Example usage for com.google.gson JsonObject getAsJsonPrimitive

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

Introduction

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

Prototype

public JsonPrimitive getAsJsonPrimitive(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonPrimitive element.

Usage

From source file:org.jenkinsci.plugins.fod.FoDAPI.java

/**
 * Given a URL, request, and HTTP client, authenticates with FoD API. 
 * This is just a utility method which uses none of the class member fields.
 * //from   ww w.  j  a v  a 2s .co m
 * @param baseUrl URL for FoD
 * @param request request to authenticate
 * @param client HTTP client object
 * @return
 */
private AuthTokenResponse authorize(String baseUrl, AuthTokenRequest request) {
    final String METHOD_NAME = CLASS_NAME + ".authorize";
    PrintStream out = FodBuilder.getLogger();

    AuthTokenResponse response = new AuthTokenResponse();
    try {
        String endpoint = baseUrl + "/oauth/token";
        HttpPost httppost = new HttpPost(endpoint);

        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_TIMEOUT)
                .setConnectTimeout(CONNECTION_TIMEOUT).setSocketTimeout(CONNECTION_TIMEOUT).build();

        httppost.setConfig(requestConfig);

        List<NameValuePair> formparams = new ArrayList<NameValuePair>();

        if (AuthCredentialType.CLIENT_CREDENTIALS.getName().equals(request.getGrantType())) {
            AuthApiKey cred = (AuthApiKey) request.getPrincipal();
            formparams.add(new BasicNameValuePair("scope", FOD_SCOPE_TENANT));
            formparams.add(new BasicNameValuePair("grant_type", request.getGrantType()));
            formparams.add(new BasicNameValuePair("client_id", cred.getClientId()));
            formparams.add(new BasicNameValuePair("client_secret", cred.getClientSecret()));
        } else {
            out.println(METHOD_NAME + ": unrecognized grant type");
        }

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, UTF_8);
        httppost.setEntity(entity);
        HttpResponse postResponse = getHttpClient().execute(httppost);
        StatusLine sl = postResponse.getStatusLine();
        Integer statusCode = Integer.valueOf(sl.getStatusCode());

        if (statusCode.toString().startsWith("2")) {
            InputStream is = null;

            try {
                HttpEntity respopnseEntity = postResponse.getEntity();
                is = respopnseEntity.getContent();
                StringBuffer content = collectInputStream(is);
                String x = content.toString();
                JsonParser parser = new JsonParser();
                JsonElement jsonElement = parser.parse(x);
                JsonObject jsonObject = jsonElement.getAsJsonObject();
                JsonElement tokenElement = jsonObject.getAsJsonPrimitive("access_token");
                if (null != tokenElement && !tokenElement.isJsonNull() && tokenElement.isJsonPrimitive()) {

                    response.setAccessToken(tokenElement.getAsString());

                }
                JsonElement expiresIn = jsonObject.getAsJsonPrimitive("expires_in");
                Integer expiresInInt = expiresIn.getAsInt();
                response.setExpiresIn(expiresInInt);
                //TODO handle remaining two fields in response
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {

                    }
                }
                EntityUtils.consumeQuietly(postResponse.getEntity());
                httppost.releaseConnection();
            }
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return response;
}

From source file:org.jenkinsci.plugins.fod.FoDAPI.java

public Map<String, String> getApplicationList() throws IOException {
    final String METHOD_NAME = CLASS_NAME + ".getApplicationList";

    String endpoint = baseUrl + "/api/v1/Application/?fields=applicationId,applicationName,isMobile&limit=9999"; //TODO make this consistent elsewhere by a global config
    HttpGet connection = (HttpGet) getHttpUriRequest("GET", endpoint);
    InputStream is = null;/*from  w  w  w .  ja v  a2  s . c om*/

    try {
        // Get Response
        HttpResponse response = getHttpClient().execute(connection);
        is = response.getEntity().getContent();
        StringBuffer buffer = collectInputStream(is);
        JsonArray arr = getDataJsonArray(buffer);
        Map<String, String> map = new TreeMap<String, String>();
        for (int ix = 0; ix < arr.size(); ix++) {
            JsonElement entity = arr.get(ix);
            JsonObject obj = entity.getAsJsonObject();
            JsonPrimitive name = obj.getAsJsonPrimitive("applicationName");
            JsonPrimitive id = obj.getAsJsonPrimitive("applicationID");
            JsonPrimitive isMobile = obj.getAsJsonPrimitive("isMobile");

            if (map.containsKey(name.getAsString())) {
                continue;
            }
            if (!isMobile.getAsBoolean()) {
                map.put(name.getAsString(), id.getAsString());
            }
        }
        return map;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.jenkinsci.plugins.fod.FoDAPI.java

public Map<String, String> getAssessmentTypeListWithRetry() throws IOException {

    final String METHOD_NAME = CLASS_NAME + ".getReleaseList";
    PrintStream out = FodBuilder.getLogger();
    if (null == out) {
        out = System.out;//ww  w  .j av  a2 s  . c  om
    }

    int attempts = 0;
    int maxattempts = 5;
    Map<String, String> map = new TreeMap<String, String>();

    String endpoint = baseUrl + "/api/v1/AssessmentType";

    while ((null == map || map.isEmpty()) && (attempts < maxattempts)) {
        HttpGet connection = (HttpGet) getHttpUriRequest("GET", endpoint);
        InputStream is = null;

        try {
            // Get Response
            HttpResponse response = getHttpClient().execute(connection);
            is = response.getEntity().getContent();
            StringBuffer buffer = collectInputStream(is);

            int responseCode = response.getStatusLine().getStatusCode();
            out.println(METHOD_NAME + ": calling GET " + endpoint);
            out.println(METHOD_NAME + ": responseCode = " + responseCode);
            out.println(METHOD_NAME + ": response = " + buffer);
            System.out.println(METHOD_NAME + ": called, " + attempts + " previous attempts.");

            JsonArray arr = getDataJsonArray(buffer);

            String staticTypeRegex = ".*static.*";
            Pattern p = Pattern.compile(staticTypeRegex, Pattern.CASE_INSENSITIVE);

            for (int ix = 0; ix < arr.size(); ix++) {
                JsonElement entity = arr.get(ix);
                JsonObject obj = entity.getAsJsonObject();
                JsonPrimitive name = obj.getAsJsonPrimitive("Name");
                JsonPrimitive id = obj.getAsJsonPrimitive("AssessmentTypeId");

                Matcher m = p.matcher(name.getAsString());

                if (map.containsKey(name.getAsString()) && m.matches())
                    continue;
                map.put(name.getAsString(), id.getAsString());
            }
            if (!(null == map || map.isEmpty())) {
                return map;
            }
        } finally {

            attempts++;

            if (is != null) {
                is.close();
            }
        }
    }
    out.println(METHOD_NAME
            + ": Unable to refresh assessment types, please contact your Technical Account Manager for assistance. ");
    return map;
}

From source file:org.jenkinsci.plugins.fod.FoDAPI.java

/**
 * Scan snapshot refers to a particular point in history when statistics are 
 * reevaluated, such as when a scan is completed. This call returns different 
 * data structures from the call to retrieve an individual scan by ID from
 * under the Release context path.//  w  w w. j  a  va 2 s .com
 * 
 * @throws IOException
 */
public List<ScanSnapshot> getScanSnapshotList() throws IOException {
    String endpoint = baseUrl + "/api/v1/Scan";
    HttpGet connection = (HttpGet) getHttpUriRequest("GET", endpoint);
    InputStream is = null;

    try {
        // Get Response
        HttpResponse response = getHttpClient().execute(connection);
        is = response.getEntity().getContent();
        StringBuffer buffer = collectInputStream(is);
        JsonArray arr = getDataJsonArray(buffer);
        List<ScanSnapshot> snapshots = new LinkedList<ScanSnapshot>();
        for (int ix = 0; ix < arr.size(); ix++) {
            JsonElement entity = arr.get(ix);
            JsonObject obj = entity.getAsJsonObject();

            ScanSnapshot scan = new ScanSnapshot();
            if (!obj.get("ProjectVersionId").isJsonNull()) {
                JsonPrimitive releaseIdObj = obj.getAsJsonPrimitive("ProjectVersionId");
                scan.setProjectVersionId(releaseIdObj.getAsLong());
            }
            if (!obj.get("StaticScanId").isJsonNull()) {
                JsonPrimitive staticScanIdObj = obj.getAsJsonPrimitive("StaticScanId");
                scan.setStaticScanId(staticScanIdObj.getAsLong());
            }
            if (!obj.get("DynamicScanId").isJsonNull()) {
                JsonPrimitive dynamicScanIdObj = obj.getAsJsonPrimitive("DynamicScanId");
                scan.setDynamicScanId(dynamicScanIdObj.getAsLong());
            }
            if (!obj.get("MobileScanId").isJsonNull()) {
                JsonPrimitive mobileScanIdObj = obj.getAsJsonPrimitive("MobileScanId");
                scan.setMobileScanId(mobileScanIdObj.getAsLong());
            }
            //FIXME translate CategoryRollups
            if (!obj.get("RollupHistoryId").isJsonNull()) {
                JsonPrimitive rollupHistoryIdObj = obj.getAsJsonPrimitive("RollupHistoryId");
                scan.setHistoryRollupId(rollupHistoryIdObj.getAsLong());
            }

            snapshots.add(scan);
        }
        return snapshots;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.jenkinsci.plugins.restservicescheduler.json.NodeAssignmentsDeserializer.java

License:Open Source License

public NodeAssignments deserialize(final JsonElement json, final Type typeOfT,
        final JsonDeserializationContext context) throws JsonParseException {

    final NodeAssignments.Builder builder = NodeAssignments.builder();

    final JsonArray items = json.getAsJsonObject().getAsJsonArray("solution");
    for (final JsonElement o : items) {

        final JsonObject item = o.getAsJsonObject();

        final int itemId = item.getAsJsonPrimitive("id").getAsInt();
        final String nodeName = deserilizeNodeName(item.getAsJsonPrimitive("node").getAsString());
        builder.assign(itemId, nodeName);
    }/*from w w w  . j  a  v a2  s.c o  m*/

    return builder.build();
}

From source file:org.json.other.server.Base64JsonRpcExecutor.java

License:Apache License

public void execute(JsonRpcServerTransport transport) {
    if (!locked) {
        synchronized (handlers) {
            locked = true;/*from  w  w  w .jav a 2  s .  c  o m*/
        }
    }

    String methodName = null;
    JsonArray params = null;

    JsonObject resp = new JsonObject();
    resp.addProperty("jsonrpc", "2.0");

    String errorMessage = null;
    Integer errorCode = null;
    String errorData = null;

    JsonObject req = null;
    try {
        String requestData = transport.readRequest();
        JsonParser parser = new JsonParser();
        req = (JsonObject) parser.parse(new StringReader(requestData));
    } catch (Throwable t) {
        errorCode = JsonRpcErrorCodes.PARSE_ERROR_CODE;
        errorMessage = "unable to parse json-rpc request";
        errorData = getStackTrace(t);

        sendError(transport, resp, errorCode, errorMessage, errorData);
        return;
    }

    try {
        assert req != null;
        resp.add("id", req.get("id"));

        methodName = req.getAsJsonPrimitive("method").getAsString();
        params = (JsonArray) req.get("params");
        if (params == null) {
            params = new JsonArray();
        }
    } catch (Throwable t) {
        errorCode = JsonRpcErrorCodes.INVALID_REQUEST_ERROR_CODE;
        errorMessage = "unable to read request";
        errorData = getStackTrace(t);

        sendError(transport, resp, errorCode, errorMessage, errorData);
        return;
    }

    try {
        JsonElement result = executeMethod(methodName, params);
        resp.add("result", result);
    } catch (Throwable t) {
        if (t instanceof JsonRpcRemoteException) {
            sendError(transport, resp, (JsonRpcRemoteException) t);
            return;
        }
        errorCode = JsonRpcErrorCodes.getServerError(1);
        errorMessage = t.getMessage();
        errorData = getStackTrace(t);
        sendError(transport, resp, errorCode, errorMessage, errorData);
        return;
    }

    try {
        String responseData = resp.toString();
        transport.writeResponse(responseData);
    } catch (Exception e) {
    }
}

From source file:org.json.rpc.server.InjectingJsonRpcExecutor.java

License:Apache License

public void execute(JsonRpcServerTransport transport, HttpServletRequest httpReq, HttpServletResponse httpResp,
        ServletContext servletContext) {
    if (!locked) {
        synchronized (handlers) {
            locked = true;/*from w ww.  j a va 2s.co m*/
        }
        LOG.info("locking executor to avoid modification");
    }

    String uuid = null;
    String methodName = null;
    JsonArray params = null;

    JsonObject resp = new JsonObject();
    resp.addProperty("jsonrpc", "2.0");

    String errorMessage = null;
    Integer errorCode = null;
    String errorData = null;

    JsonObject req = null;
    try {
        String requestData = transport.readRequest();
        if (LOG.isDebugEnabled()) {
            LOG.debug("JSON-RPC >>  {}", requestData);
        }
        JsonParser parser = new JsonParser();
        req = (JsonObject) parser.parse(new StringReader(requestData));
    } catch (Throwable t) {
        errorCode = JsonRpcErrorCodes.PARSE_ERROR_CODE;
        errorMessage = "unable to parse json-rpc request";
        errorData = getStackTrace(t);

        LOG.warn(errorMessage, t);

        sendError(transport, resp, errorCode, errorMessage, errorData);
        return;
    }

    try {
        assert req != null;
        resp.add("id", req.get("id"));
        JsonPrimitive uuidPrimitive = req.getAsJsonPrimitive("uuid");
        if (uuidPrimitive != null) {
            uuid = uuidPrimitive.getAsString();
        }
        methodName = req.getAsJsonPrimitive("method").getAsString();
        params = (JsonArray) req.get("params");
        if (params == null) {
            params = new JsonArray();
        }
    } catch (Throwable t) {
        errorCode = JsonRpcErrorCodes.INVALID_REQUEST_ERROR_CODE;
        errorMessage = "unable to read request";
        errorData = getStackTrace(t);

        LOG.warn(errorMessage, t);
        sendError(transport, resp, errorCode, errorMessage, errorData);
        return;
    }

    try {
        JsonElement result = executeMethod(methodName, params, uuid, httpReq, httpResp, servletContext);
        resp.add("result", result);
    } catch (Throwable t) {
        LOG.warn("exception occured while executing : " + methodName, t);
        if (t instanceof JsonRpcRemoteException) {
            sendError(transport, resp, (JsonRpcRemoteException) t);
            return;
        }
        errorCode = JsonRpcErrorCodes.getServerError(1);
        errorMessage = t.getMessage();
        errorData = getStackTrace(t);
        sendError(transport, resp, errorCode, errorMessage, errorData);
        return;
    }

    try {
        String responseData = resp.toString();
        LOG.debug("JSON-RPC result <<  {}", responseData);
        transport.writeResponse(responseData);
    } catch (Exception e) {
        LOG.warn("unable to write response : " + resp, e);
    }
}

From source file:org.json.rpc.server.JsonRpcExecutor.java

License:Apache License

public void execute(JsonRpcServerTransport transport) {

    if (!locked) {
        synchronized (handlers) {
            locked = true;/*from  www. jav a 2  s .c o m*/
        }

    }

    String methodName = null;
    JsonArray params = null;

    JsonObject resp = new JsonObject();
    resp.addProperty("jsonrpc", "2.0");
    String errorMessage = null;
    Integer errorCode = null;
    String errorData = null;

    JsonObject req = null;
    try {
        String requestData = transport.readRequest();

        JsonParser parser = new JsonParser();
        req = (JsonObject) parser.parse(new StringReader(requestData)); //??? ????

    } catch (Throwable t) {
        errorCode = JsonRpcErrorCodes.PARSE_ERROR_CODE;
        errorMessage = "unable to parse json-rpc request";
        errorData = getStackTrace(t);

        sendError(transport, resp, errorCode, errorMessage, errorData);
        return;
    }

    try {
        assert req != null;
        resp.add("id", req.get("id"));

        methodName = req.getAsJsonPrimitive("method").getAsString();
        params = (JsonArray) req.get("params");

        if (params == null) {
            params = new JsonArray();
        }
    } catch (Throwable t) {
        errorCode = JsonRpcErrorCodes.INVALID_REQUEST_ERROR_CODE;
        errorMessage = "unable to read request";
        errorData = getStackTrace(t);

        sendError(transport, resp, errorCode, errorMessage, errorData);
        return;
    }

    try {
        JsonElement result = executeMethod(methodName, params);
        resp.add("result", result);

    } catch (Throwable t) {
        LOG.warn("exception occured while executing : " + methodName, t);
        if (t instanceof JsonRpcRemoteException) {
            sendError(transport, resp, (JsonRpcRemoteException) t);
            return;
        }
        errorCode = JsonRpcErrorCodes.getServerError(1);
        errorMessage = t.getMessage();
        errorData = getStackTrace(t);
        sendError(transport, resp, errorCode, errorMessage, errorData);
        return;
    }

    try {
        String responseData = resp.toString();

        transport.writeResponse(responseData);
    } catch (Exception e) {
        LOG.warn("unable to write response : " + resp, e);
    }
}

From source file:org.kontalk.xmppserver.registration.checkmobi.CheckmobiValidationClient.java

License:Open Source License

public RequestResult request(String number) throws IOException {
    try {/*from  w w w.  j a v a  2 s. com*/
        JsonObject data = _request(number);
        try {
            String id = data.getAsJsonPrimitive("id").getAsString();
            String dialingNumber = data.has("dialing_number")
                    ? data.getAsJsonPrimitive("dialing_number").getAsString()
                    : null;
            return new RequestResult(id, dialingNumber);
        } catch (NullPointerException e) {
            // simulate bad request
            throw new HttpResponseException(400, "Bad request");
        }
    } catch (HttpResponseException e) {
        return new RequestResult(e);
    }
}

From source file:org.kontalk.xmppserver.registration.checkmobi.CheckmobiValidationClient.java

License:Open Source License

public VerifyResult verify(String requestId, String pin) throws IOException {
    try {//  w w w . ja v a 2  s.c  om
        JsonObject data = _verify(requestId, pin);
        try {
            boolean validated = data.getAsJsonPrimitive("validated").getAsBoolean();
            return new VerifyResult(validated);
        } catch (NullPointerException e) {
            // simulate bad request
            throw new HttpResponseException(400, "Bad request");
        }
    } catch (HttpResponseException e) {
        return new VerifyResult(e);
    }
}