Example usage for javax.json JsonObject containsKey

List of usage examples for javax.json JsonObject containsKey

Introduction

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

Prototype

boolean containsKey(Object key);

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

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

@Override
public void getLocation(Network network, final LocationProviderCallback callback) {
    try {//from   w  w w  .j av  a  2 s  . co  m
        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:se.curity.oauth.JwtWithCertTest.java

@Test
public void testValidContentInToken() throws Exception {
    JwtValidator validator = new JwtValidatorWithCert(ISSUER, AUDIENCE, prepareKeyMap());

    JwtData result = validator.validate(_testToken);

    _logger.info("test token = {}", _testToken);

    assertNotNull(result);/*  w w w .  j a v a2s. c o m*/

    JsonObject jsonObject = result.getJsonObject();

    assertTrue(jsonObject.containsKey("sub"));
    assertTrue(jsonObject.containsKey(EXTRA_CLAIM));

    assertEquals(SUBJECT, ((JsonString) jsonObject.get("sub")).getString());
    assertEquals(EXTRA_CLAIM_VALUE, ((JsonString) jsonObject.get(EXTRA_CLAIM)).getString());
}

From source file:org.owasp.dependencycheck.analyzer.NodePackageAnalyzer.java

/**
 * Adds information to an evidence collection from the node json configuration.
 *
 * @param json information from node.js/*from   w ww  .  j  a  v  a  2s  .c  o m*/
 * @param collection a set of evidence about a dependency
 * @param key the key to obtain the data from the json information
 */
private void addToEvidence(JsonObject json, EvidenceCollection collection, String key) {
    if (json.containsKey(key)) {
        final JsonValue value = json.get(key);
        if (value instanceof JsonString) {
            collection.addEvidence(PACKAGE_JSON, key, ((JsonString) value).getString(), Confidence.HIGHEST);
        } else if (value instanceof JsonObject) {
            final JsonObject jsonObject = (JsonObject) value;
            for (final Map.Entry<String, JsonValue> entry : jsonObject.entrySet()) {
                final String property = entry.getKey();
                final JsonValue subValue = entry.getValue();
                if (subValue instanceof JsonString) {
                    collection.addEvidence(PACKAGE_JSON, String.format("%s.%s", key, property),
                            ((JsonString) subValue).getString(), Confidence.HIGHEST);
                } else {
                    LOGGER.warn("JSON sub-value not string as expected: {}", subValue);
                }
            }
        } else {
            LOGGER.warn("JSON value not string or JSON object as expected: {}", value);
        }
    }
}

From source file:dk.dma.msinm.user.security.oauth.GoogleOAuthProvider.java

/**
 * {@inheritDoc}/*  ww  w  .j a  va  2s .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:de.pangaea.fixo3.CreateFixO3.java

private void addFixedOceanObservatory(JsonObject jo) {
    String label;/*from   ww w .  ja v  a 2  s. c  om*/

    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:joachimeichborn.geotag.geocode.GoogleGeocoder.java

private String getStatus(final JsonObject aJsonRepresentation) {
    if (aJsonRepresentation == null || !aJsonRepresentation.containsKey(STATUS_KEY)) {
        logger.fine("JSON status cannot be obtained");
        return "";
    }//from   ww  w .  j  a  v  a  2  s.c o  m

    return aJsonRepresentation.getString(STATUS_KEY);
}

From source file:org.erstudio.guper.websocket.GuperWSEndpoint.java

@OnMessage
public void onWebSocketMessage(JsonObject json, Session session)
        throws WebSocketMessageException, MessageException, LocationException, IOException, EncodeException {
    System.out.println("onWebSocketMessage " + session.getId());

    if (!json.containsKey("type")) {
        throw new WebSocketMessageException("Type is undefined");
    }//from   ww  w.j  a va2s . c  o  m

    String type = json.getString("type");
    if (StringUtils.isBlank(type)) {
        throw new WebSocketMessageException("Empty message type");
    }

    if (!json.containsKey("message")) {
        throw new WebSocketMessageException("Message is undefined");
    }

    String message = json.get("message").toString();
    if (StringUtils.isBlank(message)) {
        throw new WebSocketMessageException("Empty message");
    }

    switch (type) {
    case "SEND_MESSAGE": {
        try {
            Message m = mapper.readValue(message, Message.class);
            onSendMessage(m, session);
        } catch (IOException ex) {
            throw new WebSocketMessageException("Incorrect Message format: " + message);
        }
    }
        break;

    case "CHANGE_LOCATION": {
        try {
            Location l = mapper.readValue(message, Location.class);
            onChangeLocation(l, session);
        } catch (IOException ex) {
            throw new WebSocketMessageException("Incorrect Location format: " + message);
        }
    }
        break;

    default:
        throw new WebSocketMessageException("Incorrect message type: " + type);
    }

}

From source file:joachimeichborn.geotag.geocode.GoogleGeocoder.java

private String getMatchingContent(final String aAttribute, final JsonArray aResults,
        final LocationType... aLocationTypes) {
    for (final LocationType locationType : aLocationTypes) {
        for (final JsonObject component : aResults.getValuesAs(JsonObject.class)) {
            final JsonArray types = component.getJsonArray(TYPES_KEY);
            if (types.containsAll(locationType.getIdentifiers()) && component.containsKey(aAttribute)) {
                return component.getString(aAttribute);
            }//  w  w  w  .j av a  2s . c o m
        }
    }

    return null;
}

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

private void addDeviceType(String name, String label, String comment, String seeAlso,
        JsonArray equivalentClasses, JsonArray subClasses) {
    IRI deviceTypeIRI = IRI.create(name);

    m.addClass(deviceTypeIRI);//from   www  .  j  a  va2  s.  co m
    m.addLabel(deviceTypeIRI, label);
    m.addComment(deviceTypeIRI, comment);
    m.addSeeAlso(deviceTypeIRI, seeAlso);

    // Default sub class, though implicit with curated sensing device type
    // hierarchy
    //      m.addSubClass(deviceTypeIRI, SSN.SensingDevice);

    for (JsonObject equivalentClass : equivalentClasses.getValuesAs(JsonObject.class)) {
        if (equivalentClass.containsKey("type")) {
            m.addEquivalentClass(deviceTypeIRI, IRI.create(equivalentClass.getString("type")));
        }
    }

    for (JsonObject subClass : subClasses.getValuesAs(JsonObject.class)) {
        if (subClass.containsKey("type")) {
            m.addSubClass(deviceTypeIRI, IRI.create(subClass.getString("type")));
        } else if (subClass.containsKey("observes")) {
            JsonObject observesJson = subClass.getJsonObject("observes");
            String propertyLabel = observesJson.getString("label");
            String propertyType = observesJson.getString("type");
            JsonObject featureJson = observesJson.getJsonObject("isPropertyOf");
            String featureLabel = featureJson.getString("label");
            String featureType = featureJson.getString("type");

            IRI propertyIRI = IRI.create(EYP.ns.toString() + md5Hex(propertyLabel));
            IRI propertyTypeIRI = IRI.create(propertyType);
            IRI featureIRI = IRI.create(EYP.ns.toString() + md5Hex(featureLabel));
            IRI featureTypeIRI = IRI.create(featureType);

            m.addObjectValue(deviceTypeIRI, observes, propertyIRI);
            m.addIndividual(propertyIRI);
            m.addType(propertyIRI, propertyTypeIRI);
            m.addLabel(propertyIRI, propertyLabel);
            m.addIndividual(featureIRI);
            m.addType(featureIRI, featureTypeIRI);
            m.addLabel(featureIRI, featureLabel);
            m.addObjectAssertion(propertyIRI, isPropertyOf, featureIRI);
        } else if (subClass.containsKey("detects")) {
            JsonObject detectsJson = subClass.getJsonObject("detects");
            String stimulusLabel = detectsJson.getString("label");
            String stimulusType = detectsJson.getString("type");

            IRI stimulusIRI = IRI.create(EYP.ns.toString() + md5Hex(stimulusLabel));
            IRI stimulusTypeIRI = IRI.create(stimulusType);

            m.addObjectValue(deviceTypeIRI, detects, stimulusIRI);
            m.addIndividual(stimulusIRI);
            m.addType(stimulusIRI, stimulusTypeIRI);
            m.addLabel(stimulusIRI, stimulusLabel);
        } else if (subClass.containsKey("capability")) {
            JsonObject capabilityJson = subClass.getJsonObject("capability");
            String capabilityLabel = capabilityJson.getString("label");
            JsonObject propertyJson = capabilityJson.getJsonObject("property");
            String propertyLabel = propertyJson.getString("label");
            String propertyType = propertyJson.getString("type");
            JsonObject valueJson = propertyJson.getJsonObject("value");
            String valueLabel = valueJson.getString("label");

            IRI capabilityIRI = IRI.create(EYP.ns.toString() + md5Hex(capabilityLabel));
            IRI propertyIRI = IRI.create(EYP.ns.toString() + md5Hex(propertyLabel));
            IRI propertyTypeIRI = IRI.create(propertyType);
            IRI valueIRI = IRI.create(EYP.ns.toString() + md5Hex(valueLabel));

            m.addObjectValue(deviceTypeIRI, hasMeasurementCapability, capabilityIRI);
            m.addIndividual(capabilityIRI);
            m.addType(capabilityIRI, MeasurementCapability);
            m.addLabel(capabilityIRI, capabilityLabel);
            m.addObjectAssertion(capabilityIRI, hasMeasurementProperty, propertyIRI);
            m.addIndividual(propertyIRI);
            m.addType(propertyIRI, SSN.MeasurementProperty);
            m.addType(propertyIRI, propertyTypeIRI);
            m.addLabel(propertyIRI, propertyLabel);
            m.addObjectAssertion(propertyIRI, hasValue, valueIRI);
            m.addIndividual(valueIRI);
            m.addType(valueIRI, SSN.ObservationValue);
            m.addLabel(valueIRI, valueLabel);

            if (valueJson.containsKey("value")) {
                m.addType(valueIRI, QuantitativeValue);
                m.addDataAssertion(valueIRI, value, Float.valueOf(valueJson.getString("value")));
            } else if (valueJson.containsKey("minValue") && valueJson.containsKey("maxValue")) {
                m.addType(valueIRI, QuantitativeValue);
                m.addDataAssertion(valueIRI, minValue, Float.valueOf(valueJson.getString("minValue")));
                m.addDataAssertion(valueIRI, maxValue, Float.valueOf(valueJson.getString("maxValue")));
            } else {
                throw new RuntimeException("Expected value or min/max value [valueJson = " + valueJson + "]");
            }

            m.addObjectAssertion(valueIRI, unitCode, IRI.create(valueJson.getString("unitCode")));
        }
    }

}

From source file:org.owasp.dependencycheck.analyzer.NodePackageAnalyzer.java

@Override
protected void analyzeFileType(Dependency dependency, Engine engine) throws AnalysisException {
    final File file = dependency.getActualFile();
    JsonReader jsonReader;//from   www .  j  a va 2 s.  com
    try {
        jsonReader = Json.createReader(FileUtils.openInputStream(file));
    } catch (IOException e) {
        throw new AnalysisException("Problem occurred while reading dependency file.", e);
    }
    try {
        final JsonObject json = jsonReader.readObject();
        final EvidenceCollection productEvidence = dependency.getProductEvidence();
        final EvidenceCollection vendorEvidence = dependency.getVendorEvidence();
        if (json.containsKey("name")) {
            final Object value = json.get("name");
            if (value instanceof JsonString) {
                final String valueString = ((JsonString) value).getString();
                productEvidence.addEvidence(PACKAGE_JSON, "name", valueString, Confidence.HIGHEST);
                vendorEvidence.addEvidence(PACKAGE_JSON, "name_project",
                        String.format("%s_project", valueString), Confidence.LOW);
            } else {
                LOGGER.warn("JSON value not string as expected: {}", value);
            }
        }
        addToEvidence(json, productEvidence, "description");
        addToEvidence(json, vendorEvidence, "author");
        addToEvidence(json, dependency.getVersionEvidence(), "version");
        dependency.setDisplayFileName(String.format("%s/%s", file.getParentFile().getName(), file.getName()));
    } catch (JsonException e) {
        LOGGER.warn("Failed to parse package.json file.", e);
    } finally {
        jsonReader.close();
    }
}