How to get a value from a JSON string using jackson library? - java

I am trying to get a value from a JSON string but I am getting a null value instead.
App2.java :
package JsonExample1;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
import java.io.StringReader;
public class App2 {
private JsonNode rootNode;
public void setup() throws IOException {
String jsonString = "{\n" +
" \"HotelListResponse\" : {\n" +
" \"customerSessionId\" : \"0ABAAA7A-90C9-7491-3FF2-7E2C37496CA2\",\n" +
" \"numberOfRoomsRequested\" : 1,\n" +
" \"moreResultsAvailable\" : true,\n" +
" \"cacheKey\" : \"7790c974:13ff7e2c374:6ccd\",\n" +
" \"cacheLocation\" : \"10.186.170.122:7300\",\n" +
" \"HotelList\" : {\n" +
" \"#activePropertyCount\" : \"223\",\n" +
" \"#size\" : \"1\",\n" +
" \"HotelSummary\" : {\n" +
" \"#order\" : \"0\",\n" +
" \"hotelId\" : 125727,\n" +
" \"name\" : \"Red Lion Hotel on Fifth Avenue\",\n" +
" \"address1\" : \"1415 5th Ave\",\n" +
" \"city\" : \"Seattle\",\n" +
" \"stateProvinceCode\" : \"WA\",\n" +
" \"postalCode\" : 98101,\n" +
" \"countryCode\" : \"US\",\n" +
" \"airportCode\" : \"SEA\",\n" +
" \"supplierType\" : \"E\",\n" +
" \"hotelRating\" : 3.5,\n" +
" \"propertyCategory\" : 1,\n" +
" \"confidenceRating\" : 90,\n" +
" \"amenityMask\" : 7847938,\n" +
" \"tripAdvisorRating\" : 4,\n" +
" \"locationDescription\" : \"Near Pike Place Market\",\n" +
" \"shortDescription\" : \"<p><b>Location. </b> <br />Red Lion Hotel on Fifth Avenue is located close to 5th Avenue Theater, Pike Place Market, and Washington State Convention & Trade Center. Additional points of interest\",\n" +
" \"highRate\" : 149,\n" +
" \"lowRate\" : 126.65,\n" +
" \"rateCurrencyCode\" : \"USD\",\n" +
" \"latitude\" : 47.60985,\n" +
" \"longitude\" : -122.33475,\n" +
" \"proximityDistance\" : 11.168453,\n" +
" \"proximityUnit\" : \"MI\",\n" +
" \"hotelInDestination\" : true,\n" +
" \"thumbNailUrl\" : \"/hotels/1000000/60000/51000/50947/50947_180_t.jpg\",\n" +
" \"deepLink\" : \"http://travel.ian.com/index.jsp?pageName=hotAvail&cid=55505&hotelID=125727&mode=2&numberOfRooms=1&room-0-adult-total=2&room-0-child-total=0&arrivalMonth=8&arrivalDay=4&departureMonth=8&departureDay=5&showInfo=true&locale=en_US&currencyCode=USD\",\n" +
" \"RoomRateDetailsList\" : {\n" +
" \"RoomRateDetails\" : {\n" +
" \"roomTypeCode\" : 253461,\n" +
" \"rateCode\" : 201054304,\n" +
" \"maxRoomOccupancy\" : 2,\n" +
" \"quotedRoomOccupancy\" : 2,\n" +
" \"minGuestAge\" : 0,\n" +
" \"roomDescription\" : \"Classic Single Queen\",\n" +
" \"promoId\" : 202161947,\n" +
" \"promoDescription\" : \"Summer Sale! Save 15%\",\n" +
" \"currentAllotment\" : 0,\n" +
" \"propertyAvailable\" : true,\n" +
" \"propertyRestricted\" : false,\n" +
" \"expediaPropertyId\" : 50947,\n" +
" \"rateKey\" : \"0ABAAA7A-90C9-7491-3FF2-7E2C37496CCE\",\n" +
" \"RateInfo\" : {\n" +
" \"#rateChange\" : \"false\",\n" +
" \"#promo\" : \"true\",\n" +
" \"#priceBreakdown\" : \"true\",\n" +
" \"ChargeableRateInfo\" : {\n" +
" \"#total\" : \"151.23\",\n" +
" \"#surchargeTotal\" : \"24.58\",\n" +
" \"#nightlyRateTotal\" : \"126.65\",\n" +
" \"#maxNightlyRate\" : \"126.65\",\n" +
" \"#currencyCode\" : \"USD\",\n" +
" \"#commissionableUsdTotal\" : \"126.65\",\n" +
" \"#averageRate\" : \"126.65\",\n" +
" \"#averageBaseRate\" : \"149.0\",\n" +
" \"NightlyRatesPerRoom\" : {\n" +
" \"#size\" : \"1\",\n" +
" \"NightlyRate\" : {\n" +
" \"#promo\" : \"true\",\n" +
" \"#rate\" : \"126.65\",\n" +
" \"#baseRate\" : \"149.0\"\n" +
" }\n" +
" },\n" +
" \"Surcharges\" : {\n" +
" \"#size\" : \"1\",\n" +
" \"Surcharge\" : {\n" +
" \"#amount\" : \"24.58\",\n" +
" \"#type\" : \"TaxAndServiceFee\"\n" +
" }\n" +
" }\n" +
" }\n" +
" },\n" +
" \"ValueAdds\" : {\n" +
" \"#size\" : \"1\",\n" +
" \"ValueAdd\" : {\n" +
" \"#id\" : \"2048\",\n" +
" \"description\" : \"Free Wireless Internet\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }";
rootNode = new ObjectMapper().readTree(new StringReader(jsonString));
}
//other methods
public void basicTreeModelRead()
{
//Just like DOM, our data is in a hierarchy of node (in this case, it is JsonNode)
JsonNode aField = rootNode.get("customerSessionId");
//the customerSessionId has a String value
String myString = aField.asText();
System.out.println("customerSessionId is:" + myString);
}
}
StartHere.java:
package JsonExample1;
import java.io.IOException;
public class StartHere {
public static void main(String[] args) {
App2 myApp = new App2();
try {
myApp.setup();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
myApp.basicTreeModelRead();
}
}
After debugging I found that aField value remains null.
Any ideas?

Your root node doesn't have a customerSessionId, it has a HotelListResponse. Get that first.
//other methods
public void basicTreeModelRead()
{
JsonNode innerNode = rootNode.get("HotelListResponse"); // Get the only element in the root node
// get an element in that node
JsonNode aField = innerNode.get("customerSessionId");
//the customerSessionId has a String value
String myString = aField.asText();
System.out.println("customerSessionId is:" + myString);
}
This prints
customerSessionId is:0ABAAA7A-90C9-7491-3FF2-7E2C37496CA2

Another way to get the inner element, with .at() method:
rootNode.at("/HotelListResponse/customerSessionId")

Convert to the Map
Map map = objectMapper.readValue(jsonString, Map.class);
Method for navigation in the map
private static <T> T get(Map map, Class<T> clazz, String... path) {
Map node = map;
for (int i = 0; i < path.length - 1; i++) {
node = (Map) node.get(path[i]);
}
return (T) node.get(path[path.length - 1]);
}
Usage:
String value = get(map, String.class, "path", "to", "the", "node")

Related

avoid adding the same element if exist in the list instead just add the elements inside the existing list [duplicate]

This question already has an answer here:
Add item to arraylist if it does not already exist in list
(1 answer)
Closed last year.
This post was edited and submitted for review last year and failed to reopen the post:
Original close reason(s) were not resolved
Below is the sample code
String jsonString = "{\n" +
" \"models\":[\n" +
" {\n" +
" \"model\":{\n" +
" \"code\":\"ALL\",\n" +
" \"type\":null,\n" +
" \"name\":\"ALL\",\n" +
" \"feature_types\":null\n" +
" }\n" +
" },\n" +
" {\n" +
" \"model\":{\n" +
" \"code\":\"102e\",\n" +
" \"defaultLookup\":\"false\",\n" +
" \"type\":\"SIT\",\n" +
" \"name\":\"MUSTANG\",\n" +
" \"feature_types\":[\n" +
" {\n" +
" \"feature_type\":{\n" +
" \"code\":\"A\",\n" +
" \"desc\":\"All feature types\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"feature_type\":{\n" +
" \"code\":\"B\",\n" +
" \"desc\":\"Series\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"feature_type\":{\n" +
" \"code\":\"C\",\n" +
" \"desc\":\"BodyStyle\"\n" +
" }\n" +
" }\n" +
" ]\n" +
" }\n" +
" },\n" +
" {\n" +
" \"model\":{\n" +
" \"code\":\"980p\",\n" +
" \"defaultLookup\":\"false\",\n" +
" \"type\":\"SIT\",\n" +
" \"name\":\"Ranger\",\n" +
" \"feature_types\":[\n" +
" {\n" +
" \"feature_type\":{\n" +
" \"code\":\"C\",\n" +
" \"desc\":\"All feature types\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"feature_type\":{\n" +
" \"code\":\"D\",\n" +
" \"desc\":\"Series\"\n" +
" }\n" +
" } \n" +
" ]\n" +
" }\n" +
" },\n" +
" {\n" +
" \"model\":{\n" +
" \"code\":\"kkpou\",\n" +
" \"defaultLookup\":\"false\",\n" +
" \"type\":\"UAT\",\n" +
" \"name\":\"Transit Custom\",\n" +
" \"feature_types\":[\n" +
" {\n" +
" \"feature_type\":{\n" +
" \"code\":\"F\",\n" +
" \"desc\":\"All feature types\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"feature_type\":{\n" +
" \"code\":\"G\",\n" +
" \"desc\":\"Series\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"feature_type\":{\n" +
" \"code\":\"H\",\n" +
" \"desc\":\"Payload\"\n" +
" }\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
" ]\n" +
"}";
for(int i = 0; i<myData.size();i++)
{
String type = "SIT";
FeaturedItems item = resultList.stream().filter(featureItem -> type != null && type.equals(featureItem.getType())).findFirst().orElse(null);
if (type != null) {
item = FeaturedItems.builder().type(type).items(new ArrayList<>()).build();
resultList.add(item);//if the item already exists in the list don't add the new item, instead just add the elements in the exisiting item.
//tried the below commented code to add the item if it doesn't contain in the list -- start
/*boolean flagFound = false;
for (FeaturedItems featureItem : resultList) {
if (featureItem.getType().equalsIgnoreCase(type)) {
flagFound = true;
break;
}
}
if(!flagFound) resultList.add(item);*/
//tried the above commented code to add the item if it doesn't contain in the list -- End
for (int count = 0; count < features.size(); count++) {
String id = getFid(count);
MyDataBuild build = ....//logic to set values in the properties
item.getItems().add(build);
}
}
}
lookUpData.setFeatureGroups(resultList);
}
}
If the type value is already defined in the defined featureItems, then instead of creating the new object in the featureItems list, i need to add the unique items(desc,id) to the existing items element for the matching type. The code snippet mentioned above doesn't add the elements to the existing items if the type is matching in the featureItems list, instead it is creating the new element as shown in the output json sample.
Using a Map instead will make your live much easier. However your example is missing some data so it's a bit hard to understand what is actually happening in your code. So I can give you only a simple example for the usage.
Map<String, FeaturedItems> resultMap = new HashMap<>();
// Get the FeaturedItems for the given type. If none is present create a new one.
FeaturedItems items = resultMap.computeIfAbsent(type, k -> FeaturedItems.builder().type(k).items(new ArrayList<>()).build());
// Add your item to the list
Sale newItem // Obtain new item
items.getItems().add(newItem);

How to using ObjectMapper to map value of an json property to Object when my object have an contractor set this property is null

I am usng google DirectionsResul Object
And then I want to using Object mapper to mapping this json to DirectionsResul Object
{
"geocoded_waypoints": [],
"routes": [
{
"bounds": {},
"legs": [
{
"distance": {
"human_readable": "13 km",
"in_meters": 13175
},
"duration": {
"human_readable": "37 phút",
"in_seconds": 2206
},
"steps": []
}
],
"overview_polyline": {
"points": "aaaa"
},
"warnings": [],
"waypoint_order": []
}
]
}
Using this code
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
DirectionsResult result;
result = objectMapper.readValue(json, DirectionsResult.class.);
All is ok but overview_polyline can't mapping, the points value is null
and I see in the EncodedPolyline have a contractor like this
public EncodedPolyline() {
this.points = null;
}
So how can I mapping the points value to the DirectionsResul Object
Here is my result I got
Here is all the code that can run
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.maps.model.DirectionsResult;
public void testGetDirections() throws NetworkException {
String json = "{\n" +
" \"geocoded_waypoints\": [],\n" +
" \"routes\": [\n" +
" {\n" +
" \"bounds\": {\n" +
" \"northeast\": {\n" +
" \"lat\": 34.1358593,\n" +
" \"lng\": -117.922066\n" +
" },\n" +
" \"southwest\": {\n" +
" \"lat\": 33.815582,\n" +
" \"lng\": -118.3516983\n" +
" }\n" +
" },\n" +
" \"legs\": [\n" +
" {\n" +
" \"distance\": {\n" +
" \"human_readable\": \"13 km\",\n" +
" \"in_meters\": 13175\n" +
" },\n" +
" \"duration\": {\n" +
" \"human_readable\": \"37 phút\",\n" +
" \"in_seconds\": 2206\n" +
" },\n" +
" \"steps\": [\n" +
" {\n" +
" \"distance\": {\n" +
" \"human_readable\": \"10 ft\",\n" +
" \"in_meters\": 3\n" +
" },\n" +
" \"duration\": {\n" +
" \"human_readable\": \"1 min\",\n" +
" \"in_seconds\": 0\n" +
" }\n" +
" }\n" +
" ]\n" +
" }\n" +
" ],\n" +
" \"overview_polyline\": {\n" +
" \"points\": \"{ashdasda}\"\n" +
" },\n" +
" \"warnings\": [],\n" +
" \"waypoint_order\": []\n" +
" }\n" +
" ]\n" +
"}";
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
DirectionsResult goongMapsDirectionResult;
try {
goongMapsDirectionResult = objectMapper.readValue(json, DirectionsResult.class.);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
The problem is that there is no setter for points on EncodedPolyline.
One way to work around this is to use a DeserializationProblemHandler:
public class SO69242058 {
public static void main(String args[]) throws JsonProcessingException {
String json = "{\n" +
" \"geocoded_waypoints\": [],\n" +
" \"routes\": [\n" +
" {\n" +
" \"bounds\": {\n" +
" \"northeast\": {\n" +
" \"lat\": 34.1358593,\n" +
" \"lng\": -117.922066\n" +
" },\n" +
" \"southwest\": {\n" +
" \"lat\": 33.815582,\n" +
" \"lng\": -118.3516983\n" +
" }\n" +
" },\n" +
" \"legs\": [\n" +
" {\n" +
" \"distance\": {\n" +
" \"human_readable\": \"13 km\",\n" +
" \"in_meters\": 13175\n" +
" },\n" +
" \"duration\": {\n" +
" \"human_readable\": \"37 phút\",\n" +
" \"in_seconds\": 2206\n" +
" },\n" +
" \"steps\": [\n" +
" {\n" +
" \"distance\": {\n" +
" \"human_readable\": \"10 ft\",\n" +
" \"in_meters\": 3\n" +
" },\n" +
" \"duration\": {\n" +
" \"human_readable\": \"1 min\",\n" +
" \"in_seconds\": 0\n" +
" }\n" +
" }\n" +
" ]\n" +
" }\n" +
" ],\n" +
" \"overview_polyline\": {\n" +
" \"points\": \"{ashdasda}\"\n" +
" },\n" +
" \"warnings\": [],\n" +
" \"waypoint_order\": []\n" +
" }\n" +
" ]\n" +
"}";
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
//objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.addHandler(new DeserializationProblemHandler() {
#Override
public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser p,
JsonDeserializer<?> deserializer, Object beanOrClass,
String propertyName) throws IOException {
EncodedPolyline encodedPolyline = (EncodedPolyline)beanOrClass;
try {
Field f = EncodedPolyline.class.getDeclaredField("points");
f.setAccessible(true);
f.set(encodedPolyline, p.readValueAs(String.class));
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
return true;
}
});
DirectionsResult goongMapsDirectionResult;
goongMapsDirectionResult = objectMapper.readValue(json, DirectionsResult.class);
}
}
I've removed objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) so that the error occurs when Jackson tries to set points. Then we set it reflectively.

Java - Obtain text within script tag

How to get value https://example1.com/2147414277.mp4?md5=OFvyZ55egHb4A5hUZJvSEQ&time=1580513886&ip=176.9.117.35 in this script?
the first Link value https://example.com/2147414277.mp4?md5=OFvyZ55egHb4A5hUZJvSEQ&time=1580513886 just does not work.
String html ="<script>function getcookie(Name){\n" +
" var search=Name+\"=\";\n" +
" if(document.cookie.length>0){\n" +
" offset=document.cookie.indexOf(search)\n" +
" if(offset!=-1){\n" +
" offset+=search.length\n" +
" end=document.cookie.indexOf(\";\",offset)\n" +
" if(end==-1){end=document.cookie.length}\n" +
" return unescape(document.cookie.substring(offset, en))\n" +
" }\n" +
" }\n" +
"}\n" +
" var player = new Playerjs({\n" +
" \"id\":\"player\",\n" +
" \"poster\":\"https://media.example.com/img/2147414277.jpg\",\n" +
" \"file\":\"[SD (480p)]https://example.com/2147414277.mp4?md5=OFvyZ55egHb4A5hUZJvSEQ&time=1580513886 or https://example1.com/2147414277.mp4?md5=OFvyZ55egHb4A5hUZJvSEQ&time=1580513886&ip=176.9.117.35,[HD (720р)]https://example2.com/720/2147414277.mp4?md5=GXD4cKVnM5RVY363Uxn9ww&time=1580513886 or https://exampl3.com/720/2147414277.mp4?md5=GXD4cKVnM5RVY363Uxn9ww&time=1580513886&ip=190.9.117.35\",\n" +
" \"default_quality\":\"SD (480p)\"\n" +
" });\n" +
" function PlayerjsEvents(event,id,data){\n" +
" if(event==\"start\"){\n" +
" var xhttp = new XMLHttpRequest();\n" +
" xhttp.open(\"GET\", \"stat.php?id=2147414277\", true);\n" +
" xhttp.send();\n" +
" }\n" +
" if(event==\"end\"){\n" +
" \n" +
" }\n" +
" }</script>";
Pattern p = Pattern.compile("file\"",Pattern.DOTALL);
String url = "";
for (Element element : script) {
Matcher m = p.matcher(element.data());
if (m.find()){
url = m.group(1);
}
}
System.out.println(url);
I don’t really understand how the Java Regex Pattern works. I tried to find this URL many times but I'm failed.
I would be grateful if someone will help with that or at least give me a link guide of java regex for a newbie. thx
It seems to me you are trying to extract URLs from JS code using java.
There are many regex playgrounds on the web you can try such as:
http://buildregex.com
https://regex101.com
and of course Google
Search.
For your specific case :
import java.util.*;
import java.util.regex.*;
import java.net.*;
public class HelloWorld{
public static void main(String []args){
System.out.println("Hello World");
String jsCode ="<script>function getcookie(Name){\n" +
" var search=Name+\"=\";\n" +
" if(document.cookie.length>0){\n" +
" offset=document.cookie.indexOf(search)\n" +
" if(offset!=-1){\n" +
" offset+=search.length\n" +
" end=document.cookie.indexOf(\";\",offset)\n" +
" if(end==-1){end=document.cookie.length}\n" +
" return unescape(document.cookie.substring(offset, en))\n" +
" }\n" +
" }\n" +
"}\n" +
" var player = new Playerjs({\n" +
" \"id\":\"player\",\n" +
" \"poster\":\"https://media.example.com/img/2147414277.jpg\",\n" +
" \"file\":\"[SD (480p)]https://example.com/2147414277.mp4?md5=OFvyZ55egHb4A5hUZJvSEQ&time=1580513886 or https://example1.com/2147414277.mp4?md5=OFvyZ55egHb4A5hUZJvSEQ&time=1580513886&ip=176.9.117.35,[HD (720р)]https://example2.com/720/2147414277.mp4?md5=GXD4cKVnM5RVY363Uxn9ww&time=1580513886 or https://exampl3.com/720/2147414277.mp4?md5=GXD4cKVnM5RVY363Uxn9ww&time=1580513886&ip=190.9.117.35\",\n" +
" \"default_quality\":\"SD (480p)\"\n" +
" });\n" +
" function PlayerjsEvents(event,id,data){\n" +
" if(event==\"start\"){\n" +
" var xhttp = new XMLHttpRequest();\n" +
" xhttp.open(\"GET\", \"stat.php?id=2147414277\", true);\n" +
" xhttp.send();\n" +
" }\n" +
" if(event==\"end\"){\n" +
" \n" +
" }\n" +
" }</script>";
List<String> urls = new ArrayList<String>();
String myUrlPattern = "((https?|file):((//)|(\\\\))+[\\w\\d:##%/;$()~_?\\+-=\\\\\\.&]*)";
Pattern p = Pattern.compile(myUrlPattern);
Matcher m = p.matcher(jsCode);
while (m.find()) {
urls.add(m.group());
}
for(String s: urls)
System.out.println(s);
}
}
Gives out:
https://media.example.com/img/2147414277.jpg
https://example.com/2147414277.mp4?md5=OFvyZ55egHb4A5hUZJvSEQ&time=1580513886
https://example1.com/2147414277.mp4?md5=OFvyZ55egHb4A5hUZJvSEQ&time=1580513886&ip=176.9.117.35,
https://example2.com/720/2147414277.mp4?md5=GXD4cKVnM5RVY363Uxn9ww&time=1580513886
https://exampl3.com/720/2147414277.mp4?md5=GXD4cKVnM5RVY363Uxn9ww&time=1580513886&ip=190.9.117.35
Hope this helps!

Selenium Webdriver | DragAndDrop Feature | No Exception, but code is not working

I'm trying to drag and drop and logo to an container, not getting exception. I'm able to find elements and the same drag and drop code is working fine for another site with other elements. But don't know why this is not working here. Can any one assist.
// Searching elements
driver.get(https://www.w3schools.com/html/tryit.asp?ilename=tryhtml5_draganddrop");
driver.switchTo().frame(driver.findElement(By.name("iframeResult")));
driver.manage().timeouts().implicitlyWait(10000, TimeUnit.MILLISECONDS);
WebElement From = driver.findElement(By.id("drag1"));
WebElement To = driver.findElement(By.id("div1"));
//Drag and Drop Action
Actions builder = new Actions(driver);
Action DragnDrop = builder.clickAndHold(From).moveToElement(To).release(To).build();
DragnDrop.perform();
Based on my experience to achieve more stable drag and drop actions we switched from Actions implementation to a javascript one. Yes, it might look like a hack, but constant false negatives of test result made us measure the risk and use the js impl. (We didn't create the script from scratch, just applied multiple suggestions found in the internet)
You can use it for your case, add the code below instead of Actions you used.
driver.executeScript("function dnd(elemDrag, elemDrop) {\n" +
" var DELAY_INTERVAL_MS = 100;\n" +
" var MAX_TRIES = 10;\n" +
" var dragStartEvent;\n" +
" if (!elemDrag || !elemDrop) {\n" +
" return false;\n" +
" }\n" +
" function fireMouseEvent(type, elem, dataTransfer) {\n" +
" var evt = document.createEvent('MouseEvents');\n" +
" evt.initMouseEvent(type, true, true, window, 1, 1, 1, 0, 0, false, false, false, false, 0, elem);\n" +
" if (/^dr/i.test(type)) {\n" +
" evt.dataTransfer = dataTransfer || createNewDataTransfer();\n" +
" }\n" +
" elem.dispatchEvent(evt);\n" +
" return evt;\n" +
" }\n" +
" function createNewDataTransfer() {\n" +
" var data = {};\n" +
" return {\n" +
" clearData: function (key) {\n" +
" if (key === undefined) {\n" +
" data = {};\n" +
" } else {\n" +
" delete data[key];\n" +
" }\n" +
" },\n" +
" getData: function (key) {\n" +
" return data[key];\n" +
" },\n" +
" setData: function (key, value) {\n" +
" data[key] = value;\n" +
" },\n" +
" setDragImage: function () {\n" +
" },\n" +
" dropEffect: 'none',\n" +
" files: [],\n" +
" items: [],\n" +
" types: []\n" +
" }\n" +
" }\n" +
" fireMouseEvent('mousedown', elemDrag);\n" +
" dragStartEvent = fireMouseEvent('dragstart', elemDrag);\n" +
" function dragover() {\n" +
" fireMouseEvent('dragover', elemDrop, dragStartEvent.dataTransfer);\n" +
" }\n" +
" function drop() {\n" +
" fireMouseEvent('drop', elemDrop, dragStartEvent.dataTransfer);\n" +
" fireMouseEvent('mouseup', elemDrop);\n" +
" fireMouseEvent('dragend', elemDrag);\n" +
" }\n" +
" setTimeout(dragover, DELAY_INTERVAL_MS);\n" +
" setTimeout(drop, DELAY_INTERVAL_MS * 2);\n" +
" return true;\n" +
"}\n" +
" dnd(arguments[0], arguments[1])", From, To)
Source: https://github.com/WileyLabs/teasy/blob/master/src/main/java/com/wiley/utils/JsActions.java
p.s. There is a typo in the link from your question. (instead of "asp?ilename" it should be "asp?filename)

Jsonpath to show children with dynamic names

I have this json data that I was to parse with jsonpath:
{
"kind": "tm:sys:hardware:hardwarestats",
"selfLink": "https://localhost/mgmt/tm/sys/hardware?ver\u003d11.5.4",
"entries": {
"https://localhost/mgmt/tm/sys/hardware/platform": {
"nestedStats": {
"entries": {
"https://localhost/mgmt/tm/sys/hardware/platform/0": {
"nestedStats": {
"entries": {
"baseMac": {
"description": "00:00ยง:00:00:00:00"
},
"biosRev": {
"description": "OBJ-0065-xx Build: 1.06.043.0 05/02/2014"
},
"marketingName": {
"description": "BIG-IP VPR-C2400"
},
"pvaVersion": {
"description": "20"
}
}
}
}
}
}
}
}
}
As you can see some parts consists of children named according to this:
https://[host]/path
I would like to be able to essentially ignore the host part by using a wildcard:
$.entries.https://*/mgmt/tm/sys/hardware/platform.nestedStats.entries.*.nestedStats.entries.marketingName.description
Note the wildcard replacing localhost (it differs depending on which host header is sent to the api endpoint).
I have no control over the server side. Any suggestion appreciated!
/Patrik
If you just want to get the values of those baseMac, biosRev descriptions without filtering path, this should be enough
public static void main(String[] args) {
String samplejson = "{\n" +
" \"kind\": \"tm:sys:hardware:hardwarestats\",\n" +
" \"selfLink\": \"https://localhost/mgmt/tm/sys/hardware?ver\\u003d11.5.4\",\n" +
" \"entries\": {\n" +
" \"https://localhost/mgmt/tm/sys/hardware/platform\": {\n" +
" \"nestedStats\": {\n" +
" \"entries\": {\n" +
" \"https://localhost/mgmt/tm/sys/hardware/platform/0\": {\n" +
" \"nestedStats\": {\n" +
" \"entries\": {\n" +
" \"baseMac\": {\n" +
" \"description\": \"00:00ยง:00:00:00:00\"\n" +
" },\n" +
" \"biosRev\": {\n" +
" \"description\": \"OBJ-0065-xx Build: 1.06.043.0 05/02/2014\"\n" +
" },\n" +
" \"marketingName\": {\n" +
" \"description\": \"BIG-IP VPR-C2400\"\n" +
" },\n" +
" \"pvaVersion\": {\n" +
" \"description\": \"20\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
Object baseMac = JsonPath.read(samplejson, "$.entries..nestedStats.entries.marketingName.description");
System.out.println(baseMac.toString());
}
But, if you want to read those descriptions w.r.t only certain paths, like you want to read only https://localhost/mgmt/tm/sys/hardware/platform/0 and NOT https://localhost/mgmt/tm/sys/hardware/platform/**1**, then solution should be something else.

Categories

Resources