Example usage for javax.json Json createObjectBuilder

List of usage examples for javax.json Json createObjectBuilder

Introduction

In this page you can find the example usage for javax.json Json createObjectBuilder.

Prototype

public static JsonObjectBuilder createObjectBuilder() 

Source Link

Document

Creates a JSON object builder

Usage

From source file:nl.sidn.dnslib.message.records.NotImplementedResourceRecord.java

@Override
public JsonObject toJSon() {
    String actualClass = null;/*from   w  w  w. j ava  2 s.c o m*/
    String actualType = null;
    if (classz == null) {
        actualClass = "CLASS" + (int) rawClassz;
    } else {
        actualClass = classz.name();
    }

    if (type == null) {
        actualType = "TYPE" + (int) rawType;
    } else {
        actualType = "" + type;
    }

    JsonObjectBuilder builder = Json.createObjectBuilder();
    return builder.add("rdata", Json.createObjectBuilder().add("class", actualClass).add("type", actualType)
            .add("rdlength", (int) rdLength).add("rdata", Hex.encodeHexString(rdata))).build();
}

From source file:org.fuin.esc.spi.Base64Data.java

@Override
public final JsonObject toJson() {
    return Json.createObjectBuilder().add(EL_ROOT_NAME, base64Str).build();
}

From source file:onl.area51.metoffice.metoffice.forecast.layer.ForecastImageLayerWS.java

protected HttpEntity sendLayerNames() {
    JsonObjectBuilder b = Json.createObjectBuilder().add("layers",
            forecastImageLayerService.getLayers().values().stream().reduce(Json.createArrayBuilder(),
                    (a, l) -> a.add(l.getLayerName()), Functions.writeOnceBinaryOperator()));
    JsonUtils.add(b, "timestamp", forecastImageLayerService.getLastReload());
    return new JsonEntity(b);
}

From source file:org.jboss.set.aphrodite.stream.services.json.StreamComponentJsonParser.java

public static JsonObject encodeStreamComponent(StreamComponent c) {
    final JsonObjectBuilder object = Json.createObjectBuilder();
    object.add(JSON_NAME, c.getName());// w  w w  .  j a v a 2  s .  c om
    object.add(JSON_CONTACTS, encodeContacts(c.getContacts()));
    object.add(JSON_REPOSITORY_TYPE, c.getRepositoryType().toString());
    object.add(JSON_REPOSITORY_URL, c.getRepositoryURL() == null ? "" : c.getRepositoryURL().toString());
    object.add(JSON_CODEBASE, c.getCodebase().getName());
    object.add(JSON_TAG, c.getTag());
    object.add(JSON_VERSION, c.getVersion());
    object.add(JSON_GAV, c.getGAV());
    object.add(JSON_COMMENT, c.getComment());
    return object.build();
}

From source file:sg.edu.ntu.hrms.service.EmployeeListService.java

private String convertToJson(List<UserDTO> userList, HashMap map) {
    JsonArrayBuilder array = Json.createArrayBuilder();
    for (int i = 0; i < userList.size(); i++) {
        UserDTO user = userList.get(i);//  w  w w  .j a v a 2  s  .com
        Date datejoin = user.getDateJoin();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String joinDateStr = formatter.format(datejoin);

        String approver = "";

        if (map.containsKey(user.getApprover())) {
            UserDTO mgr = (UserDTO) map.get(user.getApprover());
            approver = mgr.getName();
        }
        String deptDescr = "";
        if (user.getDept() != null) {
            deptDescr = user.getDept().getDept().getDescription();
        }
        System.out.println("approver: " + approver);
        array.add(Json.createObjectBuilder().add("id", user.getLogin()).add("name", user.getName())
                .add("email", user.getEmail()).add("dept", deptDescr)
                //.add("dept", user.getDept().getDept().getDescription())
                .add("title", user.getTitle().getDescription())
                //.add("category","coming")
                .add("manager", approver).add("datejoin", joinDateStr));

    }
    return array.build().toString();
}

From source file:co.runrightfast.vertx.orientdb.verticle.EventLogRepository.java

public static void initDatabase(@NonNull final ODatabase db) {
    final JsonLog info = JsonLog.newInfoLog(Logger.getLogger(EventLogRepository.class.getName()),
            EventLogRepository.class.getName());
    try {/*from   w ww  . java  2  s .  c o m*/
        OClass timestampedClass = db.getMetadata().getSchema().getClass(Timestamped.class.getSimpleName());
        if (timestampedClass == null) {
            timestampedClass = db.getMetadata().getSchema()
                    .createAbstractClass(Timestamped.class.getSimpleName());
            timestampedClass.createProperty(Timestamped.Field.created_on.name(), OType.DATETIME);
            timestampedClass.createProperty(Timestamped.Field.updated_on.name(), OType.DATETIME);
            info.log("startUp", () -> Json.createObjectBuilder().add("class", Timestamped.class.getSimpleName())
                    .add("created", true).build());
        } else {
            info.log("startUp",
                    () -> Json.createObjectBuilder().add("class", Timestamped.class.getSimpleName()).build());
        }

        OClass logRecordClass = db.getMetadata().getSchema().getClass(EventLogRecord.class.getSimpleName());
        if (logRecordClass == null) {
            logRecordClass = db.getMetadata().getSchema().createClass(EventLogRecord.class.getSimpleName())
                    .setSuperClasses(ImmutableList.of(timestampedClass));
            logRecordClass.createProperty(EventLogRecord.Field.event.name(), OType.STRING);
            info.log("startUp", () -> Json.createObjectBuilder()
                    .add("class", EventLogRecord.class.getSimpleName()).add("created", true).build());
        } else {
            info.log("startUp", () -> Json.createObjectBuilder()
                    .add("class", EventLogRecord.class.getSimpleName()).build());
        }

    } finally {
        db.close();
    }
}

From source file:au.org.ands.vocabs.toolkit.provider.transform.SolrIndexTransformProvider.java

@Override
public final boolean transform(final TaskInfo taskInfo, final JsonNode subtask,
        final HashMap<String, String> results) {
    Path dir = Paths.get(ToolkitFileUtils.getTaskHarvestOutputPath(taskInfo));
    ConceptHandler conceptHandler = new ConceptHandler();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        for (Path entry : stream) {
            RDFFormat format = Rio.getParserFormatForFileName(entry.toString());
            RDFParser rdfParser = Rio.createParser(format);
            rdfParser.setRDFHandler(conceptHandler);
            FileInputStream is = new FileInputStream(entry.toString());
            rdfParser.parse(is, entry.toString());

            logger.debug("Reading RDF:" + entry.toString());

        }/*from  w  w w .ja  v a2s  .c  o  m*/
    } catch (DirectoryIteratorException | IOException | RDFParseException | RDFHandlerException ex) {
        // I/O error encountered during the iteration,
        // the cause is an IOException
        results.put(TaskStatus.EXCEPTION, "Exception in SolrIndexTransform while Parsing RDF");
        logger.error("Exception in SolrIndexTransform while Parsing RDF:", ex);
        return false;
    }

    String resultFileName = ToolkitFileUtils.getTaskOutputPath(taskInfo, "concepts_solr.json");
    try {
        FileOutputStream out = new FileOutputStream(resultFileName);
        JsonObjectBuilder job = Json.createObjectBuilder();
        job.add("concepts_count", conceptHandler.getCountedPrefLabels());
        results.put("concepts_count", Integer.toString(conceptHandler.getCountedPrefLabels()));
        job.add("concepts_text", conceptHandler.getConceptText());
        results.put("concepts_solr", resultFileName);

        JsonWriter jsonWriter = Json.createWriter(out);
        jsonWriter.writeObject(job.build());
        jsonWriter.close();
    } catch (FileNotFoundException ex) {
        results.put(TaskStatus.EXCEPTION, "Exception in SolrIndexTransform while generating result");
        logger.error("Exception in SolrIndexTransform generating result:", ex);
        return false;
    }
    return true;
}

From source file:co.runrightfast.vertx.core.eventbus.EventBusAddressMessageMapping.java

public JsonObject toJson() {
    final JsonObjectBuilder json = Json.createObjectBuilder().add("address", address).add("requestMessageType",
            requestDefaultInstance.getDescriptorForType().getFullName());
    getResponseDefaultInstance().ifPresent(
            instance -> json.add("responseMessageType", instance.getDescriptorForType().getFullName()));
    return json.build();
}

From source file:nl.sidn.dnslib.message.records.dnssec.DSResourceRecord.java

@Override
public JsonObject toJSon() {
    JsonObjectBuilder builder = super.createJsonBuilder();
    return builder.add("rdata",
            Json.createObjectBuilder().add("keytag", (int) keytag)
                    .add("algorithm", algorithm != null ? algorithm.name() : "")
                    .add("digest-type", digestType.name()).add("digest", hex))
            .build();/*from w  w  w  .j ava2s  .  c  o m*/
}

From source file:org.takes.facets.auth.social.PsLinkedinTest.java

/**
 * PsLinkedin can login.//w w w . j  a va  2s. com
 * @throws IOException If some problem inside
 */
@Test
public void logins() throws IOException {
    final String code = RandomStringUtils.randomAlphanumeric(10);
    final String lapp = RandomStringUtils.randomAlphanumeric(10);
    final String lkey = RandomStringUtils.randomAlphanumeric(10);
    final String identifier = RandomStringUtils.randomAlphanumeric(10);
    final Take take = new TkFork(new FkRegex("/uas/oauth2/accessToken",
            // @checkstyle AnonInnerLengthCheck (100 lines)
            new Take() {
                @Override
                public Response act(final Request req) throws IOException {
                    MatcherAssert.assertThat(new RqPrint(req).printBody(),
                            Matchers.stringContainsInOrder(Arrays.asList("grant_type=authorization_code",
                                    String.format("client_id=%s", lapp), "redirect_uri=",
                                    String.format("client_secret=%s", lkey), String.format("code=%s", code))));
                    MatcherAssert.assertThat(new RqHref.Base(req).href().toString(),
                            Matchers.endsWith("/uas/oauth2/accessToken"));
                    return new RsJSON(Json.createObjectBuilder()
                            .add("access_token", RandomStringUtils.randomAlphanumeric(10)).build());
                }
            }), new FkRegex("/v1/people", new Take() {
                @Override
                public Response act(final Request req) throws IOException {
                    return new RsJSON(Json.createObjectBuilder().add("id", identifier).add("firstName", "Frodo")
                            .add("lastName", "Baggins").build());
                }
            }));
    new FtRemote(take).exec(
            // @checkstyle AnonInnerLengthCheck (100 lines)
            new FtRemote.Script() {
                @Override
                public void exec(final URI home) throws IOException {
                    final Identity identity = new PsLinkedin(
                            new Href(String.format("%s/uas/oauth2/accessToken", home)),
                            new Href(String.format("%s/v1/people/", home)), lapp, lkey)
                                    .enter(new RqFake("GET", String.format("?code=%s", code))).get();
                    MatcherAssert.assertThat(identity.urn(),
                            CoreMatchers.equalTo(String.format("urn:linkedin:%s", identifier)));
                    MatcherAssert.assertThat(identity.properties(), Matchers.allOf(
                            Matchers.hasEntry("firstName", "Frodo"), Matchers.hasEntry("lastName", "Baggins")));
                }
            });
}