List of usage examples for com.google.gson JsonElement isJsonObject
public boolean isJsonObject()
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 a2s . com 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.SubmissionTimeValue.java
License:Open Source License
/** * Enrich the json composite operator definition's parameters * to include parameters for submission parameters. * <p>// ww w. j a va 2 s. c o m * The composite is augmented with a TYPE_SUBMISSION_PARAMETER parameter * for each submission parameter used within the composite - e.g, as * a parallel width value or SPL operator parameter value. * <p> * If the composite has any functional operator children, enrich * the composite to have declarations for all submission parameters. * Also accumulate the functional children and make them available via * {@link #getFunctionalOps()}. * * @param composite the composite definition */ void addJsonParamDefs(JsonObject composite) { // scan immediate children ops for submission param use // and add corresponding param definitions to the composite. // Also, if the op has functional logic, enrich the op too... // and further enrich the composite. if (allSubmissionParams.isEmpty()) return; // scan for spParams JsonObject spParams = new JsonObject(); AtomicBoolean addedAll = new AtomicBoolean(); GsonUtilities.objectArray(composite, "operators", op -> { JsonObject params = jobject(op, "parameters"); if (params != null) { boolean addAll = false; for (Entry<String, JsonElement> p : params.entrySet()) { // if functional logic add "submissionParameters" param if (params.has(FUNCTIONAL_LOGIC_PARAM)) { functionalOps.put(jstring(op, "name"), op); addAll = true; break; } else { JsonObject param = p.getValue().getAsJsonObject(); String type = jstring(param, "type"); if (TYPE_SUBMISSION_PARAMETER.equals(type)) { addInnerCompositeParameter(spParams, param); } } } if (addAll && !addedAll.getAndSet(true)) { for (String name : allSubmissionParams.keySet()) { addInnerCompositeParameter(spParams, allSubmissionParams.get(name)); } } } boolean isParallel = jboolean(op, "parallelOperator"); if (isParallel) { JsonElement width = op.get("parallelInfo").getAsJsonObject().get("width"); if (width.isJsonObject()) { JsonObject jwidth = width.getAsJsonObject(); String type = jstring(jwidth, "type"); if (TYPE_SUBMISSION_PARAMETER.equals(type)) { addInnerCompositeParameter(spParams, jwidth); } } } }); // augment the composite's parameters JsonObject params = jobject(composite, "parameters"); if (params == null && !GsonUtilities.jisEmpty(spParams)) { params = new JsonObject(); composite.add("parameters", params); } for (Entry<String, JsonElement> p : spParams.entrySet()) { String pname = p.getKey(); if (!params.has(pname)) params.add(pname, spParams.get(pname)); } // make the results of our efforts available to addJsonInstanceParams composite.add(OP_ATTR_SPL_SUBMISSION_PARAMS, spParams); }
From source file:com.ibm.streamsx.topology.internal.streaminganalytics.VcapServices.java
License:Open Source License
/** * Get the top-level VCAP services object. * //from w w w.ja v a2s . co m * Object can be one of the following: * <ul> * <li>JsonObject - assumed to contain VCAP_SERVICES </li> * <li>String - assumed to contain serialized VCAP_SERVICES JSON, or the * location of a file containing the serialized VCAP_SERVICES JSON</li> * <li>null - assumed to be in the environment variable VCAP_SERVICES</li> * </ul> */ public static JsonObject getVCAPServices(JsonElement rawServices) throws IOException { JsonParser parser = new JsonParser(); String vcapString; String vcapContents = null; if (rawServices == null || rawServices.isJsonNull()) { // if rawServices is null, then pull from the environment vcapString = System.getenv("VCAP_SERVICES"); if (vcapString == null) { throw new IllegalStateException( "VCAP_SERVICES are not defined, please set environment variable VCAP_SERVICES or configuration property: " + VCAP_SERVICES); } // resulting string can be either the serialized JSON or filename if (Files.isRegularFile(Paths.get(vcapString))) { Path vcapFile = Paths.get(vcapString); vcapContents = new String(Files.readAllBytes(vcapFile), StandardCharsets.UTF_8); } else { vcapContents = vcapString; } } else if (rawServices.isJsonObject()) { return rawServices.getAsJsonObject(); } else if (rawServices.isJsonPrimitive()) { // String can be either the serialized JSON or filename String rawString = rawServices.getAsString(); if (Files.isRegularFile(Paths.get(rawString))) { Path vcapFile = Paths.get(rawString); vcapContents = new String(Files.readAllBytes(vcapFile), StandardCharsets.UTF_8); } else vcapContents = rawString; } else { throw new IllegalArgumentException("Unknown VCAP_SERVICES object class: " + rawServices.getClass()); } return parser.parse(vcapContents).getAsJsonObject(); }
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()); }/*from 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.ibm.watson.developer_cloud.alchemy.v1.util.AlchemyEndPoints.java
License:Open Source License
/** * Load the endpoints from json file./*from w ww. j a va 2 s . co m*/ */ private static void loadEndPointsFromJsonFile() { LOG.log(Level.FINE, "Parsing End Points JSON file "); operationsByEndpoint = new HashMap<String, Map<String, String>>(); final JsonParser parser = new JsonParser(); Reader fileReader = null; try { final InputStream is = AlchemyEndPoints.class.getResourceAsStream(FILE_PATH); if (null != is) { fileReader = new InputStreamReader(is); } final Object obj = parser.parse(fileReader); final JsonObject jsonObject = (JsonObject) obj; for (final AlchemyAPI object : AlchemyAPI.values()) { if (jsonObject.get(object.name()) == null) { continue; } final JsonElement elt = jsonObject.get(object.name()).getAsJsonObject(); if (elt.isJsonObject()) { final Map<String, String> records = new HashMap<String, String>(); for (final Map.Entry<String, JsonElement> e : elt.getAsJsonObject().entrySet()) { records.put(e.getKey(), e.getValue().getAsString()); } operationsByEndpoint.put(object.name(), records); } } } catch (final JsonParseException e) { LOG.log(Level.SEVERE, "Could not parse json file: " + FILE_PATH, e); } catch (final NullPointerException e) { LOG.log(Level.SEVERE, "Not able to locate the end points json file: " + FILE_PATH, e); } finally { if (fileReader != null) { try { fileReader.close(); } catch (final IOException e) { LOG.log(Level.SEVERE, "Could not close file reader: " + FILE_PATH, e); } } } }
From source file:com.ibm.watson.developer_cloud.util.AlchemyEndPoints.java
License:Open Source License
/** * Load the endpoints from json file./*w w w. j a v a2 s . c o m*/ */ private static void loadEndPointsFromJsonFile() { log.log(Level.FINE, "Parsing End Points JSON file "); operations = new HashMap<String, Map<String, String>>(); JsonParser parser = new JsonParser(); try { Object obj = parser.parse(new FileReader(filePath)); JsonObject jsonObject = (JsonObject) obj; for (AlchemyAPI object : AlchemyAPI.values()) { if (jsonObject.get(object.name()) == null) continue; ; JsonElement elt = jsonObject.get(object.name()).getAsJsonObject(); if (elt.isJsonObject()) { Map<String, String> records = new HashMap<String, String>(); for (Map.Entry<String, JsonElement> e : elt.getAsJsonObject().entrySet()) { records.put(e.getKey(), e.getValue().getAsString()); } operations.put(object.name(), records); } } } catch (JsonParseException e) { log.log(Level.SEVERE, "Could not parse json file: " + filePath, e); } catch (FileNotFoundException e) { log.log(Level.SEVERE, "File not found: " + filePath, e); } }
From source file:com.iheart.quickio.client.QuickIo.java
License:Open Source License
private void routeCallback(final String evPath, final QuickIoCallback cb, final JsonElement json) { if (!json.isJsonObject()) { return;//w ww . j a va2s.c om } long cbId = Long.parseLong(evPath.substring(QuickIo.EV_CALLBACK.length())); QuickIoCallback evCb = null; synchronized (this) { evCb = this.cbs.remove(cbId); } if (evCb == null) { return; } JsonObject obj = json.getAsJsonObject(); int code = obj.get("code").getAsInt(); String errMsg = ""; if (obj.has("err_msg")) { JsonElement errObj = obj.get("err_msg"); errMsg = errObj.isJsonNull() ? null : errObj.getAsString(); } evCb.onCallback(obj.get("data"), cb, code, errMsg); }
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();//from w w w .j a va2s .c o 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; }
From source file:com.ikanow.infinit.e.data_model.custom.InfiniteFileInputJsonParser.java
License:Apache License
private BasicDBObject convertJsonToDocument(JsonElement meta) { // Check if all required fields exist: if (!checkIfMandatoryFieldsExist(meta)) { return null; }//from w w w .jav a 2 s .c o m //TESTED // Primary key and create doc BasicDBObject currObj = new BasicDBObject(); if ((null != primaryKey) && (null != sourceName)) { String primaryKey = getPrimaryKey(meta); if (null != primaryKey) { currObj.put(DocumentPojo.url_, sourceName + primaryKey); } } if (meta.isJsonObject()) { currObj.put(DocumentPojo.metadata_, new BasicDBObject("json", Arrays.asList(convertJsonObjectToBson(meta.getAsJsonObject())))); } return currObj; }
From source file:com.ikanow.infinit.e.data_model.custom.InfiniteFileInputJsonParser.java
License:Apache License
private String getKey(JsonElement meta, String key, boolean bPrimitiveOnly) { try {/* w ww.j a va 2 s . com*/ String[] components = key.split("\\."); JsonObject metaObj = meta.getAsJsonObject(); for (String comp : components) { meta = metaObj.get(comp); if (null == meta) { return null; } //TESTED else if (meta.isJsonObject()) { metaObj = meta.getAsJsonObject(); } //TESTED else if (meta.isJsonPrimitive()) { return meta.getAsString(); } //TESTED else if (bPrimitiveOnly) { // (meta isn't allowed to be an array, then you'd have too many primary keys!) return null; } //TOTEST (? - see JsonToMetadataParser) else { // Check with first instance JsonArray array = meta.getAsJsonArray(); meta = array.get(0); if (meta.isJsonObject()) { metaObj = meta.getAsJsonObject(); } } //TESTED } if (!bPrimitiveOnly) { // allow objects, we just care if the field exists... if (null != metaObj) { return "[Object]"; } } //TESTED } catch (Exception e) { } // no primary key return null; }