Example usage for com.google.gson JsonObject has

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

Introduction

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

Prototype

public boolean has(String memberName) 

Source Link

Document

Convenience method to check if a member with the specified name is present in this object.

Usage

From source file:co.cask.cdap.internal.app.ServiceSpecificationCodec.java

License:Apache License

private boolean isOldSpec(JsonObject json) {
    return json.has("classname"); // In old spec, it's misspelled as classname, not className.
}

From source file:co.cask.cdap.proto.codec.HttpServiceSpecificationCodec.java

License:Apache License

private boolean isOldSpec(JsonObject json) {
    return !json.has("endpoints"); // This field wasn't in the original spec
}

From source file:co.uk.mattredmond.basewatcher.handlers.APIHandler.java

License:Open Source License

/**
 * Parsing of the returned JSON from the server
 *
 * @param rawJson Raw JSON string from server
 *///from w  ww .  jav  a2 s  . c o  m
private JsonObject parseJson(String rawJson) {
    JsonObject rawObject = new Gson().fromJson(rawJson, JsonObject.class);
    JsonObject baseWatcherObject = rawObject.get("BaseWatcher").getAsJsonObject();
    JsonObject dataInner = baseWatcherObject.get("data").getAsJsonObject();

    if (dataInner.has("error")) {
        BaseWatcher.logger.error(dataInner.get("error").getAsString());
        return null;
    } else {
        return dataInner;
    }
}

From source file:co.uk.mattredmond.basewatcher.handlers.APIHandler.java

License:Open Source License

/**
 * Validates the URL being used. Simple ping / pong
 *
 * @return boolean// w  w w  . j  av a2  s  .c o  m
 */
private boolean validUrl() {
    JsonObject ping = APIGet(APIEndpoints.ping);

    if (ping != null) {
        if (ping.has("ping")) {
            return true;
        }
    } else {
        return false;
    }

    return false;
}

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

License:Apache License

@Override
public boolean isConnected() {
    try {/*  ww w .  jav  a2s  .  c  o  m*/
        JsonObject response = processGet(new URIBuilder(url).build(), null);
        return !response.has(RESULT_ERROR);
    } catch (Exception e) {
        LOGGER.error("Problem testing the connection for {}", id, e);
    }
    return false;
}

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 a  2  s  .com
        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 Result getResult(String jobId) {
    log.debug("getting result for {}", jobId);
    Request request = httpClientFactory.get("/speech-to-text/api/v1/recognitions/" + jobId);
    try {/*w ww. j  av  a  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.exporters.impl.users.Parameters.java

License:Apache License

public Parameters(SlingHttpServletRequest request) throws IOException {
    final JsonObject json = new JsonParser().parse(request.getParameter("params")).getAsJsonObject();

    final List<String> tmpCustomProperties = new ArrayList<String>();
    final List<String> tmpGroups = new ArrayList<String>();

    groupFilter = getString(json, GROUP_FILTER);

    JsonArray groupsJSON = json.getAsJsonArray(GROUPS);
    for (int i = 0; i < groupsJSON.size(); i++) {
        tmpGroups.add(groupsJSON.get(i).getAsString());
    }//  w  w w.  jav  a2  s . c  o m

    this.groups = tmpGroups.toArray(new String[tmpGroups.size()]);

    JsonArray customPropertiesJSON = json.getAsJsonArray(CUSTOM_PROPERTIES);
    for (int i = 0; i < customPropertiesJSON.size(); i++) {
        JsonObject tmp = customPropertiesJSON.get(i).getAsJsonObject();

        if (tmp.has(RELATIVE_PROPERTY_PATH)) {
            String relativePropertyPath = getString(tmp, RELATIVE_PROPERTY_PATH);
            tmpCustomProperties.add(relativePropertyPath);
        }
    }

    this.customProperties = tmpCustomProperties.toArray(new String[tmpCustomProperties.size()]);
}

From source file:com.adobe.acs.commons.replication.impl.ReplicateVersionServlet.java

License:Apache License

@Override
public final void doPost(SlingHttpServletRequest req, SlingHttpServletResponse res)
        throws ServletException, IOException {

    log.debug("Entering ReplicatePageVersionServlet.doPost(..)");

    String[] rootPaths = req.getParameterValues("rootPaths");
    Date date = getDate(req.getParameter("datetimecal"));
    String[] agents = req.getParameterValues("cmbAgent");

    JsonObject obj = validate(rootPaths, agents, date);

    if (!obj.has(KEY_ERROR)) {
        log.debug("Initiating version replication");

        List<ReplicationResult> response = replicateVersion.replicate(req.getResourceResolver(), rootPaths,
                agents, date);//w ww.  java2 s.com

        if (log.isDebugEnabled()) {
            for (final ReplicationResult replicationResult : response) {
                log.debug("Replication result: {} -- {}", replicationResult.getPath(),
                        replicationResult.getStatus());
            }
        }

        JsonArray arr = convertResponseToJson(response);
        obj = new JsonObject();
        obj.add(KEY_RESULT, arr);

    } else {
        log.debug("Did not attempt to replicate version due to issue with input params");

        res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        obj.addProperty(KEY_STATUS, KEY_ERROR);
    }

    res.setContentType("application/json");
    res.getWriter().print(obj.toString());
}

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 ava2  s . c  om
            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());
}