Example usage for javax.json JsonObject toString

List of usage examples for javax.json JsonObject toString

Introduction

In this page you can find the example usage for javax.json JsonObject toString.

Prototype

@Override
String toString();

Source Link

Document

Returns JSON text for this JSON value.

Usage

From source file:tools.xor.logic.DefaultJson.java

protected void checkDateField() throws JSONException {
    // create person
    JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
    jsonBuilder.add("name", "DILIP_DALTON");
    jsonBuilder.add("displayName", "Dilip Dalton");
    jsonBuilder.add("description", "Software engineer in the bay area");
    jsonBuilder.add("userName", "daltond");

    // 1/1/15 7:00 PM EST
    final long CREATED_ON = 1420156800000L;
    Date createdOn = new Date(CREATED_ON);
    DateFormat df = new SimpleDateFormat(ImmutableJsonProperty.ISO8601_FORMAT);
    jsonBuilder.add("createdOn", df.format(createdOn));

    Settings settings = new Settings();
    settings.setEntityClass(Person.class);
    Person person = (Person) aggregateService.create(jsonBuilder.build(), settings);
    assert (person.getId() != null);
    assert (person.getName().equals("DILIP_DALTON"));
    assert (person.getCreatedOn().getTime() == CREATED_ON);

    Object jsonObject = aggregateService.read(person, settings);
    JsonObject json = (JsonObject) jsonObject;
    System.out.println("JSON string: " + json.toString());
    assert (((JsonString) json.get("name")).getString().equals("DILIP_DALTON"));
    assert (((JsonString) json.get("createdOn")).getString().equals("2015-01-01T16:00:00.000-0800"));
}

From source file:tools.xor.logic.DefaultJson.java

protected void checkEntityField() {
    final String TASK_NAME = "SETUP_DSL";

    // Create task
    JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
    jsonBuilder.add("name", TASK_NAME);
    jsonBuilder.add("displayName", "Setup DSL");
    jsonBuilder.add("description", "Setup high-speed broadband internet using DSL technology");

    // Create quote
    final BigDecimal price = new BigDecimal("123456789.987654321");
    jsonBuilder.add("quote", Json.createObjectBuilder().add("price", price));

    Settings settings = getSettings();/*from   w w w  .  ja  v a2  s .co  m*/
    settings.setEntityClass(Task.class);
    Task task = (Task) aggregateService.create(jsonBuilder.build(), settings);
    assert (task.getId() != null);
    assert (task.getName().equals(TASK_NAME));
    assert (task.getQuote() != null);
    assert (task.getQuote().getId() != null);
    assert (task.getQuote().getPrice().equals(price));

    Object jsonObject = aggregateService.read(task, settings);
    JsonObject jsonTask = (JsonObject) jsonObject;
    System.out.println("JSON string: " + jsonTask.toString());
    assert (((JsonString) jsonTask.get("name")).getString().equals(TASK_NAME));
    JsonObject jsonQuote = jsonTask.getJsonObject("quote");
    assert (((JsonNumber) jsonQuote.get("price")).bigDecimalValue().equals(price));
}

From source file:tools.xor.logic.DefaultJson.java

protected void checkSetField() {
    final String TASK_NAME = "SETUP_DSL";
    final String CHILD_TASK_NAME = "TASK_1";

    // Create task
    JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
    jsonBuilder.add("name", TASK_NAME);
    jsonBuilder.add("displayName", "Setup DSL");
    jsonBuilder.add("description", "Setup high-speed broadband internet using DSL technology");

    // Create and add 1 child task
    jsonBuilder.add("taskChildren",
            Json.createArrayBuilder().add(Json.createObjectBuilder().add("name", CHILD_TASK_NAME)
                    .add("displayName", "Task 1").add("description", "This is the first child task")));

    Settings settings = getSettings();// www .  jav a2s  .co  m
    settings.setEntityClass(Task.class);
    Task task = (Task) aggregateService.create(jsonBuilder.build(), settings);
    assert (task.getId() != null);
    assert (task.getName().equals(TASK_NAME));
    assert (task.getTaskChildren() != null);
    System.out.println("Children size: " + task.getTaskChildren().size());
    assert (task.getTaskChildren().size() == 1);
    for (Task child : task.getTaskChildren()) {
        System.out.println("Task name: " + child.getName());
    }

    Object jsonObject = aggregateService.read(task, settings);
    JsonObject jsonTask = (JsonObject) jsonObject;
    System.out.println("JSON string for object: " + jsonTask.toString());
    assert (((JsonString) jsonTask.get("name")).getString().equals(TASK_NAME));
    JsonArray jsonChildren = jsonTask.getJsonArray("taskChildren");
    assert (((JsonArray) jsonChildren).size() == 1);
}

From source file:at.porscheinformatik.sonarqube.licensecheck.webservice.mavenlicense.MavenLicenseDeleteAction.java

@Override
public void handle(Request request, Response response) throws Exception {
    JsonReader jsonReader = Json.createReader(new StringReader(request.param(MavenLicenseConfiguration.PARAM)));
    JsonObject jsonObject = jsonReader.readObject();
    jsonReader.close();/*from  w  w w .  ja v  a2s .c  o m*/

    if (StringUtils.isNotBlank(jsonObject.getString(MavenLicenseConfiguration.PROPERTY_REGEX))) {
        mavenLicenseSettingsService
                .deleteMavenLicense(jsonObject.getString(MavenLicenseConfiguration.PROPERTY_REGEX));
        LOGGER.info(MavenLicenseConfiguration.INFO_DELETE_SUCCESS + jsonObject.toString());
        mavenLicenseSettingsService.sortMavenLicenses();
        response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_OK);
    } else {
        LOGGER.error(MavenLicenseConfiguration.ERROR_DELETE_INVALID_INPUT + jsonObject.toString());
        response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_NOT_MODIFIED);
    }
}

From source file:at.porscheinformatik.sonarqube.licensecheck.webservice.mavendependency.MavenDependencyDeleteAction.java

@Override
public void handle(Request request, Response response) throws Exception {
    JsonReader jsonReader = Json/*from  ww  w .ja  v  a 2 s  .c  o  m*/
            .createReader(new StringReader(request.param(MavenDependencyConfiguration.PARAM)));
    JsonObject jsonObject = jsonReader.readObject();
    jsonReader.close();

    if (StringUtils.isNotBlank(jsonObject.getString(MavenDependencyConfiguration.PROPERTY_KEY))) {
        mavenDependencySettingsService
                .deleteMavenDependency(jsonObject.getString(MavenDependencyConfiguration.PROPERTY_KEY));
        LOGGER.info(MavenDependencyConfiguration.INFO_DELETE_SUCCESS + jsonObject.toString());
        response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_OK);
    } else {
        LOGGER.error(MavenDependencyConfiguration.ERROR_DELETE_INVALID_INPUT + jsonObject.toString());
        response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_NOT_MODIFIED);
    }
}

From source file:org.fuin.esc.test.DataTest.java

@Test
public void testValueOfJson() throws MimeTypeParseException {

    // PREPARE/*  w ww .  j  a v a 2s  .c  om*/
    final JsonObject event = Json.createObjectBuilder().add("name", "Shining").add("author", "Stephen King")
            .build();

    // TEST
    final Data data = Data.valueOf("BookAddedEvent", event);

    System.out.println(event.toString());

    // VERIFY
    assertThat(data.getType()).isEqualTo("BookAddedEvent");
    assertThat(data.getMimeType()).isEqualTo(new EnhancedMimeType("application/json; encoding=utf-8"));
    assertThat(data.getContent()).isEqualTo("{\"name\":\"Shining\",\"author\":\"Stephen King\"}");
    assertThat(data.isXml()).isFalse();
    assertThat(data.isJson()).isTrue();

}

From source file:mypackage.products.java

private String getResults(String query, String... params) {
    JSONArray jArray = new JSONArray();
    StringBuilder sb = new StringBuilder();
    Boolean isSingle = false;//www.  j  a v a  2  s .c om
    try (Connection cn = Credentials.getConnection()) {
        PreparedStatement pstmt = cn.prepareStatement(query);
        for (int i = 1; i <= params.length; i++) {
            pstmt.setString(i, params[i - 1]);
            isSingle = true;
        }
        ResultSet rs = pstmt.executeQuery();
        if (isSingle == false) {
            while (rs.next()) {
                JSONObject json = new JSONObject();
                json.put("productId", rs.getInt("productId"));
                json.put("name", rs.getString("name"));
                json.put("description", rs.getString("description"));
                json.put("quantity", rs.getInt("quantity"));
                jArray.add(json);
            }
        } else {
            while (rs.next()) {
                JsonObject jsonObj = Json.createObjectBuilder().add("productId", rs.getInt("productId"))
                        .add("name", rs.getString("name")).add("description", rs.getString("description"))
                        .add("quantity", rs.getInt("quantity")).build();
                return jsonObj.toString();
            }
        }
    } catch (SQLException ex) {
        Logger.getLogger(products.class.getName()).log(Level.SEVERE, null, ex);
    }
    return jArray.toJSONString();
}

From source file:org.gameontext.mediator.PlayerClient.java

/**
 * Update the player's location. The new location will always be returned
 * from the service, in the face of a conflict between updates for the
 * player across devices, we'll get back the one that won.
 *
 * @param playerId/*from  w w  w. ja  v a2 s .  c om*/
 *            The player id
 * @param jwt
 *            The server jwt for this player id.
 * @param oldRoomId
 *            The old room's id
 * @param newRoomId
 *            The new room's id
 * @return The id of the selected new room, taking contention into account.
 * @throws IOException
 * @throws JsonProcessingException
 */
public String updatePlayerLocation(String playerId, String jwt, String oldRoomId, String newRoomId) {
    WebTarget target = this.root.path("{playerId}/location").resolveTemplate("playerId", playerId)
            .queryParam("jwt", jwt);

    JsonObject parameter = Json.createObjectBuilder().add("oldLocation", oldRoomId)
            .add("newLocation", newRoomId).build();

    Log.log(Level.INFO, this, "updating location using {0} with putdata {1}", target.getUri().toString(),
            parameter.toString());

    try {
        // Make PUT request using the specified target, get result as a
        // string containing JSON
        String resultString = target.request(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)
                .header("Content-type", "application/json").put(Entity.json(parameter), String.class);

        Log.log(Level.INFO, this, "response was {0}", resultString);

        JsonReader r = Json.createReader(new StringReader(resultString));
        JsonObject result = r.readObject();
        String location = result.getString("location");

        Log.log(Level.INFO, this, "response location {0}", location);
        //location should match the 'newRoomId' unless we didn't win the race to change the location.
        return location;
    } catch (ResponseProcessingException rpe) {
        Response response = rpe.getResponse();
        Log.log(Level.WARNING, this, "Exception changing player location,  uri: {0} resp code: {1}",
                target.getUri().toString(),
                response.getStatusInfo().getStatusCode() + " " + response.getStatusInfo().getReasonPhrase());
        Log.log(Level.WARNING, this, "Exception changing player location", rpe);
    } catch (ProcessingException | WebApplicationException ex) {
        Log.log(Level.WARNING, this, "Exception changing player location (" + target.getUri().toString() + ")",
                ex);
    }

    // Sadly, badness happened while trying to set the new room location
    // return to old room
    return oldRoomId;
}

From source file:prod.products.java

private String getResults(String query, String... params) {
    Boolean Result = false;
    JsonArrayBuilder pList = Json.createArrayBuilder();
    StringBuilder sb = new StringBuilder();
    try (Connection cn = credentials.getConnection()) {
        PreparedStatement pstmt = cn.prepareStatement(query);
        for (int i = 1; i <= params.length; i++) {
            pstmt.setString(i, params[i - 1]);
            Result = true;//from   w  w  w .j  a  va  2s  . co m
        }
        ResultSet rs = pstmt.executeQuery();

        if (Result == false) {
            while (rs.next()) {
                JsonObjectBuilder productBuilder = Json.createObjectBuilder();
                productBuilder.add("productId", rs.getInt("product_id"))
                        .add("name", rs.getString("product_name"))
                        .add("description", rs.getString("product_description"))
                        .add("quantity", rs.getInt("quantity"));
                pList.add(productBuilder);
            }
        } else {
            while (rs.next()) {
                JsonObject jsonObt = Json.createObjectBuilder().add("productId", rs.getInt("product_id"))
                        .add("name", rs.getString("product_name"))
                        .add("description", rs.getString("product_description"))
                        .add("quantity", rs.getInt("quantity")).build();
                return jsonObt.toString();
            }
        }

    } catch (SQLException ex) {
        Logger.getLogger(products.class.getName()).log(Level.SEVERE, null, ex);
    }
    return pList.build().toString();
}

From source file:org.bsc.confluence.rest.AbstractRESTConfluenceService.java

/**
 *
 * @param inputData//from  ww w  .j a  v a  2s .c o  m
 * @return
 */
public final Optional<JsonObject> createPage(final JsonObject inputData) {
    final MediaType storageFormat = MediaType.parse("application/json");

    final RequestBody inputBody = RequestBody.create(storageFormat, inputData.toString());

    final HttpUrl url = urlBuilder().addPathSegment("content").build();

    return fromUrlPOST(url, inputBody, "create page").map(this::mapToObject).findFirst();
}