下面列出了怎么用com.fasterxml.jackson.databind.node.MissingNode的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Creates a forked {@link Watcher} based on an existing {@link JsonNode}-watching {@link Watcher}.
*
* @param jsonPointer a <a href="https://tools.ietf.org/html/rfc6901">JSON pointer</a> that is encoded
*
* @return A new child {@link Watcher}, whose transformation is a
* <a href="https://tools.ietf.org/html/rfc6901">JSON pointer</a> query.
*/
static Watcher<JsonNode> atJsonPointer(Watcher<JsonNode> watcher, String jsonPointer) {
requireNonNull(watcher, "watcher");
requireNonNull(jsonPointer, "jsonPointer");
return watcher.newChild(new Function<JsonNode, JsonNode>() {
@Override
public JsonNode apply(JsonNode node) {
if (node == null) {
return MissingNode.getInstance();
} else {
return node.at(jsonPointer);
}
}
@Override
public String toString() {
return "JSON pointer " + jsonPointer;
}
});
}
@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;
}
@Override
JsonNode apply(final JsonNode node) {
if (path.toString().isEmpty()) {
return MissingNode.getInstance();
}
final JsonNode found = node.at(path);
if (found.isMissingNode()) {
return node;
}
final JsonNode parentNode = node.at(path.head());
final String raw = path.last().getMatchingProperty();
if (parentNode.isObject()) {
((ObjectNode) parentNode).remove(raw);
} else if (parentNode.isArray()) {
((ArrayNode) parentNode).remove(Integer.parseInt(raw));
}
return node;
}
/**
* Return COPY of JSON node value (will parse node from string at first call).
* WARNING if object constructed with invalid JSON string, exception will be thrown.
*
* @return Copy of valid JsonNode or MissingNode if no data.
* @throws RuntimeException On JSON parsing errors.
*/
public JsonNode get() throws RuntimeException {
if (!isPresent()) {
return MissingNode.getInstance();
}
if (value == null) {
synchronized (this) {
if (value == null) {
try {
value = ReaderWriter.readTree(source);
} catch (Exception ex) {
throw new RuntimeException("Can not parse JSON string. " + ex.getMessage(), ex);
}
}
}
}
return value.deepCopy();
}
/**
* Returns the asset id in the bid request of the requested index
*
* @param type String. The type of asset
* @param subtype String. sub type of the asset
* @param value int. The integer representation of the entity.
* @return int. Returns the index in the asset object. If not found, returns
* -1
*/
public int getNativeAdAssetIndex(String type, String subtype, int value) {
JsonNode nat = rootNode.path("imp");
if (nat == null || nat.isArray() == false)
return -1;
ArrayNode array = (ArrayNode) nat;
JsonNode node = array.get(0).path("native").path("assets");
ArrayNode nodes = (ArrayNode) node;
for (int i = 0; i < nodes.size(); i++) {
JsonNode asset = nodes.get(i);
JsonNode n = asset.path(type);
JsonNode id = asset.path("id");
if (n instanceof MissingNode == false) {
if (subtype != null) {
n = n.path(subtype);
if (n != null) {
if (n.intValue() == value)
return id.intValue();
}
} else {
return id.intValue();
}
}
}
return -1;
}
@Override
public void attach(String path, DataModelTree tree) throws WorkflowException {
if (root == null || root instanceof MissingNode) {
throw new WorkflowException("Invalid root node");
}
JsonPointer ptr = JsonPointer.compile(path);
if (!(tree instanceof JsonDataModelTree)) {
throw new WorkflowException("Invalid subTree(" + tree + ")");
}
JsonNode attachingNode = ((JsonDataModelTree) tree).root();
attach(ptr, attachingNode);
}
/**
* Allocates json data model tree on json pointer path with specific leaf type.
*
* @param ptr json pointer to allocate
* @param leaftype type of leaf node
* @return json data model tree
* @throws WorkflowException workflow exception
*/
private JsonDataModelTree alloc(JsonPointer ptr, Nodetype leaftype) throws WorkflowException {
if (root == null || root instanceof MissingNode) {
throw new WorkflowException("Invalid root node");
}
switch (leaftype) {
case MAP:
alloc(root, ptr, JsonNodeType.OBJECT);
break;
case ARRAY:
alloc(root, ptr, JsonNodeType.ARRAY);
break;
default:
throw new WorkflowException("Not supported leaftype(" + leaftype + ")");
}
return this;
}
/**
* Creating workplace description from json tree.
* @param root root node for workplace description
* @return workplace description
* @throws WorkflowException workflow exception
*/
public static DefaultWorkplaceDescription valueOf(JsonNode root) throws WorkflowException {
JsonNode node = root.at(ptr(WP_NAME));
if (!(node instanceof TextNode)) {
throw new WorkflowException("invalid workplace name for " + root);
}
Builder builder = builder()
.name(node.asText());
node = root.at(ptr(WP_DATA));
if (node != null && !(node instanceof MissingNode)) {
if (!(node instanceof ObjectNode) && !(node instanceof ArrayNode)) {
throw new WorkflowException("invalid workplace data for " + root);
}
builder.data(node);
}
return builder.build();
}
@Test
public void removeNonExistingRoot() throws PatchApplicationException {
PatchSet patchSet = patchSet(REMOVE, "", null);
JsonNode result = underTest.processPatch(patchSet);
assertThat(result, is(MissingNode.getInstance()));
assertThat(store.get(DOCUMENT_ID), is(nullValue()));
}
@Test
public void removeExistingRoot() throws PatchApplicationException {
store.put(DOCUMENT_ID, jsonNode1);
PatchSet patchSet = patchSet(REMOVE, "", null);
JsonNode result = underTest.processPatch(patchSet);
assertThat(result, is(MissingNode.getInstance()));
assertThat(store.get(DOCUMENT_ID), is(nullValue()));
}
@Test
public void missingNode() throws JsonProcessingException, IOException {
String json = "{ \"a\": { \"b\": {} } }";
JsonNode node = new ObjectMapper().readTree(json);
underTest = new PartitionNodeFunction(KeyPathParser.parse("$.a.b.c"));
JsonNode result = underTest.apply(node);
assertThat(result, is(MissingNode.getInstance()));
}
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;
}
/**
* Converts JsonNode to PrimitiveObject.
*/
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() );
}
}
public static JsonNode path(JsonNode jsonNode, String pathStr) {
String[] splitPaths = pathStr.split("\\.");
jsonNode = jsonNode.path(splitPaths[0]);
if (jsonNode instanceof MissingNode) {
return null;
} else if (splitPaths.length == 1) {
return jsonNode;
} else {
return path(jsonNode, pathStr.substring(pathStr.indexOf(".") + 1));
}
}
public Object getNode(String what) {
Object o = database.get(what);
if (o == null || o instanceof MissingNode) {
return null;
}
return o;
}
/**
* Makes sure the Appnexus keys are available on the creative
* @param c Creative. The creative in question.
* @param sb StringBuilder. The error handling string. Add your error here if not null.
* @returns boolean. Returns true if the Exchange and creative are compatible.
*/
@Override
public boolean checkNonStandard(Creative c, StringBuilder sb) {
if (c.extensions == null || c.extensions.get("appnexus_crid") == null) {
if (sb != null)
sb.append("Creative is not Appnexus compatible");
return false;
}
///////////////////////////
//
// Check for seat id
//
Object obj = interrogate("wseat");
if (obj == null || obj instanceof MissingNode) {
if (sb != null) {
sb.append("appnexus seat missing");
return false;
}
}
ArrayNode list = (ArrayNode) obj;
boolean hasSeat = false;
for (int i = 0; i < list.size(); i++) {
JsonNode nx = list.get(i);
if (nx.asText().equals(Appnexus.seatId)) {
return true;
}
}
if (sb != null)
sb.append("Not our seat");
return false;
}
/**
* Return a JsonNode value as a key
* @param obj Object.
* @return
*/
public static String asString(Object obj) {
if (obj == null)
return null;
if (obj instanceof JsonNode == false)
return obj.toString();
JsonNode node = (JsonNode)obj;
if (node instanceof MissingNode)
return null;
return node.asText();
}
/**
* Return a JsonNode value as a key
* @param obj Object.
* @return
*/
public static String asString(Object obj) {
if (obj == null)
return null;
if (obj instanceof JsonNode == false)
return obj.toString();
JsonNode node = (JsonNode)obj;
if (node instanceof MissingNode)
return null;
return node.asText();
}
private boolean checkGroupExists(String group) throws IOException {
logger.info("checking if group '{}' exists!", group);
String url =
String.format(CONFLUENCE_API_GROUP_PATTERN, confluenceUri, confluenceApiPath, group);
String response = null;
try {
response = getRestClient().execute(httpGet().url(url).returnType(String.class));
Assert.notNull(response, "Response is null for '" + group + "'");
} catch (HttpException e) {
if (HttpStatus.NOT_FOUND.value() == e.getResponseCode()) {
logger.debug("Group '{}' was not found in {}!", group, ADAPTER_NAME, e);
return false;
} else {
logger.warn("Unexpected method trying to get group '{}'!", group, e);
throw e;
}
}
JsonNode json = new ObjectMapper().readTree(response);
JsonNode haveGroup = json.at("/name");
if (MissingNode.class.isInstance(haveGroup)) {
logger.warn("Missing node for '{}'!", json);
return false;
}
return group.equalsIgnoreCase(haveGroup.asText());
}
public Function<List<CheckPreconditionFailure>, List<CheckPreconditionFailure>>
createUserCanCreateProjectCheck(String username) {
return preconditionFailures -> {
logger.info("checking if user '{}' has permissions to create project in Jira!", username);
String url = String.format(JIRA_API_MYPERMISSIONS_PATTERN, jiraUri, jiraApiPath);
try {
String response = getRestClient().execute(httpGet().url(url).returnType(String.class));
Assert.notNull(response, "Response is null for '" + username + "'");
JsonNode json = new ObjectMapper().readTree(response);
String failureMessage =
String.format(
"User '%s' do not have permission 'ADMINISTER' which is required to create a project in Jira!",
username);
JsonNode havePermission = json.at(PERMISSIONS_ADMINISTER_JSON_PATH);
if (MissingNode.class.isInstance(havePermission)) {
logger.warn("Missing node for '{}'!", PERMISSIONS_ADMINISTER_JSON_PATH);
preconditionFailures.add(
CheckPreconditionFailure.getCreateProjectPermissionMissingInstance(failureMessage));
return preconditionFailures;
} else if (!havePermission.asBoolean()) {
logger.debug(failureMessage);
preconditionFailures.add(
CheckPreconditionFailure.getCreateProjectPermissionMissingInstance(failureMessage));
return preconditionFailures;
}
return preconditionFailures;
} catch (IOException e) {
throw new AdapterException(e);
}
};
}
@Test
public void makeHttpRequestsShouldReturnBidRequestsWithoutInventoryAndVisitorDataIfAbsentInPreBidRequest() {
// when
final List<AdapterHttpRequest<BidRequest>> httpRequests = adapter.makeHttpRequests(adapterRequest,
preBidRequestContext);
// then
assertThat(httpRequests)
.flatExtracting(r -> r.getPayload().getImp()).hasSize(1)
.extracting(imp -> imp.getExt().at("/rp/target")).containsOnly(MissingNode.getInstance());
assertThat(httpRequests)
.extracting(r -> r.getPayload().getUser()).isNotNull()
.extracting(User::getExt).containsNull();
}
private void validateCustomProperties(IAPI apiConfig) throws AppException {
if(apiConfig.getCustomProperties()!=null) {
JsonNode configuredProps = APIManagerAdapter.getCustomPropertiesConfig();
Iterator<String> props = apiConfig.getCustomProperties().keySet().iterator();
while(props.hasNext()) {
String propertyKey = props.next();
String propertyValue = apiConfig.getCustomProperties().get(propertyKey);
JsonNode configuredProp = configuredProps.at("/api/"+propertyKey);
if(configuredProp instanceof MissingNode) {
ErrorState.getInstance().setError("The custom-property: '" + propertyKey + "' is not configured in API-Manager.", ErrorCode.CANT_READ_CONFIG_FILE, false);
throw new AppException("The custom-property: '" + propertyKey + "' is not configured in API-Manager.", ErrorCode.CANT_READ_CONFIG_FILE);
}
JsonNode propType = configuredProp.get("type");
if(propType!=null && ( propType.asText().equals("select") || propType.asText().equals("switch") )) {
boolean valueFound = false;
ArrayNode selectOptions = (ArrayNode)configuredProp.get("options");
for(JsonNode option : selectOptions) {
if(option.at("/value").asText().equals(propertyValue)) {
valueFound = true;
break;
}
}
if(!valueFound) {
ErrorState.getInstance().setError("The value: '" + propertyValue + "' isn't configured for custom property: '" + propertyKey + "'", ErrorCode.CANT_READ_CONFIG_FILE, false);
throw new AppException("The value: '" + propertyValue + "' isn't configured for custom property: '" + propertyKey + "'", ErrorCode.CANT_READ_CONFIG_FILE);
}
}
}
}
}
/**
* Retrieves the operating system disk encryption status from the given instance view.
*
* @param instanceView encryption extension instance view
* @return os disk status
*/
static EncryptionStatus osDiskStatus(VirtualMachineExtensionInstanceView instanceView) {
final JsonNode subStatusNode = instanceViewFirstSubStatus(instanceView);
if (subStatusNode == null) {
return EncryptionStatus.UNKNOWN;
}
JsonNode diskNode = subStatusNode.path("os");
if (diskNode instanceof MissingNode) {
return EncryptionStatus.UNKNOWN;
}
return EncryptionStatus.fromString(diskNode.asText());
}
/**
* Retrieves the data disk encryption status from the given instance view.
*
* @param instanceView encryption extension instance view
* @return data disk status
*/
static EncryptionStatus dataDiskStatus(VirtualMachineExtensionInstanceView instanceView) {
final JsonNode subStatusNode = instanceViewFirstSubStatus(instanceView);
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;
}
/**
* Method for locating node specified by given JSON pointer instances.
* Method will never return null; if no matching node exists,
* will return a node for which {@link #isMissingNode()} returns true.
*
* @return Node that matches given JSON Pointer: if no match exists,
* will return a node for which {@link #isMissingNode()} returns true.
*
* @since 2.3
*/
@Override
public final JsonNode at(JsonPointer ptr)
{
// Basically: value nodes only match if we have "empty" path left
if (ptr.matches()) {
return this;
}
JsonNode n = _at(ptr);
if (n == null) {
return MissingNode.getInstance();
}
return n.at(ptr.tail());
}
protected boolean isActive(String path, Predicate<JsonNode> matcher, boolean defaultValue) {
readLock().lock();
try {
JsonNode array = getConfiguration().path(JsonConstants.ACTIVATION).path(path);
return createStream(array).filter(matcher)
.findAny().orElseGet(MissingNode::getInstance)
.path(JsonConstants.ACTIVE).asBoolean(defaultValue);
} finally {
readLock().unlock();
}
}
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);
}
}
protected JsonNode lookupPath(JsonNode source, String path) {
JsonNode s = source;
for (String component : path.substring(1).split("/")) {
if (s.isArray()) {
try {
s = s.path(Integer.parseInt(component));
} catch (NumberFormatException e) {
return MissingNode.getInstance();
}
} else {
s = s.path(component);
}
}
return s;
}
private TreeNode fromString(String source) {
if (source == null || source.isEmpty()) {
// This is where we replace null result with empty node
return MissingNode.getInstance();
} else {
// I really hope that source will be valid JSON string (^_^)
return new TreeNodeLazyWrapper(source);
}
}