List of usage examples for javax.json JsonObject entrySet
Set<Map.Entry<K, V>> entrySet();
From source file:eu.forgetit.middleware.component.Extractor.java
public void videoNDDAnalysis(Exchange exchange) { logger.debug("New message retrieved"); JsonObject jsonBody = MessageTools.getBody(exchange); JsonObjectBuilder job = Json.createObjectBuilder(); for (Entry<String, JsonValue> entry : jsonBody.entrySet()) { job.add(entry.getKey(), entry.getValue()); }//from w w w . j av a 2 s. co m if (jsonBody != null) { //String videoPaths = getVideoPath(jsonBody); String videoPath = jsonBody.getString("videoPath"); logger.debug("Retrieved Video Path: " + videoPath); job.add("videoPath", videoPath); //String method = jsonBody.getString("method"); //System.out.println("Retrieved VAM: "+method); // ONE video per call if (videoPath != null && !videoPath.isEmpty()) { logger.debug("Executing Video Analysis Method: Near Duplicate Detection"); String response_tmp = service.video_ndd_request(videoPath); logger.debug("Video NDD Analysis method result:\n" + response_tmp); // call id is returned at the response String callid; String[] callid_tmp = response_tmp.split("::"); callid = callid_tmp[1].trim(); String response = service.video_ndd_result(callid); logger.debug("Video NDD result:\n" + response); job.add("result", response); } else { logger.debug("Unable to process video, wrong request"); job.add("result", "Unable to process video, wrong request"); } exchange.getOut().setBody(job.build().toString()); exchange.getOut().setHeaders(exchange.getIn().getHeaders()); } }
From source file:com.open.shift.support.controller.SupportResource.java
@GET @Produces(MediaType.APPLICATION_JSON)/*from w ww. j a v a 2s . co m*/ @Path("piechart") public JsonObject generatePieChart() throws Exception { URL u = ctx.getResource("/WEB-INF/classes/templates/pie.json"); String pieJson = null; if (OS.indexOf("win") >= 0) { pieJson = u.toString().substring(6); } else if (OS.indexOf("nux") >= 0) { pieJson = u.toString().substring(5); } JsonReader reader = Json.createReader(new FileReader(pieJson)); JsonObject main = reader.readObject(); JsonObjectBuilder title = Json.createObjectBuilder().add("text", "Companies Contribution in Deposits"); JsonArrayBuilder data = Json.createArrayBuilder().add(Json.createArrayBuilder().add("Infosys").add(45.0)) .add(Json.createArrayBuilder().add("TCS").add(26.8)) .add(Json.createArrayBuilder().add("Oracle").add(8.5)) .add(Json.createArrayBuilder().add("Accenture").add(6.2)).add(Json.createObjectBuilder() .add("name", "IBM").add("y", 12.8).add("sliced", true).add("selected", true)); JsonArrayBuilder series = Json.createArrayBuilder().add( Json.createObjectBuilder().add("type", "pie").add("name", "Deposit Contributed").add("data", data)); JsonObjectBuilder mainJsonObj = Json.createObjectBuilder(); for (Map.Entry<String, JsonValue> entrySet : main.entrySet()) { String key = entrySet.getKey(); JsonValue value = entrySet.getValue(); mainJsonObj.add(key, value); } mainJsonObj.add("title", title.build()).add("series", series.build()); return mainJsonObj.build(); }
From source file:com.open.shift.support.controller.SupportResource.java
@GET @Produces(MediaType.APPLICATION_JSON)// www . j ava 2 s . c om @Path("areachart") public JsonObject generateAreaChart() throws Exception { System.out.println("The injected hashcode is " + this.supportDAO); int usa[] = { 0, 0, 0, 0, 0, 6, 11, 32, 110, 235, 369, 640, 1005, 1436, 2063, 3057, 4618, 6444, 9822, 15468, 20434, 24126, 27387, 29459, 31056, 31982, 32040, 31233, 29224, 27342, 26662, 26956, 27912, 28999, 28965, 27826, 25579, 25722, 24826, 24605, 24304, 23464, 23708, 24099, 24357, 24237, 24401, 24344, 23586, 22380, 21004, 17287, 14747, 13076, 12555, 12144, 11009, 10950, 10871, 10824, 10577, 10527, 10475, 10421, 10358, 10295, 10104 }; int ussr[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 25, 50, 120, 150, 200, 426, 660, 869, 1060, 1605, 2471, 3322, 4238, 5221, 6129, 7089, 8339, 9399, 10538, 11643, 13092, 14478, 15915, 17385, 19055, 21205, 23044, 25393, 27935, 30062, 32049, 33952, 35804, 37431, 39197, 45000, 43000, 41000, 39000, 37000, 35000, 33000, 31000, 29000, 27000, 25000, 24000, 23000, 22000, 21000, 20000, 19000, 18000, 18000, 17000, 16000 }; URL u = ctx.getResource("/WEB-INF/classes/templates/area.json"); String areaJson = null; if (OS.indexOf("win") >= 0) { areaJson = u.toString().substring(6); } else if (OS.indexOf("nux") >= 0) { areaJson = u.toString().substring(5); } System.out.println("The areaJson is " + areaJson); JsonReader reader = Json.createReader(new FileReader(areaJson)); JsonObject main = reader.readObject(); JsonObject yaxis = main.getJsonObject("yAxis"); JsonObjectBuilder title = Json.createObjectBuilder().add("text", "US and USSR Deposits"); JsonObjectBuilder ytitle = Json.createObjectBuilder().add("text", "Amount Deposisted"); JsonArrayBuilder usaData = Json.createArrayBuilder(); for (Integer usa1 : usa) { usaData.add(usa1); } JsonArrayBuilder ussrData = Json.createArrayBuilder(); for (Integer uss1 : ussr) { ussrData.add(uss1); } JsonObjectBuilder usaSeries = Json.createObjectBuilder().add("name", "USA").add("data", usaData); JsonObjectBuilder ussrSeries = Json.createObjectBuilder().add("name", "USSR").add("data", ussrData); JsonArrayBuilder series = Json.createArrayBuilder().add(usaSeries).add(ussrSeries); //main json object builder JsonObjectBuilder mainJsonObj = Json.createObjectBuilder(); for (Map.Entry<String, JsonValue> mainObj : main.entrySet()) { String key = mainObj.getKey(); JsonValue value = mainObj.getValue(); if (key.equalsIgnoreCase("yAxis")) { String yaxisLabel = "labels"; mainJsonObj.add(key, Json.createObjectBuilder().add(yaxisLabel, yaxis.getJsonObject(yaxisLabel)) .add("title", ytitle.build())); } else { mainJsonObj.add(key, value); } } mainJsonObj.add("title", title.build()).add("series", series.build()); return mainJsonObj.build(); }
From source file:eu.forgetit.middleware.component.Condensator.java
public void imageClustering_bkp(Exchange exchange) { logger.debug("New message retrieved"); JsonObject headers = MessageTools.getHeaders(exchange); long taskId = headers.getInt("taskId"); scheduler.updateTask(taskId, TaskStatus.RUNNING, "IMAGE CLUSTERING", null); MessageTools.setHeaders(exchange, headers); JsonObject jsonBody = MessageTools.getBody(exchange); if (jsonBody != null) { try {/*from w w w .j a v a 2 s .c o m*/ String jsonNofImagesElement = jsonBody.getString("numOfImages"); String minCLusteringImages = headers.getString("minClusteringImages"); int nofImages = 0; int minNofImages = 0; if (jsonNofImagesElement != null) nofImages = Integer.parseInt(jsonNofImagesElement); if (minCLusteringImages != null) minNofImages = Integer.parseInt(minCLusteringImages); else minNofImages = 0; String jsonImageAnalysisResult = jsonBody.getString("imageAnalysis-all"); if (jsonImageAnalysisResult != null) imageAnalysisResult = jsonImageAnalysisResult; logger.debug("Retrieved Image Analysis Result: " + imageAnalysisResult); String jsonMetadataDir = jsonBody.getString("sipMetadataDir"); if (jsonMetadataDir != null) sipMetadataDirPath = jsonMetadataDir; logger.debug("Retrieved SIP Metadata Directory: " + sipMetadataDirPath); if (nofImages >= minNofImages) { logger.debug("Executing Image Collection Clustering"); String response = service.request(imageAnalysisResult); logger.debug("Clustering result:\n" + response); File resultFile = new File(sipMetadataDirPath, "clustering.xml"); FileUtils.writeStringToFile(resultFile, response); JsonObjectBuilder job = Json.createObjectBuilder(); job.add("clustering", resultFile.getAbsolutePath()); for (Entry<String, JsonValue> entry : jsonBody.entrySet()) { job.add(entry.getKey(), entry.getValue()); } exchange.getIn().setBody(jsonBody.toString()); } else { logger.debug("Found only " + nofImages + " images, below threshold (" + minCLusteringImages + ")... skipping."); } } catch (NumberFormatException | IOException e) { e.printStackTrace(); } } else { JsonObjectBuilder job = Json.createObjectBuilder().add("taskStatus", TaskStatus.FAILED.toString()); for (Entry<String, JsonValue> entry : headers.entrySet()) { job.add(entry.getKey(), entry.getValue()); } MessageTools.setHeaders(exchange, headers); } }
From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java
JsonObject getResult(HttpResponse response, String body, String type) throws HTTPException, ParseException, IOException { int respStatusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); logger.trace(format("response status %d, HttpEntity %s ", respStatusCode, "" + entity)); String responseBody = entity != null ? EntityUtils.toString(entity) : null; logger.trace(format("responseBody: %s ", responseBody)); // If the status code in the response is greater or equal to the status code set in the client object then an exception will // be thrown, otherwise, we continue to read the response and return any error code that is less than 'statusCode' if (respStatusCode >= statusCode) { HTTPException e = new HTTPException( format("%s request to %s failed request body %s. Response: %s", type, url, body, responseBody), respStatusCode);//from www . j a v a 2s .c o m logger.error(e.getMessage()); throw e; } if (responseBody == null) { HTTPException e = new HTTPException( format("%s request to %s failed request body %s with null response body returned.", type, url, body), respStatusCode); logger.error(e.getMessage()); throw e; } logger.debug("Status: " + respStatusCode); JsonReader reader = Json.createReader(new StringReader(responseBody)); JsonObject jobj = (JsonObject) reader.read(); JsonObjectBuilder job = Json.createObjectBuilder(); job.add("statusCode", respStatusCode); JsonArray errors = jobj.getJsonArray("errors"); // If the status code is greater than or equal to 400 but less than or equal to the client status code setting, // then encountered an error and we return back the status code, and log the error rather than throwing an exception. if (respStatusCode < statusCode && respStatusCode >= 400) { if (errors != null && !errors.isEmpty()) { JsonObject jo = errors.getJsonObject(0); String errorMsg = format( "[HTTP Status Code: %d] - %s request to %s failed request body %s error message: [Error Code %d] - %s", respStatusCode, type, url, body, jo.getInt("code"), jo.getString("message")); logger.error(errorMsg); } return job.build(); } if (errors != null && !errors.isEmpty()) { JsonObject jo = errors.getJsonObject(0); HTTPException e = new HTTPException( format("%s request to %s failed request body %s error message: [Error Code %d] - %s", type, url, body, jo.getInt("code"), jo.getString("message")), respStatusCode); throw e; } boolean success = jobj.getBoolean("success"); if (!success) { HTTPException e = new HTTPException( format("%s request to %s failed request body %s Body of response did not contain success", type, url, body), respStatusCode); logger.error(e.getMessage()); throw e; } JsonObject result = jobj.getJsonObject("result"); if (result == null) { HTTPException e = new HTTPException( format("%s request to %s failed request body %s " + "Body of response did not contain result", type, url, body), respStatusCode); logger.error(e.getMessage()); throw e; } JsonArray messages = jobj.getJsonArray("messages"); if (messages != null && !messages.isEmpty()) { JsonObject jo = messages.getJsonObject(0); String message = format( "%s request to %s failed request body %s response message: [Error Code %d] - %s", type, url, body, jo.getInt("code"), jo.getString("message")); logger.info(message); } // Construct JSON object that contains the result and HTTP status code for (Entry<String, JsonValue> entry : result.entrySet()) { job.add(entry.getKey(), entry.getValue()); } job.add("statusCode", respStatusCode); result = job.build(); logger.debug(format("%s %s, body:%s result: %s", type, url, body, "" + result)); return result; }
From source file:org.apache.johnzon.maven.plugin.ExampleToModelMojo.java
private void generateFieldsAndMethods(final Writer writer, final JsonObject object, final String prefix, final Collection<String> imports) throws IOException { final Map<String, JsonObject> nestedTypes = new TreeMap<String, JsonObject>(); {//from w w w . ja va2 s .c om final Iterator<Map.Entry<String, JsonValue>> iterator = object.entrySet().iterator(); while (iterator.hasNext()) { final Map.Entry<String, JsonValue> entry = iterator.next(); final String key = entry.getKey(); final String fieldName = toJavaFieldName(key); switch (entry.getValue().getValueType()) { case ARRAY: imports.add("java.util.List"); handleArray(writer, prefix, nestedTypes, entry.getValue(), key, fieldName, 1, imports); break; case OBJECT: final String type = toJavaName(fieldName); nestedTypes.put(type, JsonObject.class.cast(entry.getValue())); fieldGetSetMethods(writer, key, fieldName, type, prefix, 0, imports); break; case TRUE: case FALSE: fieldGetSetMethods(writer, key, fieldName, "Boolean", prefix, 0, imports); break; case NUMBER: fieldGetSetMethods(writer, key, fieldName, "Double", prefix, 0, imports); break; case STRING: fieldGetSetMethods(writer, key, fieldName, "String", prefix, 0, imports); break; case NULL: default: throw new UnsupportedOperationException("Unsupported " + entry.getValue() + "."); } if (iterator.hasNext()) { writer.write("\n"); } } } if (!object.isEmpty() && !nestedTypes.isEmpty()) { writer.write("\n"); } final Iterator<Map.Entry<String, JsonObject>> entries = nestedTypes.entrySet().iterator(); while (entries.hasNext()) { final Map.Entry<String, JsonObject> entry = entries.next(); writer.write(prefix + "public static class " + entry.getKey() + " {\n"); generateFieldsAndMethods(writer, entry.getValue(), " " + prefix, imports); writer.write(prefix + "}\n"); if (entries.hasNext()) { writer.write("\n"); } } }
From source file:org.codice.plugin.version.MavenVersionValidationPlugin.java
/** * Extracts key and value from JsonObject and evaluates if contains bad range symbol * key: dependency name// w w w . j a va 2s . c o m * value: version number * * @param jsonObject: Incoming Json structure to parse (key-value pairs) * @param filename: File being parsed (used for name in error message) * @return true if there are version range characters in the file */ private boolean hasRangeChars(JsonObject jsonObject, String filename) throws MojoFailureException { // (ex. key = "babel-core", value = "^6.17.0") String key; String value; String rangeChar; String errorMessage; boolean hasRangeChar = false; if (jsonObject == null) { return false; } for (Map.Entry<String, JsonValue> entry : jsonObject.entrySet()) { key = entry.getKey(); value = entry.getValue().toString(); rangeChar = scanTokenForRangeSymbol(value); if (rangeChar != null) { errorMessage = String.format("In [%s] | Invalid version range symbol: [%s] in [%s] : %s", filename, rangeChar, key, value); getLog().error(errorMessage); hasRangeChar = true; } } return hasRangeChar; }
From source file:org.hyperledger.fabric.sdk.ChaincodeCollectionConfiguration.java
private SignaturePolicy parsePolicy(IndexedHashMap<String, MSPPrincipal> identities, JsonObject policy) throws ChaincodeCollectionConfigurationException { if (policy.size() != 1) { throw new ChaincodeCollectionConfigurationException( format("Expected policy size of 1 but got %d", policy.size())); }/* w ww. j a va 2 s . c om*/ final String key = policy.entrySet().iterator().next().getKey(); if ("signed-by".equals(key)) { final String vo = getJsonString(policy, key); MSPPrincipal mspPrincipal = identities.get(vo); if (null == mspPrincipal) { throw new ChaincodeCollectionConfigurationException( format("No identity found by name %s in signed-by.", vo)); } return SignaturePolicy.newBuilder().setSignedBy(identities.getKeysIndex(vo)).build(); } else { Matcher match = noofPattern.matcher(key); final JsonArray vo = getJsonArray(policy, key); if (match.matches() && match.groupCount() == 1) { String matchStingNo = match.group(1).trim(); int matchNo = Integer.parseInt(matchStingNo); if (vo.size() < matchNo) { throw new ChaincodeCollectionConfigurationException( format("%s expected to have at least %d items to match but only found %d.", key, matchNo, vo.size())); } SignaturePolicy.NOutOf.Builder spBuilder = SignaturePolicy.NOutOf.newBuilder().setN(matchNo); for (int i = vo.size() - 1; i >= 0; --i) { JsonValue jsonValue = vo.get(i); if (jsonValue.getValueType() != JsonValue.ValueType.OBJECT) { throw new ChaincodeCollectionConfigurationException( format("Expected object type in Nof but got %s", jsonValue.getValueType().name())); } SignaturePolicy sp = parsePolicy(identities, jsonValue.asJsonObject()); spBuilder.addRules(sp); } return SignaturePolicy.newBuilder().setNOutOf(spBuilder.build()).build(); } else { throw new ChaincodeCollectionConfigurationException(format("Unsupported policy type %s", key)); } } }
From source file:org.hyperledger.fabric.sdk.ChaincodeCollectionConfiguration.java
private IndexedHashMap<String, MSPPrincipal> parseIdentities(JsonArray identities) throws ChaincodeCollectionConfigurationException { IndexedHashMap<String, MSPPrincipal> ret = new IndexedHashMap<>(); for (JsonValue jsonValue : identities) { if (jsonValue.getValueType() != JsonValue.ValueType.OBJECT) { throw new ChaincodeCollectionConfigurationException( format("Expected in identies user to be Object type but got: %s", jsonValue.getValueType().name())); }// ww w .j a v a2 s . co m JsonObject user = jsonValue.asJsonObject(); if (user.entrySet().size() != 1) { throw new ChaincodeCollectionConfigurationException( "Only expected on property for user entry in identies."); } Map.Entry<String, JsonValue> next = user.entrySet().iterator().next(); String name = next.getKey(); jsonValue = next.getValue(); if (jsonValue.getValueType() != JsonValue.ValueType.OBJECT) { throw new ChaincodeCollectionConfigurationException( format("Expected in identies role to be Object type but got: %s", jsonValue.getValueType().name())); } JsonObject role = jsonValue.asJsonObject(); JsonObject roleObj = getJsonObject(role, "role"); String roleName = getJsonString(roleObj, "name"); String mspId = getJsonString(roleObj, "mspId"); MSPRole.MSPRoleType mspRoleType; switch (roleName.intern()) { case "member": mspRoleType = MSPRole.MSPRoleType.MEMBER; break; case "admin": mspRoleType = MSPRole.MSPRoleType.ADMIN; break; case "client": mspRoleType = MSPRole.MSPRoleType.CLIENT; break; case "peer": mspRoleType = MSPRole.MSPRoleType.PEER; break; default: throw new ChaincodeCollectionConfigurationException(format( "In identities with key %s name expected member, admin, client, or peer in role got %s ", name, roleName)); } MSPRole mspRole = MSPRole.newBuilder().setRole(mspRoleType).setMspIdentifier(mspId).build(); MSPPrincipal principal = MSPPrincipal.newBuilder() .setPrincipalClassification(MSPPrincipal.Classification.ROLE) .setPrincipal(mspRole.toByteString()).build(); ret.put(name, principal); } return ret; }
From source file:org.hyperledger.fabric.sdk.NetworkConfig.java
private void createAllOrderers() throws NetworkConfigurationException { // Sanity check if (orderers != null) { throw new NetworkConfigurationException("INTERNAL ERROR: orderers has already been initialized!"); }/*from w w w . jav a 2 s .c om*/ orderers = new HashMap<>(); // orderers is a JSON object containing a nested object for each orderers JsonObject jsonOrderers = getJsonObject(jsonConfig, "orderers"); if (jsonOrderers != null) { for (Entry<String, JsonValue> entry : jsonOrderers.entrySet()) { String ordererName = entry.getKey(); JsonObject jsonOrderer = getJsonValueAsObject(entry.getValue()); if (jsonOrderer == null) { throw new NetworkConfigurationException( format("Error loading config. Invalid orderer entry: %s", ordererName)); } Node orderer = createNode(ordererName, jsonOrderer, "url"); if (orderer == null) { throw new NetworkConfigurationException( format("Error loading config. Invalid orderer entry: %s", ordererName)); } orderers.put(ordererName, orderer); } } }