List of usage examples for javax.json Json createReader
public static JsonReader createReader(InputStream in)
From source file:de.pangaea.fixo3.CreateEsonetYellowPages.java
private void run() throws OWLOntologyCreationException, OWLOntologyStorageException, FileNotFoundException { m = new OntologyManager(ns); m.addTitle("ESONET Yellow Pages Ontology"); m.addVersion("1.0"); m.addDate("2016-11-23"); m.addCreator("Markus Stocker"); m.addSeeAlso("http://www.esonetyellowpages.com/"); m.addImport(SSN.ns);/* ww w . j a v a2 s. co m*/ m.addSubClass(Frequency, MeasurementProperty); m.addLabel(Frequency, "Frequency"); m.addSubClass(ProfilingRange, MeasurementProperty); m.addLabel(ProfilingRange, "Profiling Range"); m.addSubClass(CellSize, MeasurementProperty); m.addLabel(CellSize, "Cell Size"); m.addSubClass(OperatingDepth, MeasurementProperty); m.addLabel(OperatingDepth, "Operating Depth"); m.addSubClass(TemperatureRange, MeasurementProperty); m.addLabel(TemperatureRange, "Temperature Range"); m.addSubClass(MeasuringRange, MeasurementProperty); m.addLabel(MeasuringRange, "Measuring Range"); m.addClass(WaterCurrent); m.addLabel(WaterCurrent, "Water Current"); m.addSubClass(WaterCurrent, FeatureOfInterest); m.addClass(CarbonDioxide); m.addLabel(CarbonDioxide, "Carbon Dioxide"); m.addSubClass(CarbonDioxide, FeatureOfInterest); m.addClass(Speed); m.addLabel(Speed, "Speed"); m.addSubClass(Speed, Property); m.addObjectSome(Speed, isPropertyOf, WaterCurrent); m.addClass(PartialPressure); m.addLabel(PartialPressure, "Partial Pressure"); m.addSubClass(PartialPressure, Property); m.addObjectSome(PartialPressure, isPropertyOf, CarbonDioxide); m.addClass(DopplerEffect); m.addSubClass(DopplerEffect, Stimulus); m.addLabel(DopplerEffect, "Doppler Effect"); m.addComment(DopplerEffect, "The Doppler effect (or the Doppler shift) is the change in frequency of a wave (or other periodic event) for an observer moving relative to its source."); m.addSource(DopplerEffect, IRI.create("https://en.wikipedia.org/wiki/Doppler_effect")); m.addObjectAll(DopplerEffect, isProxyFor, Speed); m.addClass(Infrared); m.addSubClass(Infrared, Stimulus); m.addLabel(Infrared, "Infrared"); m.addComment(Infrared, "Infrared (IR) is an invisible radiant energy."); m.addSource(Infrared, IRI.create("https://en.wikipedia.org/wiki/Infrared")); m.addObjectAll(Infrared, isProxyFor, PartialPressure); m.addClass(AcousticDopplerCurrentProfiler); m.addLabel(AcousticDopplerCurrentProfiler, "Acoustic Doppler Current Profiler"); m.addSource(AcousticDopplerCurrentProfiler, IRI.create("https://en.wikipedia.org/wiki/Acoustic_Doppler_current_profiler")); m.addComment(AcousticDopplerCurrentProfiler, "An acoustic Doppler current profiler (ADCP) is a hydroacoustic current meter similar to a sonar, attempting to measure water current velocities over a depth range using the Doppler effect of sound waves scattered back from particles within the water column."); m.addObjectAll(AcousticDopplerCurrentProfiler, detects, DopplerEffect); m.addObjectAll(AcousticDopplerCurrentProfiler, observes, Speed); m.addSubClass(AcousticDopplerCurrentProfiler, HydroacousticCurrentMeter); m.addClass(PartialPressureOfCO2Analyzer); m.addLabel(PartialPressureOfCO2Analyzer, "Partial Pressure of CO2 Analyzer"); m.addObjectAll(PartialPressureOfCO2Analyzer, detects, Infrared); m.addObjectAll(PartialPressureOfCO2Analyzer, observes, PartialPressure); m.addSubClass(PartialPressureOfCO2Analyzer, SensingDevice); m.addClass(HydroacousticCurrentMeter); m.addLabel(HydroacousticCurrentMeter, "Hydroacoustic Current Meter"); m.addSubClass(HydroacousticCurrentMeter, SensingDevice); JsonReader jr = Json.createReader(new FileReader(new File(eypDevicesFile))); JsonArray ja = jr.readArray(); for (JsonObject jo : ja.getValuesAs(JsonObject.class)) { String name = jo.getString("name"); String label = jo.getString("label"); String comment = jo.getString("comment"); String seeAlso = jo.getString("seeAlso"); JsonArray equivalentClasses = jo.getJsonArray("equivalentClasses"); JsonArray subClasses = jo.getJsonArray("subClasses"); addDeviceType(name, label, comment, seeAlso, equivalentClasses, subClasses); } m.save(eypFile); m.saveInferred(eypInferredFile); }
From source file:org.grogshop.services.endpoints.impl.ShopItemsServiceImpl.java
@Override public Response newItem(@NotNull @FormParam("user_id") Long userId, @NotNull @FormParam("club_id") Long clubId, @NotNull @FormParam("type") String type, @NotNull @NotEmpty @FormParam("name") String name, @NotNull @NotEmpty @FormParam("description") String description, @NotNull @NotEmpty @FormParam("tags") String tags, @FormParam("minPrice") String minPrice, @FormParam("maxPrice") String maxPrice) throws ServiceException { JsonReader reader = Json.createReader(new ByteArrayInputStream(tags.getBytes())); JsonArray array = reader.readArray(); reader.close();/* w ww. j a v a2 s . c o m*/ List<String> interestsList = new ArrayList<String>(); if (array != null) { for (int i = 0; i < array.size(); i++) { log.info("Tag[" + i + "]: " + array.getJsonObject(i).getString("text")); interestsList.add(array.getJsonObject(i).getString("text")); } } Long newItem = itemsService.newItem(userId, clubId, type, name, description, interestsList, (minPrice == null) ? new BigDecimal(0) : new BigDecimal(minPrice), (maxPrice == null) ? new BigDecimal(0) : new BigDecimal(maxPrice)); return Response.ok(newItem).build(); }
From source file:org.jboss.as.test.integration.logging.formatters.JsonFormatterTestCase.java
@Test public void testNoExceptions() throws Exception { configure(Collections.emptyMap(), Collections.emptyMap(), false); final String msg = "Logging test: JsonFormatterTestCase.testNoExceptions"; int statusCode = getResponse(msg, Collections.singletonMap(LoggingServiceActivator.LOG_EXCEPTION_KEY, "false")); Assert.assertTrue("Invalid response statusCode: " + statusCode, statusCode == HttpStatus.SC_OK); final List<String> expectedKeys = createDefaultKeys(); 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); validateStackTrace(json, false, false); }//from ww w .ja va 2 s . c om } }
From source file:org.kitodo.MockDatabase.java
private static String readMapping() { ClassLoader classloader = Thread.currentThread().getContextClassLoader(); try (InputStream inputStream = classloader.getResourceAsStream("mapping.json")) { if (Objects.nonNull(inputStream)) { String mapping = IOUtils.toString(inputStream, StandardCharsets.UTF_8); try (JsonReader jsonReader = Json.createReader(new StringReader(mapping))) { JsonObject jsonObject = jsonReader.readObject(); return jsonObject.toString(); }//from ww w. j a v a2 s.c om } else { return ""; } } catch (IOException e) { logger.error(e.getMessage(), e); } return ""; }
From source file:com.amazon.alexa.avs.auth.companionservice.CompanionServiceClient.java
JsonObject callService(String path, Map<String, String> parameters) throws IOException { HttpURLConnection con = null; InputStream response = null;//from www . ja v a2s. c om try { String queryString = mapToQueryString(parameters); URL obj = new URL(deviceConfig.getCompanionServiceInfo().getServiceUrl(), path + queryString); con = (HttpURLConnection) obj.openConnection(); if (con instanceof HttpsURLConnection) { ((HttpsURLConnection) con).setSSLSocketFactory(pinnedSSLSocketFactory); } con.setRequestProperty("Content-Type", "application/json"); con.setRequestMethod("GET"); if ((con.getResponseCode() >= 200) || (con.getResponseCode() < 300)) { response = con.getInputStream(); } if (response != null) { String responsestring = IOUtils.toString(response); JsonReader reader = Json .createReader(new ByteArrayInputStream(responsestring.getBytes(StandardCharsets.UTF_8))); IOUtils.closeQuietly(response); return reader.readObject(); } return Json.createObjectBuilder().build(); } catch (IOException e) { if (con != null) { response = con.getErrorStream(); if (response != null) { String responsestring = IOUtils.toString(response); JsonReader reader = Json.createReader( new ByteArrayInputStream(responsestring.getBytes(StandardCharsets.UTF_8))); JsonObject error = reader.readObject(); String errorName = error.getString("error", null); String errorMessage = error.getString("message", null); if (!StringUtils.isBlank(errorName) && !StringUtils.isBlank(errorMessage)) { throw new RemoteServiceException(errorName + ": " + errorMessage); } } } throw e; } finally { if (response != null) { IOUtils.closeQuietly(response); } } }
From source file:de.tu_dortmund.ub.hb_ng.SolRDF.java
@Override public String getAccessRights(String graph, String uri) throws LinkedDataStorageException { this.logger.info("getAccessRights: graph=" + graph); this.logger.info("getAccessRights: uri=" + uri); String accessRights = ""; if (uri.endsWith("/about")) { accessRights = "public"; } else {/* w w w .ja va 2 s .co m*/ // TODO config.properties String sparql = "SELECT ?o WHERE { GRAPH <http://data.ub.tu-dortmund.de/graph/" + this.config.getProperty("storage.graph.main") + "-public> { <" + uri + "/about> <http://purl.org/dc/terms#accessRights> ?o } }"; try { JsonReader jsonReader = Json.createReader( IOUtils.toInputStream(this.sparqlQuery(graph, URLEncoder.encode(sparql, "UTF-8"), "application/sparql-results+json;charset=UTF-8"), "UTF-8")); JsonObject jsonObject = jsonReader.readObject(); JsonArray bindings = jsonObject.getJsonObject("results").getJsonArray("bindings"); if (bindings.size() == 0) { accessRights = "internal"; } else { for (JsonObject binding : bindings.getValuesAs(JsonObject.class)) { accessRights = binding.getJsonObject("o").getJsonString("value").getString(); } } this.logger.info("accessRights: " + accessRights); } catch (IOException e) { this.logger.error("something went wrong", e); throw new LinkedDataStorageException(e.getMessage(), e.getCause()); } } return accessRights; }
From source file:org.jboss.as.test.integration.logging.formatters.JsonFormatterTestCase.java
@Test public void testFormattedException() throws Exception { configure(Collections.emptyMap(), Collections.emptyMap(), false); // Change the exception-output-type executeOperation(/*from ww w. ja v a 2s. c o m*/ Operations.createWriteAttributeOperation(FORMATTER_ADDRESS, "exception-output-type", "formatted")); final String msg = "Logging test: JsonFormatterTestCase.testNoExceptions"; int statusCode = getResponse(msg, Collections.singletonMap(LoggingServiceActivator.LOG_EXCEPTION_KEY, "true")); Assert.assertTrue("Invalid response statusCode: " + statusCode, statusCode == HttpStatus.SC_OK); final List<String> expectedKeys = createDefaultKeys(); expectedKeys.add("stackTrace"); 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); validateStackTrace(json, true, false); } } }
From source file:edu.harvard.hms.dbmi.bd2k.irct.ri.i2b2transmart.I2B2TranSMARTResourceImplementation.java
@Override public Result runQuery(SecureSession session, Query query, Result result) throws ResourceInterfaceException { result = super.runQuery(session, query, result); if (result.getResultStatus() != ResultStatus.ERROR) { String resultInstanceId = result.getResourceActionId(); String resultId = resultInstanceId.split("\\|")[2]; try {//from w w w. j av a2s. co m // Wait for it to be either ready or fail result = checkForResult(session, result); while ((result.getResultStatus() != ResultStatus.ERROR) && (result.getResultStatus() != ResultStatus.COMPLETE)) { Thread.sleep(3000); result = checkForResult(session, result); } if (result.getResultStatus() == ResultStatus.ERROR) { return result; } result.setResultStatus(ResultStatus.RUNNING); // Loop through the select clauses to build up the select string String gatherAllEncounterFacts = "false"; Map<String, String> aliasMap = new HashMap<String, String>(); for (ClauseAbstract clause : query.getClauses().values()) { if (clause instanceof SelectClause) { SelectClause selectClause = (SelectClause) clause; String pui = convertPUItoI2B2Path(selectClause.getParameter().getPui()); aliasMap.put(pui, selectClause.getAlias()); } else if (clause instanceof WhereClause) { WhereClause whereClause = (WhereClause) clause; String encounter = whereClause.getStringValues().get("ENCOUNTER"); if ((encounter != null) && (encounter.equalsIgnoreCase("yes"))) { gatherAllEncounterFacts = "true"; } } } if (!aliasMap.isEmpty()) { ResultSet rs = (ResultSet) result.getData(); if (rs.getSize() == 0) { rs = createInitialDataset(result, aliasMap, gatherAllEncounterFacts); result.setData(rs); } // Loop through the columns submitting and appending to the // rows every 10 List<String> parameterList = new ArrayList<String>(); int counter = 0; String parameters = ""; for (String param : aliasMap.keySet()) { if (counter == 10) { parameterList.add(parameters); counter = 0; parameters = ""; } if (!parameters.equals("")) { parameters += "|"; } parameters += param; } if (!parameters.equals("")) { parameterList.add(parameters); } for (String parameter : parameterList) { // Call the tranSMART API to get the dataset String url = this.transmartURL + "/ClinicalData/retrieveClinicalData?rid=" + resultId + "&conceptPaths=" + URLEncoder.encode(parameter, "UTF-8") + "&gatherAllEncounterFacts=" + gatherAllEncounterFacts; HttpClient client = createClient(session); HttpGet get = new HttpGet(url); try { HttpResponse response = client.execute(get); JsonReader reader = Json.createReader(response.getEntity().getContent()); JsonArray arrayResults = reader.readArray(); // Convert the dataset to Tabular format result = convertJsonToResultSet(result, arrayResults, aliasMap, gatherAllEncounterFacts); } catch (JsonException e) { } } } // Set the status to complete result.setResultStatus(ResultStatus.COMPLETE); } catch (InterruptedException | UnsupportedOperationException | IOException | ResultSetException | PersistableException e) { result.setResultStatus(ResultStatus.ERROR); result.setMessage(e.getMessage()); } } return result; }
From source file:de.tu_dortmund.ub.data.util.TPUUtil.java
public static JsonObject getJsonObject(final String jsonString) throws IOException { final JsonReader jsonReader = Json.createReader(IOUtils.toInputStream(jsonString, APIStatics.UTF_8)); final JsonObject jsonObject = jsonReader.readObject(); jsonReader.close();//w w w. ja v a 2 s.com return jsonObject; }
From source file:io.bitgrillr.gocddockerexecplugin.DockerExecPluginTest.java
@Test public void handleExecute() throws Exception { UnitTestUtils.mockJobConsoleLogger(); PowerMockito.mockStatic(DockerUtils.class); PowerMockito.doNothing().when(DockerUtils.class); DockerUtils.pullImage(anyString());/* ww w . j a v a 2 s . c om*/ when(DockerUtils.createContainer(anyString(), anyString(), anyMap())).thenReturn("123"); when(DockerUtils.getContainerUid(anyString())).thenReturn("4:5"); when(DockerUtils.execCommand(anyString(), any(), any())).thenReturn(0); PowerMockito.doNothing().when(DockerUtils.class); DockerUtils.removeContainer(anyString()); when(DockerUtils.getCommandString(anyString(), any())).thenCallRealMethod(); PowerMockito.mockStatic(SystemHelper.class); when(SystemHelper.getSystemUid()).thenReturn("7:8"); DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest(null, null, "execute"); JsonObject requestBody = Json.createObjectBuilder() .add("config", Json.createObjectBuilder() .add("IMAGE", Json.createObjectBuilder().add("value", "ubuntu:latest").build()) .add("COMMAND", Json.createObjectBuilder().add("value", "echo").build()) .add("ARGUMENTS", Json.createObjectBuilder().add("value", "Hello\nWorld").build()).build()) .add("context", Json.createObjectBuilder().add("workingDirectory", "pipelines/test") .add("environmentVariables", Json.createObjectBuilder().add("TEST1", "value1").add("TEST2", "value2").build()) .build()) .build(); request.setRequestBody(requestBody.toString()); final GoPluginApiResponse response = new DockerExecPlugin().handle(request); PowerMockito.verifyStatic(DockerUtils.class); DockerUtils.pullImage("ubuntu:latest"); PowerMockito.verifyStatic(DockerUtils.class); DockerUtils.createContainer("ubuntu:latest", Paths.get(System.getProperty("user.dir"), "pipelines/test").toAbsolutePath().toString(), Stream.<Map.Entry<String, String>>builder().add(new SimpleEntry<>("TEST1", "value1")) .add(new SimpleEntry<>("TEST2", "value2")).build() .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); PowerMockito.verifyStatic(DockerUtils.class); DockerUtils.getContainerUid("123"); PowerMockito.verifyStatic(DockerUtils.class); DockerUtils.execCommand("123", "root", "chown", "-R", "4:5", "."); PowerMockito.verifyStatic(DockerUtils.class); DockerUtils.execCommand("123", null, "echo", "Hello", "World"); PowerMockito.verifyStatic(DockerUtils.class); DockerUtils.execCommand("123", "root", "chown", "-R", "7:8", "."); PowerMockito.verifyStatic(DockerUtils.class); DockerUtils.removeContainer("123"); assertEquals("Expected 2xx response", DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE, response.responseCode()); final JsonObject responseBody = Json.createReader(new StringReader(response.responseBody())).readObject(); assertEquals("Expected success", Boolean.TRUE, responseBody.getBoolean("success")); assertEquals("Wrong message", "Command 'echo 'Hello' 'World'' completed with status 0", Json.createReader(new StringReader(response.responseBody())).readObject().getString("message")); }