I post two Headers from a js file in a GET REST Call:
allstaffworking: function(_getstaff){
var currentToken = _GetToken();
var Headers = {
token: currentToken.tokenStaff,
};
var HeaderId = {
idtoken: currentToken.idtokenStaff,
};
console.log("idtoken"+Headers);
if (currentToken !== null) {
$http({
method : 'GET',
headers: Headers, HeaderId,
url : REST_URL+'staff/working'
}).then(function successCallback(response) {
_getstaff(response)
}, function errorCallback(response) {
console.log(response.statusText);
});
} else {
console.log("NON SEI LOGGATO!!!");
}
},
The Headers are:
var Headers = {
token: currentToken.tokenStaff,
};
var HeaderId = {
idtoken: currentToken.idtokenStaff,
};
This is the java page called by REST_URL+'staff/working':
public List<Staff> getStaff()
{
List<Staff> listOfStaff=sDao.getAll(Staff.class);
return listOfStaff;
}
#GET
#Path("/working")
#Produces(MediaType.APPLICATION_JSON)
#Consumes("application/json")
public List<Staff> getWStaff(#HeaderParam("token") String token, #HeaderParam("idtoken") int tokenid)
{
s = (Staff) sDao.getById(tokenid, Staff.class);
st = (StaffType) sDao.getById(s.getStaffType().getIdstaffType(), StaffType.class);
if (ex && st.getIdstaffType()==2){
List<Staff> listOfWStaff=stfDao.getAllW();
return listOfWStaff;
}
else
return null;
}
taking the two Header with: #HeaderParam("token") String token, #HeaderParam("idtoken") int tokenid
The first Header Param works, the second doesn't works, look this debug's image
How you can see from the image, the idtoken's header value is 11.
Therefore my java class should work taking this second #HeaderParman such int. But it doesn't work, error 500. I try to manually insert "11" , in this way:
s = (Staff) sDao.getById(11, Staff.class);
And in this way it works!! Then, the mistake is when I take the second #HeaderParam, I've also tried with take tokenid as String, an convert it using Integer.parseint(tokenid)
but it does not change.
I hope that somebody can help me
$http config object's header property takes an object as param, as you are passing 2 objects its picking the first one. Ideally you should pass something like this:
$http({
...
headers: {
token: currentToken.tokenStaff,
idtoken: currentToken.idtokenStaff
}
...
});
Also I am curious as to why you are not getting error in line where you are providing Headers and HeaderId as comma separated.
Related
I am passing data from controller.js to service.js to SpringController.java
but weird thing is happening when i pass $scope.credentials.uname data to Java Controller .
The data passed is coming in doublequotes . When i print the value in Java
its getting printed as "USER" instead of USER.
Also due to this i am not able to save the username in database.
$scope.submitUsername = function()
{
$log.info("username "+$scope.credentials.uname);
Here log is getting printed properly chrome console
username SYS_USER --> without double quotes
loginService.fetchUserType(angular.copy($scope.credentials.uname)).then(function(data)
{
if (data.loginType == 'NotValidUsername')
{
$log.info("Failure")
toaster.pop('information', "Warning", 'Enter Valid UserName');
}
else
{
$log.info("Success")
if (data.loginType == 'database')
{
$scope.isExternalUser = true;
$scope.showSubmitButton = false;
}
else
{
$scope.isExternalUser = false;
$scope.showSubmitButton = false;
}
}
})
};
service.js
fetchUserType : function(userName)
{
var promise = $http({
url : "checkUserType.do",
method : "POST",
data : JSON.stringify(userName)
}).success(function(data, status, header, config, statusText)
{
}).error(function(data, status, header, config, statusText)
{
if(!status === 901)
toaster.pop('error', status, statusText);
}).then(function(response)
{
return response.data;
})
return promise;
}
Java Controller method
#RequestMapping(value = "/checkUserType.do", method = { RequestMethod.GET, RequestMethod.POST })
#ResponseBody
public Object checkUserType(#RequestBody String username,HttpServletRequest request)
{
log.info(" Inside checkUserType "+username);
User user = new User();
user.setUserName(username);
String userType = loginService.checkUserType(user.getUserName());
user.setLoginType(userType);
return user;
}
Output on console is
Inside checkUserType "SYS_USER".
How should i pass data so that i can avoid these ""(doublequotes) being passed to Java Controller
Remove JSON.stringify(userName) from your service.js This is whats adding the double quotes around your request.
Instead your data should just be data: userName. When it gets send to your controller it will be correctly converted to json for your controller to digest.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
From a js page (in angular) I call a REST request, GET method, were I would to pass an header, this is the function that I call from the REST request:
allstaffworking: function(_getstaff){
var currentToken = _GetToken();
var Headers = {
token: currentToken.stringtoken
};
console.log("idtoken"+Headers);
if (currentToken !== null) {
$http({
method : 'GET',
headers: Headers,
url : REST_URL+'staff/working'
}).then(function successCallback(response) {
_getstaff(response)
}, function errorCallback(response) {
console.log(response.statusText);
});
} else {
console.log("NON SEI LOGGATO!!!");
}
},
Whithout headers: Headers, it works, but I want to pass an important json string: {"idtokenStaff":11,"staffType":{"idstaffType":2,"type":"Dipendente"},"tokenStaff":"88d08m8ve4n8i71k796vajkd01"} in the Headers. I don't know How I can take this string in Jersey. This is java file in with I have the REST method:
#Path("/staff")
public class StaffController {
BaseDao sDao = new StaffDaoImpl();
StaffDao stfDao = new StaffDaoImpl();
TokenStaffDao tsDao = new TokenStaffDaoImpl();
TokenStaff ts = new TokenStaff();
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<Staff> getStaff()
{
List<Staff> listOfStaff=sDao.getAll(Staff.class);
return listOfStaff;
}
#GET
#Path("/working")
#Produces(MediaType.APPLICATION_JSON)
#Consumes("application/json")
public List<Staff> getWStaff(#HeaderParam("token") String token) throws JSONException
{
JSONObject jsonObj = new JSONObject(token);
Boolean id = tsDao.getExistence(jsonObj.getInt("idtokenStaff"));
if (id){
List<Staff> listOfWStaff=stfDao.getAllW();
return listOfWStaff;
}
else
return null;
}
}
Taking header from: #HeaderParam("token") String token. How Can I take the element of the header?
A bit late to answer this, but you can also use #Context annotation to get httpheaders.
Eg.
public List<Staff> getWStaff(#Context HttpHeaders httpHeaders) {
String token = httpHeaders.getHeaderString("token");
JSONObject jsonObj = new JSONObject(token);
}
Can u explain me why DELETE method (store.remove() in Edit.js) throws 400 Bad request. Other method works well. In header request url seems to be ok "http://localhost:8080/Diary/rest/notes/22?_dc=1461837327580".
I know that problem is in payload of DELETE method, store.remove() includes ID as payload. How can i disable that and send DELETE method without body, because ID is already in URL
Rest Service
#Path("/notes")
public class NoteRestService {
#Context
private UriInfo uriInfo;
#Context
private HttpServletRequest request;
private NoteDaoImpl noteDao = new NoteDaoImpl();
#GET
#Produces("application/json")
public String getNotes(){
String login = request.getSession(true).getAttribute("login").toString();
List<Note> notes = noteDao.getUserNotes(login);
return new Gson().toJson(notes);
}
#POST
#Consumes("application/json")
public Response postNote(Note note){
String login = request.getSession(true).getAttribute("login").toString();
note.setUser(login);
noteDao.persist(note);
URI noteUri = uriInfo.getAbsolutePathBuilder().path(Long.toString(note.getId())).build();
return Response.created(noteUri).build();
}
#PUT
#Path("{id}")
#Consumes("application/json")
public Response updateNote(#PathParam("id") String id,Note note){
String login = request.getSession(true).getAttribute("login").toString();
Note editNote = noteDao.getNote(Long.parseLong(id));
note.setCreated(editNote.getCreated());
note.setUser(login);
noteDao.update(note);
return Response.ok().build();
}
#DELETE
#Path("{id}")
public Response deleteNote(#PathParam("id") String id){
Note note = noteDao.getNote(Long.valueOf(id));
if (note==null){
throw new NotFoundException();
}
noteDao.delete(Long.parseLong(id));
return Response.noContent().build();
}
}
EditController.js
Ext.define('MVC.controller.Edit', {
extend: 'Ext.app.Controller',
init: function () {
this.control({
'editForm > button#SaveRecord': {
click: this.onSaveButtonClick
},
'editForm > button#DeleteButton': {
click: this.onDeleteButtonClick
}
});
},
onSaveButtonClick: function (btn) {
//get reference to the form
var detailView = btn.up('editForm');
//get the form inputs
var data = detailView.getValues();
//see if the record exists
var store = Ext.getStore('TestStore');
console.log(data.id);
var record = store.getById(data.id);
if (!record) {
record = Ext.create('MVC.model.Note', {
title: data.title,
created: new Date(),
updated: new Date(),
text: data.text
});
Ext.MessageBox.alert('Created', data.title);
store.insert(0, record);
store.sync();
return;
}
record.set(data);
store.sync();
//manually update the record
detailView.updateRecord();
},
onDeleteButtonClick: function (btn) {
//get reference to the form
var detailView = btn.up('editForm');
//get the form inputs
var data = detailView.getValues();
var store = Ext.getStore('TestStore');
var record = store.getById(data.id);
store.remove(record);
store.sync();
}
});
UPD: Store
Ext.define('MVC.store.TestStore', {
extend: 'Ext.data.Store',
requires: [
'MVC.model.Note'
],
storeId: 'TestStore',
model: 'MVC.model.Note',
autoLoad: false,
proxy: {
type: 'rest',
url: 'rest/notes',
actionMethods: {
create: 'POST',
read: 'GET',
update: 'PUT',
destroy:' DELETE'
},
reader: {
type: 'json',
rootProperty: 'data'
},
writer: {
type: 'json',
writeAllFields: true
}
}
});
You can't have a HttpMethod.DELETE with a body.
This is not explicitly stated in the RFC, but some Proxy servers will reject the body if you have one in a delete method. Spring lowers the standard and will reject your query with a Bad Request.
Remove the body as well as the answer to fix your issue.
Check this for more information:
Is an entity body allowed for an HTTP DELETE request?
If TestStore is the store you're using, I'd guess that your problem is here:
actionMethods: {
create: 'POST',
read: 'GET',
update: 'PUT',
destroy: 'GET'
},
I don't recognize the #DELETE annotation, so I'm not 100% sure but if your controller is expecting DELETE, and you're sending GET, that could explain the 400 error.
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"
}
I have a service, which I can access with the following jQuery code (from google chrome with --disable-web-security)
$.ajax({
type: 'POST',
url: "http://10.30.1.2:9234/myapp/v6/token/generate",
headers: {
"Content-Type":"application/json",
"Accept":"application/json"
},
data: JSON.stringify({
"staffId" : "13254",
"password" : "JustADummyPassword"
})
}).done(function(data) {
console.log(data);
});
$.ajax({
type: 'GET',
url: "http://10.30.1.2:9234/myapp/v6/user/appl/Firstname/Lastname/email#address.com/1998-01-01",
headers: {
"Content-Type":"application/json",
"Accept":"application/json"
}
}).done(function(data) {
console.log(data);
});
The first call sets a cookie, which is required for the second call to authenticate. This works fine, and both requests return expected results.
I am trying to set up automated testing for the service, and have this written in JAVA, using RestAssured.
public class UserApplication {
public static Map<String, String> authCookies = null;
public static String JSESSIONID = null;
public static void main(String[] args) {
Response resp = hello();
resp = apiUserApplication();
}
public static Response apiUserApplication() {
String userAppl = "http://10.30.1.2:9234/myapp/v6/user/appl/Firstname/Lastname/email#address.com/1998-01-01";
Response response = RestAssured.given()
.cookie("JSESSIONID", JSESSIONID).and()
.header("Accept", "application/json").and()
.header("Content-Type", "application/json").and()
.when().get(userAppl);
return response;
}
public static Response hello() {
String helloUrl = "http://10.30.1.2:9234/myapp/v6/hello";
Response response = RestAssured.given().cookies(authCookies)
.contentType("application/json").when().get(helloUrl);
return response;
}
}
The first call (hello) works fine, and returns 200 code, and gets a valid token for use in the second call. The error I am getting from the second call with a 400 status code is...
{"errors":["Content type 'null' not supported"]}
I'm not experienced with RestAssured, but your code is set up to first call, hello, then apiUserApplication. You have some class level variables that you default to null, but you never explicitly give them a value. In particular, it looks in the second call, apiUserApplication, you are setting the value of the cookie to a null value.
I also do not see why you are returning this response object? It would make sense if you were to examine it, ensure that the response has data as you expected and that you then set this session ID for the second request.
It looks like JSESSIONID and authCookies are initialized as null and not changing in this code.