Example usage for com.google.gson JsonElement getAsInt

List of usage examples for com.google.gson JsonElement getAsInt

Introduction

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

Prototype

public int getAsInt() 

Source Link

Document

convenience method to get this element as a primitive integer value.

Usage

From source file:org.hibernate.search.elasticsearch.query.impl.PrimitiveProjection.java

License:LGPL

public void addDocumentField(Document tmp, JsonElement jsonValue) {
    if (jsonValue == null || jsonValue.isJsonNull()) {
        return;/*from  w  ww .  j  a v  a 2s .  c  o m*/
    }
    switch (fieldType) {
    case INTEGER:
        tmp.add(new IntField(absoluteName, jsonValue.getAsInt(), Store.NO));
        break;
    case LONG:
        tmp.add(new LongField(absoluteName, jsonValue.getAsLong(), Store.NO));
        break;
    case FLOAT:
        tmp.add(new FloatField(absoluteName, jsonValue.getAsFloat(), Store.NO));
        break;
    case DOUBLE:
        tmp.add(new DoubleField(absoluteName, jsonValue.getAsDouble(), Store.NO));
        break;
    case UNKNOWN_NUMERIC:
        throw LOG.unexpectedNumericEncodingType(rootTypeMetadata.getType(), absoluteName);
    case BOOLEAN:
        tmp.add(new StringField(absoluteName, String.valueOf(jsonValue.getAsBoolean()), Store.NO));
        break;
    default:
        tmp.add(new StringField(absoluteName, jsonValue.getAsString(), Store.NO));
        break;
    }
}

From source file:org.hibernate.search.elasticsearch.query.impl.PrimitiveProjection.java

License:LGPL

@Override
public Object convertHit(JsonObject hit, ConversionContext conversionContext) {
    JsonElement jsonValue = extractFieldValue(hit.get("_source").getAsJsonObject(), absoluteName);
    if (jsonValue == null || jsonValue.isJsonNull()) {
        return null;
    }//from   w  ww  .  j  a v a  2s .  c om
    switch (fieldType) {
    case INTEGER:
        return jsonValue.getAsInt();
    case LONG:
        return jsonValue.getAsLong();
    case FLOAT:
        return jsonValue.getAsFloat();
    case DOUBLE:
        return jsonValue.getAsDouble();
    case UNKNOWN_NUMERIC:
        throw LOG.unexpectedNumericEncodingType(rootTypeMetadata.getType(), absoluteName);
    case BOOLEAN:
        return jsonValue.getAsBoolean();
    default:
        return jsonValue.getAsString();
    }
}

From source file:org.intermine.app.json.GeneSearchResultDeserializer.java

License:GNU General Public License

private int getResultsCount(JsonObject obj) {
    JsonObject category = getJsonObject("Category", obj);

    if (null != category) {
        JsonElement resultsCount = category.get("Gene");

        if (null != resultsCount) {
            return resultsCount.getAsInt();
        }/*from w ww.  j a  v  a  2  s .c  o  m*/
    }
    return 0;
}

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.
 * /*  w  ww .  j a v a2s.c o  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.relution_publisher.util.Json.java

License:Apache License

public static int getInt(final JsonObject object, final String memberName) {
    final JsonElement element = object.get(memberName);

    if (element == null || !element.isJsonPrimitive()) {
        return 0;
    }//  w  ww  .  j a  v a 2s.  com

    return element.getAsInt();
}

From source file:org.jenkinsci.plugins.relution_publisher.util.Json.java

License:Apache License

public static Integer getInteger(final JsonObject object, final String memberName) {
    final JsonElement element = object.get(memberName);

    if (element == null || !element.isJsonPrimitive()) {
        return null;
    }/*  ww w. j a  v a  2 s.c  o m*/

    return element.getAsInt();
}

From source file:org.kurento.jsonrpc.JsonRpcAndJavaMethodManager.java

License:Apache License

private Object getAsJavaType(Class<?> type, JsonElement jsonElement) {
    if (jsonElement.isJsonNull()) {
        return null;
    } else if (type == String.class) {
        return jsonElement.getClass().equals(JsonObject.class) ? jsonElement.toString()
                : jsonElement.getAsString();
    } else if (type == boolean.class) {
        return jsonElement.getAsBoolean();
    } else if (type.isEnum()) {
        return gson.fromJson(jsonElement, type);
    } else if (type == int.class) {
        return jsonElement.getAsInt();
    } else {/*from w ww.  j  a v  a2s  .c o m*/
        return null;
    }
}

From source file:org.kurento.jsonrpc.JsonUtils.java

License:Apache License

@Override
public Response<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    if (!(json instanceof JsonObject)) {
        throw new JsonParseException("JonObject expected, found " + json.getClass().getSimpleName());
    }// w w w .jav  a 2s . c  om

    JsonObject jObject = (JsonObject) json;

    if (!jObject.has(JSON_RPC_PROPERTY)) {
        throw new JsonParseException(
                "Invalid JsonRpc response lacking version '" + JSON_RPC_PROPERTY + "' field");
    }

    if (!jObject.get(JSON_RPC_PROPERTY).getAsString().equals(JsonRpcConstants.JSON_RPC_VERSION)) {
        throw new JsonParseException("Invalid JsonRpc version");
    }

    Integer id = null;
    JsonElement idAsJsonElement = jObject.get(ID_PROPERTY);
    if (idAsJsonElement != null) {
        try {
            id = Integer.valueOf(idAsJsonElement.getAsInt());
        } catch (Exception e) {
            throw new JsonParseException("Invalid format in '" + ID_PROPERTY + "' field in request " + json);
        }
    }

    if (jObject.has(ERROR_PROPERTY)) {

        return new Response<>(id,
                (ResponseError) context.deserialize(jObject.get(ERROR_PROPERTY), ResponseError.class));

    } else {

        if (jObject.has(RESULT_PROPERTY)) {

            ParameterizedType parameterizedType = (ParameterizedType) typeOfT;

            return new Response<>(id, context.deserialize(jObject.get(RESULT_PROPERTY),
                    parameterizedType.getActualTypeArguments()[0]));

        } else {

            log.warn("Invalid JsonRpc response: " + json + " It lacks a valid '" + RESULT_PROPERTY + "' or '"
                    + ERROR_PROPERTY + "' field");

            return new Response<>(id, null);
        }
    }
}

From source file:org.kurento.room.client.internal.JsonRoomUtils.java

License:Apache License

@SuppressWarnings("unchecked")
private static <T> T getConverted(JsonElement paramValue, String property, Class<T> type, boolean allowNull) {
    if (paramValue == null) {
        if (allowNull) {
            return null;
        } else {//from   w w  w . j  a  v a 2 s.c  o  m
            throw new RoomException(Code.TRANSPORT_ERROR_CODE,
                    "Invalid method lacking parameter '" + property + "'");
        }
    }

    if (type == String.class) {
        if (paramValue.isJsonPrimitive()) {
            return (T) paramValue.getAsString();
        }
    }

    if (type == Integer.class) {
        if (paramValue.isJsonPrimitive()) {
            return (T) Integer.valueOf(paramValue.getAsInt());
        }
    }

    if (type == JsonArray.class) {
        if (paramValue.isJsonArray()) {
            return (T) paramValue.getAsJsonArray();
        }
    }

    throw new RoomException(Code.TRANSPORT_ERROR_CODE,
            "Param '" + property + "' with value '" + paramValue + "' is not a " + type.getName());
}

From source file:org.kurento.tree.client.internal.JsonTreeUtils.java

License:Apache License

@SuppressWarnings("unchecked")
private static <T> T getConverted(JsonElement paramValue, String property, Class<T> type, boolean allowNull) {
    if (paramValue == null || paramValue instanceof JsonNull) {
        if (allowNull) {
            return null;
        } else {// www  . j  a  va  2 s .c  o m
            throw new JsonRpcErrorException(1, "Invalid method lacking parameter '" + property + "'");
        }
    }

    if (type == String.class) {
        if (paramValue.isJsonPrimitive()) {
            return (T) paramValue.getAsString();
        }
    }

    if (type == Integer.class) {
        if (paramValue.isJsonPrimitive()) {
            return (T) Integer.valueOf(paramValue.getAsInt());
        }
    }

    throw new JsonRpcErrorException(2,
            "Param '" + property + "' with value '" + paramValue + "' is not a " + type.getName());
}