How to get Parameter from Ext.Ajax.request in java controller - java

I am having one problem in retrieving the parameter which i am passing using Ext.Ajax.request to my JAVA controller class.
I am sending request to my controller using below code
Ext.Ajax.request({
url : 'projecttask/GetprojectTasks.action',
method: 'POST',
jsonData: {
sampledata: record.data
},
type: 'json',
scope: this, // add the scope as the controller
callback : function(options, success, response) {
console.log('RESPONSE FROM SERVER :'+response);
}
});
my java controller method to receive the request is
#RequestMapping(value="/projecttask/GetprojectTasks.action")
public #ResponseBody Map<String, ? extends Object> getprojectTasks(HttpServletRequest request,
HttpServletResponse response,#RequestBody Project project) throws Exception {
try {
System.out.println("PROJECT ::"+project);
System.out.println("RPOJECT DATA ::"+request.getParameter("sampledata"));
Object data = request.getParameter("sampledata");
Project prj = (Project) data;
System.out.println("CREATE TASK DATA IS ::"+prj.getProjectid());
return null;
}catch(Exception e) {
return getModelMapError("Error trying to create contact");
}
}
but it gives me error mentioned below
org.codehaus.jackson.map.JsonMappingException: Unrecognized field "sampledata" (Class com.kintu.projectmgt.model.Project), not marked as ignorable
so what i am doing wrong which not allowed my function to get sampledata passed as parameters. How can i get my Parameters passed value any idea ?
My firebug shows that sampledata contains all values. Please help me to find the problem and solve it as soon as possible.
I am using Ext JS 4.0.2a and JAVA as my serverside technology.

you can use
String postParamsJSON = request.getReader().readLine();
to get the POST data.

Related

IBM Mobilefirst JAVA adapter giving MFP-Conflict=Concurrency failure while storing user data

I am building a JAVA HTTP Adapter, I am authenticating the user in UserAuthenticationSecurityCheck class using the following method
#Override
protected AuthenticatedUser createUser() {
return new AuthenticatedUser(userId, logonId, this.getName(), attributes);
}
#Override
protected boolean validateCredentials(Map<String, Object> credentials) {
return false;
}
After this control goes to android app then they call the REST API called /updateClientRegistrtion which will update the ClientRegistrationData
#GET
public Response updateClientRegistartion(#Context HttpServletRequest request) {
AuthenticatedUser authUser = securityContext.getAuthenticatedUser();
Map<String, Object> attributes = authUser.getAttributes();
ClientData clientData = securityContext.getClientRegistrationData();
clientData.getProtectedAttributes().put(some parameter);
if (clientData.getClientId() != null) {
securityContext.storeClientRegistrationData(clientData);
}
But this code is giving me error like
Exception Message :
409; headers=[ MFP-Conflict=Concurrency failure]; body={}
Is there any solution to this problem? Can someone please help me with this.
Tutorial followed : http://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/authentication-and-security/user-authentication/security-check/
409; headers=[ MFP-Conflict=Concurrency failure]; body={}
results when concurrent requests try to store attributes into the same row or the data in the row being modified by another request before it was updated.
This could be from the request being fired more than once ( in close proximity).Another possibility is that while one request was working on the data in memory, another had already modified and updated it.
The code should still work without the line:
securityContext.storeClientRegistrationData(clientData);
Try that out.
Alternatively, put a try-catch around the
storeClientRegistrationData(clientData)
and retry in the catch block.

rest controller works but ajax post method return an error

I'm making a post method using $.ajax which is this
$(function(){
$("#postMembers").click(function(){
let member ={
firstName: "khookina",
lastName : "khooak",
age:1,
sex:"female",
duty:"undefined",
dailyJeton:2
}
$.ajax({
type: "post",
url: "http://localhost:8080/RCP2/members",
data: member,
dataType: "application/json",
success: function (response) {
alert("success");
},
error: function(error){
alert("error");
}
});
});
and my rest controller is this
#PostMapping(consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE}, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public String createMembers(Member member) {
if (member.hasError()) {
throw new CreatePersonException("All the fields must be filled properly in order to create a new member.");
}
if (personDao.createMember(member)) {
return "Member: " + member.getFirstName() + " " + member.getLastName() + " successfully created.";
}
return "couldn't create member, please try again later.";
}
I have a create member button in the webpage that executes this ajax post method, when I press it, everything works fine, the member information gets sent to the rest controller, It gets created (100% working) and returns {"readyState":4 status":200, "statusText":"parsererror"} and error: function(error) of ajax post method gets called
What's the problem?
it's the first day I'm working with ajax and javascript, I don't really understand what's happening.
Thanks in advance
P.S I've tried changing data-type text json, json and some others that been suggested in similar questions, but they didn't work for me, so i decided to make a question myself.
Try changing
data: JSON.stringify(member) and you will have your response in your success in the result/
Remove data type from ajax request and it works.
Remove this.
dataType: "application/json"
For details refer this

Ajax GET error with AngularJS and Spring MVC

I have an angular function that uses $http request with GET and params :
$scope.getMatchingRecipe = function(){
$http({
method: "GET",
url: "/recipemanagement/getMatchingRecipeList",
params: {
matchingText : $scope.matchingRecipe.text
}
}).success(function (data) {
console.log(data);
$scope.recipeList = data;
console.log($scope.recipeList[0]);
})
.error(function (data) {
console.log(data);
});
};
And the MVC controller as :
#RequestMapping(value="/getMatchingRecipeList")
public #ResponseBody String getRecipeDropdownList(#RequestParam(value="matchingText") String matchingText){
List<Recipe> recipeList = recipeServiceImpl.getMatchingRecipes(matchingText);
for(Recipe recipe : recipeList){
System.out.println("recipe :"+recipe.getName());
}
List<RecipePO> recipePOList = new ArrayList<RecipePO>();
System.out.println("List Size :"+recipeList.size());
for(Recipe recipe : recipeList){
RecipePO recipePO= new RecipePO();
recipePO.setId(recipe.getId());
recipePO.setName(recipe.getName());
recipePO.setDifficulty(recipe.getDifficulty());
recipePO.setServes(recipe.getServes());
recipePOList.add(recipePO);
}
try {
return new ObjectMapper().writeValueAsString(recipePOList);
} catch (JsonProcessingException e) {
e.printStackTrace();
return "Error";
}
}
However, when the function getMatchingRecipeList is called, it returns 404. But when I check the backend console (i.e. the controller function getRecipeDropdownList makes a database call through hibernate, so it shows query executed in console), the function is executed.
It seems that the problem isnt in the ajax call. The server was throwing an error from backend and hence returned error.jsp page.
The problem :
Service class was made #Transactional.In DAO layer, I used session.close() (yeah, duh);
The analysis :
I wrapped up all the functions in try-catch block and got to know of this error. It threw hibernate session already closed error in stacktrace. That's where it was returning error.jsp page
The solution :
I removed session.close() from DAO class. That solved the issue.

How to pass input parameters using rest client in spring restful web services

I'm trying to create an web service using spring rest4, but not able to pass input parameters through rest-client, can anybody suggest me how to pass input parameters.
RequestMapping(value = "/create", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody Status addEmployee(#RequestBody User user) {
try {
// Manually setting passing parameters
user.setUserId(0);
user.setFirstName("dfsdfsd");
user.setUserMailId("sadsda");
user.setAddress("sfds");
user.setCreatedBy(1);
user.setIsDeleted(0);
user.setLastName("sadas");
user.setMobileNumber("adsasdsa");
user.setUsrtStatus(1);
user.setUserPassword("asdsaf");
user.setRoleId(1);
System.out.println("firstname:=" + user);
dataServices.addEntity(user);
System.out.println(user);
return new Status(1, "Employee added Successfully !");
} catch (Exception e) {
e.printStackTrace();
return new Status(0, e.toString());
}
}
I'm using "WizTool.org RestClient 3.2.2", Url = "http://localhost:8080/XYZ2/rest/user/create" & input parameters i'm passing as -
{
"inputs": [{
"parameterName": "pv_user_id",
"parameterValue": ""
}{
"parameterName": "pv_adress",
"parameterValue": "kjhfgkjdfhgfdhk"
}]
}
thanks in advance
Add the following to your controller,
RequestMapping(value = "/userformat", method = RequestMethod.GET)
public #ResponseBody User getUserFormat() {
User user = new User();
user.setUserId(0);
user.setFirstName("dfsdfsd");
user.setUserMailId("sadsda");
user.setAddress("sfds");
user.setCreatedBy(1);
user.setIsDeleted(0);
user.setLastName("sadas");
user.setMobileNumber("adsasdsa");
user.setUsrtStatus(1);
user.setUserPassword("asdsaf");
user.setRoleId(1);
return user;
}
Call this url "http://localhost:8080/XYZ2/rest/user/userformat" in your browser, it will return you user representation in json.
Now copy this json format for the user and remove all the above code which was added to your controller.
In wiztool rest client:
1. enter the url "http://localhost:8080/XYZ2/rest/user/userformat". Assuming that you are deleting its corresponding controller mapping after this process
2. select method as GET
3. click the '>>' button to fire the request
4. copy whatever json you get in the HTTP response "Body" as shown in figure at the bottom
User json might be something like the below one. I have included only few properties. For rest of them you can get from output of the above introduced url "userformat".
{
"userId": 1,
"firstName": "ronaldinho",
"lastName": "Gaucho",
"userMailId": "r10#gmaildummy.com",
"roleId": 2
}
You can use this in request body for this url "http://localhost:8080/XYZ2/rest/user/create"
In wiztool rest client:
1. enter the url ""http://localhost:8080/XYZ2/rest/user/create""
2. select method as POST
now click on "Body" as highlighted in image. choose "String body" from dropdown. in the next input, enter "application/json" which is content-type. Now paste the user json format which we copied from the output of first url and paste it in the text area. you can check with the below image
click '>>' to fire the request.
Why I am suggesting you this method is because I do not know if you have any json property annotations in User class. Also it is better to use this way than creating the json manually.

Tapestry5 : URL Re-writing : Pass parameters to transformPageRenderLink method

I am upgrading tapestry from 5.2.4 to 5.3.8 and am stuck at re-implementing the URL re-writing part.
In my application a user account can have multiple data stores. User can have same page of different stores active at the same time. Hence I need to put the storeId in page links and event links URLs. So What is done is as follows.
I register MyLinkTransformerClass in AppModule as follows.
#Contribute(PageRenderLinkTransformer.class)
#Primary
public static void provideURLRewriting( OrderedConfiguration<PageRenderLinkTransformer> configuration){
configuration.addInstance(
"Faces", MyLinkTransformer.class);
}
Following is the MyLinkTransformer class which implements PageRenderLinkTransformer
public PageRenderRequestParameters decodePageRenderRequest(
Request request) {
// for incoming requests - remove the store id from URL and
// save into Request as an attribute
String path = request.getPath();
if (path.equals("/")) {
// Redirect to accounts page
return new PageRenderRequestParameters("account", new EmptyEventContext(), false);
}
else {
String start = path.split("/")[1];
if (!ignoredRewriteSet.contains(start) && !start.startsWith("account")) {
String storePath = path.substring(1).substring(path.indexOf("/"));
int idx = storePath.indexOf("/");
if (idx < 0) idx = storePath.length();
String storeId = storePath.substring(0, idx).trim();
RequestHelper.setStoreId(request, storeId);
EventContext urlEventContext = new URLEventContext(contextValueEncoder, new String[]{storeId});
EventContext arrayEventContext = new ArrayEventContext(typeCoercer, "foo");
return new PageRenderRequestParameters(storePath.substring(idx), arrayEventContext, false);
//return new PageRenderRequestParameters(storePath.substring(idx), new EmptyEventContext(), false);
}
}
return null;
}
public Link transformPageRenderLink(
Link defaultLink,
PageRenderRequestParameters parameters) {
// for outgoing requests- This is where I want to access the store Id
// which is stored in Request class of Tapestry as an attribute and
// add it to the URL
return null;
}
So, the idea is to remove storeId from URL in decodePageRenderRequest method and save it in the Request class of Tapestry as an attribute. And while creating outgoing URLs of page link and event link, I want to access the storeId which was saved in Request and inject it to the URL which will be rendered in method transformPageRenderLink.
But I don't know how to pass parameters to transformPageRenderLink method or access Request instance there.
I am following http://blog.tapestry5.de/index.php/2010/09/06/new-url-rewriting-api/ example.
I am new to URL Rewriting, any help with this will be appreciated.
You will probably be interested in the ModeComponentEventLinkEncoder here. It removes a "mode" from the URL and puts it onto the Environment before passing it on to the normal tapestry URL processing.
It's a two way process so the "mode" is included in any links generated on the page.
Note: This is applied as a decorator here

Categories