下面列出了com.fasterxml.jackson.databind.node.ArrayNode#get ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public List<String> getCurrentActivityInstances(ServerConfig serverConfig, String processInstanceId) {
URIBuilder builder = clientUtil.createUriBuilder(MessageFormat.format(CURRENT_ACTIVITY_INSTANCE_LIST_URL, processInstanceId));
HttpGet get = new HttpGet(clientUtil.getServerUrl(serverConfig, builder));
JsonNode node = clientUtil.executeRequest(get, serverConfig);
List<String> result = new ArrayList<>();
if (node.isArray()) {
ArrayNode data = (ArrayNode) node;
for (int i = 0; i < data.size(); i++) {
if (data.get(i) != null) {
result.add(data.get(i).asText());
}
}
}
return result;
}
@Test
public void T_write_equalsSetValue_withNestingArrayFromParser() throws IOException {
JacksonArrayFormatter formatter = new JacksonArrayFormatter();
JsonNode node = formatter.writeParser( new TestParentParser( true ) );
assertTrue( ( node instanceof ArrayNode ) );
ArrayNode parentNode = (ArrayNode)node;
assertEquals( parentNode.size() , 1 );
JsonNode childNode = parentNode.get(0);
assertTrue( ( childNode instanceof ArrayNode ) );
ArrayNode arrayNode = (ArrayNode)childNode;
assertEquals( arrayNode.size() , 3 );
assertTrue( arrayNode.get(0).isTextual() );
assertTrue( arrayNode.get(1).isTextual() );
assertTrue( arrayNode.get(2).isTextual() );
assertEquals( arrayNode.get(0).asText() , "a" );
assertEquals( arrayNode.get(1).asText() , "b" );
assertEquals( arrayNode.get(2).asText() , "c" );
}
@Test
public void getRecordWithMoreThanOneObjectTest() {
// Setup:
String newIRI = "http://test.com/record";
Record recordWithAnotherObject = recordFactory.createNew(vf.createIRI(newIRI));
recordWithAnotherObject.getModel().add(vf.createIRI("http://test.com/subject"), vf.createIRI("http://test.com/subject"), vf.createLiteral("test"));
when(catalogManager.getRecord(any(Resource.class), any(Resource.class), any(OrmFactory.class))).thenReturn(Optional.of(recordWithAnotherObject));
Response response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(newIRI))
.request().get();
assertEquals(response.getStatus(), 200);
verify(catalogManager).getRecord(vf.createIRI(LOCAL_IRI), vf.createIRI(newIRI), recordFactory);
try {
ArrayNode arr = (ArrayNode) mapper.readTree(response.readEntity(String.class));
JsonNode firstRecord = arr.get(0);
assertTrue(firstRecord.has("@id"));
assertEquals(firstRecord.get("@id").textValue(), newIRI);
} catch (Exception e) {
fail("Expected no exception, but got: " + e.getMessage());
}
}
@Test
public void testFilterValid() throws Exception {
setMockResponse(200, "{\"result\": 6}");
Query queryParams = new Query.Builder(QueryType.COUNT)
.withEventCollection(TEST_EVENT_COLLECTION)
.withFilter(TEST_TARGET_PROPERTY, FilterOperator.LESS_THAN, 5)
.withFilter(TEST_TARGET_PROPERTY, FilterOperator.GREATER_THAN, 1)
.build();
String requestString = mockCaptureCountQueryRequest(queryParams);
ObjectNode requestNode = (ObjectNode) OBJECT_MAPPER.readTree(requestString);
assertEquals(2, requestNode.size());
ArrayNode filtersNode = (ArrayNode) requestNode.get("filters");
ObjectNode filter1Node = (ObjectNode) filtersNode.get(0);
ObjectNode filter2Node = (ObjectNode) filtersNode.get(1);
assertEquals(TEST_EVENT_COLLECTION, requestNode.get(KeenQueryConstants.EVENT_COLLECTION).asText());
assertEquals(TEST_TARGET_PROPERTY, filter1Node.get("property_name").asText());
assertEquals("lt", filter1Node.get("operator").asText());
assertEquals(5, filter1Node.get("property_value").asInt());
assertEquals(TEST_TARGET_PROPERTY, filter2Node.get("property_name").asText());
assertEquals("gt", filter2Node.get("operator").asText());
assertEquals(1, filter2Node.get("property_value").asInt());
}
/**
* 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;
}
private String getDownloadUrl(ArrayNode assetsNode) {
for (int i = 0; i < assetsNode.size(); i++) {
JsonNode jsonNode = assetsNode.get(i);
if (!jsonNode.isObject()) {
continue;
}
JsonNode nameNode = jsonNode.get("name");
if (!nameNode.isTextual()) {
continue;
}
String name = nameNode.asText();
if (!name.contains("pinpoint-agent")) {
continue;
}
JsonNode downloadNode = jsonNode.get("browser_download_url");
if (!downloadNode.isTextual()) {
continue;
}
String download = downloadNode.asText();
if (!StringUtils.isEmpty(download)) {
return download;
}
}
return null;
}
@Test
public void testNotifyJson() {
Map<String, PropertyType> properties = new HashMap<>();
properties.put("name", PropertyType.STRING);
this.sqlgGraph.getTopology().ensureSchemaExist("A").ensureVertexLabelExist("A", properties);
this.sqlgGraph.tx().commit();
List<Vertex> logs = this.sqlgGraph.topology().V().hasLabel(Topology.SQLG_SCHEMA + "." + Topology.SQLG_SCHEMA_LOG).toList();
assertEquals(1, logs.size());
Vertex log = logs.get(0);
JsonNode jsonLog = log.value(Topology.SQLG_SCHEMA_LOG_LOG);
JsonNode schemas = jsonLog.get("uncommittedSchemas");
assertNotNull("A", schemas);
assertTrue(schemas instanceof ArrayNode);
ArrayNode schemasArray = (ArrayNode)schemas;
assertEquals(1, schemasArray.size());
JsonNode aSchema = schemasArray.get(0);
assertEquals("A", aSchema.get("name").asText());
JsonNode uncommittedVertexLabels = aSchema.get("uncommittedVertexLabels");
assertNotNull(uncommittedVertexLabels);
assertTrue(uncommittedVertexLabels instanceof ArrayNode);
ArrayNode uncommittedVertexLabelsArray = (ArrayNode)uncommittedVertexLabels;
assertEquals(1, uncommittedVertexLabelsArray.size());
JsonNode vertexLabel = uncommittedVertexLabels.get(0);
assertEquals("A", vertexLabel.get("label").asText());
JsonNode propertiesJson = vertexLabel.get("uncommittedProperties");
assertNotNull(propertiesJson);
assertTrue(propertiesJson instanceof ArrayNode);
ArrayNode propertiesArray = (ArrayNode)propertiesJson;
assertEquals(1, propertiesArray.size());
}
@Override
public WampMessage fromObjectArray(ArrayNode messageNode) throws WampError {
if (messageNode.size() != 4
|| !messageNode.get(1).canConvertToLong()
|| !messageNode.get(2).isObject()
|| !messageNode.get(3).isTextual())
throw new WampError(ApplicationError.INVALID_MESSAGE);
long requestId = messageNode.get(1).asLong();
ObjectNode options = (ObjectNode) messageNode.get(2);
String topic = messageNode.get(3).asText();
return new SubscribeMessage(requestId, options, topic);
}
@Override
public WampMessage fromObjectArray(ArrayNode messageNode) throws WampError {
if (messageNode.size() != 3
|| !messageNode.get(1).canConvertToLong()
|| !messageNode.get(2).isObject())
throw new WampError(ApplicationError.INVALID_MESSAGE);
long sessionId = messageNode.get(1).asLong();
ObjectNode details = (ObjectNode) messageNode.get(2);
return new WelcomeMessage(sessionId, details);
}
@Override
public WampMessage fromObjectArray(ArrayNode messageNode) throws WampError {
if (messageNode.size() != 3
|| !messageNode.get(1).isTextual()
|| !messageNode.get(2).isObject())
throw new WampError(ApplicationError.INVALID_MESSAGE);
String signature = messageNode.get(1).asText();
ObjectNode extra = (ObjectNode) messageNode.get(2);
return new AuthenticateMessage(signature, extra);
}
@Test
public void getRecordTest() {
Response response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(RECORD_IRI))
.request().get();
assertEquals(response.getStatus(), 200);
verify(catalogManager).getRecord(vf.createIRI(LOCAL_IRI), vf.createIRI(RECORD_IRI), recordFactory);
try {
ArrayNode arr = (ArrayNode) mapper.readTree(response.readEntity(String.class));
JsonNode firstRecord = arr.get(0);
assertTrue(firstRecord.has("@id"));
assertEquals(firstRecord.get("@id").textValue(), RECORD_IRI);
} catch (Exception e) {
fail("Expected no exception, but got: " + e.getMessage());
}
}
public List<FilterSpec> deserialize(JsonNode jsonNode, ResourceInformation resourceInformation, QueryContext queryContext) {
// we support both the serialized FilterSpec (crnk-specific) and a more compact, user-friendly format
if (isSerializedFilterSpec(jsonNode)) {
ObjectMapper objectMapper = context.getObjectMapper();
try {
ObjectReader pathReader = objectMapper.readerFor(PathSpec.class);
ArrayNode arrayNode = (ArrayNode) jsonNode;
List<FilterSpec> filterSpecs = new ArrayList<>();
for (int i = 0; i < arrayNode.size(); i++) {
JsonNode filterNode = arrayNode.get(i);
JsonNode pathNode = filterNode.get("path");
JsonNode opNode = filterNode.get("operator");
JsonNode valueNode = filterNode.get("value");
JsonNode expressionNode = filterNode.get("expression");
FilterOperator operator = null;
if (opNode != null && !opNode.isNull()) {
operator = supportedOperators.get(opNode.asText());
if (operator == null) {
throw new BadRequestException("unknown operator " + opNode.asText());
}
}else{
operator = defaultOperator;
}
PathSpec pathSpec = pathNode != null && !pathNode.isNull() ? pathReader.readValue(pathNode) : null;
Object value = valueNode != null && !valueNode.isNull() ? deserializeJsonFilterValue(resourceInformation, pathSpec, valueNode, queryContext) : null;
List<FilterSpec> expressions = expressionNode != null && !expressionNode.isNull() ? deserialize(expressionNode, resourceInformation, queryContext) : null;
filterSpecs.add(expressions != null ? new FilterSpec(operator, expressions) : new FilterSpec(pathSpec, operator, value));
}
return filterSpecs;
}
catch (IOException e) {
throw new BadRequestException("failed to parse parameter", e);
}
}
return deserialize(jsonNode, resourceInformation, PathSpec.empty(), queryContext);
}
private void parseNodeContractInput(ArrayNode inputArray, NodeBusinessObjectInput rootNodeInput) {
for (int i = 0; i < inputArray.size(); i++) {
JsonNode childNode = inputArray.get(i);
if (childNode.has(REFERENCE)) {
NodeBusinessObjectInput nodeContractInput = newNodeContractInput(childNode, rootNodeInput);
rootNodeInput.addInput(nodeContractInput);
parseNodeContractInput(childInput(childNode), nodeContractInput);
} else {
rootNodeInput.addInput(newLeafContractInput(childNode, inputType(childNode)));
}
}
}
@Override
public void callService(final PluginParameters parameters, final InputStream in, final OutputStream out) throws IOException {
final String graphId = parameters.getStringValue(GRAPH_ID_PARAMETER_ID);
final boolean completeWithSchema = parameters.getBooleanValue(COMPLETE_PARAMETER_ID);
final String arrange = parameters.getStringValue(ARRANGE_PARAMETER_ID);
final boolean resetView = parameters.getBooleanValue(RESET_PARAMETER_ID);
final RecordStore rs = new GraphRecordStore();
final ObjectMapper mapper = new ObjectMapper();
final JsonNode json = mapper.readTree(in);
// We want to read a JSON document that looks like:
//
// {"columns":["A","B"],"data":[[1,"a"],[2,"b"],[3,"c"]]}
//
// which is what is output by pandas.to_json(..., orient="split').
// (We ignore the index array.)
if (!json.hasNonNull(COLUMNS) || !json.get(COLUMNS).isArray()) {
throw new RestServiceException("Could not find columns object containing column names");
}
if (!json.hasNonNull("data") || !json.get("data").isArray()) {
throw new RestServiceException("Could not find data object containing data rows");
}
final ArrayNode columns = (ArrayNode) json.get(COLUMNS);
final String[] headers = new String[columns.size()];
for (int i = 0; i < headers.length; i++) {
headers[i] = columns.get(i).asText();
}
final ArrayNode data = (ArrayNode) json.get("data");
for (final Iterator<JsonNode> i = data.elements(); i.hasNext();) {
final ArrayNode jrow = (ArrayNode) i.next();
rs.add();
boolean txFound = false;
boolean txSourceFound = false;
for (int ix = 0; ix < headers.length; ix++) {
final String h = headers[ix];
final JsonNode jn = jrow.get(ix);
if (!jn.isNull()) {
if (jn.getNodeType() == JsonNodeType.ARRAY) {
rs.set(h, RestServiceUtilities.toList((ArrayNode) jn));
} else {
rs.set(h, jn.asText());
}
}
txFound |= h.startsWith(GraphRecordStoreUtilities.TRANSACTION);
txSourceFound |= TX_SOURCE.equals(h);
}
if (txFound && !txSourceFound) {
rs.set(TX_SOURCE, API_SOURCE);
}
}
addToGraph(graphId, rs, completeWithSchema, arrange, resetView);
}
private void runTestFile(String testCaseFile) throws Exception {
final URI testCaseFileUri = URI.create("classpath:" + testCaseFile);
InputStream in = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(testCaseFile);
ArrayNode testCases = mapper.readValue(in, ArrayNode.class);
for (int j = 0; j < testCases.size(); j++) {
try {
JsonNode testCase = testCases.get(j);
SchemaValidatorsConfig config = new SchemaValidatorsConfig();
ArrayNode testNodes = (ArrayNode) testCase.get("tests");
for (int i = 0; i < testNodes.size(); i++) {
JsonNode test = testNodes.get(i);
JsonNode node = test.get("data");
JsonNode typeLooseNode = test.get("isTypeLoose");
// Configure the schemaValidator to set typeLoose's value based on the test file,
// if test file do not contains typeLoose flag, use default value: true.
config.setTypeLoose((typeLooseNode == null) ? false : typeLooseNode.asBoolean());
JsonSchema schema = validatorFactory.getSchema(testCaseFileUri, testCase.get("schema"), config);
List<ValidationMessage> errors = new ArrayList<ValidationMessage>();
errors.addAll(schema.validate(node));
if (test.get("valid").asBoolean()) {
if (!errors.isEmpty()) {
System.out.println("---- test case failed ----");
System.out.println("schema: " + schema.toString());
System.out.println("data: " + test.get("data"));
}
assertEquals(0, errors.size());
} else {
if (errors.isEmpty()) {
System.out.println("---- test case failed ----");
System.out.println("schema: " + schema);
System.out.println("data: " + test.get("data"));
} else {
JsonNode errorCount = test.get("errorCount");
if (errorCount != null && errorCount.isInt() && errors.size() != errorCount.asInt()) {
System.out.println("---- test case failed ----");
System.out.println("schema: " + schema);
System.out.println("data: " + test.get("data"));
System.out.println("errors: " + errors);
assertEquals("expected error count", errorCount.asInt(), errors.size());
}
}
assertEquals(false, errors.isEmpty());
}
}
} catch (JsonSchemaException e) {
throw new IllegalStateException(String.format("Current schema should not be invalid: %s", testCaseFile), e);
}
}
}
protected void merge(ContainerNode<?> dest, ContainerNode<?> src) {
if (dest.getNodeType() == src.getNodeType()) {
if (dest.isArray()) {
ArrayNode destArray = (ArrayNode) dest;
ArrayNode srcArray = (ArrayNode) src;
outer:
for (int i = 0; i < srcArray.size(); i++) {
// Only add a source element if it is not already present in the destination array.
JsonNode srcElem = srcArray.get(i);
for (int j = 0; j < destArray.size(); j++) {
if (destArray.get(j).equals(srcElem))
continue outer;
}
destArray.add(srcElem);
}
} else if (dest.isObject()) {
ObjectNode destObject = (ObjectNode) dest;
ObjectNode srcObject = (ObjectNode) src;
Iterator<Entry<String, JsonNode>> fields = srcObject.fields();
while (fields.hasNext()) {
Entry<String, JsonNode> field = fields.next();
String fieldName = field.getKey();
JsonNode srcChild = field.getValue();
if (destObject.has(fieldName)) {
JsonNode destChild = destObject.get(fieldName);
switch (mergePolicy) {
case OVERWRITE_EXISTING:
destObject.set(fieldName, srcChild);
// Mark the cache as dirty as we've added items from another file.
isDirty = true;
LOGGER.info("Existing root property '" + fieldName
+ "' has been overwritten by incoming data");
break;
case MERGE_RECURSIVE:
if (destChild.isContainerNode() && srcChild.isContainerNode())
merge((ContainerNode<?>) destChild, (ContainerNode<?>) srcChild);
break;
case KEEP_EXISTING:
LOGGER.info("Existing root property '" + fieldName
+ "' will not be overwritten by incoming data");
default:
// Nothing to do.
break;
}
} else {
destObject.set(fieldName, srcChild);
LOGGER.info("New property '" + fieldName + "' has been added from incoming data");
// Mark the cache as dirty as we've added items from another file.
isDirty = true;
}
}
}
} else {
LOGGER.warn("Cannot merge containers of differing types");
}
}
static ArrayNode arrayValue(ArrayNode array, int index) throws InvalidMessageException{
JsonNode node = array.get(index);
if(!node.isArray())
throw new InvalidMessageException();
return (ArrayNode)node;
}
@Test
void resolveReferences_WithSetOfNestedCategoryReferenceSetOfSomeNonExisting_ShouldOnlyResolveExistingReferences() {
// preparation
when(categoryService.fetchCachedCategoryId("nonExistingCategoryKey1"))
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
when(categoryService.fetchCachedCategoryId("nonExistingCategoryKey3"))
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
final ProductVariantDraft withSetOfNestedCategoryReferenceSetWithSomeNonExisting =
readObjectFromResource(SET_OF_NESTED_ATTRIBUTE_WITH_SOME_NOT_EXISTING_CATEGORY_REFERENCE_ATTRIBUTES,
ProductVariantDraft.class);
// test
final ProductVariantDraft resolvedAttributeDraft =
referenceResolver.resolveReferences(withSetOfNestedCategoryReferenceSetWithSomeNonExisting)
.toCompletableFuture()
.join();
// assertions
assertThat(resolvedAttributeDraft.getAttributes()).isNotNull();
final JsonNode value = resolvedAttributeDraft.getAttributes().get(0).getValue();
assertThat(value).isInstanceOf(ArrayNode.class);
final ArrayNode setOfResolvedNestedAttributes = (ArrayNode) value;
final JsonNode resolvedNestedAttribute = setOfResolvedNestedAttributes.get(0);
assertThat(resolvedNestedAttribute).isInstanceOf(ArrayNode.class);
final ArrayNode resolvedNestedAttributeAsArray = (ArrayNode) resolvedNestedAttribute;
final Map<String, JsonNode> resolvedNestedAttributesMap = StreamSupport
.stream(resolvedNestedAttributeAsArray.spliterator(), false)
.collect(Collectors.toMap(jsonNode -> jsonNode.get("name").asText(), jsonNode -> jsonNode));
assertReferenceSetAttributeValue(resolvedNestedAttributesMap,
"nested-attribute-1-name",
createReferenceObject("nonExistingCategoryKey1", Category.referenceTypeId()),
createReferenceObject(CATEGORY_ID, Category.referenceTypeId()));
assertReferenceAttributeValue(resolvedNestedAttributesMap,
"nested-attribute-2-name", CATEGORY_ID, Category.referenceTypeId());
assertReferenceAttributeValue(resolvedNestedAttributesMap,
"nested-attribute-3-name", "nonExistingCategoryKey3", Category.referenceTypeId());
}
private void runTestFile(String testCaseFile) throws Exception {
final URI testCaseFileUri = URI.create("classpath:" + testCaseFile);
InputStream in = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(testCaseFile);
ArrayNode testCases = mapper.readValue(in, ArrayNode.class);
for (int j = 0; j < testCases.size(); j++) {
try {
JsonNode testCase = testCases.get(j);
SchemaValidatorsConfig config = new SchemaValidatorsConfig();
ArrayNode testNodes = (ArrayNode) testCase.get("tests");
for (int i = 0; i < testNodes.size(); i++) {
JsonNode test = testNodes.get(i);
JsonNode node = test.get("data");
JsonNode typeLooseNode = test.get("isTypeLoose");
// Configure the schemaValidator to set typeLoose's value based on the test file,
// if test file do not contains typeLoose flag, use default value: true.
config.setTypeLoose((typeLooseNode == null) ? false : typeLooseNode.asBoolean());
JsonSchema schema = validatorFactory.getSchema(testCaseFileUri, testCase.get("schema"), config);
List<ValidationMessage> errors = new ArrayList<ValidationMessage>();
errors.addAll(schema.validate(node));
if (test.get("valid").asBoolean()) {
if (!errors.isEmpty()) {
System.out.println("---- test case failed ----");
System.out.println("schema: " + schema.toString());
System.out.println("data: " + test.get("data"));
}
assertEquals(0, errors.size());
} else {
if (errors.isEmpty()) {
System.out.println("---- test case failed ----");
System.out.println("schema: " + schema);
System.out.println("data: " + test.get("data"));
} else {
JsonNode errorCount = test.get("errorCount");
if (errorCount != null && errorCount.isInt() && errors.size() != errorCount.asInt()) {
System.out.println("---- test case failed ----");
System.out.println("schema: " + schema);
System.out.println("data: " + test.get("data"));
System.out.println("errors: " + errors);
assertEquals("expected error count", errorCount.asInt(), errors.size());
}
}
assertEquals(false, errors.isEmpty());
}
}
} catch (JsonSchemaException e) {
throw new IllegalStateException(String.format("Current schema should not be invalid: %s", testCaseFile), e);
}
}
}
static ObjectNode objectValue(ArrayNode array, int index) throws InvalidMessageException{
JsonNode node = array.get(index);
if(!node.isObject())
throw new InvalidMessageException();
return (ObjectNode)node;
}