3

I'm trying to implement java based web-service server which returns to Json and java script based web-service client. Here is my java part :

@Path("/myapp")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class MyRecommender {
            @POST
            @Path("/recs")
            public Response getRecommendations() {
                //Assume recommendation List contains some Recommendation objects 
                //I removed it for simplicity.            
                List<Recommendation> recommendation;
                JsonArrayBuilder builder = Json.createArrayBuilder();
                for (Recommendation rec : recommendations) {
                    builder.add(Json.createObjectBuilder().add("firstPersonName", "\"" + rec.getFirstPerson().getName() + "\"")
                            .add("firsPersonURL", "\"" + rec.getFirstPerson().getURL() + "\"")
                            .add("secondPersonName", "\"" + rec.getSecondPerson().getName() + "\"")
                            .add("secondPersonURL", "\"" + rec.getSecondPerson().getURL() + "\"")
                            .add("score", "\"" + rec.getSimilarity() + "\""));
                }
                JsonArray jsonData = builder.build();
                return Response.ok(jsonData, MediaType.APPLICATION_JSON).header("Access-Control-Allow-Origin", "*")
                        .header("Access-Control-Allow-Methods", "POST").allow("OPTIONS").build();
            }
        }
}

Now, when I call this function from my js client, I got :

POST http://localhost:8080/myapp/recs 500 (Request failed.)

But when I replace the for loop and return with the following code snipped I got response in my js correctly.

Changed part :

// remove for loop and change jsonData type.
  String jsonData = "{\"name\":\"John\"}";
  return Response.ok(jsonData, MediaType.APPLICATION_JSON).header("Access-Control-Allow-Origin", "*")
          .header("Access-Control-Allow-Methods", "POST").allow("OPTIONS").build();

So, I wonder what might be problem ? Since its my first time with web-services, I have some difficulty to debug my code.

EDIT

By the way, I get also another error when I try to first version of getRecommendations() functions(with loop)

     XMLHttpRequest cannot load http://localhost:8080/myapp/recs. 
     No 'Access-Control-Allow-Origin' header is present on the requested resource.   
    Origin 'http://localhost:3000' is therefore not allowed access. 
The response had HTTP status code 500.

But as I said, When I remove the loop and put second code snipped into getRecommendations() functions, both of the errors are gone and I get the response in my website.

EDIT2

When I changed the loop and return statement of getRecommendations() function with the below I again get the same errors

 JsonObject value = Json.createObjectBuilder()
                .add("name", "John").build();
return Response.ok(value, MediaType.APPLICATION_JSON).header("Access-Control-Allow-Origin", "*")
              .header("Access-Control-Allow-Methods", "POST").allow("OPTIONS").build();

EDIT 3

As far as I understood, createObjectBuilder().build() or JsonArrayBuilder.build() return an JSON object and below of this build statement in my getRecommendations() function is not even run. So, I think my problem how could I give Access-Control-Allow-Origin permission to this object?

15
  • HTTP 500 is an internal server error. did you check if the server is connected and working properly? Commented Aug 15, 2015 at 17:54
  • @SudiptoChandra yea, as I said, if I replaced the loop and return statement of my getRecommendations() function with the second code snipped, It works properly. Therefore I dont think there could be any connection problem. Commented Aug 15, 2015 at 17:56
  • 1
    IMHO getRecommendations() should be annotated with @GET Commented Aug 15, 2015 at 18:14
  • @PeterMmm may I ask why do you think in that way ? Commented Aug 15, 2015 at 18:16
  • Prefixing & suffixing with " doesn't look right to me. Commented Aug 15, 2015 at 18:17

2 Answers 2

2

If it is ok to use a third Party Library, using Google's Gson could be an efficient solution in this case. When converting Models to JSON it is quite handy. What you can do is something like this.

ArrayList<Recommendation> recommendationList = new ArrayList<Recommendation>();
Gson gson = new Gson(); String jsonData = gson.toJson(reccomendationList);

To use it as a dependency in your POM file you could do this.

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.3.1</version>
  <scope>compile</scope>
</dependency>
Sign up to request clarification or add additional context in comments.

Comments

1

You should try simplest approach:

return Response.ok().entity(recommendation).header("Access-Control-Allow-Origin", "*")
                    .header("Access-Control-Allow-Methods", "POST").allow("OPTIONS").build();

3 Comments

When I try your solution I get the same errors too.
Are you sure that recommendation!=null ? In any case you can wrap method body inside try{}catch() and print stacktrace.
I'm sure because I also print out content of recommendation into console. (I removed it in the question for the sake of simplicity)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.