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:dk.dma.msinm.user.security.oauth.GoogleOAuthProvider.java

/**
 * {@inheritDoc}//from   w ww . j  av a2 s  .  c  om
 */
@Override
public User authenticateUser(HttpServletRequest request) throws Exception {

    OAuthService service = getOAuthService(settings, app.getBaseUri());
    if (service == null) {
        log.warn("OAuth service not available for " + getOAuthProviderId());
        throw new Exception("OAuth service not available for " + getOAuthProviderId());
    }

    String oauthVerifier = request.getParameter("code");
    Verifier verifier = new Verifier(oauthVerifier);

    Token accessToken = service.getAccessToken(OAuthConstants.EMPTY_TOKEN, verifier);
    log.info("Access Granted to Google with token " + accessToken);

    // check
    // https://github.com/haklop/myqapp/blob/b005df2e100f8aff7c1529097b651b1fd7ce6a4c/src/main/java/com/infoq/myqapp/controller/GoogleController.java
    String idToken = GoogleApiProvider.getIdToken(accessToken.getRawResponse());
    String userIdToken = idToken.split("\\.")[1];
    log.info("Received ID token " + userIdToken);

    String profile = new String(Base64.getDecoder().decode(userIdToken));
    log.info("Decoded " + profile);

    try (JsonReader jsonReader = Json.createReader(new StringReader(profile))) {
        JsonObject json = jsonReader.readObject();

        String email = json.containsKey("email") ? json.getString("email") : null;
        String firstName = json.containsKey("given_name") ? json.getString("given_name") : null;
        String lastName = json.containsKey("family_name") ? json.getString("family_name") : null;
        if (StringUtils.isBlank(email)) {
            throw new Exception("No email found in OAuth token");
        }
        log.info("Email  " + email);

        User user = userService.findByEmail(email);
        if (user == null) {
            user = new User();
            user.setEmail(email);
            user.setLanguage("en");
            user.setFirstName(firstName);
            user.setLastName(StringUtils.isBlank(lastName) ? email : lastName);
            user = userService.registerOAuthOnlyUser(user);
        }
        return user;
    }
}

From source file:service.NewServlet.java

@PUT
@Path("{productId}")
public Response doPut(@PathParam("productId") String id, JsonObject obj) {

    // JSONObject obj = (JSONObject) new JSONParser().parse(st);
    //  id =  obj.getString("productId");
    String name = obj.getString("name");
    String quantity = String.valueOf(obj.getInt("quantity"));
    String description = obj.getString("description");

    Connection conn = Connect.getConnection();
    doUpdate("UPDATE product SET name=?,description=?,quantity=? where productId=? ", name, description,
            quantity, id);/*from w w w .  j  av a2s. co m*/

    return Response.ok(obj).build();

}

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

/**
 * Get shared secret for player//from w ww.  j a va 2 s .  com
 * @param playerId
 * @param jwt
 * @param oldRoomId
 * @param newRoomId
 * @return
 */
public String getSharedSecret(String playerId, String jwt) {
    WebTarget target = this.root.path("{playerId}").resolveTemplate("playerId", playerId);

    Log.log(Level.FINER, this, "requesting shared secret using {0}", target.getUri().toString());

    try {
        // Make PUT request using the specified target, get result as a
        // string containing JSON
        Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON);
        builder.header("Content-type", "application/json");
        builder.header("gameon-jwt", jwt);
        String result = builder.get(String.class);

        JsonReader p = Json.createReader(new StringReader(result));
        JsonObject j = p.readObject();
        JsonObject creds = j.getJsonObject("credentials");
        return creds.getString("sharedSecret");
    } catch (ResponseProcessingException rpe) {
        Response response = rpe.getResponse();
        Log.log(Level.FINER, this,
                "Exception obtaining shared secret for player,  uri: {0} resp code: {1} data: {2}",
                target.getUri().toString(),
                response.getStatusInfo().getStatusCode() + " " + response.getStatusInfo().getReasonPhrase(),
                response.readEntity(String.class));

        Log.log(Level.FINEST, this, "Exception obtaining shared secret for player", rpe);
    } catch (ProcessingException | WebApplicationException ex) {
        Log.log(Level.FINEST, this,
                "Exception obtaining shared secret for player (" + target.getUri().toString() + ")", ex);
    }

    // Sadly, badness happened while trying to get the shared secret
    return null;
}

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

@Test
public void testUnmarshalJsonContent() throws MimeTypeParseException {

    // PREPARE//from   ww  w.  j  ava 2  s.c o  m
    final Data data = new Data("BookAddedEvent", new EnhancedMimeType("application/json; encoding=utf-8"),
            "{\"name\":\"Shining\",\"author\":\"Stephen King\"}");

    // TEST
    final JsonObject event = data.unmarshalContent();

    // VERIFY
    assertThat(event.getString("name")).isEqualTo("Shining");
    assertThat(event.getString("author")).isEqualTo("Stephen King");

}

From source file:mypackage.products.java

@POST
@Consumes("application/json")
public Response post(String str) {
    JsonObject json = Json.createReader(new StringReader(str)).readObject();
    String id = String.valueOf(json.getInt("productId"));
    String name = json.getString("name");
    String description = json.getString("description");
    String qty = String.valueOf(json.getInt("quantity"));
    int status = doUpdate("INSERT INTO PRODUCT (productId, name, description, quantity) VALUES (?, ?, ?, ?)",
            id, name, description, qty);
    if (status == 0) {
        return Response.status(500).build();
    } else {/*from   w  w w  .j  a v a 2 s .c  o m*/
        return Response.ok("http://localhost:8080/CPD-4414-Assignment-4/products/" + id, MediaType.TEXT_HTML)
                .build();
    }
}

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//w  ww.j ava2  s  . co m
 *            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:ro.cs.products.landsat.LandsatSearch.java

public List<ProductDescriptor> execute() throws IOException {
    List<ProductDescriptor> results = new ArrayList<>();
    String queryUrl = getQuery();
    Logger.getRootLogger().info(queryUrl);
    try (CloseableHttpResponse response = NetUtils.openConnection(queryUrl, credentials)) {
        switch (response.getStatusLine().getStatusCode()) {
        case 200:
            String body = EntityUtils.toString(response.getEntity());
            final JsonReader jsonReader = Json.createReader(new StringReader(body));
            Logger.getRootLogger().debug("Parsing json response");
            JsonObject responseObj = jsonReader.readObject();
            JsonArray jsonArray = responseObj.getJsonArray("results");
            for (int i = 0; i < jsonArray.size(); i++) {
                LandsatProductDescriptor currentProduct = new LandsatProductDescriptor();
                JsonObject result = jsonArray.getJsonObject(i);
                currentProduct.setName(result.getString("scene_id"));
                currentProduct.setId(result.getString("sceneID"));
                currentProduct.setPath(String.valueOf(result.getInt("path")));
                currentProduct.setRow(String.valueOf(result.getInt("row")));
                currentProduct.setSensingDate(result.getString("acquisitionDate"));
                results.add(currentProduct);
            }/*from   www . ja va2  s.  co  m*/

            break;
        case 401:
            Logger.getRootLogger().info("The supplied credentials are invalid!");
            break;
        default:
            Logger.getRootLogger().info("The request was not successful. Reason: %s",
                    response.getStatusLine().getReasonPhrase());
            break;
        }
    }
    Logger.getRootLogger().info("Query returned %s products", results.size());
    return results;
}

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

private void addFixedOceanObservatory(JsonObject jo) {
    String label;/*w w  w  .  j  a va 2 s  .c  o  m*/

    if (jo.containsKey("label"))
        label = jo.getString("label");
    else
        throw new RuntimeException("Label is expected [jo = " + jo + "]");

    IRI observatory = IRI.create(FIXO3.ns.toString() + md5Hex(label));

    m.addIndividual(observatory);
    m.addType(observatory, FixedPointOceanObservatory);
    m.addLabel(observatory, label);

    if (jo.containsKey("title")) {
        m.addTitle(observatory, jo.getString("title"));
    }
    if (jo.containsKey("comment")) {
        m.addComment(observatory, jo.getString("comment"));
    }
    if (jo.containsKey("source")) {
        m.addSource(observatory, IRI.create(jo.getString("source")));
    }
    if (jo.containsKey("location")) {
        JsonObject j = jo.getJsonObject("location");

        String place, coordinates;

        if (j.containsKey("place"))
            place = j.getString("place");
        else
            throw new RuntimeException("Place is expected [j = " + j + "]");

        if (j.containsKey("coordinates"))
            coordinates = j.getString("coordinates");
        else
            throw new RuntimeException("Coordinates are expected [j = " + j + "]");

        String fl = place + " @ " + coordinates;
        String gl = coordinates;

        IRI feature = IRI.create(FIXO3.ns.toString() + md5Hex(fl));
        IRI geometry = IRI.create(FIXO3.ns.toString() + md5Hex(gl));

        m.addIndividual(feature);
        m.addType(feature, Feature);
        m.addLabel(feature, fl);
        m.addObjectAssertion(observatory, location, feature);

        if (coordinates.startsWith("POINT"))
            m.addType(geometry, Point);
        else
            throw new RuntimeException("Coordinates not recognized, expected POINT [j = " + j + "]");

        m.addIndividual(geometry);
        m.addLabel(geometry, gl);
        m.addObjectAssertion(feature, hasGeometry, geometry);
        m.addDataAssertion(geometry, asWKT, coordinates, wktLiteral);
    }

    if (!jo.containsKey("attachedSystems"))
        return;

    JsonArray attachedSystems = jo.getJsonArray("attachedSystems");

    for (JsonObject j : attachedSystems.getValuesAs(JsonObject.class)) {
        String l, t;

        if (j.containsKey("label"))
            l = j.getString("label");
        else
            throw new RuntimeException("Label expected [j = " + j + "]");

        if (j.containsKey("type"))
            t = j.getString("type");
        else
            throw new RuntimeException("Type excepted [j = " + j + "]");

        IRI system = IRI.create(FIXO3.ns.toString() + md5Hex(l));

        m.addIndividual(system);
        m.addType(system, IRI.create(t));
        m.addLabel(system, l);
        m.addObjectAssertion(observatory, attachedSystem, system);
    }
}

From source file:prod.products.java

@POST
@Consumes("application/json")
public void post(String str) {
    JsonObject json = Json.createReader(new StringReader(str)).readObject();
    int newid = json.getInt("PRODUCT_ID");
    String id = String.valueOf(newid);
    String name = json.getString("PRODUCT_NAME");
    String description = json.getString("PRODUCT_DESCRIPTION");
    int newqty = json.getInt("QUANTITY");
    String qty = String.valueOf(newqty);
    System.out.println(id + name + description + qty);
    doUpdate(/*from   w  ww.  j a va 2 s  .  c  om*/
            "INSERT INTO PRODUCT (PRODUCT_ID, PRODUCT_NAME, PRODUCT_DESCRIPTION, QUANTITY) VALUES (?, ?, ?, ?)",
            id, name, description, qty);
}

From source file:prod.products.java

@PUT
@Consumes("application/json")
public void put(String str) {
    JsonObject json = Json.createReader(new StringReader(str)).readObject();
    int newid = json.getInt("PRODUCT_ID");
    String id = String.valueOf(newid);
    String name = json.getString("PRODUCT_NAME");
    String description = json.getString("PRODUCT_DESCRIPTION");
    int newqty = json.getInt("QUANTITY");
    String qty = String.valueOf(newqty);
    System.out.println(id + name + description + qty);
    doUpdate(/*from  w w w.  ja  v  a 2 s .  co  m*/
            "UPDATE PRODUCT SET PRODUCT_ID= ?, PRODUCT_NAME = ?, PRODUCT_DESCRIPTION = ?, QUANTITY = ? WHERE PRODUCT_ID = ?",
            id, name, description, qty, id);
}