List of usage examples for javax.json JsonObject getString
String getString(String name);
From source file:edu.harvard.hms.dbmi.bd2k.irct.ri.i2b2transmart.I2B2TranSMARTResourceImplementation.java
private Result convertJsonToResultSet(Result result, JsonArray arrayResults, Map<String, String> aliasMap, String gatherAllEncounterFacts) throws ResultSetException, PersistableException { // If the resultset is empty create the initial result set ResultSet rs = (ResultSet) result.getData(); // Create the initial Matrix Map<String, Map<String, String>> dataMatrix = new HashMap<String, Map<String, String>>(); String pivot = "PATIENT_NUM"; if (gatherAllEncounterFacts.equalsIgnoreCase("true")) { pivot = "ENCOUNTER_NUM"; }/* w w w . j ava 2s . c o m*/ for (JsonValue val : arrayResults) { JsonObject obj = (JsonObject) val; String rowId = obj.getString(pivot); if (!dataMatrix.containsKey(rowId)) { dataMatrix.put(rowId, new HashMap<String, String>()); } dataMatrix.get(rowId).put(obj.getString("CONCEPT_PATH"), obj.getString("VALUE")); } // Loop through the result set and add the information in the matrix to // the result set rs.first(); while (rs.next()) { String rsRowId = rs.getString(pivot); if (dataMatrix.containsKey(rsRowId)) { Map<String, String> newRowData = dataMatrix.get(rsRowId); for (String colKeySet : newRowData.keySet()) { // Check to see if an alias exists if (aliasMap.get(colKeySet) != null) { rs.updateString(aliasMap.get(colKeySet), newRowData.get(colKeySet)); } else { rs.updateString(colKeySet, newRowData.get(colKeySet)); } } dataMatrix.remove(rsRowId); } } // If the information is still in the matrix add it to the result set at // the end for (String rowId : dataMatrix.keySet()) { rs.appendRow(); rs.updateString(pivot, rowId); Map<String, String> newRowData = dataMatrix.get(rowId); for (String colKeySet : newRowData.keySet()) { // Check to see if an alias exists if (aliasMap.get(colKeySet) != null) { rs.updateString(aliasMap.get(colKeySet), newRowData.get(colKeySet)); } else { rs.updateString(colKeySet, newRowData.get(colKeySet)); } } } // Add results back result.setData(rs); return result; }
From source file:eu.forgetit.middleware.component.Contextualizer.java
public void executeTextContextualization(Exchange exchange) { taskStep = "CONTEXTUALIZER_CONTEXTUALIZE_DOCUMENTS"; logger.debug("New message retrieved for " + taskStep); JsonObjectBuilder job = Json.createObjectBuilder(); JsonObject headers = MessageTools.getHeaders(exchange); long taskId = Long.parseLong(headers.getString("taskId")); scheduler.updateTask(taskId, TaskStatus.RUNNING, taskStep, null); JsonObject jsonBody = MessageTools.getBody(exchange); String cmisServerId = null;/*from w w w. j a v a 2 s . co m*/ if (jsonBody != null) { cmisServerId = jsonBody.getString("cmisServerId"); JsonArray jsonEntities = jsonBody.getJsonArray("entities"); job.add("cmisServerId", cmisServerId); job.add("entities", jsonEntities); for (JsonValue jsonValue : jsonEntities) { JsonObject jsonObject = (JsonObject) jsonValue; String type = jsonObject.getString("type"); if (type.equals(Collection.class.getName())) continue; long pofId = jsonObject.getInt("pofId"); try { String collectorStorageFolder = ConfigurationManager.getConfiguration() .getString("collector.storage.folder"); Path sipPath = Paths.get(collectorStorageFolder + File.separator + pofId); Path metadataPath = Paths.get(sipPath.toString(), "metadata"); Path contentPath = Paths.get(sipPath.toString(), "content"); Path contextAnalysisPath = Paths.get(metadataPath.toString(), "worldContext.json"); logger.debug("Looking for text documents in folder: " + contentPath); List<File> documentList = getFilteredDocumentList(contentPath); logger.debug("Document List for Contextualization: " + documentList); if (documentList != null && !documentList.isEmpty()) { File[] documents = documentList.stream().toArray(File[]::new); context = service.contextualize(documents); logger.debug("World Context:\n"); for (String contextEntry : context) { logger.debug(contextEntry); } StringBuilder contextResult = new StringBuilder(); for (int i = 0; i < context.length; i++) { Map<String, String> jsonMap = new HashMap<>(); jsonMap.put("filename", documents[i].getName()); jsonMap.put("context", context[i]); contextResult.append(jsonMap.toString()); } FileUtils.writeStringToFile(contextAnalysisPath.toFile(), contextResult.toString()); logger.debug("Document Contextualization completed for " + documentList); } } catch (IOException | ResourceInstantiationException | ExecutionException e) { e.printStackTrace(); } } exchange.getOut().setBody(job.build().toString()); exchange.getOut().setHeaders(exchange.getIn().getHeaders()); } else { scheduler.updateTask(taskId, TaskStatus.FAILED, taskStep, null); job.add("Message", "Task " + taskId + " failed"); scheduler.sendMessage("activemq:queue:ERROR.QUEUE", exchange.getIn().getHeaders(), job.build()); } }
From source file:org.erstudio.guper.websocket.GuperWSEndpoint.java
@OnMessage public void onWebSocketMessage(JsonObject json, Session session) throws WebSocketMessageException, MessageException, LocationException, IOException, EncodeException { System.out.println("onWebSocketMessage " + session.getId()); if (!json.containsKey("type")) { throw new WebSocketMessageException("Type is undefined"); }/*from w w w . j av a 2 s . c o m*/ String type = json.getString("type"); if (StringUtils.isBlank(type)) { throw new WebSocketMessageException("Empty message type"); } if (!json.containsKey("message")) { throw new WebSocketMessageException("Message is undefined"); } String message = json.get("message").toString(); if (StringUtils.isBlank(message)) { throw new WebSocketMessageException("Empty message"); } switch (type) { case "SEND_MESSAGE": { try { Message m = mapper.readValue(message, Message.class); onSendMessage(m, session); } catch (IOException ex) { throw new WebSocketMessageException("Incorrect Message format: " + message); } } break; case "CHANGE_LOCATION": { try { Location l = mapper.readValue(message, Location.class); onChangeLocation(l, session); } catch (IOException ex) { throw new WebSocketMessageException("Incorrect Location format: " + message); } } break; default: throw new WebSocketMessageException("Incorrect message type: " + type); } }
From source file:org.kuali.rice.krad.web.controller.helper.DataTablesPagingHelper.java
/** * Get the sort type string from the parsed column definitions object. * * @param jsonColumnDefs the JsonArray representation of the aoColumnDefs property from the RichTable template * options/*from ww w. ja v a 2 s. c o m*/ * @param sortCol the index of the column to get the sort type for * @return the name of the sort type specified in the template options, or the default of "string" if none is * found. */ private String getSortType(JsonArray jsonColumnDefs, int sortCol) { String sortType = "string"; // default to string if nothing is spec'd if (jsonColumnDefs != null) { JsonObject column = jsonColumnDefs.getJsonObject(sortCol); if (column.containsKey("sType")) { sortType = column.getString("sType"); } } return sortType; }
From source file:de.pangaea.fixo3.CreateEsonetYellowPages.java
private void addDeviceType(String name, String label, String comment, String seeAlso, JsonArray equivalentClasses, JsonArray subClasses) { IRI deviceTypeIRI = IRI.create(name); m.addClass(deviceTypeIRI);// ww w . j a v a 2 s. c om m.addLabel(deviceTypeIRI, label); m.addComment(deviceTypeIRI, comment); m.addSeeAlso(deviceTypeIRI, seeAlso); // Default sub class, though implicit with curated sensing device type // hierarchy // m.addSubClass(deviceTypeIRI, SSN.SensingDevice); for (JsonObject equivalentClass : equivalentClasses.getValuesAs(JsonObject.class)) { if (equivalentClass.containsKey("type")) { m.addEquivalentClass(deviceTypeIRI, IRI.create(equivalentClass.getString("type"))); } } for (JsonObject subClass : subClasses.getValuesAs(JsonObject.class)) { if (subClass.containsKey("type")) { m.addSubClass(deviceTypeIRI, IRI.create(subClass.getString("type"))); } else if (subClass.containsKey("observes")) { JsonObject observesJson = subClass.getJsonObject("observes"); String propertyLabel = observesJson.getString("label"); String propertyType = observesJson.getString("type"); JsonObject featureJson = observesJson.getJsonObject("isPropertyOf"); String featureLabel = featureJson.getString("label"); String featureType = featureJson.getString("type"); IRI propertyIRI = IRI.create(EYP.ns.toString() + md5Hex(propertyLabel)); IRI propertyTypeIRI = IRI.create(propertyType); IRI featureIRI = IRI.create(EYP.ns.toString() + md5Hex(featureLabel)); IRI featureTypeIRI = IRI.create(featureType); m.addObjectValue(deviceTypeIRI, observes, propertyIRI); m.addIndividual(propertyIRI); m.addType(propertyIRI, propertyTypeIRI); m.addLabel(propertyIRI, propertyLabel); m.addIndividual(featureIRI); m.addType(featureIRI, featureTypeIRI); m.addLabel(featureIRI, featureLabel); m.addObjectAssertion(propertyIRI, isPropertyOf, featureIRI); } else if (subClass.containsKey("detects")) { JsonObject detectsJson = subClass.getJsonObject("detects"); String stimulusLabel = detectsJson.getString("label"); String stimulusType = detectsJson.getString("type"); IRI stimulusIRI = IRI.create(EYP.ns.toString() + md5Hex(stimulusLabel)); IRI stimulusTypeIRI = IRI.create(stimulusType); m.addObjectValue(deviceTypeIRI, detects, stimulusIRI); m.addIndividual(stimulusIRI); m.addType(stimulusIRI, stimulusTypeIRI); m.addLabel(stimulusIRI, stimulusLabel); } else if (subClass.containsKey("capability")) { JsonObject capabilityJson = subClass.getJsonObject("capability"); String capabilityLabel = capabilityJson.getString("label"); JsonObject propertyJson = capabilityJson.getJsonObject("property"); String propertyLabel = propertyJson.getString("label"); String propertyType = propertyJson.getString("type"); JsonObject valueJson = propertyJson.getJsonObject("value"); String valueLabel = valueJson.getString("label"); IRI capabilityIRI = IRI.create(EYP.ns.toString() + md5Hex(capabilityLabel)); IRI propertyIRI = IRI.create(EYP.ns.toString() + md5Hex(propertyLabel)); IRI propertyTypeIRI = IRI.create(propertyType); IRI valueIRI = IRI.create(EYP.ns.toString() + md5Hex(valueLabel)); m.addObjectValue(deviceTypeIRI, hasMeasurementCapability, capabilityIRI); m.addIndividual(capabilityIRI); m.addType(capabilityIRI, MeasurementCapability); m.addLabel(capabilityIRI, capabilityLabel); m.addObjectAssertion(capabilityIRI, hasMeasurementProperty, propertyIRI); m.addIndividual(propertyIRI); m.addType(propertyIRI, SSN.MeasurementProperty); m.addType(propertyIRI, propertyTypeIRI); m.addLabel(propertyIRI, propertyLabel); m.addObjectAssertion(propertyIRI, hasValue, valueIRI); m.addIndividual(valueIRI); m.addType(valueIRI, SSN.ObservationValue); m.addLabel(valueIRI, valueLabel); if (valueJson.containsKey("value")) { m.addType(valueIRI, QuantitativeValue); m.addDataAssertion(valueIRI, value, Float.valueOf(valueJson.getString("value"))); } else if (valueJson.containsKey("minValue") && valueJson.containsKey("maxValue")) { m.addType(valueIRI, QuantitativeValue); m.addDataAssertion(valueIRI, minValue, Float.valueOf(valueJson.getString("minValue"))); m.addDataAssertion(valueIRI, maxValue, Float.valueOf(valueJson.getString("maxValue"))); } else { throw new RuntimeException("Expected value or min/max value [valueJson = " + valueJson + "]"); } m.addObjectAssertion(valueIRI, unitCode, IRI.create(valueJson.getString("unitCode"))); } } }
From source file:sample.products.java
@POST @Consumes("application/json") public void postData(String str) { JsonObject json = Json.createReader(new StringReader(str)).readObject(); //System.out.println(json.getInt("id") + ": " + json.getString("name")); int id1 = json.getInt("id"); String id = String.valueOf(id1); String name = json.getString("name"); String description = json.getString("description"); int qty1 = json.getInt("qty"); String qty = String.valueOf(qty1); System.out.println(id + name + description + qty); doUpdate("INSERT INTO PRODUCT (productId, name, description, quantity) VALUES (?, ?, ?, ?)", id, name, description, qty);/*from w w w . j ava 2 s .com*/ }
From source file:sample.products.java
@PUT @Consumes("application/json") public void putData(String str) { JsonObject json = Json.createReader(new StringReader(str)).readObject(); //System.out.println(json.getInt("id") + ": " + json.getString("name")); int id1 = json.getInt("id"); String id = String.valueOf(id1); String name = json.getString("name"); String description = json.getString("description"); int qty1 = json.getInt("qty"); String qty = String.valueOf(qty1); System.out.println(id + name + description + qty); doUpdate("UPDATE PRODUCT SET productId= ?, name = ?, description = ?, quantity = ? WHERE productId = ?", id, name, description, qty, id); }
From source file:io.hops.hopsworks.common.util.WebCommunication.java
private String execute(String path, String hostAddress, String agentPassword, String cluster, String group, String service, String command, String[] params) throws Exception { String url = createUrl(path, hostAddress, cluster, group, service, command); String optionsAndParams = ""; for (String param : params) { optionsAndParams += optionsAndParams.isEmpty() ? param : " " + param; }/*from w w w . j a v a 2 s . c om*/ Response response = postWebResource(url, agentPassword, optionsAndParams); int code = response.getStatus(); Family res = Response.Status.Family.familyOf(code); if (res == Response.Status.Family.SUCCESSFUL) { String responseString = response.readEntity(String.class); if (path.equalsIgnoreCase("execute/continue")) { JsonObject json = Json.createReader(response.readEntity(Reader.class)).readObject(); responseString = json.getString("before"); } return FormatUtils.stdoutToHtml(responseString); } throw new RuntimeException("Did not succeed to execute command."); }
From source file:eu.forgetit.middleware.component.Condensator.java
public void imageClustering(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.jav a 2 s . c om*/ if (jsonBody != null) { String xmlPath = jsonBody.getString("extractorOutput"); logger.debug("Retrieved XML of image collection Path: " + xmlPath); job.add("extractorOutput", xmlPath); if (xmlPath != null && !xmlPath.isEmpty()) { String response = service.request(xmlPath); logger.debug("Image clustering result:\n" + response); job.add("result", response); } else { logger.debug("Unable to process XML results, wrong request"); job.add("result", "Unable to process XML results, wrong request"); } exchange.getOut().setBody(job.build().toString()); exchange.getOut().setHeaders(exchange.getIn().getHeaders()); } }
From source file:org.hyperledger.fabric.sdk.MemberServicesFabricCAImpl.java
/** * Enroll the user with member service//from w w w . ja v a 2 s. c o m * * @param req Enrollment request with the following fields: name, enrollmentSecret * @return enrollment */ public Enrollment enroll(EnrollmentRequest req) throws EnrollmentException { logger.debug(String.format("[MemberServicesFabricCAImpl.enroll] [%s]", req)); if (req == null) { throw new RuntimeException("req is not set"); } final String user = req.getEnrollmentID(); final String secret = req.getEnrollmentSecret(); if (StringUtil.isNullOrEmpty(user)) { throw new RuntimeException("req.enrollmentID is not set"); } if (StringUtil.isNullOrEmpty(secret)) { throw new RuntimeException("req.enrollmentSecret is not set"); } logger.debug("[MemberServicesFabricCAImpl.enroll] Generating keys..."); try { // generate ECDSA keys: signing and encryption keys KeyPair signingKeyPair = cryptoPrimitives.ecdsaKeyGen(); logger.debug("[MemberServicesFabricCAImpl.enroll] Generating keys...done!"); // KeyPair encryptionKeyPair = cryptoPrimitives.ecdsaKeyGen(); PKCS10CertificationRequest csr = cryptoPrimitives.generateCertificationRequest(user, signingKeyPair); String pem = cryptoPrimitives.certificationRequestToPEM(csr); JsonObjectBuilder factory = Json.createObjectBuilder(); factory.add("certificate_request", pem); JsonObject postObject = factory.build(); StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = Json.createWriter(new PrintWriter(stringWriter)); jsonWriter.writeObject(postObject); jsonWriter.close(); String str = stringWriter.toString(); logger.debug("[MemberServicesFabricCAImpl.enroll] Generating keys...done!"); String responseBody = httpPost(url + COP_ENROLLMENBASE, str, new UsernamePasswordCredentials(user, secret)); logger.debug("response" + responseBody); JsonReader reader = Json.createReader(new StringReader(responseBody)); JsonObject jsonst = (JsonObject) reader.read(); String result = jsonst.getString("result"); boolean success = jsonst.getBoolean("success"); logger.debug(String.format("[MemberServicesFabricCAImpl] enroll success:[%s], result:[%s]", success, result)); if (!success) { EnrollmentException e = new EnrollmentException("COP Failed response success is false. " + result, new Exception()); logger.error(e.getMessage()); throw e; } Base64.Decoder b64dec = Base64.getDecoder(); String signedPem = new String(b64dec.decode(result.getBytes())); logger.info(String.format("[MemberServicesFabricCAImpl] enroll returned pem:[%s]", signedPem)); Enrollment enrollment = new Enrollment(); enrollment.setKey(signingKeyPair); enrollment.setPublicKey(Hex.toHexString(signingKeyPair.getPublic().getEncoded())); enrollment.setCert(signedPem); return enrollment; } catch (Exception e) { EnrollmentException ee = new EnrollmentException(String.format("Failed to enroll user %s ", user), e); logger.error(ee.getMessage(), ee); throw ee; } }