Example usage for javax.json JsonObject getString

List of usage examples for javax.json JsonObject getString

Introduction

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

Prototype

String getString(String name);

Source Link

Document

A convenience method for getJsonString(name).getString()

Usage

From source file:fr.ortolang.diffusion.runtime.engine.task.ImportReferentialEntityTask.java

private String extractField(String jsonContent, String fieldName) {
    String fieldValue = null;/*from   w  w w .j  av  a 2 s  . c  o m*/
    StringReader reader = new StringReader(jsonContent);
    JsonReader jsonReader = Json.createReader(reader);
    try {
        JsonObject jsonObj = jsonReader.readObject();
        fieldValue = jsonObj.getString(fieldName);
    } catch (IllegalStateException | NullPointerException | ClassCastException | JsonException e) {
        LOGGER.log(Level.WARNING, "No property '" + fieldName + "' in json object", e);
    } finally {
        jsonReader.close();
        reader.close();
    }

    return fieldValue;
}

From source file:org.opendaylight.eman.impl.EmanSNMPBinding.java

public String getEoAttrSNMP(String deviceIP, String attribute) {
    LOG.info("EmanSNMPBinding.getEoAttrSNMP: ");

    /* To do: generalize targetURL
        research using Java binding to make reference to 'local' ODL API
     *///from  w w  w .  j ava2  s  .co m
    String targetUrl = "http://localhost:8181/restconf/operations/snmp:snmp-get";
    String bodyString = buildSNMPGetBody(deviceIP, attribute);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    String result = null;

    try {
        /* invoke ODL SNMP API */
        HttpPost httpPost = new HttpPost(targetUrl);
        httpPost.addHeader("Authorization", "Basic " + encodedAuthStr);

        StringEntity inputBody = new StringEntity(bodyString);
        inputBody.setContentType(CONTENTTYPE_JSON);
        httpPost.setEntity(inputBody);

        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity responseEntity = httpResponse.getEntity();
        LOG.info("EmanSNMPBinding.getEoAttrSNMP: Response Status: " + httpResponse.getStatusLine().toString());
        InputStream in = responseEntity.getContent();

        /* Parse response from ODL SNMP API */
        JsonReader rdr = Json.createReader(in);
        JsonObject obj = rdr.readObject();
        JsonObject output = obj.getJsonObject("output");
        JsonArray results = output.getJsonArray("results");
        JsonObject pwr = results.getJsonObject(0);
        String oid = pwr.getString("oid");
        result = pwr.getString("value");
        rdr.close();

        LOG.info("EmanSNMPBinding.getEoAttrSNMP: oid: " + oid + " value " + result);
    } catch (Exception ex) {
        LOG.info("Error: " + ex.getMessage(), ex);
    } finally {
        try {
            httpClient.close();
        } catch (IOException ex) {
            LOG.info("Error: " + ex.getMessage(), ex);
        }
    }
    return (result);
}

From source file:jp.co.yahoo.yconnect.core.oauth2.RefreshTokenClient.java

public void fetch() throws TokenException, Exception {

    HttpParameters parameters = new HttpParameters();
    parameters.put("grant_type", OAuth2GrantType.REFRESH_TOKEN);
    parameters.put("refresh_token", refreshToken);

    String credential = clientId + ":" + clientSecret;
    String basic = new String(Base64.encodeBase64(credential.getBytes()));

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    requestHeaders.put("Authorization", "Basic " + basic);

    client = new YHttpClient();
    client.requestPost(endpointUrl, parameters, requestHeaders);

    YConnectLogger.debug(TAG, client.getResponseHeaders().toString());
    YConnectLogger.debug(TAG, client.getResponseBody().toString());

    String json = client.getResponseBody();
    JsonReader jsonReader = Json.createReader(new StringReader(json));
    JsonObject jsonObject = jsonReader.readObject();
    jsonReader.close();/*from   www .j  av  a 2  s.  c  o  m*/

    int statusCode = client.getStatusCode();

    checkErrorResponse(statusCode, jsonObject);

    String accessTokenString = (String) jsonObject.getString("access_token");
    long expiresIn = Long.parseLong((String) jsonObject.getString("expires_in"));
    accessToken = new BearerToken(accessTokenString, expiresIn, refreshToken);

}

From source file:jp.co.yahoo.yconnect.core.oauth2.TokenClient.java

@Override
public void fetch() throws TokenException, Exception {

    HttpParameters parameters = new HttpParameters();
    parameters.put("grant_type", OAuth2GrantType.AUTHORIZATION_CODE);
    parameters.put("code", authorizationCode);
    parameters.put("redirect_uri", redirectUri);

    String credential = clientId + ":" + clientSecret;
    String basic = new String(Base64.encodeBase64(credential.getBytes()));

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    requestHeaders.put("Authorization", "Basic " + basic);

    client = new YHttpClient();
    client.requestPost(endpointUrl, parameters, requestHeaders);

    YConnectLogger.debug(TAG, client.getResponseHeaders().toString());
    YConnectLogger.debug(TAG, client.getResponseBody().toString());

    String json = client.getResponseBody();
    JsonReader jsonReader = Json.createReader(new StringReader(json));

    JsonObject jsonObject = jsonReader.readObject();
    jsonReader.close();/*from  ww  w.  j  a va  2  s .c o m*/

    int statusCode = client.getStatusCode();

    checkErrorResponse(statusCode, jsonObject);

    String accessTokenString = (String) jsonObject.getString("access_token");
    long expiresIn = Long.parseLong((String) jsonObject.getString("expires_in"));
    String refreshToken = (String) jsonObject.getString("refresh_token");
    accessToken = new BearerToken(accessTokenString, expiresIn, refreshToken);
    idToken = (String) jsonObject.getString("id_token");

}

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

protected List<JsonObject> rxDescendantPages(final String id) {

    final HttpUrl url = urlBuilder().addPathSegment("content").addPathSegment(id)
            //.addPathSegments("descendant/page")
            .addPathSegments("child/page").addQueryParameter("expand", EXPAND).build();

    return fromUrlGET(url, "get descendant pages").flatMap(this::mapToStream).flatMap((JsonObject o) -> {
        final String childId = o.getString("id");
        return Stream.concat(Stream.of(o), rxDescendantPages(childId).stream());
    }).collect(Collectors.toList());

}

From source file:org.openlmis.converter.IdTypeConverter.java

@Override
public void convert(JsonObjectBuilder builder, Mapping mapping, String value) {
    BaseCommunicationService service = services.getService(mapping.getEntityName());
    String by = getBy(mapping.getType());

    JsonObject jsonRepresentation = service.findBy(by, value);

    if (null == jsonRepresentation) {
        logger.warn("The CSV file contained reference to entity {} "
                + "with {} {} but such reference does not exist.", mapping.getEntityName(), by, value);
    } else {/*  w w  w.j a  v  a  2s . c om*/
        builder.add(mapping.getTo(), jsonRepresentation.getString(ID));
    }
}

From source file:de.pangaea.fixo3.CreateEsonetYellowPages.java

private void run() throws OWLOntologyCreationException, OWLOntologyStorageException, FileNotFoundException {
    m = new OntologyManager(ns);
    m.addTitle("ESONET Yellow Pages Ontology");
    m.addVersion("1.0");
    m.addDate("2016-11-23");
    m.addCreator("Markus Stocker");
    m.addSeeAlso("http://www.esonetyellowpages.com/");
    m.addImport(SSN.ns);/*from  w w  w  . j  av a  2s . c o m*/

    m.addSubClass(Frequency, MeasurementProperty);
    m.addLabel(Frequency, "Frequency");
    m.addSubClass(ProfilingRange, MeasurementProperty);
    m.addLabel(ProfilingRange, "Profiling Range");
    m.addSubClass(CellSize, MeasurementProperty);
    m.addLabel(CellSize, "Cell Size");
    m.addSubClass(OperatingDepth, MeasurementProperty);
    m.addLabel(OperatingDepth, "Operating Depth");
    m.addSubClass(TemperatureRange, MeasurementProperty);
    m.addLabel(TemperatureRange, "Temperature Range");
    m.addSubClass(MeasuringRange, MeasurementProperty);
    m.addLabel(MeasuringRange, "Measuring Range");

    m.addClass(WaterCurrent);
    m.addLabel(WaterCurrent, "Water Current");
    m.addSubClass(WaterCurrent, FeatureOfInterest);

    m.addClass(CarbonDioxide);
    m.addLabel(CarbonDioxide, "Carbon Dioxide");
    m.addSubClass(CarbonDioxide, FeatureOfInterest);

    m.addClass(Speed);
    m.addLabel(Speed, "Speed");
    m.addSubClass(Speed, Property);
    m.addObjectSome(Speed, isPropertyOf, WaterCurrent);

    m.addClass(PartialPressure);
    m.addLabel(PartialPressure, "Partial Pressure");
    m.addSubClass(PartialPressure, Property);
    m.addObjectSome(PartialPressure, isPropertyOf, CarbonDioxide);

    m.addClass(DopplerEffect);
    m.addSubClass(DopplerEffect, Stimulus);
    m.addLabel(DopplerEffect, "Doppler Effect");
    m.addComment(DopplerEffect,
            "The Doppler effect (or the Doppler shift) is the change in frequency of a wave (or other periodic event) for an observer moving relative to its source.");
    m.addSource(DopplerEffect, IRI.create("https://en.wikipedia.org/wiki/Doppler_effect"));
    m.addObjectAll(DopplerEffect, isProxyFor, Speed);

    m.addClass(Infrared);
    m.addSubClass(Infrared, Stimulus);
    m.addLabel(Infrared, "Infrared");
    m.addComment(Infrared, "Infrared (IR) is an invisible radiant energy.");
    m.addSource(Infrared, IRI.create("https://en.wikipedia.org/wiki/Infrared"));
    m.addObjectAll(Infrared, isProxyFor, PartialPressure);

    m.addClass(AcousticDopplerCurrentProfiler);
    m.addLabel(AcousticDopplerCurrentProfiler, "Acoustic Doppler Current Profiler");
    m.addSource(AcousticDopplerCurrentProfiler,
            IRI.create("https://en.wikipedia.org/wiki/Acoustic_Doppler_current_profiler"));
    m.addComment(AcousticDopplerCurrentProfiler,
            "An acoustic Doppler current profiler (ADCP) is a hydroacoustic current meter similar to a sonar, attempting to measure water current velocities over a depth range using the Doppler effect of sound waves scattered back from particles within the water column.");
    m.addObjectAll(AcousticDopplerCurrentProfiler, detects, DopplerEffect);
    m.addObjectAll(AcousticDopplerCurrentProfiler, observes, Speed);
    m.addSubClass(AcousticDopplerCurrentProfiler, HydroacousticCurrentMeter);

    m.addClass(PartialPressureOfCO2Analyzer);
    m.addLabel(PartialPressureOfCO2Analyzer, "Partial Pressure of CO2 Analyzer");
    m.addObjectAll(PartialPressureOfCO2Analyzer, detects, Infrared);
    m.addObjectAll(PartialPressureOfCO2Analyzer, observes, PartialPressure);
    m.addSubClass(PartialPressureOfCO2Analyzer, SensingDevice);

    m.addClass(HydroacousticCurrentMeter);
    m.addLabel(HydroacousticCurrentMeter, "Hydroacoustic Current Meter");
    m.addSubClass(HydroacousticCurrentMeter, SensingDevice);

    JsonReader jr = Json.createReader(new FileReader(new File(eypDevicesFile)));
    JsonArray ja = jr.readArray();

    for (JsonObject jo : ja.getValuesAs(JsonObject.class)) {
        String name = jo.getString("name");
        String label = jo.getString("label");
        String comment = jo.getString("comment");
        String seeAlso = jo.getString("seeAlso");
        JsonArray equivalentClasses = jo.getJsonArray("equivalentClasses");
        JsonArray subClasses = jo.getJsonArray("subClasses");

        addDeviceType(name, label, comment, seeAlso, equivalentClasses, subClasses);
    }

    m.save(eypFile);
    m.saveInferred(eypInferredFile);
}

From source file:com.rhcloud.javaee.movieinfo.business.actor.boundry.ActorResourceIT.java

@Test
public void actor_integration_CRUD() {
    // Get Actor/*w ww. j  ava  2s . c o  m*/
    Response getResponse = null;
    try {
        getResponse = provider.target().path(FORWARD_SLASH + ACTORS_PATH + FORWARD_SLASH + 1)
                .request(APPLICATION_JSON).get();
    } finally {
        System.out.println("Server responded ? " + (getResponse != null));
        assumeThat(getResponse, is(notNullValue()));
    }

    final String fn = "John";
    final String ln = "Doe";

    // Post Actor
    Response postResponse = provider.target().path(FORWARD_SLASH + ACTORS_PATH).request(APPLICATION_JSON)
            .post(Entity.json(createActor(fn, ln)));
    assertThat(postResponse, is(successful()));

    String location = postResponse.getHeaderString("Location");
    assertThat(location, is(notNullValue()));
    System.out.println("ActorResourceIT.actor_integration_CRUD() Post Actor Response Location : " + location);

    try {

        // Get Actor
        Response actorResponse = provider.target(location).request(APPLICATION_JSON).get();
        assertThat(actorResponse, is(successful()));

        JsonObject actor = actorResponse.readEntity(JsonObject.class);
        assertThat(actor.getString(FIRSTNAME), is(equalTo(fn)));
        assertThat(actor.getString(LASTNAME), is(equalTo(ln)));
        System.out.println("ActorResourceIT.actor_integration_CRUD() Get Actor : " + actor);

        // Update Actor
        final String newFn = "Jane";
        JsonObject actorUpdate = Json.createObjectBuilder().add(FIRSTNAME, newFn).add(LASTNAME, ln).build();
        Response putResponse = provider.target(location).request(APPLICATION_JSON)
                .put(Entity.json(actorUpdate));
        assertThat(putResponse, is(successful()));

        JsonObject updatedActor = putResponse.readEntity(JsonObject.class);
        assertThat(updatedActor.getString(FIRSTNAME), is(equalTo(newFn)));
        assertThat(updatedActor.getString(LASTNAME), is(equalTo(ln)));
        System.out.println("ActorResourceIT.actor_integration_CRUD() Put Actor Response : " + updatedActor);

    } finally {
        // Delete Actor
        Response deleteActor = provider.target(location).request(APPLICATION_JSON).delete();
        assertThat(deleteActor, is(successful()));
        System.out.println("ActorResourceIT.actor_integration_CRUD() Delete Actor Response : " + deleteActor);
    }

}

From source file:sample.products.java

@PUT
@Path("{id}")
@Consumes("application/json")
public void putData(String str, @PathParam("id") int id1) {
    JsonObject json = Json.createReader(new StringReader(str)).readObject();
    String id = String.valueOf(id1);
    String name = json.getString("name");
    String description = json.getString("description");
    String qty = String.valueOf(json.getInt("qty"));
    doUpdate("UPDATE PRODUCT SET productId= ?, name = ?, description = ?, quantity = ? WHERE productId = ?", id,
            name, description, qty, id);
}

From source file:com.rhcloud.javaee.movieinfo.business.actor.boundry.ActorResourceIT.java

@Test
public void actor_integration_OptimisticLockingCheck() {
    // Get Actor/*w w w.  j  a  v a  2  s.  c  o  m*/
    Response getResponse = null;
    try {
        getResponse = provider.target().path(FORWARD_SLASH + ACTORS_PATH + FORWARD_SLASH + 1)
                .request(APPLICATION_JSON).get();
    } finally {
        System.out.println("Server responded ? " + (getResponse != null));
        assumeThat(getResponse, is(notNullValue()));
    }

    final String fn = "John";
    final String ln = "Doe";

    // Post Actor
    Response postResponse = provider.target().path(FORWARD_SLASH + ACTORS_PATH).request(APPLICATION_JSON)
            .post(Entity.json(createActor(fn, ln)));
    assertThat(postResponse, is(successful()));

    String location = postResponse.getHeaderString("Location");
    assertThat(location, is(notNullValue()));
    System.out.println(
            "ActorResourceIT.actor_integration_OptimisticLockingCheck() Post Actor Response Location : "
                    + location);

    try {
        // Get Actor
        Response actorResponse = provider.target(location).request(APPLICATION_JSON).get();
        assertThat(actorResponse, is(successful()));

        JsonObject actor = actorResponse.readEntity(JsonObject.class);
        assertThat(actor.getString(FIRSTNAME), is(equalTo(fn)));
        assertThat(actor.getString(LASTNAME), is(equalTo(ln)));
        assertThat(actor.keySet(), hasItem(VERSION));

        long version = actor.getJsonNumber(VERSION).longValue();
        System.out.println("ActorResourceIT.actor_integration_OptimisticLockingCheck() Get Actor : " + actor);

        // Update Actor Once
        final String newFn = "Jane";
        JsonObject actorUpdate = Json.createObjectBuilder().add(FIRSTNAME, newFn).add(LASTNAME, ln)
                .add(VERSION, version).build();
        Response putResponse = provider.target(location).request(APPLICATION_JSON)
                .put(Entity.json(actorUpdate));
        assertThat(putResponse, is(successful()));

        JsonObject updatedActor = putResponse.readEntity(JsonObject.class);
        assertThat(updatedActor.getString(FIRSTNAME), is(equalTo(newFn)));
        assertThat(updatedActor.getString(LASTNAME), is(equalTo(ln)));
        System.out.println(
                "ActorResourceIT.actor_integration_OptimisticLockingCheck() update Actor once Response : "
                        + updatedActor);

        // Update Actor Second time
        final String newFn2 = "Jamie";
        actorUpdate = Json.createObjectBuilder().add(FIRSTNAME, newFn2).add(LASTNAME, ln).add(VERSION, version)
                .build();
        putResponse = provider.target(location).request(APPLICATION_JSON).put(Entity.json(actorUpdate));
        assertThat(putResponse.getStatus(), is(409));
        System.out.println(
                "ActorResourceIT.actor_integration_OptimisticLockingCheck() update Actor second time Response : "
                        + putResponse);
        final MultivaluedMap<String, Object> putResponseHeaders = putResponse.getHeaders();
        putResponseHeaders.forEach((key, value) -> {
            System.out.println(
                    "actor_integration_OptimisticLockingCheck() : key : " + key + ", value : " + value);
        });

        assertThat((String) putResponseHeaders.getFirst("Cause"),
                containsString("There was a conflict. Details are :"));
        assertThat((String) putResponseHeaders.getFirst("additional-info"),
                containsString("Row was updated or deleted by another transaction"));

    } finally {
        // Delete Actor
        Response deleteActor = provider.target(location).request(APPLICATION_JSON).delete();
        assertThat(deleteActor, is(successful()));
        System.out.println("ActorResourceIT.actor_integration_OptimisticLockingCheck() Delete Actor Response : "
                + deleteActor);

    }
}