Example usage for javax.json Json createReader

List of usage examples for javax.json Json createReader

Introduction

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

Prototype

public static JsonReader createReader(InputStream in) 

Source Link

Document

Creates a JSON reader from a byte stream.

Usage

From source file:co.runrightfast.vertx.core.hazelcast.serializers.CompressedJsonObjectSerializer.java

@Override
public JsonObject read(final byte[] bytes) throws IOException {
    try (final JsonReader reader = Json.createReader(new GZIPInputStream(new ByteArrayInputStream(bytes)))) {
        return reader.readObject();
    }/*from  w  w  w  .j ava  2s .  c o  m*/
}

From source file:org.traccar.geolocation.UniversalGeolocationProvider.java

@Override
public void getLocation(Network network, final LocationProviderCallback callback) {
    try {//from   w  ww  .jav a  2 s . com
        String request = Context.getObjectMapper().writeValueAsString(network);
        Context.getAsyncHttpClient().preparePost(url)
                .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                .setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(request.length())).setBody(request)
                .execute(new AsyncCompletionHandler() {
                    @Override
                    public Object onCompleted(Response response) throws Exception {
                        try (JsonReader reader = Json.createReader(response.getResponseBodyAsStream())) {
                            JsonObject json = reader.readObject();
                            if (json.containsKey("error")) {
                                callback.onFailure(new GeolocationException(
                                        json.getJsonObject("error").getString("message")));
                            } else {
                                JsonObject location = json.getJsonObject("location");
                                callback.onSuccess(location.getJsonNumber("lat").doubleValue(),
                                        location.getJsonNumber("lng").doubleValue(),
                                        json.getJsonNumber("accuracy").doubleValue());
                            }
                        }
                        return null;
                    }

                    @Override
                    public void onThrowable(Throwable t) {
                        callback.onFailure(t);
                    }
                });
    } catch (JsonProcessingException e) {
        callback.onFailure(e);
    }
}

From source file:org.hyperledger.fabric_ca.sdk.MockHFCAClient.java

@Override
JsonObject httpPost(String url, String body, User admin) throws Exception {

    JsonObject response;/*from w ww.  ja va  2s .c om*/

    if (httpPostResponse == null) {
        response = super.httpPost(url, body, admin);
    } else {
        JsonReader reader = Json.createReader(new StringReader(httpPostResponse));
        response = (JsonObject) reader.read();

        // TODO: HFCAClient could do with some minor refactoring to avoid duplicating this code here!!
        JsonObject result = response.getJsonObject("result");
        if (result == null) {
            EnrollmentException e = new EnrollmentException(format(
                    "POST request to %s failed request body %s " + "Body of response did not contain result",
                    url, body), new Exception());
            throw e;
        }
    }
    return response;
}

From source file:com.dhenton9000.json.processing.FasterXMLJSONTests.java

@Test
public void testUsingStandardJSR() {

    StringReader sr = new StringReader(TEST_STRING);
    JsonObject restaurantObject;//from  ww  w.  j  a va  2s  .  com
    try (JsonReader myreader = Json.createReader(sr)) {
        restaurantObject = myreader.readObject();
    }

    LOG.debug("class is " + restaurantObject.getClass().getName());

}

From source file:uk.ac.ebi.ep.data.service.BioPortalService.java

@Transactional
public String getDiseaseDescription(String term) {
    String definition = "";

    // Reader reader = new StringReader(get(REST_URL + "/search?q=" + term+"&ontology={EFO,MeSH,OMIM}&exact_match=true"));
    Reader reader = new StringReader(get(REST_URL + "/search?q=" + term));

    JsonReader jsonReader = Json.createReader(reader);

    JsonObject jo = jsonReader.readObject();

    JsonArray jsonArray = jo.getJsonArray("collection");
    for (JsonObject obj : jsonArray.getValuesAs(JsonObject.class)) {

        for (Map.Entry<String, JsonValue> entry : obj.entrySet()) {

            if (entry.getKey().equalsIgnoreCase(DEFINITION)) {

                definition = entry.getValue().toString().replace("\"", "").replaceAll("\\[", "")
                        .replaceAll("\\]", "");
            }/*w ww  .  j ava  2s  .  c  o  m*/

        }
    }

    return definition;
}

From source file:org.kitodo.data.elasticsearch.index.type.AuthorityTypeTest.java

@Test
public void shouldCreateFirstDocument() throws Exception {
    AuthorityType authorityType = new AuthorityType();

    Authority authority = prepareData().get(0);
    HttpEntity document = authorityType.createDocument(authority);

    JsonObject actual = Json.createReader(new StringReader(EntityUtils.toString(document))).readObject();

    assertEquals("Key title doesn't match to given value!", "First",
            AuthorityTypeField.TITLE.getStringValue(actual));

    JsonArray userGroups = actual.getJsonArray(AuthorityTypeField.USER_GROUPS.getKey());
    assertEquals("Size userGroups doesn't match to given value!", 1, userGroups.size());

    JsonObject userGroup = userGroups.getJsonObject(0);
    assertEquals("Key userGroups.id doesn't match to given value!", 1,
            UserGroupTypeField.ID.getIntValue(userGroup));
    assertEquals("Key userGroups.title doesn't match to given value!", "First",
            UserGroupTypeField.TITLE.getStringValue(userGroup));
}

From source file:uk.ac.ebi.ep.adapter.bioportal.BioPortalService.java

@Override
public Disease getDisease(String term) throws BioportalAdapterException {
    String definition = "";

    // Reader reader = new StringReader(get(REST_URL + "/search?q=" + term+"&ontology={EFO,MeSH,OMIM}&exact_match=true"));
    Reader reader = new StringReader(get(REST_URL + "/search?q=" + term));

    JsonReader jsonReader = Json.createReader(reader);

    JsonObject jo = jsonReader.readObject();

    JsonArray jsonArray = jo.getJsonArray("collection");
    Disease disease = null;//from  w  ww .  j av  a2  s  . c  o m
    for (JsonObject obj : jsonArray.getValuesAs(JsonObject.class)) {
        disease = new Disease();
        disease.setId(term);
        for (Map.Entry<String, JsonValue> entry : obj.entrySet()) {

            if (entry.getKey().equalsIgnoreCase(LABEL)) {
                String name = entry.getValue().toString();
                disease.setName(name);

            }
            if (entry.getKey().equalsIgnoreCase(DEFINITION)) {

                definition = entry.getValue().toString().replace("\"", "").replaceAll("\\[", "")
                        .replaceAll("\\]", "");
                disease.setDescription(definition);
            }

        }
    }

    return disease;
}

From source file:io.bitgrillr.gocddockerexecplugin.utils.GoTestUtils.java

/**
 * Schedules the named pipeline to run.//w  w  w . j  av a2s.  co m
 *
 * @param pipeline Name of the Pipeline to run.
 * @return Counter of the pipeline instance scheduled.
 * @throws GoError If Go.CD returns a non 2XX response.
 * @throws IOException If a communication error occurs.
 * @throws InterruptedException If something has gone horribly wrong.
 */
public static int runPipeline(String pipeline) throws GoError, IOException, InterruptedException {
    final Response scheduleResponse = executor
            .execute(Request.Post(PIPELINES + pipeline + "/schedule").addHeader("Confirm", "true"));
    final int scheduleStatus = scheduleResponse.returnResponse().getStatusLine().getStatusCode();
    if (scheduleStatus != HttpStatus.SC_ACCEPTED) {
        throw new GoError(scheduleStatus);
    }

    Thread.sleep(5 * 1000);

    final HttpResponse historyResponse = executor.execute(Request.Get(PIPELINES + pipeline + "/history"))
            .returnResponse();
    final int historyStatus = historyResponse.getStatusLine().getStatusCode();
    if (historyStatus != HttpStatus.SC_OK) {
        throw new GoError(historyStatus);
    }
    final JsonArray pipelineInstances = Json.createReader(historyResponse.getEntity().getContent()).readObject()
            .getJsonArray("pipelines");
    JsonObject lastPipelineInstance = pipelineInstances.getJsonObject(0);
    for (JsonValue pipelineInstance : pipelineInstances) {
        if (pipelineInstance.asJsonObject().getInt("counter") > lastPipelineInstance.getInt("counter")) {
            lastPipelineInstance = pipelineInstance.asJsonObject();
        }
    }

    return lastPipelineInstance.getInt("counter");
}

From source file:com.dhenton9000.jersey.client.CodeBaseClass.java

/**
 *
 * these two methods use the Java JSR JSON API which is READ-ONLY
 * @param response//  w ww  .j  a v a 2  s  .  c o m
 * @return 
 */
protected JsonObject readInSingleRestaurant(Response response) {
    String jsonStringResponse = response.readEntity(String.class);
    LOG.debug(jsonStringResponse);
    StringReader sr = new StringReader(jsonStringResponse);
    JsonObject restaurantObject;
    try (JsonReader myreader = Json.createReader(sr)) {
        restaurantObject = myreader.readObject();
    }
    return restaurantObject;
}

From source file:mypackage.products.java

@PUT
@Path("{id}")
@Consumes("application/json")
public Response putData(String str, @PathParam("id") int id) {
    JsonObject json = Json.createReader(new StringReader(str)).readObject();
    String id1 = String.valueOf(id);
    String name = json.getString("name");
    String description = json.getString("description");
    String qty = String.valueOf(json.getInt("quantity"));
    int status = doUpdate(
            "UPDATE PRODUCT SET productId= ?, name = ?, description = ?, quantity = ? WHERE productId = ?", id1,
            name, description, qty, id1);
    if (status == 0) {
        return Response.status(500).build();
    } else {/* ww w . j  av  a  2 s .  c  om*/
        return Response.ok("http://localhost:8080/CPD-4414-Assignment-4/products/" + id, MediaType.TEXT_HTML)
                .build();
    }
}