As per ChromeDriver site, the user can use the emulators created/present in the chrome for Selenium execution.
Detailed View Here.
I wanted to display all the created/available emulators from Chrome. Chrome could be storing that details in some json file or something.If so how to access it and print it in Java
Did a Notepad++ Find in Files and found it.
The data is stored in JSON format in file
C:\Users\Your UserName\AppData\Local\Google\Chrome\User Data\Default\Preferences
Under Key
devtools>preferences>standardEmulatedDeviceList
I have used Jackson to parse the JSON
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Test {
public static void main(String[] args) {
try {
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readValue(
new File("C:\\Users\\<UserName>\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Preferences"),
Map.class);
Map devTools = (Map) map.get("devtools");
Map preferences = (Map) devTools.get("preferences");
String standardEmulatedDeviceList = (String) preferences.get("standardEmulatedDeviceList");
List emulatorMap = mapper.readValue(standardEmulatedDeviceList, List.class);
System.out.println(emulatorMap.size());
for (Object object : emulatorMap) {
Map device = (Map) object;
System.out.println(device.get("title"));
}
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Related
I'm creating a Spring application on backend and my main goal is to manage properties (add/update/delete) in *.properties file. I want to convert this file to JSON and then manipulate it from UI application.
Is there any possibility to convert structure like this:
a.x=1
a.y=2
b.z=3
To JSON like this:
{
"a": {
"x": 1,
"y": 2
},
"b": {
"z": 3
}
}
I found solution to use GSON library, but it creates for me flat structure, not hierarchical, code I used:
Properties props = new Properties();
try (FileInputStream in = new FileInputStream(classPathResource.getFile())) {
props.load(in);
}
String json = new GsonBuilder().enableComplexMapKeySerialization().create().toJson(props);
Is here someone who was facing same problem and maybe found a working project for this? Maybe GSON library can do that?
This solution does involve loads of work, but you will get what you want to achieve using the below code, basically, the idea is to split the key based on the single dot and then create a JsonObject if the same first key is found.
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Properties;
import org.json.JSONObject;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class SOTest {
public static void main(String[] args) throws IOException {
JSONObject jsonObject = new JSONObject();
FileReader fileReader = new FileReader(new File("C:\\Usrc\\main\\java\\Sample.properties"));
Properties properties = new Properties();
properties.load(fileReader);
Iterator<Entry<Object, Object>> iterator = properties.entrySet().iterator();
while (iterator.hasNext()) {
Entry<Object, Object> entry = iterator.next();
String value = (String) entry.getKey();
String[] values = value.split("\\.");
JSONObject opt = jsonObject.optJSONObject(values[0]);
if(opt!=null) {
opt.put(values[1],entry.getValue());
}else {
JSONObject object = new JSONObject();
object.put(values[1], entry.getValue());
jsonObject.put(values[0], object);
}
}
System.out.println(jsonObject.toString());
}
}
Output
{"a":{"x":"1","y":"3"},"b":{"z":"10"}}
I am trying to retrieve Map content via WFS Geoserver connection in Java with Geotools 18.4. But I am getting the following error: Content type is required for org.geotools.data.ows.Response.
The idea is that i want to map features (Position and Heartrate of a running person) of a WFS Layer with the java processing library.
I would be very grateful if someone can help me with this error.
here is the code:
`
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.geotools.data.DataStore;
import org.geotools.data.wfs.WFSDataStoreFactory;
public class Heartrate2 {
public static void main(String[] args) throws IOException {
Heartrate2 me = new Heartrate2();
DataStore ds = me.dataStoreWFS();
for (String n:ds.getTypeNames()) {
System.out.println(n);
}
}
public DataStore dataStoreWFS() {
DataStore dataStore = null;
try {
Map<String, Serializable> connectionParameters = new HashMap<>();
String getCapabilities = "http://webgis.regione.sardegna.it/geoserver/ows?service=WFS&request=GetCapabilities";
String variableCapabilities = "WFSDataStoreFactory:GET_CAPABILITIES_URL";
connectionParameters.put(variableCapabilities, getCapabilities);
dataStore = (new WFSDataStoreFactory()).createDataStore(connectionParameters);
} catch (IOException e) {
e.printStackTrace();
}
return dataStore;
}
}
`
I am trying to use GeoTools in order to load a shapefile into java and then check whether a point is located within one of the polygons in the shape file
The problem is that i am not able to load the shapefile and therefore to continue forward.
Here is my code so far:
public static void main(String[] args){
// create sample coordinate
double lon = -105.0;
double lat = 40.0;
GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(PrecisionModel.maximumPreciseValue),8307);
Geometry point = geometryFactory.createPoint(new Coordinate(lon,lat));
//
String path = System.getProperty("user.dir") + "/continent_shp/continent_shp.shp";
File file = new File(path);
try {
Map<String, Serializable> connectParameters = new HashMap<String, Serializable>();
// load shapefile ---- does not work !!!!!!!!
connectParameters.put("url", file.toURI().toURL());
connectParameters.put("create spatial index", true);
DataStore dataStore = DataStoreFinder.getDataStore(connectParameters);
//
FeatureSource featureSource = dataStore.getFeatureSource("POLYGON");
FeatureCollection collection = (FeatureCollection) featureSource.getFeatures();
FeatureIterator iterator = collection.features();
while (iterator.hasNext()) {
Feature feature = iterator.next();
Geometry sourceGeometry = feature.getDefaultGeometry();
boolean isContained = sourceGeometry.contains(point);
System.out.println(isContained);
}
}
catch (MalformedURLException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
}
The problem is that the dataStore variable is null after I try to load the shapefile.
Here are my imports:
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.FeatureSource;
import org.geotools.feature.Feature;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.PrecisionModel;
Can anyone shed some light on this issue?
Any help would be appreciated.
Thank you.
The most likely problem is that you don't have a Shapefile Datastore implementation available on your path. Try the following method to check what stores are available:
public Map<String, DataStoreFactorySpi> fetchAvailableDataStores() {
Iterator<DataStoreFactorySpi> it = DataStoreFinder.getAllDataStores();
while (it.hasNext()) {
DataStoreFactorySpi fac = it.next();
System.out.println(fac.getDisplayName());
}
}
Another thing that can go wrong is the File to URL conversion, especially if there are spaces in the filename or path. Try using DataUtilities.fileToURL(file) instead.
This worked for me:
// load shapefile ---- does not work !!!!!!!!
connectParameters.put("url", file.toURI().toURL());
connectParameters.put("create spatial index", Boolean.TRUE);
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
ShapefileDataStore store = (ShapefileDataStore) dataStoreFactory.createNewDataStore(connectParameters);
//
I have this code and I tried to getting items from this JSON string but it failed.
I'm parsing the Json string from remote host.
package selectDB;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import org.json.simple.*;
public class selectDB
{
public static void main(String[] args) throws IOException, ParseException
{
String s = "";
URL u = new URL("http://192.168.3.1/android/select.php");
URLConnection c = u.openConnection();
InputStream r = c.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(r));
for(String line; (line = reader.readLine()) != null;)
{
s+=line;
}
System.out.println(s);
}
}
the result is
{"result" : "true" , "messages" : [{"id":"866343023633578","latitute":"27","longitude":"31","number_phone":"01113171374"},{"id":"352168066354050","latitute":"27","longitude":"31","number_phone":"202222"},{"id":"50","latitute":"50","longitude":"100","number_phone":"50"},{"id":"110","latitute":"50","longitude":"50","number_phone":"110"},{"id":"120","latitute":"27","longitude":"31","number_phone":"120"},{"id":"130","latitute":"28","longitude":"29","number_phone":"120"},{"id":"140","latitute":"30","longitude":"40","number_phone":"140"},{"id":"800","latitute":"60","longitude":"30","number_phone":"800"},{"id":"353629054230064","latitute":"70","longitude":"80","number_phone":"120"}]}
Please help!
U can use the JsonReader class.
try (JsonReader in = Json.createReader(r)) {
JsonObject jsonObject= in.readObject();
YourObject obj = new YourObject();
obj.setSomething(jsonObject.getString("something", null));
// "something" is the key in the json file, null is the default
// when "something" was not found
} catch (JsonException | ClassCastException ex) {
throw new BadRequestException("Invalid Json Input");
}
you can use the Google Library GSON as well, it is easy to use and self explaining.
https://code.google.com/p/google-gson/
Gson Goals
Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
Allow pre-existing unmodifiable objects to be converted to and from JSON
Extensive support of Java Generics
Allow custom representations for objects
Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)
I have a json file that looks like
[{"field1":Value1,
"field2":value2,
"field3_find":[value3,value4],
"field4_find":{"sub1":subval1,"sub2":subvalue2}
}
{"field1":Value5,
"field2":value6,
"field3_find":[value7,value8],
"field4_find":{"sub1":subval3,"sub2":subvalue3}
}
]
I want to read the Json. Find a particular key value pair. Once a matching field is found , create a new field depending on the value of this field. Write back Json.
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.io.FileReader;
JSONParser parser = new JSONParser();
ArrayList<LinkedHashMap< String, JSONObject>> AllRows;
AllRows = (JSONArray) parser.parse(new FileReader(InputFile));
JSONArray New_rows =new JSONArray();
LinkedList<String> FieldNameAnotation=new LinkedList<String>();
FieldNameAnotation.add(new String("field3_find"));
FieldNameAnotation.add(new String("field4_find"));
try {
for(LinkedHashMap<String,JSONObject> map : AllRows){
JSONObject extend_row=new JSONObject();
for (Map.Entry<String, JSONObject> entry : map.entrySet()) {
if ((FieldNameAnotation).contains(entry.getKey()))
{
newvalue1=process1(entry.getKey());
newvalue2=process2(entry.getKey());// call a function process to get this value
extend_row.put(newvalue1,newvalue2);
}
}
extend_row.putAll(map);
New_rows.add(extend_row);
}
}catch (Exception e) {
System.err.println(e);
System.exit(0);
}
However this gives an error
org.json.simple.JSONObject cannot be cast to java.util.LinkedHashMap.
I know that it is because the way I have read the JSON .It is read as an array of JSON objects, But I do not how to read it as
ArrayList<LinkedHashMap< String, JSONObject>>