Example usage for com.google.gson JsonElement getAsJsonObject

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

Introduction

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

Prototype

public JsonObject getAsJsonObject() 

Source Link

Document

convenience method to get this element as a JsonObject .

Usage

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

public HashMap<String, String> getSchedulesIdTitleHashMap(String leaptestAddress,
        ArrayList<String> rawScheduleList, BuildLogger buildLogger, ScheduleCollection buildResult,
        ArrayList<InvalidSchedule> invalidSchedules) throws Exception {

    HashMap<String, String> schedulesIdTitleHashMap = new HashMap<>();

    String scheduleListUri = String.format(Messages.GET_ALL_AVAILABLE_SCHEDULES_URI, leaptestAddress);

    try {//from w ww .ja  v a2  s. c  o  m

        try {

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

            switch (response.getStatusCode()) {
            case 200:
                JsonParser parser = new JsonParser();
                JsonArray jsonScheduleList = parser.parse(response.getResponseBody()).getAsJsonArray();

                for (String rawSchedule : rawScheduleList) {
                    boolean successfullyMapped = false;
                    for (JsonElement jsonScheduleElement : jsonScheduleList) {
                        JsonObject jsonSchedule = jsonScheduleElement.getAsJsonObject();

                        String Id = Utils.defaultStringIfNull(jsonSchedule.get("Id"), "null Id");
                        String Title = Utils.defaultStringIfNull(jsonSchedule.get("Title"), "null Title");

                        if (Id.contentEquals(rawSchedule)) {
                            if (!schedulesIdTitleHashMap.containsValue(Title)) {
                                schedulesIdTitleHashMap.put(rawSchedule, Title);
                                buildResult.Schedules.add(new Schedule(rawSchedule, Title));
                                buildLogger.addBuildLogEntry(
                                        String.format(Messages.SCHEDULE_DETECTED, Title, rawSchedule));
                            }
                            successfullyMapped = true;
                        }

                        if (Title.contentEquals(rawSchedule)) {
                            if (!schedulesIdTitleHashMap.containsKey(Id)) {
                                schedulesIdTitleHashMap.put(Id, rawSchedule);
                                buildResult.Schedules.add(new Schedule(Id, rawSchedule));
                                buildLogger.addBuildLogEntry(
                                        String.format(Messages.SCHEDULE_DETECTED, rawSchedule, Title));
                            }
                            successfullyMapped = true;
                        }
                    }

                    if (!successfullyMapped)
                        invalidSchedules.add(new InvalidSchedule(rawSchedule, Messages.NO_SUCH_SCHEDULE));
                }
                break;

            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 Exception(errorMessage445);

            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 (ConnectException | UnknownHostException e) {
            String connectionErrorMessage = String.format(Messages.COULD_NOT_CONNECT_TO, e.getMessage());
            throw new Exception(connectionErrorMessage);
        } catch (InterruptedException e) {
            String interruptedExceptionMessage = String.format(Messages.INTERRUPTED_EXCEPTION, e.getMessage());
            throw new Exception(interruptedExceptionMessage);
        } catch (ExecutionException e) {
            if (e.getCause() instanceof ConnectException || e.getCause() instanceof UnknownHostException) {
                String connectionErrorMessage = String.format(Messages.COULD_NOT_CONNECT_TO,
                        e.getCause().getMessage());
                throw new Exception(connectionErrorMessage);
            } 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) {
        buildLogger.addErrorLogEntry(Messages.SCHEDULE_TITLE_OR_ID_ARE_NOT_GOT);
        throw e;
    }

    return schedulesIdTitleHashMap;
}

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 va2 s. c o  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.cybozu.kintone.database.JsonParser.java

License:Apache License

/**
 * Converts the json string to the resultset object.
 * @param con/*from  w  ww  .  j a  v  a  2  s.c om*/
 *            a connection object
 * @param json
 *            a json string
 * @return resultset object
 * @throws IOException
 */
public ResultSet jsonToResultSet(Connection con, String json) throws IOException {

    ResultSet rs = new ResultSet(con);
    com.google.gson.JsonParser parser = new com.google.gson.JsonParser();
    JsonElement root = parser.parse(json);

    if (root.isJsonObject()) {
        JsonObject rootObject = root.getAsJsonObject();
        JsonArray records = rootObject.get("records").getAsJsonArray();
        for (JsonElement elem : records) {
            Record record = readRecord(elem);
            if (record != null) {
                rs.add(record);
            }
        }

        if (!rootObject.get("totalCount").isJsonNull()) {
            rs.setTotalCount(rootObject.get("totalCount").getAsLong());

        }
    }

    return rs;
}

From source file:com.cybozu.kintone.database.JsonParser.java

License:Apache License

/**
 * Reads and parses each record element.
 * @param elem// w  ww.ja  v a 2s. co  m
 *            a json element represents a record object
 * @return the record object created
 * @throws IOException
 */
private Record readRecord(JsonElement elem) throws IOException {

    Record record = new Record();

    if (elem.isJsonObject()) {
        JsonObject obj = elem.getAsJsonObject();
        Set<Map.Entry<String, JsonElement>> set = obj.entrySet();
        for (Map.Entry<String, JsonElement> entry : set) {
            Field field = readField(entry.getKey(), entry.getValue());
            if (field != null) {
                record.addField(field.getName(), field);
            }
        }
    }

    return record;
}

From source file:com.cybozu.kintone.database.JsonParser.java

License:Apache License

/**
 * Reads and parses each field element./*from   w ww  .  ja  v a 2  s . co m*/
 * @param fieldName
 *            the field name
 * @param elem
 *            a json element represents a record object
 * @return the field object created
 * @throws IOException
 */
private Field readField(String fieldName, JsonElement fieldElem) throws IOException {

    Field field = null;

    if (!fieldElem.isJsonObject())
        return null;
    JsonObject obj = fieldElem.getAsJsonObject();

    FieldType type = FieldType.getEnum(obj.get("type").getAsString());
    JsonElement element = obj.get("value");

    Object object = null;
    String strVal = null;
    if (type == null || element == null)
        return null;

    if (!element.isJsonNull()) {
        switch (type) {
        case SINGLE_LINE_TEXT:
        case CALC:
        case MULTI_LINE_TEXT:
        case RICH_TEXT:
        case RADIO_BUTTON:
        case DROP_DOWN:
        case LINK:
        case STATUS:
        case RECORD_NUMBER:
        case NUMBER:
            object = element.getAsString();
            break;
        case __ID__:
        case __REVISION__:
            strVal = element.getAsString();
            try {
                object = Long.valueOf(strVal);
            } catch (NumberFormatException e) {
            }
            break;
        case DATE:
        case TIME:
        case DATETIME:
        case CREATED_TIME:
        case UPDATED_TIME:
            object = element.getAsString();
            break;
        case CHECK_BOX:
        case MULTI_SELECT:
        case CATEGORY:
            object = jsonToStringArray(element);
            break;
        case FILE:
            object = jsonToFileArray(element);
            break;
        case CREATOR:
        case MODIFIER:
            if (element.isJsonObject()) {
                Gson gson = new Gson();
                object = gson.fromJson(element, UserDto.class);
            }
            break;
        case USER_SELECT:
        case STATUS_ASSIGNEE:
            object = jsonToUserArray(element);
            break;
        case SUBTABLE:
            object = jsonToSubtable(element);
            break;
        }
    }
    field = new Field(fieldName, type, object);

    return field;
}

From source file:com.cybozu.kintone.database.JsonParser.java

License:Apache License

/**
 * Converts json element to the sub table object.
 * @param element json element//from   ww w .j a va 2 s. c o  m
 * @return sub table object
 * @throws IOException
 */
private List<Record> jsonToSubtable(JsonElement element) throws IOException {
    List<Record> rs = new ArrayList<Record>();

    if (!element.isJsonArray())
        return null;

    JsonArray records = element.getAsJsonArray();
    for (JsonElement elem : records) {
        if (elem.isJsonObject()) {
            JsonObject obj = elem.getAsJsonObject();
            String id = obj.get("id").getAsString();
            JsonElement value = obj.get("value");
            Record record = readRecord(value);
            if (record != null) {
                try {
                    record.setId(Long.valueOf(id));
                } catch (NumberFormatException e) {
                }
                rs.add(record);
            }
        }
    }

    return rs;
}

From source file:com.cybozu.kintone.database.JsonParser.java

License:Apache License

/**
 * Retrieves the array of the ids from json string.
 * @param json/*from   w ww. j av a  2s  .c om*/
 *            a json string
 * @return the array of the id
 * @throws IOException
 */
public List<Long> jsonToIDs(String json) throws IOException {
    com.google.gson.JsonParser parser = new com.google.gson.JsonParser();
    JsonElement root = parser.parse(json);

    List<Long> ids = new ArrayList<Long>();
    if (root.isJsonObject()) {
        JsonArray jsonIds = root.getAsJsonObject().get("ids").getAsJsonArray();
        for (JsonElement elem : jsonIds) {
            Long id = new Long(elem.getAsString());
            ids.add(id);
        }
    }

    return ids;
}

From source file:com.cybozu.kintone.database.JsonParser.java

License:Apache License

/**
 * Retrieves the file key string from json string.
 * @param json//  ww w  . j ava  2  s .  com
 *            a json string
 * @return the file key
 * @throws IOException
 */
public String jsonToFileKey(String json) throws IOException {
    com.google.gson.JsonParser parser = new com.google.gson.JsonParser();
    JsonElement root = parser.parse(json);

    String fileKey = null;
    if (root.isJsonObject()) {
        fileKey = root.getAsJsonObject().get("fileKey").getAsString();
    }

    return fileKey;
}

From source file:com.cybozu.kintone.database.JsonParser.java

License:Apache License

/**
 * Retrieves the revision string from json string.
 * @param json/*  w  w  w  . ja  va2s .c  om*/
 *            a json string
 * @return the revision number
 * @throws IOException
 */
public long jsonToRevision(String json) throws IOException {
    com.google.gson.JsonParser parser = new com.google.gson.JsonParser();
    JsonElement root = parser.parse(json);

    String revision = null;
    if (root.isJsonObject()) {
        revision = root.getAsJsonObject().get("revision").getAsString();
    }

    return Long.valueOf(revision);
}

From source file:com.cybozu.kintone.database.JsonParser.java

License:Apache License

/**
 * Retrieves the id string from json string.
 * @param json/* ww  w.j av  a  2s .  c o  m*/
 *            a json string
 * @return the id number
 * @throws IOException
 */
public long jsonToId(String json) throws IOException {
    com.google.gson.JsonParser parser = new com.google.gson.JsonParser();
    JsonElement root = parser.parse(json);

    String id = null;
    if (root.isJsonObject()) {
        id = root.getAsJsonObject().get("id").getAsString();
    }

    return Long.valueOf(id);
}