List of usage examples for com.google.gson JsonArray iterator
public Iterator<JsonElement> iterator()
From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.DsAPIImpl.java
License:Open Source License
@Override public HashMap<Integer, BaseSensorValues> getApartmentSensorValues(String sessionToken) { String response = transport.execute(SimpleRequestBuilder.buildNewJsonRequest(ClassKeys.APARTMENT) .addFunction(FunctionKeys.GET_SENSOR_VALUES).addParameter(ParameterKeys.TOKEN, sessionToken) .buildRequestString());/*from w w w . jav a2 s. co m*/ JsonObject responseObj = JSONResponseHandler.toJsonObject(response); if (JSONResponseHandler.checkResponse(responseObj)) { JsonObject obj = JSONResponseHandler.getResultJsonObject(responseObj); if (obj.get(JSONApiResponseKeysEnum.ZONES.getKey()).isJsonArray()) { JsonArray jArray = obj.get(JSONApiResponseKeysEnum.ZONES.getKey()).getAsJsonArray(); WeatherSensorData weather = new WeatherSensorData(obj); if (jArray.size() != 0) { HashMap<Integer, BaseSensorValues> map = new HashMap<Integer, BaseSensorValues>( jArray.size() + 1); Iterator<JsonElement> iter = jArray.iterator(); while (iter.hasNext()) { SensorValues sensorValues = new SensorValues(iter.next().getAsJsonObject()); map.put(sensorValues.getZoneID(), sensorValues); } map.put(GeneralLibConstance.BROADCAST_ZONE_GROUP_ID, weather); return map; } } } return null; }
From source file:org.eiichiro.bootleg.json.JSONRequest.java
License:Open Source License
@SuppressWarnings("unchecked") private Object body(Type type, String name, final JsonElement element) { Function<String, Object> value = new Function<String, Object>() { public Object apply(String name) { if (element instanceof JsonObject) { JsonObject jsonObject = (JsonObject) element; return jsonObject.get(name); } else { return null; }/*from w w w .ja va 2s. c om*/ } }; Function<String, Collection<Object>> values = new Function<String, Collection<Object>>() { public Collection<Object> apply(String name) { if (element instanceof JsonObject) { JsonObject jsonObject = (JsonObject) element; JsonElement jsonElement = jsonObject.get(name); if (jsonElement != null && jsonElement.isJsonArray()) { Collection<Object> collection = new ArrayList<Object>(); Iterator<JsonElement> iterator = jsonElement.getAsJsonArray().iterator(); while (iterator.hasNext()) { collection.add(iterator.next()); } return (collection.isEmpty()) ? null : collection; } else { logger.warn("Element [" + name + "] is not a JSON array"); return null; } } else if ((name == null || name.isEmpty()) && element instanceof JsonArray) { JsonArray array = (JsonArray) element; Collection<Object> collection = new ArrayList<Object>(); Iterator<JsonElement> iterator = array.iterator(); while (iterator.hasNext()) { collection.add(iterator.next()); } return (collection.isEmpty()) ? null : collection; } else { return null; } } }; if (name != null && !name.isEmpty()) { if (Types.isCollection(type)) { if (Types.isSupportedCollection(type)) { Class<?> elementType = Types.getElementType(type); if (!Types.isCoreValueType(elementType) && !Types.isUserDefinedValueType(elementType)) { // Named collection of user-defined object type. Collection<Object> jsonElements = values.apply(name); if (jsonElements == null) { logger.debug("Collection named [" + name + "] not found"); return jsonElements; } try { Class<?> implementationType = Types.getDefaultImplementationType(type); Collection<Object> collection = (Collection<Object>) implementationType.newInstance(); try { for (Object jsonElement : jsonElements) { Object instance = elementType.newInstance(); for (Field field : elementType.getDeclaredFields()) { Object object = body(field.getGenericType(), field.getName(), (JsonElement) jsonElement); if (object != null) { field.setAccessible(true); field.set(instance, object); } } collection.add(instance); } return (collection.isEmpty()) ? null : collection; } catch (Exception e) { logger.warn("Cannot instantiate [" + elementType + "] (Collection element type of [" + type + "])", e); } } catch (Exception e) { logger.debug("Cannot instantiate [" + Types.getDefaultImplementationType(type) + "] (Default implementation type of [" + type + "])", e); } return null; } } } else if (!Types.isCoreValueType(type) && !Types.isUserDefinedValueType(type)) { // Named user-defined object type. Class<?> rawType = Types.getRawType(type); Object jsonElement = value.apply(name); try { Object instance = rawType.newInstance(); for (Field field : rawType.getDeclaredFields()) { Object object = body(field.getGenericType(), field.getName(), (JsonElement) jsonElement); if (object != null) { field.setAccessible(true); field.set(instance, object); } } return instance; } catch (Exception e) { logger.warn("Cannot instantiate [" + type + "]", e); } return null; } } else { if (Types.isCollection(type)) { if (Types.isSupportedCollection(type)) { Collection<Object> objects = values.apply(name); if (objects == null) { logger.debug("Posted JSON element is not a JSON array"); return objects; } try { Class<?> implementationType = Types.getDefaultImplementationType(type); Collection<Object> collection = (Collection<Object>) implementationType.newInstance(); Class<?> elementType = Types.getElementType(type); boolean coreValueType = Types.isCoreValueType(elementType); try { if (coreValueType || Types.isUserDefinedValueType(elementType)) { // No-named collection of core value type. // No-named collection of user-defined value type. for (Object object : objects) { Object convert = (coreValueType) ? convert(object, elementType) : convertUserDefinedValueType(object, elementType); if (convert != null && ClassUtils.primitiveToWrapper(elementType) .isAssignableFrom(convert.getClass())) { collection.add(convert); } else { logger.debug("Parameter [" + convert + "] cannot be converted to [" + elementType + "]"); } } } else { // No-named collection of user-defined object type. for (Object jsonElement : objects) { Object instance = elementType.newInstance(); for (Field field : elementType.getDeclaredFields()) { Object object = body(field.getGenericType(), field.getName(), (JsonElement) jsonElement); if (object != null) { field.setAccessible(true); field.set(instance, object); } } collection.add(instance); } } return (collection.isEmpty()) ? null : collection; } catch (Exception e) { logger.warn("Cannot instantiate [" + elementType + "] (Collection element type of [" + type + "])", e); } } catch (Exception e) { logger.debug("Cannot instantiate [" + Types.getDefaultImplementationType(type) + "] (Default implementation type of [" + type + "])", e); } } return null; } } return parameter(type, name, value, values); }
From source file:org.emoncms.com.http.json.FromJson.java
License:Open Source License
public LinkedList<Double[]> getDoubleArrayList() { LinkedList<Double[]> resultList = new LinkedList<Double[]>(); if (!jse.isJsonNull() && jse.isJsonArray()) { JsonArray jsa = jse.getAsJsonArray(); Iterator<JsonElement> iteratorJsonArray = jsa.iterator(); while (iteratorJsonArray.hasNext()) { resultList.add(gson.fromJson(iteratorJsonArray.next(), Double[].class)); }/*ww w . j a v a 2 s.c om*/ } if (resultList.size() == 0) { resultList = null; } return resultList; }
From source file:org.faul.jql.utils.RemoteObjectHandler.java
License:Open Source License
Object getList(JsonArray array) { List list = new ArrayList(); Iterator it = array.iterator(); Object target = null;//from ww w . j av a 2 s . c o m while (it.hasNext()) { Object obj = it.next(); if (obj instanceof JsonArray) { target = getList((JsonArray) obj); } if (obj instanceof JsonPrimitive) { target = getPrimitive((JsonPrimitive) obj); } if (obj instanceof JsonObject) { Map map = new HashMap(); mapHandler(map, (JsonObject) obj); target = map; } list.add(target); target = null; } return list; }
From source file:org.fracturedatlas.athena.web.serialization.JsonTicketSerializer.java
License:Open Source License
public PTicket deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try {// www .j a v a 2 s. c o m PTicket pTicket = new PTicket(); JsonObject ticketObj = json.getAsJsonObject(); pTicket.setId(JsonUtil.nullSafeGetAsString(ticketObj.get("id"))); ticketObj.remove("id"); for (Entry<String, JsonElement> entry : ticketObj.entrySet()) { JsonElement val = entry.getValue(); if (val.isJsonArray()) { JsonArray jsonArray = val.getAsJsonArray(); Iterator<JsonElement> iter = jsonArray.iterator(); while (iter.hasNext()) { pTicket.getProps().add(entry.getKey(), iter.next().getAsString()); } } else if (val.isJsonNull()) { pTicket.put(entry.getKey(), null); } else { pTicket.put(entry.getKey(), val.getAsString()); } } return pTicket; } catch (JsonParseException jpe) { jpe.printStackTrace(); throw jpe; } }
From source file:org.hibernate.search.backend.elasticsearch.impl.ToElasticsearch.java
License:LGPL
private static JsonObject convertBooleanQuery(BooleanQuery booleanQuery) { JsonArray musts = new JsonArray(); JsonArray shoulds = new JsonArray(); JsonArray mustNots = new JsonArray(); JsonArray filters = new JsonArray(); for (BooleanClause clause : booleanQuery.clauses()) { switch (clause.getOccur()) { case MUST: musts.add(fromLuceneQuery(clause.getQuery())); break; case FILTER: filters.add(fromLuceneQuery(clause.getQuery())); break; case MUST_NOT: mustNots.add(fromLuceneQuery(clause.getQuery())); break; case SHOULD: shoulds.add(fromLuceneQuery(clause.getQuery())); break; }// ww w. jav a 2 s . c om } JsonObject clauses = new JsonObject(); if (musts.size() > 1) { clauses.add("must", musts); } else if (musts.size() == 1) { clauses.add("must", musts.iterator().next()); } if (shoulds.size() > 1) { clauses.add("should", shoulds); } else if (shoulds.size() == 1) { clauses.add("should", shoulds.iterator().next()); } if (mustNots.size() > 1) { clauses.add("must_not", mustNots); } else if (mustNots.size() == 1) { clauses.add("must_not", mustNots.iterator().next()); } if (filters.size() > 1) { clauses.add("filter", filters); } else if (filters.size() == 1) { clauses.add("filter", filters.iterator().next()); } JsonObject bool = new JsonObject(); bool.add("bool", clauses); return bool; }
From source file:org.hillview.storage.JsonFileLoader.java
License:Open Source License
public ITable load() { Schema schema = null;/*from ww w .j a v a 2s . c o m*/ if (this.schemaPath != null) schema = Schema.readFromJsonFile(Paths.get(this.schemaPath)); Reader file = this.getFileReader(); JsonReader jReader = new JsonReader(file); JsonElement elem = Streams.parse(jReader); if (!elem.isJsonArray()) throw new RuntimeException("Expected a JSON array in " + filename); JsonArray array = elem.getAsJsonArray(); if (array.size() == 0 && schema == null) throw new RuntimeException("Empty JSON array in " + filename); if (schema == null) schema = this.guessSchema(filename, array.iterator()); IAppendableColumn[] columns = schema.createAppendableColumns(); this.currentRow = 0; for (JsonElement e : array) this.append(columns, e); this.close(file); return new Table(columns, this.filename, null); }
From source file:org.indigo.heapsterprobe.HeapsterClient.java
License:Apache License
/** * This method access the Heapster REST API in order to obtain the list of pods * available in the Kubernetes cluster.//w w w . ja v a 2s . c om * @return List of pod identifiers */ public String[] getPodsList() { // Call to Heapster API WebTarget target = client.target(baseHeapsterUrl + "/model/namespaces/"); Invocation.Builder invocationBuilder = target.request(); Response response = invocationBuilder.get(); String message = response.readEntity(String.class); if (response.getStatus() > 300) { System.out.println("Heapster service did not respond as expected: " + response.getStatus()); return null; } // Retrieve the namespaces list JsonElement jelement = new JsonParser().parse(message); JsonArray listArray = jelement.getAsJsonArray(); System.out.println("Number of namespaces: " + listArray.size()); ArrayList<String> namespacesList = new ArrayList<String>(); Iterator<JsonElement> myIter = listArray.iterator(); while (myIter.hasNext()) { String currentResource = myIter.next().getAsString(); System.out.println("Namespace: " + currentResource); if (!currentResource.equalsIgnoreCase("default")) { namespacesList.add(currentResource); } } // Retrieve the pods per 'not default' namespace ArrayList<String> podsList = new ArrayList<String>(); for (int i = 0; i < namespacesList.size(); i++) { // Perform the request String namespaceName = namespacesList.get(i); target = client.target(baseHeapsterUrl + "/model/namespaces/" + namespaceName + "/pods/"); invocationBuilder = target.request(); response = invocationBuilder.get(); message = response.readEntity(String.class); // Parse the result jelement = new JsonParser().parse(message); listArray = jelement.getAsJsonArray(); System.out.println("Number of pods: " + listArray.size()); myIter = listArray.iterator(); while (myIter.hasNext()) { String currentPod = myIter.next().getAsString(); podsList.add(namespaceName + "/" + currentPod); System.out.println("Pod: " + currentPod); } } // Provide result podsList.trimToSize(); String[] resultList = new String[podsList.size()]; podsList.toArray(resultList); return resultList; }
From source file:org.indigo.heapsterprobe.HeapsterClient.java
License:Apache License
/** * Given a namespace and a pod name, this method access the Heapster API * in order to list the containers which belong to the pod. * @param podName String with the pod name * @param namespace String indicating the pod namespace * @return List of identifiers of the containers *//*from w w w . ja v a 2 s . co m*/ public String[] getContainersList(String podName, String namespace) { // Call to Heapster API String targetUrl = baseHeapsterUrl + "/model/namespaces/" + namespace + "/pods/" + podName + "/containers/"; WebTarget target = client.target(targetUrl); Invocation.Builder invocationBuilder = target.request(); Response response = invocationBuilder.get(); String message = response.readEntity(String.class); if (response.getStatus() > 300) { System.out.println("Heapster service did not respond as expected: " + response.getStatus()); return null; } // Retrieve the containers list JsonElement jelement = new JsonParser().parse(message); JsonArray listArray = jelement.getAsJsonArray(); System.out.println("Number of containers: " + listArray.size()); ArrayList<String> containersList = new ArrayList<String>(); Iterator<JsonElement> myIter = listArray.iterator(); while (myIter.hasNext()) { String currentResource = myIter.next().getAsString(); System.out.println("Container: " + currentResource); containersList.add(currentResource); } // Provide result containersList.trimToSize(); String[] resultList = new String[containersList.size()]; containersList.toArray(resultList); return resultList; }
From source file:org.indigo.heapsterprobe.HeapsterClient.java
License:Apache License
/** * This method access the Heapster REST API in order to list the physical * nodes which are part of the Kubernetes cluster. * @return List of nodes identifiers./*from w ww .ja v a 2 s .c o m*/ */ public String[] getNodesList() { // Call to Heapster API WebTarget target = client.target(baseHeapsterUrl + "/model/nodes/"); Invocation.Builder invocationBuilder = target.request(); Response response = invocationBuilder.get(); String message = response.readEntity(String.class); // Retrieve the nodes JsonElement jelement = new JsonParser().parse(message); JsonArray listArray = jelement.getAsJsonArray(); System.out.println("Number of nodes: " + listArray.size()); String[] resultList = new String[listArray.size()]; int pointer = 0; Iterator<JsonElement> myIter = listArray.iterator(); while (myIter.hasNext()) { String currentResource = myIter.next().getAsString(); System.out.println("Node: " + currentResource); resultList[pointer] = currentResource; pointer++; } // Provide result return resultList; }