Example usage for com.google.gson JsonParser JsonParser

List of usage examples for com.google.gson JsonParser JsonParser

Introduction

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

Prototype

@Deprecated
public JsonParser() 

Source Link

Usage

From source file:com.crypticbit.diff.demo.swing.contacts.JsonEditPanel.java

License:Apache License

/**
 * Replaces the current tree structure in the contained JTree component with a new structure built from the JSON
 * string provided.//from   ww  w. j ava 2  s  .co  m
 * 
 * @param json
 *            - the JSON to update the tree control with
 * @param updateType
 *            - if a node is selected when this method is called then the updateType indicates where the new json
 *            goes: REPLACE - replace current selected node with new JSON INSERT - place node before selected node
 *            APPEND - place node after selected node AS_CHILD - append to end of child nodes or insert new child
 *            node if no children present. Selected node must be of type ARRAY or OBJECT
 */
@SuppressWarnings("unchecked")
public void setJson(String json, UpdateType updateType) {
    TreePath selection = jTree.getSelectionPath();
    if (selection == null) {
        if (updateType == UpdateType.REPLACE) {
            JsonElement root = new JsonParser().parse(json);
            JsonJTreeNode rootNode = new JsonJTreeNode(null, -1, root);
            jTree.setModel(new DefaultTreeModel(rootNode));
        } else {
            JOptionPane.showMessageDialog(this,
                    "Only replace JSON and get JSON are supported when no node is selected.", "Notice",
                    JOptionPane.INFORMATION_MESSAGE);
        }
    } else {
        JsonJTreeNode selectedNode = (JsonJTreeNode) selection.getLastPathComponent();
        JsonJTreeNode parent = (JsonJTreeNode) selectedNode.getParent();
        switch (updateType) {
        case REPLACE: {
            if (parent == null) {
                JsonElement root = new JsonParser().parse(json);
                JsonJTreeNode rootNode = new JsonJTreeNode(null, -1, root);
                jTree.setModel(new DefaultTreeModel(rootNode));
                return;
            }
            JsonElement root = new JsonParser().parse(json);
            JsonJTreeNode replacementNode = new JsonJTreeNode(selectedNode.fieldName, selectedNode.index, root);
            int index = selectedNode.getParent().getIndex(selectedNode);
            selectedNode.removeFromParent();
            parent.insert(replacementNode, index);
            ((DefaultTreeModel) jTree.getModel()).reload(parent);
        }
            break;
        case INSERT:
        case APPEND: {
            if (parent == null) {
                JOptionPane.showMessageDialog(this, "You cannot append to the root element.", "Notice",
                        JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            JsonElement root = new JsonParser().parse(json);
            JsonJTreeNode replacementNode = new JsonJTreeNode(selectedNode.fieldName, selectedNode.index, root);
            int index = selectedNode.getParent().getIndex(selectedNode);
            if (updateType.equals(UpdateType.APPEND)) {
                index++;
            }
            parent.insert(replacementNode, index);
            ((DefaultTreeModel) jTree.getModel()).reload(parent);
        }
            break;
        case AS_CHILD: {
            JsonElement root = new JsonParser().parse(json);
            String fieldName = null;
            int arrayIndex = -1;
            if (selectedNode.dataType.equals(JsonJTreeNode.DataType.ARRAY)) {
                Enumeration en = selectedNode.children();
                int count = 0;
                while (en.hasMoreElements()) {
                    en.nextElement();
                    count++;
                }
                arrayIndex = count;
            } else if (selectedNode.dataType.equals(JsonJTreeNode.DataType.OBJECT)) {
                fieldName = "new-field";
            } else {
                JOptionPane.showMessageDialog(this, "Vaue type entities can not have children.", "Notice",
                        JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            JsonJTreeNode newNode = new JsonJTreeNode(fieldName, arrayIndex, root);
            selectedNode.add(newNode);
            ((DefaultTreeModel) jTree.getModel()).reload(selectedNode);
        }
            break;
        }
    }
}

From source file:com.crypticbit.diff.demo.swing.contacts.JsonJTreeNode.java

License:Apache License

public JsonElement asJsonElement() {
    StringBuilder sb = new StringBuilder();
    buildJsonString(sb);/*from  w  w w .j  a v a2 s . c  o  m*/
    String json = sb.toString().trim();
    if (json.startsWith("{") || json.startsWith("[")) {
        return new JsonParser().parse(sb.toString());
    } else {
        // Safety check the JSON, if it is of a named value object
        // We cheat a little if it is an orphan name value pair then
        // if we wrap it in {} chars it will parse if it isn't the parse
        // fails.
        String testValue = "{" + json + "}";
        try {
            JsonElement wrapperElt = new JsonParser().parse(testValue);
            JsonObject obj = (JsonObject) wrapperElt;
            Iterator<Entry<String, JsonElement>> it = obj.entrySet().iterator();
            Entry<String, JsonElement> entry = it.next();
            return entry.getValue();
        } catch (JsonSyntaxException jse) {
            JsonElement rawElement = new JsonParser().parse(json);
            return rawElement;
        }
    }
}

From source file:com.crypticbit.diff.demo.swing.contacts.JsonJTreeNode.java

License:Apache License

@SuppressWarnings("unchecked")
private void buildJsonString(StringBuilder sb) {
    if (!(this.fieldName == null || this.fieldName.length() == 0)) {
        sb.append("\"" + this.fieldName + "\":");
    }//from www  . j  a  v  a  2 s. c om
    Enumeration children;
    switch (dataType) {
    case ARRAY:
        sb.append("[");
        children = this.children();
        while (children.hasMoreElements()) {
            JsonJTreeNode child = (JsonJTreeNode) children.nextElement();
            child.buildJsonString(sb);
            if (children.hasMoreElements()) {
                sb.append(",");
            }
        }
        sb.append("]");
        break;
    case OBJECT:
        sb.append("{");
        children = this.children();
        while (children.hasMoreElements()) {
            JsonJTreeNode child = (JsonJTreeNode) children.nextElement();
            child.buildJsonString(sb);
            if (children.hasMoreElements()) {
                sb.append(",");
            }
        }
        sb.append("}");
        break;
    default: {
        // Use the JSON parser to parse the value for safety
        JsonElement elt = new JsonParser().parse(this.value);
        sb.append(elt.toString());
    }
    }
}

From source file:com.crypticbit.diff.demo.swing.JSONEditPanel.java

License:Apache License

/**
 * Replaces the current tree structure in the contained JTree component with a new structure built from the JSON
 * string provided./*from  w  ww .  j a  va  2 s  .co  m*/
 * 
 * @param json
 *            - the JSON to update the tree control with
 * @param updateType
 *            - if a node is selected when this method is called then the updateType indicates where the new json
 *            goes: REPLACE - replace current selected node with new JSON INSERT - place node before selected node
 *            APPEND - place node after selected node AS_CHILD - append to end of child nodes or insert new child
 *            node if no children present. Selected node must be of type ARRAY or OBJECT
 */
@SuppressWarnings("unchecked")
public void setJson(String json, UpdateType updateType) {
    TreePath selection = jTree.getSelectionPath();
    if (selection == null) {
        if (updateType == UpdateType.REPLACE) {
            JsonElement root = new JsonParser().parse(json);
            JSONJTreeNode rootNode = new JSONJTreeNode(null, -1, root);
            jTree.setModel(new DefaultTreeModel(rootNode));
        } else {
            JOptionPane.showMessageDialog(this,
                    "Only replace JSON and get JSON are supported when no node is selected.", "Notice",
                    JOptionPane.INFORMATION_MESSAGE);
        }
    } else {
        JSONJTreeNode selectedNode = (JSONJTreeNode) selection.getLastPathComponent();
        JSONJTreeNode parent = (JSONJTreeNode) selectedNode.getParent();
        switch (updateType) {
        case REPLACE: {
            if (parent == null) {
                JsonElement root = new JsonParser().parse(json);
                JSONJTreeNode rootNode = new JSONJTreeNode(null, -1, root);
                jTree.setModel(new DefaultTreeModel(rootNode));
                return;
            }
            JsonElement root = new JsonParser().parse(json);
            JSONJTreeNode replacementNode = new JSONJTreeNode(selectedNode.fieldName, selectedNode.index, root);
            int index = selectedNode.getParent().getIndex(selectedNode);
            selectedNode.removeFromParent();
            parent.insert(replacementNode, index);
            ((DefaultTreeModel) jTree.getModel()).reload(parent);
        }
            break;
        case INSERT:
        case APPEND: {
            if (parent == null) {
                JOptionPane.showMessageDialog(this, "You cannot append to the root element.", "Notice",
                        JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            JsonElement root = new JsonParser().parse(json);
            JSONJTreeNode replacementNode = new JSONJTreeNode(selectedNode.fieldName, selectedNode.index, root);
            int index = selectedNode.getParent().getIndex(selectedNode);
            if (updateType.equals(UpdateType.APPEND)) {
                index++;
            }
            parent.insert(replacementNode, index);
            ((DefaultTreeModel) jTree.getModel()).reload(parent);
        }
            break;
        case AS_CHILD: {
            JsonElement root = new JsonParser().parse(json);
            String fieldName = null;
            int arrayIndex = -1;
            if (selectedNode.dataType.equals(JSONJTreeNode.DataType.ARRAY)) {
                Enumeration en = selectedNode.children();
                int count = 0;
                while (en.hasMoreElements()) {
                    en.nextElement();
                    count++;
                }
                arrayIndex = count;
            } else if (selectedNode.dataType.equals(JSONJTreeNode.DataType.OBJECT)) {
                fieldName = "new-field";
            } else {
                JOptionPane.showMessageDialog(this, "Vaue type entities can not have children.", "Notice",
                        JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            JSONJTreeNode newNode = new JSONJTreeNode(fieldName, arrayIndex, root);
            selectedNode.add(newNode);
            ((DefaultTreeModel) jTree.getModel()).reload(selectedNode);
        }
            break;
        }
    }
}

From source file:com.crypticbit.diff.demo.swing.JSONJTreeNode.java

License:Apache License

@SuppressWarnings("unchecked")
private void buildJsonString(StringBuilder sb) {
    if (!(this.fieldName == null || this.fieldName.length() == 0)) {
        sb.append("\"" + this.fieldName + "\":");
    }// w ww  .j  a va 2  s. c o m
    Enumeration children;
    switch (dataType) {
    case ARRAY:
        sb.append("[");
        children = this.children();
        while (children.hasMoreElements()) {
            JSONJTreeNode child = (JSONJTreeNode) children.nextElement();
            child.buildJsonString(sb);
            if (children.hasMoreElements()) {
                sb.append(",");
            }
        }
        sb.append("]");
        break;
    case OBJECT:
        sb.append("{");
        children = this.children();
        while (children.hasMoreElements()) {
            JSONJTreeNode child = (JSONJTreeNode) children.nextElement();
            child.buildJsonString(sb);
            if (children.hasMoreElements()) {
                sb.append(",");
            }
        }
        sb.append("}");
        break;
    default: {
        // Use the JSON parser to parse the value for safety
        JsonElement elt = new JsonParser().parse(this.value);
        sb.append(elt.toString());
    }
    }
}

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  . j a v a 2  s .  c om*/

        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 {// ww w  .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.daa.verifier.Models.Verifier.java

/**
 * Turns a revocation list as JSON object into a set of big integers
 * @param json the revocation list as a JSON object
 * @param curve the curve used//from  ww  w.  j  a  v a 2s .  c  om
 * @return the revocation list as a Set<BigInteger>
 */
public static Set<BigInteger> revocationListFromJson(String json, BNCurve curve) {
    Base64.Decoder decoder = Base64.getUrlDecoder();

    JsonArray object = new JsonParser().parse(json).getAsJsonObject().getAsJsonArray(JSON_REVOCATION_LIST);
    Set<BigInteger> rl = new HashSet<BigInteger>(object.size());
    for (JsonElement element : object) {
        rl.add(curve.bigIntegerFromB(
                decoder.decode(element.getAsJsonObject().get(JSON_REVOCATION_LIST_ENTRY).getAsString())));
    }
    return rl;
}

From source file:com.daking.sports.api.HttpLoggingInterceptor.java

License:Apache License

private String format2UTF8(String text) {
    try {//w  ww .ja  va2s  .  c o  m
        JsonElement jsonElement = new JsonParser().parse(text);
        return jsonElement.toString();
    } catch (Exception e) {
        return text;
    }
}

From source file:com.dangdang.ddframe.job.cloud.scheduler.mesos.fixture.master.MesosMasterServerMock.java

License:Apache License

@GET
@Path("/state")
public JsonObject state() throws JSONException {
    return (JsonObject) new JsonParser().parse(
            "{\"version\":\"1.1.0\",\"build_date\":\"2017-02-27 10:51:31\",\"build_time\":1488163891.0,\"build_user\":\"gaohongtao\",\"start_time\""
                    + ":1488179758.62289,\"elected_time\":1488179758.69795,\"id\":\"d8701508-41b7-471e-9b32-61cf824a660d\",\"pid\":\"master@127.0.0.1:9050\",\"hostname\":\"127.0.0.1\","
                    + "\"activated_slaves\":1.0,\"deactivated_slaves\":0.0,\"leader\":\"master@127.0.0.1:9050\",\"leader_info\":{\"id\":\"d8701508-41b7-471e-9b32-61cf824a660d\","
                    + "\"pid\":\"master@127.0.0.1:9050\",\"port\":9050,\"hostname\":\"127.0.0.1\"},\"flags\":{\"agent_ping_timeout\":\"15secs\",\"agent_reregister_timeout\":\"10mins\","
                    + "\"allocation_interval\":\"1secs\",\"allocator\":\"HierarchicalDRF\",\"authenticate_agents\":\"false\",\"authenticate_frameworks\":\"false\","
                    + "\"authenticate_http_frameworks\":\"false\",\"authenticate_http_readonly\":\"false\",\"authenticate_http_readwrite\":\"false\",\"authenticators\":\"crammd5\","
                    + "\"authorizers\":\"local\",\"framework_sorter\":\"drf\",\"help\":\"false\",\"hostname_lookup\":\"true\",\"http_authenticators\":\"basic\","
                    + "\"initialize_driver_logging\":\"true\",\"ip\":\"127.0.0.1\",\"log_auto_initialize\":\"true\",\"logbufsecs\":\"0\",\"logging_level\":\"INFO\",\"max_agent_ping_timeouts\":\"5\","
                    + "\"max_completed_frameworks\":\"50\",\"max_completed_tasks_per_framework\":\"1000\",\"port\":\"9050\",\"quiet\":\"false\",\"quorum\":\"1\",\"recovery_agent_removal_limit\":\"100%\","
                    + "\"registry\":\"replicated_log\",\"registry_fetch_timeout\":\"1mins\",\"registry_gc_interval\":\"15mins\",\"registry_max_agent_age\":\"2weeks\",\"registry_max_agent_count\""
                    + ":\"102400\",\"registry_store_timeout\":\"20secs\",\"registry_strict\":\"false\",\"root_submissions\":\"true\",\"user_sorter\":\"drf\",\"version\":\"false\",\"webui_dir\":\"\\/home"
                    + "\\/gaohongtao\\/mesos\\/mesos-1.1.0\\/build\\/..\\/src\\/webui\",\"work_dir\":\"\\/home\\/gaohongtao\\/mesos\\/work-1.1.0\",\"zk\":\"zk:\\/\\/localhost:4181,\\/mesos\","
                    + "\"zk_session_timeout\":\"10secs\"},\"slaves\":[{\"id\":\"d8701508-41b7-471e-9b32-61cf824a660d-S0\",\"pid\":\"slave(1)@127.0.0.1:9051\",\"hostname\":\"127.0.0.1\","
                    + "\"registered_time\":1488179768.08728,\"resources\":{\"disk\":416050.0,\"mem\":6883.0,\"gpus\":0.0,\"cpus\":4.0,\"ports\":\"[31000-32000]\"},\"used_resources\":"
                    + "{\"disk\":0.0,\"mem\":512.0,\"gpus\":0.0,\"cpus\":2.5},\"offered_resources\":{\"disk\":416050.0,\"mem\":6371.0,\"gpus\":0.0,\"cpus\":1.5,\"ports\":\"[31000-32000]\"},"
                    + "\"reserved_resources\":{},\"unreserved_resources\":{\"disk\":416050.0,\"mem\":6883.0,\"gpus\":0.0,\"cpus\":4.0,\"ports\":\"[31000-32000]\"},\"attributes\":{},\"active\":true,"
                    + "\"version\":\"1.1.0\"}],\"frameworks\":[{\"id\":\"d8701508-41b7-471e-9b32-61cf824a660d-0000\",\"name\":\"Elastic-Job-Cloud\",\"pid\":"
                    + "\"scheduler-da326b36-34ed-4b6e-ac40-0c936f76be4e@127.0.0.1:53639\",\"used_resources\":{\"disk\":0.0,\"mem\":512.0,\"gpus\":0.0,\"cpus\":2.5},\"offered_resources\""
                    + ":{\"disk\":416050.0,\"mem\":6371.0,\"gpus\":0.0,\"cpus\":1.5,\"ports\":\"[31000-32000]\"},\"capabilities\":[],\"hostname\":\"127.0.0.1\",\"webui_url\":\"http:\\/"
                    + "\\/127.0.0.1:8899\",\"active\":true,\"user\":\"gaohongtao\",\"failover_timeout\":604800.0,\"checkpoint\":false,\"role\":\"*\",\"registered_time\":1488179830.94584,"
                    + "\"unregistered_time\":0.0,\"resources\":{\"disk\":416050.0,\"mem\":6883.0,\"gpus\":0.0,\"cpus\":4.0,\"ports\":\"[31000-32000]\"},\"tasks\":[{\"id\":"
                    + "\"cpu_job_1@-@2@-@READY@-@d8701508-41b7-471e-9b32-61cf824a660d-S0@-@a03017a7-f520-483b-afce-2a5685d0ca2e\",\"name\":\"cpu_job_1@-@2@-@READY@-@d8701508-41b7-471e-"
                    + "9b32-61cf824a660d-S0\",\"framework_id\":\"d8701508-41b7-471e-9b32-61cf824a660d-0000\",\"executor_id\":\"foo_app@-@d8701508-41b7-471e-9b32-61cf824a660d-S0\",\"slave_id\":"
                    + "\"d8701508-41b7-471e-9b32-61cf824a660d-S0\",\"state\":\"TASK_RUNNING\",\"resources\":{\"disk\":0.0,\"mem\":128.0,\"gpus\":0.0,\"cpus\":0.5},\"statuses\":[{\"state\""
                    + ":\"TASK_RUNNING\",\"timestamp\":1488179870.00284,\"container_status\":{\"network_infos\":[{\"ip_addresses\":[{\"ip_address\":\"127.0.0.1\"}]}]}}]},{\"id\":"
                    + "\"cpu_job_1@-@0@-@READY@-@d8701508-41b7-471e-9b32-61cf824a660d-S0@-@31a2862f-c68c-448d-bbcf-8815b5c2dfef\",\"name\":\"cpu_job_1@-@0@-@READY@-@d8701508-41b7-471e-"
                    + "9b32-61cf824a660d-S0\",\"framework_id\":\"d8701508-41b7-471e-9b32-61cf824a660d-0000\",\"executor_id\":\"foo_app@-@d8701508-41b7-471e-9b32-61cf824a660d-S0\",\"slave_id\":"
                    + "\"d8701508-41b7-471e-9b32-61cf824a660d-S0\",\"state\":\"TASK_RUNNING\",\"resources\":{\"disk\":0.0,\"mem\":128.0,\"gpus\":0.0,\"cpus\":0.5},\"statuses\":[{\"state\":"
                    + "\"TASK_RUNNING\",\"timestamp\":1488179870.00305,\"container_status\":{\"network_infos\":[{\"ip_addresses\":[{\"ip_address\":\"127.0.0.1\"}]}]}}]},{\"id\":"
                    + "\"cpu_job_1@-@1@-@READY@-@d8701508-41b7-471e-9b32-61cf824a660d-S0@-@ede114f0-f2db-4bad-b0e0-e820a7d19c59\",\"name\":\"cpu_job_1@-@1@-@READY@-@d8701508-41b7-471e-"
                    + "9b32-61cf824a660d-S0\",\"framework_id\":\"d8701508-41b7-471e-9b32-61cf824a660d-0000\",\"executor_id\":\"foo_app@-@d8701508-41b7-471e-9b32-61cf824a660d-S0\",\"slave_id\":"
                    + "\"d8701508-41b7-471e-9b32-61cf824a660d-S0\",\"state\":\"TASK_RUNNING\",\"resources\":{\"disk\":0.0,\"mem\":128.0,\"gpus\":0.0,\"cpus\":0.5},\"statuses\":"
                    + "[{\"state\":\"TASK_RUNNING\",\"timestamp\":1488179870.00294,\"container_status\":{\"network_infos\":[{\"ip_addresses\":[{\"ip_address\":\"127.0.0.1\"}]}]}}]}],"
                    + "\"completed_tasks\":[],\"offers\":[{\"id\":\"d8701508-41b7-471e-9b32-61cf824a660d-O1\",\"framework_id\":\"d8701508-41b7-471e-9b32-61cf824a660d-0000\",\"slave_id\":"
                    + "\"d8701508-41b7-471e-9b32-61cf824a660d-S0\",\"resources\":{\"disk\":416050.0,\"mem\":6371.0,\"gpus\":0.0,\"cpus\":1.5,\"ports\":\"[31000-32000]\"}}],\"executors\":"
                    + "[{\"executor_id\":\"foo_app@-@d8701508-41b7-471e-9b32-61cf824a660d-S0\",\"name\":\"\",\"framework_id\":\"d8701508-41b7-471e-9b32-61cf824a660d-0000\",\"command\":"
                    + "{\"shell\":true,\"value\":\"bin\\/start.sh\",\"argv\":[],\"uris\":[{\"value\":\"http:\\/\\/127.0.0.1\\/image\\/es-test-1.0.tar.gz\",\"executable\":false}]},"
                    + "\"resources\":{\"disk\":0.0,\"mem\":128.0,\"gpus\":0.0,\"cpus\":1.0},\"slave_id\":\"d8701508-41b7-471e-9b32-61cf824a660d-S0\"}]}],\"completed_frameworks\":[],"
                    + "\"orphan_tasks\":[],\"unregistered_frameworks\":[]}");
}