get Header in jersey from a GET request - java

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);
}

Related

How to extract data from POST request in azure functions java

I send form data in POST request from angular app to my azure functions who wrriten in java.
the client side look like this:
#Injectable({
providedIn: 'root'
})
export class SendItemToAzureFunctionsService {
private functionURI: string;
constructor(private http: HttpClient) {
this.functionURI = 'https://newsfunctions.azurewebsites.net/api/HttpTrigger-Java?code=k6e/VlXltNs7CmJBu7lmBbzaY4tlo21lXaLuvfG/tI7m/XXXX';
}
// {responseType: 'text'}
sendItem(item: Item){
let body = new FormData();
body.append('title', item.title);
body.append('description', item.description);
body.append('link', item.link);
return this.http.post(this.functionURI, body)
.pipe(
map((data: string) => {
return data;
}), catchError( error => {
return throwError( 'Something went wrong!' );
})
)
}
}
when Item recived to azure functions.
the aim of functions is to send this item in push notifications via firebase to android app.
the azure functions with HTTP trigger look like this:
#FunctionName("HttpTrigger-Java")
public HttpResponseMessage run(#HttpTrigger(name = "req", methods = { HttpMethod.GET,
HttpMethod.POST }, authLevel = AuthorizationLevel.FUNCTION) HttpRequestMessage<Optional<String>> request,
final ExecutionContext context) {
context.getLogger().info("Java HTTP trigger processed a request.");
// Parse query parameter
String itemDetails = request.getBody().get();
if (itemDetails == null) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("Please pass a name on the query string or in the request body").build();
} else {
// ======
String postUrl = "https://fcm.googleapis.com/fcm/send";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(postUrl);
post.setHeader("authorization", FIREBAE_AUTH);
post.setHeader("Content-type", "application/json");
JSONObject contentJson = new JSONObject();
contentJson.put("title", "example title");
contentJson.put("description", "example text");
JSONObject pushNotificationJson = new JSONObject();
pushNotificationJson.put("data", contentJson);
pushNotificationJson.put("to", "/topics/newsUpdateTopic");
try {
StringEntity stringEntity = new StringEntity(pushNotificationJson.toString(), "UTF-8");
post.setEntity(stringEntity);
HttpResponse response = httpClient.execute(post);
System.out.println(response.getEntity().getContent().toString());
} catch (IOException var9) {
var9.printStackTrace();
}
// =========
}
return request.createResponseBuilder(HttpStatus.OK)
.body("succeed to send new item in push notification to clients").build();
}
when I am running String itemDetails = request.getBody().get();
I am getting:
------WebKitFormBoundary2gNlxQx5pqyAeDL3
Content-Disposition: form-data; ....
I will be glad to know how to get data item from that?
If you want to parse from-date type data in Azure function with java, you can try to use MultipartStream in SDK org.apache.commons.fileupload to implement it. For example
code
public HttpResponseMessage run(
#HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
final ExecutionContext context) throws IOException {
context.getLogger().info("Java HTTP trigger processed a request.");
String contentType = request.getHeaders().get("content-type");
String body = request.getBody().get(); // Get request body
String boundary = contentType.split(";")[1].split("=")[1]; // Get boundary from content-type header
int bufSize = 1024;
InputStream in = new ByteArrayInputStream(body.getBytes()); // Convert body to an input stream
MultipartStream multipartStream = new MultipartStream(in, boundary.getBytes(), bufSize, null); // Using MultipartStream to parse body input stream
boolean nextPart = multipartStream.skipPreamble();
while (nextPart) {
String header = multipartStream.readHeaders();
int start =header.indexOf("name=") + "name=".length()+1;
int end = header.indexOf("\r\n")-1;
String name = header.substring(start, end);
System.out.println(name);
multipartStream.readBodyData(System.out);
System.out.println("");
nextPart = multipartStream.readBoundary();
}
return request.createResponseBuilder(HttpStatus.OK).body("success").build();
}
Test. I test with postman
I've used #Jim Xu's code and created a class to get the data in easier way. Here is the gist - https://gist.github.com/musa-pro/dcef0bc23e48227e4b89f6e2095f7c1e

Taking two HeaderParam in GET, a strange mistake for int #HeaderParam

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.

Parameters of POST request to Java server from Angular client

I've got Angular app and Java server.
I need to send POST request with JSON object consisting of string array and string field.
I'm using Angularjs $resource and Java javax.ws.rs.
My latest try as follows:
Client:
var messages = $resource('resources/messages/getmessages', {}, {
update: { method: 'POST', url: 'resources/messages/updatemessages' }
});
//...
var _args = { 'msgIdList': ['1', '2', '3'],
'action': 'makeSmth' };
return messages.update(_args).$promise.then(
function (data) {
//...
},
function (error) {
//...
}
)
Server:
#POST
#Path("updatemessages")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Produces(MediaType.APPLICATION_JSON +"; charset=UTF-8")
public Response updateMessages( #FormParam("msgIdList") List<String> msgIdList,
#DefaultValue("") #FormParam("action") String action,
#CookieParam("rgsid") String c_sid,
#Context HttpServletRequest httpservletreq) {
//...
}
The problem is that I've got 415 Unsupported Media Type error, and don't know what to do next. I've tried lots of things, but may be I was wrong from the start, and I can't pass parameters this way?
Any help would be appreciated, thanks!
you can try this in your angular, maybe it can help.
var sendPost = $http({
method: "post",
url:"JAVA_SERVER_SERVICE_URL",
data: {
msgIdList: 'your_value',
action: 'your_value'
},
headers: { 'Content-Type': 'application/json' }
});
So, eventually I made a wrapper class, so now it looks this way:
#XmlRootElement
private static class RequestWrapper {
#XmlElement
private ArrayList<String> msgIdList;
#XmlElement
private String action;
public ArrayList<String> getMsgIdList() {
return msgIdList;
}
public void setMsgIdList(ArrayList<String> msgIdList) {
this.msgIdList = msgIdList;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public RequestWrapper() {
}
}
#POST
#Path("updatemessages")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON +"; charset=UTF-8")
public Response updateMessages( RequestWrapper requestData,
#CookieParam("rgsid") String c_sid,
#Context HttpServletRequest httpservletreq) {
//...}
Angular part stays unchanged.
I'm not really sure, if this the right way to go (class description and so on), but it works.

Rest DELETE Bad Request

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.

Consuming JSON as application/x-www-form-urlencoded

I have a JAX-RS project where the POST is not working. I have #GET URLs which work fine. Everything seems to work fine except this #POST.
#POST
#Path("/json/insert")
#Produces(MediaType.APPLICATION_JSON)
#Consumes("application/x-www-form-urlencoded")
public String postJSONInsert(
#FormParam("instance") String instance,
#FormParam("db") String table) {
String json;
EDPObject edp_obj = new EDPObject();
try {
json = edp_obj.insert("json", instance, table);
} catch(Exception e) {
edp_obj.endSession();
json = handleJSONError(e);
}
return json;
}
Getting 500 not yet connected in firebug when trying this on client:
$.ajax('http://127.0.0.1:8070/sixaxis/webapi/json/insert', {
data: {
db: '17:2',
instance: 'shawn'
},
dataType: 'json',
type: 'POST'
});
Have you tried:
#Consumes(MediaType.APPLICATION_JSON)
since your jQuery is:
dataType:'json'
Update (thanks for the feedback):
Then the method at least should be:
#POST
#Path("/json/insert")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public String postJSONInsert( Map<String,Object> params ){
// Your business logic
}

Categories