List of usage examples for javax.json JsonObject getString
String getString(String name);
From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java
/** * Gets the parameters of the bulletin board from the bulletin board and converts the recieved Json in a Parameters object and returns it * @return returns bulletin board's parameters in form of a parameter object *//*from ww w. java 2 s. c om*/ public Parameters getParameters() { try { //Get parameters json with a get request URL url = new URL(bulletinBoardUrl + "/parameters"); InputStream urlInputStream = url.openStream(); JsonReader jsonReader = Json.createReader(urlInputStream); JsonObject obj = jsonReader.readObject(); //Json contains String representations of the parameter elements String oString = obj.getString("o"); String pString = obj.getString("p"); String h0String = obj.getString("h0"); String h1String = obj.getString("h1"); String h2String = obj.getString("h2"); String g0String = obj.getString("g0"); String g1String = obj.getString("g1"); //Converting the parameter Element Strings into Parameters Object containing the restored Parameter Elements Parameters parameters = new Parameters(oString, pString, h0String, h1String, h2String, g0String, g1String); return parameters; } catch (Exception x) { System.err.println(x); return null; } }
From source file:org.optaplanner.examples.conferencescheduling.persistence.ConferenceSchedulingCfpDevoxxImporter.java
private void scheduleTalk(JsonObject timeslotObject, Room room, Timeslot timeslot) { Talk talk = talkCodeToTalkMap.get(timeslotObject.getJsonObject("talk").getString("id")); if (talk == null) { throw new IllegalStateException("The timeslot (" + timeslotObject.getString("slotId") + ") has a talk (" + timeslotObject.getJsonObject("talk").getString("id") + ") that does not exist in the talk list"); }// www . j a va 2 s. co m if (talk.isPinnedByUser()) { throw new IllegalStateException("The timeslot (" + timeslotObject.getString("slotId") + ") has a talk (" + timeslotObject.getJsonObject("talk").getString("id") + ") that is already pinned by user at another timeslot (" + talk.getTimeslot().toString() + ")."); } talk.setRoom(room); talk.setTimeslot(timeslot); talk.setPinnedByUser(true); }
From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java
/** * gets the all registered voters from the bulletin board and returns them as a List of Voter objects * @return returns a list of all voters/*from w w w .ja va 2 s.com*/ */ public List<Voter> getAllARegisteredVoters() { List<Voter> voterlist = new ArrayList<Voter>(); try { URL url = new URL(bulletinBoardUrl + "/voters"); InputStream urlInputStream = url.openStream(); JsonReader jsonReader = Json.createReader(urlInputStream); JsonArray obj = jsonReader.readArray(); //For each Voter-Json in the Json Array for (JsonObject result : obj.getValuesAs(JsonObject.class)) { //JsonData converted into Voter Object and added to the list String email = result.getString("email"); String publicCredential = result.getString("publicCredential"); String appVersion = result.getString("appVersion"); Voter voter = new Voter(email, publicCredential, appVersion); voterlist.add(voter); } } catch (IOException x) { System.err.println(x); } return voterlist; }
From source file:eu.forgetit.middleware.component.Extractor.java
private synchronized String getVideoPath(JsonObject jsonBody) { long pofId = jsonBody.getInt("pofId"); logger.debug("Retrieved PoF ID: " + pofId); String jsonContentDir = jsonBody.getString("sipContentDir"); if (jsonContentDir != null) sipContentDirPath = jsonContentDir; logger.debug("Retrieved SIP Content Directory: " + sipContentDirPath); String rootPublicDir = ConfigurationManager.getConfiguration().getString("pofmiddleware.pub.dir"); File publicDir = new File(rootPublicDir, String.valueOf(pofId)); logger.debug("Publication Dir: " + publicDir.getAbsolutePath()); if (!publicDir.exists()) publicDir.mkdirs();// w w w .ja v a 2s . c om String rootPublicURL = ConfigurationManager.getConfiguration().getString("pofmiddleware.pub.url"); String publicURL = rootPublicURL + File.separator + pofId; logger.debug("Publication URL: " + publicURL); List<String> videoList = getFilteredVideoList(sipContentDirPath); numOfVideos = videoList.size(); logger.debug("Video List for Analysis: " + videoList); StringBuilder videoPaths = new StringBuilder(); int i = 0; for (String videoFilePath : videoList) { File videoFile = new File(videoFilePath); String uniqueImageFileName = "vd-" + UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(videoFilePath); File outputFile = new File(publicDir, uniqueImageFileName); try { FileUtils.copyFile(videoFile, outputFile); String videoPath = publicURL + File.separator + outputFile.getName(); logger.debug("videoPath: " + videoList); if (i == 0) videoPaths.append(videoPath); else // Store only the first video .. one video per call videoPaths.append("+" + videoPath); i++; } catch (IOException e) { e.printStackTrace(); } } logger.debug("videoPaths: " + videoPaths); return videoPaths.toString(); }
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 .j a v a 2 s . c o m 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:com.buffalokiwi.aerodrome.jet.JetAPI.java
/** * Sets the configuration data from an authentication request response * @param response Response from login() * @throws JetException if the response does not contain * id_token, token_type or expires_on /*from www . j a v a 2 s. co m*/ * @see JetAPI#login() */ private void setConfigurationDataFromLogin(final IJetAPIResponse response) throws JetException { //..Turn it into JSON final JsonObject res = response.getJsonObject(); try { //..Set the authentication data config.setAuthenticationData(res.getString("id_token"), res.getString("token_type"), res.getString("expires_on")); } catch (NullPointerException e) { throw new JetException("Authentication response is missing id_token, token_type or " + "expires_on. Check authentication response", e); } }
From source file:DesignGUI.java
private void parseStackExchange(String jsonStr) { JsonReader reader = null;//from w w w . ja v a 2 s. c om StringBuilder content = new StringBuilder(); this.jEditorPane_areaShow.setContentType("text/html"); content.append("<html></body>"); try { reader = Json.createReader(new StringReader(jsonStr)); JsonObject jsonObject = reader.readObject(); reader.close(); JsonArray array = jsonObject.getJsonArray("items"); for (JsonObject result : array.getValuesAs(JsonObject.class)) { JsonObject ownerObject = result.getJsonObject("owner"); // int ownerReputation = ownerObject.getInt("reputation"); // System.out.println("Reputation:"+ownerReputation); int viewCount = result.getInt("view_count"); content.append("<br>View Count :" + viewCount + "<br>"); int answerCount = result.getInt("answer_count"); content.append("Answer Count :" + answerCount + "<br>"); String title = result.getString("title"); content.append("Title: <FONT COLOR=green>" + title + "</FONT>.<br>"); String link = result.getString("link"); content.append("URL :<a href="); content.append("'link'>" + link); content.append("</a>.<br>"); // String body = result.getString("body"); // content.append("Body:"+body); /* JsonArray tagsArray = result.getJsonArray("tags"); StringBuilder tagBuilder = new StringBuilder(); int i = 1; for(JsonValue tag : tagsArray){ tagBuilder.append(tag.toString()); if(i < tagsArray.size()) tagBuilder.append(","); i++; } content.append("Tags: "+tagBuilder.toString());*/ } content.append("</body></html>"); this.jEditorPane_areaShow.setText(content.toString()); System.out.println(content.toString()); } catch (Exception e) { e.printStackTrace(); } }
From source file:de.tu_dortmund.ub.data.dswarm.Init.java
public String call() { final String serviceName = config.getProperty(TPUStatics.SERVICE_NAME_IDENTIFIER); final String engineDswarmAPI = config.getProperty(TPUStatics.ENGINE_DSWARM_API_IDENTIFIER); final Optional<Boolean> optionalEnhanceInputDataResource = TPUUtil .getBooleanConfigValue(TPUStatics.ENHANCE_INPUT_DATA_RESOURCE, config); LOG.info(String.format("[%s][%d] Starting 'Init (Task)' ...", serviceName, cnt)); try {/* w w w . ja v a 2s. com*/ final boolean doIngest; final String doIngestString = config.getProperty(TPUStatics.DO_INITIAL_DATA_MODEL_INGEST_IDENTIFIER); if (doIngestString != null && !doIngestString.trim().isEmpty()) { doIngest = Boolean.valueOf(doIngestString); } else { // default = true doIngest = true; } if (doIngest) { LOG.debug("[{}][{}] do data model creation with data ingest", serviceName, cnt); TPUUtil.initSchemaIndices(serviceName, config); } final String configurationFileName = config.getProperty(TPUStatics.CONFIGURATION_NAME_IDENTIFIER); final String configurationJSONString = readFile(configurationFileName, Charsets.UTF_8); final JsonObject configurationJSON = TPUUtil.getJsonObject(configurationJSONString); final String finalInputResourceFile; if (optionalEnhanceInputDataResource.isPresent() && Boolean.TRUE.equals(optionalEnhanceInputDataResource.get())) { final Optional<String> optionalUpdatedInputResourceFile = enhanceInputDataResource(initResourceFile, configurationJSON); if (optionalUpdatedInputResourceFile.isPresent()) { finalInputResourceFile = optionalUpdatedInputResourceFile.get(); } else { finalInputResourceFile = initResourceFile; } } else { finalInputResourceFile = initResourceFile; } final String name = String.format("resource for project '%s'", initResourceFile); final String description = String.format("'resource does not belong to a project' - case %d", cnt); final String inputResourceJson = uploadFileAndCreateResource(finalInputResourceFile, name, description, serviceName, engineDswarmAPI); if (inputResourceJson == null) { final String message = "something went wrong at resource creation"; LOG.error(message); throw new RuntimeException(message); } final JsonObject inputResourceJSON = TPUUtil.getJsonObject(inputResourceJson); final String inputResourceID = inputResourceJSON.getString(DswarmBackendStatics.UUID_IDENTIFIER); LOG.info(String.format("[%s][%d] input resource id = %s", serviceName, cnt, inputResourceID)); if (inputResourceID == null) { final String message = "something went wrong at resource creation, no resource uuid available"; LOG.error(message); throw new RuntimeException(message); } // TODO: refactor this, so that a configuration only needs to be create once per TPU task // create configuration final String finalConfigurationJSONString = createConfiguration(configurationJSONString, serviceName, engineDswarmAPI); if (finalConfigurationJSONString == null) { final String message = "something went wrong at configuration creation"; LOG.error(message); throw new RuntimeException(message); } final JsonObject finalConfigurationJSON = TPUUtil.getJsonObject(finalConfigurationJSONString); final String configurationID = finalConfigurationJSON.getString(DswarmBackendStatics.UUID_IDENTIFIER); LOG.info(String.format("[%s][%d] configuration id = %s", serviceName, cnt, configurationID)); if (configurationID == null) { final String message = "something went wrong at configuration creation, no configuration uuid available"; LOG.error(message); throw new RuntimeException(message); } // check for existing input schema final Optional<JsonObject> optionalInputSchema = getInputSchema(serviceName, engineDswarmAPI); // create the datamodel (will use it's resource) final String dataModelName = String.format("data model %d", cnt); final String dataModelDescription = String.format("data model description %d", cnt); final String dataModelJSONString = createDataModel(inputResourceJSON, finalConfigurationJSON, optionalInputSchema, dataModelName, dataModelDescription, serviceName, engineDswarmAPI, doIngest); if (dataModelJSONString == null) { final String message = "something went wrong at data model creation"; LOG.error(message); throw new RuntimeException(message); } final JsonObject dataModelJSON = TPUUtil.getJsonObject(dataModelJSONString); final String dataModelID = dataModelJSON.getString(DswarmBackendStatics.UUID_IDENTIFIER); LOG.info(String.format("[%s][%d] data model id = %s", serviceName, cnt, dataModelID)); if (dataModelID == null) { final String message = "something went wrong at data model creation, no data model uuid available"; LOG.error(message); throw new RuntimeException(message); } // we don't need to transform after each ingest of a slice of records, // so transform and export will be done separately LOG.info(String.format("[%s][%d] (Note: Only ingest, but no transformation or export done.)", serviceName, cnt)); final StringWriter stringWriter = new StringWriter(); final JsonGenerator jp = Json.createGenerator(stringWriter); jp.writeStartObject(); jp.write(DATA_MODEL_ID, dataModelID); jp.write(RESOURCE_ID, inputResourceID); jp.write(CONFIGURATION_ID, configurationID); jp.writeEnd(); jp.flush(); jp.close(); final String result = stringWriter.toString(); stringWriter.flush(); stringWriter.close(); return result; } catch (final Exception e) { final String message = String.format("[%s][%d] Processing resource '%s' failed with a %s", serviceName, cnt, initResourceFile, e.getClass().getSimpleName()); LOG.error(message, e); throw new RuntimeException(message, e); } }
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(); }//from w w w . j a v a 2 s . 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:eu.forgetit.middleware.component.Extractor.java
public void testZeedAnalysis(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 a2 s . c o m*/ if (jsonBody != null) { String diary = jsonBody.getString("diary"); logger.debug("Retrieved Video Path: " + diary); job.add("diary", diary); String imagePath = jsonBody.getString("imgPath"); logger.debug("Retrieved VAM: " + imagePath); job.add("imgPath", imagePath); // ONE video per call if (diary != null && !diary.isEmpty()) { if (imagePath != null && !imagePath.isEmpty()) { logger.debug( "Executing Zero Example Event Detection Method for image collection: " + imagePath); String response = service.zeed_request(diary, imagePath); logger.debug("Zeed method for text file: " + imagePath + " result:\n" + response); } else { logger.debug("Unable to process image collection, wrong request"); } } else { logger.debug("Unable to process textual information, wrong request"); } } }