Example usage for com.google.gson JsonElement isJsonNull

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

Introduction

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

Prototype

public boolean isJsonNull() 

Source Link

Document

provides check for verifying if this element represents a null value or not.

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 2 s . c om*/
 * @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 boolean isNull(final JsonElement element) {
    return element == null || element.isJsonNull();
}

From source file:org.jenkinsci.plugins.skytap.SkytapUtils.java

License:Open Source License

/**
 * Utility method to extract errors, if any, from the Skytap json response,
 * and throw an exception which can be handled by the caller.
 * /*from  w  ww .  ja  v a 2s .  c  o  m*/
 * @param response
 * @throws SkytapException
 */
public static void checkResponseForErrors(String response) throws SkytapException {

    // check skytap response body for errors
    JsonParser parser = new JsonParser();
    JsonElement je = parser.parse(response);
    JsonObject jo = null;

    if (je.isJsonNull()) {
        return;
    } else if (je.isJsonArray()) {
        return;
    }

    je = parser.parse(response);
    jo = je.getAsJsonObject();

    if (!(jo.has("error") || jo.has("errors"))) {
        return;
    }

    // handle case where skytap returns an array of errors
    if (jo.has("errors")) {

        String errorString = "";

        JsonArray skytapErrors = (JsonArray) je.getAsJsonObject().get("errors");

        Iterator itr = skytapErrors.iterator();
        while (itr.hasNext()) {
            JsonElement errorElem = (JsonElement) itr.next();
            String errMsg = errorElem.toString();

            errorString += errMsg + "\n";

        }

        throw new SkytapException(errorString);

    }

    if (jo.has("error")) {

        // handle case where 'error' element is null value
        if (jo.get("error").isJsonNull()) {
            return;
        }

        // handle case where 'error' element is a boolean OR quoted string
        if (jo.get("error").isJsonPrimitive()) {

            String error = jo.get("error").getAsString();

            // handle boolean cases
            if (error.equals("false")) {
                return;
            }

            // TODO: find out where the error msg would be in this case
            if (error.equals("true")) {
                throw new SkytapException(error);
            }

            if (!error.equals("")) {
                throw new SkytapException(error);
            }
        }

    }

}

From source file:org.kairosdb.util.Validator.java

License:Apache License

public static boolean isNotNullOrEmpty(ValidationErrors validationErrors, Object name, JsonElement value) {
    if (value == null) {
        validationErrors.addErrorMessage(name + " may not be null.");
        return false;
    }// www  .  jav  a  2  s  .c  om
    if (value.isJsonNull()) {
        validationErrors.addErrorMessage(name + " may not be empty.");
        return false;
    }
    if (value.isJsonArray() && value.getAsJsonArray().size() < 1) {
        validationErrors.addErrorMessage(name + " may not be an empty array.");
        return false;
    }
    if (!value.isJsonObject() && value.getAsString().isEmpty()) {
        validationErrors.addErrorMessage(name + " may not be empty.");
        return false;
    }

    return true;
}

From source file:org.kurento.commons.BasicJsonUtils.java

License:Apache License

private static Object convertValue(JsonElement value) {
    if (value.isJsonNull()) {
        return null;
    } else if (value.isJsonPrimitive()) {
        JsonPrimitive prim = value.getAsJsonPrimitive();
        if (prim.isBoolean()) {
            return prim.getAsBoolean();
        } else if (prim.isNumber()) {
            Number n = prim.getAsNumber();
            if (n.doubleValue() == n.intValue()) {
                return n.intValue();
            } else {
                return n.doubleValue();
            }//from w w  w.j a  v a2s.c  o  m
        } else if (prim.isString()) {
            return prim.getAsString();
        } else {
            throw new RuntimeException("Unrecognized value: " + value);
        }
    } else {
        return value.toString();
    }
}

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 om*/
        return null;
    }
}

From source file:org.lanternpowered.server.script.function.action.json.ActionTypeAdapterFactory.java

License:MIT License

@Override
protected Action deserialize(TypeToken<Action> type, JsonElement element, Gson gson) {
    final Class<? super Action> raw = type.getRawType();
    if (ScriptFunction.class.isAssignableFrom(raw)) {
        return LanternScriptGameRegistry.get().compile(element.getAsString(), Action.class).get();
    } else if (ConditionalAction.class.isAssignableFrom(raw)) {
        return gson.getDelegateAdapter(this, TypeToken.get(ConditionalAction.class)).fromJsonTree(element);
    } else if (EmptyAction.class.isAssignableFrom(raw)) {
        return gson.getDelegateAdapter(this, TypeToken.get(EmptyAction.class)).fromJsonTree(element);
    } else if (MultiAction.class.isAssignableFrom(raw)) {
        return gson.getDelegateAdapter(this, TypeToken.get(MultiAction.class)).fromJsonTree(element);
    } else if (raw == Action.class) {
        // The actual action type isn't provided, we will try
        // to assume the right type based in the json format
        if (element.isJsonNull()) {
            return Action.empty();
        } else if (element.isJsonArray()) {
            return gson.getDelegateAdapter(this, TypeToken.get(MultiAction.class)).fromJsonTree(element);
        } else if (element.isJsonObject()) {
            final JsonObject obj = element.getAsJsonObject();
            if (obj.has(ConditionalActionJsonSerializer.ACTION)
                    && obj.has(ConditionalActionJsonSerializer.CONDITION)) {
                return gson.getDelegateAdapter(this, TypeToken.get(ConditionalAction.class))
                        .fromJsonTree(element);
            }/*  w  w  w.java  2s .  c  o  m*/
        } else {
            final String value = element.getAsString();
            if (value.startsWith(SCRIPT_PREFIX)) {
                return LanternScriptGameRegistry.get().compile(value, Action.class).get();
            }
        }
    }
    return super.deserialize(type, element, gson);
}

From source file:org.mobilelite.android.GingerbreadWebChromeClient.java

License:Apache License

@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
    if (message != null && message.startsWith(MobileLiteConstants.PROTOCOL_MOBILELITE)) {
        Log.d("request", url);
        //String request = URLDecoder.decode(url.substring(MobileLiteConstants.PROTOCOL_MOBILELITE.length()));
        String request = message.substring(MobileLiteConstants.PROTOCOL_MOBILELITE.length());
        Log.d("decoded request", request);

        JsonParser jsonParser = new JsonParser();
        JsonElement jsonParam = jsonParser.parse(request);

        if (jsonParam.isJsonNull() || jsonParam.isJsonPrimitive()) {
            Log.e("Invoke Bean Action",
                    "request should be in format {bean:'beanName', method:'methodName', params:[], callback:'callback string' }");
            return true;
        }/*from ww w . j  a  va2s . c om*/

        String beanName = null, methodName = null, callback = null;
        JsonElement params = null;
        boolean requestParsed = true;
        if (jsonParam.isJsonArray()) {
            JsonArray ja = jsonParam.getAsJsonArray();
            if (ja.size() == 4) {
                beanName = ja.get(1).getAsString();
                methodName = ja.get(2).getAsString();
                params = ja.get(3);
                callback = ja.get(4).getAsString();
            } else {
                Log.e("Invoke Bean Action", "request should have 4 element");
                requestParsed = false;
            }
        } else if (jsonParam.isJsonObject()) {
            JsonObject jo = jsonParam.getAsJsonObject();
            if (jo.has(MobileLiteConstants.PARAM_KEY_BEAN))
                beanName = jo.get(MobileLiteConstants.PARAM_KEY_BEAN).getAsString();
            else {
                Log.e("Invoke Bean Action", "request should have 'bean' element");
                requestParsed = false;
            }

            if (jo.has(MobileLiteConstants.PARAM_KEY_METHOD))
                methodName = jo.get(MobileLiteConstants.PARAM_KEY_METHOD).getAsString();
            else {
                Log.e("Invoke Bean Action", "request should have 'method' element");
                requestParsed = false;
            }

            if (jo.has(MobileLiteConstants.PARAM_KEY_PARAMS))
                params = jo.get(MobileLiteConstants.PARAM_KEY_PARAMS);
            else {
                Log.e("Invoke Bean Action", "request should have 'params' element");
                requestParsed = false;
            }

            if (jo.has(MobileLiteConstants.PARAM_KEY_CALLBACK)) {
                JsonElement callbackJson = null;
                callbackJson = jo.get(MobileLiteConstants.PARAM_KEY_CALLBACK);
                if (callbackJson.isJsonPrimitive())
                    callback = callbackJson.getAsString();
            } else {
                Log.e("Invoke Bean Action", "request should have 'callback' element");
                requestParsed = false;
            }
        }

        if (requestParsed) {
            dispatcher._invokeBeanAction(beanName, methodName, params, callback);
        }

        result.confirm();
        return true;
    }
    return super.onJsAlert(view, url, message, result);
}

From source file:org.mobilelite.android.GingerbreadWebViewClient.java

License:Apache License

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (url.startsWith(MobileLiteConstants.PROTOCOL_MOBILELITE)) {
        Log.d("request", url);
        String request = URLDecoder.decode(url.substring(MobileLiteConstants.PROTOCOL_MOBILELITE.length()));
        Log.d("decoded request", request);

        JsonParser jsonParser = new JsonParser();
        JsonElement jsonParam = jsonParser.parse(request);

        if (jsonParam.isJsonNull() || jsonParam.isJsonPrimitive()) {
            Log.e("Invoke Bean Action",
                    "request should be in format {bean:'beanName', method:'methodName', params:[], callback:'callback string' }");
            return true;
        }/*from  w w w . j  a  v  a2 s  . com*/

        String beanName = null, methodName = null, callback = null;
        JsonElement params = null;
        boolean requestParsed = true;
        if (jsonParam.isJsonArray()) {
            JsonArray ja = jsonParam.getAsJsonArray();
            if (ja.size() == 4) {
                beanName = ja.get(1).getAsString();
                methodName = ja.get(2).getAsString();
                params = ja.get(3);
                callback = ja.get(4).getAsString();
            } else {
                Log.e("Invoke Bean Action", "request should have 4 element");
                requestParsed = false;
            }
        } else if (jsonParam.isJsonObject()) {
            JsonObject jo = jsonParam.getAsJsonObject();
            if (jo.has(MobileLiteConstants.PARAM_KEY_BEAN))
                beanName = jsonParam.getAsJsonObject().get(MobileLiteConstants.PARAM_KEY_BEAN).getAsString();
            else {
                Log.e("Invoke Bean Action", "request should have 'bean' element");
                requestParsed = false;
            }

            if (jo.has(MobileLiteConstants.PARAM_KEY_METHOD))
                methodName = jsonParam.getAsJsonObject().get(MobileLiteConstants.PARAM_KEY_METHOD)
                        .getAsString();
            else {
                Log.e("Invoke Bean Action", "request should have 'method' element");
                requestParsed = false;
            }

            if (jo.has(MobileLiteConstants.PARAM_KEY_PARAMS))
                params = jsonParam.getAsJsonObject().get(MobileLiteConstants.PARAM_KEY_PARAMS);
            else {
                Log.e("Invoke Bean Action", "request should have 'params' element");
                requestParsed = false;
            }

            if (jo.has(MobileLiteConstants.PARAM_KEY_CALLBACK))
                callback = jsonParam.getAsJsonObject().get(MobileLiteConstants.PARAM_KEY_CALLBACK)
                        .getAsString();
            else {
                Log.e("Invoke Bean Action", "request should have 'callback' element");
                requestParsed = false;
            }
        }

        if (requestParsed) {
            dispatcher._invokeBeanAction(beanName, methodName, params, callback);
        }

        return true;
    }
    return super.shouldOverrideUrlLoading(view, url);
}

From source file:org.mule.runtime.extension.internal.persistence.metadata.MetadataKeyTypeAdapter.java

License:Open Source License

@Override
public MetadataKey read(JsonReader in) throws IOException {
    JsonElement jsonElement = new JsonParser().parse(in);
    if (jsonElement.isJsonNull()) {
        return null;
    }/*from w  w w.j  a  va2 s  .  co m*/
    JsonObject metadataKey = jsonElement.getAsJsonObject();

    if (metadataKey.entrySet().isEmpty()) {
        return new NullMetadataKey();
    } else {
        return gson.fromJson(jsonElement, DefaultMetadataKey.class);
    }
}