Get the values of posted array in servlet - java

var schedule = [];
var data = {
'user_id' : '12',
'day_of_week' : 'Monday',
'when' : 'start',
'modified' : 'true'
}
schedule.push(data);
var data = {
'user_id' : '13',
'day_of_week' : 'Tuesday',
'when' : 'end',
'modified' : 'false'
}
schedule.push(data);
// schedule would have two objects in it
I am posting array to servlet using jquery ajax post request as below .
data : {'myData':schedule},
url :"./myController",
Now how can I get array of objects and literate to get all the values? Each array object has string, long and boolean type values. How can I get all the values by iterating?

May be you can try this
json.getJSONObject("myData").getString("your_values");

Related

How to return only 1 field in MongoDB?

I'm trying to get the order number where a transactionId is equal to another variable I have in my code. My tolls.booths collection looks like this
In my code,
def boothsException = booths.find([ "pings.loc.transactionId": tollEvent.id, "pings.loc.order":1] as BasicDBObject).iterator()
println boothsException
I am getting boothsException = DBCursor{collection=DBCollection{database=DB{name='tolls'}
I would like to essentially say get where transactionId = 410527376 and give me that order number in boothsException (5233423).
This is using MongoDB Java Driver v3.12.2.
The code extracts the value from the returned cursor. I am using newer APIs, so you will find some differences in class names.
int transId = 410527376; // same as tollEvent.id
MongoCursor<Document> cursor = collection
.find(eq("pings.loc.transactionId", transId))
.projection(fields(elemMatch("pings.loc.transactionId"), excludeId()))
.iterator();
while (cursor.hasNext()) {
Document doc = cursor.next();
List<Document> pings = doc.get("pings", List.class);
Integer order = pings.get(0).getEmbedded(Arrays.asList("loc","order"), Double.class).intValue();
System.out.println(order.toString()); // prints 5233423
}
NOTES:
The query with projection gets the following one sub-document from the pings array:
"pings" : [
{
"upvote" : 575,
"loc" : {
"type" : "2dsphere",
"coordinates" : [ .... ],
"transactionId" : 410527376,
"order" : 5233423
},
...
}
]
The remaining code with looping the cursor is to extract the order value from it.
The following are the imports used with the find method's filter and projection:
import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Projections.*;

how to retrive nested document and arrays values in elasticsearch

I have a following document
{
"_index" : "Testdb",
"_type" : "artWork",
"_id" : "0",
"_version" : 1,
"found" : true,
"_source":{"uuid":0,"ArtShare":{"TotalArtShares":0,"pricePerShare":0,"ArtworkUuid":12,"AvailableShares":0,"SoldShares":0},"StatusHistoryList":[{"ArtWorkDate":"2015-08-26T13:20:17.725+05:00","ArtworkStatus":"ACTIVE"}]}
}
i want to access/retrieve the value of ArtShare and its attributes and values of array StatusHistoryList
i am doing like this
val get=client.prepareGet("Testdb","artWork",Id.toString())
.setOperationThreaded(false)
.setFields("uuid","ArtShare","StatusHistoryList"
)
.execute()
.actionGet()
if(get.isExists())
{
uuid=get.getField("uuid").getValue.toString().toInt
//how to fetch `artShare` whole nested document and array elements `StatusHistoryListof`
}
UPDATE
if i do this
val get=client.prepareGet("Testdb","artWork",Id.toString())
.setOperationThreaded(false)
.setFields("uuid","ArtShare","StatusHistoryList"
,"_source","ArtShare.TotalArtShares")
.execute()
.actionGet()
if(get.isExists())
{
uuid=get.getField("uuid").getValue.toString().toInt
var totalShares= get.getField("ArtShare.TotalArtShares").getValue.toString().toInt
}
then following exception thrown
org.elasticsearch.ElasticsearchIllegalArgumentException: field [ArtShare] isn't a leaf field
at org.elasticsearch.index.get.ShardGetService.innerGetLoadFromStoredFields(ShardGetService.java:368)
at org.elasticsearch.index.get.ShardGetService.innerGet(ShardGetService.java:210)
at org.elasticsearch.index.get.ShardGetService.get(ShardGetService.java:104)
at org.elasticsearch.action.get.TransportGetAction.shardOperation(TransportGetAction.java:104)
at org.elasticsearch.action.get.TransportGetAction.shardOperation(TransportGetAction.java:44)
at org.elasticsearch.action.support.single.shard.TransportShardSingleOperationAction$ShardTransportHandler.messageReceived(TransportShardSingleOperationAction.java:297)
at org.elasticsearch.action.support.single.shard.TransportShardSingleOperationAction$ShardTransportHandler.messageReceived(TransportShardSingleOperationAction.java:280)
at org.elasticsearch.transport.netty.MessageChannelHandler$RequestHandler.doRun(MessageChannelHandler.java:279)
at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:36)
please guide me how to fetch these values
Yeah Actually the problem is that you have mentioned both "ArtShare" and "ArtShare.TotalArtShares" in the fields array. So it throws exception as you have already retrieved complete ArtShare object.
So please mention the fields that you want, If you want specified nested values then no need to access complete parent object.
Try this:
val get=client.prepareGet("Testdb","artWork",Id.toString())
.setOperationThreaded(false)
.setFields("uuid","StatusHistoryList",
"ArtShare.TotalArtShares")
.execute()
.actionGet()
if(get.isExists())
{
uuid=get.getField("uuid").getValue.toString().toInt
var totalShares= get.getField("ArtShare.TotalArtShares"
}
And if you want complete "ArtShare" object then simply write :
val get=client.prepareGet("Testdb","artWork",Id.toString())
.setOperationThreaded(false)
.setFields("uuid","ArtShare","StatusHistoryList"
)
.execute()
.actionGet()
if(get.isExists())
{
uuid=get.getField("uuid").getValue.toString().toInt
//how to fetch `artShare` whole nested document and array elements `StatusHistoryListof`
}

How to convert an array from javascript to a java array?

I have this javascript code :
$.ajax({
url: 'assignRenameRuleToAgency.do',
data: {agenciesId:agenciesId,ruleId: JSON.stringify ( ruleIDd ) },
success: function(response) {
toastr.success(response.message);
}
})
in the server side I did this :
String ruleId = request.getParameter("ruleId");
String[] agenciesId = request.getParameterValues("agenciesId");
ruleId was correct, but agenciesId was null.
Get JSON response from ajax call and then convert that json response to Java objects using below solutions.
Click here to know the working examples
It is a single String, not an array! You can change your structure to
agenciesId: [agenciesId]
then it will be an array.
I would however map the JSON message to a single POJO, for example by using Jackson.
If the parameter for ruleId can be received the way you describe the following should work:
String ruleId = request.getParameter("ruleId");
String agenciesId = request.getParameter("agenciesId");
I found the solution :
String[] myJsonData = request.getParameterValues("json[]");

Passing java attribute to a javascript function array argument

Currently, I have a servlet that forwards to a jsp. The jsp has access to a session attribute "current".
During the loading of the jsp, the information in "current" is passed to a javascript function that generates a graph.
This is all working fine. My only problem is that i'm hard coding the graph data.
How would i go about passing the data array from the servlet to the jsp. Basically, in the creerRapport function, in the 5th argument,
how do I replace that with java attributes?
Any help or ideas would be appreciated.
My current code with hard coded data.
<body onload="soumettreRapport();">
<script type="text/javascript">
function soumettreRapport() {
creerRapport( "${current.title}",
"${current.type}",
${current.width},
${current.height},
[
{
key: "Cumulative Return",
values: [
{
"label" : "2001" ,
"value" : -29.76
} ,
{
"label" : "2002" ,
"value" : 0
} ,
{
"label" : "2003 ,
"value" : 32.80
}
]
}
]
);
return false;
}
In Servlet, You need to to have JSON array as String then put this String into Request scope.
String jsonArrayString = convert(...); // Output [{key:"Cumulative Return", .... }]
request.setAttribute("jsonArrayString", jsonArrayString);
In JSP:
function soumettreRapport() {
var jsonArray = ${jsonArrayString};
creerRapport( "${current.title}",
"${current.type}",
${current.width},
${current.height}, jsonArray );
}

How to parse JSON object in Java:

I am trying to parse to JSON object in java. I am posting json key value object using dojo.xhrPost() method as shown below:
dojo.xhrPost({
url: /esturl/,
handleAs : "text",
content : {INST1 : {"0001" : "aa"},
INST2 : {"0002" : "bb"},
INST3 : {"0003" : "cc"}},
load : load(data),
error : error
});
Now I am reading this post data from request context:
Map<String, String[]> paramMap = requestContext.getParameterMap();
when I am printing this in loop:
Iterator it = paramMap.entrySet().iterator();
while(it.hasnext()){
Map.entry pairs = (Map.Entry) it.next();
System.out.println(pairs.getKey());
System.out.println(pairs.getkValue());
}
this returns me :
INST1
[Ljava.lang.String;#1b4cef
INST2
[Ljava.lang.String;#5801d
like wise, but I should be getting values like
INST1 : {"0001" : "aa"}, INST2 : {"0002" : "bb"}, INST3 : {"0003" : "cc"}}, any guidance would be highly appreciated.
Update
When I try to get value of one parameter using
String[] X = requestContext.getParameters{"INST1"};
if (X != null){
System.out.println(X.length);
System.out.println(X[0]);
System.out.println(X[0].length);
}
then am getting :
1
[object Object]
[object Object]
Q Now how can I get actual values of Object like INST1 : {"0001" : "aa"} instead of [object Object] ?
you can use this modified JSONObject class, pass the raw JSON code through the constructor or create (new object and assign JSON content later..) and use built-in get methods. view full javadoc here.
as given in the dojo documentation here the object which you set up will be read as name1=value1. So may be in your case the variables are being passed like INST1=0001,INST1=aa.
You can try to make the syntax of 'content' on these lines - INST1 : '{"0001" : "aa"}' or
INST1 : "{\"0001\" : \"aa\"}" so that INST1 has 1 unambiguous value

Categories