List of usage examples for com.google.gson JsonObject entrySet
public Set<Map.Entry<String, JsonElement>> entrySet()
From source file:com.google.wave.api.impl.OperationRequestGsonAdaptor.java
License:Apache License
@Override public OperationRequest deserialize(JsonElement json, Type type, JsonDeserializationContext ctx) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); JsonObject parameters = jsonObject.getAsJsonObject(RequestProperty.PARAMS.key()); OperationRequest request = new OperationRequest(jsonObject.get(RequestProperty.METHOD.key()).getAsString(), jsonObject.get(RequestProperty.ID.key()).getAsString(), getPropertyAsStringThenRemove(parameters, ParamsProperty.WAVE_ID), getPropertyAsStringThenRemove(parameters, ParamsProperty.WAVELET_ID), getPropertyAsStringThenRemove(parameters, ParamsProperty.BLIP_ID)); for (Entry<String, JsonElement> parameter : parameters.entrySet()) { ParamsProperty parameterType = ParamsProperty.fromKey(parameter.getKey()); if (parameterType != null) { Object object;/*from w w w .j a v a 2 s . com*/ if (parameterType == ParamsProperty.RAW_DELTAS) { object = ctx.deserialize(parameter.getValue(), GsonFactory.RAW_DELTAS_TYPE); } else { object = ctx.deserialize(parameter.getValue(), parameterType.clazz()); } request.addParameter(Parameter.of(parameterType, object)); } } return request; }
From source file:com.google.wave.splash.data.serialize.JsonSerializer.java
License:Apache License
/** * Parses a string of json from a wave.robot.fetchWave into a result. * * @param json the json to parse.//from w w w . ja v a 2s . c om * @return the result object, which may not contain a wavelet. */ @Timed public FetchWaveletResult parseFetchWaveletResult(String json) { JsonObject dataObject = getDataObject(json); if (dataObject == null || !dataObject.has("waveletData")) { LOG.warning("Fetch returned empty result."); return FetchWaveletResult.emptyResult(); } JsonObject waveletDataJson = dataObject.getAsJsonObject("waveletData"); OperationQueue operationQueue = new OperationQueue(); WaveletData waveletData = gson.fromJson(waveletDataJson, WaveletData.class); Map<String, Blip> blips = Maps.newHashMap(); HashMap<String, BlipThread> threads = Maps.newHashMap(); Wavelet wavelet = Wavelet.deserialize(operationQueue, blips, threads, waveletData); JsonObject threadMap = dataObject.getAsJsonObject("threads"); if (null != threadMap) { for (Map.Entry<String, JsonElement> entries : threadMap.entrySet()) { JsonObject threadElement = entries.getValue().getAsJsonObject(); int location = threadElement.get("location").getAsInt(); List<String> blipIds = Lists.newArrayList(); for (JsonElement blipId : threadElement.get("blipIds").getAsJsonArray()) { blipIds.add(blipId.getAsString()); } BlipThread thread = new BlipThread(entries.getKey(), location, blipIds, blips); threads.put(thread.getId(), thread); } } JsonObject blipMap = dataObject.getAsJsonObject("blips"); for (Map.Entry<String, JsonElement> entries : blipMap.entrySet()) { BlipData blipData = gson.fromJson(entries.getValue(), BlipData.class); Blip blip = Blip.deserialize(operationQueue, wavelet, blipData); blips.put(blipData.getBlipId(), blip); } return new FetchWaveletResult(wavelet); }
From source file:com.graphaware.module.es.Neo4jElasticVerifier.java
License:Open Source License
/** * @param node a node/* w w w. java 2s . c om*/ * @param indexPrefix non-suffixed index name */ public void verifyEsReplication(Node node, String indexPrefix) { String index = INDEX(true, indexPrefix); Map<String, Object> properties = new HashMap<>(); Set<String> labels = new HashSet<>(); String nodeKey; String nodeKeyProperty; try (Transaction tx = database.beginTx()) { nodeKeyProperty = configuration.getMapping().getKeyProperty(); nodeKey = node.getProperty(nodeKeyProperty).toString(); for (String key : node.getPropertyKeys()) { if (configuration.getInclusionPolicies().getNodePropertyInclusionPolicy().include(key, node)) { properties.put(key, node.getProperty(key)); } } for (Label label : node.getLabels()) { labels.add(label.name()); } tx.success(); } for (String label : labels) { Get get = new Get.Builder(index, nodeKey).type(label).build(); JestResult result = esClient.execute(get); assertTrue(result.getErrorMessage(), result.isSucceeded()); assertEquals(index, result.getValue("_index")); assertEquals(label, result.getValue("_type")); assertEquals(nodeKey, result.getValue("_id")); assertTrue((Boolean) result.getValue("found")); JsonObject source = result.getJsonObject().getAsJsonObject("_source"); assertEquals(properties.size() - 1, source.entrySet().size()); for (String key : properties.keySet()) { if (key.equals(nodeKeyProperty)) { assertNull(source.get(key)); } else if (properties.get(key) instanceof String[]) { checkStringArray(source, key, properties); } else if (properties.get(key) instanceof int[]) { checkIntArray(source, key, properties); } else if (properties.get(key) instanceof char[]) { checkCharArray(source, key, properties); } else if (properties.get(key) instanceof byte[]) { checkByteArray(source, key, properties); } else if (properties.get(key) instanceof boolean[]) { checkBooleanArray(source, key, properties); } else if (properties.get(key) instanceof float[]) { checkFloatArray(source, key, properties); } else if (properties.get(key) instanceof double[]) { checkDoubleArray(source, key, properties); } else if (properties.get(key) instanceof short[]) { checkShortArray(source, key, properties); } else if (properties.get(key) instanceof long[]) { checkLongArray(source, key, properties); } else assertEquals(properties.get(key).toString(), source.get(key).getAsString()); } } }
From source file:com.graphaware.module.es.Neo4jElasticVerifier.java
License:Open Source License
public void verifyEsAdvancedReplication(Node node, String indexPrefix) { String index = INDEX(true, indexPrefix); Map<String, Object> properties = new HashMap<>(); Set<String> labels = new TreeSet<>(); String nodeKey;/*from www . j a v a2s . c o m*/ String nodeKeyProperty; try (Transaction tx = database.beginTx()) { nodeKeyProperty = configuration.getKeyProperty(); nodeKey = node.getProperty(nodeKeyProperty).toString(); for (String key : node.getPropertyKeys()) { if (configuration.getInclusionPolicies().getNodePropertyInclusionPolicy().include(key, node)) { properties.put(key, node.getProperty(key)); } } for (Label label : node.getLabels()) { labels.add(label.name()); } tx.success(); } Get get = new Get.Builder(index, nodeKey).type(AdvancedMapping.NODE_TYPE).build(); JestResult result = esClient.execute(get); assertTrue(result.getErrorMessage(), result.isSucceeded()); assertEquals(index, result.getValue("_index")); assertEquals(AdvancedMapping.NODE_TYPE, result.getValue("_type")); assertEquals(nodeKey, result.getValue("_id")); assertTrue((Boolean) result.getValue("found")); JsonObject source = result.getJsonObject().getAsJsonObject("_source"); // field count: "_labels"/"_type" added but "uuid" removed assertEquals(properties.size(), source.entrySet().size()); for (String key : properties.keySet()) { if (key.equals(nodeKeyProperty)) { assertNull(source.get(key)); } else if (properties.get(key) instanceof String[]) { checkStringArray(source, key, properties); } else if (properties.get(key) instanceof int[]) { checkIntArray(source, key, properties); } else if (properties.get(key) instanceof char[]) { checkCharArray(source, key, properties); } else if (properties.get(key) instanceof byte[]) { checkByteArray(source, key, properties); } else if (properties.get(key) instanceof boolean[]) { checkBooleanArray(source, key, properties); } else if (properties.get(key) instanceof float[]) { checkFloatArray(source, key, properties); } else if (properties.get(key) instanceof double[]) { checkDoubleArray(source, key, properties); } else if (properties.get(key) instanceof short[]) { checkShortArray(source, key, properties); } else if (properties.get(key) instanceof long[]) { checkLongArray(source, key, properties); } else { assertEquals(properties.get(key).toString(), source.get(key).getAsString()); } } checkLabels(source, labels); }
From source file:com.graphaware.module.es.proc.ESModuleEndToEndProcTestAdvanced.java
License:Open Source License
public void testEsMapping(boolean node) { String itemType = node ? "node" : "relationship"; // match all items try (Transaction tx = getDatabase().beginTx()) { Result result = getDatabase().execute("CALL ga.es." + itemType + "Mapping() YIELD json return json"); List<String> columns = result.columns(); assertEquals(columns.size(), 1); Map<String, Object> next = result.next(); assertTrue(next.get("json") instanceof String); JsonObject e = new JsonParser().parse((String) next.get("json")).getAsJsonObject(); assertTrue(e.has("mappings")); assertTrue(e.get("mappings").isJsonObject()); // item types e.get("mappings").getAsJsonObject().entrySet().stream().forEach(typeEntry -> { // item type assertTrue(typeEntry.getKey() instanceof String); assertEquals(typeEntry.getKey(), itemType); // item properties assertTrue(typeEntry.getValue() instanceof JsonObject); JsonObject typeProps = (JsonObject) typeEntry.getValue(); assertTrue(typeProps.has("properties")); JsonObject propertiesMapping = typeProps.get("properties").getAsJsonObject(); propertiesMapping.entrySet().stream().forEach(propertyMapping -> { // property key assertTrue(propertyMapping.getKey() instanceof String); // property mapping info assertTrue(propertyMapping.getValue() instanceof JsonObject); JsonObject propertyInfo = (JsonObject) propertyMapping.getValue(); assertTrue(propertyInfo.has("type")); });/*from w ww .j a v a2 s .co m*/ String categField = node ? AdvancedMapping.LABELS_FIELD : AdvancedMapping.RELATIONSHIP_FIELD; assertTrue(propertiesMapping.has(categField)); assertTrue(propertiesMapping.get(categField).isJsonObject()); JsonObject categMapping = propertiesMapping.get(categField).getAsJsonObject(); // categ field has type:string categMapping.get("type").isJsonPrimitive(); assertEquals(categMapping.get("type").getAsString(), "string"); // categ field has fields:{raw:{type:string, index:not_analyzed}} assertTrue(categMapping.get("fields").isJsonObject()); assertTrue(categMapping.get("fields").getAsJsonObject().has("raw")); assertTrue(categMapping.get("fields").getAsJsonObject().get("raw").isJsonObject()); JsonObject rawField = categMapping.get("fields").getAsJsonObject().get("raw").getAsJsonObject(); // raw categ field assertTrue(rawField.has("type")); assertTrue(rawField.get("type").isJsonPrimitive()); assertEquals(rawField.get("type").getAsString(), "string"); assertTrue(rawField.has("index")); assertTrue(rawField.get("index").isJsonPrimitive()); assertEquals(rawField.get("index").getAsString(), "not_analyzed"); }); tx.success(); } }
From source file:com.gsaul.AethonSimulator.RuntimeTypeAdapterFactory.java
License:Apache License
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (type.getRawType() != baseType) { return null; }//from ww w . j a v a 2 s . com final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>(); final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>(); for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) { TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue())); labelToDelegate.put(entry.getKey(), delegate); subtypeToDelegate.put(entry.getValue(), delegate); } return new TypeAdapter<R>() { @Override public R read(JsonReader in) throws IOException { JsonElement jsonElement = Streams.parse(in); JsonElement labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName); //used to be .remove(typeFieldName); if (labelJsonElement == null) { throw new JsonParseException("cannot deserialize " + baseType + " because it does not define a field named " + typeFieldName); } String label = labelJsonElement.getAsString(); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label); if (delegate == null) { throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label + "; did you forget to register a subtype?"); } return delegate.fromJsonTree(jsonElement); } @Override public void write(JsonWriter out, R value) throws IOException { Class<?> srcType = value.getClass(); String label = subtypeToLabel.get(srcType); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType); if (delegate == null) { throw new JsonParseException( "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?"); } JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); if (jsonObject.has(typeFieldName)) { throw new JsonParseException("cannot serialize " + srcType.getName() + " because it already defines a field named " + typeFieldName); } JsonObject clone = new JsonObject(); clone.add(typeFieldName, new JsonPrimitive(label)); for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue()); } Streams.write(clone, out); } }.nullSafe(); }
From source file:com.gst.batch.service.ResolutionHelper.java
License:Apache License
/** * Returns a BatchRequest after dependency resolution. It takes a request * and the response of the request it is dependent upon as its arguments and * change the body or relativeUrl of the request according to parent * Request.//ww w . ja v a2s . com * * @param request * @param lastResponse * @return BatchRequest */ public BatchRequest resoluteRequest(final BatchRequest request, final BatchResponse parentResponse) { // Create a duplicate request final BatchRequest br = request; final JsonModel responseJsonModel = JsonModel.model(parentResponse.getBody()); // Gets the body from current Request as a JsonObject final JsonObject jsonRequestBody = this.fromJsonHelper.parse(request.getBody()).getAsJsonObject(); JsonObject jsonResultBody = new JsonObject(); // Iterate through each element in the requestBody to find dependent // parameter for (Entry<String, JsonElement> element : jsonRequestBody.entrySet()) { final String key = element.getKey(); final JsonElement value = resolveDependentVariables(element, responseJsonModel); jsonResultBody.add(key, value); } // Set the body after dependency resolution br.setBody(jsonResultBody.toString()); // Also check the relativeUrl for any dependency resolution String relativeUrl = request.getRelativeUrl(); if (relativeUrl.contains("$.")) { String queryParams = ""; if (relativeUrl.contains("?")) { queryParams = relativeUrl.substring(relativeUrl.indexOf("?")); relativeUrl = relativeUrl.substring(0, relativeUrl.indexOf("?")); } final String[] parameters = relativeUrl.split("/"); for (String parameter : parameters) { if (parameter.contains("$.")) { final String resParamValue = responseJsonModel.get(parameter).toString(); relativeUrl = relativeUrl.replace(parameter, resParamValue); br.setRelativeUrl(relativeUrl + queryParams); } } } return br; }
From source file:com.gst.batch.service.ResolutionHelper.java
License:Apache License
private JsonElement processJsonObject(final JsonObject jsObject, final JsonModel responseJsonModel) { JsonObject valueObj = new JsonObject(); for (Entry<String, JsonElement> element : jsObject.entrySet()) { final String key = element.getKey(); final JsonElement value = resolveDependentVariable(element.getValue(), responseJsonModel); valueObj.add(key, value);//w w w. j av a2 s . co m } return valueObj; }
From source file:com.gst.infrastructure.core.serialization.FromJsonHelper.java
License:Apache License
public void checkForUnsupportedParameters(final JsonObject object, final Set<String> supportedParams) { if (object == null) { throw new InvalidParameterException(); }//w ww . java2 s . c om final Set<Entry<String, JsonElement>> entries = object.entrySet(); final List<String> unsupportedParameterList = new ArrayList<>(); for (final Entry<String, JsonElement> providedParameter : entries) { if (!supportedParams.contains(providedParameter.getKey())) { unsupportedParameterList.add(providedParameter.getKey()); } } if (!unsupportedParameterList.isEmpty()) { throw new UnsupportedParameterException(unsupportedParameterList); } }
From source file:com.haulmont.cuba.core.app.importexport.EntityImportViewBuilder.java
License:Apache License
protected EntityImportView buildFromJsonObject(JsonObject jsonObject, MetaClass metaClass) { EntityImportView view = new EntityImportView(metaClass.getJavaClass()); for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) { String propertyName = entry.getKey(); MetaProperty metaProperty = metaClass.getProperty(propertyName); if (metaProperty != null) { Range propertyRange = metaProperty.getRange(); Class<?> propertyType = metaProperty.getJavaType(); if (propertyRange.isDatatype() || propertyRange.isEnum()) { if (security.isEntityAttrUpdatePermitted(metaClass, propertyName)) view.addLocalProperty(propertyName); } else if (propertyRange.isClass()) { if (Entity.class.isAssignableFrom(propertyType)) { if (metadataTools.isEmbedded(metaProperty)) { MetaClass propertyMetaClass = metadata.getClass(propertyType); JsonElement propertyJsonObject = entry.getValue(); if (!propertyJsonObject.isJsonObject()) { throw new RuntimeException("JsonObject was expected for property " + propertyName); }/*from w w w .j a va 2 s.c o m*/ if (security.isEntityAttrUpdatePermitted(metaClass, propertyName)) { EntityImportView propertyImportView = buildFromJsonObject( propertyJsonObject.getAsJsonObject(), propertyMetaClass); view.addEmbeddedProperty(propertyName, propertyImportView); } } else { MetaClass propertyMetaClass = metadata.getClass(propertyType); if (metaProperty.getType() == MetaProperty.Type.COMPOSITION) { JsonElement propertyJsonObject = entry.getValue(); if (security.isEntityAttrUpdatePermitted(metaClass, propertyName)) { if (propertyJsonObject.isJsonNull()) { //in case of null we must add such import behavior to update the reference with null value later if (metaProperty.getRange() .getCardinality() == Range.Cardinality.MANY_TO_ONE) { view.addManyToOneProperty(propertyName, ReferenceImportBehaviour.IGNORE_MISSING); } else { view.addOneToOneProperty(propertyName, ReferenceImportBehaviour.IGNORE_MISSING); } } else { if (!propertyJsonObject.isJsonObject()) { throw new RuntimeException( "JsonObject was expected for property " + propertyName); } EntityImportView propertyImportView = buildFromJsonObject( propertyJsonObject.getAsJsonObject(), propertyMetaClass); if (metaProperty.getRange() .getCardinality() == Range.Cardinality.MANY_TO_ONE) { view.addManyToOneProperty(propertyName, propertyImportView); } else { view.addOneToOneProperty(propertyName, propertyImportView); } } } } else { if (security.isEntityAttrUpdatePermitted(metaClass, propertyName)) if (metaProperty.getRange().getCardinality() == Range.Cardinality.MANY_TO_ONE) { view.addManyToOneProperty(propertyName, ReferenceImportBehaviour.ERROR_ON_MISSING); } else { view.addOneToOneProperty(propertyName, ReferenceImportBehaviour.ERROR_ON_MISSING); } } } } else if (Collection.class.isAssignableFrom(propertyType)) { MetaClass propertyMetaClass = metaProperty.getRange().asClass(); switch (metaProperty.getRange().getCardinality()) { case MANY_TO_MANY: if (security.isEntityAttrUpdatePermitted(metaClass, propertyName)) view.addManyToManyProperty(propertyName, ReferenceImportBehaviour.ERROR_ON_MISSING, CollectionImportPolicy.REMOVE_ABSENT_ITEMS); break; case ONE_TO_MANY: if (metaProperty.getType() == MetaProperty.Type.COMPOSITION) { JsonElement compositionJsonArray = entry.getValue(); if (!compositionJsonArray.isJsonArray()) { throw new RuntimeException( "JsonArray was expected for property " + propertyName); } EntityImportView propertyImportView = buildFromJsonArray( compositionJsonArray.getAsJsonArray(), propertyMetaClass); if (security.isEntityAttrUpdatePermitted(metaClass, propertyName)) view.addOneToManyProperty(propertyName, propertyImportView, CollectionImportPolicy.REMOVE_ABSENT_ITEMS); } break; } } } } } return view; }