Example usage for com.google.gson JsonArray get

List of usage examples for com.google.gson JsonArray get

Introduction

In this page you can find the example usage for com.google.gson JsonArray get.

Prototype

public JsonElement get(int i) 

Source Link

Document

Returns the ith element of the array.

Usage

From source file:com.couchbase.cbadmin.client.CouchbaseAdmin.java

License:Open Source License

@Override
public List<Node> getNodes() throws RestApiException {
    List<Node> ret = new ArrayList<Node>();
    JsonElement e;//from w  w w  .j a  va 2  s . co m
    try {
        e = getJson(P_POOL_NODES);
    } catch (IOException ex) {
        throw new RestApiException(ex);
    }

    if (!e.isJsonObject()) {
        throw new RestApiException("Expected JsonObject", e);
    }

    JsonObject obj = e.getAsJsonObject();
    JsonArray nodesArr;
    e = obj.get("nodes");

    if (e == null) {
        throw new RestApiException("Expected 'nodes' array", obj);
    }

    nodesArr = e.getAsJsonArray();
    for (int i = 0; i < nodesArr.size(); i++) {
        e = nodesArr.get(i);
        JsonObject nObj;
        if (!e.isJsonObject()) {
            throw new RestApiException("Malformed node entry", e);
        }
        nObj = e.getAsJsonObject();
        Node n = new Node(nObj);
        ret.add(n);
    }

    return ret;
}

From source file:com.createtank.payments.coinbase.CoinbaseApi.java

License:Apache License

/**
 * List bitcoin addresses associated with the current account
 * @param page the page of addresses to retrieve. Can be used to page through results
 * @param limit the maximum number of addresses to retrieve. Can't exceed 1000
 * @param query string match to filter addresses. Matches the address itself and also
 * if the use has set a label on the address.
 * @return the list of bitcoin addresses associated with the current account
 * @throws IOException//from w  ww. j a  v  a2s  .  c o  m
 */
public Address[] getAddresses(int page, int limit, String query) throws IOException {
    Map<String, String> params = new HashMap<String, String>();
    if (apiKey != null)
        params.put("api_key", apiKey);
    params.put("page", Integer.toString(page));
    params.put("limit", Integer.toString(limit));
    if (query != null)
        params.put("query", query);

    JsonObject response = RequestClient.get(this, "addresses", params, accessToken);
    JsonArray addresses = response.getAsJsonArray("addresses");
    int size = addresses.size();
    Address[] result = new Address[size];
    for (int i = 0; i < size; ++i) {
        JsonObject addy = addresses.get(i).getAsJsonObject().getAsJsonObject("address");
        result[i] = Address.fromJson(addy);
    }

    return result;
}

From source file:com.createtank.payments.coinbase.CoinbaseApi.java

License:Apache License

/**
 * List the current user's recent transactions.
 * @param page Used to paginate through results. Thirty transactions are returned per page.
 * @return an array of Transaction objects
 * @throws IOException/*w w w.j  ava 2 s.  c  om*/
 */
public Transaction[] getTransactions(int page) throws IOException {
    Map<String, String> params = new HashMap<String, String>();
    if (apiKey != null)
        params.put("api_key", apiKey);

    params.put("page", Integer.toString(page));
    JsonObject response = RequestClient.get(this, "transactions", params, accessToken);
    JsonArray transactionsJson = response.getAsJsonArray("transactions");
    Transaction[] transactions = new Transaction[transactionsJson.size()];
    for (int i = 0; i < transactionsJson.size(); ++i) {
        JsonObject transactionJson = transactionsJson.get(i).getAsJsonObject().getAsJsonObject("transaction");
        transactions[i] = Transaction.fromJson(transactionJson);
    }

    return transactions;
}

From source file:com.customatics.leaptest_integration_for_bamboo.impl.PluginHandler.java

public boolean getScheduleState(String leaptestAddress, String scheduleId, String scheduleTitle,
        int currentScheduleIndex, String doneStatusValue, BuildLogger buildLogger,
        ScheduleCollection buildResult, ArrayList<InvalidSchedule> invalidSchedules)
        throws InterruptedException {
    boolean isScheduleStillRunning = true;

    String uri = String.format(Messages.GET_SCHEDULE_STATE_URI, leaptestAddress, scheduleId);

    try {//from w  ww.j a  v  a2 s  .co m

        try {

            AsyncHttpClient client = new AsyncHttpClient();
            Response response = client.prepareGet(uri).execute().get();
            client = null;

            switch (response.getStatusCode()) {
            case 200:

                JsonParser parser = new JsonParser();
                JsonObject jsonState = parser.parse(response.getResponseBody()).getAsJsonObject();
                parser = null;

                String ScheduleId = jsonState.get("ScheduleId").getAsString();

                if (isScheduleStillRunning(jsonState))
                    isScheduleStillRunning = true;
                else {
                    isScheduleStillRunning = false;

                    /////////Schedule Info
                    JsonElement jsonLastRun = jsonState.get("LastRun");

                    JsonObject lastRun = jsonLastRun.getAsJsonObject();

                    String ScheduleTitle = lastRun.get("ScheduleTitle").getAsString();

                    buildResult.Schedules.get(currentScheduleIndex)
                            .setTime(parseExecutionTimeToSeconds(lastRun.get("ExecutionTotalTime")));

                    int passedCount = caseStatusCount("PassedCount", lastRun);
                    int failedCount = caseStatusCount("FailedCount", lastRun);
                    int doneCount = caseStatusCount("DoneCount", lastRun);

                    if (doneStatusValue.contentEquals("Failed"))
                        failedCount += doneCount;
                    else
                        passedCount += doneCount;

                    ///////////AutomationRunItemsInfo
                    JsonArray jsonAutomationRunItems = lastRun.get("AutomationRunItems").getAsJsonArray();

                    ArrayList<String> automationRunId = new ArrayList<String>();
                    for (JsonElement jsonAutomationRunItem : jsonAutomationRunItems)
                        automationRunId.add(
                                jsonAutomationRunItem.getAsJsonObject().get("AutomationRunId").getAsString());
                    ArrayList<String> statuses = new ArrayList<String>();
                    for (JsonElement jsonAutomationRunItem : jsonAutomationRunItems)
                        statuses.add(jsonAutomationRunItem.getAsJsonObject().get("Status").getAsString());
                    ArrayList<String> elapsed = new ArrayList<String>();
                    for (JsonElement jsonAutomationRunItem : jsonAutomationRunItems)
                        elapsed.add(
                                defaultElapsedIfNull(jsonAutomationRunItem.getAsJsonObject().get("Elapsed")));
                    ArrayList<String> environments = new ArrayList<String>();
                    for (JsonElement jsonAutomationRunItem : jsonAutomationRunItems)
                        environments.add(jsonAutomationRunItem.getAsJsonObject().get("Environment")
                                .getAsJsonObject().get("Title").getAsString());

                    ArrayList<String> caseTitles = new ArrayList<String>();
                    for (JsonElement jsonAutomationRunItem : jsonAutomationRunItems) {
                        String caseTitle = Utils.defaultStringIfNull(jsonAutomationRunItem.getAsJsonObject()
                                .get("Case").getAsJsonObject().get("Title"), "Null case Title");
                        if (caseTitle.contentEquals("Null case Title"))
                            caseTitles.add(caseTitles.get(caseTitles.size() - 1));
                        else
                            caseTitles.add(caseTitle);
                    }

                    makeCaseTitlesNonRepeatable(caseTitles); //this is required because Bamboo junit reporter does not suppose that there can be 2 or more case with the same name but different results

                    for (int i = 0; i < jsonAutomationRunItems.size(); i++) {

                        //double seconds = jsonArray.getJSONObject(i).getDouble("TotalSeconds");
                        double seconds = parseExecutionTimeToSeconds(elapsed.get(i));

                        buildLogger.addBuildLogEntry(Messages.CASE_CONSOLE_LOG_SEPARATOR);

                        if (statuses.get(i).contentEquals("Failed")
                                || (statuses.get(i).contentEquals("Done")
                                        && doneStatusValue.contentEquals("Failed"))
                                || statuses.get(i).contentEquals("Error")
                                || statuses.get(i).contentEquals("Cancelled")) {
                            if (statuses.get(i).contentEquals("Error")
                                    || statuses.get(i).contentEquals("Cancelled"))
                                failedCount++;

                            JsonArray jsonKeyframes = jsonAutomationRunItems.get(i).getAsJsonObject()
                                    .get("Keyframes").getAsJsonArray();

                            //KeyframeInfo
                            ArrayList<String> keyFrameTimeStamps = new ArrayList<String>();
                            for (JsonElement jsonKeyFrame : jsonKeyframes)
                                keyFrameTimeStamps
                                        .add(jsonKeyFrame.getAsJsonObject().get("Timestamp").getAsString());
                            ArrayList<String> keyFrameLogMessages = new ArrayList<String>();
                            for (JsonElement jsonKeyFrame : jsonKeyframes)
                                keyFrameLogMessages
                                        .add(jsonKeyFrame.getAsJsonObject().get("LogMessage").getAsString());

                            buildLogger.addBuildLogEntry(String.format(Messages.CASE_INFORMATION,
                                    caseTitles.get(i), statuses.get(i), elapsed.get(i)));

                            String fullstacktrace = "";
                            int currentKeyFrameIndex = 0;

                            for (JsonElement jsonKeyFrame : jsonKeyframes) {
                                String level = Utils
                                        .defaultStringIfNull(jsonKeyFrame.getAsJsonObject().get("Level"), "");
                                if (!level.contentEquals("") && !level.contentEquals("Trace")) {
                                    String stacktrace = String.format(Messages.CASE_STACKTRACE_FORMAT,
                                            keyFrameTimeStamps.get(currentKeyFrameIndex),
                                            keyFrameLogMessages.get(currentKeyFrameIndex));
                                    buildLogger.addBuildLogEntry(stacktrace);
                                    fullstacktrace += stacktrace;
                                    fullstacktrace += "&#xA;"; //fullstacktrace += '\n';
                                }

                                currentKeyFrameIndex++;
                            }

                            fullstacktrace += "Environment: " + environments.get(i);
                            buildLogger.addBuildLogEntry("Environment: " + environments.get(i));
                            buildResult.Schedules.get(currentScheduleIndex).Cases
                                    .add(new Case(caseTitles.get(i), statuses.get(i), seconds, fullstacktrace,
                                            ScheduleTitle/* + "[" + ScheduleId + "]"*/));
                        } else {
                            buildLogger.addBuildLogEntry(String.format(Messages.CASE_INFORMATION,
                                    caseTitles.get(i), statuses.get(i), elapsed.get(i)));
                            buildResult.Schedules.get(currentScheduleIndex).Cases
                                    .add(new Case(caseTitles.get(i), statuses.get(i), seconds,
                                            ScheduleTitle/* + "[" + ScheduleId + "]"*/));
                        }
                    }

                    buildResult.Schedules.get(currentScheduleIndex).setPassed(passedCount);
                    buildResult.Schedules.get(currentScheduleIndex).setFailed(failedCount);

                    if (buildResult.Schedules.get(currentScheduleIndex).getFailed() > 0)
                        buildResult.Schedules.get(currentScheduleIndex).setStatus("Failed");
                    else
                        buildResult.Schedules.get(currentScheduleIndex).setStatus("Passed");
                }
                break;

            case 404:
                String errorMessage404 = String.format(Messages.ERROR_CODE_MESSAGE, response.getStatusCode(),
                        response.getStatusText());
                errorMessage404 += String.format("\n%1$s",
                        String.format(Messages.NO_SUCH_SCHEDULE_WAS_FOUND, scheduleTitle, scheduleId));
                throw new Exception(errorMessage404);

            case 445:
                String errorMessage445 = String.format(Messages.ERROR_CODE_MESSAGE, response.getStatusCode(),
                        response.getStatusText());
                errorMessage445 += String.format("\n%1$s", Messages.LICENSE_EXPIRED);
                throw new InterruptedException(errorMessage445);

            case 448:
                String errorMessage448 = String.format(Messages.ERROR_CODE_MESSAGE, response.getStatusCode(),
                        response.getStatusText());
                errorMessage448 += String.format("\n%1$s",
                        String.format(Messages.CACHE_TIMEOUT_EXCEPTION, scheduleTitle, scheduleId));
                isScheduleStillRunning = true;
                buildLogger.addErrorLogEntry(errorMessage448);
                break;

            case 500:
                String errorMessage500 = String.format(Messages.ERROR_CODE_MESSAGE, response.getStatusCode(),
                        response.getStatusText());
                errorMessage500 += String.format("\n%1$s", Messages.CONTROLLER_RESPONDED_WITH_ERRORS);
                throw new Exception(errorMessage500);

            default:
                String errorMessage = String.format(Messages.ERROR_CODE_MESSAGE, response.getStatusCode(),
                        response.getStatusText());
                throw new Exception(errorMessage);
            }

        } catch (NoRouteToHostException e) {
            String connectionLostErrorMessage = String.format(Messages.CONNECTION_LOST,
                    e.getCause().getMessage());
            buildLogger.addErrorLogEntry(connectionLostErrorMessage);
            return true;
        } catch (ConnectException | UnknownHostException e) {
            String connectionErrorMessage = String.format(Messages.COULD_NOT_CONNECT_TO_BUT_WAIT,
                    e.getMessage());
            buildLogger.addErrorLogEntry(connectionErrorMessage);
            return true;
        } catch (ExecutionException e) {
            if (e.getCause() instanceof ConnectException || e.getCause() instanceof UnknownHostException) {
                String connectionErrorMessage = String.format(Messages.COULD_NOT_CONNECT_TO_BUT_WAIT,
                        e.getCause().getMessage());
                buildLogger.addErrorLogEntry(connectionErrorMessage);
                return true;
            } else if (e.getCause() instanceof NoRouteToHostException) {
                String connectionLostErrorMessage = String.format(Messages.CONNECTION_LOST,
                        e.getCause().getMessage());
                buildLogger.addErrorLogEntry(connectionLostErrorMessage);
                return true;
            } else {
                String executionExceptionMessage = String.format(Messages.EXECUTION_EXCEPTION, e.getMessage());
                throw new Exception(executionExceptionMessage);
            }

        } catch (IOException e) {
            String ioExceptionMessage = String.format(Messages.IO_EXCEPTION, e.getMessage());
            throw new Exception(ioExceptionMessage);
        } catch (Exception e) {
            throw e;
        }
    } catch (InterruptedException e) {
        throw new InterruptedException(e.getMessage());
    } catch (Exception e) {
        String errorMessage = String.format(Messages.SCHEDULE_STATE_FAILURE, scheduleTitle, scheduleId);
        buildLogger.addErrorLogEntry(errorMessage);
        buildLogger.addErrorLogEntry(e.getMessage());
        buildLogger.addErrorLogEntry(Messages.PLEASE_CONTACT_SUPPORT);
        buildResult.Schedules.get(currentScheduleIndex)
                .setError(String.format("%1$s\n%2$s", errorMessage, e.getMessage()));
        buildResult.Schedules.get(currentScheduleIndex).incErrors();
        invalidSchedules
                .add(new InvalidSchedule(String.format(Messages.SCHEDULE_FORMAT, scheduleTitle, scheduleId),
                        buildResult.Schedules.get(currentScheduleIndex).getError()));
        return false;
    }

    return isScheduleStillRunning;
}

From source file:com.denimgroup.threadfix.cli.util.JsonTestUtils.java

License:Mozilla Public License

public static <T> void assertHasArrayOfObjectsWithFields(RestResponse<T> restResponse, String objectKey,
        String... fields) {/*w w  w.  j a  v  a  2s.c  o  m*/

    assert getJsonObject(restResponse) != null : "Failed to parse RestResponse from data: "
            + restResponse.getOriginalJson();
    assert getJsonObject(restResponse).getAsJsonObject("object")
            .getAsJsonArray(objectKey) != null : "Failed to retrieve object for key object." + objectKey
                    + " in object " + restResponse.getOriginalJson();
    JsonArray jsonArray = getJsonObject(restResponse).getAsJsonObject("object").getAsJsonArray(objectKey);

    assert jsonArray != null;

    innerValidate(jsonArray.get(0).getAsJsonObject(), fields);

}

From source file:com.denimgroup.threadfix.cli.util.JsonTestUtils.java

License:Mozilla Public License

public static <T> void assertIsArrayWithFields(RestResponse<T> restResponse, String... fields) {
    JsonArray jsonArray = getJsonObject(restResponse).getAsJsonArray("object");

    assert getJsonObject(restResponse) != null : "Failed to parse RestResponse from data: "
            + restResponse.getOriginalJson();

    assert jsonArray != null : "Unable to parse array from " + restResponse.getOriginalJson();

    innerValidate(jsonArray.get(0).getAsJsonObject(), fields);
}

From source file:com.devamatre.core.JSONHelper.java

License:Open Source License

/**
 * Returns the list of the specified objects from the given JSON string.
 * /*from w w  w  .  ja v  a 2  s. com*/
 * @param jsonString
 * @param classType
 * @return
 */
public static <T> List<T> listOfObjects(String jsonString, Class<T> classType) {
    List<T> objects = new ArrayList<T>();
    JsonArray jsonArray = toJSONArray(jsonString);
    if (jsonArray != null) {
        for (int i = 0; i < jsonArray.size(); i++) {
            Gson gson = new Gson();
            T object = gson.fromJson(jsonArray.get(i), classType);
            objects.add(object);
        }
    }

    return objects;
}

From source file:com.devamatre.core.JSONHelper.java

License:Open Source License

/**
 * Returns the list of the specified objects from the given JSON string.
 * /*from ww  w.  ja  va  2  s .co m*/
 * @param jsonString
 * @param classType
 * @return
 */
public static List<?> listOfObjects(String jsonString, String key, Class<?>... classTypes) {
    List<Object> mixedObjects = new ArrayList<Object>();
    if (jsonString == null || !isValidJSONString(jsonString)) {
        return mixedObjects;
    }

    JsonArray jsonArray = toJSONArray(jsonString);
    if (jsonArray != null) {
        for (int i = 0; i < jsonArray.size(); i++) {
            String objectJSONString = toJSONString(jsonArray.get(i));
            for (int j = 0; j < classTypes.length; j++) {
                String value = (String) toMap(objectJSONString).get(key);
                if (value.equalsIgnoreCase(classTypes[j].getSimpleName())) {
                    Object object = fromJSONString(objectJSONString, classTypes[j]);
                    mixedObjects.add(object);
                    break;
                }
            }
        }
    }

    return mixedObjects;
}

From source file:com.devamatre.core.JSONHelper.java

License:Open Source License

/**
 * Returns the value for the given key from the given jsonArray.
 * /*from   w w w .jav  a 2 s  .co  m*/
 * @param jsonArray
 * @param key
 * @return
 */
public static String valueForKeyAsString(JsonArray jsonArray, String key) {
    String value = null;
    if (jsonArray != null && !CoreHelper.isNullOrEmpty(key)) {
        for (int i = 0; i < jsonArray.size(); i++) {
            JsonObject jsonObject = (JsonObject) jsonArray.get(i);
            if (jsonObject != null && getAsString(jsonObject, "name").equals(key)) {
                value = getAsString(jsonObject, "value");
                break;
            }
        }
    }

    return value;
}

From source file:com.devnexus.ting.web.controller.AndroidLoginController.java

License:Open Source License

@RequestMapping(path = "/s/user-schedule", method = { RequestMethod.POST, RequestMethod.PUT })
public List<UserScheduleItem> updateUserScheduleCurrentEvent(HttpServletRequest request) {

    try {//from  w w  w  . j a  v  a  2  s . co m
        String accessToken = request.getHeader("authToken");

        User user;
        user = (User) userService.loadUserByAndroidToken(accessToken);

        JsonArray presentaitonIds = new JsonParser().parse(request.getReader()).getAsJsonArray();
        List<UserScheduleItem> scheduleItems = new ArrayList<>(presentaitonIds.size());

        for (int index = 0; index < presentaitonIds.size(); index++) {
            UserScheduleItem item = new UserScheduleItem();

            item.setUser(user);
            item.setScheduleItem(
                    businessService.getPresentation(presentaitonIds.get(index).getAsLong()).getScheduleItem());
            scheduleItems.add(item);
        }

        calendarServices.replaceScheduleItemsForUser(user, scheduleItems);
        return businessService.getUserScheduleItemsForCurrentEventForUser(user);
    } catch (IOException ex) {
        Logger.getLogger(AndroidLoginController.class.getName()).log(Level.SEVERE, null, ex);
        throw new RuntimeException(ex);
    }
}