Example usage for com.google.gson JsonParser parse

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

Introduction

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

Prototype

@Deprecated
public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException 

Source Link

Usage

From source file:com.commonslibrary.commons.utils.JsonUtils.java

License:Open Source License

/**
 * ?JsonObject// ww w  .ja  va2s . c  o  m
 *
 * @param json
 * @return
 */
public static JsonObject parseJson(String json) {
    try {
        JsonParser parser = new JsonParser();
        JsonObject jsonObj = parser.parse(json).getAsJsonObject();
        return jsonObj;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.compose.nifi.processors.ComposeBatchPutMongo.java

License:Apache License

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;// ww w  . j a  v  a 2s.c o  m
    }

    final Charset charset = Charset.forName(context.getProperty(CHARACTER_SET).getValue());
    final String collectionName = context.getProperty(COLLECTION_NAME).getValue();
    final WriteConcern writeConcern = mongoWrapper.getWriteConcern(context);

    final MongoCollection<Document> collection = mongoWrapper.getDatabase(context).getCollection(collectionName)
            .withWriteConcern(writeConcern);

    try {
        // Read the contents of the FlowFile into a byte array
        final byte[] content = new byte[(int) flowFile.getSize()];
        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(final InputStream in) throws IOException {
                StreamUtils.fillBuffer(in, content, true);
            }
        });

        //Hack away :)
        ArrayList<Document> docs = new ArrayList<>();
        JsonParser parser = new JsonParser();
        JsonArray array = parser.parse(new String(content, charset)).getAsJsonArray();
        for (JsonElement element : array) {
            //Terrible. surely a better way. learn more.
            Document doc = Document.parse(element.toString());
            docs.add(doc);
        }

        collection.insertMany(docs);

        session.getProvenanceReporter().send(flowFile, mongoWrapper.getURI(context));
        session.transfer(flowFile, REL_SUCCESS);
    } catch (Exception e) {
        getLogger().error("Failed to insert {} into MongoDB due to {}", new Object[] { flowFile, e }, e);
        session.transfer(flowFile, REL_FAILURE);
        context.yield();
    }
}

From source file:com.couchbase.plugin.basement.api.Client.java

License:Open Source License

public HashMap<String, Object> parse(String json) {
    JsonParser parser = new JsonParser();
    JsonObject object = (JsonObject) parser.parse(json);

    Set<Map.Entry<String, JsonElement>> set = object.entrySet();
    Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator();
    HashMap<String, Object> map = new HashMap<String, Object>();
    while (iterator.hasNext()) {
        Map.Entry<String, JsonElement> entry = iterator.next();
        String key = entry.getKey();
        JsonElement value = entry.getValue();

        addJsonElement(key, value, map);

    }//from   w ww  . j a  va  2 s .  c o m

    return map;
}

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

License:Apache License

private boolean doTokenRequest(Collection<BasicNameValuePair> params) throws IOException {
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(OAUTH_BASE_URL + "/token");
    List<BasicNameValuePair> paramBody = new ArrayList<BasicNameValuePair>();
    paramBody.add(new BasicNameValuePair("client_id", clientId));
    paramBody.add(new BasicNameValuePair("client_secret", clientSecret));
    paramBody.addAll(params);/*w ww  . j ava 2 s . c om*/
    post.setEntity(new UrlEncodedFormEntity(paramBody, "UTF-8"));
    HttpResponse response = client.execute(post);
    int code = response.getStatusLine().getStatusCode();

    if (code == 401) {
        return false;
    } else if (code != 200) {
        throw new IOException("Got HTTP response code " + code);
    }
    String responseString = EntityUtils.toString(response.getEntity());

    JsonParser parser = new JsonParser();
    JsonObject content = (JsonObject) parser.parse(responseString);
    System.out.print("content: " + content.toString());
    accessToken = content.get("access_token").getAsString();
    refreshToken = content.get("refresh_token").getAsString();
    return true;
}

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

License:Apache License

private boolean doTokenRequest(Map<String, String> params) throws IOException {
    Map<String, String> paramsBody = new HashMap<String, String>();
    paramsBody.put("client_id", clientId);
    paramsBody.put("client_secret", clientSecret);
    paramsBody.putAll(params);/*from ww w  .j  a  va2s .c  o m*/

    String bodyStr = RequestClient.createRequestParams(paramsBody);
    System.out.println(bodyStr);
    HttpURLConnection conn = (HttpsURLConnection) new URL(OAUTH_BASE_URL + "/token").openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(bodyStr);
    writer.flush();
    writer.close();

    int code = conn.getResponseCode();

    if (code == 401) {
        return false;
    } else if (code != 200) {
        throw new IOException("Got HTTP response code " + code);
    }
    String response = RequestClient.getResponseBody(conn.getInputStream());

    JsonParser parser = new JsonParser();
    JsonObject content = (JsonObject) parser.parse(response);
    System.out.print("content: " + content.toString());
    accessToken = content.get("access_token").getAsString();
    refreshToken = content.get("refresh_token").getAsString();
    return true;
}

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

License:Apache License

private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, JsonObject json, boolean retry,
        String accessToken) throws IOException, UnsupportedRequestVerbException {

    if (verb == RequestVerb.DELETE || verb == RequestVerb.GET) {
        throw new UnsupportedRequestVerbException();
    }// w w  w .  jav a  2 s  . c o m
    if (api.allowSecure()) {

        HttpClient client = HttpClientBuilder.create().build();
        String url = BASE_URL + method;
        HttpUriRequest request;

        switch (verb) {
        case POST:
            request = new HttpPost(url);
            break;
        case PUT:
            request = new HttpPut(url);
            break;
        default:
            throw new RuntimeException("RequestVerb not implemented: " + verb);
        }

        ((HttpEntityEnclosingRequestBase) request)
                .setEntity(new StringEntity(json.toString(), ContentType.APPLICATION_JSON));

        if (accessToken != null)
            request.addHeader("Authorization", String.format("Bearer %s", accessToken));

        request.addHeader("Content-Type", "application/json");
        HttpResponse response = client.execute(request);
        int code = response.getStatusLine().getStatusCode();

        if (code == 401) {
            if (retry) {
                api.refreshAccessToken();
                call(api, method, verb, json, false, api.getAccessToken());
            } else {
                throw new IOException("Account is no longer valid");
            }
        } else if (code != 200) {
            throw new IOException("HTTP response " + code + " to request " + method);
        }

        String responseString = EntityUtils.toString(response.getEntity());
        if (responseString.startsWith("[")) {
            // Is an array
            responseString = "{response:" + responseString + "}";
        }

        JsonParser parser = new JsonParser();
        JsonObject resp = (JsonObject) parser.parse(responseString);
        System.out.println(resp.toString());
        return resp;
    }

    String url = BASE_URL + method;

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod(verb.name());
    conn.addRequestProperty("Content-Type", "application/json");

    if (accessToken != null)
        conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken));

    conn.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(json.toString());
    writer.flush();
    writer.close();

    int code = conn.getResponseCode();
    if (code == 401) {

        if (retry) {
            api.refreshAccessToken();
            return call(api, method, verb, json, false, api.getAccessToken());
        } else {
            throw new IOException("Account is no longer valid");
        }

    } else if (code != 200) {
        throw new IOException("HTTP response " + code + " to request " + method);
    }

    String responseString = getResponseBody(conn.getInputStream());
    if (responseString.startsWith("[")) {
        responseString = "{response:" + responseString + "}";
    }

    JsonParser parser = new JsonParser();
    return (JsonObject) parser.parse(responseString);
}

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

License:Apache License

private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, Map<String, String> params,
        boolean retry, String accessToken) throws IOException {
    if (api.allowSecure()) {

        HttpClient client = HttpClientBuilder.create().build();
        String url = BASE_URL + method;
        HttpUriRequest request = null;/*from  w w  w.  j  a  v  a  2 s .c o  m*/

        if (verb == RequestVerb.POST || verb == RequestVerb.PUT) {
            switch (verb) {
            case POST:
                request = new HttpPost(url);
                break;
            case PUT:
                request = new HttpPut(url);
                break;
            default:
                throw new RuntimeException("RequestVerb not implemented: " + verb);
            }

            List<BasicNameValuePair> paramsBody = new ArrayList<BasicNameValuePair>();

            if (params != null) {
                List<BasicNameValuePair> convertedParams = convertParams(params);
                paramsBody.addAll(convertedParams);
            }

            ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(paramsBody, "UTF-8"));
        } else {
            if (params != null) {
                url = url + "?" + createRequestParams(params);
            }

            if (verb == RequestVerb.GET) {
                request = new HttpGet(url);
            } else if (verb == RequestVerb.DELETE) {
                request = new HttpDelete(url);
            }
        }
        if (request == null)
            return null;

        if (accessToken != null)
            request.addHeader("Authorization", String.format("Bearer %s", accessToken));
        System.out.println("auth header: " + request.getFirstHeader("Authorization"));
        HttpResponse response = client.execute(request);
        int code = response.getStatusLine().getStatusCode();

        if (code == 401) {
            if (retry) {
                api.refreshAccessToken();
                call(api, method, verb, params, false, api.getAccessToken());
            } else {
                throw new IOException("Account is no longer valid");
            }
        } else if (code != 200) {
            throw new IOException("HTTP response " + code + " to request " + method);
        }

        String responseString = EntityUtils.toString(response.getEntity());
        if (responseString.startsWith("[")) {
            // Is an array
            responseString = "{response:" + responseString + "}";
        }

        JsonParser parser = new JsonParser();
        JsonObject resp = (JsonObject) parser.parse(responseString);
        System.out.println(resp.toString());
        return resp;
    }

    String paramStr = createRequestParams(params);
    String url = BASE_URL + method;

    if (paramStr != null && verb == RequestVerb.GET || verb == RequestVerb.DELETE)
        url += "?" + paramStr;

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod(verb.name());

    if (accessToken != null)
        conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken));

    if (verb != RequestVerb.GET && verb != RequestVerb.DELETE && paramStr != null) {
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(paramStr);
        writer.flush();
        writer.close();
    }

    int code = conn.getResponseCode();
    if (code == 401) {

        if (retry) {
            api.refreshAccessToken();
            return call(api, method, verb, params, false, api.getAccessToken());
        } else {
            throw new IOException("Account is no longer valid");
        }

    } else if (code != 200) {
        throw new IOException("HTTP response " + code + " to request " + method);
    }

    String responseString = getResponseBody(conn.getInputStream());
    if (responseString.startsWith("[")) {
        responseString = "{response:" + responseString + "}";
    }

    JsonParser parser = new JsonParser();
    return (JsonObject) parser.parse(responseString);
}

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  w  w.ja v  a 2s  . 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 {//w  w  w . java  2 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.dardenestates.code.src.Servlets.JsonServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from ww  w . j  a  v  a  2s  .  c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/json");

    BufferedReader reader = request.getReader();
    List<String> message = new ArrayList();
    JsonObject jsonObject;

    if (reader.ready()) {
        JsonParser jsonParser = new JsonParser();

        try {
            jsonObject = jsonParser.parse(reader).getAsJsonObject();

        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.out.println(e.getStackTrace());
            jsonObject = new JsonObject();
            jsonObject.add("Exception_Code", new JsonPrimitive("malformed request structure"));
        }

    } else {
        jsonObject = new JsonObject();
        jsonObject.add("Exception_Code", new JsonPrimitive("Empty Request"));
        System.out.println(" Empty Request ");
    }
    try (PrintWriter out = response.getWriter()) {

        out.write(jsonObject.toString());

    }

    //extract the commandkey
    String commandKey = jsonObject.get("COMMANDKEY").getAsString();
    // route the command
    RoutingEnum routingEnum = RoutingEnum.valueOf(commandKey);
    ControllerInterface command = routingEnum.getExecutable();
    String urlLocation = routingEnum.getResponseURL();

    if (command.validate(jsonObject, message, makeDataSource())) {
        MysqlDataSource dataSource = new MysqlDataSource();
        if (command.processRequest(jsonObject, message, dataSource)) {
            response.sendRedirect(urlLocation);
        }
    }

    //get the value of command
    //match it with the enum

}