Example usage for com.google.gson JsonObject get

List of usage examples for com.google.gson JsonObject get

Introduction

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

Prototype

public JsonElement get(String memberName) 

Source Link

Document

Returns the member with the specified name.

Usage

From source file:app.abhijit.iter.data.source.TelemetryDataSource.java

License:Open Source License

public void processTelemetry(String response) {
    try {/*ww  w  .  j a  v  a 2 s. c o m*/
        JsonObject telemetry = new JsonParser().parse(response).getAsJsonObject();
        boolean updateAvailable = telemetry.get("update").getAsBoolean();
        boolean displayAds = telemetry.get("ads").getAsBoolean();
        EventBus.getDefault().post(new Telemetry(updateAvailable, displayAds));
    } catch (Exception ignored) {
    }
}

From source file:application.Genius.java

License:Open Source License

public static ArrayList<Lyrics> search(String query) {
    ArrayList<Lyrics> results = new ArrayList<>();
    query = Normalizer.normalize(query, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+",
            "");/*from  w  ww. ja  v a 2 s . c  o  m*/
    JsonObject response = null;
    try {
        URL queryURL = new URL(
                String.format("http://api.genius.com/search?q=%s", URLEncoder.encode(query, "UTF-8")));
        Connection connection = Jsoup.connect(queryURL.toExternalForm())
                .header("Authorization", "Bearer " + Keys.GENIUS).ignoreContentType(true);
        Document document = connection.userAgent(USER_AGENT).get();
        response = new JsonParser().parse(document.text()).getAsJsonObject();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (response == null || response.getAsJsonObject("meta").get("status").getAsInt() != 200)
        return results;
    JsonArray hits = response.getAsJsonObject("response").getAsJsonArray("hits");

    int processed = 0;
    while (processed < hits.size()) {
        JsonObject song = hits.get(processed).getAsJsonObject().getAsJsonObject("result");
        String artist = song.getAsJsonObject("primary_artist").get("name").getAsString();
        String title = song.get("title").getAsString();
        String url = "http://genius.com/songs/" + song.get("id").getAsString();
        Lyrics l = new Lyrics();
        l.mArtist = artist;
        l.mTitle = title;
        l.mSourceUrl = url;
        l.mSource = "Genius";
        results.add(l);
        processed++;
    }
    return results;
}

From source file:application.rest.LibertyRestEndpoint.java

License:Apache License

@POST
@Path("/text")
@Produces("text/plain") // sends JSON
public String hello(@FormParam("phrase") String phrase, @FormParam("language") String targetLang) {

    String decodePhrase = new String(Base64.getDecoder().decode(phrase.getBytes()));
    System.out.println(decodePhrase);

    LanguageDetection ld = new LanguageDetection();
    com.ibm.watson.developer_cloud.alchemy.v1.model.Language sourceLang = ld.detect(decodePhrase);

    TranslateCredentials tc = new TranslateCredentials();
    LanguageTranslator service = new LanguageTranslator();

    service.setEndPoint(tc.getUrl());//  w w  w.  j av  a2  s . co  m
    service.setUsernameAndPassword(tc.getUser(), tc.getPass());

    TranslationResult translationResult = null;

    Language lans = getLanguaje(sourceLang.getLanguage().toLowerCase());
    Language lant = getLanguaje(targetLang.toLowerCase());

    try {
        if (lans != null && lant != null)
            translationResult = service.translate(decodePhrase, lans, lant).execute();
        else
            throw new Exception();
    } catch (Exception e) {
        //return Base64.getEncoder().encode("Error detecting languaje or source/target translation is not implemented".getBytes());
        return "Error detecting languaje or source/target translation is not implemented";
    }
    JsonObject result = new JsonParser().parse(translationResult.toString()).getAsJsonObject();
    System.out.println(result);
    JsonObject translations = result.getAsJsonArray("translations").get(0).getAsJsonObject();
    System.out.println(translations);
    String translation = translations.get("translation").getAsString();
    //return Base64.getEncoder().encode(translation.getBytes());
    return translation;
}

From source file:ar.com.ws.djnextension.config.GsonBuilderConfiguratorForTesting.java

License:Open Source License

/**
 * @param parent/*from   www .j  av  a 2  s  .c om*/
 * @param elementName
 * @return
 */
private static int getIntValue(JsonObject parent, String elementName) {
    assert parent != null;
    assert !StringUtils.isEmpty(elementName);

    JsonElement element = parent.get(elementName);
    if (!element.isJsonPrimitive()) {
        throw new JsonParseException("Element + '" + elementName + "' must be a valid integer");
    }
    JsonPrimitive primitiveElement = (JsonPrimitive) element;
    if (!primitiveElement.isNumber()) {
        throw new JsonParseException("Element + '" + elementName + "' must be a valid integer");
    }
    return primitiveElement.getAsInt();
}

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

License:Open Source License

/**
 * Parse SPARQL 1.1 Query and Update//from   ww w.java 2  s .  c om
 * 
 * Update and error responses are serialized as JSON objects:
 * 
 * {"code": HTTP Return Code, "body": "Message body"}
 */

@Override
protected Response parseEndpointResponse(int token, String jsonResponse, SPARQLPrimitive op,
        QueryResultsFormat format) {
    if (token != -1)
        logger.debug("Parse endpoint response #" + token + " " + jsonResponse);
    else
        logger.debug("Parse endpoint response " + jsonResponse);

    JsonObject json = null;
    try {
        json = new JsonParser().parse(jsonResponse).getAsJsonObject();
    } catch (JsonParseException | IllegalStateException e) {
        //An update response is not forced to be JSON
        if (op.equals(SPARQLPrimitive.UPDATE))
            return new UpdateResponse(token, jsonResponse);

        logger.error(e.getMessage());
        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);

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

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

License:Open Source License

protected Response parseSPARQL11SEResponse(String response, SPARQL11SEPrimitive op) {
    if (response == null)
        return new ErrorResponse(0, 500, "Response is null");

    JsonObject json = null;
    try {/*from w  w w . j ava2  s .c o  m*/
        json = new JsonParser().parse(response).getAsJsonObject();
    } catch (JsonParseException | IllegalStateException e) {
        //if (op == SPARQL11SEPrimitive.SECUREUPDATE) return new UpdateResponse(response);

        return new ErrorResponse(0, 500, "Unknown response: " + response);
    }

    //Error response
    if (json.get("code") != null)
        if (json.get("code").getAsInt() >= 400)
            return new ErrorResponse(0, json.get("code").getAsInt(), json.get("body").getAsString());

    if (op == SPARQL11SEPrimitive.SECUREQUERY)
        return new QueryResponse(json);
    if (op == SPARQL11SEPrimitive.SECUREUPDATE)
        return new UpdateResponse(response);

    if (op == SPARQL11SEPrimitive.REGISTER) {
        if (json.get("client_id") != null && json.get("client_secret") != null) {
            try {
                properties.setCredentials(json.get("client_id").getAsString(),
                        json.get("client_secret").getAsString());
            } catch (IOException e) {
                return new ErrorResponse(ErrorResponse.NOT_FOUND, "Failed to save credentials");
            }

            return new RegistrationResponse(json.get("client_id").getAsString(),
                    json.get("client_secret").getAsString(), json.get("signature"));
        }
        return new ErrorResponse(0, 401, "Credentials not found in registration response");
    }

    if (op == SPARQL11SEPrimitive.REQUESTTOKEN) {
        if (json.get("access_token") != null && json.get("expires_in") != null
                && json.get("token_type") != null) {
            int seconds = json.get("expires_in").getAsInt();
            Date expires = new Date();
            expires.setTime(expires.getTime() + (1000 * seconds));
            try {
                properties.setJWT(json.get("access_token").getAsString(), expires,
                        json.get("token_type").getAsString());
            } catch (IOException e) {
                return new ErrorResponse(ErrorResponse.NOT_FOUND, "Failed to save JWT");
            }
            return new JWTResponse(json.get("access_token").getAsString(), json.get("token_type").getAsString(),
                    json.get("expires_in").getAsLong());
        } else if (json.get("code") != null && json.get("body") != null)
            return new ErrorResponse(0, json.get("code").getAsInt(), json.get("body").getAsString());
        else if (json.get("code") != null)
            return new ErrorResponse(0, json.get("code").getAsInt(), "");

        return new ErrorResponse(0, 500, "Response not recognized: " + json.toString());
    }

    return new ErrorResponse(0, 500, "Response unknown: " + response);
}

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;// ww w  . ja  va 2s .c o  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.client.pattern.ApplicationProfile.java

License:Open Source License

/**
 * "forcedBindings": {//  w  ww.  j  a  v  a 2  s . co m
   "person" : {"type":"uri", "value":""},
   "name" : {"type":"literal", "value":""}}}
           
 * @param selectedValue
 * @return
 */
public Bindings updateBindings(String selectedValue) {
    JsonElement elem;
    Bindings ret = new Bindings();
    if ((elem = doc.get("updates")) != null)
        if ((elem = elem.getAsJsonObject().get(selectedValue)) != null)
            if ((elem = elem.getAsJsonObject().get("forcedBindings")) != null) {
                for (Entry<String, JsonElement> binding : elem.getAsJsonObject().entrySet()) {
                    JsonObject value = binding.getValue().getAsJsonObject();
                    RDFTerm bindingValue = null;

                    if (value.get("type") != null) {
                        if (value.get("type").getAsString().equals("uri")) {
                            bindingValue = new RDFTermURI(value.get("value").getAsString());
                        } else {
                            bindingValue = new RDFTermLiteral(value.get("value").getAsString());
                        }
                    }
                    ret.addBinding(binding.getKey(), bindingValue);
                }
            }
    return ret;
}

From source file:arces.unibo.SEPA.client.pattern.ApplicationProfile.java

License:Open Source License

public Bindings subscribeBindings(String selectedValue) {
    JsonElement elem;/*ww  w.j a  v  a 2 s.  com*/
    Bindings ret = new Bindings();
    if ((elem = doc.get("subscribes")) != null)
        if ((elem = elem.getAsJsonObject().get(selectedValue)) != null)
            if ((elem = elem.getAsJsonObject().get("forcedBindings")) != null) {
                for (Entry<String, JsonElement> binding : elem.getAsJsonObject().entrySet()) {
                    JsonObject value = binding.getValue().getAsJsonObject();
                    RDFTerm bindingValue = null;

                    if (value.get("type") != null) {
                        if (value.get("type").getAsString().equals("uri")) {
                            bindingValue = new RDFTermURI(value.get("value").getAsString());
                        } else {
                            bindingValue = new RDFTermLiteral(value.get("value").getAsString());
                        }
                    }
                    ret.addBinding(binding.getKey(), bindingValue);
                }
            }
    return ret;
}

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   www .jav  a  2 s . 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());
}