I need to retrieve URL from current Web page opened in Firefox by using Wicket. Can somebody tell me how to do that?
To get the current page's url use the webrequest and UrlRenderer:
Url url = ((WebRequest)RequestCycle.get().getRequest()).getUrl();
String fullUrl = RequestCycle.get().getUrlRenderer().renderFullUrl(url);
You need to query the underlying HTTPServletRequest:
public class DummyPage extends WebPage{
private String getRequestUrl(){
// this is a wicket-specific request interface
final Request request = getRequest();
if(request instanceof WebRequest){
final WebRequest wr = (WebRequest) request;
// but this is the real thing
final HttpServletRequest hsr = wr.getHttpServletRequest();
String reqUrl = hsr.getRequestURL().toString();
final String queryString = hsr.getQueryString();
if(queryString != null){
reqUrl += "?" + queryString;
}
return reqUrl;
}
return null;
}
}
Reference:
(Wicket) Component.getRequest()
(Wicket) Request
(Wicket) WebRequest
(Servlet API) HTTPServletRequest
The solution from Sean Patrick Floyd seems to be obsolete for wicket 1.5
If using wicket 1.5 (or above I guess) here is the solution:
RequestCycle.get().getUrlRenderer().renderFullUrl(
Url.parse(urlFor(MyPage.class,null).toString()));
Reference:
Getting a url for display
Depending on what exactly you want, this may not be possible. There is a short guide here in the Wicket wiki, but it has some caveats, notably that it only returns a relative URL in versions of Wicket after 1.3. That said, the method used is
String url = urlFor("pageMapName", MyPage.class, new PageParameters("foo=bar"));
If you go with the wiki's alternate method — the one involving the form — be warned: getPage() is not part of Wicket's public API.
This works. I'm using wicket 1.5;
new URL(RequestCycle.get().getUrlRenderer().renderFullUrl(
Url.parse(urlFor(HomePage.class,null).toString()))).getAuthority();
Example: http://example.com:80/a_long_path/
getAuthproty() will return example.com:80
getHost() will return example.com.
Related
I am trying to access the contents of an API and I need to send a URL using RestTemplate.
String url1 = "http://api.example.com/Search?key=52ddafbe3ee659bad97fcce7c53592916a6bfd73&term=&limit=100&sort={\"price\":\"desc\"}";
OutputPage page = restTemplate.getForObject(url1, OutputPage .class);
But, I am getting the following error.
Exception in thread "main" java.lang.IllegalArgumentException: Not enough variable values available to expand '"price"'
at org.springframework.web.util.UriComponents$VarArgsTemplateVariables.getValue(UriComponents.java:284)
at org.springframework.web.util.UriComponents.expandUriComponent(UriComponents.java:220)
at org.springframework.web.util.HierarchicalUriComponents.expandInternal(HierarchicalUriComponents.java:317)
at org.springframework.web.util.HierarchicalUriComponents.expandInternal(HierarchicalUriComponents.java:46)
at org.springframework.web.util.UriComponents.expand(UriComponents.java:162)
at org.springframework.web.util.UriTemplate.expand(UriTemplate.java:119)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:501)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:239)
at hello.Application.main(Application.java:26)
If I remove the sort criteria, it is working properly.
I need to parse the JSON using sort criteria.
Any help will be much appreciated.
Thanks
The root cause is that RestTemplate considers curly braces {...} in the given URL as a placeholder for URI variables and tries to replace them based on their name. For example
{pageSize}
would try to get a URI variable called pageSize. These URI variables are specified with some of the other overloaded getForObject methods. You haven't provided any, but your URL expects one, so the method throws an exception.
One solution is to make a String object containing the value
String sort = "{\"price\":\"desc\"}";
and provide a real URI variable in your URL
String url1 = "http://api.example.com/Search?key=52ddafbe3ee659bad97fcce7c53592916a6bfd73&term=&limit=100&sort={sort}";
You would call your getForObject() like so
OutputPage page = restTemplate.getForObject(url1, OutputPage.class, sort);
I strongly suggest you do not send any JSON in a request parameter of a GET request but rather send it in the body of a POST request.
If the solution suggested by sotirios-delimanolis is a little difficult to implement in a scenario, and if the URI string containing curly braces and other characters is guaranteed to be correct, it might be simpler to pass the encoded URI string to a method of RestTemplate that hits the ReST server.
The URI string can be built using UriComponentsBuilder.build(), encoded using UriComponents.encode(), and sent using RestTemplate.exchange() like this:
public ResponseEntity<Object> requestRestServer()
{
HttpEntity<?> entity = new HttpEntity<>(requestHeaders);
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(rawValidUrl)
.queryParams(
(LinkedMultiValueMap<String, String>) allRequestParams);
UriComponents uriComponents = builder.build().encode();
ResponseEntity<Object> responseEntity = restTemplate.exchange(uriComponents.toUri(), HttpMethod.GET,
entity, String.class);
return responseEntity;
}
Building, encoding, and extracting URI have been seperated out for clarity in the above code snippet.
You can URL encode the parameter values:
String url1 = "http://api.example.com/Search?key=52ddafbe3ee659bad97fcce7c53592916a6bfd73&term=&limit=100&sort=";
org.apache.commons.codec.net.URLCodec codec = new org.apache.commons.codec.net.URLCodec();
url1 = url1 + codec.encode("{\"price\":\"desc\"}");
OutputPage page = restTemplate.getForObject(url1, OutputPage.class);
You can set a specific UriTemplateHandler in your restTemplate. This handler would just ignore uriVariables :
UriTemplateHandler skipVariablePlaceHolderUriTemplateHandler = new UriTemplateHandler() {
#Override
public URI expand(String uriTemplate, Object... uriVariables) {
return retrieveURI(uriTemplate);
}
#Override
public URI expand(String uriTemplate, Map<String, ?> uriVariables) {
return retrieveURI(uriTemplate);
}
private URI retrieveURI(String uriTemplate) {
return UriComponentsBuilder.fromUriString(uriTemplate).build().toUri();
}
};
restTemplate.setUriTemplateHandler(skipVariablePlaceHolderUriTemplateHandler);
You can encode url before using RestTemplate
URLEncoder.encode(data, StandardCharsets.UTF_8.toString());
You can simply append a variable key to the URL and give the value using the restTemplate.getForObject() method.
Example:
String url = "http://example.com/api?key=12345&sort={data}";
String data="{\"price\":\"desc\"}";
OutputPage page = restTemplate.getForObject(url, OutputPage.class, data);
I have the below piece spring REST controller class.
#RestController
#RequestMapping("/global")
public class ProxyController extends BaseController{
#RequestMapping(value = "/**")
public ResponseEntity<String> proxy(HttpServletRequest request, HttpServletResponse response ) throws Exception {
try {
String restOfTheUrl = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
URL uri = new URL("https://myrealserver" +
restOfTheUrl);
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> httpEntity = new HttpEntity<>(headers);
RestTemplate restTemplate = new RestTemplate();
return resp;
} catch (Exception e) {
logger.error("Error ", e);
return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
What I am trying to achieve here is to hide a server behind a proxy, which blindly forwards requests to the server.
This piece of code is invoked with url
https://myproxyserver/myapp1/end/point1
which in turn returns an html page with few clickable links. Now when the user clicks I am expecting the link to be invoked as
https://myproxyserver/myapp1/end/point2
Where as actually the endpoint invoked is
https://myproxyserver/end/point2
In the html page returned by the actual server, the path is end/point2 and has no mention of myapp1. So on click on those links my context changes to https://myproxyserver/end/point2 instead of https://myproxyserver/myapp1/end/point2
How do I ensure that the root context is always https://myproxyserver/myapp1 and not https://myproxyserver ?
You want to get your server context path. this is sample code.
like this :
public static String getServerNameAndContextPath(HttpServletRequest req) {
return "https://" + req.getServerName() + req.getContextPath();
}
Finally I resolved the problem by taking what D D suggested. I scanned through the whole response body, fortunately I had a pattern that I could use to scan and appended the context of the url to where ever required. That resolved the problem for me this problem.
I'm calling a jsp page through an jax-rs endpoint as below.
public String logout(#Context HttpServletRequest request,#DefaultValue("Empty Details") #QueryParam("logoutNotification") String logoutNotification,
#QueryParam("id_token_hint") String id_token_hint) {
Response response= Response.status(200).entity(logoutNotification).build();
if(response.getEntity().toString().equals("True")){
return "<html><head><script>\n" +
"window.open(\"https://localhost:9443/carbon/authenticationendpoint/test.jsp\");</script></head><body></body></html>";
}
else {
return null;
}
The thing is I need to pass some parameters to the 'https://localhost:9443/carbon/authenticationendpoint/test.jsp' from this endpoint. How can I do it?
Can I pass it as a queryparam from the endpoint? Please advice me.
Thanks
I dont have much knowledge on RESTful webservices. But in an url if you want to pass paramters it can done as <url URL>?par1=val1&par2=val2 If your code opens a new window then this will work.
I hope so this would help you.
Example: https://localhost:9443/carbon/authenticationendpoint/test.jsp?name=Joe&age=24
I am new to Restful web service in java and this is my first web application, I searched a lot but everybody asking more complicated question than what I need.
I have a pretty simple html with a textbox and a submit button. Also I have a POST function in my web service as below:
#POST
#Consumes({MediaType.APPLICATION_FORM_URLENCODED,MediaType.APPLICATION_JSON})
public Response showSearchResult(String incomingData) throws Exception {
String query = incomingData;
RepositoryMongo repository = new RepositoryMongo("InvertedIndex", "InvertedIndex", "documents");
InvertedIndex invertedIndex = new InvertedIndex(repository);
ArrayList<Posting> result = invertedIndex.processQuery_Posting_Based(query, 10,"1");
String htmlResult = invertedIndex.getHTMLResult(result);
return Response.ok(htmlResult).build();
}
The problem is that my incomingData = "query_input=canada+singer&search=search", while I want it to be the content of the textbox only. I can parse the string that I am receiving, but is that way correct? Is there any way that I can get "canada singer" as input directly? how can I control input type?
You can use the #FormParam annotation for a POST request, or the #PathParam annotation for a GET request. These go on parameters to your method, to indicate that the values for the parameters should be pulled out of either the URL (for a GET) or the posted body (for a POST).
Have a look at section 7.3 of http://www.vogella.com/tutorials/REST/article.html where there is a working example.
For this result - “query_input=canada+singer" ,you can get the url value with #QueryParam("query_input").
Alternatively,
We can even implement this using this #Context UriInfo
getQueryParameters() method has getFirst - in which you include the argument to fetch,just like below
String query_input_value= url.getQueryParameters().getFirst("query_input");
Try this :
#POST
#Consumes({MediaType.APPLICATION_FORM_URLENCODED,MediaType.APPLICATION_JSON})
public Response showSearchResult(#Context UriInfo url) throws Exception {
String query_input_value= url.getQueryParameters().getFirst("query_input");
String query = incomingData;
RepositoryMongo repository = new RepositoryMongo("InvertedIndex", "InvertedIndex", "documents");
InvertedIndex invertedIndex = new InvertedIndex(repository);
ArrayList<Posting> result = invertedIndex.processQuery_Posting_Based(query, 10,"1");
String htmlResult = invertedIndex.getHTMLResult(result);
return Response.ok(htmlResult).build();
}
I have the URL: http://demo.lendingclub.com/account/summary.action.
When visit this url, it will first go to the authenticate interceptor, in the interceptor class, If I use:
String uri = req.getRequestURI();
it will return /account/summary.action
But if I use it in jsp:
<%
HttpServletRequest req = ServletActionContext.getRequest();
String uri = req.getRequestURI();
%>
it will return : /mainapp/pages/account/summary.jsp
Why they're different, and how can I get action URL in JSP?
The easiest way to get the current actions url is: <s:url/> if you supply namespace and action parameters you can make it point at other actions but without these parameters it defaults to the current url.
You could get the action URL or any other value if you set property to the action, and then retrieve that property from the value stack via OGNL.
private String actionURL;
public String getActionURL(){
return actionURL;
}
the code to calculate the action URL is similar you posted to the comments
public String getPath(){
ActionProxy proxy = ActionContext.getContext().getActionInvocation().getProxy();
String namespace = proxy.getNamespace();
String name = proxy.getActionName();
return namespace+(name == null || name.equals("/") ?"":("/"+name));
}
this code is not supported .action extension, if you need to add the extension to the path then you need to modify this code correspondingly.
then write your action method
public String excute() {
actionURL = getPath();
...
return SUCCESS;
}
in the JSP
<s:property value="%{actionURL}"/>
you have been used dispatcher result to forward request to the JSP as a result you get the URI pointed to the JSP location.