List of usage examples for com.google.gson JsonElement getAsJsonArray
public JsonArray getAsJsonArray()
From source file:com.ibm.g11n.pipeline.resfilter.GlobalizeJsResource.java
License:Open Source License
/** * The override of addBundleStrings is necessary because globalizejs treats arrays of strings * as a single long string, with each piece separated by a space, rather than treating it like * a real JSON array.//from www . ja va2 s.c o m */ @Override protected int addBundleStrings(JsonObject obj, String keyPrefix, Bundle bundle, int sequenceNum) { for (Map.Entry<String, JsonElement> entry : obj.entrySet()) { String key = entry.getKey(); JsonElement value = entry.getValue(); if (value.isJsonObject()) { sequenceNum = addBundleStrings(value.getAsJsonObject(), encodeResourceKey(keyPrefix, key, false), bundle, sequenceNum); } else if (value.isJsonArray()) { JsonArray ar = value.getAsJsonArray(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < ar.size(); i++) { JsonElement arrayEntry = ar.get(i); if (arrayEntry.isJsonPrimitive() && arrayEntry.getAsJsonPrimitive().isString()) { if (i > 0) { sb.append(" "); // } sb.append(arrayEntry.getAsString()); } else { throw new IllegalResourceFormatException( "Arrays must contain only strings in a globalizejs resource."); } } sequenceNum++; bundle.addResourceString(encodeResourceKey(keyPrefix, key, true), sb.toString(), sequenceNum); } else if (!value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString()) { throw new IllegalResourceFormatException("The value of JSON element " + key + " is not a string."); } else { sequenceNum++; bundle.addResourceString(encodeResourceKey(keyPrefix, key, true), value.getAsString(), sequenceNum); } } return sequenceNum; }
From source file:com.ibm.g11n.pipeline.resfilter.impl.GlobalizeJsResource.java
License:Open Source License
/** * The override of addBundleStrings is necessary because globalizejs treats arrays of strings * as a single long string, with each piece separated by a space, rather than treating it like * a real JSON array./*from w w w .ja va 2s. co m*/ */ @Override protected int addBundleStrings(JsonObject obj, String keyPrefix, LanguageBundleBuilder bb, int sequenceNum) throws ResourceFilterException { for (Map.Entry<String, JsonElement> entry : obj.entrySet()) { String key = entry.getKey(); JsonElement value = entry.getValue(); if (value.isJsonObject()) { sequenceNum = addBundleStrings(value.getAsJsonObject(), encodeResourceKey(keyPrefix, key, false), bb, sequenceNum); } else if (value.isJsonArray()) { JsonArray ar = value.getAsJsonArray(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < ar.size(); i++) { JsonElement arrayEntry = ar.get(i); if (arrayEntry.isJsonPrimitive() && arrayEntry.getAsJsonPrimitive().isString()) { if (i > 0) { sb.append(" "); // } sb.append(arrayEntry.getAsString()); } else { throw new IllegalResourceFormatException( "Arrays must contain only strings in a globalizejs resource."); } } sequenceNum++; bb.addResourceString(encodeResourceKey(keyPrefix, key, true), sb.toString(), sequenceNum); } else if (!value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString()) { throw new IllegalResourceFormatException("The value of JSON element " + key + " is not a string."); } else { sequenceNum++; bb.addResourceString(encodeResourceKey(keyPrefix, key, true), value.getAsString(), sequenceNum); } } return sequenceNum; }
From source file:com.ibm.g11n.pipeline.resfilter.impl.JsonResource.java
License:Open Source License
protected int addBundleStrings(JsonObject obj, String keyPrefix, LanguageBundleBuilder bb, int sequenceNum) throws ResourceFilterException { for (Map.Entry<String, JsonElement> entry : obj.entrySet()) { String key = entry.getKey(); JsonElement value = entry.getValue(); if (value.isJsonObject()) { sequenceNum = addBundleStrings(value.getAsJsonObject(), encodeResourceKey(keyPrefix, key, false), bb, sequenceNum);// w w w.j a v a2s . co m } else if (value.isJsonArray()) { JsonArray ar = value.getAsJsonArray(); for (int i = 0; i < ar.size(); i++) { JsonElement arrayEntry = ar.get(i); String arrayKey = encodeResourceKey(keyPrefix, key, false) + "[" + Integer.toString(i) + "]"; if (arrayEntry.isJsonPrimitive() && arrayEntry.getAsJsonPrimitive().isString()) { sequenceNum++; bb.addResourceString(ResourceString.with(arrayKey, arrayEntry.getAsString()) .sequenceNumber(sequenceNum)); } else { sequenceNum = addBundleStrings(arrayEntry.getAsJsonObject(), arrayKey, bb, sequenceNum); } } } else if (!value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString()) { throw new IllegalResourceFormatException("The value of JSON element " + key + " is not a string."); } else { sequenceNum++; bb.addResourceString( ResourceString.with(encodeResourceKey(keyPrefix, key, true), value.getAsString()) .sequenceNumber(sequenceNum)); } } return sequenceNum; }
From source file:com.ibm.g11n.pipeline.resfilter.impl.JsonResource.java
License:Open Source License
@Override public void write(OutputStream outStream, LanguageBundle languageBundle, FilterOptions options) throws IOException, ResourceFilterException { // extracts key value pairs in original sequence order List<ResourceString> resStrings = languageBundle.getSortedResourceStrings(); JsonObject output = new JsonObject(); JsonObject top_level;//from w w w . j a va 2 s.com if (this instanceof GlobalizeJsResource) { String resLanguageCode = languageBundle.getEmbeddedLanguageCode(); if (resLanguageCode == null || resLanguageCode.isEmpty()) { throw new ResourceFilterException( "Missing resource language code in the specified language bundle."); } top_level = new JsonObject(); top_level.add(resLanguageCode, output); } else { top_level = output; } for (ResourceString res : resStrings) { String key = res.getKey(); List<KeyPiece> keyPieces = splitKeyPieces(key); JsonElement current = output; for (int i = 0; i < keyPieces.size(); i++) { if (i + 1 < keyPieces.size()) { // There is structure under this // key piece if (current.isJsonObject()) { JsonObject currentObject = current.getAsJsonObject(); if (!currentObject.has(keyPieces.get(i).keyValue)) { if (keyPieces.get(i + 1).keyType == JsonToken.BEGIN_ARRAY) { currentObject.add(keyPieces.get(i).keyValue, new JsonArray()); } else { currentObject.add(keyPieces.get(i).keyValue, new JsonObject()); } } current = currentObject.get(keyPieces.get(i).keyValue); } else { JsonArray currentArray = current.getAsJsonArray(); Integer idx = Integer.valueOf(keyPieces.get(i).keyValue); for (int arrayIndex = currentArray.size(); arrayIndex <= idx; arrayIndex++) { currentArray.add(JsonNull.INSTANCE); } if (currentArray.get(idx).isJsonNull()) { if (keyPieces.get(i + 1).keyType == JsonToken.BEGIN_ARRAY) { currentArray.set(idx, new JsonArray()); } else { currentArray.set(idx, new JsonObject()); } } current = currentArray.get(idx); } } else { // This is the leaf node if (keyPieces.get(i).keyType == JsonToken.BEGIN_ARRAY) { JsonArray currentArray = current.getAsJsonArray(); Integer idx = Integer.valueOf(keyPieces.get(i).keyValue); JsonPrimitive e = new JsonPrimitive(res.getValue()); for (int arrayIndex = currentArray.size(); arrayIndex <= idx; arrayIndex++) { currentArray.add(JsonNull.INSTANCE); } current.getAsJsonArray().set(idx, e); } else { current.getAsJsonObject().addProperty(keyPieces.get(i).keyValue, res.getValue()); } } } } try (OutputStreamWriter writer = new OutputStreamWriter(new BufferedOutputStream(outStream), StandardCharsets.UTF_8)) { new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(top_level, writer); } }
From source file:com.ibm.iotf.sample.client.application.api.SampleHistorianAPIOperations.java
License:Open Source License
/** * This method retrieves events across all devices of a particular device type but with a * list of query parameters,// ww w .j ava2s . co m */ private void getAllHistoricalEventsByDeviceType() { System.out.println("Get all blink events under device type " + DEVICE_TYPE + " and summarize the datapoints cpu and mem "); // Get the historical events try { ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("evt_type", "blink")); parameters.add(new BasicNameValuePair("summarize", "{cpu,mem}")); parameters.add(new BasicNameValuePair("summarize_type", "avg")); JsonElement response = this.apiClient.getHistoricalEvents(DEVICE_TYPE, parameters); for (Iterator<JsonElement> iterator = response.getAsJsonArray().iterator(); iterator.hasNext();) { JsonElement event = iterator.next(); JsonObject responseJson = event.getAsJsonObject(); System.out.println(responseJson); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.ibm.iotf.sample.client.application.api.SampleHistorianAPIOperations.java
License:Open Source License
/** * This sample retrieves events based on the device ID and with supplied query parameters. *///from w w w . ja v a 2s. co m private void getAllHistoricalEventsByDeviceID() { System.out.println("Get all blink events under device " + DEVICE_ID + " of Type " + DEVICE_TYPE + " and summarize the datapoints cpu and mem "); // Get the historical events try { ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("evt_type", "blink")); parameters.add(new BasicNameValuePair("summarize", "{cpu,mem}")); parameters.add(new BasicNameValuePair("summarize_type", "avg")); JsonElement response = this.apiClient.getHistoricalEvents(DEVICE_TYPE, DEVICE_ID, parameters); for (Iterator<JsonElement> iterator = response.getAsJsonArray().iterator(); iterator.hasNext();) { JsonElement event = iterator.next(); JsonObject responseJson = event.getAsJsonObject(); System.out.println(responseJson); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.ibm.og.json.type.SelectionConfigTypeAdapterFactory.java
License:Open Source License
@Override @SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) { final Class<T> rawType = (Class<T>) type.getRawType(); if (!SelectionConfig.class.equals(rawType)) { return null; }//from w w w . j a va 2s. c om final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); return new TypeAdapter<T>() { @Override public void write(final JsonWriter out, final T value) throws IOException { delegate.write(out, value); } @Override public T read(final JsonReader in) throws IOException { final Class<?> genericType = (Class<?>) ((ParameterizedType) type.getType()) .getActualTypeArguments()[0]; final JsonElement element = gson.getAdapter(JsonElement.class).read(in); if (element.isJsonObject()) { final JsonObject object = element.getAsJsonObject(); if (object.entrySet().size() <= 2 && object.has("choices")) { return delegate.fromJsonTree(object); } else { return (T) choice(genericType, object); } } else if (element.isJsonArray()) { return (T) choiceList(genericType, element.getAsJsonArray()); } return (T) choice(genericType, element); } private <S> SelectionConfig<S> choice(final Class<S> clazz, final JsonElement element) throws IOException { final SelectionConfig<S> config = new SelectionConfig<S>(); config.choices.add(gson.getAdapter(choiceToken(clazz)).fromJsonTree(element)); return config; } private <S> SelectionConfig<S> choiceList(final Class<S> clazz, final JsonArray array) throws IOException { final SelectionConfig<S> config = new SelectionConfig<S>(); config.choices = gson.getAdapter(choiceListToken(clazz)).fromJsonTree(array); return config; } // must use guava's TypeToken implementation to create a TypeToken instance with a dynamic // type; then convert back to gson's TypeToken implementation for use in calling code. See: // https://groups.google.com/forum/#!topic/guava-discuss/HdBuiO44uaw private <S> TypeToken<ChoiceConfig<S>> choiceToken(final Class<S> clazz) { @SuppressWarnings("serial") final com.google.common.reflect.TypeToken<ChoiceConfig<S>> choiceToken = new com.google.common.reflect.TypeToken<ChoiceConfig<S>>() { }.where(new TypeParameter<S>() { }, com.google.common.reflect.TypeToken.of(clazz)); return (TypeToken<ChoiceConfig<S>>) TypeToken.get(choiceToken.getType()); } private <S> TypeToken<List<ChoiceConfig<S>>> choiceListToken(final Class<S> clazz) { @SuppressWarnings("serial") final com.google.common.reflect.TypeToken<List<ChoiceConfig<S>>> choiceToken = new com.google.common.reflect.TypeToken<List<ChoiceConfig<S>>>() { }.where(new TypeParameter<S>() { }, com.google.common.reflect.TypeToken.of(clazz)); return (TypeToken<List<ChoiceConfig<S>>>) TypeToken.get(choiceToken.getType()); } }.nullSafe(); }
From source file:com.ibm.streamsx.topology.generator.spl.SPLGenerator.java
License:Open Source License
/** * Add an arbitrary SPL value./* w ww. j a v a2 s . c o m*/ * JsonObject has a type and a value. */ static void value(StringBuilder sb, JsonObject tv) { JsonElement value = tv.get("value"); String type = JParamTypes.TYPE_SPL_EXPRESSION; if (tv.has("type")) { type = tv.get("type").getAsString(); } else { if (value.isJsonPrimitive()) { JsonPrimitive pv = value.getAsJsonPrimitive(); if (pv.isString()) type = "RSTRING"; } else if (value.isJsonArray()) { type = "RSTRING"; } } if (value.isJsonArray()) { JsonArray array = value.getAsJsonArray(); for (int i = 0; i < array.size(); i++) { if (i != 0) sb.append(", "); value(sb, type, array.get(i)); } } else { value(sb, type, value); } }
From source file:com.ibm.streamsx.topology.internal.gson.GsonUtilities.java
License:Open Source License
/** * Return a Json array. If the value is not * an array then an array containing the single * value is returned.//w ww . j a v a2 s .c o m * Returns null if the array is not present or present as JSON null. */ public static JsonArray array(JsonObject object, String property) { if (object.has(property)) { JsonElement je = object.get(property); if (je.isJsonNull()) return null; if (je.isJsonArray()) return je.getAsJsonArray(); JsonArray array = new JsonArray(); array.add(je); return array; } return null; }
From source file:com.ibm.watson.apis.conversation_enhanced.discovery.DiscoveryClient.java
License:Open Source License
/** * Helper Method to include highlighting information along with the retrieve * and rank response so the final payload includes id,title,body,sourceUrl as * json key value pairs./*from w w w. j av a 2s.c om*/ * * @param input * The user's query sent to the discovery service * @param results * The results obtained from a call to the discovery service service * with <code>input</code> as the query * @return A list of DocumentPayload objects, each representing a single * document the discovery service believes is a possible answer to the * user's query */ private List<DocumentPayload> createPayload(String input, JsonElement resultsElement) { logger.info(Messages.getString("Service.CREATING_DISCOVERY_PAYLOAD")); List<DocumentPayload> payload = new ArrayList<DocumentPayload>(); HashMap<String, Integer> hm = new HashMap<String, Integer>(); JsonArray jarray = resultsElement.getAsJsonArray(); for (int i = 0; i < jarray.size() && i < Constants.DISCOVERY_MAX_SEARCH_RESULTS_TO_SHOW; i++) { DocumentPayload documentPayload = new DocumentPayload(); String id = jarray.get(i).getAsJsonObject().get(Constants.DISCOVERY_FIELD_ID).toString() .replaceAll("\"", ""); documentPayload.setId(id); documentPayload.setTitle(jarray.get(i).getAsJsonObject().get(Constants.DISCOVERY_FIELD_TITLE).toString() .replaceAll("\"", "")); if (jarray.get(i).getAsJsonObject().get(Constants.DISCOVERY_FIELD_BODY) != null) { String body = jarray.get(i).getAsJsonObject().get(Constants.DISCOVERY_FIELD_BODY).toString() .replaceAll("\"", ""); // This method limits the response text in this sample // app to two paragraphs. String bodyTwoPara = limitParagraph(body); documentPayload.setBody(bodyTwoPara); documentPayload.setBodySnippet(getSniplet(body)); } else { documentPayload.setBody("empty"); } if (jarray.get(i).getAsJsonObject().get(Constants.DISCOVERY_FIELD_SOURCE_URL) == null) { documentPayload.setSourceUrl("empty"); } else { documentPayload.setSourceUrl(jarray.get(i).getAsJsonObject() .get(Constants.DISCOVERY_FIELD_SOURCE_URL).toString().replaceAll("\"", "")); } if (jarray.get(i).getAsJsonObject().get(Constants.DISCOVERY_FIELD_CONFIDENCE) != null) { documentPayload.setConfidence(jarray.get(i).getAsJsonObject() .get(Constants.DISCOVERY_FIELD_CONFIDENCE).toString().replaceAll("\"", "")); } else { documentPayload.setConfidence("0.0"); } payload.add(i, documentPayload); hm.put(id, i); } return payload; }