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:com.actimem.blog.gson.immutable.CompanyDeserializer.java

License:Apache License

@Override
public Company deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObject = json.getAsJsonObject();
    String name = jsonObject.get("name").getAsString();
    int foundedYear = jsonObject.get("foundedYear").getAsInt();
    double shareValue = jsonObject.get("shareValue").getAsDouble();
    return new Company(name, foundedYear, shareValue);
}

From source file:com.adeebnqo.Thula.mmssms.Transaction.java

License:Apache License

private void sendRnrSe(String authToken, String rnrse, String number, String text) throws Exception {
    JsonObject json = Ion.with(context).load("https://www.google.com/voice/sms/send/")
            .setHeader("Authorization", "GoogleLogin auth=" + authToken).setBodyParameter("phoneNumber", number)
            .setBodyParameter("sendErrorSms", "0").setBodyParameter("text", text)
            .setBodyParameter("_rnr_se", rnrse).asJsonObject().get();

    if (!json.get("ok").getAsBoolean())
        throw new Exception(json.toString());
}

From source file:com.adeebnqo.Thula.mmssms.Transaction.java

License:Apache License

private String fetchRnrSe(String authToken, Context context) throws ExecutionException, InterruptedException {
    JsonObject userInfo = Ion.with(context).load("https://www.google.com/voice/request/user")
            .setHeader("Authorization", "GoogleLogin auth=" + authToken).asJsonObject().get();

    String rnrse = userInfo.get("r").getAsString();

    try {//from w  w  w  . ja v  a  2  s  .  c o m
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Activity.TELEPHONY_SERVICE);
        String number = tm.getLine1Number();
        if (number != null) {
            JsonObject phones = userInfo.getAsJsonObject("phones");
            for (Map.Entry<String, JsonElement> entry : phones.entrySet()) {
                JsonObject phone = entry.getValue().getAsJsonObject();
                if (!PhoneNumberUtils.compare(number, phone.get("phoneNumber").getAsString()))
                    continue;
                if (!phone.get("smsEnabled").getAsBoolean())
                    break;

                Ion.with(context).load("https://www.google.com/voice/settings/editForwardingSms/")
                        .setHeader("Authorization", "GoogleLogin auth=" + authToken)
                        .setBodyParameter("phoneId", entry.getKey()).setBodyParameter("enabled", "0")
                        .setBodyParameter("_rnr_se", rnrse).asJsonObject();
                break;
            }
        }
    } catch (Exception e) {

    }

    // broadcast so you can save it to your shared prefs or something so that it doesn't need to be retrieved every time
    Intent intent = new Intent(VOICE_TOKEN);
    intent.putExtra("_rnr_se", rnrse);
    context.sendBroadcast(intent);

    return rnrse;
}

From source file:com.adobe.acs.commons.adobeio.service.impl.IntegrationServiceImpl.java

License:Apache License

private String fetchAccessToken() {
    String token = StringUtils.EMPTY;

    try (CloseableHttpClient client = helper.getHttpClient(getTimeoutinMilliSeconds())) {
        HttpPost post = new HttpPost(jwtServiceConfig.endpoint());
        post.addHeader(CACHE_CONTRL, NO_CACHE);
        post.addHeader(CONTENT_TYPE, CONTENT_TYPE_URL_ENCODED);

        List<BasicNameValuePair> params = Lists.newArrayList();
        params.add(new BasicNameValuePair(CLIENT_ID, jwtServiceConfig.clientId()));
        params.add(new BasicNameValuePair(CLIENT_SECRET, jwtServiceConfig.clientSecret()));
        params.add(new BasicNameValuePair(JWT_TOKEN, getJwtToken()));

        post.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse response = client.execute(post);

        if (response.getStatusLine().getStatusCode() != 200) {
            LOGGER.info("response code {} ", response.getStatusLine().getStatusCode());
        }/*from   w w w.  ja v  a2  s  . co m*/
        String result = IOUtils.toString(response.getEntity().getContent(), "UTF-8");

        LOGGER.info("JSON Response : {}", result);
        JsonParser parser = new JsonParser();
        JsonObject json = parser.parse(result).getAsJsonObject();

        if (json.has(JSON_ACCESS_TOKEN)) {
            token = json.get(JSON_ACCESS_TOKEN).getAsString();
        } else {
            LOGGER.error("JSON does not contain an access_token");
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    }

    LOGGER.info("JWT Access Token : {}", token);
    return token;
}

From source file:com.adobe.acs.commons.dam.audio.watson.impl.TranscriptionServiceImpl.java

License:Apache License

@Override
public String startTranscriptionJob(InputStream stream, String mimeType) {
    Request request = httpClientFactory
            .post("/speech-to-text/api/v1/recognitions?continuous=true&timestamps=true")
            .addHeader("Content-Type", mimeType).bodyStream(stream);

    try {//from   www  .ja  v  a2s .c  om
        JsonObject json = (JsonObject) httpClientFactory.getExecutor().execute(request).handleResponse(HANDLER);
        Gson gson = new Gson();
        log.trace("content: {}", gson.toJson(json));
        return json.get("id").getAsString();
    } catch (IOException e) {
        log.error("error submitting job", e);
        return null;
    }
}

From source file:com.adobe.acs.commons.dam.audio.watson.impl.TranscriptionServiceImpl.java

License:Apache License

@Override
public Result getResult(String jobId) {
    log.debug("getting result for {}", jobId);
    Request request = httpClientFactory.get("/speech-to-text/api/v1/recognitions/" + jobId);
    try {//from w  w w  . j  ava 2  s.  c  o  m
        JsonObject json = (JsonObject) httpClientFactory.getExecutor().execute(request).handleResponse(HANDLER);

        Gson gson = new Gson();
        log.trace("content: {}", gson.toJson(json));
        if (json.has("status") && json.get("status").getAsString().equals("completed")) {
            JsonArray results = json.get("results").getAsJsonArray().get(0).getAsJsonObject().get("results")
                    .getAsJsonArray();
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < results.size(); i++) {
                JsonObject result = results.get(i).getAsJsonObject();
                if (result.get("final").getAsBoolean()) {
                    JsonObject firstAlternative = result.get("alternatives").getAsJsonArray().get(0)
                            .getAsJsonObject();
                    String line = firstAlternative.get("transcript").getAsString();
                    if (StringUtils.isNotBlank(line)) {
                        double firstTimestamp = firstAlternative.get("timestamps").getAsJsonArray().get(0)
                                .getAsJsonArray().get(1).getAsDouble();
                        builder.append("[").append(firstTimestamp).append("s]: ").append(line).append("\n");
                    }
                }
            }

            String concatenated = builder.toString();
            concatenated = concatenated.replace("%HESITATION ", "");

            return new ResultImpl(true, concatenated);
        } else {
            return new ResultImpl(false, null);
        }
    } catch (IOException e) {
        log.error("Unable to get result. assuming failure.", e);
        return new ResultImpl(true, "error");
    }

}

From source file:com.adobe.acs.commons.json.JsonObjectUtil.java

License:Apache License

public static Optional<JsonElement> getOptional(JsonObject obj, String prop) {
    return Optional.ofNullable(obj.get(prop));
}

From source file:com.adobe.acs.commons.remoteassets.impl.RemoteAssetsNodeSyncImpl.java

License:Apache License

/**
 * Handler for when a JSON element represents a resource property.
 *
 * @param key String//from   w  w w .  ja va2 s .  c om
 * @param json JsonObject
 * @param resource Resource
 * @throws RepositoryException exception
 */
private void setNodeProperty(final ResourceResolver remoteAssetsResolver, final String key,
        final JsonObject json, final Resource resource) throws RepositoryException {
    try {
        JsonElement value = json.get(key);

        if (":".concat(JcrConstants.JCR_DATA).equals(key)) {
            setNodeJcrDataProperty(remoteAssetsResolver, resource,
                    json.getAsJsonPrimitive(JcrConstants.JCR_LASTMODIFIED).getAsString());
        } else if (key.startsWith(":")) {
            // Skip binary properties, since they do not come across in JSON
            return;
        } else if (PROTECTED_PROPERTIES.contains(key)) {
            // Skipping due to the property being unmodifiable.
            return;
        } else if (resource.getValueMap().get(key) != null
                && resource.getValueMap().get(key, String.class).equals(value.getAsString())) {
            // Skipping due to the property already existing and being equal
            return;
        } else {
            setNodeSimpleProperty(value.getAsJsonPrimitive(), key, resource);
        }
    } catch (RepositoryException re) {
        LOG.warn("Repository exception thrown. Skipping '{}' single property for resource '{}'.", key,
                resource.getPath());
    }
}

From source file:com.adobe.acs.commons.wcm.impl.RTEConfigurationServlet.java

License:Apache License

private void writeConfigResource(Resource resource, String rteName, SlingHttpServletRequest request,
        SlingHttpServletResponse response) throws IOException, ServletException {
    JsonObject widget = createEmptyWidget(rteName);

    // these two size properties seem to be necessary to get the size correct
    // in a component dialog
    widget.addProperty("width", RTE_WIDTH);
    widget.addProperty("height", RTE_HEIGHT);

    RequestParameterMap map = request.getRequestParameterMap();
    for (Map.Entry<String, RequestParameter[]> entry : map.entrySet()) {
        String key = entry.getKey();
        RequestParameter[] params = entry.getValue();
        if (params != null && (params.length > 1 || EXTERNAL_STYLESHEETS_PROPERTY.equals(key))) {
            JsonArray arr = new JsonArray();
            for (int i = 0; i < params.length; i++) {
                arr.add(new JsonPrimitive(params[i].getString()));
            }//w  w  w .  j  a  v a2  s .c o  m
            widget.add(key, arr);
        } else if (params != null && params.length == 1) {
            widget.addProperty(key, params[0].getString());
        }
    }

    if (widget.has("fieldLabel")) {
        widget.remove("hideLabel");
    }

    JsonObject config = toJsonObject(resource);

    if (config == null) {
        config = new JsonObject();
    }

    if (config.has("includeDefault") && config.get("includeDefault").getAsBoolean()) {
        config = underlay(config, resource.getResourceResolver().getResource(DEFAULT_CONFIG));
    }

    widget.add("rtePlugins", config);

    JsonObject parent = new JsonObject();
    parent.addProperty("xtype", "dialogfieldset");
    parent.addProperty("border", false);
    parent.addProperty("padding", 0);
    parent.add("items", widget);
    Gson gson = new Gson();
    gson.toJson(parent, response.getWriter());
}

From source file:com.adobe.acs.commons.workflow.bulk.execution.impl.servlets.InitFormServlet.java

License:Apache License

private JsonObject accumulate(JsonObject obj, String key, JsonElement value) {
    if (obj.has(key)) {
        JsonElement existingValue = obj.get(key);
        if (existingValue instanceof JsonArray) {
            ((JsonArray) existingValue).add(value);
        } else {//w  w w . j a  v  a 2s.  c o m
            JsonArray array = new JsonArray();
            array.add(existingValue);
            obj.add(key, array);
        }
    } else {
        JsonArray array = new JsonArray();
        array.add(value);
        obj.add(key, array);
    }
    return obj;
}