List of usage examples for javax.json JsonObject getJsonObject
JsonObject getJsonObject(String name);
From source file:org.optaplanner.examples.conferencescheduling.persistence.ConferenceSchedulingCfpDevoxxImporter.java
private Set<String> extractThemeTrackSet(JsonObject talkObject, String code, String title) { Set<String> themeTrackSet = new HashSet<>(Arrays.asList(talkObject.getJsonObject("track").getString("id"))); if (!trackIdSet.containsAll(themeTrackSet)) { throw new IllegalStateException("The talk (" + title + ") with id (" + code + ") contains trackId + (" + trackIdSet + ") that doesn't exist in the trackIdSet."); }/*from ww w . ja v a 2 s . c o m*/ return themeTrackSet; }
From source file:edu.harvard.hms.dbmi.bd2k.irct.ri.exac.EXACResourceImplementation.java
private String getValue(JsonObject obj, String field) { if (field.contains(".")) { String thisField = field.split("\\.")[0]; String remaining = field.replaceFirst(thisField + ".", ""); return getValue(obj.getJsonObject(thisField), remaining); }//from w ww . ja va 2 s. c o m if (obj.containsKey(field)) { ValueType vt = obj.get(field).getValueType(); if (vt == ValueType.NUMBER) { return obj.getJsonNumber(field).toString(); } else if (vt == ValueType.TRUE) { return "TRUE"; } else if (vt == ValueType.FALSE) { return "FALSE"; } return obj.getString(field); } return ""; }
From source file:de.tu_dortmund.ub.data.dswarm.Init.java
private Optional<String> enhanceInputDataResource(final String inputDataResourceFile, final JsonObject configurationJSON) throws Exception { final JsonObject parameters = configurationJSON.getJsonObject(DswarmBackendStatics.PARAMETERS_IDENTIFIER); if (parameters == null) { LOG.debug("could not find parameters in configuration '{}'", configurationJSON.toString()); return Optional.empty(); }/* w w w . j av a 2s. c o m*/ final String storageType = parameters.getString(DswarmBackendStatics.STORAGE_TYPE_IDENTIFIER); if (storageType == null || storageType.trim().isEmpty()) { LOG.debug("could not find storage in parameters of configuration '{}'", configurationJSON.toString()); return Optional.empty(); } switch (storageType) { case DswarmBackendStatics.XML_STORAGE_TYPE: case DswarmBackendStatics.MABXML_STORAGE_TYPE: case DswarmBackendStatics.MARCXML_STORAGE_TYPE: case DswarmBackendStatics.PNX_STORAGE_TYPE: case DswarmBackendStatics.OAI_PMH_DC_ELEMENTS_STORAGE_TYPE: case DswarmBackendStatics.OAI_PMH_DCE_AND_EDM_ELEMENTS_STORAGE_TYPE: case DswarmBackendStatics.OAIPMH_DC_TERMS_STORAGE_TYPE: case DswarmBackendStatics.OAIPMH_MARCXML_STORAGE_TYPE: // only XML is supported right now break; default: LOG.debug("storage type '{}' is currently not supported for input data resource enhancement", storageType); return Optional.empty(); } final Path inputDataResourcePath = Paths.get(inputDataResourceFile); final Path inputDataResourceFileNamePath = inputDataResourcePath.getFileName(); final String inputDataResourceFileName = inputDataResourceFileNamePath.toString(); final String newInputDataResourcePath = OS_TEMP_DIR + File.separator + inputDataResourceFileName; LOG.debug("try to enhance input data resource '{}'", inputDataResourceFile); XMLEnhancer.enhanceXML(inputDataResourceFile, newInputDataResourcePath); LOG.debug("enhanced input data resource for '{}' can be found at ''{}", inputDataResourceFile, newInputDataResourcePath); return Optional.of(newInputDataResourcePath); }
From source file:edu.harvard.hms.dbmi.bd2k.irct.ri.exac.EXACResourceImplementation.java
private List<String> getNames(String prefix, JsonObject obj) { List<String> returns = new ArrayList<String>(); for (String field : obj.keySet()) { if (obj.get(field).getValueType() == ValueType.OBJECT) { if (prefix.equals("")) { returns.addAll(getNames(field, obj.getJsonObject(field))); } else { returns.addAll(getNames(prefix + "." + field, obj.getJsonObject(field))); }/*from w w w. j a v a 2 s . co m*/ } else if (obj.get(field).getValueType() != ValueType.ARRAY) { if (prefix.equals("")) { returns.add(field); } else { returns.add(prefix + "." + field); } } } return returns; }
From source file:org.optaplanner.examples.conferencescheduling.persistence.ConferenceSchedulingCfpDevoxxImporter.java
private void importTalkList() { this.talkCodeToTalkMap = new HashMap<>(); List<Talk> talkList = new ArrayList<>(); Long talkId = 0L;//from ww w . ja v a 2 s . c o m String talksPath = getClass().getResource("devoxxBE").toString(); String[] confFiles = { "BOF", "Conf14Sept2018", "DeepDive", "HandsOnLabs", "Quickies", "ToolsInAction" }; for (String confType : confFiles) { LOGGER.debug("Sending a request to: " + talksPath + "/" + confType + ".json"); JsonArray talksArray = readJson(talksPath + "/" + confType + ".json", JsonReader::readObject) .getJsonObject("approvedTalks").getJsonArray("talks"); for (int i = 0; i < talksArray.size(); i++) { JsonObject talkObject = talksArray.getJsonObject(i); String code = talkObject.getString("id"); String title = talkObject.getString("title").substring(5); String talkTypeName = talkObject.getJsonObject("talkType").getString("id"); Set<String> themeTrackSet = extractThemeTrackSet(talkObject, code, title); String language = talkObject.getString("lang"); int audienceLevel = Integer .parseInt(talkObject.getString("audienceLevel").replaceAll("[^0-9]", "")); List<Speaker> speakerList = extractSpeakerList(confType, talkObject, code, title); Set<String> contentTagSet = extractContentTagSet(talkObject); String state = talkObject.getJsonObject("state").getString("code"); if (!Arrays.asList(IGNORED_TALK_TYPES).contains(code) && !state.equals("declined")) { Talk talk = createTalk(talkId++, code, title, talkTypeName, themeTrackSet, language, speakerList, audienceLevel, contentTagSet); talkCodeToTalkMap.put(code, talk); talkList.add(talk); talkTalkTypeToTotalMap.merge(talkTypeName, 1, Integer::sum); } } } solution.setTalkList(talkList); }
From source file:de.tu_dortmund.ub.data.dswarm.Task.java
/** * get the resource id of the resource for the data model for the the prototype project * * @param dataModelID// w ww. jav a 2 s. co m * @return * @throws Exception */ private String getProjectResourceID(String dataModelID) throws Exception { String resourceID = null; CloseableHttpClient httpclient = HttpClients.createDefault(); try { // Hole Mappings aus dem Projekt mit 'projectID' HttpGet httpGet = new HttpGet(config.getProperty("engine.dswarm.api") + "datamodels/" + dataModelID); CloseableHttpResponse httpResponse = httpclient.execute(httpGet); logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpGet.getRequestLine()); try { int statusCode = httpResponse.getStatusLine().getStatusCode(); HttpEntity httpEntity = httpResponse.getEntity(); switch (statusCode) { case 200: { StringWriter writer = new StringWriter(); IOUtils.copy(httpEntity.getContent(), writer, "UTF-8"); String responseJson = writer.toString(); logger.info("[" + config.getProperty("service.name") + "] responseJson : " + responseJson); JsonReader jsonReader = Json.createReader(IOUtils.toInputStream(responseJson, "UTF-8")); JsonObject jsonObject = jsonReader.readObject(); JsonArray resources = jsonObject.getJsonObject("configuration").getJsonArray("resources"); resourceID = resources.getJsonObject(0).getJsonString("uuid").getString(); logger.info("[" + config.getProperty("service.name") + "] resourceID : " + resourceID); break; } default: { logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : " + httpResponse.getStatusLine().getReasonPhrase()); } } EntityUtils.consume(httpEntity); } finally { httpResponse.close(); } } finally { httpclient.close(); } return resourceID; }
From source file:de.tu_dortmund.ub.data.dswarm.Transform.java
private JsonObject getDataModel(final String dataModelID, final String serviceName, final String engineDswarmAPI) throws Exception { try (final CloseableHttpClient httpclient = HttpClients.createDefault()) { // Hole Mappings aus dem Projekt mit 'projectID' final String uri = engineDswarmAPI + DswarmBackendStatics.DATAMODELS_ENDPOINT + APIStatics.SLASH + dataModelID;/* w w w .ja v a 2 s. c om*/ final HttpGet httpGet = new HttpGet(uri); LOG.info(String.format("[%s][%d] request : %s", serviceName, cnt, httpGet.getRequestLine())); try (CloseableHttpResponse httpResponse = httpclient.execute(httpGet)) { final int statusCode = httpResponse.getStatusLine().getStatusCode(); final String response = TPUUtil.getResponseMessage(httpResponse); switch (statusCode) { case 200: { final JsonObject jsonObject = TPUUtil.getJsonObject(response); LOG.debug( String.format("[%s][%d] inputDataModel : %s", serviceName, cnt, jsonObject.toString())); final JsonObject dataResourceJSON = jsonObject .getJsonObject(DswarmBackendStatics.DATA_RESOURCE_IDENTIFIER); if (dataResourceJSON != null) { final String inputResourceID = dataResourceJSON .getString(DswarmBackendStatics.UUID_IDENTIFIER); LOG.info(String.format("[%s][%d] inout resource ID : %s", serviceName, cnt, inputResourceID)); } return jsonObject; } default: { LOG.error(String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode, httpResponse.getStatusLine().getReasonPhrase())); throw new Exception("something went wrong at data model retrieval: " + response); } } } } }
From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java
/** * Gets a list of all the posted ballots of the given election form the bulletin board and returns it * @param election/* ww w. j av a 2 s. com*/ * Election for which the list of ballots should be retrieved * @return * the list of all posted ballots to the given election */ public List<Ballot> getBallotsByElection(Election election) { List<Ballot> ballots = new ArrayList<Ballot>(); try { URL url = new URL(bulletinBoardUrl + "/elections/" + election.getId() + "/ballots"); InputStream urlInputStream = url.openStream(); JsonReader jsonReader = Json.createReader(urlInputStream); JsonArray obj = jsonReader.readArray(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); //transforms the recieved json string into a list of ballot objects for (JsonObject result : obj.getValuesAs(JsonObject.class)) { int id = Integer.parseInt(result.getString("id")); LocalDateTime timeStamp = LocalDateTime.parse(result.getString("timestamp"), format); JsonObject jsonData = result.getJsonObject("jsonData"); List<String> selectedOptions = new ArrayList<String>(); JsonArray optionsArray = jsonData.getJsonArray("e"); for (int i = 0; i < optionsArray.size(); i++) { selectedOptions.add(optionsArray.getString(i)); } String u_HatString = jsonData.getString("u_Hat"); String cString = jsonData.getString("c"); String dString = jsonData.getString("d"); String pi1String = jsonData.getString("pi1"); String pi2String = jsonData.getString("pi2"); String pi3String = jsonData.getString("pi3"); //create ballot object and add it to the list Ballot ballot = new Ballot(id, election, selectedOptions, u_HatString, cString, dString, pi1String, pi2String, pi3String, timeStamp); System.out.println(ballot.isValid()); ballots.add(ballot); } } catch (IOException x) { System.err.println(x); } return ballots; }
From source file:org.jboss.as.test.integration.logging.formatters.JsonFormatterTestCase.java
@Test public void testKeyOverrides() throws Exception { final Map<String, String> keyOverrides = new HashMap<>(); keyOverrides.put("timestamp", "dateTime"); keyOverrides.put("sequence", "seq"); final Map<String, String> metaData = new LinkedHashMap<>(); metaData.put("test-key-1", "test-value-1"); metaData.put("key-no-value", null); // Configure the subsystem configure(keyOverrides, metaData, true); final String msg = "Logging test: JsonFormatterTestCase.defaultLoggingTest"; final Map<String, String> params = new LinkedHashMap<>(); // Indicate we need an exception logged params.put(LoggingServiceActivator.LOG_EXCEPTION_KEY, "true"); // Add an NDC value params.put(LoggingServiceActivator.NDC_KEY, "test.ndc.value"); // Add some map entries for MDC values params.put("mdcKey1", "mdcValue1"); params.put("mdcKey2", "mdcValue2"); final List<String> expectedKeys = createDefaultKeys(); expectedKeys.remove("timestamp"); expectedKeys.remove("sequence"); expectedKeys.addAll(keyOverrides.values()); expectedKeys.addAll(metaData.keySet()); expectedKeys.add("exception"); expectedKeys.add("stackTrace"); expectedKeys.add("sourceFileName"); expectedKeys.add("sourceMethodName"); expectedKeys.add("sourceClassName"); expectedKeys.add("sourceLineNumber"); expectedKeys.add("sourceModuleVersion"); expectedKeys.add("sourceModuleName"); final int statusCode = getResponse(msg, params); Assert.assertTrue("Invalid response statusCode: " + statusCode, statusCode == HttpStatus.SC_OK); // Validate each line for (String s : Files.readAllLines(logFile, StandardCharsets.UTF_8)) { if (s.trim().isEmpty()) continue; try (JsonReader reader = Json.createReader(new StringReader(s))) { final JsonObject json = reader.readObject(); validateDefault(json, expectedKeys, msg); // Timestamp should have been renamed to dateTime Assert.assertNull("Found timestamp entry in " + s, json.get("timestamp")); // Sequence should have been renamed to seq Assert.assertNull("Found sequence entry in " + s, json.get("sequence")); // Validate MDC final JsonObject mdcObject = json.getJsonObject("mdc"); Assert.assertEquals("mdcValue1", mdcObject.getString("mdcKey1")); Assert.assertEquals("mdcValue2", mdcObject.getString("mdcKey2")); // Validate the meta-data Assert.assertEquals("test-value-1", json.getString("test-key-1")); Assert.assertEquals("Expected a null type but got " + json.get("key-no-value"), JsonValue.ValueType.NULL, json.get("key-no-value").getValueType()); validateStackTrace(json, true, true); }//from w w w .ja va 2s .c om } }
From source file:com.buffalokiwi.aerodrome.jet.orders.OrderItemRec.java
/** * Create an OrderItemRec from jet json * @param json jet json/*from www.j av a 2 s . co m*/ * @return instance */ public static OrderItemRec fromJson(final JsonObject json) throws JetException { final Builder b = (new Builder()).setOrderItemId(json.getString("order_item_id", "")) .setAltOrderItemId(json.getString("alt_order_item_id", "")) .setMerchantSku(json.getString("merchant_sku", "")).setTitle(json.getString("product_title", "")) .setRequestOrderQty(json.getInt("request_order_quantity", 0)) //..This appears to have been removed. I don't know if jet still returns this value or not. .setRequestOrderCancelQty(json.getInt("request_order_cancel_qty", 0)) .setAdjReason(json.getString("adjustment_reason", "")) .setTaxCode(json.getString("item_tax_code", "")).setUrl(json.getString("url", "")) .setPriceAdj(Utils.jsonNumberToMoney(json, "price_adjustment")) .setFees(Utils.jsonNumberToMoney(json, "item_fees")).setTaxInfo(json.getString("tax_info", "")) //..This might not work... .setRegFees(Utils.jsonNumberToMoney(json, "regulatory_fees")) .setAdjustments(jsonToFeeAdj(json.getJsonArray("fee_adjustments"))) .setItemAckStatus(ItemAckStatus.fromText(json.getString("order_item_acknowledgement_status", ""))); final JsonObject price = json.getJsonObject("item_price"); if (price != null) b.setItemPrice(ItemPriceRec.fromJson(price)); return b.build(); }