No suitable HttpMessageConverter found when trying to execute restclient request - java

I'm trying to use Spring for Android rest client to send data with an http post , to avoid creating and parsing the json data.
From their manual they have the following method:
restTemplate.postForObject(url, m, String.class)
After the method is called I get the following exception:
No suitable HttpMessageConverter found when trying to execute restclient request
My activity code snippet is :
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
Message m = new Message();
m.setLibrary("1");
m.setPassword("1395");
m.setUserName("1395");
String result = restTemplate.postForObject(url, m, String.class);
And the Message object is :
public class Message {
private String UserName, Password, Library;
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getLibrary() {
return Library;
}
public void setLibrary(String library) {
Library = library;
}
}
Why can't it convert the Message object to JSON ?

There could be a few different reasons why this can happen. In my case, i had the RestTemplate already wired in, but still got this error. Turns out, i had to add a dependency on "jackson-databind":
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>

It looks like you have not added a Message-specific HttpMessageConverter. HttpMessageConverter is an interface. You need to create a class that implements HttpMessageConverter<Message> and add an instance of that class to the RestTemplate via restTemplate.getMessageConverters().add(new MyMessageConverter());

Your code looks fine in general. Maybe this is a version problem. Check whether you use Jackson 2, and if so, change the converter to MappingJackson2HttpMessageConverter.
No need for something like HttpMessageConverter<Message>.
On a side node:
Java convention is to use lower casing for variable names. So, it would be more readable for other Java developers to do:
private String library;
public void setLibrary(String library) {
this.library = library;
}

Related

Spring Boot REST: #DeleteMapping that consuming form_urlencoded not work as expect

I'm using Spring boot 1.4.0, Consider below code in a #RestController, what I expect is, the server side will receive a http body with form_urlencoded content type, but unfortunately it demands me a query parameter type with email and token. What's the problem here and how to fix?
#DeleteMapping(consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
#ResponseStatus(HttpStatus.NO_CONTENT)
public void removeAdmin(#RequestParam(value = "email") String email, #RequestParam(value = "token") String token) {
//...
}
#DeleteMapping is only a convenience extension the provides #RequestMapping(method=DELETE) It will not handle request paramters. You will still have to map those in the controllers method signature if you need the data to perform the work.
Since you want a body, You could create an object and mark it as #RequestBody:
public class DeleteBody {
public String email;
public String token;
}
public void removeAdmin(#RequestBody DeleteBody deleteBody) {
...
}

Custom annotation injection with Jersey 1.x

I am using jersey 1.9.1. I have rest method like following where
Authorization header contained encoded credentials such as username
and password and it is parsed in a method and mapped local values.
#PUT
#Path(SystemConstants.REST_MESSAGE_SENDSMS)
#Consumes(MediaType.APPLICATION_JSON)
#Produces({MediaType.APPLICATION_JSON})
public Response sendSms(#HeaderParam("Authorization") String authorization, String param) {
String[] credentials = ImosUtils.getUserCredentials(authorization);
String username = credentials[0];
String password = credentials[1];
}
I am trying to design a way to make this process automatically, without writing same parsing code in each method. I mean I would like to know if writing a special annotation such as HeaderParamExtended to this is used to parse this credentials.
I am using jersey 1.9.1 version as rest api. Where I have to edit a class in that life cycle?
#PUT
#Path(SystemConstants.REST_MESSAGE_SENDSMS)
#Consumes(MediaType.APPLICATION_JSON)
#Produces({MediaType.APPLICATION_JSON})
public Response sendSms(#HeaderParamExtended("Authorization","username") String username, #HeaderParamExtended("Authorization","password") String password, , String param) {
}
Normally you need an InjectableProvider to support the custom injection, and also an Injectable to provide the value.
Here's an example
#BasicAuth
#Target(ElementType.PARAMETER)
#Retention(RetentionPolicy.RUNTIME)
public #interface BasicAuth {
}
InjectableProvider
#Provider
public class BasicAuthInjectionProvider
implements InjectableProvider<BasicAuth, Parameter> {
#Override
public ComponentScope getScope() {
return ComponentScope.PerRequest;
}
#Override
public Injectable getInjectable(ComponentContext cc, BasicAuth a, Parameter c) {
return new BasicAuthInjectable();
}
}
Injectable
public class BasicAuthInjectable extends AbstractHttpContextInjectable<User>{
#Override
public User getValue(HttpContext hc) {
String authHeaderValue = hc.getRequest()
.getHeaderValue(HttpHeaders.AUTHORIZATION);
String[] credentials = ImosUtils.getUserCredentials(authHeaderValue);
return new User(credentials[0], credentials[1]);
}
}
One thing you'll notice is that I have a User class. This is to wrap the username and password, and just have one injection point. i.e.
public Response getSomething(#BasicAuth User user) {
}
I actually tried to do it your way, with
public Response getSomething(#BasicAuth("username") String username,
#BasicAuth("password") String password) {
And in the InjectableProvider get the annotation value from the annotation passed to the getInjectable, then pass that value onto the BasicAuthInjectable. From there check to see if the value is "username" or "password" and return the corresponding value. But for some reason the injection providers were not even called. You can play around with it to see if you can get it to work. But to me the User looks cleaner anyway, and with the two strings, the injection providers are called twice and you need to parse the headers twice. Seems unnecessary.

GWT - Serializing POST parameter in JSON before sending

I am trying to invoke a REST server from my GWT client. The server is not under my control and I am using GWT just for the client. The service expects to receive a JSON which is going to be deserialized with Jackson and mapped to a Java bean like this:
public DTO {
String username;
String password;
/*...*/
}
Therefore, on my GWT project I created this class:
import com.google.gwt.json.client.JSONObject;
import com.lh.clte.client.gui.util.CLTELabelProperties;
public class DTO extends JSONObject {
String username;
String password;
/*...*/
}
And I am trying to send a POST request this way:
DTO dto= new DTO();
dto.setUsername(username);
dto.setPassword(password);
RequestBuilder b = new RequestBuilder(RequestBuilder.POST, url);
b.setHeader("content-type", "application/x-www-form-urlencoded");
/***** ERROR *************/
String data = dto.toString(); // JSONObject.toString(), no ovveriding
/*************************/
b.setRequestData(data);
b.setCallback(new MyCallback<DTO>());
try {
b.send();
} catch (RequestException e) {
e.printStackTrace();
}
However, the toString method doesn't produce the expected JSON, but rather the string "{}". Where am I doing it wrong?
I also tried com.google.gwt.json.client.dev.JsonObject, but it doesn't change the outcome.
You have to stringify your JSO object before sending over the wire:
String data = JsonUtils.stringify(dto);
This function is available in 2.7.0-SNAPSHOT, for 2.6.1 you have to create your own JSNI method
String data = stringify(dto);
private native String stringfy(JavaScriptObject jso) /*-{
return JSON.stringify(obj);
}-*/;
JSONObject is a "map", it's not meant to be extended.
You could have your accessors store the value in an internal JSONObject rather than in fields, or you could use a JavaScriptObject with accessors written in JSNI and using JsonUtils for parsing and JSONObject for serialization (new JSONObject(myJso).toString(), pending GWT 2.7's JsonUtils.stringify), or you could use AutoBeans.
See also https://stackoverflow.com/a/10685489/116472 or How to genearte JSON on the client, among many others.
If your backend uses Jackson, you should give gwt-jackson a try.
You'll be able to use any DTO and even the server beans if you have access to the sources.
You declare your mapper like that :
public static interface DTOWriter extends ObjectWriter<DTO> {}
And then :
DTOWriter dtoWriter = GWT.create(DTOWriter.class);
String data = dtoWriter.write(dto);
BTW, shouldn't your Content-type header be application/json ?
An alternative approach will be to use RestyGWT (http://restygwt.fusesource.org/).
RestyGWT will take care of both serializing to/from JSON and also doing the POST request.
In your example, you will need a Class that defines which fields are serializable:
public class DTO {
#Json(name = "username") // 'username' will be the name of the parameter in the json object
private String username;
#Json(name = "password")
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Then, you define the service by extending RestService
public interface DTORestService extends RestService {
/**
* Utility/Convenience class.
* Use DTORestService.App.getInstance() to access static instance of DTORestService
*/
public static class App {
private static DTORestService ourInstance = null;
public static DTORestService getInstance() {
if (ourInstance == null) {
Defaults.setServiceRoot(host); // the host from the 'url' you want the POST to be sent
ourInstance = (DTORestService) GWT.create(DTORestService.class);
}
return ourInstance;
}
}
#POST
#Path("/dto.json") // the path from the 'url' you want the POST to be sent
public void getDTO(DTO dto, // the json object you want to add to the post
MethodCallback<DTO> callback); // the method callback with any json result you will receive
}
Finally, you can call it by doing:
DTO dto = new DTO();
dto.setUsername(username);
dto.setPassword(password);
DTORestService.getInstance().getDTO(dto, new AMethodCallback<DTO>());
hope it helps

How to parse JSON Response to POJO with AndroidAnnotations?

I'm using AndroidAnnotations to build a Rest for an Android Application.
On the Serverside im using PHP, which send a json looking like :
{"tag":"register","success":0,"error":2,"msg":"User already existed","body":[]}
I have two POJOS :
User.java:
public class User implements Serializable {
private String name;
private String email;
private String password;
//getter and setter Methods
}
Response.java:
public class RegistrationResponse implements Serializable {
private String tag;
private int success;
private int error;
private String msg;
private String body;
//getter and setter Methods
}
Rest Client:
#Rest(rootUrl = "http://my.domain.com", converters = {
MappingJacksonHttpMessageConverter.class,
StringHttpMessageConverter.class, GsonHttpMessageConverter.class }, interceptors = { MyInterceptor.class })
public interface RestClient extends RestClientErrorHandling {
#Post("/user/register/{name}/{email}/{pass}")
#Accept(MediaType.APPLICATION_JSON_VALUE)
Response sendUserRegistration(User user, String name, String email,
String pass);
RestTemplate getRestTemplate();
}
Activity.java:
//User and Response are POJOs
Response result = RestClient.sendUserRegistration(user,
user.getName(),user.getEmail(),user.getPassword());
But i got an Null Pointer Exception error on Activity.java. But if i change the return value of "sendUserRegistration" function to String all work. So my "Response" POJO seems not to be converted from AndroidAnnotations.
How can i convert the Rest Response to my "Response"-POJO using AndroidAnnotations?
You don't need to return the entire response object per rest call, just set the response to your custom object. Or you can also return a JsonObject also and use gson to convert it later on.
#Rest(rootUrl = "http://my.domain.com", converters = {
MappingJacksonHttpMessageConverter.class,
StringHttpMessageConverter.class, GsonHttpMessageConverter.class }, interceptors = { MyInterceptor.class })
public interface RestClient extends RestClientErrorHandling {
#Post("/user/register/{name}/{email}/{pass}")
#Accept(MediaType.APPLICATION_JSON_VALUE)
User sendUserRegistration(User user, String name, String email,
String pass);
RestTemplate getRestTemplate();
}
then just simply call
User newUser = RestClient.sendUserRegistration(user,
user.getName(),user.getEmail(),user.getPassword());
AA relies on Spring Android RestTemplate to make the rest call. And in order to build requests and handle responses this lib uses converters. And to know which converter the RestTemplate should use, it checks the content-type response header.
As MappingJacksonHttpMessageConverter and GsonHttpMessageConverter handles only http response with content-type=application/json and your result is converted to string, I'm pretty sure you forgot to set this header in your php server. So it send the default one (ie: text/plain) which is only handle by StringHttpMessageConverter.
Also, the body field is an object in your json example, but in your POJO you declared it as a String. So parsing will fail on this point.

Using Gson with Interface Types

I am working on some server code, where the client sends requests in form of JSON. My problem is, there are a number of possible requests, all varying in small implementation details.
I therefore thought to use a Request interface, defined as:
public interface Request {
Response process ( );
}
From there, I implemented the interface in a class named LoginRequest as shown:
public class LoginRequest implements Request {
private String type = "LOGIN";
private String username;
private String password;
public LoginRequest(String username, String password) {
this.username = username;
this.password = password;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
/**
* This method is what actually runs the login process, returning an
* appropriate response depending on the outcome of the process.
*/
#Override
public Response process() {
// TODO: Authenticate the user - Does username/password combo exist
// TODO: If the user details are ok, create the Player and add to list of available players
// TODO: Return a response indicating success or failure of the authentication
return null;
}
#Override
public String toString() {
return "LoginRequest [type=" + type + ", username=" + username
+ ", password=" + password + "]";
}
}
To work with JSON, I created a GsonBuilder instance and registered an InstanceCreator as shown:
public class LoginRequestCreator implements InstanceCreator<LoginRequest> {
#Override
public LoginRequest createInstance(Type arg0) {
return new LoginRequest("username", "password");
}
}
which I then used as shown in the snippet below:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(LoginRequest.class, new LoginRequestCreator());
Gson parser = builder.create();
Request request = parser.fromJson(completeInput, LoginRequest.class);
System.out.println(request);
and I get the expected output.
The thing I wish to do is replace the line Request request = parser.fromJson(completeInput, LoginRequest.class); with something similar to Request request = parser.fromJson(completeInput, Request.class); but doing that will not work, since Request is an interface.
I want my Gson to return the appropriate type of request depending on the received JSON.
An example of the JSON I passed to the server is shown below:
{
"type":"LOGIN",
"username":"someuser",
"password":"somepass"
}
To reiterate, I am looking for a way to parse requests (In JSON) from clients and return objects of classes implementing the Request interface
Polymorphic mapping of the type described is not available in Gson without some level of custom coding. There is an extension type adapter available as an extra that provides a bulk of the functionality you are looking for, with the caveat that the polymorphic sub-types need to be declared to the adapter ahead of time. Here is an example of its use:
public interface Response {}
public interface Request {
public Response process();
}
public class LoginRequest implements Request {
private String userName;
private String password;
// Constructors, getters/setters, overrides
}
public class PingRequest implements Request {
private String host;
private Integer attempts;
// Constructors, getters/setters, overrides
}
public class RequestTest {
#Test
public void testPolymorphicSerializeDeserializeWithGSON() throws Exception {
final TypeToken<List<Request>> requestListTypeToken = new TypeToken<List<Request>>() {
};
final RuntimeTypeAdapterFactory<Request> typeFactory = RuntimeTypeAdapterFactory
.of(Request.class, "type")
.registerSubtype(LoginRequest.class)
.registerSubtype(PingRequest.class);
final Gson gson = new GsonBuilder().registerTypeAdapterFactory(
typeFactory).create();
final List<Request> requestList = Arrays.asList(new LoginRequest(
"bob.villa", "passw0rd"), new LoginRequest("nantucket.jones",
"crabdip"), new PingRequest("example.com", 5));
final String serialized = gson.toJson(requestList,
requestListTypeToken.getType());
System.out.println("Original List: " + requestList);
System.out.println("Serialized JSON: " + serialized);
final List<Request> deserializedRequestList = gson.fromJson(serialized,
requestListTypeToken.getType());
System.out.println("Deserialized list: " + deserializedRequestList);
}
}
Note that you don't actually need to define the type property on the individual Java objects - it exists only in the JSON.
Assuming that the different possible JSON requests you may have are not extremely different to each other, I suggest a different approach, simpler in my opinion.
Let's say that you have these 3 different JSON requests:
{
"type":"LOGIN",
"username":"someuser",
"password":"somepass"
}
////////////////////////////////
{
"type":"SOMEREQUEST",
"param1":"someValue",
"param2":"someValue"
}
////////////////////////////////
{
"type":"OTHERREQUEST",
"param3":"someValue"
}
Gson allows you to have a single class to wrap all the possible responses, like this:
public class Request {
#SerializedName("type")
private String type;
#SerializedName("username")
private String username;
#SerializedName("password")
private String password;
#SerializedName("param1")
private String param1;
#SerializedName("param2")
private String param2;
#SerializedName("param3")
private String param3;
//getters & setters
}
By using the annotation #SerializedName, when Gson try to parse the JSON request, it just look, for each named attribute in the class, if there's a field in the JSON request with the same name. If there's no such field, the attribute in the class is just set to null.
This way you can parse many different JSON responses using only your Request class, like this:
Gson gson = new Gson();
Request request = gson.fromJson(jsonString, Request.class);
Once you have your JSON request parsed into your class, you can transfer the data from the wrap class to a concrete XxxxRequest object, something like:
switch (request.getType()) {
case "LOGIN":
LoginRequest req = new LoginRequest(request.getUsername(), request.getPassword());
break;
case "SOMEREQUEST":
SomeRequest req = new SomeRequest(request.getParam1(), request.getParam2());
break;
case "OTHERREQUEST":
OtherRequest req = new OtherRequest(request.getParam3());
break;
}
Note that this approach gets a bit more tedious if you have many different JSON requests and those requests are very different to each other, but even so I think is a good and very simple approach...
Genson library provides support for polymorphic types by default. Here is how it would work:
// tell genson to enable polymorphic types support
Genson genson = new Genson.Builder().setWithClassMetadata(true).create();
// json value will be {"#class":"mypackage.LoginRequest", ... other properties ...}
String json = genson.serialize(someRequest);
// the value of #class property will be used to detect that the concrete type is LoginRequest
Request request = genson.deserialize(json, Request.class);
You can also use aliases for your types.
// a better way to achieve the same thing would be to use an alias
// no need to use setWithClassMetadata(true) as when you add an alias Genson
// will automatically enable the class metadata mechanism
genson = new Genson.Builder().addAlias("loginRequest", LoginRequest.class).create();
// output is {"#class":"loginRequest", ... other properties ...}
genson.serialize(someRequest);
By default, GSON cannot differentiate classes serialized as JSON; in other words, you will need to explicitly tell the parser what class you are expecting.
A solution could be custom deserializing or using a type adapter, as described here.
I found this answer: https://stackoverflow.com/a/28830173 which solved my issue when using Calendar as the interface as the RunTimeType would be GregorianCalendar.
Have a utility method to create GSON for an interface of generic type.
// Utility method to register interface and its implementation to work with GSON
public static <T> Gson buildInterface(Class<T> interfaceType, List<Class<? extends T>> interfaceImplmentations) {
final RuntimeTypeAdapterFactory<T> typeFactory = RuntimeTypeAdapterFactory.of(interfaceType, "type");
for (Class<? extends T> implementation : interfaceImplmentations) {
typeFactory.registerSubtype(implementation);
}
final Gson gson = new GsonBuilder().registerTypeAdapterFactory(typeFactory).create();
return gson;
}
// Build Gson
List<Class<? extends Request>> customConfigs = new ArrayList<>();
customConfigs.add(LoginRequest.getClass());
customConfigs.add(SomeOtherRequest.getClass());
Gson gson = buildInterface(Request.class, customConfigs);
Use this gson to serialize or deserialize and this works.

Categories