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:servlets.Analysis_servlets.java

private void get_all_analysis_handler(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    try {/*from   ww w  .j av a2 s.  c om*/
        DAO dao_instance = null;
        ArrayList<Object> analysisList = 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. Please sign in again.");
            }

            /**
             * *******************************************************
             * STEP 2 Get ALL THE ANALYSIS Object from DB. IF ERROR -->
             * throws MySQL exception, GO TO STEP 3b ELSE --> GO TO STEP 3
             * *******************************************************
             */
            boolean loadRecursive = false;
            if (requestData.has("loadRecursive")) {
                loadRecursive = requestData.get("loadRecursive").getAsBoolean();
            }

            String experiment_id = null;
            if (requestData.has("experiment_id")) {
                experiment_id = requestData.get("experiment_id").getAsString();
            } else {
                experiment_id = requestData.get("currentExperimentID").getAsString();
            }

            Object[] params = { loadRecursive, experiment_id };
            dao_instance = DAOProvider.getDAOByName("Analysis");
            analysisList = dao_instance.findAll(params);
        } catch (Exception e) {
            ServerErrorManager.handleException(e, Analysis_servlets.class.getName(), "get_all_analysis_handler",
                    e.getMessage());
        } finally {
            /**
             * *******************************************************
             * STEP 3b CATCH ERROR. GO TO STEP 4
             * *******************************************************
             */
            if (ServerErrorManager.errorStatus()) {
                response.setStatus(400);
                response.getWriter().print(ServerErrorManager.getErrorResponse());
            } else {
                /**
                 * *******************************************************
                 * STEP 3A WRITE RESPONSE ERROR. GO TO STEP 4
                 * *******************************************************
                 */
                String analysisJSON = "[";

                for (int i = 0; i < analysisList.size(); i++) {
                    analysisJSON += ((Analysis) analysisList.get(i)).toJSON()
                            + ((i < analysisList.size() - 1) ? "," : "");
                }
                analysisJSON += "]";

                response.getWriter().print(analysisJSON);
            }
            /**
             * *******************************************************
             * STEP 4 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, Analysis_servlets.class.getName(), "get_all_analysis_handler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

From source file:servlets.Analysis_servlets.java

private void unlock_analysis_handler(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    boolean alreadyUnlocked = false;
    ArrayList<String> notUnlockedSteps = new ArrayList<String>();

    try {//from w ww.j a va2  s.co m
        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 UNLOCK IT. IF ERROR -->
         * throws exception, GO TO STEP ELSE --> GO TO STEP 3
         * *******************************************************
         */
        String analysis_id = requestData.get("analysis_id").getAsString();
        alreadyUnlocked = !BlockedElementsManager.getBlockedElementsManager().unlockObject(analysis_id,
                loggedUser);

        /**
         * *******************************************************
         * STEP 3 TRY TO UNLOCK THE STEPS. exception, GO TO STEP ELSE --> GO
         * TO STEP 3 *******************************************************
         */
        DAO dao_instance = DAOProvider.getDAOByName("Analysis");
        boolean loadRecursive = true;
        Object[] params = { loadRecursive };
        Analysis analysis = (Analysis) dao_instance.findByID(analysis_id, params);
        dao_instance.closeConnection();
        if (analysis != null) {
            String step_id;
            for (Step step : analysis.getNonProcessedData()) {
                step_id = step.getStepID();
                if (!BlockedElementsManager.getBlockedElementsManager().unlockObject(step_id, loggedUser)) {
                    notUnlockedSteps.add(step_id);
                }
            }
            for (Step step : analysis.getProcessedData()) {
                step_id = step.getStepID();
                if (!BlockedElementsManager.getBlockedElementsManager().unlockObject(step_id, loggedUser)) {
                    notUnlockedSteps.add(step_id);
                }
            }
        }

    } catch (Exception e) {
        ServerErrorManager.handleException(e, Analysis_servlets.class.getName(), "unlock_analysis_handler",
                e.getMessage());
    } finally {
        /**
         * *******************************************************
         * STEP 3b CATCH ERROR.
         * *******************************************************
         */
        if (ServerErrorManager.errorStatus()) {
            response.setStatus(400);
            response.getWriter().print(ServerErrorManager.getErrorResponse());
        } else {
            /**
             * *******************************************************
             * STEP 3A WRITE RESPONSE .
             * *******************************************************
             */
            JsonObject obj = new JsonObject();
            if (alreadyUnlocked) {
                obj.add("success", new JsonPrimitive(false));
                obj.add("reason", new JsonPrimitive(BlockedElementsManager.getErrorMessage()));
            } else {
                obj.add("success", new JsonPrimitive(true));

                if (notUnlockedSteps.size() > 0) {
                    JsonArray _notUnlockedSteps = new JsonArray();
                    for (String step_id : notUnlockedSteps) {
                        _notUnlockedSteps.add(new JsonPrimitive(step_id));
                    }
                    obj.add("notUnlockedSteps", _notUnlockedSteps);
                }
            }
            response.getWriter().print(obj.toString());
        }
    }
}

From source file:com.impala.paga.all.RouteRemit1.java

/**
 * //from   www. ja v  a2  s  .  c o m
 * @param request
 * @return
 * @throws IOException
 */
private String moneytransfer(HttpServletRequest request)
        throws IOException, JSONException, NoSuchAlgorithmException {

    // joined json string
    String join = "";
    JsonElement root = null;
    JsonElement root2 = null;
    JsonElement root3 = null;

    String responseobject = "";
    String remiturl = "https://www.mypaga.com/paga-webservices/business-rest/secured/moneyTransfer";
    String hashkey = "372e9b1c62ef47db83c566cf2db033cb4e1b847e12ec435997971ebd7ab8121cbd8458176374480eae7d4cb55f722f4ab328207b461f423a85a9bbad8850ce66";
    String principal = "02A10715-0E53-4A8C-982E-2B7BFC7CF550";
    String credentials = "QE3@u=jd*2b+";
    /*String referenceNumber = "",  amount = "",currency="",destinationAccount="",
    destinationBank= "", senderPrincipal = "", senderCrendetials = "",  transferReference = "", 
         sourceOfFunds = "", sendWithdrawalCode = ""
    , minRecipientKYCLevel = "",   holdingPeriod = "", principal = "" , credentials = "", hash = "";
    */

    // These represent parameters received over the network
    String referenceNumber = "", amount = "", currency = "", destinationAccount = "", destinationBank = "",
            senderPrincipal = "", senderCrendetials = "", transferReference = "", sourceOfFunds = "",
            sendWithdrawalCode = "", minRecipientKYCLevel = "", holdingPeriod = "";

    // Get all parameters, the keys of the parameters are specified
    List<String> lines = IOUtils.readLines(request.getReader());

    // used to format/join incoming JSon string
    join = StringUtils.join(lines.toArray(), "");

    //###############################################################################
    // instantiate the JSon
    //Note
    //The = sign is encoded to \u003d. Hence you need to use disableHtmlEscaping().
    //###############################################################################

    Gson g = new GsonBuilder().disableHtmlEscaping().create();
    //Gson g = new Gson();
    Map<String, String> expected = new HashMap<>();

    try {
        // parse the JSon string

        root = new JsonParser().parse(join);

        referenceNumber = root.getAsJsonObject().get("referenceNumber").getAsString();
        amount = root.getAsJsonObject().get("amount").getAsString();
        destinationAccount = root.getAsJsonObject().get("destinationAccount").getAsString();

    } catch (Exception e) {

        expected.put("command_status", "COMMANDSTATUS_INVALID_PARAMETERS");
        String jsonResult = g.toJson(expected);
        System.out.println(e);

        return jsonResult;
    }
    /*String referenceNumber = "",  amount = "",currency="",destinationAccount="",
    destinationBank= "", senderPrincipal = "", senderCrendetials = "",  transferReference = "", 
         sourceOfFunds = "", sendWithdrawalCode = ""
    , minRecipientKYCLevel = "",   holdingPeriod = "", principal = "" , credentials = "", hash = "";
    */
    // check for the presence of all required parameters
    if (StringUtils.isBlank(referenceNumber) || StringUtils.isBlank(amount)
            || StringUtils.isBlank(destinationAccount)) {

        expected.put("am_referenceid", referenceNumber);
        expected.put("am_timestamp", "tombwa");
        expected.put("status_code", statuscode);
        expected.put("status_description", Statusdescription);
        String jsonResult = g.toJson(expected);

        return jsonResult;
    }
    MessageDigest md = null;
    String saltedToken = referenceNumber + amount + destinationAccount + hashkey;
    md = MessageDigest.getInstance("SHA-512");
    md.update(saltedToken.getBytes());
    byte byteData[] = md.digest();

    //convert the byte to hex format method 1
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < byteData.length; i++) {
        sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
    }

    System.out.println("Hex format : " + sb.toString());
    String hash = sb.toString();

    int intamount = Integer.parseInt(amount);

    toPaga.put("referenceNumber", referenceNumber);
    toPaga.put("amount", amount);

    toPaga.put("destinationAccount", destinationAccount);

    System.out.println(toPaga.toString());

    //assign the remit url from properties.config
    CLIENT_URL = remiturl;
    //principal = "" , credentials = "", hash = ""
    PostWithIgnoreSSLPaga = new PostWithIgnoreSSLPaga(CLIENT_URL, toPaga.toString(), principal, credentials,
            hash);

    //capture the switch respoinse.
    responseobject = PostWithIgnoreSSLPaga.doPost();

    System.out.println(responseobject);

    //pass the returned json string
    JsonElement roots = new JsonParser().parse(responseobject);

    int responseCode = roots.getAsJsonObject().get("responseCode").getAsInt();

    String switchresponse = Integer.toString(responseCode);

    //add 

    String success = "S001";

    if (responseCode == 0) {

        //exctract a specific json element from the object(status_code)
        String statusdescription = roots.getAsJsonObject().get("message").getAsString();

        expected.put("am_referenceid", referenceNumber);
        expected.put("am_timestamp", success);
        expected.put("status_code", "S001");
        expected.put("status_description", statusdescription);
        String jsonResult = g.toJson(expected);

        return jsonResult;
    }

    expected.put("am_referenceid", "");
    expected.put("am_timestamp", "");
    expected.put("status_code", "");
    expected.put("status_description", "");

    String jsonResult = g.toJson(expected);

    return jsonResult;

}

From source file:com.impala.paga.all.BankRouteRemit.java

/**
 * /*from  w  w w  . j a  va 2 s . c  o m*/
 * @param request
 * @return
 * @throws IOException
 */
private String SendRequest(HttpServletRequest request) throws IOException, NoSuchAlgorithmException {
    // joined json string
    Account account = null;
    Properties prop = new Properties();
    String hashkey = prop.getProperty("hashkey");
    String principal = prop.getProperty("principal");
    String credentials = prop.getProperty("credentials");
    // String hashkey ="372e9b1c62ef47db83c566cf2db033cb4e1b847e12ec435997971ebd7ab8121cbd8458176374480eae7d4cb55f722f4ab328207b461f423a85a9bbad8850ce66";
    // String principal="02A10715-0E53-4A8C-982E-2B7BFC7CF550";
    // String credentials ="QE3@u=jd*2b+";

    String join = "";
    JsonElement root = null, roots = null;
    JsonObject root2 = null, creditrequest = null;
    JSONObject toPaga = new JSONObject();

    String apiusername = "", apipassword = "", username = "", transactioinid = "", sourcecountrycode = "",
            recipientcurrencycode = "", recipientcountrycode = "", sourcemsisdn = "", recipientmobile = "",
            sendername = "", amountstring = "", remiturlss = "", responseobject = "", statuscode = "",
            statusdescription = "", referencenumber = "", senderaddress = "", sendercity = "",
            accountnumber = "", bankcode = "", recipientname = "";

    // Get all parameters, the keys of the parameters are specified
    List<String> lines = IOUtils.readLines(request.getReader());

    // used to format/join incoming JSon string
    join = StringUtils.join(lines.toArray(), "");

    // ###############################################################################################
    // instantiate the JSon
    // Note
    // The = sign is encoded to \u003d. Hence you need to use
    // disableHtmlEscaping().
    // ###############################################################################################

    Gson g = new GsonBuilder().disableHtmlEscaping().create();
    // Gson g = new Gson();
    Map<String, String> expected = new HashMap<>();

    try {
        // parse the JSon string
        root = new JsonParser().parse(join);

        apiusername = root.getAsJsonObject().get("username").getAsString();

        apipassword = root.getAsJsonObject().get("password").getAsString();

        username = root.getAsJsonObject().get("sendingIMT").getAsString();

        transactioinid = root.getAsJsonObject().get("transaction_id").getAsString();

        sourcecountrycode = root.getAsJsonObject().get("sourcecountrycode").getAsString();

        recipientcurrencycode = root.getAsJsonObject().get("recipientcurrencycode").getAsString();

        recipientcountrycode = root.getAsJsonObject().get("recipientcountrycode").getAsString();

        sendername = root.getAsJsonObject().get("Sender_Name").getAsString();

        amountstring = root.getAsJsonObject().get("amount").getAsString();

        remiturlss = root.getAsJsonObject().get("url").getAsString();

        sourcemsisdn = root.getAsJsonObject().get("source_msisdn").getAsString();

        recipientmobile = root.getAsJsonObject().get("beneficiary_msisdn").getAsString();

        senderaddress = root.getAsJsonObject().get("sender_address").getAsString();

        sendercity = root.getAsJsonObject().get("sender_city").getAsString();

        bankcode = root.getAsJsonObject().get("bank_code").getAsString();

        accountnumber = root.getAsJsonObject().get("account_number").getAsString();

        recipientname = root.getAsJsonObject().get("recipient_name").getAsString();

        root2 = root.getAsJsonObject();

    } catch (Exception e) {

        expected.put("command_status", APIConstants.COMMANDSTATUS_INVALID_PARAMETERS);
        String jsonResult = g.toJson(expected);

        return jsonResult;
    }

    // check for the presence of all required parameters
    if (StringUtils.isBlank(apiusername) || StringUtils.isBlank(apipassword) || StringUtils.isBlank(username)
            || StringUtils.isBlank(transactioinid) || StringUtils.isBlank(sourcecountrycode)
            || StringUtils.isBlank(recipientcurrencycode) || StringUtils.isBlank(sendername)
            || StringUtils.isBlank(amountstring) || StringUtils.isBlank(remiturlss)
            || StringUtils.isBlank(senderaddress) || StringUtils.isBlank(recipientmobile)
            || StringUtils.isBlank(sourcemsisdn) || StringUtils.isBlank(sendercity)
            || StringUtils.isBlank(bankcode) || StringUtils.isBlank(accountnumber)
            || StringUtils.isBlank(recipientcountrycode) || StringUtils.isBlank(recipientname)) {

        expected.put("status_code", "server error");
        expected.put("status_description", "missing parameters");
        String jsonResult = g.toJson(expected);

        return jsonResult;
    }

    if (root2.has("vendor_uniquefields")) {

    }

    // Retrieve the account details
    Element element;
    if ((element = accountsCache.get(username)) != null) {
        account = (Account) element.getObjectValue();
    }

    // Secure against strange servers making request(future upgrade should
    // lock on IP)
    if (account == null) {
        expected.put("status_code", "server error");
        expected.put("status_description", "unauthorised user");
        String jsonResult = g.toJson(expected);

        return jsonResult;
    }

    MessageDigest md = null;
    String saltedToken = transactioinid + amountstring + bankcode + accountnumber + hashkey;
    md = MessageDigest.getInstance("SHA-512");
    md.update(saltedToken.getBytes());
    byte byteData[] = md.digest();

    //convert the byte to hex format method 1
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < byteData.length; i++) {
        sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
    }

    System.out.println("Hex format : " + sb.toString());
    String hash = sb.toString();

    Double intamount = Double.parseDouble(amountstring);

    /*{ referenceNumber": "", "amount": "", "currency": "",
    "destinationBankUUID": "","destinationBankAccountNumber": "", 
    "recipientPhoneNumber": ""}
    */

    toPaga.put("referenceNumber", transactioinid);
    toPaga.put("amount", amountstring);
    toPaga.put("currency", recipientcurrencycode);
    toPaga.put("destinationBankUUID", bankcode);
    toPaga.put("destinationBankAccountNumber", accountnumber);
    toPaga.put("recipientPhoneNumber", recipientmobile);

    //toVitesse.put("source","IMPALAPAY");

    System.out.println(toPaga.toString());

    //assign the remit url from properties.config
    CLIENT_URL = remiturlss;
    //principal = "" , credentials = "", hash = ""
    PostWithIgnoreSSLPaga = new PostWithIgnoreSSLPaga(CLIENT_URL, toPaga.toString(), principal, credentials,
            hash);

    //capture the switch respoinse.
    responseobject = PostWithIgnoreSSLPaga.doPost();

    System.out.println(responseobject);

    //pass the returned json string
    JsonElement roots2 = new JsonParser().parse(responseobject);

    int responseCode = roots2.getAsJsonObject().get("responseCode").getAsInt();

    String switchresponse = Integer.toString(responseCode);

    //exctract a specific json element from the object(status_code)
    String message = roots2.getAsJsonObject().get("message").getAsString();

    //add 

    String success = "S001";

    if (responseCode == 0) {

        expected.put("am_referenceid", transactioinid);
        expected.put("am_timestamp", success);
        expected.put("status_code", "S001");
        expected.put("status_description", message);
        String jsonResult = g.toJson(expected);

        return jsonResult;
    }

    expected.put("am_referenceid", "");
    expected.put("am_timestamp", responseCode + "");
    expected.put("status_code", "00029");
    expected.put("status_description", message);

    String jsonResult = g.toJson(expected);

    return jsonResult;

}

From source file:net.myrrix.web.servlets.IngestServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    MyrrixRecommender recommender = getRecommender();

    boolean fromBrowserUpload = request.getContentType().startsWith("multipart/form-data");

    Reader reader;/* w  w  w .  ja  v  a 2 s.c  o m*/
    if (fromBrowserUpload) {

        Collection<Part> parts = request.getParts();
        if (parts == null || parts.isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No form data");
            return;
        }
        Part part = parts.iterator().next();
        String partContentType = part.getContentType();
        InputStream in = part.getInputStream();
        if ("application/zip".equals(partContentType)) {
            in = new ZipInputStream(in);
        } else if ("application/gzip".equals(partContentType)) {
            in = new GZIPInputStream(in);
        } else if ("application/x-gzip".equals(partContentType)) {
            in = new GZIPInputStream(in);
        } else if ("application/bzip2".equals(partContentType)) {
            in = new BZip2CompressorInputStream(in);
        } else if ("application/x-bzip2".equals(partContentType)) {
            in = new BZip2CompressorInputStream(in);
        }
        reader = new InputStreamReader(in, Charsets.UTF_8);

    } else {

        String charEncodingName = request.getCharacterEncoding();
        Charset charEncoding = charEncodingName == null ? Charsets.UTF_8 : Charset.forName(charEncodingName);
        String contentEncoding = request.getHeader(HttpHeaders.CONTENT_ENCODING);
        if (contentEncoding == null) {
            reader = request.getReader();
        } else if ("gzip".equals(contentEncoding)) {
            reader = new InputStreamReader(new GZIPInputStream(request.getInputStream()), charEncoding);
        } else if ("zip".equals(contentEncoding)) {
            reader = new InputStreamReader(new ZipInputStream(request.getInputStream()), charEncoding);
        } else if ("bzip2".equals(contentEncoding)) {
            reader = new InputStreamReader(new BZip2CompressorInputStream(request.getInputStream()),
                    charEncoding);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported Content-Encoding");
            return;
        }

    }

    try {
        recommender.ingest(reader);
    } catch (IllegalArgumentException iae) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.toString());
        return;
    } catch (NoSuchElementException nsee) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
        return;
    } catch (TasteException te) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.toString());
        getServletContext().log("Unexpected error in " + getClass().getSimpleName(), te);
        return;
    }

    String referer = request.getHeader(HttpHeaders.REFERER);
    if (fromBrowserUpload && referer != null) {
        // Parsing avoids response splitting
        response.sendRedirect(new URL(referer).toString());
    }

}

From source file:io.fabric8.gateway.servlet.ProxyServlet.java

/**
 * Sets up the given {@link PostMethod} to send the same standard
 * data as was sent in the given {@link javax.servlet.http.HttpServletRequest}
 *
 * @param entityEnclosingMethod The {@link EntityEnclosingMethod} that we are
 *                               configuring to send a standard request
 * @param httpServletRequest     The {@link javax.servlet.http.HttpServletRequest} that contains
 *                               the data to be sent via the {@link EntityEnclosingMethod}
 *///from   w  w w  .ja  v a 2 s . c o m
@SuppressWarnings("unchecked")
private void handleEntity(EntityEnclosingMethod entityEnclosingMethod, HttpServletRequest httpServletRequest)
        throws IOException {
    // Get the client POST data as a Map
    Map<String, String[]> mapPostParameters = (Map<String, String[]>) httpServletRequest.getParameterMap();
    // Create a List to hold the NameValuePairs to be passed to the PostMethod
    List<NameValuePair> listNameValuePairs = new ArrayList<NameValuePair>();
    // Iterate the parameter names
    for (String stringParameterName : mapPostParameters.keySet()) {
        // Iterate the values for each parameter name
        String[] stringArrayParameterValues = mapPostParameters.get(stringParameterName);
        for (String stringParamterValue : stringArrayParameterValues) {
            // Create a NameValuePair and store in list
            NameValuePair nameValuePair = new NameValuePair(stringParameterName, stringParamterValue);
            listNameValuePairs.add(nameValuePair);
        }
    }
    RequestEntity entity = null;
    String contentType = httpServletRequest.getContentType();
    if (contentType != null) {
        contentType = contentType.toLowerCase();
        if (contentType.contains("json") || contentType.contains("xml") || contentType.contains("application")
                || contentType.contains("text")) {
            String body = IOHelpers.readFully(httpServletRequest.getReader());
            entity = new StringRequestEntity(body, contentType, httpServletRequest.getCharacterEncoding());
            entityEnclosingMethod.setRequestEntity(entity);
        }
    }
    NameValuePair[] parameters = listNameValuePairs.toArray(new NameValuePair[] {});
    if (entity != null) {
        // TODO add as URL parameters?
        //postMethodProxyRequest.addParameters(parameters);
    } else {
        // Set the proxy request POST data
        if (entityEnclosingMethod instanceof PostMethod) {
            ((PostMethod) entityEnclosingMethod).setRequestBody(parameters);
        }
    }
}

From source file:servlets.Analysis_servlets.java

private void lock_analysis_handler(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    boolean alreadyLocked = false;
    String locker_id = "";
    ArrayList<String> notLockedSteps = new ArrayList<String>();

    try {//from ww  w.  j  a v a2s .  c o  m
        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 analysis_id = requestData.get("analysis_id").getAsString();
        alreadyLocked = !BlockedElementsManager.getBlockedElementsManager().lockObject(analysis_id, loggedUser);

        /**
         * *******************************************************
         * STEP 3 TRY TO LOCK THE STEPS. exception, GO TO STEP ELSE --> GO
         * TO STEP 3 *******************************************************
         */
        if (!alreadyLocked) {
            DAO dao_instance = DAOProvider.getDAOByName("Analysis");
            boolean loadRecursive = true;
            Object[] params = { loadRecursive };
            Analysis analysis = (Analysis) dao_instance.findByID(analysis_id, params);
            dao_instance.closeConnection();
            String step_id;
            for (Step step : analysis.getNonProcessedData()) {
                step_id = step.getStepID();
                if (!BlockedElementsManager.getBlockedElementsManager().lockObject(step_id, loggedUser)) {
                    notLockedSteps.add(step_id);
                }
            }
            for (Step step : analysis.getProcessedData()) {
                step_id = step.getStepID();
                if (!BlockedElementsManager.getBlockedElementsManager().lockObject(step_id, loggedUser)) {
                    notLockedSteps.add(step_id);
                }
            }

            //UNLOCK STEPS AND ANALYSIS
            if (notLockedSteps.size() > 0) {
                BlockedElementsManager.getBlockedElementsManager().unlockObject(analysis_id, loggedUser);
                for (Step step : analysis.getNonProcessedData()) {
                    BlockedElementsManager.getBlockedElementsManager().unlockObject(step.getStepID(),
                            loggedUser);
                }
                for (Step step : analysis.getProcessedData()) {
                    BlockedElementsManager.getBlockedElementsManager().unlockObject(step.getStepID(),
                            loggedUser);
                }
            }
        } else {
            locker_id = BlockedElementsManager.getBlockedElementsManager().getLockerID(analysis_id);
        }
    } catch (Exception e) {
        ServerErrorManager.handleException(e, Analysis_servlets.class.getName(), "lock_analysis_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 .
             * *******************************************************
             */
            JsonObject obj = new JsonObject();
            if (alreadyLocked) {
                obj.add("success", new JsonPrimitive(false));
                obj.add("reason", new JsonPrimitive(BlockedElementsManager.getErrorMessage()));
                obj.add("user_id", new JsonPrimitive(locker_id));
            } else if (notLockedSteps.size() > 0) {
                JsonArray _notLockedSteps = new JsonArray();
                obj.add("success", new JsonPrimitive(false));
                obj.add("reason", new JsonPrimitive("Some of the steps are locked by other users"));
                for (String step_id : notLockedSteps) {
                    _notLockedSteps.add(new JsonPrimitive(step_id));
                }
                obj.add("notLockedSteps", _notLockedSteps);

            } else {
                obj.add("success", new JsonPrimitive(true));
            }
            response.getWriter().print(obj.toString());
        }
    }
}

From source file:org.apache.marmotta.platform.core.webservices.resource.MetaWebService.java

public Response putMeta(String uri, String mimetype, HttpServletRequest request) throws HttpErrorException {
    try {/*from   ww w  . ja va2s .com*/
        // create parser
        RDFFormat parser = kiWiIOService.getParser(mimetype);
        if (parser == null) {
            return status(Status.UNSUPPORTED_MEDIA_TYPE)
                    .header(CONTENT_TYPE, appendMetaTypes(kiWiIOService.getProducedTypes()))
                    .entity("media type " + mimetype + " not supported").build();
        }
        if (request.getContentLength() == 0) {
            throw new HttpErrorException(Status.BAD_REQUEST, uri, "content may not be empty in resource update",
                    ImmutableMap.of(ACCEPT, mimetype));
        }

        // a intercepting connection that filters out all triples that have
        // the wrong subject
        InterceptingRepositoryConnection connection = new InterceptingRepositoryConnectionWrapper(
                sesameService.getRepository(), sesameService.getConnection());
        //RepositoryConnection connection = sesameService.getConnection();
        try {
            connection.begin();
            final Resource subject = connection.getValueFactory().createURI(uri);

            connection.addRepositoryConnectionInterceptor(new ResourceSubjectMetadata(subject));

            // delete all triples for given subject
            connection.remove(subject, null, null, (Resource) null);

            // add RDF data from input to the suject
            connection.add(request.getReader(), configurationService.getBaseUri(), parser,
                    contextService.getDefaultContext());
        } finally {
            connection.commit();
            connection.close();
        }
        return ok().build();
    } catch (URISyntaxException e) {
        throw new HttpErrorException(Status.INTERNAL_SERVER_ERROR, uri, "invalid target context",
                ImmutableMap.of(ACCEPT, mimetype));
    } catch (IOException | RDFParseException e) {
        throw new HttpErrorException(Status.NOT_ACCEPTABLE, uri, "could not parse request body",
                ImmutableMap.of(ACCEPT, mimetype));
    } catch (RepositoryException e) {
        throw new HttpErrorException(Status.INTERNAL_SERVER_ERROR, request, e);
    }
}

From source file:com.liferay.petra.doulos.servlet.DoulosServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

    String remoteAddr = request.getRemoteAddr();

    if (_log.isInfoEnabled()) {
        _log.info("Remote address: " + remoteAddr);
    }//from  w ww  .j  a v  a 2  s  .  c o  m

    if (!isValidIP(remoteAddr)) {
        sendError(response, "IP " + remoteAddr + " is invalid.");

        return;
    }

    String pathInfo = request.getPathInfo();

    if (pathInfo.length() > 1) {
        if (pathInfo.endsWith("/")) {
            pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
        }
    }

    for (Map.Entry<String, DoulosRequestProcessor> entry : _doulosRequestProcessors.entrySet()) {

        String doulosRequestProcessorKey = entry.getKey();

        if (!pathInfo.startsWith(doulosRequestProcessorKey)) {
            continue;
        }

        DoulosRequestProcessor doulosRequestProcessor = entry.getValue();

        if (_log.isInfoEnabled()) {
            _log.info(StringBundler.concat("Processing ", String.valueOf(request.getRequestURL()), " with ",
                    String.valueOf(doulosRequestProcessor)));
        }

        try {
            String payload = request.getParameter("payload");

            if (_log.isInfoEnabled()) {
                _log.info("Payload parameter: " + payload);
            }

            if (payload == null) {
                StringBuilder sb = new StringBuilder();

                String line = null;

                BufferedReader bufferedReader = request.getReader();

                while ((line = bufferedReader.readLine()) != null) {
                    sb.append(line);
                }

                bufferedReader.close();

                payload = sb.toString();

                if (_log.isInfoEnabled()) {
                    _log.info("Payload body: " + payload);
                }
            }

            JSONObject payloadJSONObject = null;

            if (payload.length() > 0) {
                payloadJSONObject = new JSONObject(payload);
            } else {
                payloadJSONObject = new JSONObject();
            }

            JSONObject responseJSONObject = new JSONObject();

            doulosRequestProcessor.process(request.getMethod(),
                    pathInfo.substring(doulosRequestProcessorKey.length()), request.getParameterMap(),
                    payloadJSONObject, responseJSONObject);

            String redirect = responseJSONObject.optString("doulosRedirect");

            if (!isBlank(redirect)) {
                response.sendRedirect(redirect);

                return;
            }

            String json = responseJSONObject.toString();

            write(response, new ByteArrayInputStream(json.getBytes("UTF-8")));
        } catch (Exception e) {
            StringWriter stringWriter = new StringWriter();

            PrintWriter printWriter = new PrintWriter(stringWriter);

            e.printStackTrace(printWriter);

            String output = stringWriter.toString();

            if (_log.isInfoEnabled()) {
                _log.info(output);
            }

            sendError(response, output);
        }

        return;
    }

    sendError(response, "Unregistered path " + request.getPathInfo() + ".");
}

From source file:servlets.Analysis_servlets.java

private void add_analysis_handler(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {//  w ww .  j  a  v a 2 s. c  o  m
        String lockedID = null;
        boolean ROLLBACK_NEEDED = false;
        DAO daoInstance = null;
        Analysis analysis = 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
             * 6b 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 new ID for the ANALYSIS. IF ERROR --> throws
             * SQL Exception, GO TO STEP 5b ELSE --> GO TO STEP 3
             * *******************************************************
             */
            daoInstance = DAOProvider.getDAOByName("Analysis");
            lockedID = daoInstance.getNextObjectID(null);

            /**
             * *******************************************************
             * STEP 3 Get the ANALYSIS Object by parsing the JSON data. IF
             * ERROR --> throws JsonParseException, GO TO STEP 5b ELSE -->
             * GO TO STEP 4
             * *******************************************************
             */
            //Get parameters
            analysis = Analysis.fromJSON(requestData.get("analysis_json_data"));

            ArrayList<Step> steps = new ArrayList<Step>();
            for (Step step : analysis.getNonProcessedData()) {
                if (!"new_deleted".equals(step.getStatus())) {
                    steps.add(step);
                }
            }
            analysis.setNonProcessedData(steps.toArray(new NonProcessedData[] {}));

            steps = new ArrayList<Step>();
            for (Step step : analysis.getProcessedData()) {
                if (!"new_deleted".equals(step.getStatus())) {
                    steps.add(step);
                }
            }
            analysis.setProcessedData(steps.toArray(new ProcessedData[] {}));

            String experimentID = requestData.get("currentExperimentID").getAsString();

            //Parse the data
            analysis.updateAnalysisID(lockedID);
            analysis.setAssociated_experiment(experimentID);

            /**
             * *******************************************************
             * STEP 4 Add the new ANALYSIS Object in the DATABASE. IF ERROR
             * --> throws SQL Exception, GO TO STEP 5b ELSE --> GO TO STEP 5
             * *******************************************************
             */
            daoInstance.disableAutocommit();
            ROLLBACK_NEEDED = true;
            daoInstance.insert(analysis);

            /**
             * *******************************************************
             * STEP 5 COMMIT CHANGES TO DATABASE. throws SQLException IF
             * ERROR --> throws SQL Exception, GO TO STEP 5b ELSE --> GO TO
             * STEP 6
             * *******************************************************
             */
            daoInstance.doCommit();

        } catch (Exception e) {
            ServerErrorManager.handleException(e, Analysis_servlets.class.getName(), "add_analysis_handler",
                    e.getMessage());
        } finally {
            /**
             * *******************************************************
             * STEP 5b CATCH ERROR, CLEAN CHANGES. throws SQLException
             * *******************************************************
             */
            if (ServerErrorManager.errorStatus()) {
                response.setStatus(400);
                response.getWriter().print(ServerErrorManager.getErrorResponse());
                if (ROLLBACK_NEEDED) {
                    daoInstance.doRollback();
                }
            } else {
                JsonObject obj = new JsonObject();
                obj.add("newID", new JsonPrimitive(lockedID));
                response.getWriter().print(obj.toString());
            }

            /**
             * UNLOCK THE IDS
             */
            if (lockedID != null) {
                BlockedElementsManager.getBlockedElementsManager().unlockID(lockedID);
            }
            /**
             * *******************************************************
             * STEP 6 Close connection.
             * ********************************************************
             */
            if (daoInstance != null) {
                daoInstance.closeConnection();
            }
        }
        //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE 
    } catch (Exception e) {
        ServerErrorManager.handleException(e, Analysis_servlets.class.getName(), "add_analysis_handler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}