Java Code Examples for com.fasterxml.jackson.databind.node.ArrayNode

The following examples show how to use com.fasterxml.jackson.databind.node.ArrayNode. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: mobi   Source File: OntologyRest.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Returns object property IRIs in the ontology identified by the provided IDs.
 *
 * @param context     the context of the request.
 * @param recordIdStr the String representing the record Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:".
 * @param branchIdStr the String representing the Branch Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the
 *                    master Branch.
 * @param commitIdStr the String representing the Commit Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the head
 *                    Commit. The provided commitId must be on the Branch identified by the provided branchId;
 *                    otherwise, nothing will be returned.
 * @return object properties in the ontology identified by the provided IDs.
 */
@GET
@Path("{recordId}/object-properties")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@ApiOperation("Gets the object properties in the identified ontology.")
@ResourceId(type = ValueType.PATH, value = "recordId")
public Response getObjectPropertiesInOntology(@Context ContainerRequestContext context,
                                              @PathParam("recordId") String recordIdStr,
                                              @QueryParam("branchId") String branchIdStr,
                                              @QueryParam("commitId") String commitIdStr) {
    try {
        ArrayNode result = doWithOntology(context, recordIdStr, branchIdStr, commitIdStr,
                this::getObjectPropertyArray, true);
        return Response.ok(result.toString()).build();
    } catch (MobiException e) {
        throw ErrorUtils.sendError(e, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
    }
}
 
Example 2
Source Project: incubator-taverna-language   Source File: JsonExport.java    License: Apache License 2.0 6 votes vote down vote up
protected JsonNode toJson(Revision currentRevision) {
    ArrayNode revisions = mapper.createArrayNode();
    while (currentRevision != null) {
        ObjectNode rev = mapper.createObjectNode();
        rev.putPOJO("id", currentRevision.getIdentifier());
        if (currentRevision.getGeneratedAtTime() != null) {
            rev.putPOJO("generatedAtTime", currentRevision.getGeneratedAtTime());
        }
        currentRevision = currentRevision.getPreviousRevision();
        if (currentRevision != null) {
            rev.putPOJO("wasRevisionOf", currentRevision.getIdentifier());
        }
        revisions.add(rev);
    }
    return revisions;
}
 
Example 3
@Override
public void setData(ObjectNode mainNode, ArrayNode arrayNode)
    throws AxelorException, JSONException {

  mainNode.put("status", 0);
  mainNode.set("data", arrayNode);
  Optional<Address> optionalAddress = Beans.get(UserService.class).getUserActiveCompanyAddress();

  if (optionalAddress.isPresent()) {
    Optional<Pair<BigDecimal, BigDecimal>> latLong =
        Beans.get(AddressService.class).getOrUpdateLatLong(optionalAddress.get());

    if (latLong.isPresent()) {
      JsonNodeFactory factory = JsonNodeFactory.instance;
      ObjectNode objectNode = factory.objectNode();
      objectNode.put("lat", latLong.get().getLeft());
      objectNode.put("lng", latLong.get().getRight());
      mainNode.set("company", objectNode);
    }
  }
}
 
Example 4
Source Project: constellation   Source File: ListGraphs.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void callService(final PluginParameters parameters, final InputStream in, final OutputStream out) throws IOException {
    final ObjectMapper mapper = new ObjectMapper();
    final ArrayNode root = mapper.createArrayNode();
    final Map<String, Graph> graphs = GraphNode.getAllGraphs();
    graphs.entrySet().forEach(entry -> {
        final String id = entry.getKey();
        final Graph graph = entry.getValue();
        final ObjectNode obj = mapper.createObjectNode();
        obj.put("id", id);
        obj.put("name", GraphNode.getGraphNode(id).getDisplayName());
        final Schema schema = graph.getSchema();
        obj.put("schema", schema != null ? schema.getFactory().getName() : null);
        root.add(obj);
    });

    mapper.writeValue(out, root);
}
 
Example 5
Source Project: flowable-engine   Source File: ModelsResource.java    License: Apache License 2.0 6 votes vote down vote up
protected void internalDeleteNodeByNameFromBPMNModel(JsonNode editorJsonNode, String propertyName) {
    JsonNode childShapesNode = editorJsonNode.get("childShapes");
    if (childShapesNode != null && childShapesNode.isArray()) {
        ArrayNode childShapesArrayNode = (ArrayNode) childShapesNode;
        for (JsonNode childShapeNode : childShapesArrayNode) {
            // Properties
            ObjectNode properties = (ObjectNode) childShapeNode.get("properties");
            if (properties != null && properties.has(propertyName)) {
                JsonNode propertyNode = properties.get(propertyName);
                if (propertyNode != null) {
                    properties.remove(propertyName);
                }
            }

            // Potential nested child shapes
            if (childShapeNode.has("childShapes")) {
                internalDeleteNodeByNameFromBPMNModel(childShapeNode, propertyName);
            }

        }
    }
}
 
Example 6
Source Project: onos   Source File: ControlMetricsWebResource.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns disk metrics of all resources.
 *
 * @return disk metrics of all resources
 * @onos.rsModel DiskMetrics
 */
@GET
@Path("disk_metrics")
@Produces(MediaType.APPLICATION_JSON)
public Response diskMetrics() {
    ObjectNode root = mapper().createObjectNode();
    ControlPlaneMonitorService monitorService = get(ControlPlaneMonitorService.class);
    ClusterService clusterService = get(ClusterService.class);
    NodeId localNodeId = clusterService.getLocalNode().id();
    ArrayNode diskNodes = root.putArray("disks");
    monitorService.availableResourcesSync(localNodeId, DISK).forEach(name -> {
        ObjectNode diskNode = mapper().createObjectNode();
        ObjectNode valueNode = mapper().createObjectNode();

        metricsStats(monitorService, localNodeId, DISK_METRICS, name, valueNode);
        diskNode.put("name", name);
        diskNode.set("value", valueNode);

        diskNodes.add(diskNode);
    });

    return ok(root).build();
}
 
Example 7
Source Project: onos   Source File: BasicHostConfig.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the auxLocations of the host.
 *
 * @return auxLocations of the host or null if none specified
 * @throws IllegalArgumentException if auxLocations are set but empty or not
 *                                  specified with correct format
 */
public Set<HostLocation> auxLocations() {
    if (!object.has(AUX_LOCATIONS)) {
        return null; //no auxLocations are specified
    }

    ImmutableSet.Builder<HostLocation> auxLocationsSetBuilder = ImmutableSet.<HostLocation>builder();

    ArrayNode auxLocationNodes = (ArrayNode) object.path(AUX_LOCATIONS);
    auxLocationNodes.forEach(n -> {
        ConnectPoint cp = ConnectPoint.deviceConnectPoint((n.asText()));
        auxLocationsSetBuilder.add(new HostLocation(cp, 0));
    });

    return auxLocationsSetBuilder.build();
}
 
Example 8
Source Project: bootique   Source File: InPlaceMapOverriderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testApply_ObjectArray_PastEnd() {

    Map<String, String> props = Collections.singletonMap("a[2]", "50");
    InPlaceMapOverrider overrider = new InPlaceMapOverrider(props);

    JsonNode node = YamlReader.read("a:\n" +
            "  - 1\n" +
            "  - 5");
    overrider.apply(node);

    ArrayNode array = (ArrayNode) node.get("a");
    assertEquals(3, array.size());
    assertEquals(1, array.get(0).asInt());
    assertEquals(5, array.get(1).asInt());
    assertEquals(50, array.get(2).asInt());
}
 
Example 9
@Get("/autocompleteTags/:key")
@ProducesJson
public JsonNode getAutocompleteValues(@Param("key") String key) {
  try {
    if (!storage.traceSearchEnabled) return MAPPER.createArrayNode();
    ReadOnlyKeyValueStore<String, Set<String>> autocompleteTagsStore =
        storage.getTraceStorageStream().store(AUTOCOMPLETE_TAGS_STORE_NAME,
            QueryableStoreTypes.keyValueStore());
    Set<String> values = autocompleteTagsStore.get(key);
    ArrayNode array = MAPPER.createArrayNode();
    if (values != null) values.forEach(array::add);
    return array;
  } catch (InvalidStateStoreException e) {
    LOG.debug("State store is not ready", e);
    throw e;
  }
}
 
Example 10
Source Project: symja_android_library   Source File: Pods.java    License: GNU General Public License v3.0 6 votes vote down vote up
static ObjectNode createJSONErrorString(String str) {
	ObjectNode outJSON = JSON_OBJECT_MAPPER.createObjectNode();
	outJSON.put("prefix", "Error");
	outJSON.put("message", Boolean.TRUE);
	outJSON.put("tag", "syntax");
	outJSON.put("symbol", "General");
	outJSON.put("text", "<math><mrow><mtext>" + str + "</mtext></mrow></math>");

	ObjectNode resultsJSON = JSON_OBJECT_MAPPER.createObjectNode();
	resultsJSON.putNull("line");
	resultsJSON.putNull("result");

	ArrayNode temp = JSON_OBJECT_MAPPER.createArrayNode();
	temp.add(outJSON);
	resultsJSON.putPOJO("out", temp);

	temp = JSON_OBJECT_MAPPER.createArrayNode();
	temp.add(resultsJSON);
	ObjectNode json = JSON_OBJECT_MAPPER.createObjectNode();
	json.putPOJO("results", temp);
	return json;
}
 
Example 11
Source Project: endpoints-java   Source File: JsonConfigWriter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Converts the auth config from the auth annotation. Subclasses may override
 * to add additional information to the auth config.
 */
private void convertApiAuth(ObjectNode root, ApiAuthConfig config) {
  ObjectNode authConfig = objectMapper.createObjectNode();

  authConfig.put("allowCookieAuth", config.getAllowCookieAuth());

  List<String> blockedRegions = config.getBlockedRegions();
  if (!blockedRegions.isEmpty()) {
    ArrayNode blockedRegionsNode = objectMapper.createArrayNode();
    for (String region : blockedRegions) {
      blockedRegionsNode.add(region);
    }
    authConfig.set("blockedRegions", blockedRegionsNode);
  }

  root.set("auth", authConfig);
}
 
Example 12
Source Project: onos   Source File: PiTableModelCodec.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ObjectNode encode(PiTableModel table, CodecContext context) {

    ObjectNode result = context.mapper().createObjectNode();

    result.put(NAME, table.id().toString());
    result.put(MAX_SIZE, table.maxSize());
    result.put(HAS_COUNTERS, table.counters().size() > 0);
    result.put(SUPPORT_AGING, table.supportsAging());

    ArrayNode matchFields = result.putArray(MATCH_FIELDS);
    table.matchFields().forEach(matchField -> {
        ObjectNode matchFieldData =
                context.encode(matchField, PiMatchFieldModel.class);
        matchFields.add(matchFieldData);
    });

    ArrayNode actions = result.putArray(ACTIONS);
    table.actions().forEach(action -> {
        actions.add(action.id().toString());
    });

    return result;
}
 
Example 13
Source Project: crnk-framework   Source File: JsonFilterSpecMapper.java    License: Apache License 2.0 6 votes vote down vote up
private Object deserializeJsonFilterValue(ResourceInformation resourceInformation, PathSpec attributePath, JsonNode jsonNode, QueryContext queryContext) {
	QueryPathSpec resolvedPath = pathResolver.resolve(resourceInformation, attributePath.getElements(), QueryPathResolver.NamingType.JSON, "filter", queryContext);
	resolvedPath.verifyFilterable();

	Class valueType = ClassUtils.getRawType(resolvedPath.getValueType());
	ObjectReader reader = context.getObjectMapper().readerFor(valueType);
	try {
		if (jsonNode instanceof ArrayNode) {
			List values = new ArrayList();
			for (JsonNode elementNode : jsonNode) {
				values.add(reader.readValue(elementNode));
			}
			return values;
		}
		return reader.readValue(jsonNode);
	}
	catch (IOException e) {
		throw new ParametersDeserializationException("failed to parse value " + jsonNode + " to type " + valueType);
	}
}
 
Example 14
Source Project: onos   Source File: MappingTreatmentCodec.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ObjectNode encode(MappingTreatment treatment, CodecContext context) {
    checkNotNull(treatment, "Mapping treatment cannot be null");

    final ObjectNode result = context.mapper().createObjectNode();
    final ArrayNode jsonInstructions = result.putArray(INSTRUCTIONS);

    final JsonCodec<MappingInstruction> instructionCodec =
            context.codec(MappingInstruction.class);

    final JsonCodec<MappingAddress> addressCodec =
            context.codec(MappingAddress.class);

    for (final MappingInstruction instruction : treatment.instructions()) {
        jsonInstructions.add(instructionCodec.encode(instruction, context));
    }

    result.set(ADDRESS, addressCodec.encode(treatment.address(), context));

    return result;
}
 
Example 15
Source Project: onos   Source File: EncodeConstraintCodecHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Encodes a link type constraint.
 *
 * @return JSON ObjectNode representing the constraint
 */
private ObjectNode encodeLinkTypeConstraint() {
    checkNotNull(constraint, "Link type constraint cannot be null");

    final LinkTypeConstraint linkTypeConstraint =
            (LinkTypeConstraint) constraint;

    final ObjectNode result = context.mapper().createObjectNode()
            .put(ConstraintCodec.INCLUSIVE, linkTypeConstraint.isInclusive());

    final ArrayNode jsonTypes = result.putArray(ConstraintCodec.TYPES);

    if (linkTypeConstraint.types() != null) {
        for (Link.Type type : linkTypeConstraint.types()) {
            jsonTypes.add(type.name());
        }
    }

    return result;
}
 
Example 16
Source Project: yosegi   Source File: TestJacksonArrayFormatter.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void T_write_equalsSetValue_withNestingObjectFromParser() throws IOException {
  JacksonArrayFormatter formatter = new JacksonArrayFormatter();
  JsonNode node = formatter.writeParser( new TestParentParser( false ) );
  assertTrue( ( node instanceof ArrayNode ) );

  ArrayNode parentNode = (ArrayNode)node;
  assertEquals( parentNode.size() , 1 );

  JsonNode childNode = parentNode.get(0);
  assertTrue( ( childNode instanceof ObjectNode ) );
  ObjectNode objNode = (ObjectNode)childNode;

  assertEquals( objNode.size() , 3 );
  assertTrue( objNode.get("key1").isTextual() );
  assertTrue( objNode.get("key2").isTextual() );
  assertTrue( objNode.get("key3").isTextual() );
  assertEquals( objNode.get("key1").asText() , "a" );
  assertEquals( objNode.get("key2").asText() , "b" );
  assertEquals( objNode.get("key3").asText() , "c" );
}
 
Example 17
Source Project: serverless   Source File: GatewayUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static final String proxyIntegration(int statusCode, String[] headers, String body) {
	ObjectMapper mapper = Jackson.getObjectMapper();
	ObjectNode json = mapper.createObjectNode();
	
    json.put("statusCode", statusCode);
    
    ArrayNode array = mapper.createArrayNode();
    Arrays.stream(headers).forEach(header -> array.add(header));
    json.put("headers", array);

    json.put("body", body);

    return json.toString();
}
 
Example 18
Source Project: link-move   Source File: JsonQueryTest.java    License: Apache License 2.0 5 votes vote down vote up
private List<JsonNode> collectNodes(ArrayNode arrayNode) {

        List<JsonNode> nodes = new ArrayList<>();

        Iterator<JsonNode> iter = arrayNode.elements();
        while (iter.hasNext()) {
            nodes.add(iter.next());
        }
        return nodes;
    }
 
Example 19
Source Project: azure-cosmosdb-java   Source File: IncludedPath.java    License: MIT License 5 votes vote down vote up
private Collection<Index> getIndexCollection() {
    if (this.propertyBag != null && this.propertyBag.has(Constants.Properties.INDEXES)) {
        ArrayNode jsonArray = (ArrayNode) this.propertyBag.get(Constants.Properties.INDEXES);
        Collection<Index> result = new ArrayList<Index>();

        for (int i = 0; i < jsonArray.size(); i++) {
            JsonNode jsonObject = jsonArray.get(i);

            IndexKind indexKind = IndexKind.valueOf(WordUtils.capitalize(
                    jsonObject.get(Constants.Properties.INDEX_KIND).asText()));
            switch (indexKind) {
            case Hash:
                result.add(new HashIndex(jsonObject.toString()));
                break;
            case Range:
                result.add(new RangeIndex(jsonObject.toString()));
                break;
            case Spatial:
                result.add(new SpatialIndex(jsonObject.toString()));
                break;
            }
        }

        return result;
    }

    return null;
}
 
Example 20
/**
 * Converts a DynamoDB list to a JSON list.
 *
 * @param item
 *            DynamoDB list
 * @param depth
 *            Current JSON depth
 * @return JSON array node representation of DynamoDB list
 * @throws JacksonConverterException
 *             Null DynamoDB list or JSON too deep
 */
private JsonNode listToJsonArray(final List<AttributeValue> item, final int depth) throws JacksonConverterException {
    assertDepth(depth);
    if (item != null) {
        final ArrayNode node = JsonNodeFactory.instance.arrayNode();
        for (final AttributeValue value : item) {
            node.add(getJsonNode(value, depth + 1));
        }
        return node;
    }
    throw new JacksonConverterException("Item cannot be null");
}
 
Example 21
Source Project: flowable-engine   Source File: CaseInstanceResourceTest.java    License: Apache License 2.0 5 votes vote down vote up
protected ArrayNode getStageOverviewResponse(CaseInstance caseInstance) throws IOException {
    CloseableHttpResponse response = executeRequest(new HttpGet(SERVER_URL_PREFIX + CmmnRestUrls.createRelativeResourceUrl(
            CmmnRestUrls.URL_CASE_INSTANCE_STAGE_OVERVIEW, caseInstance.getId())), HttpStatus.SC_OK);
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK);
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);

    assertThat(responseNode.isArray()).isTrue();
    return (ArrayNode) responseNode;
}
 
Example 22
Source Project: arctic-sea   Source File: FieldEncoder.java    License: Apache License 2.0 5 votes vote down vote up
private ObjectNode encodeSweTimeRangeField(SweField field) {
    ObjectNode jfield = createField(field);
    jfield.put(JSONConstants.TYPE, JSONConstants.TIME_RANGE_TYPE);
    SweTimeRange sweTimeRange = (SweTimeRange) field.getElement();
    jfield.put(JSONConstants.UOM, sweTimeRange.getUom());
    if (sweTimeRange.isSetValue()) {
        ArrayNode av = jfield.putArray(JSONConstants.VALUE);
        av.add(DateTimeHelper.formatDateTime2IsoString(sweTimeRange.getValue().getRangeStart()));
        av.add(DateTimeHelper.formatDateTime2IsoString(sweTimeRange.getValue().getRangeEnd()));
    }
    return jfield;
}
 
Example 23
Source Project: incubator-pinot   Source File: AvroWriter.java    License: Apache License 2.0 5 votes vote down vote up
public static org.apache.avro.Schema getAvroSchema(Schema schema) {
  ObjectNode avroSchema = JsonUtils.newObjectNode();
  avroSchema.put("name", "data_gen_record");
  avroSchema.put("type", "record");

  ArrayNode fields = JsonUtils.newArrayNode();
  for (FieldSpec fieldSpec : schema.getAllFieldSpecs()) {
    JsonNode jsonObject = AvroSchemaUtil.toAvroSchemaJsonObject(fieldSpec);
    fields.add(jsonObject);
  }
  avroSchema.set("fields", fields);

  return new org.apache.avro.Schema.Parser().parse(avroSchema.toString());
}
 
Example 24
@StreamListener(target = Sink.INPUT)
public void messageReceived(String messageJson) throws Exception { 

  // Build array with exactly this one event
  ArrayNode messageArray = objectMapper.createArrayNode();    
  messageArray.add(objectMapper.readTree(messageJson));
  
  // and send it over to Optimize
  sendCloudEventsToOptimize(messageArray.toString());
  
  // An optimization could be to collect events and send them as batch
  // if you have high loads
}
 
Example 25
Source Project: keycloak   Source File: ReflectionUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static void setArrayItem(ArrayNode list, int index, JsonNode valNode) {
    if (index == -1) {
        // append to end of array
        list.add(valNode);
        return;
    }
    // make sure items up to index exist
    for (int i = list.size(); i < index+1; i++) {
        list.add(NullNode.instance);
    }
    list.set(index, valNode);
}
 
Example 26
@Deployment(resources = { "org/activiti/engine/test/bpmn/dynamic/dynamic-bpmn-test-process.bpmn20.xml" })
public void testTheCandidateUserOfTheFirstTasksIsChanged() throws Exception {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("dynamicServiceTest");
    String processDefinitionId = processInstance.getProcessDefinitionId();

    ObjectNode processInfo = dynamicBpmnService.changeUserTaskCandidateUser(TASK_ONE_SID, "bob", false);
    dynamicBpmnService.saveProcessDefinitionInfo(processDefinitionId, processInfo);

    DynamicProcessDefinitionSummary summary = dynamicBpmnService.getDynamicProcessDefinitionSummary(processDefinitionId);

    ArrayNode bpmnModelCandidateUsers = processEngineConfiguration.getObjectMapper().createArrayNode();
    bpmnModelCandidateUsers.add("david");

    ArrayNode dynamicCandidateUsers = processEngineConfiguration.getObjectMapper().createArrayNode();
    dynamicCandidateUsers.add("bob");

    JsonNode taskOneNode = summary.getElement(TASK_ONE_SID).get(ELEMENT_PROPERTIES);
    assertThat((ArrayNode) taskOneNode.get(USER_TASK_CANDIDATE_USERS).get(BPMN_MODEL_VALUE), is(bpmnModelCandidateUsers));
    assertThat((ArrayNode) taskOneNode.get(USER_TASK_CANDIDATE_USERS).get(DYNAMIC_VALUE), is(dynamicCandidateUsers));

    // verify if runtime is up to date
    runtimeService.startProcessInstanceById(processDefinitionId);
    // bob and david both should have a single task.
    org.flowable.task.api.Task bobTask = taskService.createTaskQuery().taskCandidateUser("bob").singleResult();
    assertThat("Bob must have one task", bobTask, is(notNullValue()));

    org.flowable.task.api.Task davidTask = taskService.createTaskQuery().taskCandidateUser("david").singleResult();
    assertThat("David must have one task", davidTask, is(not(nullValue())));
}
 
Example 27
Source Project: lams   Source File: PresenceWebsocketServer.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
    * Filteres messages meant for the given user (group or personal).
    */
   private static ArrayNode filterMessages(List<PresenceChatMessage> messages, String nickName) {
ArrayNode messagesJSON = JsonNodeFactory.instance.arrayNode();

for (PresenceChatMessage message : messages) {
    String messageTo = message.getTo();
    if ((messageTo == null) || message.getTo().equals(nickName) || message.getFrom().equals(nickName)) {
	ObjectNode messageJSON = PresenceWebsocketServer.buildMessageJSON(message);
	messagesJSON.add(messageJSON);
    }
}

return messagesJSON;
   }
 
Example 28
Source Project: cloudbreak   Source File: AmbariClusterResponse.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object handle(Request request, Response response) {
    response.type("text/plain");
    ObjectNode rootNode = JsonNodeFactory.instance.objectNode();

    Set<String> hostNames = instanceMap.values().stream()
            .map(cv -> HostNameUtil.generateHostNameByIp(cv.getMetaData().getPrivateIp())).collect(Collectors.toSet());
    rootNode.putObject("hosts")
            .set("Hosts", getObjectMapper().valueToTree(new Hosts(hostNames, "HEALTHY")));

    ArrayNode items = rootNode.putArray("items");
    items.addObject()
            .set("Clusters", getObjectMapper().valueToTree(new Clusters(clusterName)));
    return rootNode;
}
 
Example 29
Source Project: onos   Source File: VirtualFlowsListCommand.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Produces a JSON array of flows grouped by the each device.
 *
 * @param devices     collection of devices to group flow by
 * @param flows       collection of flows per each device
 * @return JSON array
 */
private JsonNode json(Iterable<Device> devices,
                      Map<Device, List<FlowEntry>> flows) {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode result = mapper.createArrayNode();
    for (Device device : devices) {
        result.add(json(mapper, device, flows.get(device)));
    }
    return result;
}
 
Example 30
Source Project: sf-java-ui   Source File: UiFormSchemaGenerator.java    License: MIT License 5 votes vote down vote up
private void handleActionsAnnotation(ObjectMapper mapper, Class<? extends Serializable> formDto,
		ArrayNode formDefinition) {
	ObjectNode groupedActionsNode = mapper.createObjectNode();

	buildActions(mapper, formDto, formDefinition);
	buildGroupedActions(mapper, formDto, groupedActionsNode, formDefinition);
}