List of usage examples for com.fasterxml.jackson.databind ObjectMapper readTree
public JsonNode readTree(URL source) throws IOException, JsonProcessingException
From source file:io.orchestrate.client.SearchOperation.java
/** {@inheritDoc} */ @Override// ww w . j a v a 2 s. co m @SuppressWarnings("unchecked") SearchResults<T> fromResponse(final int status, final HttpHeader httpHeader, final String json, final JacksonMapper mapper) throws IOException { assert (status == 200); final ObjectMapper objectMapper = mapper.getMapper(); final JsonNode jsonNode = objectMapper.readTree(json); final int totalCount = jsonNode.get("total_count").asInt(); final int count = jsonNode.get("count").asInt(); final List<Result<T>> results = new ArrayList<Result<T>>(count); final Iterator<JsonNode> iter = jsonNode.get("results").elements(); while (iter.hasNext()) { final JsonNode result = iter.next(); // parse result structure (e.g.): // {"path":{...},"value":{},"score":1.0} final double score = result.get("score").asDouble(); final KvObject<T> kvObject = jsonToKvObject(objectMapper, result, builder.clazz); results.add(new Result<T>(kvObject, score)); } return new SearchResults<T>(results, totalCount); }
From source file:ac.ucy.cs.spdx.service.SpdxViolationAnalysis.java
@POST @Path("/correct/") @Consumes(MediaType.TEXT_PLAIN)/*from w ww .jav a 2 s .c o m*/ @Produces(MediaType.TEXT_XML) public Response correctSpdx(String jsonString) throws Exception { ObjectMapper mapper = new ObjectMapper(); JsonNode fileNode = null; try { fileNode = mapper.readTree(jsonString); } catch (JsonProcessingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String fileName = fileNode.get("filename").toString(); fileName = fileName.substring(1, fileName.length() - 1); final String LICENSE_HTML = "http://spdx.org/licenses/"; String contentXML = fileNode.get("content").toString(); contentXML = StringEscapeUtils.unescapeXml(contentXML); contentXML = contentXML.substring(1, contentXML.length() - 1); String newDeclared = fileNode.get("declared").toString(); newDeclared = newDeclared.substring(1, newDeclared.length() - 1); String fullpath = ParseRdf.parseToRdf(fileName, contentXML); setLastCorrected(fullpath); File xmlFile = new File(fullpath); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlFile); if (doc.getElementsByTagName("licenseDeclared").item(0).getAttributes() .getNamedItem("rdf:resource") == null) { Element e = (Element) doc.getElementsByTagName("licenseDeclared").item(0); e.setAttribute("rdf:resource", LICENSE_HTML + newDeclared); } else { doc.getElementsByTagName("licenseDeclared").item(0).getAttributes().getNamedItem("rdf:resource") .setNodeValue(LICENSE_HTML + newDeclared); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); PrintWriter writer = new PrintWriter(xmlFile); writer.print(""); writer.close(); StreamResult result = new StreamResult(xmlFile); transformer.transform(source, result); ResponseBuilder response = Response.ok((Object) xmlFile); response.header("Content-Disposition", "attachment; filename=" + fileName); return response.build();// {"filename":"anomos","declared":"Apache-2.0","content":""} }
From source file:fr.irit.sparql.Proxy.SparqlProxy.java
public boolean sendAskQuery(String query) throws SparqlQueryMalFormedException, SparqlEndpointUnreachableException { boolean ret = false; HttpURLConnection connection = null; JsonNode arr = null;//from w w w. j av a 2 s .c o m query = SparqlProxy.cleanString(query); try { URL url = new URL(this.urlServer + "query?output=json&query=" + URLEncoder.encode(query, "UTF-8")); // Create connection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Get Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuilder response = new StringBuilder(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); String jsonRet = response.toString(); ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(jsonRet); // JSONObject json = (JSONObject) JSONSerializer.toJSON(jsonRet); ret = root.get("boolean").asBoolean(); } catch (UnsupportedEncodingException ex) { throw new SparqlQueryMalFormedException("Encoding unsupported"); } catch (MalformedURLException ex) { throw new SparqlQueryMalFormedException("Query malformed"); } catch (IOException ex) { throw new SparqlEndpointUnreachableException(ex); } finally { if (connection != null) { connection.disconnect(); } } return ret; }
From source file:org.hawkular.client.ClientResponse.java
@SuppressWarnings({ "unchecked", "rawtypes" }) public ClientResponse(Class<?> clazz, Response response, int statusCode, String tenantId, Class<? extends Collection> collectionType) { try {//from ww w . j a v a 2s . co m this.setStatusCode(response.getStatus()); if (response.getStatus() == statusCode) { this.setSuccess(true); if (clazz.getName().equalsIgnoreCase(String.class.getName())) { this.setEntity((T) response.readEntity(clazz)); } else if (clazz.getName().equalsIgnoreCase(Condition.class.getName())) { ObjectMapper objectMapper = new ObjectMapper(); String jsonConditions = response.readEntity(String.class); JsonNode rootNode = objectMapper.readTree(jsonConditions); List<Condition> conditions = new ArrayList<>(); if (!(null == jsonConditions || jsonConditions.trim().isEmpty())) { for (JsonNode conditionNode : rootNode) { Condition condition = JacksonDeserializer.deserializeCondition(conditionNode); if (condition == null) { this.setSuccess(false); this.setErrorMsg("Bad json conditions: " + jsonConditions); return; } conditions.add(condition); } } this.setEntity((T) conditions); } else { ObjectMapper objectMapper = new ObjectMapper(); InventoryJacksonConfig.configure(objectMapper); MetricsJacksonConfig.configure(objectMapper); if (clazz.getName().equalsIgnoreCase(Tenant.class.getName())) { objectMapper.addMixIn(CanonicalPath.class, CanonicalPathMixin.class); } else if (tenantId != null) { DetypedPathDeserializer .setCurrentCanonicalOrigin(CanonicalPath.of().tenant(tenantId).get()); } if (collectionType != null) { this.setEntity(objectMapper.readValue(response.readEntity(String.class), objectMapper.getTypeFactory().constructCollectionType(collectionType, clazz))); } else { this.setEntity((T) objectMapper.readValue(response.readEntity(String.class), clazz)); } } } else { this.setErrorMsg(response.readEntity(String.class)); } } catch (JsonParseException e) { _logger.error("Error, ", e); } catch (JsonMappingException e) { _logger.error("Error, ", e); } catch (IOException e) { _logger.error("Error, ", e); } finally { response.close(); if (_logger.isDebugEnabled()) { _logger.debug("Client response:{}", this.toString()); } } }
From source file:com.nebhale.jsonpath.JsonPath.java
/** * Reads content from a JSON payload based on the expression compiled into this instance * * @param json The JSON payload to retrieve data from * @param expectedReturnType The type that the return value is expected to be * * @return The content read from the JSON payload * * @throws InvalidJsonException if the {@code json} argument is not a legal JSON string *///w w w .j a va2 s . co m public <T> T read(String json, Class<T> expectedReturnType) { try { ObjectMapper objectMapper = new ObjectMapper(); JsonNode tree = objectMapper.readTree(json); return read(tree, expectedReturnType); } catch (IOException e) { throw new InvalidJsonException(e); } }
From source file:com.nebhale.jsonpath.JsonPath.java
/** * Reads content from a JSON payload based on the expression compiled into this instance * * @param json The JSON payload to retrieve data from * @param expectedReturnType The type that the return value is expected to be * * @return The content read from the JSON payload * * @throws InvalidJsonException if the {@code json} argument is not a legal JSON string *///from ww w . j a v a 2 s .com public <T> T read(String json, TypeReference<?> expectedReturnType) { try { ObjectMapper objectMapper = new ObjectMapper(); JsonNode tree = objectMapper.readTree(json); return read(tree, expectedReturnType); } catch (IOException e) { throw new InvalidJsonException(e); } }
From source file:com.nebhale.jsonpath.JsonPath.java
/** * Reads content from a JSON payload based on the expression compiled into this instance * * @param json The JSON payload to retrieve data from * @param expectedReturnType The type that the return value is expected to be * * @return The content read from the JSON payload * * @throws InvalidJsonException if the {@code json} argument is not a legal JSON string *//*from w ww . j a va2 s . c o m*/ public <T> T read(String json, JavaType expectedReturnType) { try { ObjectMapper objectMapper = new ObjectMapper(); JsonNode tree = objectMapper.readTree(json); return read(tree, expectedReturnType); } catch (IOException e) { throw new InvalidJsonException(e); } }
From source file:com.msopentech.odatajclient.engine.performance.BasicPerfTest.java
@Test public void readJSONViaLowerlevelLibs() throws IOException { final ObjectMapper mapper = new ObjectMapper(); final JsonNode entry = mapper.readTree(IOUtils.toInputStream(input.get(ODataPubFormat.JSON))); assertNotNull(entry); }
From source file:ac.ucy.cs.spdx.service.SpdxViolationAnalysis.java
@POST @Path("/analyze/") @Consumes(MediaType.TEXT_PLAIN)/*from www . j a v a 2 s .c o m*/ @Produces(MediaType.APPLICATION_JSON) public String analyzeSpdx(String jsonString) { ObjectMapper mapper = new ObjectMapper(); JsonNode spdxFilesContent = null; try { spdxFilesContent = mapper.readTree(jsonString); } catch (JsonProcessingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } ArrayList<SpdxLicensePairConflictError> fileNames = new ArrayList<SpdxLicensePairConflictError>(); for (JsonNode fileNode : spdxFilesContent.get("files")) { String fileName = fileNode.get("filename").toString(); fileName = fileName.substring(1, fileName.length() - 1); String content = fileNode.get("content").toString(); content = StringEscapeUtils.unescapeXml(content); content = content.substring(1, content.length() - 1); try { fileNames.add(new SpdxLicensePairConflictError( new CaptureLicense(ParseRdf.parseToRdf(fileName, content)))); } catch (InvalidLicenseStringException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InvalidSPDXAnalysisException e) { e.printStackTrace(); } catch (UnsupportedSpdxVersionException e) { e.printStackTrace(); } } ViolationAnalysisInfo analysis = null; try { analysis = new ViolationAnalysisInfo( fileNames.toArray(new SpdxLicensePairConflictError[fileNames.size()])); } catch (LicenseNodeNotFoundException e) { e.printStackTrace(); } return analysis.toJson();// {"count":"","files":[{"filename":"","content":""}]} }
From source file:fr.irit.sparql.Proxy.SparqlProxy.java
public ArrayList<JsonNode> getResponse(String query) throws SparqlQueryMalFormedException, SparqlEndpointUnreachableException { HttpURLConnection connection = null; ArrayList<JsonNode> arr = new ArrayList<>(); String jsonRet = ""; query = SparqlProxy.cleanString(query); //System.out.println("Query : "+query); try {/*from w w w. j a v a2s . c o m*/ URL url = new URL(this.urlServer + "query?output=json&query=" + URLEncoder.encode(query, "UTF-8")); // Create connection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Get Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuilder response = new StringBuilder(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); jsonRet = response.toString(); ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(jsonRet); Iterator<JsonNode> i = root.get("results").get("bindings").iterator(); while (i.hasNext()) { arr.add(i.next()); } } catch (MalformedURLException ex) { throw new SparqlQueryMalFormedException("Query malformed : " + query); } catch (UnsupportedEncodingException ex) { throw new SparqlQueryMalFormedException("Encoding unsupported"); } catch (IOException ex) { throw new SparqlEndpointUnreachableException(ex); } finally { if (connection != null) { connection.disconnect(); } } return arr; }