String query validate on json data - java

Map<String, Object> data = new HashMap<>()
data.put("Description","laks");
data.put("EntityName","Pub");
data.put("Severity","Critical");
String query = "Severity = Critical AND (EntityName contains P OR
EntityName contains p )";
In the above sample code I want to apply/validate the "query" string on sample json object "data". Is there any sample code which can help me. In above sample data and query it should return false?

It looks like you need this library:
https://github.com/json-path/JsonPath

Related

Using Java, how to add some node to an existing json at the start of array?

The below code inserts the "myvalue" field to the existing JSON but after the "id" key-value pair, I want to insert a value in this JSON but before the "id" field.
String originalJson="{"checkouts":[{"line_items":[{"id":"343f1f49d0ba7752b5ba84e0184384f4"}]}]}";
String modifiedJson= JsonPath.parse(originalJson)
.add("$.checkouts[0].line_items","myValue")
.jsonString();
The current output of the above code is :
{"checkouts":[{"line_items":[{"id":"343f1f49d0ba7752b5ba84e0184384f4"},"myValue"]}]}
But I want an output like this :
{"checkouts":[{"line_items":["myValue",{"id":"343f1f49d0ba7752b5ba84e0184384f4"}]}]}
You can do this:
String originalJson="{\"checkouts\":[{\"line_items\":[{\"id\":\"343f1f49d0ba7752b5ba84e0184384f4\"}]}]}";
DocumentContext json = JsonPath.parse(originalJson);
JSONArray array = json.read("$.checkouts[0].line_items");
array.add(0, "myValue");
String modifiedJson= json
.set("$.checkouts[0].line_items",array)
.jsonString();

How to Store a multiple values( during run time) in a map and getting a single value again

Iterator searchGetResponseIterator = searchGetResponse.entrySet().iterator();
Object obj = null;
Object dataPicker = null;
while(searchGetResponseIterator.hasNext()) {
Map.Entry searchGetResponseElement = (Map.Entry)searchGetResponseIterator.next();
if(searchGetResponseElement.getKey().equals("seSearch")) {
obj = searchGetResponseElement.getValue();
}
}
want to store the "obj" in map. In obj i have this >>
{"columns":[{"exp":{"$ali":"t2acName"},"ali":"sourceacName"},"**id**":"4c99eedc836adbeefd0e10db76a","**table**":"public.4c99eedc836adbeefd0e10db76a","fieldIds":["0336e7c7-b236-41b7-8ae8-194dcfc49693","369bc4de-b220-41a2-a7be-090c6386aa2e","37926ca2-044f-44f2-a349-0f2e1b61f120","2310dcca-010f-4830-b300-01fb00d2d15e","306554be-92b3-41a3-bb24-b59f4adc8b79","21cdee98-e3b4-4da9-a502-587c0a221413","1f26c177-944f-4378-9e26-8ee0882221cc","13532fa7-8320-4cc1-90fb-aa8fcc3f5f6f","16d3a857-e8d5-4172-87f5-a149187ec409",],"executionQueue":[{"flow":0,"start":1574674632999,"count":0,"rEnd":1574676432999,"status":"done"},{"flow":0,"start":1574620200000,"count":0,"rEnd":1574674632999,"status":"done"}]}
and i want to get id and table from table again.
You know the format of obj
{"**id**":"4c99eedc836adbeefd0e10db76a","**table**":"public.
Looks like there is consistent pattern where id appears, and where table appears in that blob of string / json.
Look at RegEx java tutorial and create one to extract id and table
https://www.baeldung.com/regular-expressions-java
An easier way is to convert the Object string to a map and get your fields.
if(searchGetResponseElement.getKey().equals("seSearch")) {
obj = searchGetResponseElement.getValue();
ObjectMapper objectMapper = new ObjectMapper();
HashMap responseMap = objectMapper.readValue(obj.toString(), HashMap.class);
}
Once you have the responseMap, you can inspect that object and get the required hierarchy from it.
For example: ((Map) ((List) responseMap.get("columns")).get(0)).get("id")
Note: The above example may not accurately represent your response model.

Mybatis - without any error it just return [] instead of db data

I'm trying to get return value from DB but it return [] instead of data
JAVA Restful
#RequestMapping("/regLocal")
public List<Map<String, Object>> regist_local(#RequestBody Map<String, Object> params){
Map<String, String> map = new HashMap<String, String>();
String location = (String) params.get("location_name"); // 'country'
String code = (String) params.get("location_code"); // '1'
map.put("location", location);
map.put("code", code);
List<Map<String, Object>> lists = se.selectList(ns+".regLocal", map); // it return []
return lists;
}
Mybatis
<select id="regLocal" resultType="map">
select hll.hll_code hll_code, hll.hll_name hll_name
from hl_local hll, h_location hl
where hll.hl_location = #{code} and hl.hl_name = #{location}
</select>
in Oracle DB SQL select is working fine without a single problem.
but it keep return this []
anyone know the problem??
You are using the selectList api and the XML declaration the return type is map, but you did not specify how the query results must fill the map. If you want that every row from the db is mapped to a Map<String, Object> you must write a ResultHandler.
You can use the selectMap api but the result is a Map<String,AnObject> where AnObject is a class that represents the columns selected in the query.
You can check this respone for more details.

How to parse query param effectively in java?

All I have is the request URI from which I have to parse the query params. What I'm doing is adding them to json/hashmap and fetching again like the following
String requestUri = "name=raju&school=abcd&college=mnop&color=black&fruit=mango";
All I have to do is to finally assign it to variables like the following
String name = "raju";
String school = "abcd";
String college = "mnop";
String color = "black";
String fruit = "mango";
So I am parsing the request uri like the following
String[] paramsKV = requestUri.split("&");
JSONArray jsonKVArr = new JSONArray();
for (String params : paramsKV) {
String[] tempArr = params.split("=");
if(tempArr.length>1) {
String key = tempArr[0];
String value = tempArr[1];
JSONObject jsonObj = new JSONObject();
jsonObj.put(key, value);
jsonKVArr.put(jsonObj);
}
}
The another way is to populate the same in hash map and obtain the same. The other way is to match the requestUri string with regex pattern and obtain the results.
Say for an example to get the value of school I have to match the values between the starting point of the string school and the next & - which doesn't sound good.
What is the better approach to parse the query String in java?
How could i handle the following thing in a better way?
I need to construct another hash map like the following from the above results like
Map<String, String> resultMap = new HashMap<String, String>;
resultMap.put("empname", name);
resultMap.put("rschool", school);
resultMap.put("empcollege", college);
resultMap.put("favcolor", color);
resultMap.put("favfruit", fruit);
To make it simple all I have to do is to parse the query param and construct a hashMap by naming the key filed differently. How could I do it in a simple way? Any help in this is much appreciated.
Short answer: Every HTTP Client library will do this for you.
Example: Apache HttpClient's URLEncodedUtils class
String queryComponent = "name=raju&school=abcd&college=mnop&color=black&fruit=mango";
List<NameValuePair> params = URLEncodedUtils.parse(queryComponent, Charset.forName("UTF-8"));
They're basically approaching it the same way. Parameter key-value pairs are delimited by & and the keys from the values by = so String's split is appropriate for both.
From what I can tell however your hashmap inserts are mapping new keys to the existing values so there's really no optimization, save maybe for moving to a Java 8 Stream for readability/maintenance and/or discarding the initial jsonArray and mapping straight to the hashmap.
Here is another possible solution:
Pattern pat = Pattern.compile("([^&=]+)=([^&]*)");
Matcher matcher = pat.matcher(requestUri);
Map<String,String> map = new HashMap<>();
while (matcher.find()) {
map.put(matcher.group(1), matcher.group(2));
}
System.out.println(map);
You can use Java 8 and store your data in HashMap in one operation.
Map<String,String> map = Pattern.compile("\\s*&\\s*")
.splitAsStream(requestUri.trim())
.map(s -> s.split("=", 2))
.collect(Collectors.toMap(a -> a[0], a -> a.length > 1 ? a[1]: ""));
You can do it by Jersey library (com.sun.jersey.api.uri.UriComponent or org.glassfish.jersey.uri.UriComponent class):
String queryComponent = "name=raju&school=abcd&college=mnop&color=black&fruit=mango";
MultivaluedMap<String, String> params = UriComponent.decodeQuery(queryComponent, true);
Use jackson json parser. Maven dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
Now use ObjectMapper to create Map from json string:
ObjectMapper mapper = new ObjectMapper();
Map list = mapper.readValue(requestUri, Map.class);

Extract field value from mongodb BasicDBobject

I am developing simple web application to learn jsp, mongodb, html. I have created an simple registration form in jsp which takes Name, Address and MobileNo information from user and insert it into mongodb, Now I want to retrieve this stored data and put value of every field in individual string variable.
Ex:
Name: varun; Address: Nagpur; MobileNo: 1234567890
Above data is stored in mongodb as:
{
"_id" : ObjectId("5259bacea6f8b1c4cd3431d3"),
"Name" : "varun",
"Address" : "nagpur",
"MobileNumber" : "1234567890"
}
Retrieved in jsp as follows:
MongoClient mongoC = new MongoClient(new ServerAddress("Localhost",27017));
DB database = mongoC.getDB("dbfrnzout");
DBCollection collec1 = database.getCollection("coll");
DBObject dock= collec1.findOne();
out.println(dock);
This code print one record as json document and I want to store value associated with every
field in individual string variable, something like this:
String s1 = varun ie. value of field Name
Need some guidance.
DBObject implements the Map<String, Object> interface so you should be able to do something like:
String name = (String) dock.get( "Name" );
String address = (String) dock.get( "Address" );
String mobileNumber = (String) dock.get( "MobileNumber" );
Be careful with the casts and make sure you are certain of the type and existence of each field. For numeric values I strongly recommend casting to a Number instead of Integer since MongoDB will re-cast values to a Long or Double at the weirdest times.
HTH, Rob.
Edit: If you are iterating over the results of a query you will have to inspect each document as it is returned from the iterator
DBCollection collec1 = database.getCollection("coll");
for( DBObject dock : collec1.find() ) {
String name = (String) dock.get( "Name" );
String address = (String) dock.get( "Address" );
String mobileNumber = (String) dock.get( "MobileNumber" );
// Do Something...
}
Do something like this to get an object from a cursor
while (cursor.hasNext())
dbObject o = cursor.next()

Categories