下面列出了怎么用com.fasterxml.jackson.databind.node.ValueNode的API类实例代码及写法,或者点击链接到github查看源代码。
private static void updateObject(JsonNode target,
ValueNode value,
Map.Entry<String, JsonNode> src) {
boolean newEntry = true;
Iterator<Map.Entry<String, JsonNode>> iter = target.fields();
while (iter.hasNext()) {
Map.Entry<String, JsonNode> entry = iter.next();
if (entry.getKey().equals(src.getKey())) {
newEntry = false;
entry.setValue(value);
}
}
if (newEntry) {
((ObjectNode) target).replace(src.getKey(), src.getValue());
}
}
public static String resultToJson(final Object result, final ObjectMapper objectMapper) throws IOException {
if (result == null) {
return null;
}
if (result instanceof String) {
String resultStr = (String) result;
if (resultStr.isEmpty()) {
return null;
}
JsonNode jsonNode = objectMapper.readTree(resultStr);
if (!(jsonNode instanceof ValueNode)) {
return resultStr;
}
}
return objectMapper.writeValueAsString(result);
}
@Override
public void onValueNode(ValueNode node, Optional<ContainerNode<?>> parent, List<PathElement> path) {
String value = node.isTextual() ? node.textValue() : node.toString();
List<Placeholder> placeholders = extractPlaceholders(value);
if (!placeholders.isEmpty()) {
for (Placeholder placeholder : placeholders) {
if (placeholder.hasDefaultValue()) {
String valueWithReplacements = replacePlaceholder(value, placeholder.name(), placeholder.defaultValue());
last(path).setChild(parent.get(), TextNode.valueOf(valueWithReplacements));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("At {}, replaced {} with {}", new Object[]{path, value, valueWithReplacements});
}
}
}
}
}
public void jsonToMap(String currentPath, JsonNode jsonNode, Map<String, String> map) {
if (jsonNode.isObject()) {
ObjectNode objectNode = (ObjectNode) jsonNode;
Iterator<Entry<String, JsonNode>> iter = objectNode.fields();
String pathPrefix = currentPath.isEmpty() ? "" : currentPath + ".";
while (iter.hasNext()) {
Entry<String, JsonNode> entry = iter.next();
jsonToMap(pathPrefix + entry.getKey(), entry.getValue(), map);
}
} else if (jsonNode.isArray()) {
ArrayNode arrayNode = (ArrayNode) jsonNode;
for (int i = 0; i < arrayNode.size(); i++) {
jsonToMap(currentPath + "." + i, arrayNode.get(i), map);
}
} else if (jsonNode.isValueNode()) {
ValueNode valueNode = (ValueNode) jsonNode;
map.put(currentPath, valueNode.asText());
}
}
private void addKeys(String currentPath, JsonNode jsonNode, Map<Object, Object> props) {
if (jsonNode.isObject()) {
ObjectNode objectNode = (ObjectNode) jsonNode;
Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
String pathPrefix = currentPath.isEmpty() ? "" : currentPath + ".";
while (iter.hasNext()) {
Map.Entry<String, JsonNode> entry = iter.next();
addKeys(pathPrefix + entry.getKey(), entry.getValue(), props);
}
} else if (jsonNode.isArray()) {
ArrayNode arrayNode = (ArrayNode) jsonNode;
for (int i = 0; i < arrayNode.size(); i++) {
addKeys(currentPath + "[" + i + "]", arrayNode.get(i), props);
}
} else if (jsonNode.isValueNode()) {
ValueNode valueNode = (ValueNode) jsonNode;
if(isAllowOverride || !props.containsKey(currentPath))
props.put(currentPath, valueNode.asText());
}
}
/**
* Creates a new JSON-RPC request as a JSON object
*
* @param id request id
* @param method request method
* @param params request params
* @return a new request as a JSON object
*/
@NotNull
protected ObjectNode request(@NotNull ValueNode id, @NotNull String method,
@NotNull JsonNode params) {
if (method.isEmpty()) {
throw new IllegalArgumentException("Method is not set");
}
ObjectNode requestNode = mapper.createObjectNode();
requestNode.put(JSONRPC, VERSION_2_0);
requestNode.put(METHOD, method);
requestNode.set(PARAMS, params);
if (!id.isNull()) {
requestNode.set(ID, id);
}
return requestNode;
}
private static void buildConfigFor(String path, Map<String, String> config, JsonNode node) {
for (Iterator<Map.Entry<String, JsonNode>> i = node.fields(); i.hasNext();) {
Map.Entry<String, JsonNode> field = i.next();
if (field.getValue() instanceof ValueNode) {
ValueNode valueNode = (ValueNode) field.getValue();
config.put(DOT_JOINER.join(path, field.getKey()), valueNode.asText());
} else if (field.getValue() instanceof ArrayNode) {
StringBuilder combinedValue = new StringBuilder();
ArrayNode arrayNode = (ArrayNode) field.getValue();
for (Iterator<JsonNode> it = arrayNode.elements(); it.hasNext();) {
String value = it.next().asText().replaceAll("^\"|\"$", "");
if (combinedValue.length() > 0)
combinedValue.append(',');
combinedValue.append(value);
}
config.put(DOT_JOINER.join(path, field.getKey()), combinedValue.toString());
}
buildConfigFor(DOT_JOINER.join(path, field.getKey()), config, field.getValue());
}
}
private <P> PaginatedList<T> pagedQueryView(String viewName, P startKey, P endKey, PaginationOffset<P> pagination, boolean descending, Function<P, ValueNode> startToNode) {
int limit = pagination.getLimit() != null ? pagination.getLimit() : DEFAULT_LIMIT;
int page = pagination.getPage() != null ? pagination.getPage() : 0;
String startDocId = pagination.getStartDocumentId();
ViewQuery viewQuery = createQuery(viewName)
.startKey(startKey)
.includeDocs(true)
.startDocId(startDocId)
.limit(limit)
.descending(descending);
if (endKey != null) {
viewQuery = viewQuery.endKey(endKey);
}
PageRequest.Builder builder = new PageRequest.Builder().pageSize(limit).page(page);
if (startKey !=null || startDocId != null) {
builder.nextKey(new PageRequest.KeyIdPair(pagination.getStartKey() == null ? null : startToNode.apply(pagination.getStartKey()), startDocId)).page(Math.max(page,1));
}
PageRequest pr = builder.build();
Page<T> ts = db.queryForPage(viewQuery, pr, type);
Object sk = ts.getTotalSize() > ts.getPageSize() && ts.getNextPageRequest() != null ? ts.getNextPageRequest().getStartKey() : null;
return new PaginatedList<>(
ts.getPageSize(),
ts.getTotalSize(),
ts.getRows(),
sk != null ?
new PaginatedDocumentKeyIdPair((sk instanceof NullNode) ? null : (sk instanceof LongNode) ? Collections.singletonList(""+((LongNode) sk).longValue()) : Collections.singletonList(((TextNode) sk).textValue()), ts.getNextPageRequest().getStartKeyDocId())
: null
);
}
@Override
public void onValueNode(ValueNode node, Optional<ContainerNode<?>> parent, List<PathElement> pathAsList) {
String path = new NodePath(pathAsList).toString();
String value = node.isTextual() ? node.textValue() : node.toString();
List<Placeholder> placeholders = extractPlaceholders(value);
if (placeholders.isEmpty() && !resolved.containsKey(path)) {
resolved.put(path, value);
passAgain = true;
} else {
boolean changes = false;
for (Placeholder placeholder : placeholders) {
String replacement = resolved.get(placeholder.name());
if (replacement != null) {
String valueWithReplacements = replacePlaceholder(value, placeholder.name(), replacement);
last(pathAsList).setChild(parent.get(), TextNode.valueOf(valueWithReplacements));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("At {}, replaced {} with {}", new Object[]{pathAsList, value, valueWithReplacements});
}
value = valueWithReplacements;
changes = true;
}
}
passAgain |= changes;
}
}
@Override
public void onValueNode(ValueNode node, Optional<ContainerNode<?>> parent, List<PathElement> path) {
String value = node.isTextual() ? node.textValue() : node.toString();
List<String> placeholders = extractPlaceholderStrings(value);
if (!placeholders.isEmpty()) {
String pathString = new NodePath(path).toString();
for (String placeholder : placeholders) {
unresolvedPlaceholderDescriptions.add(new UnresolvedPlaceholder(pathString, value, placeholder));
}
}
}
public static Object getValueFromJsonNode(JsonNode node) throws JSONException {
Object value = null;
if (node instanceof TextNode) {
value = ((TextNode) (node)).textValue();
} else if (node instanceof ObjectNode) {
value = toJSONObject((ObjectNode) node);
} else if (node instanceof ArrayNode) {
value = toJSONArray((ArrayNode) node);
} else if (node instanceof ValueNode) {
value = ((ValueNode) node).asText();
}
return value;
}
public void flattenJsonIntoMap(String currentPath, JsonNode jsonNode, Map<String, Object> map) {
if (jsonNode.isObject()) {
ObjectNode objectNode = (ObjectNode) jsonNode;
Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
String pathPrefix = currentPath.isEmpty() ? "" : currentPath + ".";
while (iter.hasNext()) {
Map.Entry<String, JsonNode> entry = iter.next();
flattenJsonIntoMap(pathPrefix + entry.getKey(), entry.getValue(), map);
}
} else if (jsonNode.isArray()) {
ArrayNode arrayNode = (ArrayNode) jsonNode;
for (int i = 0; i < arrayNode.size(); i++) {
flattenJsonIntoMap(currentPath + "[" + i + "]", arrayNode.get(i), map);
}
} else if (jsonNode.isValueNode()) {
ValueNode valueNode = (ValueNode) jsonNode;
Object value = null;
if (valueNode.isNumber()) {
value = valueNode.numberValue();
} else if (valueNode.isBoolean()) {
value = valueNode.asBoolean();
} else if (valueNode.isTextual()){
value = valueNode.asText();
}
map.put(currentPath, value);
}
}
private Duration deserializeObject(TreeNode tree, DeserializationContext c)
throws JsonMappingException {
if (tree == null) {
throw c.mappingException("expected object");
}
TreeNode node;
ValueNode valueNode;
final long duration;
final TimeUnit unit;
if ((node = tree.get("duration")) != null && node.isValueNode() &&
(valueNode = (ValueNode) node).isNumber()) {
duration = valueNode.asLong();
} else {
throw c.mappingException("duration is not a numeric field");
}
if ((node = tree.get("unit")) != null && node.isValueNode() &&
(valueNode = (ValueNode) node).isTextual()) {
unit = TimeUnit.valueOf(valueNode.asText().toUpperCase());
} else {
unit = Duration.DEFAULT_UNIT;
}
return new Duration(duration, unit);
}
private void flattenJsonTree(String currentPath, JsonNode jsonNode, ByteArrayOutputStream out)
throws SerializationException {
if (jsonNode.isObject()) {
ObjectNode objectNode = (ObjectNode) jsonNode;
Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
String pathPrefix = currentPath.isEmpty() ? "" : currentPath + ".";
while (iter.hasNext()) {
Map.Entry<String, JsonNode> entry = iter.next();
flattenJsonTree(pathPrefix + entry.getKey(), entry.getValue(), out);
}
} else if (jsonNode.isArray()) {
throw new SerializationException("Arrays in JSON are not supported yet.");
} else if (jsonNode.isValueNode()) {
ValueNode valueNode = (ValueNode) jsonNode;
if (!fieldMapping.containsField(currentPath)) {
fieldMapping.put(currentPath, delimiters[currentDelimiterIdx++], getNodeType(jsonNode));
} else {
DataType existingType = fieldMapping.getDataType(currentPath);
DataType newType = getNodeType(valueNode);
if (existingType != newType) {
DataType encapsulatingType = DataType.encapsulatingType(existingType, newType);
fieldMapping.updateType(currentPath, encapsulatingType);
}
}
try {
byte fieldByte = fieldMapping.getDelimiter(currentPath);
out.write(fieldByte);
out.write(valueNode.asText().getBytes());
out.write(fieldByte);
} catch (IOException e) {
throw new SerializationException(e.getMessage());
}
}
}
@Override
public CustomAttribute deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
CustomAttribute cda = null;
final String currentName = jp.getParsingContext().getCurrentName();
final ObjectMapper mapper = (ObjectMapper) jp.getCodec();
final ValueNode vNode = mapper.readTree(jp);
if (vNode.asToken().isScalarValue()) {
if (vNode.getNodeType() == JsonNodeType.BOOLEAN) {
cda = new CustomAttribute<Boolean>(currentName, vNode.asBoolean(), Boolean.class);
} else if (vNode.getNodeType() == JsonNodeType.STRING) {
cda = new CustomAttribute<String>(currentName, vNode.asText(), String.class);
} else if (vNode.getNodeType() == JsonNodeType.NUMBER) {
final NumericNode nNode = (NumericNode) vNode;
if (currentName.endsWith("_at")) {
cda = new CustomAttribute<Long>(currentName, vNode.longValue(), Long.class);
} else if (nNode.isInt()) {
cda = new CustomAttribute<Integer>(currentName, vNode.intValue(), Integer.class);
} else if (nNode.isFloat()) {
cda = new CustomAttribute<Float>(currentName, vNode.floatValue(), Float.class);
} else if (nNode.isDouble()) {
cda = new CustomAttribute<Double>(currentName, vNode.doubleValue(), Double.class);
} else if (nNode.isLong()) {
cda = new CustomAttribute<Long>(currentName, vNode.longValue(), Long.class);
} else {
cda = new CustomAttribute<String>(currentName, vNode.asText(), String.class);
}
} else {
cda = new CustomAttribute<String>(currentName, vNode.asText(), String.class);
}
}
return cda;
}
public void setActualId(ValueNode id) {
actualId = id;
if (actualId instanceof TextNode) {
externalId = actualId.asText();
} else if (actualId instanceof IntNode) {
this.id = actualId.asInt();
}
}
public Request(@JsonProperty("jsonrpc") @Nullable String jsonrpc,
@JsonProperty("method") @Nullable String method,
@JsonProperty("params") @NotNull JsonNode params,
@JsonProperty("id") @NotNull ValueNode id) {
this.jsonrpc = jsonrpc;
this.method = method;
this.id = id;
this.params = params;
}
private Call(ValueNode node, Optional<ContainerNode<?>> parent, List<PathElement> path) {
this.node = node;
this.parent = parent;
this.path = path;
}
private void addKeys(String currentPath, JsonNode jsonNode, Map<String, JsonPathData> map, List<JsonNodeType> knownTypes) {
if (jsonNode.isObject()) {
ObjectNode objectNode = (ObjectNode) jsonNode;
Iterator<Map.Entry<String, JsonNode>> iterator = objectNode.fields();
String pathPrefix = currentPath.isEmpty() ? "" : currentPath + ".";
if (knownTypes == null)
knownTypes = new ArrayList<>();
knownTypes.add(JsonNodeType.OBJECT);
while (iterator.hasNext()) {
Map.Entry<String, JsonNode> entry = iterator.next();
addKeys(pathPrefix + entry.getKey(), entry.getValue(), map, new ArrayList<>(knownTypes));
}
} else if (jsonNode.isArray()) {
ArrayNode arrayNode = (ArrayNode) jsonNode;
if (currentPath.isEmpty())
currentPath = "root";
if (knownTypes == null)
knownTypes = new ArrayList<>();
knownTypes.add(JsonNodeType.ARRAY);
for (int i = 0; i < arrayNode.size(); i++) {
addKeys(currentPath + "." + i, arrayNode.get(i), map, new ArrayList<>(knownTypes));
}
} else if (jsonNode.isValueNode()) {
ValueNode valueNode = (ValueNode) jsonNode;
if (knownTypes == null)
knownTypes = new ArrayList<>();
knownTypes.add(valueNode.getNodeType());
JsonPathData.JsonPathDataBuilder data = JsonPathData.builder().types(knownTypes);
switch (valueNode.getNodeType()) {
case NUMBER: {
if (valueNode.asText().contains("."))
map.put(currentPath, data.value(valueNode.asDouble()).build());
else
map.put(currentPath, data.value(valueNode.asLong()).build());
break;
}
case BOOLEAN: {
map.put(currentPath, data.value(valueNode.asBoolean()).build());
break;
}
default: {
map.put(currentPath, data.value(valueNode.asText()).build());
break;
}
}
}
}
@Override
public Subscription.Topic deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
final ObjectMapper mapper = (ObjectMapper) jp.getCodec();
final ValueNode vNode = mapper.readTree(jp);
return Subscription.Topic.valueOf(vNode.asText());
}
public ValueNode getActualId() {
return actualId;
}
/**
* Performs single JSON-RPC request and return JSON-RPC response
*
* @param request JSON-RPC request as a Java object
* @param service service object
* @return JSON-RPC response as a Java object
* @throws Exception in case of a runtime error (reflections, business logic...)
*/
@NotNull
private Response handleSingle(@NotNull Request request, @NotNull Object service) throws Exception {
// Check mandatory fields and correct protocol version
String requestMethod = request.getMethod();
String jsonrpc = request.getJsonrpc();
ValueNode id = request.getId();
if (jsonrpc == null || requestMethod == null) {
log.error("Not a JSON-RPC request: " + request);
return new ErrorResponse(id, INVALID_REQUEST);
}
if (!jsonrpc.equals(VERSION)) {
log.error("Not a JSON_RPC 2.0 request: " + request);
return new ErrorResponse(id, INVALID_REQUEST);
}
JsonNode params = request.getParams();
if (!params.isObject() && !params.isArray() && !params.isNull()) {
log.error("Params of request: '" + request + "' should be an object, an array or null");
return new ErrorResponse(id, INVALID_REQUEST);
}
ClassMetadata classMetadata = classesMetadata.get(service.getClass());
if (!classMetadata.isService()) {
log.warn(service.getClass() + " is not available as a JSON-RPC 2.0 service");
return new ErrorResponse(id, METHOD_NOT_FOUND);
}
MethodMetadata method = classMetadata.getMethods().get(requestMethod);
if (method == null) {
log.error("Unable find a method: '" + requestMethod + "' in a " + service.getClass());
return new ErrorResponse(id, METHOD_NOT_FOUND);
}
ContainerNode<?> notNullParams = !params.isNull() ?
(ContainerNode<?>) params : mapper.createObjectNode();
Object[] methodParams;
try {
methodParams = convertToMethodParams(notNullParams, method);
} catch (IllegalArgumentException e) {
log.error("Bad params: " + notNullParams + " of a method '" + method.getName() + "'", e);
return new ErrorResponse(id, INVALID_PARAMS);
}
Object result = method.getMethod().invoke(service, methodParams);
return new SuccessResponse(id, result);
}
public SuccessResponse(@JsonProperty("id") @NotNull ValueNode id,
@JsonProperty("result") @Nullable Object result) {
super(id);
this.result = result;
}
public Response(@NotNull ValueNode id) {
this.id = id;
jsonrpc = VERSION;
}
public Response(@NotNull ValueNode id, @NotNull String jsonrpc) {
this.id = id;
this.jsonrpc = jsonrpc;
}
@NotNull
public ValueNode getId() {
return id;
}
@JsonCreator
public ErrorResponse(@JsonProperty("id") @NotNull ValueNode id,
@JsonProperty("error") @NotNull ErrorMessage error) {
super(id);
this.error = error;
}
@NotNull
public ValueNode getId() {
return id;
}
@Activate
public void activate() {
appId = coreService.registerApplication("org.onosproject.workplacestore");
log.info("appId=" + appId);
KryoNamespace workplaceNamespace = KryoNamespace.newBuilder()
.register(KryoNamespaces.API)
.register(WorkflowData.class)
.register(Workplace.class)
.register(DefaultWorkplace.class)
.register(WorkflowContext.class)
.register(DefaultWorkflowContext.class)
.register(SystemWorkflowContext.class)
.register(WorkflowState.class)
.register(ProgramCounter.class)
.register(DataModelTree.class)
.register(JsonDataModelTree.class)
.register(List.class)
.register(ArrayList.class)
.register(JsonNode.class)
.register(ObjectNode.class)
.register(TextNode.class)
.register(LinkedHashMap.class)
.register(ArrayNode.class)
.register(BaseJsonNode.class)
.register(BigIntegerNode.class)
.register(BinaryNode.class)
.register(BooleanNode.class)
.register(ContainerNode.class)
.register(DecimalNode.class)
.register(DoubleNode.class)
.register(FloatNode.class)
.register(IntNode.class)
.register(JsonNodeType.class)
.register(LongNode.class)
.register(MissingNode.class)
.register(NullNode.class)
.register(NumericNode.class)
.register(POJONode.class)
.register(ShortNode.class)
.register(ValueNode.class)
.register(JsonNodeCreator.class)
.register(JsonNodeFactory.class)
.build();
localWorkplaceMap.clear();
workplaceMap = storageService.<String, WorkflowData>consistentMapBuilder()
.withSerializer(Serializer.using(workplaceNamespace))
.withName("workplace-map")
.withApplicationId(appId)
.build();
workplaceMap.addListener(workplaceMapEventListener);
localContextMap.clear();
contextMap = storageService.<String, WorkflowData>consistentMapBuilder()
.withSerializer(Serializer.using(workplaceNamespace))
.withName("workflow-context-map")
.withApplicationId(appId)
.build();
contextMap.addListener(contextMapEventListener);
workplaceMapEventListener.syncLocal();
contextMapEventListener.syncLocal();
log.info("Started");
}
void onValueNode(ValueNode node, Optional<ContainerNode<?>> parent, List<PathElement> path);