Run Selenium automation tests on LambdaTest cloud grid
Perform automation testing on 3000+ real desktop and mobile devices online.
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.openqa.grid.web.servlet;
import static org.openqa.selenium.json.Json.MAP_TYPE;
import com.google.common.collect.ImmutableMap;
import org.openqa.grid.common.exception.GridException;
import org.openqa.grid.internal.ExternalSessionKey;
import org.openqa.grid.internal.GridRegistry;
import org.openqa.grid.internal.RemoteProxy;
import org.openqa.grid.internal.TestSession;
import org.openqa.selenium.json.Json;
import org.openqa.selenium.json.JsonException;
import org.openqa.selenium.json.JsonInput;
import org.openqa.selenium.json.JsonOutput;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestSessionStatusServlet extends RegistryBasedServlet {
private final Json json = new Json();
public TestSessionStatusServlet() {
super(null);
}
public TestSessionStatusServlet(GridRegistry registry) {
super(registry);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
Map<String, Object> json = ImmutableMap.of(
"session", request.getParameter("session"));
process(response, json);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
Map<String, Object> requestJSON = new HashMap<>();
if (request.getInputStream() != null) {
try (Reader rd = new BufferedReader(new InputStreamReader(request.getInputStream()));
JsonInput jin = json.newInput(rd)) {
requestJSON = jin.read(MAP_TYPE);
}
}
process(response, requestJSON);
}
protected void process(HttpServletResponse response, Map<String, Object> requestJson)
throws IOException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setStatus(200);
try (Writer writer = response.getWriter();
JsonOutput out = json.newOutput(writer)) {
out.write(getResponse(requestJson));
} catch (JsonException e) {
throw new GridException(e.getMessage());
}
}
private Map<String, Object> getResponse(Map<String, Object> requestJson) {
Map<String, Object> res = new TreeMap<>();
res.put("success", false);
// the id can be specified via a param, or in the json request.
String session;
if (!requestJson.containsKey("session")) {
res.put(
"msg",
"you need to specify at least a session or internalKey when call the test slot status service.");
return res;
}
session = String.valueOf(requestJson.get("session"));
TestSession testSession = getRegistry().getSession(ExternalSessionKey.fromString(session));
if (testSession == null) {
res.put("msg", "Cannot find test slot running session " + session + " in the registry.");
return res;
}
res.put("msg", "slot found !");
res.remove("success");
res.put("success", true);
res.put("session", testSession.getExternalKey().getKey());
res.put("internalKey", testSession.getInternalKey());
res.put("inactivityTime", testSession.getInactivityTime());
RemoteProxy p = testSession.getSlot().getProxy();
res.put("proxyId", p.getId());
return res;
}
}
EvalClassName[] evalClassName;
ArrayList<EvalClassName> list;
evalClassName= new Gson().fromJson(JSONArrayValue.toString(),EvalClassName[].class);
list = new ArrayList<>(Arrays.asList(evalClassName));
val jsonArrayString = "['A','B','C']"
val gson = Gson()
val listType: Type = object : TypeToken<List<String?>?>() {}.getType()
val stringList : List<String> = gson.fromJson(
jsonArrayString,
listType)
[
{
id : '1',
title: 'sample title',
....
},
{
id : '2',
title: 'sample title',
....
},
...
]
Gson gson=new GsonBuilder().create();
List<Post> list= Arrays.asList(gson.fromJson(yourResponse.toString,Post[].class));
val fileData = "your_json_string"
val gson = GsonBuilder().create()
val packagesArray = gson.fromJson(fileData , Array<YourClass>::class.java).toList()
/**
* Convert JSON string to a list of objects
* @param sJson String sJson to be converted
* @param tClass Class
* @return List<T> list of objects generated or null if there was an error
*/
public static <T> List<T> convertFromJsonArray(String sJson, Class<T> tClass){
try{
Gson gson = new Gson();
List<T> listObjects = new ArrayList<>();
//read each object of array with Json library
JSONArray jsonArray = new JSONArray(sJson);
for(int i=0; i<jsonArray.length(); i++){
//get the object
JSONObject jsonObject = jsonArray.getJSONObject(i);
//get string of object from Json library to convert it to real object with Gson library
listObjects.add(gson.fromJson(jsonObject.toString(), tClass));
}
//return list with all generated objects
return listObjects;
}catch(Exception e){
e.printStackTrace();
}
//error: return null
return null;
}
Type listType = new TypeToken<List<Post>>() {}.getType();
List<Post> posts = new Gson().fromJson(jsonOutput.toString(), listType);
Gson gson=new Gson();
ElementType [] refVar=gson.fromJson(jsonString,ElementType[].class);
Gson gson=new Gson();
Post [] refVar=gson.fromJson(jsonString,Post[].class);
List<Post> posts=(List<Post>)gson.fromJson(jsonString,
new TypeToken<List<Post>>(){}.getType());
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
public class CollectionDeserializer implements JsonDeserializer<Collection<?>> {
@Override
public Collection<?> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
Type realType = ((ParameterizedType)typeOfT).getActualTypeArguments()[0];
return parseAsArrayList(json, realType);
}
/**
* @param serializedData
* @param type
* @return
*/
@SuppressWarnings("unchecked")
public <T> ArrayList<T> parseAsArrayList(JsonElement json, T type) {
ArrayList<T> newArray = new ArrayList<T>();
Gson gson = new Gson();
JsonArray array= json.getAsJsonArray();
Iterator<JsonElement> iterator = array.iterator();
while(iterator.hasNext()){
JsonElement json2 = (JsonElement)iterator.next();
T object = (T) gson.fromJson(json2, (Class<?>)type);
newArray.add(object);
}
return newArray;
}
}
public class JSONParsingTest {
List<World> worlds;
@Test
public void grantThatDeserializerWorksAndParseObjectArrays(){
String worldAsString = "{\"worlds\": [" +
"{\"name\":\"name1\",\"id\":1}," +
"{\"name\":\"name2\",\"id\":2}," +
"{\"name\":\"name3\",\"id\":3}" +
"]}";
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Collection.class, new CollectionDeserializer());
Gson gson = builder.create();
Object decoded = gson.fromJson((String)worldAsString, JSONParsingTest.class);
assertNotNull(decoded);
assertTrue(JSONParsingTest.class.isInstance(decoded));
JSONParsingTest decodedObject = (JSONParsingTest)decoded;
assertEquals(3, decodedObject.worlds.size());
assertEquals((Long)2L, decodedObject.worlds.get(1).getId());
}
}
public class World {
private String name;
private Long id;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
Gson gson = new Gson();
String jsonOutput = "Your JSON String";
Type listType = new TypeToken<List<Post>>(){}.getType();
List<Post> posts = gson.fromJson(jsonOutput, listType);
EvalClassName[] evalClassName;
ArrayList<EvalClassName> list;
evalClassName= new Gson().fromJson(JSONArrayValue.toString(),EvalClassName[].class);
list = new ArrayList<>(Arrays.asList(evalClassName));
val jsonArrayString = "['A','B','C']"
val gson = Gson()
val listType: Type = object : TypeToken<List<String?>?>() {}.getType()
val stringList : List<String> = gson.fromJson(
jsonArrayString,
listType)
[
{
id : '1',
title: 'sample title',
....
},
{
id : '2',
title: 'sample title',
....
},
...
]
Gson gson=new GsonBuilder().create();
List<Post> list= Arrays.asList(gson.fromJson(yourResponse.toString,Post[].class));
val fileData = "your_json_string"
val gson = GsonBuilder().create()
val packagesArray = gson.fromJson(fileData , Array<YourClass>::class.java).toList()
/**
* Convert JSON string to a list of objects
* @param sJson String sJson to be converted
* @param tClass Class
* @return List<T> list of objects generated or null if there was an error
*/
public static <T> List<T> convertFromJsonArray(String sJson, Class<T> tClass){
try{
Gson gson = new Gson();
List<T> listObjects = new ArrayList<>();
//read each object of array with Json library
JSONArray jsonArray = new JSONArray(sJson);
for(int i=0; i<jsonArray.length(); i++){
//get the object
JSONObject jsonObject = jsonArray.getJSONObject(i);
//get string of object from Json library to convert it to real object with Gson library
listObjects.add(gson.fromJson(jsonObject.toString(), tClass));
}
//return list with all generated objects
return listObjects;
}catch(Exception e){
e.printStackTrace();
}
//error: return null
return null;
}
Type listType = new TypeToken<List<Post>>() {}.getType();
List<Post> posts = new Gson().fromJson(jsonOutput.toString(), listType);
Gson gson=new Gson();
ElementType [] refVar=gson.fromJson(jsonString,ElementType[].class);
Gson gson=new Gson();
Post [] refVar=gson.fromJson(jsonString,Post[].class);
List<Post> posts=(List<Post>)gson.fromJson(jsonString,
new TypeToken<List<Post>>(){}.getType());
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
public class CollectionDeserializer implements JsonDeserializer<Collection<?>> {
@Override
public Collection<?> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
Type realType = ((ParameterizedType)typeOfT).getActualTypeArguments()[0];
return parseAsArrayList(json, realType);
}
/**
* @param serializedData
* @param type
* @return
*/
@SuppressWarnings("unchecked")
public <T> ArrayList<T> parseAsArrayList(JsonElement json, T type) {
ArrayList<T> newArray = new ArrayList<T>();
Gson gson = new Gson();
JsonArray array= json.getAsJsonArray();
Iterator<JsonElement> iterator = array.iterator();
while(iterator.hasNext()){
JsonElement json2 = (JsonElement)iterator.next();
T object = (T) gson.fromJson(json2, (Class<?>)type);
newArray.add(object);
}
return newArray;
}
}
public class JSONParsingTest {
List<World> worlds;
@Test
public void grantThatDeserializerWorksAndParseObjectArrays(){
String worldAsString = "{\"worlds\": [" +
"{\"name\":\"name1\",\"id\":1}," +
"{\"name\":\"name2\",\"id\":2}," +
"{\"name\":\"name3\",\"id\":3}" +
"]}";
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Collection.class, new CollectionDeserializer());
Gson gson = builder.create();
Object decoded = gson.fromJson((String)worldAsString, JSONParsingTest.class);
assertNotNull(decoded);
assertTrue(JSONParsingTest.class.isInstance(decoded));
JSONParsingTest decodedObject = (JSONParsingTest)decoded;
assertEquals(3, decodedObject.worlds.size());
assertEquals((Long)2L, decodedObject.worlds.get(1).getId());
}
}
public class World {
private String name;
private Long id;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
Gson gson = new Gson();
String jsonOutput = "Your JSON String";
Type listType = new TypeToken<List<Post>>(){}.getType();
List<Post> posts = gson.fromJson(jsonOutput, listType);
objectMapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
// Pretty-print the JSON result
try {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> response = objectMapper.readValue(result, HashMap.class);
System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(response));
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
<bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
<property name="lenient" value="false" />
</bean>
</property>
<property name="serializationInclusion">
<value type="com.fasterxml.jackson.annotation.JsonInclude.Include">
NON_NULL
</value>
</property>
</bean>
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject">
<ref bean="objectMapper" />
</property>
<property name="targetMethod">
<value>enable</value>
</property>
<property name="arguments">
<value type="com.fasterxml.jackson.databind.SerializationFeature">
INDENT_OUTPUT
</value>
</property>
</bean>
val indentOutput = SerializationFeature.INDENT_OUTPUT
val defaultStateField = indentOutput.getClass.getDeclaredField("_defaultState")
defaultStateField.setAccessible(true)
defaultStateField.set(indentOutput, true)
public static void main(String[] args) throws IOException {
byte[] jsonBytes = Files.readAllBytes(Paths.get("C:\\data\\testfiles\\single-line.json"));
ObjectMapper objectMapper = new ObjectMapper();
Object json = objectMapper.readValue( jsonBytes, Object.class );
System.out.println( objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString( json ) );
}
new ObjectMapper()
.writer()
.withDefaultPrettyPrinter()
.writeValueAsString(new HashMap<String, Object>());
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonInstance));
System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(jsonInstance));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
Accelerate Your Automation Test Cycles With LambdaTest
Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.