Example usage for javax.servlet.http HttpServletRequest getReader

List of usage examples for javax.servlet.http HttpServletRequest getReader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getReader.

Prototype

public BufferedReader getReader() throws IOException;

Source Link

Document

Retrieves the body of the request as character data using a BufferedReader.

Usage

From source file:guru.nidi.raml.doc.servlet.MirrorServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    final int delay = req.getParameter("delay") == null ? 0 : Integer.parseInt(req.getParameter("delay"));
    try {//from  w w w  .  ja v  a 2s  . co m
        Thread.sleep(delay);
    } catch (InterruptedException e) {
        //ignore
    }
    final String q = req.getParameter("q") == null ? "" : req.getParameter("q");
    if (q.equals("png")) {
        final ServletOutputStream out = res.getOutputStream();
        res.setContentType("image/png");
        copy(getClass().getClassLoader().getResourceAsStream("data/google.png"), out);
    } else {
        final PrintWriter out = res.getWriter();
        switch (q) {
        case "html":
            res.setContentType("text/html");
            out.print("<html><body><ul>");
            for (int i = 0; i < 50; i++) {
                out.println("<li>" + i + "</li>");
            }
            out.print("</ul></body></html>");
            break;
        case "json":
            res.setContentType("application/json");
            final ObjectMapper mapper = new ObjectMapper();
            final Map<String, Object> map = new HashMap<>();
            map.put("method", req.getMethod());
            map.put("url", req.getRequestURL().toString());
            map.put("headers", headers(req));
            map.put("query", query(req));
            mapper.writeValue(out, map);
            break;
        case "error":
            res.sendError(500, "Dummy error message");
            break;
        default:
            out.println(req.getMethod() + " " + req.getRequestURL());
            headers(req, out);
            query(req, out);
            copy(req.getReader(), out);
        }
    }
    res.flushBuffer();
}

From source file:com.extjs.djn.ioc.servlet.BaseDirectJNgineServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    assert request != null;
    assert response != null;

    NDC.push("rid=" + Long.toString(getUniqueRequestId()));
    try {/*from  w w  w .j a v a2s.c o  m*/
        Timer timer = new Timer();
        try {
            attachThreadLocalData(request, response);
            try {
                if (logger.isTraceEnabled()) {
                    String requestInfo = ServletUtils.getDetailedRequestInformation(request);
                    logger.trace("Request info: " + requestInfo);
                }

                response.setContentType("text/html"); // MUST be "text/html" for uploads to work!
                String requestEncoding = request.getCharacterEncoding();
                // If we don't know what the request encoding is, assume it to be UTF-8
                if (StringUtils.isEmpty(requestEncoding)) {
                    request.setCharacterEncoding(EncodingUtils.UTF8);
                }
                response.setCharacterEncoding(EncodingUtils.UTF8);

                RequestType type = getFromRequestContentType(request);
                switch (type) {
                case FORM_SIMPLE_POST:
                    this.processor.processSimpleFormPostRequest(request.getReader(), response.getWriter());
                    break;
                case FORM_UPLOAD_POST:
                    processUploadFormPost(request, response);
                    break;
                case JSON:
                    this.processor.processJsonRequest(request.getReader(), response.getWriter());
                    break;
                case POLL:
                    this.processor.processPollRequest(request.getReader(), response.getWriter(),
                            request.getPathInfo());
                    break;
                }
            } finally {
                detachThreadLocalData();
            }
        } finally {
            timer.stop();
            timer.logDebugTimeInMilliseconds("Total servlet processing time");
        }

    } finally {
        NDC.pop();
    }
}

From source file:com.redhat.rhn.frontend.action.common.DownloadFile.java

@Override
protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String path = "";
    Map params = (Map) request.getAttribute(PARAMS);
    String type = (String) params.get(TYPE);
    if (type.equals(DownloadManager.DOWNLOAD_TYPE_KICKSTART)) {
        return getStreamInfoKickstart(mapping, form, request, response, path);
    } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_COBBLER)) {
        String url = ConfigDefaults.get().getCobblerServerUrl() + (String) params.get(URL_STRING);
        KickstartHelper helper = new KickstartHelper(request);
        String data = "";
        if (helper.isProxyRequest()) {
            data = KickstartManager.getInstance().renderKickstart(helper.getKickstartHost(), url);
        } else {//from w  w  w. j av  a 2  s. c  om
            data = KickstartManager.getInstance().renderKickstart(url);
        }
        setTextContentInfo(response, data.length());
        return getStreamForText(data.getBytes());
    } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_COBBLER_API)) {
        // read data from POST body
        String postData = new String();
        String line = null;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            postData += line;
        }

        // Send data
        URL url = new URL(ConfigDefaults.get().getCobblerServerUrl() + "/cobbler_api");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        // this will write POST /download//cobbler_api instead of
        // POST /cobbler_api, but cobbler do not mind
        wr.write(postData, 0, postData.length());
        wr.flush();
        conn.connect();

        // Get the response
        String output = new String();
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = rd.readLine()) != null) {
            output += line;
        }
        wr.close();

        KickstartHelper helper = new KickstartHelper(request);
        if (helper.isProxyRequest()) {
            // Search/replacing all instances of cobbler host with host
            // we pass in, for use with Spacewalk Proxy.
            output = output.replaceAll(ConfigDefaults.get().getCobblerHost(), helper.getForwardedHost());
        }

        setXmlContentInfo(response, output.length());
        return getStreamForXml(output.getBytes());
    } else {
        Long fileId = (Long) params.get(FILEID);
        Long userid = (Long) params.get(USERID);
        User user = UserFactory.lookupById(userid);
        if (type.equals(DownloadManager.DOWNLOAD_TYPE_PACKAGE)) {
            Package pack = PackageFactory.lookupByIdAndOrg(fileId, user.getOrg());
            setBinaryContentInfo(response, pack.getPackageSize().intValue());
            path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + pack.getPath();
            return getStreamForBinary(path);
        } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_SOURCE)) {
            Package pack = PackageFactory.lookupByIdAndOrg(fileId, user.getOrg());
            List<PackageSource> src = PackageFactory.lookupPackageSources(pack);
            if (!src.isEmpty()) {
                setBinaryContentInfo(response, src.get(0).getPackageSize().intValue());
                path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + src.get(0).getPath();
                return getStreamForBinary(path);
            }
        } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_REPO_LOG)) {
            Channel c = ChannelFactory.lookupById(fileId);
            ChannelManager.verifyChannelAdmin(user, fileId);
            StringBuilder output = new StringBuilder();
            for (String fileName : ChannelManager.getLatestSyncLogFiles(c)) {
                RandomAccessFile file = new RandomAccessFile(fileName, "r");
                long fileLength = file.length();
                if (fileLength > DOWNLOAD_REPO_LOG_LENGTH) {
                    file.seek(fileLength - DOWNLOAD_REPO_LOG_LENGTH);
                    // throw away text till end of the actual line
                    file.readLine();
                } else {
                    file.seek(0);
                }
                String line;
                while ((line = file.readLine()) != null) {
                    output.append(line);
                    output.append("\n");
                }
                file.close();
                if (output.length() > DOWNLOAD_REPO_LOG_MIN_LENGTH) {
                    break;
                }
            }

            setTextContentInfo(response, output.length());
            return getStreamForText(output.toString().getBytes());
        } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_CRASHFILE)) {
            CrashFile crashFile = CrashManager.lookupCrashFileByUserAndId(user, fileId);
            String crashPath = crashFile.getCrash().getStoragePath();
            setBinaryContentInfo(response, (int) crashFile.getFilesize());
            path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + crashPath + "/"
                    + crashFile.getFilename();
            return getStreamForBinary(path);

        }
    }

    throw new UnknownDownloadTypeException(
            "The specified download type " + type + " is not currently supported");

}

From source file:org.structr.rest.servlet.JsonRestServlet.java

@Override
protected void doPut(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    final SecurityContext securityContext;
    final Authenticator authenticator;
    final Resource resource;

    RestMethodResult result = new RestMethodResult(HttpServletResponse.SC_BAD_REQUEST);

    try {/*from   w ww .j a  v a2s  . co m*/

        // first thing to do!
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8;");

        // isolate request authentication in a transaction
        try (final Tx tx = StructrApp.getInstance().tx()) {
            authenticator = config.getAuthenticator();
            securityContext = authenticator.initializeAndExamineRequest(request, response);
            tx.success();
        }

        final App app = StructrApp.getInstance(securityContext);
        final String input = IOUtils.toString(request.getReader());
        final IJsonInput jsonInput = cleanAndParseJsonString(app, input);

        if (securityContext != null) {

            // isolate resource authentication
            try (final Tx tx = app.tx()) {

                // evaluate constraint chain
                resource = ResourceHelper.applyViewTransformation(request, securityContext,
                        ResourceHelper.optimizeNestedResourceChain(
                                ResourceHelper.parsePath(securityContext, request, resourceMap, propertyView)),
                        propertyView);
                authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(),
                        propertyView.get(securityContext));
                tx.success();
            }

            // isolate doPut
            boolean retry = true;
            while (retry) {

                try (final Tx tx = app.tx()) {
                    result = resource.doPut(convertPropertySetToMap(jsonInput.getJsonInputs().get(0)));
                    tx.success();
                    retry = false;

                } catch (DeadlockDetectedException ddex) {
                    retry = true;
                }
            }

            // isolate write output
            try (final Tx tx = app.tx()) {
                result.commitResponse(gson.get(), response);
                tx.success();
            }

        } else {

            // isolate write output
            try (final Tx tx = app.tx()) {
                result = new RestMethodResult(HttpServletResponse.SC_FORBIDDEN);
                result.commitResponse(gson.get(), response);
                tx.success();
            }

        }

    } catch (FrameworkException frameworkException) {

        // set status & write JSON output
        response.setStatus(frameworkException.getStatus());
        gson.get().toJson(frameworkException, response.getWriter());
        response.getWriter().println();

    } catch (JsonSyntaxException jsex) {

        logger.log(Level.WARNING, "PUT: Invalid JSON syntax", jsex.getMessage());

        int code = HttpServletResponse.SC_BAD_REQUEST;

        response.setStatus(code);
        response.getWriter()
                .append(RestMethodResult.jsonError(code, "JsonSyntaxException in PUT: " + jsex.getMessage()));

    } catch (JsonParseException jpex) {

        logger.log(Level.WARNING, "PUT: Unable to parse JSON string", jpex.getMessage());

        int code = HttpServletResponse.SC_BAD_REQUEST;

        response.setStatus(code);
        response.getWriter()
                .append(RestMethodResult.jsonError(code, "JsonSyntaxException in PUT: " + jpex.getMessage()));

    } catch (Throwable t) {

        logger.log(Level.WARNING, "Exception in PUT", t);

        int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;

        response.setStatus(code);
        response.getWriter()
                .append(RestMethodResult.jsonError(code, "JsonSyntaxException in PUT: " + t.getMessage()));

    } finally {

        try {
            //response.getWriter().flush();
            response.getWriter().close();

        } catch (Throwable t) {

            logger.log(Level.WARNING, "Unable to flush and close response: {0}", t.getMessage());
        }

    }
}

From source file:org.apache.tuscany.sca.binding.jsonrpc.provider.JsonRpcServlet.java

private void handleJsonRpcInvocation(HttpServletRequest request, HttpServletResponse response)
        throws UnsupportedEncodingException, IOException, ServletException {

    // Decode using the charset in the request if it exists otherwise
    // use UTF-8 as this is what all browser implementations use.
    // The JSON-RPC-Java JavaScript client is ASCII clean so it
    // although here we can correctly handle data from other clients
    // that do not escape non ASCII data
    String charset = request.getCharacterEncoding();
    if (charset == null) {
        charset = "UTF-8";
    }/*from w w w  .  ja v a  2  s . c om*/

    JsonNode root = null;
    if (request.getMethod().equals("GET")) {
        // if using GET Support (see http://groups.google.com/group/json-rpc/web/json-rpc-over-http)

        //parse the GET QueryString
        try {
            String params = new String(
                    Base64.decodeBase64(URLDecoder.decode(request.getParameter("params"), charset).getBytes()));
            StringBuilder sb = new StringBuilder();
            sb.append("{");
            sb.append("\"method\": \"" + request.getParameter("method") + "\",");
            sb.append("\"params\": " + params + ",");
            sb.append("\"id\":" + request.getParameter("id"));
            sb.append("}");

            root = JacksonHelper.MAPPER.readTree(sb.toString());
        } catch (Throwable e) {
            JsonRpc10Response error = new JsonRpc10Response(
                    JsonNodeFactory.instance.textNode(request.getParameter("id")), e);
            error.write(response.getWriter());
            return;
        }
    } else {
        root = JacksonHelper.MAPPER.readTree(request.getReader());
    }

    try {
        if (root.isArray()) {
            ArrayNode input = (ArrayNode) root;
            JsonRpc20BatchRequest batchReq = new JsonRpc20BatchRequest(input);
            for (int i = 0; i < batchReq.getRequests().size(); i++) {
                JsonRpcResponse result = batchReq.getBatchResponse().getResponses().get(i);
                if (result == null) {
                    result = invoke(batchReq.getRequests().get(i));
                    batchReq.getBatchResponse().getResponses().set(i, result);
                }
            }
            ArrayNode responses = batchReq.getBatchResponse().toJSONArray();
            JacksonHelper.MAPPER.writeValue(response.getWriter(), responses);
        } else {
            if (root.has("jsonrpc")) {
                JsonRpc20Request jsonReq = new JsonRpc20Request((ObjectNode) root);
                JsonRpcResponse jsonResult = invoke(jsonReq);
                if (jsonResult != null) {
                    jsonResult.write(response.getWriter());
                }
            } else {
                JsonRpc10Request jsonReq = new JsonRpc10Request((ObjectNode) root);
                JsonRpc10Response jsonResult = invoke(jsonReq);
                if (jsonResult != null) {
                    jsonResult.write(response.getWriter());
                }
            }
        }
    } catch (Throwable e) {
        throw new ServletException(e);
    }
}

From source file:org.structr.rest.servlet.JsonRestServlet.java

@Override
protected void doPost(final HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final List<RestMethodResult> results = new LinkedList<>();
    final SecurityContext securityContext;
    final Authenticator authenticator;
    final Resource resource;

    try {// w w  w  .j  a v a2 s. c o m

        // first thing to do!
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8;");

        // isolate request authentication in a transaction
        try (final Tx tx = StructrApp.getInstance().tx()) {
            authenticator = config.getAuthenticator();
            securityContext = authenticator.initializeAndExamineRequest(request, response);
            tx.success();
        }

        final App app = StructrApp.getInstance(securityContext);
        final String input = IOUtils.toString(request.getReader());
        final IJsonInput jsonInput = cleanAndParseJsonString(app, input);

        if (securityContext != null) {

            // isolate resource authentication
            try (final Tx tx = app.tx()) {

                resource = ResourceHelper.applyViewTransformation(request, securityContext,
                        ResourceHelper.optimizeNestedResourceChain(
                                ResourceHelper.parsePath(securityContext, request, resourceMap, propertyView)),
                        propertyView);
                authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(),
                        propertyView.get(securityContext));
                tx.success();
            }

            // isolate doPost
            boolean retry = true;
            while (retry) {

                if (resource.createPostTransaction()) {

                    try (final Tx tx = app.tx()) {

                        for (JsonInput propertySet : jsonInput.getJsonInputs()) {

                            results.add(resource.doPost(convertPropertySetToMap(propertySet)));
                        }

                        tx.success();
                        retry = false;

                    } catch (DeadlockDetectedException ddex) {
                        retry = true;
                    }

                } else {

                    try {

                        for (JsonInput propertySet : jsonInput.getJsonInputs()) {

                            results.add(resource.doPost(convertPropertySetToMap(propertySet)));
                        }

                        retry = false;

                    } catch (DeadlockDetectedException ddex) {
                        retry = true;
                    }
                }
            }

            // set default value for property view
            propertyView.set(securityContext, config.getDefaultPropertyView());

            // isolate write output
            try (final Tx tx = app.tx()) {

                if (!results.isEmpty()) {

                    final RestMethodResult result = results.get(0);
                    final int resultCount = results.size();

                    if (result != null) {

                        if (resultCount > 1) {

                            for (final RestMethodResult r : results) {

                                final GraphObject objectCreated = r.getContent().get(0);
                                if (!result.getContent().contains(objectCreated)) {

                                    result.addContent(objectCreated);
                                }

                            }

                            // remove Location header if more than one object was
                            // written because it may only contain a single URL
                            result.addHeader("Location", null);
                        }

                        result.commitResponse(gson.get(), response);
                    }

                }

                tx.success();
            }

        } else {

            // isolate write output
            try (final Tx tx = app.tx()) {

                new RestMethodResult(HttpServletResponse.SC_FORBIDDEN).commitResponse(gson.get(), response);
                tx.success();
            }

        }

    } catch (FrameworkException frameworkException) {

        // set status & write JSON output
        response.setStatus(frameworkException.getStatus());
        gson.get().toJson(frameworkException, response.getWriter());
        response.getWriter().println();

    } catch (JsonSyntaxException jsex) {

        logger.log(Level.WARNING, "POST: Invalid JSON syntax", jsex.getMessage());

        int code = HttpServletResponse.SC_BAD_REQUEST;

        response.setStatus(code);
        response.getWriter()
                .append(RestMethodResult.jsonError(code, "JsonSyntaxException in POST: " + jsex.getMessage()));

    } catch (JsonParseException jpex) {

        logger.log(Level.WARNING, "Unable to parse JSON string", jpex.getMessage());

        int code = HttpServletResponse.SC_BAD_REQUEST;

        response.setStatus(code);
        response.getWriter()
                .append(RestMethodResult.jsonError(code, "JsonParseException in POST: " + jpex.getMessage()));

    } catch (UnsupportedOperationException uoe) {

        logger.log(Level.WARNING, "POST not supported");

        int code = HttpServletResponse.SC_BAD_REQUEST;

        response.setStatus(code);
        response.getWriter()
                .append(RestMethodResult.jsonError(code, "POST not supported: " + uoe.getMessage()));

    } catch (Throwable t) {

        logger.log(Level.WARNING, "Exception in POST", t);

        int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;

        response.setStatus(code);
        response.getWriter()
                .append(RestMethodResult.jsonError(code, "JsonSyntaxException in POST: " + t.getMessage()));

    } finally {

        try {
            //response.getWriter().flush();
            response.getWriter().close();

        } catch (Throwable t) {

            logger.log(Level.WARNING, "Unable to flush and close response: {0}", t.getMessage());
        }

    }
}

From source file:org.openhab.binding.amazonechocontrol.internal.AccountServlet.java

void doVerb(String verb, @Nullable HttpServletRequest req, @Nullable HttpServletResponse resp)
        throws ServletException, IOException {
    if (req == null) {
        return;/*from w  w  w .  ja  v a  2 s  .  c  om*/
    }
    if (resp == null) {
        return;
    }
    String baseUrl = req.getRequestURI().substring(servletUrl.length());
    String uri = baseUrl;
    String queryString = req.getQueryString();
    if (queryString != null && queryString.length() > 0) {
        uri += "?" + queryString;
    }

    Connection connection = this.account.findConnection();
    if (connection != null && uri.equals("/changedomain")) {
        Map<String, String[]> map = req.getParameterMap();
        String domain = map.get("domain")[0];
        String loginData = connection.serializeLoginData();
        Connection newConnection = new Connection(null);
        if (newConnection.tryRestoreLogin(loginData, domain)) {
            account.setConnection(newConnection);
        }
        resp.sendRedirect(servletUrl);
        return;
    }
    if (uri.startsWith(PROXY_URI_PART)) {
        // handle proxy request

        if (connection == null) {
            returnError(resp, "Account not online");
            return;
        }
        String getUrl = "https://alexa." + connection.getAmazonSite() + "/"
                + uri.substring(PROXY_URI_PART.length());

        String postData = null;
        if (verb == "POST" || verb == "PUT") {
            postData = req.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
        }

        this.handleProxyRequest(connection, resp, verb, getUrl, null, postData, true,
                connection.getAmazonSite());
        return;
    }

    // handle post of login page
    connection = this.connectionToInitialize;
    if (connection == null) {
        returnError(resp, "Connection not in intialize mode.");
        return;
    }

    resp.addHeader("content-type", "text/html;charset=UTF-8");

    Map<String, String[]> map = req.getParameterMap();
    StringBuilder postDataBuilder = new StringBuilder();
    for (String name : map.keySet()) {
        if (postDataBuilder.length() > 0) {
            postDataBuilder.append('&');
        }

        postDataBuilder.append(name);
        postDataBuilder.append('=');
        String value = map.get(name)[0];
        if (name.equals("failedSignInCount")) {
            value = "ape:AA==";
        }
        postDataBuilder.append(URLEncoder.encode(value, StandardCharsets.UTF_8.name()));
    }

    uri = req.getRequestURI();
    if (!uri.startsWith(servletUrl)) {
        returnError(resp, "Invalid request uri '" + uri + "'");
        return;
    }
    String relativeUrl = uri.substring(servletUrl.length()).replace(FORWARD_URI_PART, "/");

    String site = connection.getAmazonSite();
    if (relativeUrl.startsWith("/ap/signin")) {
        site = "amazon.com";
    }
    String postUrl = "https://www." + site + relativeUrl;
    queryString = req.getQueryString();
    if (queryString != null && queryString.length() > 0) {
        postUrl += "?" + queryString;
    }
    String referer = "https://www." + site;
    String postData = postDataBuilder.toString();
    handleProxyRequest(connection, resp, "POST", postUrl, referer, postData, false, site);
}

From source file:servlets.Samples_servlets.java

private void unlock_biocondition_handler(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    boolean alreadyLocked = false;
    try {/*from ww  w  .  j  av a 2s  . com*/
        JsonParser parser = new JsonParser();
        JsonObject requestData = (JsonObject) parser.parse(request.getReader());

        String loggedUser = requestData.get("loggedUser").getAsString();
        String sessionToken = requestData.get("sessionToken").getAsString();

        /**
         * *******************************************************
         * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF ERROR
         * --> throws exception if not valid session, GO TO STEP ELSE --> GO
         * TO STEP 2 *******************************************************
         */
        if (!checkAccessPermissions(loggedUser, sessionToken)) {
            throw new AccessControlException("Your session is invalid. User or session token not allowed.");
        }
        /**
         * *******************************************************
         * STEP 2 GET THE OBJECT ID AND TRY TO LOCK IT. IF ERROR --> throws
         * exception, GO TO STEP ELSE --> GO TO STEP 3
         * *******************************************************
         */
        String biocondition_id = requestData.get("biocondition_id").getAsString();
        alreadyLocked = !BlockedElementsManager.getBlockedElementsManager().unlockObject(biocondition_id,
                loggedUser);
    } catch (Exception e) {
        ServerErrorManager.handleException(e, Samples_servlets.class.getName(), "unlock_biocondition_handler",
                e.getMessage());
    } finally {
        /**
         * *******************************************************
         * STEP 4b CATCH ERROR. GO TO STEP 5
         * *******************************************************
         */
        if (ServerErrorManager.errorStatus()) {
            response.setStatus(400);
            response.getWriter().print(ServerErrorManager.getErrorResponse());
        } else {
            /**
             * *******************************************************
             * STEP 3A WRITE RESPONSE ERROR.
             * *******************************************************
             */
            JsonObject obj = new JsonObject();
            if (alreadyLocked) {
                obj.add("success", new JsonPrimitive(false));
                obj.add("reason", new JsonPrimitive(BlockedElementsManager.getErrorMessage()));
            } else {
                obj.add("success", new JsonPrimitive(true));
            }
            response.getWriter().print(obj.toString());
        }
    }
}

From source file:servlets.Samples_servlets.java

private void get_biocondition_handler(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from  w  w w  .  j  a v a2s  .  c om*/
        DAO dao_instance = null;
        BioCondition biocondition = null;
        try {
            JsonParser parser = new JsonParser();
            JsonObject requestData = (JsonObject) parser.parse(request.getReader());

            String loggedUser = requestData.get("loggedUser").getAsString();
            String sessionToken = requestData.get("sessionToken").getAsString();
            /**
             * *******************************************************
             * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF
             * ERROR --> throws exception if not valid session, GO TO STEP
             * 5b ELSE --> GO TO STEP 2
             * *******************************************************
             */
            if (!checkAccessPermissions(loggedUser, sessionToken)) {
                throw new AccessControlException("Your session is invalid. User or session token not allowed.");
            }

            /**
             * *******************************************************
             * STEP 2 Get ALL THE ANALYSIS Object from DB. IF ERROR -->
             * throws MySQL exception, GO TO STEP 3b ELSE --> GO TO STEP 3
             * *******************************************************
             */
            dao_instance = DAOProvider.getDAOByName("BioCondition");
            boolean loadRecursive = requestData.get("recursive").getAsBoolean();
            ;
            Object[] params = { loadRecursive };

            String biocondition_id = requestData.get("biocondition_id").getAsString();
            biocondition = (BioCondition) dao_instance.findByID(biocondition_id, params);
        } catch (Exception e) {
            ServerErrorManager.handleException(e, Samples_servlets.class.getName(), "get_biocondition_handler",
                    e.getMessage());
        } finally {
            /**
             * *******************************************************
             * STEP 4b CATCH ERROR. GO TO STEP 5
             * *******************************************************
             */
            if (ServerErrorManager.errorStatus()) {
                response.setStatus(400);
                response.getWriter().print(ServerErrorManager.getErrorResponse());
            } else {
                /**
                 * *******************************************************
                 * STEP 4A WRITE RESPONSE ERROR. GO TO STEP 5
                 * *******************************************************
                 */
                response.getWriter().print(biocondition.toJSON());
            }
            /**
             * *******************************************************
             * STEP 5 Close connection.
             * ********************************************************
             */
            if (dao_instance != null) {
                dao_instance.closeConnection();
            }
        }
        //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE 
    } catch (Exception e) {
        ServerErrorManager.handleException(e, Samples_servlets.class.getName(), "get_biocondition_handler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}