Example usage for com.google.gson JsonParser JsonParser

List of usage examples for com.google.gson JsonParser JsonParser

Introduction

In this page you can find the example usage for com.google.gson JsonParser JsonParser.

Prototype

@Deprecated
public JsonParser() 

Source Link

Usage

From source file:arces.unibo.SEPA.client.api.WebsocketClientEndpoint.java

License:Open Source License

@Override
public void onMessage(String message) {
    logger.debug("Message: " + message);
    if (handler == null) {
        logger.warn("Notification handler is NULL");
        return;// w w  w.  j av a  2  s.co m
    }

    synchronized (handler) {
        JsonObject notify = new JsonParser().parse(message).getAsJsonObject();

        //Error
        if (notify.get("code") != null) {
            ErrorResponse error;
            if (notify.get("body") != null)
                error = new ErrorResponse(notify.get("code").getAsInt(), notify.get("body").getAsString());
            else
                error = new ErrorResponse(notify.get("code").getAsInt(), "");

            handler.onError(error);
            return;
        }

        //Ping
        if (notify.get("ping") != null) {
            handler.ping();

            watchDog.ping();
            return;
        }

        //Subscribe confirmed
        if (notify.get("subscribed") != null) {
            SubscribeResponse response;
            if (notify.get("alias") != null)
                response = new SubscribeResponse(0, notify.get("subscribed").getAsString(),
                        notify.get("alias").getAsString());
            else
                response = new SubscribeResponse(0, notify.get("subscribed").getAsString());

            handler.subscribeConfirmed(response);

            if (!watchDog.isAlive())
                watchDog.start();
            watchDog.subscribed();
            return;
        }

        //Unsubscribe confirmed
        if (notify.get("unsubscribed") != null) {
            handler.unsubscribeConfirmed(new UnsubscribeResponse(0, notify.get("unsubscribed").getAsString()));

            try {
                wsClientSession.close();
            } catch (IOException e) {
                logger.error(e.getMessage());
            }

            watchDog.unsubscribed();
            return;
        }

        //Notification
        if (notify.get("results") != null)
            handler.semanticEvent(new Notification(notify));
    }
}

From source file:arces.unibo.SEPA.commons.protocol.SPARQL11Properties.java

License:Open Source License

protected void loadProperties() throws FileNotFoundException, NoSuchElementException, IOException {
    FileReader in = null;//from   www  .  j  ava  2s.c o m
    try {
        in = new FileReader(propertiesFile);
        if (in != null) {
            doc = new JsonParser().parse(in).getAsJsonObject();
            if (doc.get("parameters") == null) {
                logger.warn("parameters key is missing");
                throw new NoSuchElementException("parameters key is missing");
            }
            parameters = doc.get("parameters").getAsJsonObject();
        }
        if (in != null)
            in.close();
    } catch (IOException e) {
        logger.warn(e.getMessage());

        defaults();

        storeProperties(defaultsFileName);

        logger.warn("USING DEFAULTS. Edit \"" + defaultsFileName + "\" and rename it to \"" + propertiesFile
                + "\"");

        throw new FileNotFoundException("USING DEFAULTS. Edit \"" + defaultsFileName + "\" and rename it to \""
                + propertiesFile + "\"");
    }
}

From source file:arces.unibo.SEPA.commons.protocol.SPARQL11Protocol.java

License:Open Source License

public SPARQL11Protocol(SPARQL11Properties properties) throws IllegalArgumentException {

    if (properties == null) {
        logger.fatal("Properties are null");
        throw new IllegalArgumentException("Properties are null");
    }//from   w ww  .ja v a 2 s .c  o m

    this.properties = properties;

    responseHandler = new ResponseHandler<String>() {
        @Override
        public String handleResponse(final HttpResponse response) {
            /*SPARQL 1.1 Protocol (https://www.w3.org/TR/sparql11-protocol/)
                    
            UPDATE
            2.2 update operation
            The response to an update request indicates success or failure of the request via HTTP response status code.
                    
            QUERY
            2.1.5 Accepted Response Formats
                    
            Protocol clients should use HTTP content negotiation [RFC2616] to request response formats that the client can consume. See below for more on potential response formats.
                    
            2.1.6 Success Responses
                    
            The SPARQL Protocol uses the response status codes defined in HTTP to indicate the success or failure of an operation. Consult the HTTP specification [RFC2616] for detailed definitions of each status code. While a protocol service should use a 2XX HTTP response code for a successful query, it may choose instead to use a 3XX response code as per HTTP.
                    
            The response body of a successful query operation with a 2XX response is either:
                    
            a SPARQL Results Document in XML, JSON, or CSV/TSV format (for SPARQL Query forms SELECT and ASK); or,
            an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT).
            The content type of the response to a successful query operation must be the media type defined for the format of the response body.
                    
            2.1.7 Failure Responses
                    
            The HTTP response codes applicable to an unsuccessful query operation include:
                    
            400 if the SPARQL query supplied in the request is not a legal sequence of characters in the language defined by the SPARQL grammar; or,
            500 if the service fails to execute the query. SPARQL Protocol services may also return a 500 response code if they refuse to execute a query. This response does not indicate whether the server may or may not process a subsequent, identical request or requests.
            The response body of a failed query request is implementation defined. Implementations may use HTTP content negotiation to provide human-readable or machine-processable (or both) information about the failed query request.
                    
            A protocol service may use other 4XX or 5XX HTTP response codes for other failure conditions, as per HTTP.
            */
            JsonObject json = new JsonObject();

            // Status code
            int code = response.getStatusLine().getStatusCode();

            //Body
            String body = null;
            HttpEntity entity = response.getEntity();
            try {
                body = EntityUtils.toString(entity, Charset.forName("UTF-8"));
            } catch (ParseException e) {
                code = 500;
                body = e.getMessage();
            } catch (IOException e) {
                code = 500;
                body = e.getMessage();
            }

            JsonObject jsonBody = null;
            try {
                jsonBody = new JsonParser().parse(body).getAsJsonObject();
            } catch (JsonParseException | IllegalStateException e) {
                json.add("body", new JsonPrimitive(body));
            }

            if (jsonBody != null)
                json.add("body", jsonBody);

            json.add("code", new JsonPrimitive(code));
            return json.toString();
        }
    };
}

From source file:arces.unibo.SEPA.commons.protocol.SPARQL11Protocol.java

License:Open Source License

protected Response parseEndpointResponse(int token, String jsonResponse, SPARQLPrimitive op,
        QueryResultsFormat format) {//from w  w w .j av  a 2s .  c o m
    logger.debug("Parse endpoint response #" + token + " " + jsonResponse);

    JsonObject json = null;
    try {
        json = new JsonParser().parse(jsonResponse).getAsJsonObject();
    } catch (JsonParseException | IllegalStateException e) {
        logger.warn(e.getMessage());

        if (op.equals(SPARQLPrimitive.UPDATE))
            return new UpdateResponse(token, jsonResponse);

        return new ErrorResponse(token, 500, e.getMessage());
    }

    if (json.get("code") != null) {
        if (json.get("code").getAsInt() >= 400)
            return new ErrorResponse(token, json.get("code").getAsInt(), json.get("body").getAsString());
    }

    if (op.equals(SPARQLPrimitive.UPDATE))
        return new UpdateResponse(token, json.get("body").getAsString());
    if (op.equals(SPARQLPrimitive.QUERY))
        return new QueryResponse(token, json.get("body").getAsJsonObject());

    return new ErrorResponse(token, 500, jsonResponse.toString());
}

From source file:arces.unibo.SEPA.server.core.EngineProperties.java

License:Open Source License

private void loadProperties() throws NoSuchElementException, IOException {
    FileReader in = null;//from   ww  w  .  ja v a  2  s  .  c om
    try {
        in = new FileReader(propertiesFile);
        if (in != null) {
            parameters = new JsonParser().parse(in).getAsJsonObject();
            if (parameters.get("parameters") == null) {
                logger.warn("parameters key is missing");
                throw new NoSuchElementException("parameters key is missing");
            }
            parameters = parameters.get("parameters").getAsJsonObject();
        }
        if (in != null)
            in.close();
    } catch (IOException e) {
        logger.warn(e.getMessage());

        defaults();

        storeProperties(defaultsFileName);

        logger.warn("USING DEFAULTS. Edit \"" + defaultsFileName + "\" and rename it to \"" + propertiesFile
                + "\"");
        throw new FileNotFoundException("USING DEFAULTS. Edit \"" + defaultsFileName + "\" and rename it to \""
                + propertiesFile + "\"");

    }
}

From source file:arces.unibo.SEPA.server.protocol.WSGate.java

License:Open Source License

protected Request parseRequest(Integer token, String request) {
    JsonObject req;//from w w w.j  a va 2s  .c o m
    try {
        req = new JsonParser().parse(request).getAsJsonObject();
    } catch (JsonParseException | IllegalStateException e) {
        return null;
    }

    if (req.get("subscribe") != null) {
        if (req.get("alias") != null)
            return new SubscribeRequest(token, req.get("subscribe").getAsString(),
                    req.get("alias").getAsString());
        return new SubscribeRequest(token, req.get("subscribe").getAsString());
    }
    if (req.get("unsubscribe") != null)
        return new UnsubscribeRequest(token, req.get("unsubscribe").getAsString());

    return null;
}

From source file:arces.unibo.SEPA.server.protocol.WSSGate.java

License:Open Source License

private Response validateToken(String request) {
    JsonObject req;//from w  w w  .  j  a v a  2  s.c  o  m
    try {
        req = new JsonParser().parse(request).getAsJsonObject();
    } catch (JsonParseException | IllegalStateException e) {

        return new ErrorResponse(500, e.getMessage());
    }

    if (req.get("authorization") == null)
        return new ErrorResponse(400, "authorization key is missing");
    ;

    //Token validation
    return am.validateToken(req.get("authorization").getAsString());
}

From source file:arces.unibo.SEPA.server.security.AuthorizationManager.java

License:Open Source License

private boolean init(String keyAlias, String keyPwd) {
    // Load the key from the key store
    RSAKey jwk = sManager.getJWK(keyAlias, keyPwd);

    //Get the private and public keys to sign and verify
    RSAPrivateKey privateKey;// ww w .  java 2s.c  om
    RSAPublicKey publicKey;
    try {
        privateKey = jwk.toRSAPrivateKey();
    } catch (JOSEException e) {
        logger.error(e.getMessage());
        return false;
    }
    try {
        publicKey = jwk.toRSAPublicKey();
    } catch (JOSEException e) {
        logger.error(e.getMessage());
        return false;
    }

    // Create RSA-signer with the private key
    signer = new RSASSASigner(privateKey);

    // Create RSA-verifier with the public key
    verifier = new RSASSAVerifier(publicKey);

    //Serialize the public key to be deliverer during registration
    jwkPublicKey = new JsonParser().parse(jwk.toPublicJWK().toJSONString());

    // Set up a JWT processor to parse the tokens and then check their signature
    // and validity time window (bounded by the "iat", "nbf" and "exp" claims)
    jwtProcessor = new DefaultJWTProcessor<SEPASecurityContext>();
    JWKSet jws = new JWKSet(jwk);
    JWKSource<SEPASecurityContext> keySource = new ImmutableJWKSet<SEPASecurityContext>(jws);
    JWSAlgorithm expectedJWSAlg = JWSAlgorithm.RS256;
    JWSKeySelector<SEPASecurityContext> keySelector = new JWSVerificationKeySelector<SEPASecurityContext>(
            expectedJWSAlg, keySource);
    jwtProcessor.setJWSKeySelector(keySelector);

    return true;
}

From source file:asteroidtracker.AsteroidTrackerSpeechlet.java

License:Open Source License

/**
 * Parse JSON-formatted list of events/births/deaths from Wikipedia, extract list of events and
 * split the events into a String array of individual events. Run Regex matchers to make the
 * list pretty by adding a comma after the year to add a pause, and by removing a unicode char.
 * //  w  ww  .jav  a2 s  .com
 * @param text
 *            the JSON formatted list of events/births/deaths for a certain date
 * @return String array of events for that date, 1 event per element of the array
 */
private ArrayList<String> parseJson(String text, String date) {
    ArrayList<String> events = new ArrayList<String>();

    if (text.isEmpty()) {
        return events;
    }
    JsonParser parser = new JsonParser();
    JsonObject object = parser.parse(text).getAsJsonObject();

    JsonArray asteroidArray = object.get("near_earth_objects").getAsJsonObject().get(date).getAsJsonArray();

    for (int i = 0; i < object.get("element_count").getAsInt(); i++) {
        JsonObject thisAsteroid = asteroidArray.get(i).getAsJsonObject();

        String asteroidName = thisAsteroid.get("name").getAsString();

        float absoluteMagnitude = thisAsteroid.get("absolute_magnitude_h").getAsFloat();

        JsonObject estimatedDiameterKilometers = thisAsteroid.get("estimated_diameter").getAsJsonObject()
                .get("kilometers").getAsJsonObject();
        float minimumDiameter = estimatedDiameterKilometers.get("estimated_diameter_min").getAsFloat();
        float maximumDiameter = estimatedDiameterKilometers.get("estimated_diameter_max").getAsFloat();

        boolean isDangerousObject = thisAsteroid.get("is_potentially_hazardous_asteroid")
                .getAsString() == "false";

        JsonObject closeApproachData = thisAsteroid.get("close_approach_data").getAsJsonArray().get(0)
                .getAsJsonObject();
        float speed = closeApproachData.get("relative_velocity").getAsJsonObject().get("kilometers_per_hour")
                .getAsFloat();
        Number missDistance = closeApproachData.get("miss_distance").getAsJsonObject().get("kilometers")
                .getAsNumber();
        String orbitingBody = closeApproachData.get("orbiting_body").getAsString();

        DecimalFormat df = new DecimalFormat("#.##");

        String asteroidIdText = "Asteroid " + i + ", name is " + asteroidName + ",";
        String magnitudeText = "The absolute magnitude is " + absoluteMagnitude;
        String sizeText = ", the estimated diameter is from " + df.format(minimumDiameter) + " to "
                + df.format(maximumDiameter) + " kilometers,";

        String dangerousnessText;
        if (isDangerousObject) {
            dangerousnessText = "This object is dangerous!";
        } else {
            dangerousnessText = "This object is not dangerous,";
        }

        String speedText = "It is traveling at " + df.format(speed) + " kilometers per hour";
        String distanceText = " at a distance of " + missDistance + " kilometers";
        String orbitingBodyText = " and is orbiting " + orbitingBody;

        String eventText = asteroidIdText + magnitudeText + sizeText + dangerousnessText + speedText
                + distanceText + orbitingBodyText;
        events.add(eventText);
    }

    return events;
}

From source file:at.ac.dbisinformatik.snowprofile.web.SingleSnowProfileResource.java

License:Open Source License

/**
 * generates a Snow Profile by type (pdf, png, jpg,...)
 * /*from  ww  w . j av  a 2 s . c  o m*/
 * @param type
 * @return
 */
@SuppressWarnings("resource")
public ByteArrayOutputStream generateSnowProfileDiagramm(String type) {
    ByteArrayOutputStream ret = new ByteArrayOutputStream();
    String jsonRawString = "";
    try {
        boolean pdfFlag = true;
        Context cx = Context.enter();
        Scriptable scope = cx.initStandardObjects();
        Reader script = new InputStreamReader(SingleSnowProfileResource.class
                .getResourceAsStream("/at/ac/dbisinformatik/snowprofile/web/resources/includeFunctions.js"));
        cx.evaluateReader(scope, script, "<cmd>", 1, null);
        Object func = scope.get("getJSON", scope);

        JSONObject jsObject = SchichtprofilDAO.getSingleSnowProfile(db,
                getRequestAttributes().get("id").toString());
        jsonRawString = jsObject.get("SnowProfile").toString();

        Object stringify = ((Scriptable) scope.get("JSON", scope)).get("stringify", scope);
        Object jsonParse = ((Scriptable) scope.get("JSON", scope)).get("parse", scope);
        Object jsonRawObject = ((Function) jsonParse).call(cx, scope, scope, new Object[] { jsonRawString });
        if (func instanceof Function) {
            Object funcArgs[] = new Object[] { jsonRawObject, pdfFlag };
            Object result = ((Function) func).call(cx, scope, scope, funcArgs);
            String jsonString = (String) ((Function) stringify).call(cx, scope, scope, new Object[] { result });
            JsonArray jsonObject = (JsonArray) new JsonParser().parse(jsonString);
            ret = SVGCreator.svgDocument(jsonObject, type, new JSONObject(jsonRawString).get("rid").toString());
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (JavaScriptException jse) {
        jse.printStackTrace();
    } catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TranscoderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        Context.exit();
    }
    return ret;
}