Build a REST endpoint and SOAP with one implementation in Java EE - java

So I'm trying to annotate a method with both JAX-RS and JAX-WS, I've looked at this and FWIW it really isn't a good idea however I got stuck when trying to implement this
#GET
#Path("loginWithEmail")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#WebResult(name = "response")
#WebMethod(operationName = "loginWithEmail")
public BaseResponse loginWithEmail(
#WebParam(name = "sessionId", header = true) String sessionId,
#WebParam(name = "email") String email,
#WebParam(name = "password") String password) {
System.out.println("Session Id is " + sessionId);
}
Passing the sessionId header works perfectly for the SOAP but doesn't for REST - any ideas why and how to resolve?
PS - This is purely experimental and won't be using such in production - just curious to know how to set header - Thank you :)

you have not defined any parameter for restful service you need to make #queryparan or #pathparam or #bean .. it may work

Related

How to change jax-ws to jax-rs without client sens of changes

There is an application that was configured and has developed by JAX-WS; the piece of code like this:
#WebService(targetNamespace = "http://webservice.bulk.test.net/", serviceName = "BulkService")
#BindingType(value = SOAPBinding.SOAP12HTTP_BINDING)
#XmlSeeAlso({
ObjectFactory.class
})
public class Bulk {
#WebMethod
#RequestWrapper(localName = "getProvinces", targetNamespace = "http://webservice.bulk.test.net/", className = "test.GetProvinces")
#ResponseWrapper(localName = "getProvincesResponse", targetNamespace = "http://webservice.bulk.test.net/", className = "test.GetProvincesResponse")
#Action(input = "http://webservice.bulk.test.net/Bulk/getProvincesRequest", output = "http://webservice.bulk.test.net/Bulk/getProvincesResponse")
public void getProvinces(
#WebParam(name = "username", targetNamespace = "") #XmlElement(nillable = false, required = true)
String username,
#WebParam(name = "password", targetNamespace = "") #XmlElement(nillable = false, required = true)
String password,
...) {
}
According to this webservice, so many clients(jax-ws clients) are using.
I want to change the jax-ws to jax-rs without changing the client, another hand, the clients have no sens about the changes and do api-call as before.
Is it possible?
I solved this problem by separating soap layer from the application because of some reasons, first, used Jax-rs and Jax-ws endpoints simultaneously and secondly, is technical debt; due to separating soap from application, it is able to migrate to JDK-11 without any problems and thirdly, according to separating Soap from application, it is independent from JAX-WS clients except changing JAX-WS endpoints.

Form application encoded value is not working in spring rest

I have the below post request and of which below is the controller code
#RestController
#RequestMapping(/flow", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
#Override
#ResponseStatus(HttpStatus.OK)
#PostMapping("{abcCode}/token")
public TokenResponse createToken(#PathVariable("abcCode") String abcCode,
#RequestParam("grant_type") String grantType,
#RequestParam String code,
#RequestParam("redirect_uri") String redirectUri,
#RequestParam String clientId) {
LOG.info(
"Received call for createIdToken for abcCode: {} , clientId: {} , grantType: {} ,code: {} , redirectUri: {}",
abcCode, clientId, grantType, code, redirectUri);
}
Now the problem is that when I test the same above controller through postman by choosing the body type as application form-encoded then it is working fine but when I choose the body type as none in postman and just pass the above request parameters as query one then also it works which ideally it should not please advise how can I overcome from the same
http://localhost:19080/testService/flow/token?grant_type=authorization_code&code=3272&redirect_uri=http://www.abchui.com&clientId=ATS
it should not work for the above URL
From spring sources:
public static final String APPLICATION_FORM_URLENCODED_VALUE = "application/x-www-form-urlencoded";
According to docs, when using url-form-encoded data pass as query params.
Try to change form mime type.

CXF RESTful Client - How to do basic http authentication without Spring?

I am familiar with using Jersey to create RESTful webservice servers and clients, but due to class loading issues, I am trying to convert a Jersey client into CXF. I believe I want to use an HTTP-centric client but we don't use Spring. We need to use basic HTTP authentication. The user guide has this example:
WebClient client = WebClient.create("http:books", "username", "password", "classpath:/config/https.xml");
The first parameter isn't a URI string. Is it a format used by Spring? Can this method only be used to create WebClients using Spring?
The other way of doing authentication shown is to add a header string:
String authorizationHeader = "Basic " + org.apache.cxf.common.util.Base64Utility.encode("user:password".getBytes());
webClient.header("Authorization", authorizationHeader);
I am guessing that "user:password" should be substituted with the real values, but would appreciate confirmation.
This answer came from the CXF users mailing list.
The first example referenced above had a typo in it. It has been updated to:
WebClient client = WebClient.create("http://books", "username", "password", "classpath:/config/https.xml");
The fourth argument can be null if a Spring config file is (and therefore Spring) is not being used.
So, this worked for me:
private WebClient webClient;
public RESTfulClient(String url, String username, String password)
throws IllegalArgumentException
{
this.username = username;
this.password = password;
this.serviceURL = url;
if (username == null || password == null || serviceURL == null)
{
String msg = "username, password and serviceURL MUST be defined.";
log.error(msg);
throw new IllegalArgumentException(msg);
}
webClient = WebClient.create(this.serviceURL,
this.username,
this.password,
null); // Spring config file - we don't use this
}

Java consuming a webservice

I've been asked to rebuild our customer portal, using gwt and connecting to our data using various webservices set up on the server.
I generated all the proxy classes usign the WSDL and Jax-WS/wsimport utility, however when i make the below call:
ReportingApiSoap soap = api.getReportingApiSoap();
ArrayOfReport returnValues = soap.getReports(serverCredentials, true);
My returnValues object is null. I know the webservice itself works because I was able to test it with the same parameters I'm passing in now.
I was previously have some issues sending data to the webservice; that turning out to be the namespaces weren't lining up as they needed to. I suspect something similar is happening here, but haven't been able to figure out what yet.
Anyone ever run into something similiar before? Or if not any idea how I can check the raw xml I'm getting out of the webservice call? That way I can track the problem a step furthur.
-Ian
My Credentials object:
public class ApiCredentials {
#XmlElement(name = "Id", namespace="http://mycompany.com")
protected String id;
#XmlElement(name = "Login", namespace="http://mycompany.com")
protected String login;
#XmlElement(name = "Password", namespace="http://mycompany.com")
protected String password;
...
}
ArrayofReport:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "ArrayOfReport", propOrder = {
"report"
})
public class ArrayOfReport {
#XmlElement(name = "Report", nillable = true)
protected List<Report> report;
public List<Report> getReport() {
if (report == null) {
report = new ArrayList<Report>();
}
return this.report;
}
}
Webservice call:
#WebMethod(operationName = "GetReports", action = "http://mycompany.com/GetReports")
#WebResult(name = "GetReportsResult", targetNamespace = "http://mycompany.com")
#RequestWrapper(localName = "GetReports", targetNamespace = "http://mycompany.com", className = "com.mycompany.customerportal.server.GetReports")
#ResponseWrapper(localName = "GetReportsResponse", targetNamespace = "http://mycompany.com", className = "com.mycompany.customerportal.server.GetReportsResponse")
public ArrayOfReport getReports(
#WebParam(name = "credentials", targetNamespace = "http://mycompany.com")
ApiCredentials credentials,
#WebParam(name = "includeFields", targetNamespace = "http://mycompany.com")
boolean includeFields);
I recommend creating a mock web service (e.g. using soapUI). This will allow you to see and validate the request XML against your WSDL. You can cut'n'paste/edit mock responses to the client to see the effect.
JAX-WS implementations are a dime-a-dozen, so any further options depend on the client technology in your runtime. I would ensure that validation is enabled (this might be implemented as a feature, for example).

Spring 3.0 MVC Ajax example

I'm trying to send an Ajax request to a Spring MVC controller and map it to a Java class accordingly:
public class Person implements Serializable {
private MutableLong Id = new MutableLong();
#NotEmpty
#Size(min = 1, max = 50)
String FirstName=null;
#NotEmpty
#Size(min = 1, max = 50)
String LastName=null;
public Person(){}
public long getId(){
return this.Id.longValue();
}
//getters and setters
}
then I have JavaScript which sends the AJAX request:
function loadXMLDoc(){
if(window.ActiveXObject)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
xmlHttp=new XMLHttpRequest();
}
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.open("POST","/authenticate.dlp", true);
xmlHttp.setRequestHeader('Content-Type', 'application/json');
param = '{\"FirstName\"=\"test\",\"LastName\"=\"test2\"}';
xmlHttp.send(param);
}
and then the controller itself:
#RequestMapping(value="/authenticate.dlp",method = RequestMethod.POST)
#ResponseBody
public String getAjax(#RequestBody Person person){
Set<ConstraintViolation<Person>> failures = validator.validate(person);
if(!failures.isEmpty())
//......
}
It looks like no response from the server. If I'm using Fiddler, I see the following response from the server:
The server refused this request
because the request entity is in a
format not supported by the requested
resource for the requested method ().
What am I doing wrong?
There are two possible reasons:
You forget <mvc:annotation-driven />. It automatically configures HTTP message converters for use with #RequestBody/#ResponseBody
You don't have Jackson JSON Processor in the classpath. Spring requires it to bind application/json to #RequestBody
Just a couple of other helpful links...check out this Spring blog post:
http://blog.springsource.com/2010/07/22/spring-mvc-3-showcase/
And the examples which make use of #ResponseBody:
https://src.springframework.org/svn/spring-samples/mvc-showcase/
There's also ResponseEntity:
http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/http/ResponseEntity.html
#RequestMapping("/ajax/helloworld")
public ResponseEntity<String> helloworld() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>("Hello World", headers, HttpStatus.OK);
}
Where instead of "Hello World" you could return a marshalled object.
This is not exactly an answer to your question, but have you looked at DWR before? It makes JS to Java RPC super-easy. http://directwebremoting.org/dwr/index.html

Categories