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
Related
I want to be able to fetch a param from the redirect url whenever it is automated. I am having difficulties doing this as I am getting a bad request after I created another endpoint to effect this.
I have an endpoint that works fine. The endpoint is a get method. Loading the endpoint takes a user to a page where they need to provide some necessary details. Once these details have been verified, the user is redirected to my redirecr_uri. The redirect_uri now contains important information like session_id, code, etc. The most important thing I need is the code. I need to pass the code into yet another endpoint which will return an access token.
I have manually done this process and it works but I want it to be done automatically because I can't keep doing that when I push the code to staging or production.
Here is the endpoint that redirects as well as the method.
#GetMapping("/get-token")
public RedirectView getBvn() throws UnirestException {
return nibss.getAccessToken();
}
This is the method that the controller calls
public RedirectView getAccessToken() throws UnirestException {
String url = "https://idsandbox.nibss-plc.com.ng/oxauth/authorize.htm?scope=profile&acr_values=otp&response" +
"_type=code&redirect_uri=https://www.accionmfb.com/&client_id=0915cd00-67f2-4768-99ac-1b2ff9f1da2e";
RedirectView redirectView = new RedirectView();
redirectView.setUrl(url);
return redirectView;
}
When the user provides the right information they are redirected to something like this
https://www.accionmfb.com/?code=9ad91f13-4698-4030-8a8f-a857e6a9907e&acr_values=otp&scope=profile&session_state=fa525cabc5b62854c73315d0322fd830c12a5941b89fd8e6e518da369e386572.b78a3d21-e98e-4e9a-8d60-afca779d9fad&sid=fd60ab92-ef37-4a5b-99b9-f8f52321985d
It is important to state that this 3rd party API I am trying to consume uses oath2.0 client authentication.
I created this endpoint to get the code from the redirected_uri
#GetMapping("/redirect-url")
public void handleRedirect(#RequestParam("code") String code) throws UnirestException {
if(Objects.nonNull(code) || !code.isEmpty()){
nibss.getToken(code);
log.info("Code is not being passed {}", code);
} else {
log.info("Code is not being passed {}", code);
}
}
public String getToken(String code) throws UnirestException {
log.info("This is the code here oooooooooo {}", code);
String url = "https://idsandbox.nibss-plc.com.ng/oxauth/restv1/token";
String parameters = "client_id=0915cd00-67f2-4768-99ac-1b2ff9f1da2e&code="+code+"&redirect_uri=https://www.accionmfb.com/&grant_type=authorization_code";
HttpResponse<String> apiResponse = Unirest.post(url)
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Authorization", "Basic MDkxNWNkMDAtNjdmMi00NzY4LTk5YWMtMWIyZmY5ZjFkYTJlOlRVRnEwcGFBQXRzbzBZOEcxMkl2WFZHUmx6WG5zaERiaGt1dzI1YUM=")
.body(parameters)
.asString();
//JSONObject apiJson = apiResponse.getBody().getObject();
//return apiJson.getString("access_token");
JSONObject json = new JSONObject(apiResponse.getBody());
String accessToken = json.getString("access_token");
log.info(accessToken);
return accessToken;
}
But this is not working, I get 400 whenever I hit the second endpoint. What am I doing wrong?
The redirect_uri that you are passing to the OAuth server is https://www.accionmfb.com which does not include the path /redirect-url so the redirect never hits your method.
Either register and pass a callback uri like redirect_uri=https://www.accionmfb.com/redirect-url
Or change #GetMapping("/redirect-url") to #GetMapping("/")
I have been trying to use restful webservice in place of legacy soap webservice without altering the user part of the request. I wanted to know whether this is achievable. Here is a sample code to demonstrate the issue :
Soap request :
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:sch="https://www.flopradalley.com/xml/school">
<soapenv:Header/>
<soapenv:Body>
<sch:StudentDetailsRequest>
<sch:name>Arun</sch:name>
</sch:StudentDetailsRequest>
</soapenv:Body>
</soapenv:Envelope>
And this is my rest controller which should be able to respond to the request from SoapUI :
#RestController
#RequestMapping(value = "/restservice")
public class KenRestController {
#RequestMapping(value = "/details", method = RequestMethod.POST,
produces = MediaType.TEXT_XML_VALUE, consumes = MediaType.TEXT_XML_VALUE
)
public StudentDetailsResponse execute(HttpServletRequest request)
{
StudentDetailsRequest objectFromBody = null;// unmarshall the object from soap request and store it here
StringBuffer sb = new StringBuffer();
try {
BufferedReader reader = request.getReader();
String lineStr = null;
while ((lineStr = reader.readLine()) != null) {
sb.append(lineStr);
}catch(IOException ex) {
ex.printStackTrace();
}
/* other code */
return ---;
}
}
I was only able to get the soap request as text and store it in a string buffer. I know this isn't remotely the way it should be done if it is possible to handle soap requests using rest. I know that rest is an archicture and is a whole lot difference from soap and it looks like there is no direct way to handle soap requests using rest at the least.
Apart from this sample code, I should be able to extract the SoapMessage, MessageContext, Soapheader, SoapBody from the request. That brings me to the original question on whether it is possible?
If you make the change into a REST API I highly recommend to not keep thinging in some of the webservice logic.
The SOAP protocol is a method to pass information that contains both the answer and the metadata of the call.
In rest you obtain the answer in the body of the responses and the most used format is json. You can directly pass as a parameter in the method the object that is going to be parsed into the java object by Spring REST (it uses Jackson library to parse in reality).
#RestController
public class KenRestController {
#GetMapping("/restService/details/{studentId}") // post is for saving an elelement
public StudentDetailsResponse getDetails(#PathVariable("studentId") Integer studentId) {
// you get the details and parse it to the object you want to return
return studentService.getStudentById(studentId);
}
// example of response class
private class StudentDetailsResponse implements Serializable{
// pojo class
}
}
Please don't hesitate to make any questions about that.
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 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 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.