List of usage examples for com.fasterxml.jackson.databind JsonNode asText
public abstract String asText();
From source file:com.reprezen.swagedit.assist.SwaggerProposalProvider.java
protected Collection<String> enumLiterals(TypeDefinition type) { Collection<String> literals = new LinkedHashSet<>(); for (JsonNode literal : type.asJson().get("enum")) { literals.add(literal.asText()); }/*from ww w . j ava2 s . co m*/ return literals; }
From source file:org.apache.streams.riak.http.RiakHttpPersistReader.java
@Override public StreamsResultSet readAll() { Queue<StreamsDatum> readAllQueue = constructQueue(); URIBuilder lk = null;//www .j av a2s. c o m try { lk = new URIBuilder(client.baseURI.toString()); lk.setPath(client.baseURI.getPath().concat("/buckets/" + configuration.getDefaultBucket() + "/keys")); lk.setParameter("keys", "true"); } catch (URISyntaxException e) { LOGGER.warn("URISyntaxException", e); } HttpResponse lkResponse = null; try { HttpGet lkGet = new HttpGet(lk.build()); lkResponse = client.client().execute(lkGet); } catch (IOException e) { LOGGER.warn("IOException", e); return null; } catch (URISyntaxException e) { LOGGER.warn("URISyntaxException", e); return null; } String lkEntityString = null; try { lkEntityString = EntityUtils.toString(lkResponse.getEntity()); } catch (IOException e) { LOGGER.warn("IOException", e); return null; } JsonNode lkEntityNode = null; try { lkEntityNode = MAPPER.readValue(lkEntityString, JsonNode.class); } catch (IOException e) { LOGGER.warn("IOException", e); return null; } ArrayNode keysArray = null; keysArray = (ArrayNode) lkEntityNode.get("keys"); Iterator<JsonNode> keysIterator = keysArray.iterator(); while (keysIterator.hasNext()) { JsonNode keyNode = keysIterator.next(); String key = keyNode.asText(); URIBuilder gk = null; try { gk = new URIBuilder(client.baseURI.toString()); gk.setPath(client.baseURI.getPath() .concat("/buckets/" + configuration.getDefaultBucket() + "/keys/" + key)); } catch (URISyntaxException e) { LOGGER.warn("URISyntaxException", e); continue; } HttpResponse gkResponse = null; try { HttpGet gkGet = new HttpGet(gk.build()); gkResponse = client.client().execute(gkGet); } catch (IOException e) { LOGGER.warn("IOException", e); continue; } catch (URISyntaxException e) { LOGGER.warn("URISyntaxException", e); continue; } String gkEntityString = null; try { gkEntityString = EntityUtils.toString(gkResponse.getEntity()); } catch (IOException e) { LOGGER.warn("IOException", e); continue; } readAllQueue.add(new StreamsDatum(gkEntityString, key)); } return new StreamsResultSet(readAllQueue); }
From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java
public static Schedule parseSchedule(JsonNode node) { // Initialize ObjectMapper Schedule sched = null;// w w w . j a v a 2 s . c om Event event = null; // task or meeting final JsonNode scheduleArray = node.get(Keys.User.SCHEDULE); JsonNode _id; if (scheduleArray.isArray()) { sched = new Schedule(); // start parsing a schedule for (final JsonNode meetingOrTaskNode : scheduleArray) { if ((_id = meetingOrTaskNode.get(Keys._ID)) != null) { // Get the type of event String type = JsonUtils.getJSONValue(meetingOrTaskNode, Keys.TYPE); if (TextUtils.equals(type, "meeting")) { event = new Meeting(); } else if (TextUtils.equals(type, "task")) { event = new Task(); } if (event != null) { event.setID(_id.asText()); event.setTitle(JsonUtils.getJSONValue(meetingOrTaskNode, Keys.Meeting.TITLE)); event.setDescription(JsonUtils.getJSONValue(meetingOrTaskNode, Keys.Meeting.DESC)); event.setStartTime(JsonUtils.getJSONValue(meetingOrTaskNode, Keys.Meeting.START)); event.setEndTime(JsonUtils.getJSONValue(meetingOrTaskNode, Keys.Meeting.END)); // Add event to the schedule if (event instanceof Meeting) sched.addMeeting((Meeting) event); else if (event instanceof Task) sched.addTask((Task) event); else Log.w(TAG + "> getSchedule", "Event cast failure"); } } } // end for } return sched; }
From source file:com.amazonaws.service.apigateway.importer.impl.SchemaTransformer.java
private void removeExampleFromBooleanNode(JsonNode node) { JsonNode refNode = node.path("type"); if (!refNode.isMissingNode()) { if (refNode.asText().equalsIgnoreCase("boolean")) { ((ObjectNode) node).remove("example"); }//from w ww.ja v a2 s. c o m } for (JsonNode child : node) { removeExampleFromBooleanNode(child); } }
From source file:io.appform.jsonrules.utils.ComparisonUtils.java
static int compare(JsonNode evaluatedNode, Object value) { int comparisonResult = 0; if (evaluatedNode.isNumber()) { if (Number.class.isAssignableFrom(value.getClass())) { Number nValue = (Number) value; if (evaluatedNode.isIntegralNumber()) { comparisonResult = Long.compare(evaluatedNode.asLong(), nValue.longValue()); } else if (evaluatedNode.isFloatingPointNumber()) { comparisonResult = Double.compare(evaluatedNode.asDouble(), nValue.doubleValue()); }//w w w.j a v a2 s . c o m } else { throw new IllegalArgumentException("Type mismatch between operator and operand"); } } else if (evaluatedNode.isBoolean()) { if (Boolean.class.isAssignableFrom(value.getClass())) { Boolean bValue = Boolean.parseBoolean(value.toString()); comparisonResult = Boolean.compare(evaluatedNode.asBoolean(), bValue); } else { throw new IllegalArgumentException("Type mismatch between operator and operand"); } } else if (evaluatedNode.isTextual()) { if (String.class.isAssignableFrom(value.getClass())) { comparisonResult = evaluatedNode.asText().compareTo(String.valueOf(value)); } else { throw new IllegalArgumentException("Type mismatch between operator and operand"); } } else if (evaluatedNode.isObject()) { throw new IllegalArgumentException("Object comparisons not supported"); } return comparisonResult; }
From source file:com.ksc.http.JsonErrorResponseHandler.java
@Override public KscServiceException handle(HttpResponse response) throws Exception { JsonContent jsonContent = JsonContent.createJsonContent(response, jsonFactory); JsonNode errorNode = jsonContent.jsonNode.get("Error"); // String errorCode = // errorCodeParser.parseErrorCode(response.getHeaders(), // jsonContent.jsonNode); KscServiceException ase = new KscServiceException("Unable to parse HTTP response content,not Error"); if (errorNode == null) { return ase; }/*from w w w .j a v a2s . c om*/ JsonNode errorCodeNode = errorNode.get("Code"); if (errorCodeNode != null) { ase.setErrorCode(errorCodeNode.asText()); } // Jackson has special-casing for 'message' values when deserializing // Throwables, but sometimes the service passes the error message in // other JSON fields - handle it here. ase.setErrorMessage(errorMessageParser.parseErrorMessage(errorNode)); ase.setServiceName(response.getRequest().getServiceName()); ase.setStatusCode(response.getStatusCode()); ase.setErrorType(getErrorTypeFromStatusCode(response.getStatusCode())); ase.setRawResponse(jsonContent.rawContent); // String requestId = getRequestIdFromHeaders(response.getHeaders()); JsonNode requestIdNode = jsonContent.jsonNode.get("RequestId"); if (requestIdNode != null) { ase.setRequestId(requestIdNode.asText()); } JsonNode errorType = errorNode.get("Type"); if (errorType == null) { ase.setErrorType(ErrorType.Unknown); } else if (errorType.asText().equalsIgnoreCase("Receiver")) { ase.setErrorType(ErrorType.Service); } else if (errorType.asText().equalsIgnoreCase("Sender")) { ase.setErrorType(ErrorType.Client); } return ase; }
From source file:com.redhat.lightblue.config.AbstractMetadataConfiguration.java
@Override public void initializeFromJson(JsonNode node) { if (node != null) { JsonNode x = node.get("hookConfigurationParsers"); if (x != null && x.isArray()) { // each element in array is a class Iterator<JsonNode> elements = ((ArrayNode) x).elements(); while (elements.hasNext()) { JsonNode e = elements.next(); String clazz = e.asText(); // instantiate the class Object o = null;/*w w w . j a v a 2 s . c o m*/ try { o = Class.forName(clazz).newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException ex) { throw Error.get(MetadataConstants.ERR_CONFIG_NOT_VALID, ex.getMessage()); } // add to list or fail if (o instanceof HookConfigurationParser) { hookConfigurationParsers.add((HookConfigurationParser) o); } else { throw Error.get(MetadataConstants.ERR_CONFIG_NOT_VALID, "Class not instance of HookConfigurationParser: " + clazz); } } } ArrayNode backendParsersJs = (ArrayNode) node.get("backendParsers"); if (backendParsersJs != null) { Iterator<JsonNode> bpjsItr = backendParsersJs.iterator(); while (bpjsItr.hasNext()) { JsonNode jsonNode = bpjsItr.next(); String name = jsonNode.get("name").asText(); String clazz = jsonNode.get("clazz").asText(); if (name == null || clazz == null) { throw Error.get(MetadataConstants.ERR_CONFIG_NOT_VALID, "Backend/DataStoreParser class was not informed: name='" + name + "' clazz=" + clazz); } try { DataStoreParser instance = (DataStoreParser) Class.forName(clazz).newInstance(); AbstractMap.SimpleEntry<String, DataStoreParser> stringDataStoreParserSimpleEntry = new AbstractMap.SimpleEntry<>( name, instance); backendParsers.add(stringDataStoreParserSimpleEntry); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw Error.get(MetadataConstants.ERR_CONFIG_NOT_VALID, "Class not instance of Backend/DataStoreParser: " + clazz); } } } ArrayNode propertyParserJs = (ArrayNode) node.get("propertyParsers"); if (propertyParserJs != null) { for (JsonNode jsonNode : propertyParserJs) { String name = jsonNode.get("name").asText(); String clazz = jsonNode.get("clazz").asText(); if (name == null || clazz == null) { throw Error.get(MetadataConstants.ERR_CONFIG_NOT_VALID, "PropertyParser Name/Class not informed: name=" + name + " clazz=" + clazz); } try { PropertyParser instance = (PropertyParser) Class.forName(clazz).newInstance(); AbstractMap.SimpleEntry<String, PropertyParser> stringPropertyParserSimpleEntry = new AbstractMap.SimpleEntry<>( name, instance); propertyParsers.add(stringPropertyParserSimpleEntry); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw Error.get(MetadataConstants.ERR_CONFIG_NOT_VALID, "Class not instance of PropertyParser: " + clazz); } } } JsonNode roleMapJs = node.get("roleMap"); if (roleMapJs != null) { // If the roleMap element is defined, it is expected to have all the roles mapped MetadataRole[] values = MetadataRole.values(); for (MetadataRole value : values) { String name = value.toString(); ArrayNode rolesJs = (ArrayNode) roleMapJs.get(name); if (rolesJs == null || rolesJs.size() == 0) { throw Error.get(MetadataConstants.ERR_CONFIG_NOT_VALID, "roleMap missing the role \"" + name + "\""); } roleMap.put(value, new ArrayList<String>()); for (JsonNode jsonNode : rolesJs) { roleMap.get(value).add(jsonNode.textValue()); } } } x = node.get("validateRequests"); if (x != null) { validateRequests = x.booleanValue(); } } }
From source file:com.epam.catgenome.manager.externaldb.ncbi.NCBIGeneManager.java
private void parseJsonFromBio(final JsonNode biosystemsResultRoot, final JsonNode biosystemsEntries, final NCBIGeneVO ncbiGeneVO) throws JsonProcessingException { if (biosystemsResultRoot.isArray()) { ncbiGeneVO.setPathwaysNumber(biosystemsResultRoot.size()); List<NCBISummaryVO> pathways = new ArrayList<>(biosystemsResultRoot.size()); for (final JsonNode objNode : biosystemsResultRoot) { JsonNode jsonNode = biosystemsEntries.path(RESULT_PATH).get("" + objNode.asText()); NCBISummaryVO biosystemsReference = mapper.treeToValue(jsonNode, NCBISummaryVO.class); biosystemsReference.setLink( String.format(NCBI_BIOSYSTEM_URL, biosystemsReference.getUid(), ncbiGeneVO.getGeneId())); pathways.add(biosystemsReference); }/*from w ww . j a v a 2 s .co m*/ ncbiGeneVO.setBiosystemsReferences(pathways.stream() .sorted(Comparator.comparing(summary -> summary.getBiosystem().getBiosystemname())) .collect(Collectors.toList())); } }
From source file:com.ikanow.aleph2.enrichment.utils.services.SimpleRegexFilterService.java
@Override public void onObjectBatch(Stream<Tuple2<Long, IBatchRecord>> batch, Optional<Integer> batch_size, Optional<JsonNode> grouping_key) { batch.forEach(record -> {//from www . ja v a 2s. com final JsonNode record_json = record._2().getJson(); boolean matched = false; final Iterator<InternalRegexConfig.InternalRegexElement> it_outer = _regex_config.get().elements() .iterator(); while (it_outer.hasNext() && !matched) { final InternalRegexConfig.InternalRegexElement element = it_outer.next(); final Iterator<String> it_inner = element.fields().iterator(); while (it_inner.hasNext() && !matched) { final String field = it_inner.next(); final JsonNode j = record_json.get(field); if ((null != j) && j.isTextual()) { matched |= element.regex().matcher(j.asText()).find(); } } } if (matched) { _context.get().emitImmutableObject(record._1(), record_json, Optional.empty(), Optional.empty(), Optional.empty()); } }); }
From source file:com.redhat.lightblue.metadata.types.BinaryTypeTest.java
License:asdf
@Test public void testFromJsonString() throws IOException { String jsonString = "{\"binaryData\": \"asdf\"}"; JsonNode node = JsonUtils.json(jsonString); assertTrue(node != null);/* w w w . ja va2s. c o m*/ JsonNode binaryDataNode = node.get("binaryData"); assertTrue(binaryDataNode != null); byte[] bytes = binaryDataNode.binaryValue(); assertTrue(bytes != null); assertTrue(bytes.length > 0); // try to convert back to json, verify we get the exact same thing JsonNodeFactory jsonNodeFactory = new JsonNodeFactory(true); JsonNode binaryDataNodeOut = binaryType.toJson(jsonNodeFactory, bytes); assertTrue(binaryDataNodeOut != null); assertEquals("asdf", binaryDataNodeOut.asText()); assertEquals("\"asdf\"", binaryDataNodeOut.toString()); }