@Override JsonNode apply(final JsonNode node) { if (path.toString().isEmpty()) { return MissingNode.getInstance(); } ensureExistence(node); final JsonNode parentNode = node.at(path.head()); final String raw = path.last().getMatchingProperty(); if (parentNode.isObject()) { ((ObjectNode) parentNode).remove(raw); } else { ((ArrayNode) parentNode).remove(Integer.parseInt(raw)); } return node; }
/** * Traverses the argument {@link JsonNode} to find any contained * {@code JsonNode JsonNodes} which match the argument cohort, if * present. * * If {@code node} is an {@code ArrayNode}, then the array is * traversed and the first matching filter node, if any, is * returned. * * @param node A {@code JsonNode} to traverse in search of cohort * information. * @param cohortOpt An optional cohort string to match against the * argument {@code JsonNode}. * @return A {@code JsonNode} matching the specified cohort, or else * {@link MissingNode}. */ public static JsonNode findByCohort(JsonNode node, Optional<String> cohortOpt) { if (node.isObject() && ToggleJsonNode.matchesCohort(node, cohortOpt)) { return node; } else if (node.isArray()) { final Iterator<JsonNode> iterator = node.elements(); while (iterator.hasNext()) { final JsonNode containedNode = iterator.next(); if (containedNode.isObject() && ToggleJsonNode.matchesCohort(containedNode, cohortOpt)) { return containedNode; } } return MissingNode.getInstance(); } else { return MissingNode.getInstance(); } }
/** * Recursively search for the JsonNode for the specified key. If found, this function will return an ObjectNode containing the key with underlying JsonNode. * For instance, if searching for "key2" in JSON "{key1:{key2:{key3:value}}}" this will return "{key2:{key3:value}}" * @param jn the JsonNode to search in * @param key the key to search for * @return the found object with {key:JsonNode} or MissingNode if not found */ public JsonNode searchKey(JsonNode jn, String key){ //this is a null node or a leaf node if(jn == null || !jn.isContainerNode()) { return MissingNode.getInstance(); } //yay, found it! //extract value and place it in clean wrapper ObjectNode with the key if(jn.has(key)) { return om.createObjectNode().set(key, jn.get(key)); } //not found on this level... try to go deeper for (JsonNode child : jn) { if (child.isContainerNode()) { JsonNode childResult = searchKey(child, key); if (childResult != null && !childResult.isMissingNode()) { return childResult; } } } // not found at all return MissingNode.getInstance(); }
/** * Build an array of email subscribers and batch insert via bulk MailChimp API * Reference: https://developer.mailchimp.com/documentation/mailchimp/reference/lists/#create-post_lists_list_id * * @param node the data * @param task the task * @return the report response * @throws JsonProcessingException the json processing exception */ ReportResponse push(final ObjectNode node, PluginTask task) throws JsonProcessingException { String endpoint = MessageFormat.format(mailchimpEndpoint + "/lists/{0}", task.getListId()); JsonNode response = client.sendRequest(endpoint, HttpMethod.POST, node.toString(), task); client.avoidFlushAPI("Process next request"); if (response instanceof MissingNode) { ReportResponse reportResponse = new ReportResponse(); reportResponse.setErrors(new ArrayList<ErrorResponse>()); return reportResponse; } return mapper.treeToValue(response, ReportResponse.class); }
@Override public Resource deserialize(JsonParser parser, DeserializationContext context) throws IOException { TreeNode tree = parser.readValueAsTree(); Assert.isTrue(tree.path("rClass") != MissingNode.getInstance(), "No 'rClass' field found. Cannot deserialize Resource JSON."); RClass rClass = modelService.resolveRType(((TextNode) tree.path("rClass")).textValue()); if (rClass.isAbstract()) { throw new AbstractRClassException(rClass); } Resource resource = factory.createResource(rClass); TreeNode properties = tree.path("properties"); if (properties instanceof ObjectNode) { populateProperties((ObjectNode) properties, resource); } return resource; }
/** * Constructs a {@link JsonNode} from a JSON string. * * @param json A string encoding a JSON object * @return A {@code JsonNode} if the argument string is valid, otherwise * {@link MissingNode}. */ public static JsonNode fromString(String json) { try { return DEFAULT_OBJECT_READER.readTree(json); } catch (IOException err) { return MissingNode.getInstance(); } }
public JsonNode getJson() { if (isValid()) { return json; } else { return MissingNode.getInstance(); } }
@Override public EncryptionStatus osDiskStatus() { if (!hasEncryptionExtension()) { return EncryptionStatus.NOT_ENCRYPTED; } final JsonNode subStatusNode = instanceViewFirstSubStatus(); if (subStatusNode == null) { return EncryptionStatus.UNKNOWN; } JsonNode diskNode = subStatusNode.path("os"); if (diskNode instanceof MissingNode) { return EncryptionStatus.UNKNOWN; } return EncryptionStatus.fromString(diskNode.asText()); }
@Override public EncryptionStatus dataDiskStatus() { if (!hasEncryptionExtension()) { return EncryptionStatus.NOT_ENCRYPTED; } final JsonNode subStatusNode = instanceViewFirstSubStatus(); if (subStatusNode == null) { return EncryptionStatus.UNKNOWN; } JsonNode diskNode = subStatusNode.path("data"); if (diskNode instanceof MissingNode) { return EncryptionStatus.UNKNOWN; } return EncryptionStatus.fromString(diskNode.asText()); }
private static String extractCapturedImageUri(String capturedResultJson) { ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode; try { rootNode = mapper.readTree(capturedResultJson); } catch (IOException exception) { throw new RuntimeException("Parsing JSON failed -" + capturedResultJson, exception); } JsonNode resourcesNode = rootNode.path("resources"); if (resourcesNode instanceof MissingNode) { throw new IllegalArgumentException("Expected 'resources' node not found in the capture result -" + capturedResultJson); } String imageUri = null; for (JsonNode resourceNode : resourcesNode) { JsonNode propertiesNodes = resourceNode.path("properties"); if (!(propertiesNodes instanceof MissingNode)) { JsonNode storageProfileNode = propertiesNodes.path("storageProfile"); if (!(storageProfileNode instanceof MissingNode)) { JsonNode osDiskNode = storageProfileNode.path("osDisk"); if (!(osDiskNode instanceof MissingNode)) { JsonNode imageNode = osDiskNode.path("image"); if (!(imageNode instanceof MissingNode)) { JsonNode uriNode = imageNode.path("uri"); if (!(uriNode instanceof MissingNode)) { imageUri = uriNode.asText(); } } } } } } if (imageUri == null) { throw new IllegalArgumentException("Could not locate image uri under expected section in the capture result -" + capturedResultJson); } return imageUri; }
public static PrimitiveObject get( final JsonNode jsonNode ) throws IOException{ if( jsonNode instanceof TextNode ){ return new StringObj( ( (TextNode)jsonNode ).textValue() ); } else if( jsonNode instanceof BooleanNode ){ return new BooleanObj( ( (BooleanNode)jsonNode ).booleanValue() ); } else if( jsonNode instanceof IntNode ){ return new IntegerObj( ( (IntNode)jsonNode ).intValue() ); } else if( jsonNode instanceof LongNode ){ return new LongObj( ( (LongNode)jsonNode ).longValue() ); } else if( jsonNode instanceof DoubleNode ){ return new DoubleObj( ( (DoubleNode)jsonNode ).doubleValue() ); } else if( jsonNode instanceof BigIntegerNode ){ return new StringObj( ( (BigIntegerNode)jsonNode ).bigIntegerValue().toString() ); } else if( jsonNode instanceof DecimalNode ){ return new StringObj( ( (DecimalNode)jsonNode ).decimalValue().toString() ); } else if( jsonNode instanceof BinaryNode ){ return new BytesObj( ( (BinaryNode)jsonNode ).binaryValue() ); } else if( jsonNode instanceof POJONode ){ return new BytesObj( ( (POJONode)jsonNode ).binaryValue() ); } else if( jsonNode instanceof NullNode ){ return NullObj.getInstance(); } else if( jsonNode instanceof MissingNode ){ return NullObj.getInstance(); } else{ return new StringObj( jsonNode.toString() ); } }
@Test public void shouldReturnBaseClaimWhenParsingMissingNode() throws Exception { JsonNode value = MissingNode.getInstance(); Claim claim = claimFromNode(value); assertThat(claim, is(notNullValue())); assertThat(claim, is(instanceOf(NullClaim.class))); assertThat(claim.isNull(), is(true)); }
private static void checkContextData(LogEvent logEvent, String mdcKeyRegex, final JsonNode rootNode) { final Pattern mdcKeyPattern = mdcKeyRegex == null ? null : Pattern.compile(mdcKeyRegex); logEvent.getContextData().forEach(new BiConsumer<String, Object>() { @Override public void accept(String key, Object value) { JsonNode node = point(rootNode, "mdc", key); boolean matches = mdcKeyPattern == null || mdcKeyPattern.matcher(key).matches(); if (matches) { assertThat(node.asText()).isEqualTo(value); } else { assertThat(node).isEqualTo(MissingNode.getInstance()); } } }); }
@Override public JsonNode evaluate(FunctionArgs args, EvaluationContext context) { final String value = valueParam.required(args, context); try { return objectMapper.readTree(value); } catch (IOException e) { log.warn("Unable to parse JSON", e); } return MissingNode.getInstance(); }
private static Matcher<JsonNode> createNodeMatcher(final JsonNode value) { final JsonNodeType nodeType = value.getNodeType(); switch (nodeType) { case ARRAY: return IsJsonArray.jsonArray((ArrayNode) value); case BINARY: throw new UnsupportedOperationException( "Expected value contains a binary node, which is not implemented."); case BOOLEAN: return IsJsonBoolean.jsonBoolean((BooleanNode) value); case MISSING: return IsJsonMissing.jsonMissing((MissingNode) value); case NULL: return IsJsonNull.jsonNull((NullNode) value); case NUMBER: return IsJsonNumber.jsonNumber((NumericNode) value); case OBJECT: return IsJsonObject.jsonObject((ObjectNode) value); case POJO: throw new UnsupportedOperationException( "Expected value contains a POJO node, which is not implemented."); case STRING: return IsJsonText.jsonText((TextNode) value); default: throw new UnsupportedOperationException("Unsupported node type " + nodeType); } }
/** * Attempt to decode the input as JSON. Returns the {@link JsonNode} if * the decode is successful. * * If the decode fails and the {@code failQuietly} flag is true, returns a * {@link MissingNode}. Otherwise an {@link IllegalArgumentException} will * be thrown. */ public static JsonNode decode(String input, boolean failQuietly) { try { return MAPPER.readTree(input); } catch (IOException e) { if (failQuietly) { return MissingNode.getInstance(); } throw new IllegalArgumentException("Unable to decode JSON", e); } }
/** * Uses a String path to create a List of keys in order to move * through a nested ${@link JsonNode} in order to find a specific * value. If the value is found, it is returned. If it can not be * found, a ${@link MissingNode} will be returned. * * @param node the node to use for the search * @param path the path to find the value for * @return a ${@link JsonNode} if found, a ${@link MissingNode} if not * @throws ParseException if any parsing issues occur */ public static JsonNode get(JsonNode node, String path) throws ParseException { // check for bad targets if (node == null) { return MissingNode.getInstance(); } // create a list of keys from the path List<NotedKey> keys = keys(path); // store a cheap reference JsonNode tmp = node; // grab length int lastIndex = keys.size() - 1; // go through every key we have (except the last) for(int i = 0; i < lastIndex; i++) { tmp = DotUtils.findNode(tmp, keys.get(i)); // if we've hit a dead end if (tmp.isMissingNode() || tmp.isNull()) { // short-circuit return tmp; } } // get the last key from the list NotedKey key = keys.get(lastIndex); // if the key is a Number if (key.isNumber()) { // return the ArrayNode index return tmp.path(key.asNumber()); } // return the ObjectNode value return tmp.path(key.asString()); }
@Test public void iteratesMissingValues() throws Exception { final ObjectNode objectNode = factory.objectNode(); objectNode.set("test", MissingNode.getInstance()); final int[] iterator = new int[]{0}; DotNotes.recurse(objectNode, new DotNotes.NodeIterator() { @Override protected void execute(NotedKey key, JsonNode value, String path) { iterator[0]++; assertNotNull(key); assertTrue(key.isString()); assertEquals(key.asString(), "test"); assertNotNull(value); assertTrue(value.isMissingNode()); assertNotNull(path); assertEquals(path, "test"); } }); assertEquals(iterator[0], 1); }
private static JsonNode locateNode(JsonNode tree, DecoderColumnHandle columnHandle) { String mapping = columnHandle.getMapping(); checkState(mapping != null, "No mapping for %s", columnHandle.getName()); JsonNode currentNode = tree; for (String pathElement : Splitter.on('/').omitEmptyStrings().split(mapping)) { if (!currentNode.has(pathElement)) { return MissingNode.getInstance(); } currentNode = currentNode.path(pathElement); } return currentNode; }
private static JsonNode locateNode(JsonNode tree, KinesisColumnHandle columnHandle) { String mapping = columnHandle.getMapping(); checkState(mapping != null, "No mapping for %s", columnHandle.getName()); JsonNode currentNode = tree; for (String pathElement : Splitter.on('/').omitEmptyStrings().split(mapping)) { if (!currentNode.has(pathElement)) { return MissingNode.getInstance(); } currentNode = currentNode.path(pathElement); } return currentNode; }
private JsonNode readJson (final byte[] data) { if (data == null) { return MissingNode.getInstance (); } final String stringContent = new String (data, Charset.forName ("UTF-8")); try { return new ObjectMapper().readTree (stringContent); } catch (IOException e) { log.error (e, "Unable to read ZooKeeper service payload, ignoring."); return MissingNode.getInstance (); } }
@NotNull protected Tuple2<Integer, JsonNode> fetchJson(final String rel, final boolean post) throws Exception { final JsonFactory factory = new JsonFactory(); final HttpURLConnection conn = (HttpURLConnection) resolve(rel).toURL().openConnection(); try { conn.setRequestMethod(post ? "POST" : "GET"); conn.setRequestProperty("Accept", "application/json"); conn.connect(); final int responseCode = conn.getResponseCode(); InputStream in; try { in = conn.getInputStream(); } catch (final IOException e) { in = conn.getErrorStream(); } if (in == null) { return Tuple2.tuple2(responseCode, (JsonNode) MissingNode.getInstance()); } assertEquals("application/json", conn.getHeaderField("Content-Type")); try { final ObjectMapper om = new ObjectMapper(); return Tuple2.tuple2(responseCode, om.reader() .with(factory) .readTree(in)); } finally { in.close(); } } finally { conn.disconnect(); } }
/** * Convert a {@link JsonNode} to a specified value type. * * @param node * @param clazz * @return * @since 0.6.2 */ @SuppressWarnings("unchecked") public static <T> T convertValue(JsonNode node, Class<T> clazz) { if (clazz == null) { throw new NullPointerException("Class parameter is null!"); } if (node == null || node instanceof NullNode || node instanceof MissingNode) { return null; } if (Number.class.isAssignableFrom(clazz) || byte.class == clazz || short.class == clazz || int.class == clazz || long.class == clazz || float.class == clazz || double.class == clazz) { return convertNumber(node, clazz); } if (clazz == Boolean.class || clazz == boolean.class) { return (T) convertBoolean(node); } if (clazz == Character.class || clazz == char.class) { return (T) convertChar(node); } if (Date.class.isAssignableFrom(clazz)) { return (T) convertDate(node); } if (Object[].class.isAssignableFrom(clazz) || List.class.isAssignableFrom(clazz)) { return (T) convertArrayOrList(node); } if (clazz.isAssignableFrom(node.getClass())) { return (T) node; } if (clazz == String.class) { return (T) (node.isTextual() ? node.asText() : node.toString()); } throw new IllegalArgumentException( "Cannot convert an object of type [" + node.getClass() + "] to [" + clazz + "]!"); }
private static JsonNode extractValue(JsonNode node, String index) { if (node == null || node instanceof NullNode || node instanceof MissingNode) { return null; } Matcher m = PATTERN_INDEX.matcher(index); if (m.matches()) { try { int i = Integer.parseInt(m.group(1)); if (node instanceof ArrayNode) { if (i >= 0 && i < node.size()) { return node.get(i); } else { throw new IndexOutOfBoundsException(String.valueOf(i)); } } throw new IllegalArgumentException("Expect an ArrayNode for index [" + index + "] but received [" + node.getClass() + "] instead."); } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid index value: " + index, e); } } if (node instanceof ObjectNode) { return node.get(index); } throw new IllegalArgumentException( "Unsupported type [" + node.getClass() + "] or invalid index [" + index + "]"); }
@org.junit.Test public void testSetValue2() { JacksonUtils.setValue(COMPANY, "employees[0]", null); JsonNode nullNow = JacksonUtils.getValue(COMPANY, "employees[0]"); assertTrue( nullNow == null || nullNow instanceof NullNode || nullNow instanceof MissingNode); }
@org.junit.Test public void testSetValue2() { DPathUtils.setValue(COMPANY, "employees[0]", null); JsonNode nullNow = DPathUtils.getValue(COMPANY, "employees[0]"); assertTrue( nullNow == null || nullNow instanceof NullNode || nullNow instanceof MissingNode); }
private JsonNode readJsonNode(JsonNode jsonNode, String field) { return jsonNode.has(field) ? jsonNode.get(field) : MissingNode.getInstance(); }
public static Matcher<JsonNode> jsonMissing(MissingNode value) { return IsJsonMissing.jsonMissing(value); }
@SuppressWarnings("unused") public static Matcher<JsonNode> jsonMissing(final MissingNode value) { return jsonMissing(); }
@Override protected boolean matchesNode(MissingNode node, Description mismatchDescription) { return true; }
@Test public void testType() throws Exception { final Matcher<JsonNode> sut = jsonMissing(); assertThat(MissingNode.getInstance(), is(sut)); }
@Test public void testLiteral() throws Exception { final Matcher<JsonNode> sut = jsonMissing(MissingNode.getInstance()); assertThat(MissingNode.getInstance(), is(sut)); }
@Test public void testMatch() throws Exception { final Matcher<JsonNode> sut = jsonMissing(); assertThat(MissingNode.getInstance(), is(sut)); }
public Context(JsonNode node, StringBuilder buf, Locale locale) { this.currentFrame = new Frame(null, node == null ? MissingNode.getInstance() : node); this.buf = buf == null ? new StringBuilder() : buf; this.javaLocale = locale == null ? Locale.getDefault() : locale; // this.cldrLocale = ??? TODO: replace with lookup }
@Override public JsonNode toJsonNode() { return value .map(JsonValue::toJsonNode) .orElse(MissingNode.getInstance()); }
public JsonNode sendRequest(final String endpoint, final HttpMethod method, final String content, final MailChimpOutputPluginDelegate.PluginTask task) { try (final Jetty92RetryHelper retryHelper = createRetryHelper(task)) { final String authorizationHeader = getAuthorizationHeader(task); String responseBody = retryHelper.requestWithRetry( new StringJetty92ResponseEntityReader(task.getTimeoutMillis()), new Jetty92SingleRequester() { @Override public void requestOnce(HttpClient client, Response.Listener responseListener) { Request request = client .newRequest(endpoint) .timeout(task.getTimeoutMillis(), TimeUnit.MILLISECONDS) .accept("application/json") .method(method); if (method == HttpMethod.POST || method == HttpMethod.PUT) { request.content(new StringContentProvider(content), "application/json;utf-8"); } if (!authorizationHeader.isEmpty()) { request.header("Authorization", authorizationHeader); } request.send(responseListener); } @Override public boolean isResponseStatusToRetry(Response response) { int status = response.getStatus(); return status == 429 || status / 100 != 4; } @Override protected boolean isExceptionToRetry(Exception exception) { LOG.error("Exception to retry.", exception); // This check is to make sure the exception is retryable, e.g: server not found, internal server error... if (exception instanceof ConfigException || exception instanceof ExecutionException) { return toRetry((Exception) exception.getCause()); } return exception instanceof TimeoutException || super.isExceptionToRetry(exception); } }); return responseBody != null && !responseBody.isEmpty() ? parseJson(responseBody) : MissingNode.getInstance(); } catch (Exception ex) { LOG.error("Exception occurred while sending request.", ex); throw Throwables.propagate(ex); } }
@Override public Schema missing(MissingNode ignored) { throw new UnsupportedOperationException("MissingNode is not supported."); }
private static <T> T visit(JsonNode node, JsonTreeVisitor<T> visitor) { switch (node.getNodeType()) { case OBJECT: Preconditions.checkArgument(node instanceof ObjectNode, "Expected instance of ObjectNode: " + node); // use LinkedHashMap to preserve field order Map<String, T> fields = Maps.newLinkedHashMap(); Iterator<Map.Entry<String, JsonNode>> iter = node.fields(); while (iter.hasNext()) { Map.Entry<String, JsonNode> entry = iter.next(); visitor.recordLevels.push(entry.getKey()); fields.put(entry.getKey(), visit(entry.getValue(), visitor)); visitor.recordLevels.pop(); } return visitor.object((ObjectNode) node, fields); case ARRAY: Preconditions.checkArgument(node instanceof ArrayNode, "Expected instance of ArrayNode: " + node); List<T> elements = Lists.newArrayListWithExpectedSize(node.size()); for (JsonNode element : node) { elements.add(visit(element, visitor)); } return visitor.array((ArrayNode) node, elements); case BINARY: Preconditions.checkArgument(node instanceof BinaryNode, "Expected instance of BinaryNode: " + node); return visitor.binary((BinaryNode) node); case STRING: Preconditions.checkArgument(node instanceof TextNode, "Expected instance of TextNode: " + node); return visitor.text((TextNode) node); case NUMBER: Preconditions.checkArgument(node instanceof NumericNode, "Expected instance of NumericNode: " + node); return visitor.number((NumericNode) node); case BOOLEAN: Preconditions.checkArgument(node instanceof BooleanNode, "Expected instance of BooleanNode: " + node); return visitor.bool((BooleanNode) node); case MISSING: Preconditions.checkArgument(node instanceof MissingNode, "Expected instance of MissingNode: " + node); return visitor.missing((MissingNode) node); case NULL: Preconditions.checkArgument(node instanceof NullNode, "Expected instance of NullNode: " + node); return visitor.nullNode((NullNode) node); default: throw new IllegalArgumentException( "Unknown node type: " + node.getNodeType() + ": " + node); } }