Java 类com.fasterxml.jackson.databind.node.ArrayNode 实例源码

项目:GitHub    文件:DefaultRule.java   
/**
 * Creates a default value for a set property by:
 * <ol>
 * <li>Creating a new {@link LinkedHashSet} with the correct generic type
 * <li>Using {@link Arrays#asList(Object...)} to initialize the set with the
 * correct default values
 * </ol>
 *
 * @param fieldType
 *            the java type that applies for this field ({@link Set} with
 *            some generic type argument)
 * @param node
 *            the node containing default values for this set
 * @return an expression that creates a default value that can be assigned
 *         to this field
 */
private JExpression getDefaultSet(JType fieldType, JsonNode node) {

    JClass setGenericType = ((JClass) fieldType).getTypeParameters().get(0);

    JClass setImplClass = fieldType.owner().ref(LinkedHashSet.class);
    setImplClass = setImplClass.narrow(setGenericType);

    JInvocation newSetImpl = JExpr._new(setImplClass);

    if (node instanceof ArrayNode && node.size() > 0) {
        JInvocation invokeAsList = fieldType.owner().ref(Arrays.class).staticInvoke("asList");
        for (JsonNode defaultValue : node) {
            invokeAsList.arg(getDefaultValue(setGenericType, defaultValue));
        }
        newSetImpl.arg(invokeAsList);
    } else if (!ruleFactory.getGenerationConfig().isInitializeCollections()) {
        return JExpr._null();
    }

    return newSetImpl;

}
项目:Equella    文件:ItemApiEditTest.java   
private ObjectNode createItemObject(String collectionUuid, PropBagEx metadata, boolean withAttachment)
{
    ObjectNode item = mapper.createObjectNode();

    ObjectNode collection = item.objectNode();
    collection.put("uuid", collectionUuid);
    item.put("collection", collection);
    item.put("metadata", metadata.toString());
    if( withAttachment )
    {
        ArrayNode attachments = item.arrayNode();
        ObjectNode attachment = item.objectNode();
        attachment.put("type", "url");
        attachment.put("description", "Google");
        attachment.put("url", "http://google.com.au/");
        attachment.put("uuid", "uuid:0");
        attachments.add(attachment);
        item.put("attachments", attachments);
    }
    return item;
}
项目:gemnasium-maven-plugin    文件:ProjectsUtils.java   
public static ArrayNode getJsonDependencies(List<Artifact> artifacts, List<Dependency> directDependencies) {
    HashMap<String, String> requirements = new HashMap<String, String>(directDependencies.size());
    for (Dependency dep : directDependencies) {
        requirements.put(dep.getGroupId() + ":" + dep.getArtifactId(), dep.getVersion());
    }

    ObjectMapper mapper = new ObjectMapper();
    ArrayNode arrayNode = mapper.createArrayNode();
    for (Artifact art : artifacts) {
        ObjectNode artNode = depToJsonNode(mapper, art);
        String requirement;
        requirement = requirements.get(art.getGroupId() + ":" + art.getArtifactId());
        // Temporary workaround for transitive dependencies
        if (requirement == null){
            requirement = art.getVersion();
        }
        artNode.put("requirement", requirement);
        arrayNode.add(artNode);
    }
    return arrayNode;
}
项目:athena    文件:IntentCodec.java   
@Override
public ObjectNode encode(Intent intent, CodecContext context) {
    checkNotNull(intent, "Intent cannot be null");

    final ObjectNode result = context.mapper().createObjectNode()
            .put(TYPE, intent.getClass().getSimpleName())
            .put(ID, intent.id().toString())
            .put(APP_ID, UrlEscapers.urlPathSegmentEscaper()
                    .escape(intent.appId().name()));

    final ArrayNode jsonResources = result.putArray(RESOURCES);

    for (final NetworkResource resource : intent.resources()) {
        jsonResources.add(resource.toString());
    }

    IntentService service = context.getService(IntentService.class);
    IntentState state = service.getIntentState(intent.key());
    if (state != null) {
        result.put(STATE, state.toString());
    }

    return result;
}
项目:athena    文件:TopologyResource.java   
@Path("geoloc")
@GET
@Produces("application/json")
public Response getGeoLocations() {
    ObjectNode rootNode = mapper.createObjectNode();
    ArrayNode devices = mapper.createArrayNode();
    ArrayNode hosts = mapper.createArrayNode();

    Map<String, ObjectNode> metaUi = TopologyViewMessageHandler.getMetaUi();
    for (String id : metaUi.keySet()) {
        ObjectNode memento = metaUi.get(id);
        if (id.length() > 17 && id.charAt(17) == '/') {
            addGeoData(hosts, "id", id, memento);
        } else {
            addGeoData(devices, "uri", id, memento);
        }
    }

    rootNode.set("devices", devices);
    rootNode.set("hosts", hosts);
    return Response.ok(rootNode.toString()).build();
}
项目:athena    文件:TopoJson.java   
/**
 * Translates the given property panel into JSON, for returning
 * to the client.
 *
 * @param pp the property panel model
 * @return JSON payload
 */
public static ObjectNode json(PropertyPanel pp) {
    ObjectNode result = objectNode()
            .put(TITLE, pp.title())
            .put(TYPE, pp.typeId())
            .put(ID, pp.id());

    ObjectNode pnode = objectNode();
    ArrayNode porder = arrayNode();
    for (PropertyPanel.Prop p : pp.properties()) {
        porder.add(p.key());
        pnode.put(p.key(), p.value());
    }
    result.set(PROP_ORDER, porder);
    result.set(PROPS, pnode);

    ArrayNode buttons = arrayNode();
    for (ButtonId b : pp.buttons()) {
        buttons.add(b.id());
    }
    result.set(BUTTONS, buttons);
    return result;
}
项目:exam    文件:QuestionController.java   
private void processOptions(Question question, ArrayNode node) {
    Set<Long> persistedIds = question.getOptions().stream()
            .map(MultipleChoiceOption::getId)
            .collect(Collectors.toSet());
    Set<Long> providedIds = StreamSupport.stream(node.spliterator(), false)
            .filter(n -> SanitizingHelper.parse("id", n, Long.class).isPresent())
            .map(n -> SanitizingHelper.parse("id", n, Long.class).get())
            .collect(Collectors.toSet());
    // Updates
    StreamSupport.stream(node.spliterator(), false)
            .filter(o -> {
                Optional<Long> id = SanitizingHelper.parse("id", o, Long.class);
                return id.isPresent() && persistedIds.contains(id.get());
            }).forEach(o -> updateOption(o, false));
    // Removals
    question.getOptions().stream()
            .filter(o -> !providedIds.contains(o.getId()))
            .forEach(this::deleteOption);
    // Additions
    StreamSupport.stream(node.spliterator(), false)
            .filter(o -> !SanitizingHelper.parse("id", o, Long.class).isPresent())
            .forEach(o -> createOption(question, o));
}
项目:travny    文件:SimpleJsonReader.java   
@Override
protected Map readMap(MapSchema schema, JsonNode node) {
    Preconditions.checkNotNull(schema);
    Preconditions.checkNotNull(node);
    if (node instanceof ArrayNode) {
        return super.readMap(schema, node);
    }
    Preconditions.checkArgument(node instanceof ObjectNode);
    Schema keySchema = schema.getKeySchema();
    switch (keySchema.getType()) {
        case RECORD:
        case MAP:
        case LIST:
            return super.readMap(schema, node);
    }
    Map map = Maps.newLinkedHashMap();
    Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
    while (fields.hasNext()) {
        Map.Entry<String, JsonNode> field = fields.next();
        String key = field.getKey();
        JsonNode val = field.getValue();
        map.put(keyFromString(schema.getKeySchema(), key), getNodeData(schema.getValueSchema(), val));
    }
    return map;
}
项目:pprxmtr    文件:Handler.java   
private void sendSlackImageResponse(ObjectNode json, String s3Key) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode message = mapper.createObjectNode();
        ArrayNode attachments = mapper.createArrayNode();
        ObjectNode attachment = mapper.createObjectNode();

        String emoji = json.get("text").asText();

        if (UrlValidator.getInstance().isValid(emoji)) {
            attachment.put("title_link", emoji);
            emoji = StringUtils.substringAfterLast(emoji, "/");
        }

        String username = json.get("user_name").asText();
        String responseUrl = json.get("response_url").asText();
        String slackChannelId = json.get("channel_id").asText();
        String imageUrl = String.format("https://s3.amazonaws.com/%s/%s", PROPERTIES.getProperty(S3_BUCKET_NAME), s3Key);

        message.put("response_type", "in_channel");
        message.put("channel_id", slackChannelId);
        attachment.put("title", resolveMessage("slackImageResponse", emoji, username));
        attachment.put("fallback", resolveMessage("approximated", emoji));
        attachment.put("image_url", imageUrl);
        attachments.add(attachment);
        message.set("attachments", attachments);

        HttpClient client = HttpClientBuilder.create().build();
        HttpPost slackResponseReq = new HttpPost(responseUrl);
        slackResponseReq.setEntity(new StringEntity(mapper.writeValueAsString(message), ContentType.APPLICATION_JSON));
        HttpResponse slackResponse = client.execute(slackResponseReq);
        int status = slackResponse.getStatusLine().getStatusCode();
        LOG.info("Got {} status from Slack API after sending approximation to response url.", status);
    } catch (UnsupportedOperationException | IOException e) {
        LOG.error("Exception occured when sending Slack response", e);
    }
}
项目:athena    文件:DistributedNetworkConfigStore.java   
@Activate
public void activate() {
    KryoNamespace.Builder kryoBuilder = new KryoNamespace.Builder()
            .register(KryoNamespaces.API)
            .register(ConfigKey.class, ObjectNode.class, ArrayNode.class,
                      JsonNodeFactory.class, LinkedHashMap.class,
                      TextNode.class, BooleanNode.class,
                      LongNode.class, DoubleNode.class, ShortNode.class, IntNode.class,
                      NullNode.class);

    configs = storageService.<ConfigKey, JsonNode>consistentMapBuilder()
            .withSerializer(Serializer.using(kryoBuilder.build()))
            .withName("onos-network-configs")
            .withRelaxedReadConsistency()
            .build();
    configs.addListener(listener);
    log.info("Started");
}
项目:athena    文件:ControlMetricsWebResource.java   
/**
 * 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() {

    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();
}
项目:kafka-0.11.0.0-src-with-comment    文件:JsonConverterTest.java   
@Test
public void mapToJsonNonStringKeys() {
    Schema intIntMap = SchemaBuilder.map(Schema.INT32_SCHEMA, Schema.INT32_SCHEMA).build();
    Map<Integer, Integer> input = new HashMap<>();
    input.put(1, 12);
    input.put(2, 15);
    JsonNode converted = parse(converter.fromConnectData(TOPIC, intIntMap, input));
    validateEnvelope(converted);
    assertEquals(parse("{ \"type\": \"map\", \"keys\": { \"type\" : \"int32\", \"optional\": false }, \"values\": { \"type\" : \"int32\", \"optional\": false }, \"optional\": false }"),
            converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));

    assertTrue(converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME).isArray());
    ArrayNode payload = (ArrayNode) converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME);
    assertEquals(2, payload.size());
    Set<JsonNode> payloadEntries = new HashSet<>();
    for (JsonNode elem : payload)
        payloadEntries.add(elem);
    assertEquals(new HashSet<>(Arrays.asList(JsonNodeFactory.instance.arrayNode().add(1).add(12),
                    JsonNodeFactory.instance.arrayNode().add(2).add(15))),
            payloadEntries
    );
}
项目:centraldogma    文件:GitMirrorAuthTest.java   
@Test
public void testAuth() throws Exception {
    // Add /credentials.json and /mirrors.json
    final ArrayNode credentials = JsonNodeFactory.instance.arrayNode().add(credential);
    client.push(projName, Project.REPO_META, Revision.HEAD, TestConstants.AUTHOR, "Add a mirror",
                Change.ofJsonUpsert("/credentials.json", credentials),
                Change.ofJsonUpsert("/mirrors.json",
                                    "[{" +
                                    "  \"type\": \"single\"," +
                                    "  \"direction\": \"REMOTE_TO_LOCAL\"," +
                                    "  \"localRepo\": \"main\"," +
                                    "  \"localPath\": \"/\"," +
                                    "  \"remoteUri\": \"" + gitUri + '"' +
                                    "}]")).join();

    // Try to perform mirroring to see if authentication works as expected.
    mirroringService.mirror().join();
}
项目:scanning    文件:SubsetStatus.java   
/**
 * Returns true if expected is a subset of returned
 *
 * This is used for JSON serialiser comparisons. This is taken from
 * the 'equals' definition of JsonNode's, but without the length check
 * on the list of children nodes, plus location reporting.
 *
 * @param expected
 * @param returned
 * @return
 */
protected boolean isJsonNodeSubset(JsonNode expected, JsonNode returned) {

    if (returned == null) {
    errorDescription = "Returned value is null, expected JSON:\n" + expected.toString();
    return false;
    }
    if (returned == expected) return true;

    if (returned.getClass() != expected.getClass()) {
    errorDescription = "Returned value class is incorrect, expected JSON: " + expected.toString()
    + ", returned JSON: " + returned.toString();
    return false;
    }

    switch (expected.getNodeType()) {
    case ARRAY:     return isArrayNodeSubset((ArrayNode)expected, (ArrayNode)returned);
    case OBJECT:    return isObjectNodeSubset((ObjectNode)expected, (ObjectNode)returned);
    default:        return isValueEqual((ValueNode)expected, (ValueNode)returned);  // Will be a ValueNode subclass
    }
}
项目:athena    文件:PceWebTopovMessageHandler.java   
@Override
public void process(long sid, ObjectNode payload) {
    String srcId = string(payload, SRCID);
    ElementId src = elementId(srcId);
    String dstId = string(payload, DSTID);
    ElementId dst = elementId(dstId);
    Device srcDevice = deviceService.getDevice((DeviceId) src);
    Device dstDevice = deviceService.getDevice((DeviceId) dst);

    TunnelEndPoint tunSrc = IpTunnelEndPoint.ipTunnelPoint(IpAddress
            .valueOf(srcDevice.annotations().value("lsrId")));
    TunnelEndPoint tunDst = IpTunnelEndPoint.ipTunnelPoint(IpAddress
            .valueOf(dstDevice.annotations().value("lsrId")));

    Collection<Tunnel> tunnelSet = tunnelService.queryTunnel(tunSrc, tunDst);
    ObjectNode result = objectNode();
    ArrayNode arrayNode = arrayNode();
    for (Tunnel tunnel : tunnelSet) {
        if (tunnel.type() == MPLS) {
            arrayNode.add(tunnel.tunnelId().toString());
        }
    }

    result.putArray(BUFFER_ARRAY).addAll(arrayNode);
    sendMessage(PCEWEB_SHOW_TUNNEL, sid, result);
}
项目:exam    文件:OrganisationController.java   
@Restrict({@Group("STUDENT")})
public CompletionStage<Result> listOrganisations() throws MalformedURLException {
    URL url = parseUrl();
    WSRequest request = wsClient.url(url.toString());
    String localRef = ConfigFactory.load().getString("sitnet.integration.iop.organisationRef");

    Function<WSResponse, Result>  onSuccess = response -> {
        JsonNode root = response.asJson();
        if (response.getStatus() != 200) {
            return internalServerError(root.get("message").asText("Connection refused"));
        }
        if (root instanceof ArrayNode) {
            ArrayNode node = (ArrayNode) root;
            for (JsonNode n : node) {
                ((ObjectNode) n).put("homeOrg", n.get("_id").asText().equals(localRef));
            }
        }
        return ok(root);
    };
    return request.get().thenApplyAsync(onSuccess);
}
项目:plumdo-work    文件:ProcessDefinitionAuthorizeResource.java   
@RequestMapping(value = "/process-definition/{processDefinitionId}/authorize", method = RequestMethod.GET, produces = "application/json", name = "流程定义授权查询")
public ArrayNode getAuthorizes(@PathVariable String processDefinitionId) {
    ProcessDefinition processDefinition = getProcessDefinitionFromRequest(processDefinitionId);
    List<IdentityLink> identityLinks = repositoryService.getIdentityLinksForProcessDefinition(processDefinition.getId());
    ArrayNode arrayNode = objectMapper.createArrayNode();
    for(IdentityLink identityLink :identityLinks){
        ObjectNode objectNode = objectMapper.createObjectNode();
        if(identityLink.getGroupId()!=null){
            objectNode.put("type", ProcessDefinitionAuthorizeRequest.AUTHORIZE_GROUP);
            objectNode.put("identityId", identityLink.getGroupId());
        }else if(identityLink.getUserId()!=null){
            objectNode.put("type", ProcessDefinitionAuthorizeRequest.AUTHORIZE_USER);
            objectNode.put("identityId", identityLink.getUserId());
        }
        arrayNode.add(objectNode);
    }

    return arrayNode;
}
项目:crnk-framework    文件:BaseMetaPartition.java   
public BaseMetaPartition() {
    registerPrimitiveType(String.class);
    registerPrimitiveType(Number.class);
    registerPrimitiveType(Boolean.class);
    registerPrimitiveType(Integer.class);
    registerPrimitiveType(Short.class);
    registerPrimitiveType(Byte.class);
    registerPrimitiveType(Long.class);
    registerPrimitiveType(Float.class);
    registerPrimitiveType(Double.class);
    registerPrimitiveType(UUID.class);
    registerPrimitiveType(Date.class);
    registerPrimitiveType(Timestamp.class);
    registerPrimitiveType(JsonNode.class);
    registerPrimitiveType(ObjectNode.class);
    registerPrimitiveType(ArrayNode.class);
    registerPrimitiveType(byte[].class);
    registerPrimitiveType(boolean[].class);
    registerPrimitiveType(int[].class);
    registerPrimitiveType(short[].class);
    registerPrimitiveType(long[].class);
    registerPrimitiveType(double[].class);
    registerPrimitiveType(float[].class);
}
项目:marklogic-rdf4j    文件:ConnectedRESTQA.java   
public static void addGeospatialElementIndexes(String dbName,String localname,String namespace,String coordinateSystem,String pointFormat,boolean rangeValuePositions,String invalidValues) throws Exception{
    ObjectMapper mapper = new ObjectMapper();
    //      ObjectNode mainNode = mapper.createObjectNode();
    ObjectNode childNode = mapper.createObjectNode();
    ArrayNode childArray = mapper.createArrayNode();
    ObjectNode childNodeObject = mapper.createObjectNode();
    childNodeObject.put( "namespace-uri", namespace);
    childNodeObject.put( "localname", localname);
    childNodeObject.put( "coordinate-system", coordinateSystem);
    childNodeObject.put("range-value-positions", false);
    childNodeObject.put("invalid-values", invalidValues);
    childNodeObject.put("point-format",pointFormat);
    childArray.add(childNodeObject);
    childNode.putArray("geospatial-element-index").addAll(childArray);
    //          mainNode.put("geospatial-element-indexes", childNode);
    //          System.out.println(type + mainNode.path("range-path-indexes").path("range-path-index").toString());
    setDatabaseProperties(dbName,"geospatial-element-index",childNode);
}
项目:Equella    文件:InstitutionRequests.java   
/**
 * 
 * @param urlPortion http://serverurl/urlPortion
 * @return
 */
public ObjectNode getByUrl(String urlPortion)
{
    String fullUrl = baseUrl + urlPortion;
    if( !fullUrl.endsWith("/") )
    {
        fullUrl = fullUrl + "/";
    }
    ArrayNode all = list();
    for( JsonNode inst : all )
    {
        ObjectNode i = (ObjectNode) inst;
        if( i.get("url").asText().equals(fullUrl) )
        {
            return i;
        }
    }
    return null;
}
项目:exam    文件:ExamOwnerController.java   
@Restrict({@Group("TEACHER"), @Group("ADMIN")})
public Result getExamOwners(Long id) {
    Exam exam = Ebean.find(Exam.class).fetch("examOwners").where().idEq(id).findUnique();
    if (exam == null) {
        return notFound();
    }
    ArrayNode node = Json.newArray();
    exam.getExamOwners().stream().map(u -> {
        ObjectNode o = Json.newObject();
        o.put("firstName", u.getFirstName());
        o.put("id", u.getId());
        o.put("lastName", u.getLastName());
        return o;
    }).forEach(node::add);
    return ok(Json.toJson(node));
}
项目:csap-core    文件:ServiceCollectionResults.java   
public void updateJmxResultCache ( Map<String, ObjectNode> jmxResultCacheNode ) {
    // String metricFullName = metricsArray[0] + "_" +
    // serviceName;
    ensureJmxStandardCacheInitialized( jmxResultCacheNode );
    String serviceNamePort = serviceInstance.getServiceName_Port();
    ObjectNode serviceCacheNode = jmxResultCacheNode.get( serviceNamePort );

    for ( JmxCommonEnum metric : JmxCommonEnum.values() ) {

        // some jvms are not tomcat, so skip tomcat specific metrics
        if ( !serviceInstance.isTomcatJarsPresent() && metric.isTomcatOnly() ) {
            continue;
        }

        ArrayNode metricResultsArray = ((ArrayNode) serviceCacheNode
            .get( metric.value + "_" + serviceNamePort ));

        metricResultsArray.insert( 0, this.getValue( metric ) );

        if ( metricResultsArray.size() > inMemoryCacheSize ) {
            metricResultsArray.remove( metricResultsArray.size() - 1 );
        }
    }

}
项目:bigchaindb-java-driver    文件:SignedBigchaindbTransactionFactory.java   
private static void addFulfillments(final ObjectNode transactionEnvelopeNode, final List<KeyPair> keyPairs) {
    final String canonicalString = JsonCanonicalizer.json2CanonicalString(transactionEnvelopeNode);
    Ed25519Fulfillment fulfillment =
            Ed25519Fulfillment.BuildFromSecrets(keyPairs.get(0), new MessagePayload(encodeUtf8(canonicalString)));
    final ObjectNode fulfillmentNode = jsonNodeFactory.objectNode();
    fulfillmentNode.set("fulfillment", jsonNodeFactory.textNode(fulfillment.toURI()));
    fulfillmentNode.set("fulfills", jsonNodeFactory.nullNode());
    final ArrayNode ownersBefore = jsonNodeFactory.arrayNode();
    ownersBefore.add(jsonNodeFactory.textNode(Base58.base58Encode(keyPairs.get(0).getPublic().getEncoded())));
    fulfillmentNode.set("owners_before", ownersBefore);

    JsonNode fulfillments = transactionEnvelopeNode.get("inputs");
    if (fulfillments == null || !fulfillments.isArray()) {
        throw new RuntimeException("Badly structured transaction does not contain \"inputs\": " + transactionEnvelopeNode);
    }
    ((ArrayNode) fulfillments).set(0, fulfillmentNode);
}
项目:athena    文件:FlowsWebResource.java   
/**
 * Creates new flow rules. Creates and installs a new flow rules.<br>
 * Instructions description:
 * https://wiki.onosproject.org/display/ONOS/Flow+Rule+Instructions
 * <br>
 * Criteria description:
 * https://wiki.onosproject.org/display/ONOS/Flow+Rule+Criteria
 *
 * @param stream flow rules JSON
 * @return status of the request - CREATED if the JSON is correct,
 * BAD_REQUEST if the JSON is invalid
 * @onos.rsModel FlowsBatchPost
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createFlows(@QueryParam("appId") String appId, InputStream stream) {
    try {
        ObjectNode jsonTree = (ObjectNode) mapper().readTree(stream);
        ArrayNode flowsArray = (ArrayNode) jsonTree.get(FLOWS);

        if (appId != null) {
            flowsArray.forEach(flowJson -> ((ObjectNode) flowJson).put("appId", appId));
        }

        List<FlowRule> rules = codec(FlowRule.class).decode(flowsArray, this);
        service.applyFlowRules(rules.toArray(new FlowRule[rules.size()]));
        rules.forEach(flowRule -> {
            ObjectNode flowNode = mapper().createObjectNode();
            flowNode.put(DEVICE_ID, flowRule.deviceId().toString())
                    .put(FLOW_ID, flowRule.id().value());
            flowsNode.add(flowNode);
        });
    } catch (IOException ex) {
        throw new IllegalArgumentException(ex);
    }
    return Response.ok(root).build();
}
项目:log4j2-logstash-layout    文件:ContextStackResolver.java   
@Override
public JsonNode resolve(TemplateResolverContext context, LogEvent logEvent, String key) {
    ThreadContext.ContextStack contextStack = logEvent.getContextStack();
    if (contextStack.getDepth() == 0) {
        return null;
    }
    Pattern itemPattern = context.getNdcPattern();
    ArrayNode contextStackNode = context.getObjectMapper().createArrayNode();
    for (String contextStackItem : contextStack.asList()) {
        boolean matches = itemPattern == null || itemPattern.matcher(contextStackItem).matches();
        if (matches) {
            contextStackNode.add(contextStackItem);
        }
    }
    return contextStackNode;
}
项目:marklogic-rdf4j    文件:ConnectedRESTQA.java   
public static void addGeoSpatialElementChildIndexes(String dbName,String parentNamespaceUri,String parentLocalName,String namespace,String localname,String coordinateSystem,String pointFormat,boolean rangeValuePositions,String invalidValues) throws Exception{
    ObjectMapper mapper = new ObjectMapper();
    //      ObjectNode mainNode = mapper.createObjectNode();
    ObjectNode childNode = mapper.createObjectNode();
    ArrayNode childArray = mapper.createArrayNode();
    ObjectNode childNodeObject = mapper.createObjectNode();
    childNodeObject.put( "parent-namespace-uri", parentNamespaceUri);
    childNodeObject.put( "parent-localname", parentLocalName);
    childNodeObject.put( "namespace-uri", namespace);
    childNodeObject.put( "localname", localname);
    childNodeObject.put( "coordinate-system", coordinateSystem);
    childNodeObject.put("range-value-positions", false);
    childNodeObject.put("invalid-values", invalidValues);
    childNodeObject.put("point-format",pointFormat);
    childArray.add(childNodeObject);
    childNode.putArray("geospatial-element-child-index").addAll(childArray);
    //          mainNode.put("geospatial-element-child-indexes", childNode);
    //          System.out.println(type + mainNode.path("range-path-indexes").path("range-path-index").toString());
    setDatabaseProperties(dbName,"geospatial-element-child-index",childNode);
}
项目:csap-core    文件:ModelApi.java   
@CsapDoc ( notes = {
        "Service Definitions on host that match name specified regular expression filters", } , linkTests = {
                "CsAgent",
                "List"
        } , linkGetParams = { "serviceName=CsAgent" } )
@RequestMapping ( "/services/byName/{serviceName:.+}" )
public JsonNode serviceDefinitionsFilteredByName (
                                                    @PathVariable ( "serviceName" ) String serviceName ) {

    if ( serviceName.equals( "{serviceName}" ) ) {
        return getAllServices();
    }

    List<ServiceInstance> filterInstances = application.getActiveModel()
        .getServicesOnHost( Application.getHOST_NAME() )
        .filter( serviceInstance -> serviceInstance.getServiceName().matches( serviceName ) )
        .collect( Collectors.toList() );

    return jacksonMapper.convertValue( filterInstances, ArrayNode.class );
}
项目:dataplatform-schema-lib    文件:JacksonArrayFormatter.java   
@Override
public JsonNode writeParser( final IParser parser ) throws IOException{
  ArrayNode array = new ArrayNode( JsonNodeFactory.instance );
  for( int i = 0 ; i < parser.size() ; i++ ){
    IParser childParser = parser.getParser( i );
    if( childParser.isMap() || childParser.isStruct() ){
      array.add( JacksonParserToJsonObject.getFromObjectParser( childParser ) );
    }
    else if( childParser.isArray() ){
      array.add( JacksonParserToJsonObject.getFromArrayParser( childParser ) );
    }
    else{
      array.add( PrimitiveObjectToJsonNode.get( parser.get( i ) ) );
    }
  }
  return array;
}
项目:csap-core    文件:ModelApi.java   
@CsapDoc ( notes = "Gets packages, by cluster and hosts" )
@RequestMapping ( "/packages" )
public ArrayNode packagesWithCluster () {

    List<ObjectNode> nodeList = application
        .getReleasePackageStream()
        .map( model -> {
            ObjectNode packageJson = jacksonMapper.createObjectNode();
            packageJson.put( "packageName", model.getReleasePackageName() );
            packageJson.put( "packageFile", model.getReleasePackageFileName() );
            packageJson.set( "clusters", application.getClusters( model ) );
            return packageJson;
        } )
        .collect( Collectors.toList() );

    return jacksonMapper.convertValue( nodeList, ArrayNode.class );
}
项目:marklogic-rdf4j    文件:ConnectedRESTQA.java   
public static ObjectNode getPermissionNode(String roleName, DocumentMetadataHandle.Capability... cap){
    ObjectMapper mapper= new ObjectMapper();
    ObjectNode mNode = mapper.createObjectNode();
    ArrayNode aNode = mapper.createArrayNode();

    for(DocumentMetadataHandle.Capability c : cap){
        ObjectNode roleNode =mapper.createObjectNode();
        roleNode.put("role-name",roleName);
        roleNode.put("capability", c.toString().toLowerCase());
        aNode.add(roleNode);
    }
    mNode.withArray("permission").addAll(aNode);
    return mNode;
}
项目:athena    文件:RolesCommand.java   
private JsonNode json(MastershipService service, List<Device> sortedDevices) {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode results = mapper.createArrayNode();
    for (Device device : sortedDevices) {
        results.add(json(service, mapper, device));
    }
    return results;
}
项目:beaker-notebook-archive    文件:CategoryPlotSerializerTest.java   
@Test
public void serializeGraphicsListCategoryPlot_resultJsonHasGraphicsList() throws IOException {
  //when
  CategoryPlot categoryPlot = new CategoryPlot();
  categoryPlot.add(Arrays.asList(new CategoryBars(), new CategoryPoints()));
  categoryPlotSerializer.serialize(categoryPlot, jgen, new DefaultSerializerProvider.Impl());
  jgen.flush();
  //then
  JsonNode actualObj = mapper.readTree(sw.toString());
  Assertions.assertThat(actualObj.has("graphics_list")).isTrue();
  ArrayNode arrayNode = (ArrayNode) actualObj.get("graphics_list");
  Assertions.assertThat(arrayNode.size()).isEqualTo(2);
}
项目:GitHub    文件:FragmentResolverTest.java   
@Test
public void pathCanReferToArrayContentsAtTheDocumentRoot() {
    ArrayNode root = new ObjectMapper().createArrayNode();

    root.add(root.objectNode());
    root.add(root.objectNode());
    root.add(root.objectNode());

    assertThat(resolver.resolve(root, "#/0", "#/."), is(sameInstance(root.get(0))));
    assertThat(resolver.resolve(root, "#/1", "#/."), is(sameInstance(root.get(1))));
    assertThat(resolver.resolve(root, "#/2", "#/."), is(sameInstance(root.get(2))));

}
项目:beaker-notebook-archive    文件:XYGraphicsSerializerTest.java   
@Test
public void serializeBigIntXWithNanoPlotType_resultJsonHasStringX() throws IOException {
  //when
  line.setX(
      Arrays.asList(
          new BigInteger("12345678901234567891000"), new BigInteger("12345678901234567891000")));
  line.setPlotType(NanoPlot.class);
  xyGraphicsSerializer.serialize(line, jgen, new DefaultSerializerProvider.Impl());
  jgen.flush();
  //then
  JsonNode actualObj = mapper.readTree(sw.toString());
  Assertions.assertThat(actualObj.has("x")).isTrue();
  ArrayNode arrayNode = (ArrayNode) actualObj.get("x");
  Assertions.assertThat(arrayNode.get(1).isTextual()).isTrue();
}
项目:OperatieBRP    文件:VrijBerichtDeserializer.java   
@Override
public VrijBericht deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException {
    final ObjectCodec oc = jp.getCodec();
    final JsonNode node = oc.readTree(jp);

    final Integer id = JsonUtils.getAsInteger(node, "id");
    VrijBericht vrijBericht;
    if (id != null) {
        // Bij een bestaand vrij bericht alleen indicatieGelezen aanpassen.
        vrijBericht = entityManager.find(VrijBericht.class, id);
        final String ongelezen = JsonUtils.getAsString(node, "ongelezen");
        boolean gelezen;
        switch (ongelezen) {
            case "Nee":
                gelezen = true;
                break;
            case "Ja":
            default:
                gelezen = false;
        }
        vrijBericht.setIndicatieGelezen(gelezen);
    } else {
        final Short soortvrijberId = JsonUtils.getAsShort(node, "soortvrijber");
        final String data = JsonUtils.getAsString(node, "data");
        final SoortVrijBericht soortVrijBericht = entityManager.getReference(SoortVrijBericht.class, soortvrijberId);
        vrijBericht =
                new VrijBericht(SoortBerichtVrijBericht.STUUR_VRIJ_BERICHT, soortVrijBericht,
                        Timestamp.from(DatumUtil.nuAlsZonedDateTimeInNederland().toInstant()), data, null);
        final ArrayNode partijen = (ArrayNode) node.get("partijen");
        for (JsonNode partijNode : partijen) {
            final Short partijId = Short.valueOf(partijNode.asText());
            final VrijBerichtPartij vrijBerichtPartij = new VrijBerichtPartij(vrijBericht, partijRepository.findOne(partijId));
            vrijBericht.getVrijBerichtPartijen().add(vrijBerichtPartij);
        }
    }
    return vrijBericht;
}
项目:athena    文件:ApplicationsListCommand.java   
private JsonNode json(ApplicationService service, List<Application> apps) {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode result = mapper.createArrayNode();
    for (Application app : apps) {
        boolean isActive = service.getState(app.id()) == ACTIVE;
        if (activeOnly && isActive || !activeOnly) {
            result.add(jsonForEntity(app, Application.class));
        }
    }
    return result;
}
项目:csap-core    文件:ModelApi.java   
private ObjectNode getAllServices () {
    ObjectNode response = jacksonMapper.createObjectNode();

    response.put( "info", "add service name to url" );
    response.set( "availableServices", jacksonMapper.convertValue(
        application.getActiveModel().getAllPackagesModel().getServiceNamesInLifecycle(),
        ArrayNode.class ) );
    return response;
}
项目:beaker-notebook-archive    文件:TableDisplaySerializerTest.java   
@Test
public void serializeContextMenuItems_resultJsonHasContextMenuItems() throws IOException{
  //given
  tableDisplay.addContextMenuItem("run_tag", new Object());
  //when
  JsonNode actualObj = serializeTableDisplay();
  //then
  Assertions.assertThat((ArrayNode) actualObj.get("contextMenuItems")).isNotEmpty();
}
项目:lemon    文件:BpmnJsonConverter.java   
protected void processFlowElement(FlowElement flowElement,
        FlowElementsContainer container, BpmnModel model,
        ArrayNode shapesArrayNode, double containerX, double containerY) {
    Class<? extends BaseBpmnJsonConverter> converter = convertersToJsonMap
            .get(flowElement.getClass());

    if (converter != null) {
        try {
            converter.newInstance().convertToJson(flowElement, this, model,
                    container, shapesArrayNode, containerX, containerY);
        } catch (Exception e) {
            LOGGER.error("Error converting {}", flowElement, e);
        }
    }
}
项目:beaker-notebook-archive    文件:BarsSerializerTest.java   
@Test
public void serializeOutlineColorsBars_resultJsonHasOutlineColors() throws IOException {
  //when
  Bars bars = new Bars();
  bars.setOutlineColor(Arrays.asList(Color.BLUE, Color.GREEN, Color.BLACK));
  barsSerializer.serialize(bars, jgen, new DefaultSerializerProvider.Impl());
  jgen.flush();
  //then
  JsonNode actualObj = mapper.readTree(sw.toString());
  Assertions.assertThat(actualObj.has("outline_colors")).isTrue();
  ArrayNode arrayNode = (ArrayNode) actualObj.get("outline_colors");
  Assertions.assertThat(arrayNode.get(1).get("rgb").asInt()).isEqualTo(Color.GREEN.getRGB());
}