Java Code Examples for com.fasterxml.jackson.databind.node.ObjectNode#putArray()

The following examples show how to use com.fasterxml.jackson.databind.node.ObjectNode#putArray() . 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 File: StatisticsWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Gets port statistics of a specified devices.
 * @onos.rsModel StatisticsPorts
 * @param deviceId device ID
 * @return 200 OK with JSON encoded array of port statistics
 */
@GET
@Path("ports/{deviceId}")
@Produces(MediaType.APPLICATION_JSON)
public Response getPortStatisticsByDeviceId(@PathParam("deviceId") String deviceId) {
    final DeviceService service = get(DeviceService.class);
    final Iterable<PortStatistics> portStatsEntries =
            service.getPortStatistics(DeviceId.deviceId(deviceId));
    final ObjectNode root = mapper().createObjectNode();
    final ArrayNode rootArrayNode = root.putArray("statistics");
    final ObjectNode deviceStatsNode = mapper().createObjectNode();
    deviceStatsNode.put("device", deviceId);
    final ArrayNode statisticsNode = deviceStatsNode.putArray("ports");
    if (portStatsEntries != null) {
        for (final PortStatistics entry : portStatsEntries) {
            statisticsNode.add(codec(PortStatistics.class).encode(entry, this));
        }
    }
    rootArrayNode.add(deviceStatsNode);

    return ok(root).build();
}
 
Example 2
Source File: PowerConfigWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Gets all power config devices.
 * Returns array of all discovered power config devices.
 *
 * @return 200 OK with a collection of devices
 * @onos.rsModel PowerConfigDevicesGet
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getDevices() {
    ObjectNode root = mapper().createObjectNode();
    ArrayNode deviceIdsNode = root.putArray(DEVICE_IDS);

    Iterable<Device> devices = get(DeviceService.class).getDevices();
    if (devices != null) {
        for (Device d : devices) {
            if (getPowerConfig(d.id().toString()) != null) {
                deviceIdsNode.add(d.id().toString());
            }
        }
    }

    return ok(root).build();
}
 
Example 3
Source File: FlowsWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Gets all flow entries for a table. Returns array of all flow rules for a table.
 * @param tableId table identifier
 * @return 200 OK with a collection of flows
 * @onos.rsModel FlowEntries
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("table/{tableId}")
public Response getTableFlows(@PathParam("tableId") int tableId) {
    ObjectNode root = mapper().createObjectNode();
    ArrayNode flowsNode = root.putArray(FLOWS);
    FlowRuleService service = get(FlowRuleService.class);
    Iterable<Device> devices = get(DeviceService.class).getDevices();
    for (Device device : devices) {
        Iterable<FlowEntry> flowEntries = service.getFlowEntries(device.id());
        if (flowEntries != null) {
            for (FlowEntry entry : flowEntries) {
                if (((IndexTableId) entry.table()).id() == tableId) {
                   flowsNode.add(codec(FlowEntry.class).encode(entry, this));
                }
            }
        }
    }

    return ok(root).build();
}
 
Example 4
Source File: ControlMetricsWebResource.java    From onos with 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 5
Source File: LispTeAddressCodec.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public ObjectNode encode(LispTeAddress address, CodecContext context) {
    checkNotNull(address, "LispTeAddress cannot be null");

    final ObjectNode result = context.mapper().createObjectNode();
    final ArrayNode jsonRecords = result.putArray(TE_RECORDS);

    final JsonCodec<LispTeAddress.TeRecord> recordCodec =
            context.codec(LispTeAddress.TeRecord.class);

    for (final LispTeAddress.TeRecord record : address.getTeRecords()) {
        jsonRecords.add(recordCodec.encode(record, context));
    }

    return result;
}
 
Example 6
Source File: YangWebResource.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all models registered with YANG runtime. If the operation is
 * successful, the JSON presentation of the resource plus HTTP status
 * code "200 OK" is returned.Otherwise,
 * HTTP error status code "400 Bad Request" is returned.
 *
 * @onos.rsModel YangModelsGet
 * @return HTTP response
 */
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getModels() {

    modelRegistry = getService(YangModelRegistry.class);
    ObjectNode result = mapper().createObjectNode();
    Set<YangModel> models = modelRegistry.getModels();
    ArrayNode ids = result.putArray("model_ids");
    for (YangModel m : models) {
        ids.add(m.getYangModelId());
    }
    return Response.ok(result.toString()).build();
}
 
Example 7
Source File: XconnectCodec.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public ObjectNode encode(XconnectDesc desc, CodecContext context) {
    final ObjectNode result = context.mapper().createObjectNode();
    result.put(DEVICE_ID, desc.key().deviceId().toString());
    result.put(VLAN_ID, desc.key().vlanId().toShort());
    final ArrayNode portNode = result.putArray(ENDPOINTS);
    desc.endpoints().forEach(endpoint -> portNode.add(endpoint.toString()));

    return result;
}
 
Example 8
Source File: ObjectWriter.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Writes an array of strings to the parent node.
 * 
 * @param parent the parent json node
 * @param models list of Strings
 * @param propertyName the name of the node
 */
public static void writeStringArray(ObjectNode parent, List<String> models, String propertyName) {
    if (models == null) {
        return;
    }
    ArrayNode node = parent.putArray(propertyName);
    for (String model : models) {
        node.add(model);
    }
}
 
Example 9
Source File: PortChainWebResource.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Get details of all port chains created.
 *
 * @return 200 OK
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response getPortChains() {
    Iterable<PortChain> portChains = get(PortChainService.class).getPortChains();
    ObjectNode result = mapper().createObjectNode();
    ArrayNode portChainEntry = result.putArray("port_chains");
    if (portChains != null) {
        for (final PortChain portChain : portChains) {
            portChainEntry.add(codec(PortChain.class).encode(portChain, this));
        }
    }
    return ok(result.toString()).build();
}
 
Example 10
Source File: JsonSettingsEncoder.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
public ObjectNode encode(Map<SettingDefinitionGroup, Set<SettingDefinition<?>>> grouped) {
    ObjectNode json = nodeFactory.objectNode();
    ArrayNode sections = json.putArray(JSONSettingConstants.SECTIONS_KEY);
    grouped.keySet().stream().sorted().forEach(group -> {
        ObjectNode jgroup = sections.addObject();
        jgroup.put(JSONSettingConstants.TITLE_KEY, group.getTitle());
        jgroup.put(JSONSettingConstants.DESCRIPTION_KEY, group.getDescription());
        jgroup.set(JSONSettingConstants.SETTINGS_KEY, encode(grouped.get(group)));
    });
    return json;
}
 
Example 11
Source File: DhcpWebResource.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Get all MAC/IP mappings.
 * Shows all MAC/IP mappings held by the DHCP server.
 *
 * @onos.rsModel DhcpConfigGetMappings
 * @return 200 OK
 */
@GET
@Path("mappings")
public Response listMappings() {
    ObjectNode root = mapper().createObjectNode();

    Map<HostId, IpAssignment> intents = service.listMapping();
    ArrayNode arrayNode = root.putArray("mappings");
    intents.entrySet().forEach(i -> arrayNode.add(mapper().createObjectNode()
                                                          .put("host", i.getKey().toString())
                                                          .put("ip", i.getValue().ipAddress().toString())));

    return ok(root).build();
}
 
Example 12
Source File: HttpRequestWrapperProcessor.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static void putPrameterValueTo(final ObjectNode node, String parameter, final String... values) {
    if (values == null || values.length == 0) {
        return;
    }

    if (values.length > 1) {
        final ArrayNode ary = node.putArray(parameter);
        for (String value : values) {
            ary.add(value);
        }
    } else {
        node.put(parameter, values[0]);
    }
}
 
Example 13
Source File: ConnectivityIntentCodec.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public ObjectNode encode(ConnectivityIntent intent, CodecContext context) {
    checkNotNull(intent, "Connectivity intent cannot be null");

    final JsonCodec<Intent> intentCodec = context.codec(Intent.class);
    final ObjectNode result = intentCodec.encode(intent, context);

    if (intent.selector() != null) {
        final JsonCodec<TrafficSelector> selectorCodec =
                context.codec(TrafficSelector.class);
        result.set(SELECTOR, selectorCodec.encode(intent.selector(), context));
    }

    if (intent.treatment() != null) {
        final JsonCodec<TrafficTreatment> treatmentCodec =
                context.codec(TrafficTreatment.class);
        result.set(TREATMENT, treatmentCodec.encode(intent.treatment(), context));
    }

    result.put(IntentCodec.PRIORITY, intent.priority());

    if (intent.constraints() != null) {
        final ArrayNode jsonConstraints = result.putArray(CONSTRAINTS);

        if (intent.constraints() != null) {
            final JsonCodec<Constraint> constraintCodec =
                    context.codec(Constraint.class);
            for (final Constraint constraint : intent.constraints()) {
                final ObjectNode constraintNode =
                        constraintCodec.encode(constraint, context);
                jsonConstraints.add(constraintNode);
            }
        }
    }

    return result;
}
 
Example 14
Source File: MaoRestResource.java    From ONOS_LoadBalance_Routing_Forward with Apache License 2.0 5 votes vote down vote up
/**
 * Hello world.
 * Mao.
 *
 * REST API:
 * http://127.0.0.1:8181/onos/mao/hello
 *
 * @return Beijing
 */
@GET
@Path("hello")
@Produces(MediaType.APPLICATION_JSON)
public Response hello() {
    ObjectNode root = mapper().createObjectNode();
    root.put("Hello", 1080)
            .put("Mao", 7181);

    ArrayNode array = root.putArray("RadioStation");
    array.add("192.168.1.1").add("127.0.0.1").add("10.3.8.211");

    return ok(root.toString()).build();
}
 
Example 15
Source File: AllowedMentionsImpl.java    From Javacord with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the json data to the given object node.
 *
 * @param object The object, the data should be added to.
 * @return The provided object with the data of the embed.
 */
public ObjectNode toJsonNode(ObjectNode object) {
    ArrayNode parse = object.putArray("parse");
    ArrayNode users = object.putArray("users");
    ArrayNode roles = object.putArray("roles");

    if (mentionAllRoles) {
        parse.add("roles");
    } else {
        if (allowedRoleMentions.size() > 100) {
            allowedRoleMentions.subList(0, 99).forEach(aLong -> roles.add(aLong.toString()));
        } else {
            allowedRoleMentions.forEach(aLong -> roles.add(aLong.toString()));
        }
    }

    if (mentionAllUsers) {
        parse.add("users");
    } else {
        if (allowedUserMentions.size() > 100) {
            allowedUserMentions.subList(0, 99).forEach(aLong -> users.add(aLong.toString()));
        } else {
            allowedUserMentions.forEach(aLong -> users.add(aLong.toString()));
        }
    }

    if (mentionEveryoneAndHere) {
        parse.add("everyone");
    }
    return object;
}
 
Example 16
Source File: GetServiceDescription.java    From constellation with Apache License 2.0 5 votes vote down vote up
@Override
public void callService(final PluginParameters parameters, InputStream in, OutputStream out) throws IOException {
    final String serviceName = parameters.getStringValue(SERVICE_NAME_PARAMETER_ID);
    final HttpMethod httpMethod = HttpMethod.getValue(parameters.getStringValue(METHOD_NAME_PARAMETER_ID));

    final ObjectMapper mapper = new ObjectMapper();
    final ObjectNode root = mapper.createObjectNode();

    final RestService rs = RestServiceRegistry.get(serviceName, httpMethod);
    root.put("name", rs.getName());
    root.put("http_method", httpMethod.name());
    root.put("description", rs.getDescription());
    root.put("mimetype", rs.getMimeType());
    final ArrayNode tags = root.putArray("tags");
    for (final String tag : rs.getTags()) {
        tags.add(tag);
    }

    final ObjectNode params = root.putObject("parameters");
    rs.createParameters().getParameters().entrySet().forEach(entry -> {
        final PluginParameter<?> pp = entry.getValue();
        final ObjectNode param = params.putObject(entry.getKey());
        param.put("name", pp.getName());
        param.put("type", pp.getType().getId());
        param.put("description", pp.getDescription());
        if (pp.getObjectValue() != null) {
            param.put("value", pp.getObjectValue().toString());
        }
    });

    mapper.writeValue(out, root);
}
 
Example 17
Source File: MessageBuilderDelegateImpl.java    From Javacord with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<Message> send(TextChannel channel) {
    ObjectNode body = JsonNodeFactory.instance.objectNode()
            .put("content", toString() == null ? "" : toString())
            .put("tts", tts);
    body.putArray("mentions");


    if (allowedMentions != null) {
        ((AllowedMentionsImpl) allowedMentions).toJsonNode(body.putObject("allowed_mentions"));
    }
    if (embed != null) {
        ((EmbedBuilderDelegateImpl) embed.getDelegate()).toJsonNode(body.putObject("embed"));
    }
    if (nonce != null) {
        body.put("nonce", nonce);
    }

    RestRequest<Message> request = new RestRequest<Message>(channel.getApi(), RestMethod.POST, RestEndpoint.MESSAGE)
            .setUrlParameters(channel.getIdAsString());
    if (!attachments.isEmpty() || (embed != null && embed.requiresAttachments())) {
        CompletableFuture<Message> future = new CompletableFuture<>();
        // We access files etc. so this should be async
        channel.getApi().getThreadPool().getExecutorService().submit(() -> {
            try {
                MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("payload_json", body.toString());
                List<FileContainer> tempAttachments = new ArrayList<>(attachments);
                // Add the attachments required for the embed
                if (embed != null) {
                    tempAttachments.addAll(
                            ((EmbedBuilderDelegateImpl) embed.getDelegate()).getRequiredAttachments());
                }
                Collections.reverse(tempAttachments);
                for (int i = 0; i < tempAttachments.size(); i++) {
                    byte[] bytes = tempAttachments.get(i).asByteArray(channel.getApi()).join();

                    String mediaType = URLConnection
                            .guessContentTypeFromName(tempAttachments.get(i).getFileTypeOrName());
                    if (mediaType == null) {
                        mediaType = "application/octet-stream";
                    }
                    multipartBodyBuilder.addFormDataPart("file" + i, tempAttachments.get(i).getFileTypeOrName(),
                            RequestBody.create(MediaType.parse(mediaType), bytes));
                }

                request.setMultipartBody(multipartBodyBuilder.build());
                request.execute(result -> ((DiscordApiImpl) channel.getApi())
                        .getOrCreateMessage(channel, result.getJsonBody()))
                        .whenComplete((message, throwable) -> {
                            if (throwable != null) {
                                future.completeExceptionally(throwable);
                            } else {
                                future.complete(message);
                            }
                        });
            } catch (Throwable t) {
                future.completeExceptionally(t);
            }
        });
        return future;
    } else {
        request.setBody(body);
        return request.execute(result -> ((DiscordApiImpl) channel.getApi())
                .getOrCreateMessage(channel, result.getJsonBody()));
    }
}
 
Example 18
Source File: ExternalWorkerAcquireJobResourceTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Test
@CmmnDeployment(resources = "org/flowable/external/job/rest/service/api/simpleExternalWorkerJob.cmmn")
void terminateCmmnJobWithVariables() {
    CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder()
            .caseDefinitionKey("simpleExternalWorker")
            .start();

    assertThat(cmmnTaskService.createTaskQuery().list()).isEmpty();
    assertThat(cmmnRuntimeService.getVariables(caseInstance.getId())).isEmpty();

    ExternalWorkerJob externalWorkerJob = managementService.createExternalWorkerJobQuery().singleResult();
    assertThat(externalWorkerJob).isNotNull();

    managementService.createExternalWorkerJobAcquireBuilder()
            .topic("simple", Duration.ofMinutes(10))
            .acquireAndLock(1, "testWorker1");

    ObjectNode request = objectMapper.createObjectNode();
    request.put("workerId", "testWorker1");
    ArrayNode variables = request.putArray("variables");

    variables.add(createVariableNode("terminateReason", "string", "test"));

    ResponseEntity<String> response = restTemplate
            .postForEntity("/service/acquire/jobs/{jobId}/cmmnTerminate", request, String.class, externalWorkerJob.getId());

    assertThat(response.getStatusCode()).as(response.toString()).isEqualTo(HttpStatus.NO_CONTENT);
    String body = response.getBody();
    assertThat(body).isNull();

    CmmnJobTestHelper.waitForJobExecutorToProcessAllJobs(cmmnEngineConfiguration, 4000, 300, true);

    assertThat(cmmnTaskService.createTaskQuery().list())
            .extracting(Task::getTaskDefinitionKey)
            .containsExactlyInAnyOrder("afterExternalWorkerTerminateTask");

    assertThat(cmmnRuntimeService.getVariables(caseInstance.getId()))
            .containsOnly(
                    entry("terminateReason", "test")
            );
}
 
Example 19
Source File: SignalsResourceTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Test
@Deployment(resources = { "org/flowable/rest/service/api/runtime/SignalsResourceTest.process-signal-start.bpmn20.xml" })
public void testSignalEventReceivedAsync() throws Exception {

    org.flowable.engine.repository.Deployment tenantDeployment = repositoryService.createDeployment()
            .addClasspathResource("org/flowable/rest/service/api/runtime/SignalsResourceTest.process-signal-start.bpmn20.xml").tenantId("my tenant").deploy();

    try {

        // Signal without vars, without tenant
        ObjectNode requestNode = objectMapper.createObjectNode();
        requestNode.put("signalName", "The Signal");
        requestNode.put("async", true);

        HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_SIGNALS));
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_ACCEPTED));

        // Check if job is queued as a result of the signal without tenant ID set
        assertThat(managementService.createJobQuery().jobWithoutTenantId().count()).isEqualTo(1);

        // Signal with tenant
        requestNode.put("tenantId", "my tenant");
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_ACCEPTED));

        // Check if job is queued as a result of the signal, in the right tenant
        assertThat(managementService.createJobQuery().jobTenantId("my tenant").count()).isEqualTo(1);

        // Signal with variables and async, should fail as it's not supported
        ArrayNode vars = requestNode.putArray("variables");
        ObjectNode var = vars.addObject();
        var.put("name", "testVar");
        var.put("value", "test");

        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_BAD_REQUEST));

    } finally {
        // Clean up tenant-specific deployment
        if (tenantDeployment != null) {
            repositoryService.deleteDeployment(tenantDeployment.getId(), true);
        }

        // Clear jobs
        List<Job> jobs = managementService.createJobQuery().list();
        for (Job job : jobs) {
            managementService.deleteJob(job.getId());
        }
    }
}
 
Example 20
Source File: MSSqlServerDialect.java    From sqlg with MIT License 4 votes vote down vote up
@SuppressWarnings("Duplicates")
@Override
public void putJsonObject(ObjectNode obj, String columnName, int sqlType, Object o) {
    switch (sqlType) {
        case Types.ARRAY:
            try {
                ArrayNode arrayNode = obj.putArray(columnName);
                java.sql.Array sqlA = (java.sql.Array) o;
                Object a = sqlA.getArray();

                int len = Array.getLength(a);
                if (len > 0) {
                    PropertyType pt = PropertyType.from(Array.get(a, 0));

                    for (int i = 0; i < len; ++i) {
                        Object v = Array.get(a, i);
                        switch (pt.ordinal()) {
                            case BOOLEAN_ORDINAL:
                                arrayNode.add((Boolean) v);
                                break;
                            case BYTE_ORDINAL:
                                arrayNode.add((Byte) v);
                                break;
                            case DOUBLE_ORDINAL:
                                arrayNode.add((Double) v);
                                break;
                            case FLOAT_ORDINAL:
                                arrayNode.add((Float) v);
                                break;
                            case INTEGER_ORDINAL:
                                arrayNode.add((Integer) v);
                                break;
                            case LONG_ORDINAL:
                                arrayNode.add((Long) v);
                                break;
                            case SHORT_ORDINAL:
                                arrayNode.add((Short) v);
                                break;
                            case STRING_ORDINAL:
                                arrayNode.add((String) v);
                                break;
                        }
                    }
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            break;
        default:
            super.putJsonObject(obj, columnName, sqlType, o);
    }
}