List of usage examples for com.google.gson JsonObject size
public int size()
From source file:com.balajeetm.mystique.util.gson.lever.JsonComparator.java
License:Open Source License
/** * Checks if is subset.// ww w .j av a2s . c o m * * @param tag the tag * @param subset the subset * @param actual the actual * @param result the result * @return the myst result */ private Comparison isSubset(String tag, JsonElement subset, JsonElement actual, Comparison result) { subset = jsonLever.asJsonElement(subset, JsonNull.INSTANCE); actual = jsonLever.asJsonElement(actual, JsonNull.INSTANCE); if (jsonLever.isNotNull(subset) && jsonLever.isNull(actual)) { result.setResult(Boolean.FALSE); result.addMsg(String.format("The field %s of actual is null", tag)); } else if (!subset.getClass().getCanonicalName().equals(actual.getClass().getCanonicalName())) { result.setResult(Boolean.FALSE); result.addMsg(String.format("The field %s of expected and actual are not of the same type", tag)); } else { if (subset.isJsonObject()) { JsonObject subJson = jsonLever.asJsonObject(subset); JsonObject actJson = jsonLever.asJsonObject(actual); Set<Entry<String, JsonElement>> entrySet = subJson.entrySet(); for (Entry<String, JsonElement> entry : entrySet) { String key = entry.getKey(); JsonElement value = entry.getValue(); JsonElement actualValue = actJson.get(key); isSubset(key, value, actualValue, result); } } else if (subset.isJsonArray()) { JsonArray subJson = jsonLever.asJsonArray(subset); JsonArray actJson = jsonLever.asJsonArray(actual); if (subJson.size() != actJson.size()) { result.setResult(Boolean.FALSE); result.addMsg(String.format("The field %s of expected and actual are not of same size", tag)); } else { for (int i = 0; i < subJson.size(); i++) { isSubset(tag, subJson.get(i), actJson.get(i), result); } } } else { if (!subset.equals(actual)) { result.setResult(Boolean.FALSE); result.addMsg(String.format("The field %s of expected and actual are not same", tag)); } } } return result; }
From source file:com.google.gerrit.elasticsearch.ElasticIndexVersionDiscovery.java
License:Apache License
List<String> discover(String prefix, String indexName) throws IOException { String name = prefix + indexName + "_"; JestResult result = client.execute(new GetAliases.Builder().addIndex(name + "*").build()); if (result.isSucceeded()) { JsonObject object = result.getJsonObject().getAsJsonObject(); List<String> versions = new ArrayList<>(object.size()); for (Entry<String, JsonElement> entry : object.entrySet()) { versions.add(entry.getKey().replace(name, "")); }/*w ww .j a va2 s . co m*/ return versions; } return Collections.emptyList(); }
From source file:com.google.gwtjsonrpc.server.MapDeserializer.java
License:Apache License
public Map<Object, Object> deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { final Type kt = ((ParameterizedType) typeOfT).getActualTypeArguments()[0]; final Type vt = ((ParameterizedType) typeOfT).getActualTypeArguments()[1]; if (json.isJsonNull()) { return null; }//from ww w. jav a2 s . c o m if (kt == String.class) { if (!json.isJsonObject()) { throw new JsonParseException("Expected object for map type"); } final JsonObject p = (JsonObject) json; final Map<Object, Object> r = createInstance(typeOfT); for (final Map.Entry<String, JsonElement> e : p.entrySet()) { final Object v = context.deserialize(e.getValue(), vt); r.put(e.getKey(), v); } return r; } else { if (!json.isJsonArray()) { throw new JsonParseException("Expected array for map type"); } final JsonArray p = (JsonArray) json; final Map<Object, Object> r = createInstance(typeOfT); for (int n = 0; n < p.size();) { final Object k = context.deserialize(p.get(n++), kt); final Object v = context.deserialize(p.get(n++), vt); r.put(k, v); } return r; } }
From source file:com.nuvolect.securesuite.webserver.connector.CmdUpload.java
License:Open Source License
/** * Collect chunk data until last chuck is received, then assemble the uploaded file. * * EXAMPLE, 60.3MB file:/*from ww w .ja v a 2 s . c o m*/ * "cmd" -> "upload" * "mtime[]" -> "1489684754" * "cid" -> "697767115" * "upload_path[]" -> "l0_L3Rlc3QvdG1w" * "range" -> "0,10485760,60323475" x "post_uploads" -> "[{"file_path":"\/data\/user\/0\/com.nuvolect.securesuite.debug\/cache\/NanoHTTPD-340250228","file_name":"blob"}]" * "dropWith" -> "0" * "chunk" -> "kepler_7_weeks.mp4.0_5.part" x "target" -> "l0_L3Rlc3QvdG1w" * "unique_id" -> "1489174097708" * "upload[]" -> "blob" * "queryParameterStrings" -> "cmd=ls&target=l0_L3Rlc3QvdG1w&intersect%5B%5D=kepler_7_weeks.mp4&_=1489697705506" * "uri" -> "/connector" */ private InputStream chunksUpload(@NonNull Map<String, String> params, OmniFile targetDirectory) { String url = params.get("url"); String targetVolumeId = targetDirectory.getVolumeId(); JsonObject wrapper = new JsonObject(); String chunk = params.get("chunk"); String[] parts = chunk.split(Pattern.quote(".")); String[] twoNumbers = parts[parts.length - 2].split("_"); int chunkMax = Integer.valueOf(twoNumbers[1]); String targetFilename = parts[0] + "." + parts[1]; JsonObject fileChunks = new JsonObject(); // Chunks for the target file /** * Parse the uploads array and collect specific of the current chunk. * Metadata for each chunk is saved in a JSONObject using the chunk filename as the key. * Move each chunk from the app:/cache folder to app:/chunk. * When all chunks are uploaded, the target is assembled and chunks deleted. */ JsonParser parser = new JsonParser(); JsonArray postUploads = parser.parse(params.get("post_uploads")).getAsJsonArray(); for (int i = 0; i < postUploads.size(); i++) { JsonObject postUpload = postUploads.get(i).getAsJsonObject(); //app: /cache/xxx String cachePath = postUpload.get(CConst.FILE_PATH).getAsString(); File cacheFile = new File(cachePath); String chunkPath = chunkDirPath + FilenameUtils.getName(cachePath); File chunkFile = new File(chunkPath); /** * Move the chunk, otherwise Nanohttpd will delete it. */ cacheFile.renameTo(chunkFile); JsonObject chunkObj = new JsonObject(); chunkObj.addProperty("filepath", chunkPath); chunkObj.addProperty("range", params.get("range")); if (fileUploads.has(targetFilename)) { fileChunks = fileUploads.get(targetFilename).getAsJsonObject(); } else { fileChunks = new JsonObject(); } fileChunks.add(chunk, chunkObj); fileUploads.add(targetFilename, fileChunks); } /** * If not complete, return with intermediate results */ if (fileChunks.size() <= chunkMax) { wrapper.add("added", new JsonArray()); return getInputStream(wrapper); } try { int totalSize = 0; /** * All chunks are uploaded. Iterate over the chunk meta data and assemble the file. * Open the target file. */ OmniFile destFile = new OmniFile(targetVolumeId, targetDirectory.getPath() + File.separator + targetFilename); OutputStream destOutputStream = destFile.getOutputStream(); String error = null; for (int i = 0; i <= chunkMax; i++) { String chunkKey = targetFilename + "." + i + "_" + chunkMax + ".part"; if (!fileChunks.has(chunk)) { error = "Missing chunk: " + chunkKey; break; } JsonObject chunkObj = fileChunks.get(chunkKey).getAsJsonObject(); String chunkPath = chunkObj.get("filepath").getAsString(); File sourceFile = new File(chunkPath); if (sourceFile.exists()) { LogUtil.log(LogUtil.LogType.CMD_UPLOAD, "File exists: " + sourceFile.getPath()); } else { LogUtil.log(LogUtil.LogType.CMD_UPLOAD, "File NOT exists: " + sourceFile.getPath()); break; } FileInputStream fis = new FileInputStream(sourceFile); //TODO error check range of bytes from each chunk and compare with chunk bytes copied /** * Append next chunk to the destination file. */ int bytesCopied = OmniFiles.copyFileLeaveOutOpen(fis, destOutputStream); totalSize += bytesCopied; LogUtil.log(LogUtil.LogType.CMD_UPLOAD, "Bytes copied, total: " + bytesCopied + ", " + totalSize); // Delete temp file if (!sourceFile.delete()) { error = "Delete temp file failed : " + sourceFile.getPath(); LogUtil.log(LogUtil.LogType.CMD_UPLOAD, error); break; } else { LogUtil.log(LogUtil.LogType.CMD_UPLOAD, "Removed " + sourceFile.getName()); } } destOutputStream.flush(); destOutputStream.close(); // Done with this file, clean up. fileUploads.remove(targetFilename); JsonArray added = new JsonArray(); if (error == null) { JsonObject fileObj = FileObj.makeObj(targetVolumeId, destFile, url); added.add(fileObj); wrapper.add("added", added); LogUtil.log(LogUtil.LogType.CMD_UPLOAD, "File upload success: " + destFile.getPath()); } else { JsonArray warning = new JsonArray(); warning.add(error); wrapper.add("warning", warning); } return getInputStream(wrapper); } catch (IOException e) { logException(CmdUpload.class, e); clearChunkFiles(); } return null; }
From source file:com.simonellistonball.nifi.processors.OpenScoringProcessor.OpenScoringProcessor.java
License:Apache License
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { FlowFile flowFile = session.get();/*w w w . ja v a2 s. c o m*/ if (flowFile == null) { return; } if (id.get() == null) { try { this.id.set(postModel(context.getProperty(OPENSCORING_URL).getValue(), context.getProperty(PMML).getValue())); } catch (IOException e) { getLogger().error("Failure to post model", e); flowFile = session.penalize(flowFile); session.transfer(flowFile, FAILURE_MODEL); } } final String openScoringUrl = context.getProperty(OPENSCORING_URL).getValue(); try { final boolean isCsv = flowFile.getAttribute("mime.type") == "text/csv"; StringBuilder urlBuilder = new StringBuilder(openScoringUrl).append("/model/").append(id); if (isCsv) { urlBuilder.append("/csv"); } final PostMethod post = new PostMethod(urlBuilder.toString()); final String contentType; if (isCsv) { contentType = "text/plain"; } else { contentType = "application/json"; } post.setRequestHeader("Content-Type", contentType); session.read(flowFile, new InputStreamCallback() { @Override public void process(InputStream in) throws IOException { post.setRequestEntity(new InputStreamRequestEntity(in, contentType)); } }); httpClient.executeMethod(post); if (isCsv) { // add the results to the input flowFile = session.write(flowFile, new OutputStreamCallback() { @Override public void process(OutputStream out) throws IOException { IOUtils.copy(post.getResponseBodyAsStream(), out); } }); session.transfer(flowFile, SUCCESS); } else { JsonParser parser = new JsonParser(); JsonElement parsed = parser .parse(new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream(), "UTF-8"))); JsonObject newAttributes = parsed.getAsJsonObject().getAsJsonObject("result"); final Map<String, String> attributes = new HashMap<String, String>(newAttributes.size()); for (Entry<String, JsonElement> attribute : newAttributes.entrySet()) { if (!attribute.getValue().isJsonNull()) { attributes.put(attribute.getKey(), attribute.getValue().getAsString()); } } if (!attributes.isEmpty()) { flowFile = session.putAllAttributes(flowFile, attributes); } session.transfer(flowFile, SUCCESS); } } catch (Exception e) { getLogger().error("Failure to score model", e); flowFile = session.penalize(flowFile); session.transfer(flowFile, FAILURE); } }
From source file:com.tesla.framework.common.util.json.JSONHelper.java
License:Apache License
/** * @param json//from w ww. j a v a 2s. com * @return ???null????? */ @Nullable public static ContentValues json2ContentValues(@NonNull JsonObject json) { Preconditions.checkNotNull(json); if (json.size() == 0) return null; ContentValues values = new ContentValues(); Set<Map.Entry<String, JsonElement>> set = json.entrySet(); Iterator<Map.Entry<String, JsonElement>> itr = set.iterator(); while (itr.hasNext()) { Map.Entry<String, JsonElement> entry = itr.next(); if (entry == null) continue; String key = entry.getKey(); if (TextUtils.isEmpty(key)) continue; Object value = entry.getValue(); if (value == null) { continue; } if (value instanceof String) { values.put(key, (String) value); } else if (value instanceof Integer) { values.put(key, (Integer) value); } else if (value instanceof Float) { values.put(key, (Float) value); } else { } } return values; }
From source file:de.dfki.mmf.attributeselection.AttributeSelectionAlgorithm.java
License:Open Source License
/** * * @param identifierSet//from ww w .j ava2 s . c om * @param saliencyEndResultThreshold * @return shortest attribute set where all used attributes have a saliency value higher than certain threshold */ public JsonObject getShortestMostSalientAboveThresholdIdentifier(Set<JsonObject> identifierSet, double saliencyEndResultThreshold) { if (identifierSet == null || identifierSet.isEmpty()) { return null; } ArrayList<JsonObject> resultList = new ArrayList<>(identifierSet); Collections.sort(resultList, new CompareSize()); CompareSaliency cmpSaliency = new CompareSaliency(); JsonObject resultMap = new JsonObject(); double oldSaliencyValue = 0.0; int oldSize = resultList.get(0).size(); //check if list element has a saliency value above the threshold boolean foundVisible = false; //use same sigmoid function to normalize threshold which is used to normalize saliency value saliencyEndResultThreshold = saliencyEndResultThreshold / (Math.sqrt(1 + Math.pow(saliencyEndResultThreshold, 2.0))); for (int i = 0; i < resultList.size(); i++) { double saliencyValue = cmpSaliency.computeSaliencyValue(resultList.get(i)); int size = resultList.get(i).size(); //accept only greater size if no visible one has been found yet if (size > oldSize && foundVisible) { break; } //get the most visible one for the smallest possible size if (saliencyValue > saliencyEndResultThreshold && saliencyValue > oldSaliencyValue) { foundVisible = true; resultMap = new JsonObject(); Set<Map.Entry<String, JsonElement>> entrySet = resultList.get(i).entrySet(); for (Map.Entry<String, JsonElement> currentEntry : entrySet) { resultMap.add(currentEntry.getKey(), currentEntry.getValue()); } oldSaliencyValue = saliencyValue; oldSize = size; } } //no JsonObject has saliency value above required threshold -> take last element in list, will have highest value if (resultMap.size() == 0) { Set<Map.Entry<String, JsonElement>> entrySet = resultList.get(resultList.size() - 1).entrySet(); for (Map.Entry<String, JsonElement> entry : entrySet) { resultMap.add(entry.getKey(), entry.getValue()); } } return resultMap; }
From source file:de.dfki.mmf.attributeselection.AttributeSelectionAlgorithm.java
License:Open Source License
/** * * @param originalObject/*from w w w. j ava2 s .com*/ * @return powerset of original set */ private Set<JsonObject> powerSet(JsonObject originalObject) { HashSet<JsonObject> sets = new HashSet<>(); //check if termination condition is reached if (originalObject.size() == 0) { sets.add(new JsonObject()); return sets; } JsonObject head = new JsonObject(); JsonObject rest = new JsonObject(); //retrieve first object from current set and save it in "head", the remaining objects are saved in "rest" for (Map.Entry<String, JsonElement> entry : originalObject.entrySet()) { if (head.size() < 1) { head.add(entry.getKey(), entry.getValue()); } else { rest.add(entry.getKey(), entry.getValue()); } } //recursive call for combining all possibilities for (JsonObject set : powerSet(rest)) { JsonObject newSet = new JsonObject(); newSet.add(head.entrySet().iterator().next().getKey(), head.entrySet().iterator().next().getValue()); for (Map.Entry<String, JsonElement> entry : set.entrySet()) { newSet.add(entry.getKey(), entry.getValue()); } sets.add(newSet); sets.add(set); } return sets; }
From source file:de.dfki.mmf.input.worldmodel.OwlModelRetrieval.java
License:Open Source License
/** * Retrieve properties of the individuals in the owl model and save them in JsonObject */// w w w. ja v a2 s . co m public ArrayList<JsonObject> processRetrieval() { //resulting list of Json objects ArrayList<JsonObject> owlObjects = new ArrayList<>(); Collection<OWLClassExpression> entityClasses; Set<OWLNamedIndividual> individuals = ontology.getIndividualsInSignature(); //go over all instances of the class for (OWLNamedIndividual ind : individuals) { JsonObject owlObject = new JsonObject(); // insert object properties and its corresponding values for the current individual found in the owl model for (OWLObjectProperty p : ontology.getObjectPropertiesInSignature()) { NodeSet<OWLNamedIndividual> individualValues = reasoner.getObjectPropertyValues(ind, p); Set<OWLNamedIndividual> values = individualValues.getFlattened(); //get the name of the property String propertyName = p.getIRI().getShortForm(); if (propertyName.toLowerCase().startsWith("has")) { propertyName = propertyName.substring(3); } if (!values.isEmpty()) { //add found values to array Iterator<OWLNamedIndividual> iter = values.iterator(); JsonArray array = new JsonArray(); while (iter.hasNext()) { array.add(iter.next().getIRI().getShortForm()); } //add property-value pair to the Json object owlObject.add(propertyName, array); } } //retrieve all the data properties and corresponding value from the model as well for (OWLDataProperty d : ontology.getDataPropertiesInSignature()) { Set<OWLLiteral> values = reasoner.getDataPropertyValues(ind, d); String propertyName = d.getIRI().getShortForm(); if (propertyName.startsWith("has")) { propertyName = propertyName.substring(3); } if (!values.isEmpty()) { String[] resultSplit = new String[values.size()]; int i = 0; //check the datatype of the corresponding literal for (OWLLiteral literal : values) { OWLDatatype datatype = literal.getDatatype(); if (datatype.isDouble()) { resultSplit[i] = "" + literal.parseDouble(); } else if (datatype.isString()) { resultSplit[i] = literal.getLiteral(); } else if (datatype.isBoolean()) { resultSplit[i] = "" + literal.parseBoolean(); } else if (datatype.isInteger()) { resultSplit[i] = "" + literal.parseInteger(); } else if (datatype.isFloat()) { resultSplit[i] = "" + literal.parseFloat(); } i++; } //add values of data property to array JsonArray array = new JsonArray(); for (int j = 0; j < resultSplit.length; j++) { array.add(resultSplit[j]); } //add property-value pair to Json object owlObject.add(propertyName, array); } } if (owlObject.size() >= 1) { //add "worldobjectid" String instanceName = ind.getIRI().getShortForm(); owlObject.addProperty("worldobjectid", instanceName); //retrieve the type of the indivdual and add it as "worldobjecttype" entityClasses = EntitySearcher.getTypes(ind, ontology); JsonArray typeArray = new JsonArray(); for (OWLClassExpression entityClass : entityClasses) { typeArray.add(entityClass.asOWLClass().getIRI().getShortForm()); } owlObject.add("worldobjecttype", typeArray); //add Json object to list owlObjects.add(owlObject); } } return owlObjects; }
From source file:io.siddhi.extension.io.file.util.JsonSourceMapper.java
License:Open Source License
private Event[] convertToEventArrayForDefaultMapping(String eventString) { Gson gson = new Gson(); JsonObject[] eventObjects = gson.fromJson(eventString, JsonObject[].class); Event[] events = new Event[eventObjects.length]; int index = 0; JsonObject eventObj = null; for (JsonObject jsonEvent : eventObjects) { if (jsonEvent.has(DEFAULT_JSON_EVENT_IDENTIFIER)) { eventObj = jsonEvent.get(DEFAULT_JSON_EVENT_IDENTIFIER).getAsJsonObject(); if (failOnMissingAttribute && eventObj.size() < streamAttributes.size()) { log.error("Json message " + eventObj.toString() + " contains missing attributes. " + "Hence dropping the message."); continue; }// w ww . j a va 2 s . c o m } else { log.error("Default json message " + eventObj.toString() + " in the array does not have the valid event identifier \"event\". " + "Hence dropping the message."); continue; } Event event = new Event(streamAttributes.size()); Object[] data = event.getData(); int position = 0; for (Attribute attribute : streamAttributes) { String attributeName = attribute.getName(); Attribute.Type type = attribute.getType(); String attributeValue = eventObj.get(attributeName).getAsString(); if (attributeValue == null) { data[position++] = null; } else { data[position++] = attributeConverter.getPropertyValue(attributeValue, type); } } events[index++] = event; } return Arrays.copyOfRange(events, 0, index); }