AngularJS consumes JAX-RS rest web service - java

This is the first time that I am using a Java back-end for my web application. I have a Jax-rs webservice that I am trying to consumes with my AngularJS app
AngularJS call
$http({
url : REST_END_POINT + '/checkuser',
method : "GET",
data : {
'userId' : credentials.username,
'pwd' : credentials.password
},
dataType : "json",
headers : {
"Content-Type" : "application/json"
}
});
Webservice
#GET
#Produces("application/json")
#Consumes("application/json")
#Path("checkuser/")
public string getCheckUser(#QueryParam("userId") String userId, #QueryParam("pwd") String pwd){
try{
if(port != null){
boolean result = port.checkUser(userId, pwd);
return new java.lang.Boolean(result).toString();
}
}catch(Exception ex){
//TODO
}
return null;
}
Both userId and pwd are always null
With Firebug I can see that data contains
Object{
userId="aaa",
pwd="aa"
}
I also tried with JSON.stringify which send those data :
"{"userId":"aaa","pwd":"aa"}"

I believe that the way you are trying to access your userID and pwd is incorrect, you are using the #QueryParam which would look for the userID and pwd as query parameters of the GET request like so:
http://myservice:port/checkuser?userId=myuserid&pwd=pass
if you change your GET request to
$http({
url : REST_END_POINT + '/checkuser',
method : "GET",
params : {
'userId' : credentials.username,
'pwd' : credentials.password
},
dataType : "json",
headers : {
"Content-Type" : "application/json"
}
});
Then you should have more luck.
However I wouldn't advise this method as it could be insecure. I'd instead look at trying to utilize an existing authentication system rather than rolling your own as these existing authentication systems will be far more secure.

You can use Jackson api for converting json to/ from Java objects.
Jackson contains simple mapper methods to implicitly map your json properties to Java class member variables.
Instead of #querypram use a Java class having fields as userId and pwd

Related

How to pass large number of parameters from Angular js to rest service

I am trying to fetch parameters from angular JS $http service to rest service using **#queryParam** . I need to fetch lot of parameters(below have shown for 3 as an example ,but I need to use around 12-15 of them which I need to pass to the java side) ,so fetching all with #QueryParam makes the code look pretty bad .I am using GET.
How can I optimize this ?
Example what I am doing -
Angular Js code -
$http({
url: someUrl,
method: "GET",
params: {filter1: $scope.filter1,
filter2:$scope.filter2,
filter3:$scope.filter3
});
Java side -
#path("/getAllData")
#GET
#Produces({..}
public response getAllData(#QueryParam("filter1") final String filter1,
#QueryParam("filter2") final String filter2,
#QueryParam("filter3") final String filter3){
}
Also ,wanted to know the optimization in case when I am building URL instead of params object, and picking the same with #PathParam
$http.get('rest/test/getAllData/?filter1='$scope.filter1 +
'&filter2='$scope.filter2 + '&filter3='$scope.filter3 +
'&filter4='$scope.filter4)
I am able to do it by passing individually in #QueryParam . I am looking for optimized code when we a large number of parameters.
Create a POJO with all the required parameters.
In angular, do this
var obj = {};
obj.filter1 = $scope.filter1;
obj.filter2 = $scope.filter2;
obj.filter3 = $scope.filter3;
$http({
url: someUrl,
method: "GET",
params: obj
});
You can accept all the parameters in you rest like this -
#path("/getAllData")
#GET
#Produces({..}
public response getAllData(MyPojo obj){
//String filter1 = obj.filter1;
}
You can do it in 2 ways:
1) org.json.simple.JSONObject.
2) Bean or POJO Class.
AngularJS Controller:
var URL = appURL+'/adm/addCollProcess.do';
var json = {"col_pro_id":$scope.col_pro_id, "col_code": $scope.col_code, "exam_type_ids": $scope.exam_types.toString().replace("[","").replace("]",""),
"created_by" : "admin", "file_path" : $scope.file_path, "website" : $scope.website, "facebook" : $scope.facebook};
// using JSONObject
$http.post(URL, json).then(function(response){
if(response.data){
// Code
}
});
// using Bean Class
$http.post(URL, JSON.stringify(json)).then(function(response){
if(response.data){
// Code
}
});
Java Controller:
// using JSONObject
#RequestMapping(value="/addCollProcess.do", method=RequestMethod.POST)
public boolean addCollProcess(#RequestBody JSONObject json){
// Code
}
// using Bean Class:
#RequestMapping(value="/addCollProcess.do", method=RequestMethod.POST)
public #ResponseBody boolean addCollProcess(#RequestBody AdmissionProcessBean processBean) {
// Code
}

How can I pass a JSON object from Javascript to Java

What I am trying to do is initiate an ajax call from my frontend code by user interaction. This calls a Java Restful service that I have written. And this Java function calls another service.
I need that java service in the middle because I need to send the inputs to other service in the format of "MyModel".
The problem is, the AJAX call works but it cannot get the JSON object that I send. You see in the Java function below I create the "param1" : "asdasd" for the second time there. That's because it cannot get the JSON data from front-end. It should be dynamically created with the argument of sendInputs function.
By the way when I debug the value String input is like this: ""
Javascript AJAX call:
var paramData = {"param1" : "asdasd"};
$.ajax({
type : 'GET',
url : "/api/v2/proxy",
dataType : "json",
headers : {
"Service-End-Point" : "http://localhost:9000/service/myService/sendInputs"
},
statusCode : {
200 : function(data) {
}
},
contentType : "application/json",
data : JSON.stringify(paramData),
error : function(error) {
}
});
Java consume:
#GET
#Path("/sendInputs")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public String sendInputs(String input) {
String result = null;
//define the service endpoint to be added the default URL
String serviceEndpoint = "otherService/tool/runTool";
List<MyModel> modelParameterList = new ArrayList<MyModel>();
MyModel inputParameter = null;
inputParameter = new MyModel("param1", "asdasd");
modelParameterList.add(inputParameter);
//convert the Java Map to a json string using Jackson ObjectMapper
String jsonStringOfInputParameters = toJSON(modelParameterList);
WebClient client = WebClient
.create("http://localhost:9000");
result = client.path(serviceEndpoint)
.query("tool", "myTool")
.query("input", jsonStringOfInputParameters)
.accept("application/json")
//tells cxf to convert the json to a string type upon return
.get(String.class);
// Return the json result as a string
return result;
}
your paramData variable is already a valid json. I do not think you need yo use JSON.Stringify() again.And what is this is the ajax call:
statusCode : {
200 : function(data) {
}
}
Status code is supposed to be coming from the server in response.
First, your ajax header should be like this:
headers: {
Accept: "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8"
},
url:
url: "http://localhost:9000/service/myService/sendInputs"
Second, you need to have MyModel with param1 field and Also setters and getters. And this can be your service method:
public String sendInputs(MyModel model)
{
//model.getParam1() will be "asdasd"
}

Consume Cookie and JSON with JAX-RS Jersey Service

I am sending these data to Restful Web Service (Jersey) using jQuery code and the method POST:
var dataString = {"id":1,"status":"passed","session":"nothing"};
$.post("https://localhost:8443/pv01/ws/user/cookie", dataString);
And with this data, I am sending a cookie. The data in te cookie come from an external API.
The problem what I am facing is how to receive the cookie value and the dataString together.
Here's my Java code to read a Cookie :
#POST
#Path("cookie")
public String cookie(#CookieParam("L14c") String str) {
Logger.getLogger(Main.class.getName()).log(Level.INFO, "message : " + str );
return str;
}
And for the data, I can do like this :
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#Path("cookie")
public String cookie(DataString dataString) {
Logger.getLogger(Main.class.getName()).log(Level.INFO, "message : " + dataString );
return "ok";
}
But when I combine the two methods to accept cookie and the JSON dataString, I got Error 415, Unsupported media type!
I tried to look on HTTP Headers, but I can access only cookies.
The problem is with the jQuery request. It looks like the Content-Type is defaulting to application/x-www-form-urlencoded. You should use a Browser debugger like Firebug. Makes it easier to spot these kind of things.
From what I've tested, it should work with something like
$.ajax({
url: theUrl,
type: "POST",
data: JSON.stringify(dataString),
dataType: "json",
contentType: "application/json",
success: function(response) {
alert(JSON.stringify(response));
}
});

Problems sending multiple objects through POST and SPRING-MVC

I'm developing REST services which have to receive multiple info. In this case, two objects and an attribute.
This is the javascript where I'm testing the POST request
var user = {
username: "admin",
password: "admin"
};
var userToSubscribe = {
username: "newuser",
password: "newpassword",
email: "user#1and1.es"
};
var openid = "myopenid";
$.ajax({
url: '/myportal/rest/subscribeUser.json',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json',
data: JSON.stringify({ user: user, userToSubscribe: userToSubscribe, openid: openid})
});
The POST request:
JSON
openid
"myopenid"
user
Object { username="admin", password="admin"}
userToSubscribe
Object { username="newuser", password="newpassword", email="user#1and1.es"}
Source
{"user":{"username":"admin","password":"admin"},"userToSubscribe":{"username":"newuser","password":"newpassword","email":"user#1and1.es"},"openid":"myopenid"}
And the controller which handles the POST:
#RequestMapping(method=RequestMethod.POST, value="/subscribeUser.json")
public #ResponseBody Message subscribeUser(#RequestBody("user") User user, #RequestBody("userToSubscribe") User userToSubscribe, #RequestParam String openid){
...
}
And the error is
POST subscribeUser.json 400 Incorrect request localhost:8080 990 B [::1]:8080
What am i doing wrong?
Thank you
The request body will contain the entire JSON content. So when you want to map the JSON, you use only one RequestBody annotated-parameter. You will have to do something like this:
public #ResponseBody Message subscribeUser(#RequestBody String str)
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(str);
And then use the convertValue method of the mapper to get your different objects from the string.
JsonNode node = mapper.readTree(str);
User theUser = mapper.convertValue(node.get("user"), User.class);
Similarly for the other objects
You cannot use #ModelAttributes in a RESTful method that accepts JSON. I believe the proper method is to use #RequestBody, as done here. You will most likely need to wrap the objects in some wrapper class, but I could be wrong there as I have never personally tried to pass multiple JSON objects in one request before.
That said, I think it would be a good idea if you rethought your REST api, removing the JSON arguments and instead passing them in as part of the URI path, if possible. I would suggest reading through this blog post.
You can create a java bean(POJO) containing all the objects like..
class JavaBean{
private User user;
private UserTOSubscribe userToSubscribe;
private Long openId;
// getter and setter
}
and pass this bean in to the Web service. so web service looks like..
#RequestMapping(method=RequestMethod.POST, value="/subscribeUser.json")
public #ResponseBody Message subscribeUser(#RequestBody JavaBean javaBean) {
...
}

Json data into Java REST service causing 500 error

I am trying to send a List of JSON objects into a post request. I keep getting a 500 error here. I feel like i am not setting up my variable in the Method definiton to the right data type but im not sure what it should be set too.
AJAX Request:
function post_request(json_data) {
$j.ajax({
url : '../api/createDisplayGroup/postHtmlVar/' + containerID[1] + '/' + containerType[1],
data: JSON.stringify(json_data),
dataType: 'json',
type : 'post',
contentType : 'application/json'
}).done(function(response) {
run_update(response);
}).error(function(jQXHR, textStatus, errorThrown) {
alert('error getting request');
});
};
Java REST Service (POST only):
#POST
#Path("/postHtmlVar/{containerId}/{contentType}")
#Consumes(MediaType.APPLICATION_JSON)
public List<TabDefinition> postHtml(#PathParam("containerId") String containerId, #PathParam("contentType") String contentType, List<JSONObject> displayGroups) {
Long contId = Long.parseLong(containerId);
Long contType = Long.parseLong(contentType);
//return convertToResponse(peopleFilterService.getDisplayGroups(contId, contType));*/
return testDisplayGroup();
}
You need to take the input json string as a #FormDataParam. I don't think your JAVA REST framework can marshal the json to a list of JSONObject. You may have to create a class representing the json data and define your method like this:
public List<TabDefinition> postHtml(#PathParam("containerId") String containerId, #PathParam("contentType") String contentType, #FormDataParam MyJSonDataClass myJsonDataClassObj) {

Categories