List of usage examples for com.google.gson JsonElement isJsonArray
public boolean isJsonArray()
From source file:com.ibm.common.geojson.as2.GeoAdapter.java
License:Apache License
@Override public GeoObject deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException { GeoObject.Builder geo = null;//from www.j a v a 2 s . co m checkArgument(element.isJsonObject()); JsonObject obj = element.getAsJsonObject(); checkArgument(obj.has("type")); GeoObject.Type et = Enums.getIfPresent(GeoObject.Type.class, obj.get("type").getAsString().toUpperCase()) .orNull(); checkArgument(et != null); switch (et) { case FEATURE: geo = GeoMakers.feature(); break; case FEATURECOLLECTION: geo = GeoMakers.featureCollection(); type = Feature.class; break; case GEOMETRYCOLLECTION: geo = GeoMakers.geometryCollection(); type = Geometry.class; break; case LINESTRING: geo = GeoMakers.linestring(); type = Position.class; break; case MULTILINESTRING: geo = GeoMakers.multiLineString(); type = LineString.class; break; case MULTIPOINT: geo = GeoMakers.multipoint(); type = Position.class; break; case MULTIPOLYGON: geo = GeoMakers.multiPolygon(); type = Polygon.class; break; case POINT: geo = GeoMakers.point(); type = null; break; case POLYGON: geo = GeoMakers.polygon(); type = LineString.class; break; } for (Map.Entry<String, JsonElement> entry : obj.entrySet()) { JsonElement el = entry.getValue(); String name = entry.getKey(); if ("crs".equals(name)) { CRS.Builder cb = new CRS.Builder(); JsonObject o = el.getAsJsonObject(); if (o.has("type")) cb.type(o.get("type").getAsString()); if (o.has("properties")) { JsonObject p = o.get("properties").getAsJsonObject(); for (Map.Entry<String, JsonElement> e : p.entrySet()) { cb.set(e.getKey(), context.deserialize(e.getValue(), Object.class)); } } geo.crs(cb.get()); } else if ("properties".equals(name)) { geo.set("properties", context.deserialize(el, Map.class)); } else if ("bbox".equals(name)) { BoundingBox.Builder bb = new BoundingBox.Builder(); float[] points = context.deserialize(el, float[].class); bb.add(points); geo.boundingBox(bb.get()); } else if ("features".equals(name)) { Feature[] features = context.deserialize(el, Feature[].class); FeatureCollection.Builder fcb = (FeatureCollection.Builder) geo; for (Feature f : features) fcb.add(f); } else if ("coordinates".equals(name)) { switch (et) { case LINESTRING: { LineString.Builder lsb = (LineString.Builder) geo; float[][] positions = context.deserialize(el, float[][].class); boolean ring = ring(positions); if (ring) lsb.linearRing(); for (int n = 0; n < positions.length; n++) { if (!ring || (ring && n < positions.length - 1)) lsb.add(toPosition(positions[n])); } break; } case MULTIPOINT: { MultiPoint.Builder lsb = (MultiPoint.Builder) geo; float[][] positions = context.deserialize(el, float[][].class); for (float[] pos : positions) lsb.add(toPosition(pos)); break; } case MULTILINESTRING: { MultiLineString.Builder mlb = (MultiLineString.Builder) geo; float[][][] positions = context.deserialize(el, float[][][].class); for (float[][] lines : positions) { LineString.Builder lsb = GeoMakers.linestring(); boolean ring = ring(lines); if (ring) lsb.linearRing(); for (int n = 0; n < lines.length; n++) { if (!ring || (ring && n < lines.length - 1)) lsb.add(toPosition(lines[n])); } for (float[] pos : lines) lsb.add(toPosition(pos)); mlb.add(lsb); } break; } case POLYGON: { Polygon.Builder mlb = (Polygon.Builder) geo; float[][][] positions = context.deserialize(el, float[][][].class); for (float[][] lines : positions) { LineString.Builder lsb = GeoMakers.linestring(); for (float[] pos : lines) lsb.add(toPosition(pos)); mlb.add(lsb); } break; } case MULTIPOLYGON: { MultiPolygon.Builder mpb = (MultiPolygon.Builder) geo; float[][][][] positions = context.deserialize(el, float[][][][].class); for (float[][][] polygons : positions) { Polygon.Builder pb = GeoMakers.polygon(); for (float[][] lines : polygons) { LineString.Builder lsb = GeoMakers.linestring(); for (float[] pos : lines) lsb.add(toPosition(pos)); pb.add(lsb); } mpb.add(pb); } break; } case POINT: Point.Builder pb = (Point.Builder) geo; float[] position = context.deserialize(el, float[].class); pb.position(toPosition(position)); break; default: break; } } else if ("geometries".equals(name)) { Geometry[] geos = context.deserialize(el, Geometry[].class); GeometryCollection.Builder fcb = (GeometryCollection.Builder) geo; for (Geometry<?, ?> g : geos) fcb.add(g); } else { if (el.isJsonArray()) { geo.set(name, context.deserialize(el, Object.class)); } else if (el.isJsonObject()) { geo.set(name, context.deserialize(el, GeoObject.class)); } else if (el.isJsonPrimitive()) { JsonPrimitive p = el.getAsJsonPrimitive(); if (p.isBoolean()) geo.set(name, p.getAsBoolean()); else if (p.isNumber()) geo.set(name, p.getAsNumber()); else if (p.isString()) geo.set(name, p.getAsString()); } } } return geo.get(); }
From source file:com.ibm.g11n.pipeline.client.ServiceAccount.java
License:Open Source License
/** * Returns an instance of ServiceAccount from the VCAP_SERVICES environment * variable.//from w w w . j a v a 2s. c o m * <p> * When <code>serviceInstanceName</code> is null, this method returns * a ServiceAccount for the first valid IBM Globlization Pipeline service instance. * If <code>serviceInstanceName</code> is not null, this method look up a * matching service entry, and returns a ServiceAccount for the matching entry. * If <code>serviceInstanceName</code> is not null and there is no match, * this method returns null. * * @param serviceName * The name of IBM Globalization Pipeline service. If null, * the first service with a name matching GP_SERVICE_NAME_PATTERN * will be used. * @param serviceInstanceName * The name of IBM Globalization Pipeline service instance, or null * designating the first available service instance. * @return An instance of ServiceAccount for the specified service instance * name, or null. */ private static ServiceAccount getInstanceByVcapServices(String serviceName, String serviceInstanceName) { Map<String, String> env = System.getenv(); String vcapServices = env.get("VCAP_SERVICES"); if (vcapServices == null) { return null; } try { JsonObject obj = new JsonParser().parse(vcapServices).getAsJsonObject(); // When service name is specified, // this method returns only a matching entry if (serviceName != null) { JsonElement elem = obj.get(serviceName); if (elem != null && elem.isJsonArray()) { return parseToServiceAccount(elem.getAsJsonArray(), serviceInstanceName); } } // Otherwise, lookup a valid entry with a name matching // the default pattern GP_SERVICE_NAME_PATTERN. for (Entry<String, JsonElement> entry : obj.entrySet()) { String name = entry.getKey(); JsonElement elem = entry.getValue(); if (elem.isJsonArray() && GP_SERVICE_NAME_PATTERN.matcher(name).matches()) { ServiceAccount account = parseToServiceAccount(elem.getAsJsonArray(), serviceInstanceName); if (account != null) { return account; } } } } catch (JsonParseException e) { // Fall through - will return null } return null; }
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./* w ww.jav a 2 s.co 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 ww. j a v a2 s . c om*/ */ @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);//from w w w. j a v a2 s .c o 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.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; }//w w w. j a v a 2 s . 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./*from w w w .j a v a2 s . co 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 w w . j ava 2 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.app.common.services.impl.BluemixServicesConfigurationParser.java
License:Open Source License
public void parseAndRegisterServices(JsonElement json) { Objects.requireNonNull(json, MessageKey.AQWEGA14019E_json_element_null.getMessage().getFormattedMessage()); if (!json.isJsonObject()) { throw new JsonParseException(MessageKey.AQWEGA14001E_expected_json_object_parse_bluemix_service_conf .getMessage().getFormattedMessage()); }/*w w w.ja va 2 s. c o m*/ final boolean isTrace = logger.isTraceEnabled(); for (Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) { final String serviceKey = entry.getKey(); final JsonElement serviceConfigArray = entry.getValue(); if (!serviceConfigArray.isJsonArray()) { throw new JsonParseException(MessageKey.AQWEGA14002E_expected_json_array_while_parsing_config_1 .getMessage(serviceKey).getFormattedMessage()); } BluemixServiceInfo<? extends BluemixConfiguredService> service = BluemixServicesBinder .getBluemixServiceByName(serviceKey); if (service == null) { logger.warn(MessageKey.AQWEGA12001W_unexpected_conf_supplied_for_service_ignore_1 .getMessage(serviceKey)); continue; } if (isTrace) { logger.trace("Loading configuration for service '" + serviceKey + "'"); } for (JsonElement serviceInstanceConfig : serviceConfigArray.getAsJsonArray()) { try { BluemixConfiguredService serviceImpl = service.serviceImpl.getConstructor().newInstance(); serviceImpl .setConfig(gson.fromJson(serviceInstanceConfig, serviceImpl.getConfigurationClass())); serviceImpl.initialize(); register(service, serviceImpl); } catch (IllegalAccessException | InstantiationException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { logger.warn(MessageKey.AQWEGA12002W_unable_register_service_error_2.getMessage(serviceKey, e.getMessage())); logger.catching(Level.DEBUG, e); } } } }
From source file:com.ikanow.infinit.e.data_model.custom.InfiniteFileInputJsonParser.java
License:Apache License
private BasicDBObject getDocumentFromJson(boolean bRecursing) throws IOException { if (!_inSecondaryObject) { reader.beginObject();// ww w.ja va 2 s .co m _inSecondaryObject = true; } while (reader.hasNext()) { String name = reader.nextName(); boolean bMatch = false; if (bRecursing) { bMatch = recursiveObjectIdentifiers.contains(name.toLowerCase()); } else { bMatch = objectIdentifiers.contains(name.toLowerCase()); } //TESTED if (bMatch) { JsonElement meta = parser.parse(reader); if (meta.isJsonObject()) { BasicDBObject currObj = convertJsonToDocument(meta); if (null != currObj) { return currObj; } } //TESTED else if (meta.isJsonArray()) { _secondaryArray = meta.getAsJsonArray(); _posInSecondaryArray = 0; for (JsonElement meta2 : _secondaryArray) { _posInSecondaryArray++; BasicDBObject currObj = convertJsonToDocument(meta2); if (null != currObj) { return currObj; } } _secondaryArray = null; } //TESTED } //TESTED else { if (bRecurse) { //TODO (INF-2469): Not currently supported, it gets a bit tricky? (need to convert to a stack) JsonToken tok = reader.peek(); if (JsonToken.BEGIN_OBJECT == tok) { BasicDBObject currObj = getDocumentFromJson(true); if (null != currObj) { return currObj; } } //TESTED else if (JsonToken.BEGIN_ARRAY == tok) { reader.beginArray(); while (reader.hasNext()) { JsonToken tok2 = reader.peek(); if (JsonToken.BEGIN_OBJECT == tok2) { BasicDBObject currObj = getDocumentFromJson(true); if (null != currObj) { return currObj; } } else { reader.skipValue(); } //TESTED } //TESTED reader.endArray(); } else { reader.skipValue(); } //TESTED } else { reader.skipValue(); } //TESTED } } //(end loop over reader) reader.endObject(); _inSecondaryObject = false; return null; }