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:com.pinterest.deployservice.group.CMDBHostGroupManager.java

License:Apache License

@Override
public Map<String, HostBean> getHostIdsByGroup(String groupName) throws Exception {
    HashMap<String, HostBean> hosts = new HashMap<>();
    String url = String.format("%s/getquery", cmdbServer);

    // construct data
    String query = String.format("state:running AND (facts.deploy_service:\"%s\" facts.puppet_groups:\"%s\")",
            groupName, groupName);/*from www .  j ava2  s  .c om*/
    Map<String, String> data = new HashMap<>();
    data.put("query", query);
    data.put("fields", "id,state,config.name,config.internal_address,created_time");

    // construct head
    Map<String, String> headers = new HashMap<>();
    headers.put("Content-Type", "application/x-www-form-urlencoded");

    HTTPClient client = new HTTPClient();
    String result = client.post(url, constructQuery(data), headers, TOTAL_RETRY);
    JsonParser parser = new JsonParser();
    JsonElement elements = parser.parse(result);
    if (elements.isJsonNull()) {
        LOG.info("CMDB query: {} returns empty list", query);
        return hosts;
    }

    JsonArray jsonObjects = (JsonArray) elements;
    for (JsonElement element : jsonObjects) {
        JsonObject object = element.getAsJsonObject();
        if (object.get("state").getAsString().equals("running") && object.has("config.name")) {
            HostBean hostBean = new HostBean();
            String hostId = object.get("id").getAsString();
            hostBean.setHost_name(object.get("config.name").getAsString());
            hostBean.setHost_id(hostId);
            hostBean.setIp(object.get("config.internal_address").getAsString());
            hostBean.setCreate_date(getDateTime(object.get("created_time").getAsString()));
            hosts.put(hostId, hostBean);
        }
    }
    LOG.info("Fetched {} hosts for group {} in CMDB", hosts.size(), groupName);
    return hosts;
}

From source file:com.pinterest.deployservice.group.CMDBHostGroupManager.java

License:Apache License

@Override
public String getLastInstanceId(String groupName) throws Exception {
    String url = String.format("%s/getquery", cmdbServer);

    // construct data
    String query = String.format("state:running AND (facts.deploy_service:\"%s\" facts.puppet_groups:\"%s\")",
            groupName, groupName);/*from  w  w w. ja v a  2 s . c o  m*/
    Map<String, String> data = new HashMap<>();
    data.put("query", query);
    data.put("fields", "state,id,location,created_time");

    // construct head
    Map<String, String> headers = new HashMap<>();
    headers.put("Content-Type", "application/x-www-form-urlencoded");

    HTTPClient client = new HTTPClient();
    String result = client.post(url, constructQuery(data), headers, TOTAL_RETRY);
    JsonParser parser = new JsonParser();
    JsonElement elements = parser.parse(result);

    if (elements.isJsonNull()) {
        LOG.info("CMDB query: {} returns empty list", query);
        return null;
    }

    JsonArray jsonObjects = (JsonArray) elements;
    List<Pair<Long, String>> results = new LinkedList<>();
    for (JsonElement element : jsonObjects) {
        JsonObject object = element.getAsJsonObject();
        if (object.get("state").getAsString().equals("running")) {
            String id = object.get("id").getAsString();
            Long timestamp = getDateTime(object.get("created_time").getAsString());
            results.add(new Pair<>(timestamp, id));
        }
    }

    Collections.sort(results, new Comparator<Pair<Long, String>>() {
        @Override
        public int compare(Pair<Long, String> o1, Pair<Long, String> o2) {
            return o2.getKey().compareTo(o1.getKey());
        }
    });

    return results.get(0).getValue();
}

From source file:com.popdeem.sdk.core.api.PDAPIClient.java

License:Open Source License

/**
 * Claim a reward and post social action
 *
 * @param context             - @NonNull Application {@link Context}
 * @param facebookAccessToken - @NonNull Facebook Access Token {@link String}
 * @param rewardId            - Reward ID {@link String}
 * @param message             - Message {@link String}
 * @param taggedFriendsNames  - {@link String} {@link ArrayList} of tagged Friends.
 * @param taggedFriendsIds    - {@link String} {@link ArrayList} of tagged Friend IDs.
 * @param image               - {@link android.util.Base64} encoded {@link String}. The image data must be Base64 encoded. If left null, message will only be posted.
 * @param longitude           - Current longitude for user
 * @param latitude            - Current latitude for user
 * @param callback            {@link PDAPICallback} for API result
 *///ww w. j  av a  2  s.  c o  m
public void claimReward(@NonNull final Context context, final String facebookAccessToken,
        final String twitterAuthToken, final String twitterSecret, final String instagramAccessToken,
        @NonNull final String rewardId, @NonNull final String message, ArrayList<String> taggedFriendsNames,
        ArrayList<String> taggedFriendsIds, final String image, @NonNull final String longitude,
        @NonNull final String latitude, @NonNull final PDAPICallback<JsonObject> callback) {
    final Handler mainHandler = new Handler(context.getMainLooper());
    final String url = PDAPIConfig.PD_API_ENDPOINT + PDAPIConfig.PD_REWARDS_PATH + "/" + rewardId + "/claim";

    final OkHttpClient client = new OkHttpClient();
    FormBody.Builder bodyBuilder = new FormBody.Builder().add("message", message)
            .add("location[latitude]", latitude).add("location[longitude]", longitude);

    if (facebookAccessToken != null) {
        bodyBuilder.add("facebook[access_token]", facebookAccessToken);
        if (taggedFriendsIds != null && taggedFriendsNames != null
                && taggedFriendsIds.size() == taggedFriendsNames.size() && taggedFriendsIds.size() > 0
                && taggedFriendsNames.size() > 0) {
            for (int i = 0; i < taggedFriendsIds.size(); i++) {
                String name = taggedFriendsNames.get(i);
                String id = taggedFriendsIds.get(i);

                bodyBuilder.add("facebook[associated_account_ids][][name]", name);
                bodyBuilder.add("facebook[associated_account_ids][][id]", id);
            }
        }
    }
    if (twitterAuthToken != null) {
        bodyBuilder.add("twitter[access_token]", twitterAuthToken);
        bodyBuilder.add("twitter[access_secret]", twitterSecret);
    }
    if (instagramAccessToken != null) {
        bodyBuilder.add("instagram[access_token]", instagramAccessToken);
    }

    if (image != null) {
        bodyBuilder.add("file", image);
    }

    RequestBody body = bodyBuilder.build();

    final Request request = new Request.Builder().url(url)
            .addHeader(PDAPIConfig.REQUEST_HEADER_API_KEY, PopdeemSDK.getPopdeemAPIKey())
            .addHeader(PDAPIConfig.REQUEST_HEADER_USER_TOKEN, PDUtils.getUserToken()).post(body).build();

    client.newCall(request).enqueue(new okhttp3.Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            callback.failure(RetrofitError.networkError(url, new IOException("Unexpected code " + e)));
        }

        @Override
        public void onResponse(Call call, final okhttp3.Response response) throws IOException {
            // Convert OkHTTP response to Retrofit Response
            final String responseBody = response.body().string();
            final JsonElement object = new JsonParser().parse(responseBody);
            final TypedInput bodyTypedInput = new TypedString(responseBody);
            final ArrayList<Header> headers = new ArrayList<>();

            Headers responseHeaders = response.headers();
            for (int i = 0; i < responseHeaders.size(); i++) {
                headers.add(new Header(responseHeaders.name(i), responseHeaders.value(i)));
            }

            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    callback.success(object.isJsonNull() ? null : object.getAsJsonObject(),
                            new Response(response.request().url().toString(), response.networkResponse().code(),
                                    response.networkResponse().message(), headers, bodyTypedInput));
                }
            });
        }
    });
}

From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.QMetryRestWebservice.java

License:Open Source License

public String createTestCase(String scriptName, String folderId) {

    // create testcase using method fully qualifier name
    Builder tcBuidler = new RestTestBase().getWebResource(serviceUrl, "/rest/testcases/").getRequestBuilder();

    // add request header
    for (Iterator<Map.Entry<String, String>> it = getRequestHeader().entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, String> entry = it.next();
        tcBuidler.header(entry.getKey(), entry.getValue());
    }/*from   w ww  . j  a v a 2s.c  om*/
    JsonObject userInfoJson = new Gson().fromJson(userInfo, JsonElement.class).getAsJsonObject();

    JsonElement customListsDefaults = userInfoJson.get("customLists");
    String testingType = "";

    // get test case testing type
    if (!customListsDefaults.isJsonNull() && customListsDefaults.getAsJsonObject().has("testingType")) {
        Set<Entry<String, JsonElement>> keys = customListsDefaults.getAsJsonObject().get("testingType")
                .getAsJsonObject().entrySet();
        Iterator<Entry<String, JsonElement>> testingTypeItr = keys.iterator();
        while (testingTypeItr.hasNext()) {
            Entry<String, JsonElement> testingTypes = testingTypeItr.next();
            String value = testingTypes.getValue().getAsString();
            if (value.equalsIgnoreCase("Automated")) {
                testingType = testingTypes.getKey();
                break;
            }
        }
    } else {
        System.err.println("Custom Lists Defaults does not exists in user info");
    }

    // create testcase entity
    String randomizer = new Date().toString();
    JsonObject createTcReq = new JsonObject();
    createTcReq.addProperty("tcVersionID", 1);
    createTcReq.addProperty("tcFolderID", folderId);
    createTcReq.addProperty("tcID", 0);
    createTcReq.addProperty("scope", "cycle");
    createTcReq.addProperty("name", "AutoTestCase" + randomizer);
    createTcReq.addProperty("testScriptName", scriptName);

    if (!StringUtil.isNullOrEmpty(testingType))
        createTcReq.addProperty("testingType", testingType);
    // post action to create new testcase
    String response = null;
    try {
        response = tcBuidler.post(String.class, createTcReq.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;

}

From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.QMetryRestWebservice.java

License:Open Source License

public int createTestSuiteParentFolder() {

    JsonObject infoUSer = new Gson().fromJson(userInfo, JsonElement.class).getAsJsonObject();
    JsonElement rootFolders = infoUSer.get("rootFolders");
    JsonElement testsuite;//from w  ww.  j  a  v  a  2  s  .c  om

    // get test case parent folder id
    if (!rootFolders.isJsonNull() && rootFolders.getAsJsonObject().has("TS")) {
        testsuite = rootFolders.getAsJsonObject().get("TS");

        if (!testsuite.isJsonNull() && testsuite.getAsJsonObject().has("id"))
            return testsuite.getAsJsonObject().get("id").getAsInt();
        else
            System.err.println("Test Suite id does not exists in user info");
    } else {
        System.err.println("Test Suite does not exists in user info");
    }
    return 0;
}

From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.QMetryRestWebservice.java

License:Open Source License

public int createTestCaseParentFolder() {
    JsonObject infoUSer = new Gson().fromJson(userInfo, JsonElement.class).getAsJsonObject();
    JsonElement rootFolders = infoUSer.get("rootFolders");
    JsonElement testCase;/* www. j av a 2 s .co m*/
    // get test case parent folder id
    if (!rootFolders.isJsonNull() && rootFolders.getAsJsonObject().has("TC")) {
        testCase = rootFolders.getAsJsonObject().get("TC");

        if (!testCase.isJsonNull() && testCase.getAsJsonObject().has("id"))
            return testCase.getAsJsonObject().get("id").getAsInt();
        else
            System.err.println("Test case id does not exists in user info");
    } else {
        System.err.println("Test case does not exists in user info");
    }
    return 0;
}

From source file:com.redhat.thermostat.gateway.service.commands.channel.coders.typeadapters.BasicMessageTypeAdapter.java

License:Open Source License

private SortedMap<String, String> decodePayloadAsParamMap(JsonObject payloadElem) {
    SortedMap<String, String> paramMap = new TreeMap<>();
    if (payloadElem == null) {
        return paramMap; // no params
    }/*  w ww  .  j  av a 2 s .c  o m*/
    for (Entry<String, JsonElement> entry : payloadElem.entrySet()) {
        JsonElement value = entry.getValue();
        String strValue = null;
        if (value != null && !value.isJsonNull()) {
            strValue = value.getAsString();
        }
        paramMap.put(entry.getKey(), strValue);
    }
    return paramMap;
}

From source file:com.relayrides.pushy.apns.DateAsMillisecondsSinceEpochTypeAdapter.java

License:Open Source License

@Override
public Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
        throws JsonParseException {
    final Date date;

    if (json.isJsonPrimitive()) {
        date = new Date(json.getAsLong());
    } else if (json.isJsonNull()) {
        date = null;/*ww w.j  a v a2s  . c  o m*/
    } else {
        throw new JsonParseException(
                "Dates represented as seconds since the epoch must either be numbers or null.");
    }

    return date;
}

From source file:com.relayrides.pushy.apns.DateAsSecondsSinceEpochTypeAdapter.java

License:Open Source License

@Override
public Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
        throws JsonParseException {
    final Date date;

    if (json.isJsonPrimitive()) {
        date = new Date(json.getAsLong() * 1000);
    } else if (json.isJsonNull()) {
        date = null;/*from  w  ww  .  j a v a2 s . c  om*/
    } else {
        throw new JsonParseException(
                "Dates represented as seconds since the epoch must either be numbers or null.");
    }

    return date;
}

From source file:com.relayrides.pushy.apns.DateAsTimeSinceEpochTypeAdapter.java

License:Open Source License

@Override
public Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
        throws JsonParseException {
    final Date date;

    if (json.isJsonPrimitive()) {
        date = new Date(this.timeUnit.toMillis(json.getAsLong()));
    } else if (json.isJsonNull()) {
        date = null;//from   w  w  w  .ja  v a2s . c o m
    } else {
        throw new JsonParseException(
                "Dates represented as time since the epoch must either be numbers or null.");
    }

    return date;
}