Example usage for javax.servlet.http HttpServletRequest getCharacterEncoding

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

Introduction

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

Prototype

public String getCharacterEncoding();

Source Link

Document

Returns the name of the character encoding used in the body of this request.

Usage

From source file:com.ocpsoft.pretty.PrettyContext.java

/**
 * Must create instance through the initialize() method
 *///w  ww.j a va2s.com
protected PrettyContext(final HttpServletRequest request) {
    Assert.notNull(request, "HttpServletRequest argument was null");

    // attribute is set by PrettyFacesRewriteLifecycleListener before
    config = (PrettyConfig) request.getAttribute(CONFIG_KEY);

    // not sure if this can happen any more, but we'll keep it for now
    if (config == null) {
        config = new PrettyConfig();
    }

    contextPath = request.getContextPath();
    String requestUrl = stripContextPath(request.getRequestURI());
    Matcher sessionIdMatcher = JSESSIONID_PATTERN.matcher(requestUrl);
    if (sessionIdMatcher.matches()) {
        requestUrl = sessionIdMatcher.replaceFirst(JSESSIONID_REPLACEMENT);
    }

    String encoding = request.getCharacterEncoding() == null ? DEFAULT_ENCODING
            : request.getCharacterEncoding();

    requestURL = new URL(requestUrl);
    requestURL.setEncoding(encoding);
    requestURL = requestURL.decode();

    requestQuery = QueryString.build(request.getQueryString());

    log.trace("Initialized PrettyContext");
}

From source file:org.sakaiproject.portal.util.ErrorReporter.java

@SuppressWarnings("rawtypes")
private String requestDisplay(HttpServletRequest request) {
    ResourceBundle rb = rbDefault;
    StringBuilder sb = new StringBuilder();
    try {/*from   w  w w .  ja v  a2s .c  om*/
        sb.append(rb.getString("bugreport.request")).append("\n");
        sb.append(rb.getString("bugreport.request.authtype")).append(request.getAuthType()).append("\n");
        sb.append(rb.getString("bugreport.request.charencoding")).append(request.getCharacterEncoding())
                .append("\n");
        sb.append(rb.getString("bugreport.request.contentlength")).append(request.getContentLength())
                .append("\n");
        sb.append(rb.getString("bugreport.request.contenttype")).append(request.getContentType()).append("\n");
        sb.append(rb.getString("bugreport.request.contextpath")).append(request.getContextPath()).append("\n");
        sb.append(rb.getString("bugreport.request.localaddr")).append(request.getLocalAddr()).append("\n");
        sb.append(rb.getString("bugreport.request.localname")).append(request.getLocalName()).append("\n");
        sb.append(rb.getString("bugreport.request.localport")).append(request.getLocalPort()).append("\n");
        sb.append(rb.getString("bugreport.request.method")).append(request.getMethod()).append("\n");
        sb.append(rb.getString("bugreport.request.pathinfo")).append(request.getPathInfo()).append("\n");
        sb.append(rb.getString("bugreport.request.protocol")).append(request.getProtocol()).append("\n");
        sb.append(rb.getString("bugreport.request.querystring")).append(request.getQueryString()).append("\n");
        sb.append(rb.getString("bugreport.request.remoteaddr")).append(request.getRemoteAddr()).append("\n");
        sb.append(rb.getString("bugreport.request.remotehost")).append(request.getRemoteHost()).append("\n");
        sb.append(rb.getString("bugreport.request.remoteport")).append(request.getRemotePort()).append("\n");
        sb.append(rb.getString("bugreport.request.requesturl")).append(request.getRequestURL()).append("\n");
        sb.append(rb.getString("bugreport.request.scheme")).append(request.getScheme()).append("\n");
        sb.append(rb.getString("bugreport.request.servername")).append(request.getServerName()).append("\n");
        sb.append(rb.getString("bugreport.request.headers")).append("\n");
        for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
            String headerName = (String) e.nextElement();
            boolean censor = (censoredHeaders.get(headerName) != null);
            for (Enumeration he = request.getHeaders(headerName); he.hasMoreElements();) {
                String headerValue = (String) he.nextElement();
                sb.append(rb.getString("bugreport.request.header")).append(headerName).append(":")
                        .append(censor ? "---censored---" : headerValue).append("\n");
            }
        }
        sb.append(rb.getString("bugreport.request.parameters")).append("\n");
        for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {

            String parameterName = (String) e.nextElement();
            boolean censor = (censoredParameters.get(parameterName) != null);
            String[] paramvalues = request.getParameterValues(parameterName);
            for (int i = 0; i < paramvalues.length; i++) {
                sb.append(rb.getString("bugreport.request.parameter")).append(parameterName).append(":")
                        .append(i).append(":").append(censor ? "----censored----" : paramvalues[i])
                        .append("\n");
            }
        }
        sb.append(rb.getString("bugreport.request.attributes")).append("\n");
        for (Enumeration e = request.getAttributeNames(); e.hasMoreElements();) {
            String attributeName = (String) e.nextElement();
            Object attribute = request.getAttribute(attributeName);
            boolean censor = (censoredAttributes.get(attributeName) != null);
            sb.append(rb.getString("bugreport.request.attribute")).append(attributeName).append(":")
                    .append(censor ? "----censored----" : attribute).append("\n");
        }
        HttpSession session = request.getSession(false);
        if (session != null) {
            DateFormat serverLocaleDateFormat = DateFormat.getDateInstance(DateFormat.FULL,
                    Locale.getDefault());
            sb.append(rb.getString("bugreport.session")).append("\n");
            sb.append(rb.getString("bugreport.session.creation")).append(session.getCreationTime())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.lastaccess")).append(session.getLastAccessedTime())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.creationdatetime"))
                    .append(serverLocaleDateFormat.format(session.getCreationTime())).append("\n");
            sb.append(rb.getString("bugreport.session.lastaccessdatetime"))
                    .append(serverLocaleDateFormat.format(session.getLastAccessedTime())).append("\n");
            sb.append(rb.getString("bugreport.session.maxinactive")).append(session.getMaxInactiveInterval())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.attributes")).append("\n");
            for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) {
                String attributeName = (String) e.nextElement();
                Object attribute = session.getAttribute(attributeName);
                boolean censor = (censoredAttributes.get(attributeName) != null);
                sb.append(rb.getString("bugreport.session.attribute")).append(attributeName).append(":")
                        .append(censor ? "----censored----" : attribute).append("\n");
            }

        }
    } catch (Exception ex) {
        M_log.error("Failed to generate request display", ex);
        sb.append("Error " + ex.getMessage());
    }

    return sb.toString();
}

From source file:org.cerberus.servlet.crud.testcampaign.UpdateCampaign2.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  w  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, CerberusException, JSONException {

    JSONObject jsonResponse = new JSONObject();
    ApplicationContext appContext = WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext());
    Answer ans = new Answer();
    Answer finalAnswer = new Answer(new MessageEvent(MessageEventEnum.DATA_OPERATION_OK));

    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String charset = request.getCharacterEncoding();

    // Parameter that are already controled by GUI (no need to decode) --> We SECURE them
    // Parameter that needs to be secured --> We SECURE+DECODE them
    int cID = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("CampaignID"), 0, charset);
    String c = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("Campaign"), null,
            charset);
    String desc = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("Description"),
            null, charset);

    if (StringUtil.isNullOrEmpty(c)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Campaign").replace("%OPERATION%", "Update")
                .replace("%REASON%", "Campaign name is missing!"));
        finalAnswer.setResultMessage(msg);
    } else {
        // Parameter that we cannot secure as we need the html --> We DECODE them
        String battery = ParameterParserUtil.parseStringParam(request.getParameter("Batteries"), null);
        String parameter = ParameterParserUtil.parseStringParam(request.getParameter("Parameters"), null);

        ICampaignService campaignService = appContext.getBean(ICampaignService.class);

        AnswerItem resp = campaignService.readByKey(c);
        if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) {
            /**
             * Object could not be found. We stop here and report the error.
             */
            finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) resp);
        } else {
            Campaign camp = (Campaign) resp.getItem();
            if (!desc.equals(camp.getDescription())) {
                camp.setDescription(desc);
                finalAnswer = campaignService.update(camp);
                if (finalAnswer.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                    /**
                     * Adding Log entry.
                     */
                    ILogEventService logEventService = appContext.getBean(LogEventService.class);
                    logEventService.createPrivateCalls("/UpdateCampaign", "UPDATE", "Update Campaign : " + c,
                            request);
                }
            }

            if (finalAnswer.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && battery != null) {
                JSONArray batteries = new JSONArray(battery);
                ICampaignContentService campaignContentService = appContext
                        .getBean(ICampaignContentService.class);
                IFactoryCampaignContent factoryCampaignContent = appContext
                        .getBean(IFactoryCampaignContent.class);
                ArrayList<CampaignContent> arr = new ArrayList<>();
                for (int i = 0; i < batteries.length(); i++) {
                    JSONArray bat = batteries.getJSONArray(i);
                    CampaignContent co = factoryCampaignContent.create(0, bat.getString(0), bat.getString(1));
                    arr.add(co);
                }

                finalAnswer = campaignContentService.compareListAndUpdateInsertDeleteElements(c, arr);
                if (finalAnswer.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                    /**
                     * Adding Log entry.
                     */
                    ILogEventService logEventService = appContext.getBean(LogEventService.class);
                    logEventService.createPrivateCalls("/UpdateCampaign", "UPDATE",
                            "Update Campaign Content : " + camp.getCampaign(), request);
                }
            }

            if (parameter != null) {
                JSONArray parameters = new JSONArray(parameter);
                ICampaignParameterService campaignParameterService = appContext
                        .getBean(ICampaignParameterService.class);
                IFactoryCampaignParameter factoryCampaignParameter = appContext
                        .getBean(IFactoryCampaignParameter.class);
                ArrayList<CampaignParameter> arr = new ArrayList<>();
                for (int i = 0; i < parameters.length(); i++) {
                    JSONArray bat = parameters.getJSONArray(i);
                    CampaignParameter co = factoryCampaignParameter.create(0, bat.getString(2),
                            bat.getString(1), bat.getString(3));
                    arr.add(co);
                }

                finalAnswer = campaignParameterService.compareListAndUpdateInsertDeleteElements(c, arr);
                if (finalAnswer.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                    /**
                     * Adding Log entry.
                     */
                    ILogEventService logEventService = appContext.getBean(LogEventService.class);
                    logEventService.createPrivateCalls("/UpdateCampaign", "UPDATE",
                            "Update Campaign Parameter : " + camp.getCampaign(), request);
                }
            }
        }
    }

    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", finalAnswer.getResultMessage().getDescription());

    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}

From source file:org.apache.struts.upload.CommonsMultipartRequestHandler.java

/**
 * <p> Adds a regular text parameter to the set of text parameters for
 * this request and also to the list of all parameters. Handles the case
 * of multiple values for the same parameter by using an array for the
 * parameter value. </p>/*  w  w  w.jav a  2  s  . c o m*/
 *
 * @param request The request in which the parameter was specified.
 * @param item    The file item for the parameter to add.
 */
protected void addTextParameter(HttpServletRequest request, FileItem item) {
    String name = item.getFieldName();
    String value = null;
    boolean haveValue = false;
    String encoding = null;

    if (item instanceof DiskFileItem) {
        encoding = ((DiskFileItem) item).getCharSet();
        if (log.isDebugEnabled()) {
            log.debug("DiskFileItem.getCharSet=[" + encoding + "]");
        }
    }

    if (encoding == null) {
        encoding = request.getCharacterEncoding();
        if (log.isDebugEnabled()) {
            log.debug("request.getCharacterEncoding=[" + encoding + "]");
        }
    }

    if (encoding != null) {
        try {
            value = item.getString(encoding);
            haveValue = true;
        } catch (Exception e) {
            // Handled below, since haveValue is false.
        }
    }

    if (!haveValue) {
        try {
            value = item.getString("ISO-8859-1");
        } catch (java.io.UnsupportedEncodingException uee) {
            value = item.getString();
        }

        haveValue = true;
    }

    if (request instanceof MultipartRequestWrapper) {
        MultipartRequestWrapper wrapper = (MultipartRequestWrapper) request;

        wrapper.setParameter(name, value);
    }

    String[] oldArray = (String[]) elementsText.get(name);
    String[] newArray;

    if (oldArray != null) {
        newArray = new String[oldArray.length + 1];
        System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
        newArray[oldArray.length] = value;
    } else {
        newArray = new String[] { value };
    }

    elementsText.put(name, newArray);
    elementsAll.put(name, newArray);
}

From source file:org.cerberus.servlet.crud.testexecution.ReadTestCaseExecution.java

private AnswerItem findExecutionListBySystem(String system, ApplicationContext appContext,
        HttpServletRequest request) throws ParseException, JSONException {
    AnswerItem answer = new AnswerItem(new MessageEvent(MessageEventEnum.DATA_OPERATION_OK));

    /**// www  .  ja v a2  s.c  om
     * Parse all parameters used in the search.
     */
    String charset = request.getCharacterEncoding();
    /**
     * Parse parameters - list of values
     */

    List<String> testList = ParameterParserUtil.parseListParamAndDecode(request.getParameterValues("test"),
            null, charset);
    List<String> applicationList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("application"), null, charset);
    List<String> projectList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("project"), null, charset);

    List<String> tcstatusList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("tcstatus"), null, charset);
    List<String> groupList = ParameterParserUtil.parseListParamAndDecode(request.getParameterValues("group"),
            null, charset);
    List<String> tcactiveList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("tcactive"), null, charset);
    List<String> priorityList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("priority"), null, charset);

    List<String> targetsprintList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("targetsprint"), null, charset);
    List<String> targetrevisionList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("targetrevision"), null, charset);
    List<String> creatorList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("creator"), null, charset);
    List<String> implementerList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("implementer"), null, charset);

    List<String> environmentList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("environment"), null, charset);
    List<String> buildList = ParameterParserUtil.parseListParamAndDecode(request.getParameterValues("build"),
            null, charset);
    List<String> revisionList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("revision"), null, charset);

    List<String> countryList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("country"), null, charset);
    List<String> browserList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("browser"), null, charset);
    List<String> tcestatusList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("tcestatus"), null, charset);

    //Sorts the lists 
    if (countryList != null) {
        Collections.sort(countryList);
    }
    if (browserList != null) {
        Collections.sort(browserList);
    }

    /**
     * Parse parameters - free text
     */
    String bugid = StringEscapeUtils.escapeHtml4(request.getParameter("bugid"));
    String ticket = StringEscapeUtils.escapeHtml4(request.getParameter("ticket"));
    String ip = StringEscapeUtils.escapeHtml4(request.getParameter("ip"));
    String port = StringEscapeUtils.escapeHtml4(request.getParameter("port"));
    String tag = StringEscapeUtils.escapeHtml4(request.getParameter("tag"));
    String browserversion = StringEscapeUtils.escapeHtml4(request.getParameter("browserversion"));
    String comment = StringEscapeUtils.escapeHtml4(request.getParameter("comment"));

    /**
     * Gets regular executions (not in queue)
     */
    AnswerList answerExecutions = testCaseExecutionService.readBySystemByVarious(system, testList,
            applicationList, projectList, tcstatusList, groupList, tcactiveList, priorityList, targetsprintList,
            targetrevisionList, creatorList, implementerList, buildList, revisionList, environmentList,
            countryList, browserList, tcestatusList, ip, port, tag, browserversion, comment, bugid, ticket);

    List<TestCaseExecution> testCaseExecutions = (List<TestCaseExecution>) answerExecutions.getDataList();

    /**
     * Get list of Execution in Queue by Tag
     */
    ITestCaseExecutionInQueueService testCaseExecutionInQueueService = appContext
            .getBean(ITestCaseExecutionInQueueService.class);
    AnswerList answerExecutionsInQueue = testCaseExecutionInQueueService.readBySystemByVarious(system, testList,
            applicationList, projectList, tcstatusList, groupList, tcactiveList, priorityList, targetsprintList,
            targetrevisionList, creatorList, implementerList, buildList, revisionList, environmentList,
            countryList, browserList, tcestatusList, ip, port, tag, browserversion, comment, bugid, ticket);
    List<TestCaseExecutionInQueue> testCaseExecutionsInQueue = (List<TestCaseExecutionInQueue>) answerExecutionsInQueue
            .getDataList();

    /**
     * Merge Test Case Executions
     */
    List<TestCaseExecution> allTestCaseExecutions = hashExecution(testCaseExecutions,
            testCaseExecutionsInQueue);

    JSONArray executionList = new JSONArray();
    LinkedHashMap<String, JSONObject> ttc = new LinkedHashMap<String, JSONObject>();

    for (TestCaseExecution testCaseExecution : allTestCaseExecutions) {
        try {
            JSONObject execution = testCaseExecutionToJSONObject(testCaseExecution);
            String execKey = testCaseExecution.getCountry() + " " + testCaseExecution.getBrowser(); //the key is country and browser
            String testCaseKey = testCaseExecution.getTest() + "_" + testCaseExecution.getTestCase();
            JSONObject execTab = new JSONObject();

            executionList.put(testCaseExecutionToJSONObject(testCaseExecution));
            JSONObject ttcObject = new JSONObject();

            if (ttc.containsKey(testCaseKey)) {
                ttcObject = ttc.get(testCaseKey);
                execTab = ttcObject.getJSONObject("execTab");
                execTab.put(execKey, execution);
                ttcObject.put("execTab", execTab);
            } else {
                ttcObject.put("test", testCaseExecution.getTest());
                ttcObject.put("testCase", testCaseExecution.getTestCase());
                ttcObject.put("function", testCaseExecution.getTestCaseObj().getFunction());
                ttcObject.put("shortDesc", testCaseExecution.getTestCaseObj().getDescription());
                ttcObject.put("status", testCaseExecution.getTestCaseObj().getStatus());
                ttcObject.put("application", testCaseExecution.getApplication());
                ttcObject.put("bugId", testCaseExecution.getTestCaseObj().getBugID());
                ttcObject.put("ticket", testCaseExecution.getTestCaseObj().getTicket());
                ttcObject.put("comment", testCaseExecution.getTestCaseObj().getComment());
                ttcObject.put("priority", testCaseExecution.getTestCaseObj().getPriority());
                ttcObject.put("status", testCaseExecution.getStatus());
                ttcObject.put("group", testCaseExecution.getTestCaseObj().getGroup());
                execTab.put(execKey, execution);
                ttcObject.put("execTab", execTab);
            }
            ttc.put(testCaseExecution.getTest() + "_" + testCaseExecution.getTestCase(), ttcObject);
        } catch (JSONException ex) {
            Logger.getLogger(ReadTestCaseExecution.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    JSONObject jsonResponse = new JSONObject();
    jsonResponse.put("contentTable", ttc.values());
    jsonResponse.put("iTotalRecords", ttc.size());
    jsonResponse.put("iTotalDisplayRecords", ttc.size());

    answer.setItem(jsonResponse);
    answer.setResultMessage(new MessageEvent(MessageEventEnum.DATA_OPERATION_OK));
    return answer;
}

From source file:org.rapidcontext.core.web.Request.java

/**
 * Creates a new request wrapper.//from  w ww.ja v  a 2  s .co m
 *
 * @param request        the servlet request
 * @param response       the servlet response
 */
public Request(HttpServletRequest request, HttpServletResponse response) {
    this.request = request;
    this.response = response;
    if (request.getCharacterEncoding() == null) {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException ignore) {
            // Do nothing
        }
    }
    logRequest();
}

From source file:org.eclipse.rdf4j.http.server.repository.transaction.TransactionController.java

private ModelAndView getSparqlUpdateResult(Transaction transaction, HttpServletRequest request,
        HttpServletResponse response) throws ServerHTTPException, ClientHTTPException, HTTPException {
    String sparqlUpdateString = null;
    final String contentType = request.getContentType();
    if (contentType != null && contentType.contains(Protocol.SPARQL_UPDATE_MIME_TYPE)) {
        try {// w  ww  .  j  a v  a  2 s  .c  o  m
            final String encoding = request.getCharacterEncoding() != null ? request.getCharacterEncoding()
                    : "UTF-8";
            sparqlUpdateString = IOUtils.toString(request.getInputStream(), encoding);
        } catch (IOException e) {
            logger.warn("error reading sparql update string from request body", e);
            throw new ClientHTTPException(SC_BAD_REQUEST,
                    "could not read SPARQL update string from body: " + e.getMessage());
        }
    } else {
        sparqlUpdateString = request.getParameter(Protocol.UPDATE_PARAM_NAME);
    }

    logger.debug("SPARQL update string: {}", sparqlUpdateString);

    // default query language is SPARQL
    QueryLanguage queryLn = QueryLanguage.SPARQL;

    String queryLnStr = request.getParameter(QUERY_LANGUAGE_PARAM_NAME);
    logger.debug("query language param = {}", queryLnStr);

    if (queryLnStr != null) {
        queryLn = QueryLanguage.valueOf(queryLnStr);

        if (queryLn == null) {
            throw new ClientHTTPException(SC_BAD_REQUEST, "Unknown query language: " + queryLnStr);
        }
    }

    String baseURI = request.getParameter(Protocol.BASEURI_PARAM_NAME);

    // determine if inferred triples should be included in query evaluation
    boolean includeInferred = ProtocolUtil.parseBooleanParam(request, INCLUDE_INFERRED_PARAM_NAME, true);

    // build a dataset, if specified
    String[] defaultRemoveGraphURIs = request.getParameterValues(REMOVE_GRAPH_PARAM_NAME);
    String[] defaultInsertGraphURIs = request.getParameterValues(INSERT_GRAPH_PARAM_NAME);
    String[] defaultGraphURIs = request.getParameterValues(USING_GRAPH_PARAM_NAME);
    String[] namedGraphURIs = request.getParameterValues(USING_NAMED_GRAPH_PARAM_NAME);

    SimpleDataset dataset = new SimpleDataset();

    if (defaultRemoveGraphURIs != null) {
        for (String graphURI : defaultRemoveGraphURIs) {
            try {
                IRI uri = null;
                if (!"null".equals(graphURI)) {
                    uri = SimpleValueFactory.getInstance().createIRI(graphURI);
                }
                dataset.addDefaultRemoveGraph(uri);
            } catch (IllegalArgumentException e) {
                throw new ClientHTTPException(SC_BAD_REQUEST,
                        "Illegal URI for default remove graph: " + graphURI);
            }
        }
    }

    if (defaultInsertGraphURIs != null && defaultInsertGraphURIs.length > 0) {
        String graphURI = defaultInsertGraphURIs[0];
        try {
            IRI uri = null;
            if (!"null".equals(graphURI)) {
                uri = SimpleValueFactory.getInstance().createIRI(graphURI);
            }
            dataset.setDefaultInsertGraph(uri);
        } catch (IllegalArgumentException e) {
            throw new ClientHTTPException(SC_BAD_REQUEST, "Illegal URI for default insert graph: " + graphURI);
        }
    }

    if (defaultGraphURIs != null) {
        for (String defaultGraphURI : defaultGraphURIs) {
            try {
                IRI uri = null;
                if (!"null".equals(defaultGraphURI)) {
                    uri = SimpleValueFactory.getInstance().createIRI(defaultGraphURI);
                }
                dataset.addDefaultGraph(uri);
            } catch (IllegalArgumentException e) {
                throw new ClientHTTPException(SC_BAD_REQUEST,
                        "Illegal URI for default graph: " + defaultGraphURI);
            }
        }
    }

    if (namedGraphURIs != null) {
        for (String namedGraphURI : namedGraphURIs) {
            try {
                IRI uri = null;
                if (!"null".equals(namedGraphURI)) {
                    uri = SimpleValueFactory.getInstance().createIRI(namedGraphURI);
                }
                dataset.addNamedGraph(uri);
            } catch (IllegalArgumentException e) {
                throw new ClientHTTPException(SC_BAD_REQUEST, "Illegal URI for named graph: " + namedGraphURI);
            }
        }
    }

    try {
        // determine if any variable bindings have been set on this update.
        @SuppressWarnings("unchecked")
        Enumeration<String> parameterNames = request.getParameterNames();

        Map<String, Value> bindings = new HashMap<>();
        while (parameterNames.hasMoreElements()) {
            String parameterName = parameterNames.nextElement();

            if (parameterName.startsWith(BINDING_PREFIX) && parameterName.length() > BINDING_PREFIX.length()) {
                String bindingName = parameterName.substring(BINDING_PREFIX.length());
                Value bindingValue = ProtocolUtil.parseValueParam(request, parameterName,
                        SimpleValueFactory.getInstance());
                bindings.put(bindingName, bindingValue);
            }
        }

        transaction.executeUpdate(queryLn, sparqlUpdateString, baseURI, includeInferred, dataset, bindings);

        return new ModelAndView(EmptySuccessView.getInstance());
    } catch (UpdateExecutionException | InterruptedException | ExecutionException e) {
        if (e.getCause() != null && e.getCause() instanceof HTTPException) {
            // custom signal from the backend, throw as HTTPException directly
            // (see SES-1016).
            throw (HTTPException) e.getCause();
        } else {
            throw new ServerHTTPException("Repository update error: " + e.getMessage(), e);
        }
    } catch (RepositoryException e) {
        if (e.getCause() != null && e.getCause() instanceof HTTPException) {
            // custom signal from the backend, throw as HTTPException directly
            // (see SES-1016).
            throw (HTTPException) e.getCause();
        } else {
            throw new ServerHTTPException("Repository update error: " + e.getMessage(), e);
        }
    } catch (MalformedQueryException e) {
        ErrorInfo errInfo = new ErrorInfo(ErrorType.MALFORMED_QUERY, e.getMessage());
        throw new ClientHTTPException(SC_BAD_REQUEST, errInfo.toString());
    }
}

From source file:de.betterform.agent.web.servlet.HttpRequestHandler.java

/**
 * Parses a HTTP request. Returns an array containing maps for upload
 * controls, other controls, repeat indices, and trigger. The individual
 * maps may be null in case no corresponding parameters appear in the
 * request.//from ww w .  j a v  a2  s .c o m
 *
 * @param request a HTTP request.
 * @return an array of maps containing the parsed request parameters.
 * @throws FileUploadException          if an error occurred during file upload.
 * @throws UnsupportedEncodingException if an error occurred during
 *                                      parameter value decoding.
 */
protected Map[] parseRequest(HttpServletRequest request)
        throws FileUploadException, UnsupportedEncodingException {
    Map[] parameters = new Map[4];

    if (FileUpload.isMultipartContent(new ServletRequestContext(request))) {
        UploadListener uploadListener = new UploadListener(request, this.sessionKey);
        DiskFileItemFactory factory = new MonitoredDiskFileItemFactory(uploadListener);
        factory.setRepository(new File(this.uploadRoot));
        ServletFileUpload upload = new ServletFileUpload(factory);

        String encoding = request.getCharacterEncoding();
        if (encoding == null) {
            encoding = "UTF-8";
        }

        Iterator iterator = upload.parseRequest(request).iterator();
        FileItem item;
        while (iterator.hasNext()) {
            item = (FileItem) iterator.next();
            if (LOGGER.isDebugEnabled()) {
                if (item.isFormField()) {
                    LOGGER.debug(
                            "request param: " + item.getFieldName() + " - value='" + item.getString() + "'");
                } else {
                    LOGGER.debug("file in request: " + item.getName());
                }

            }
            parseMultiPartParameter(item, encoding, parameters);
        }
    } else {
        Enumeration enumeration = request.getParameterNames();
        String name;
        String[] values;
        while (enumeration.hasMoreElements()) {
            name = (String) enumeration.nextElement();
            values = request.getParameterValues(name);

            parseURLEncodedParameter(name, values, parameters);
        }
    }

    return parameters;
}

From source file:com.esri.gpt.control.arcims.ServletConnectorProxy.java

/**
 * Communicates with redirect url and works as a transparent proxy
 * /*  w w  w  . ja  v a2 s .  co  m*/
 * @param request
 *          the servlet request
 * @param response
 *          the servlet response
 * @throws IOException
 *           if an exception occurs
 */
private void executeProxy(HttpServletRequest request, HttpServletResponse response) throws IOException {

    HttpURLConnection httpCon = null;
    URL redirectURL = null;
    InputStream input = null;
    OutputStream output = null;
    InputStream proxyInput = null;
    OutputStream proxyOutput = null;

    try {

        input = request.getInputStream();
        output = response.getOutputStream();

        String sQueryStr = request.getQueryString();
        String sAuthorization = request.getHeader("Authorization");
        String requestBody = readInputCharacters(input);
        String requestMethod = request.getMethod();
        String contentType = request.getContentType();
        String encoding = request.getCharacterEncoding();

        LOGGER.finer(" Request method = " + requestMethod);
        LOGGER.finer(" Query string = " + sQueryStr);
        LOGGER.finer(" Authorization header =" + sAuthorization);
        LOGGER.finer(" Character Encoding = " + encoding);
        LOGGER.finer(" The redirect URL is " + this._redirectURL + "?" + sQueryStr);

        redirectURL = new URL(this._redirectURL + "?" + sQueryStr);

        httpCon = (HttpURLConnection) redirectURL.openConnection();

        httpCon.setDoInput(true);
        httpCon.setDoOutput(true);
        httpCon.setUseCaches(false);
        httpCon.setRequestMethod(requestMethod);
        httpCon.setRequestProperty("Content-type", contentType);

        if (sAuthorization != null) {
            httpCon.addRequestProperty("Authorization", sAuthorization);
        }

        proxyOutput = httpCon.getOutputStream();
        send(requestBody, proxyOutput);

        String authenticateHdr = httpCon.getHeaderField("WWW-Authenticate");
        if (authenticateHdr != null) {
            LOGGER.finer(" WWW-Authenticate : " + authenticateHdr);
            response.setHeader("WWW-Authenticate",
                    StringEscapeUtils.escapeHtml4(Val.stripControls(authenticateHdr)));
        }
        LOGGER.finer(" Response Code : " + httpCon.getResponseCode());

        if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN)) {

            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR)) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } else {
            proxyInput = httpCon.getInputStream();
            send(proxyInput, output);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (input != null) {
            input.close();
        }
        if (output != null) {
            output.close();
        }
        if (proxyInput != null) {
            proxyInput.close();
        }
        if (proxyOutput != null) {
            proxyOutput.close();
        }
        if (httpCon != null) {
            httpCon.disconnect();
        }
    }
}

From source file:com.liferay.portal.upload.UploadServletRequestImpl.java

public UploadServletRequestImpl(HttpServletRequest request) {
    super(request);

    _params = new LinkedHashMap<String, LiferayFileItem[]>();

    try {/* www. j a v a 2 s. c  o  m*/
        ServletFileUpload servletFileUpload = new LiferayFileUpload(new LiferayFileItemFactory(getTempDir()),
                request);

        servletFileUpload.setSizeMax(PrefsPropsUtil.getLong(PropsKeys.UPLOAD_SERVLET_REQUEST_IMPL_MAX_SIZE));

        _liferayServletRequest = new LiferayServletRequest(request);

        List<LiferayFileItem> liferayFileItemsList = servletFileUpload.parseRequest(_liferayServletRequest);

        for (LiferayFileItem liferayFileItem : liferayFileItemsList) {
            if (liferayFileItem.isFormField()) {
                liferayFileItem.setString(request.getCharacterEncoding());
            }

            LiferayFileItem[] liferayFileItems = _params.get(liferayFileItem.getFieldName());

            if (liferayFileItems == null) {
                liferayFileItems = new LiferayFileItem[] { liferayFileItem };
            } else {
                LiferayFileItem[] newLiferayFileItems = new LiferayFileItem[liferayFileItems.length + 1];

                System.arraycopy(liferayFileItems, 0, newLiferayFileItems, 0, liferayFileItems.length);

                newLiferayFileItems[newLiferayFileItems.length - 1] = liferayFileItem;

                liferayFileItems = newLiferayFileItems;
            }

            _params.put(liferayFileItem.getFieldName(), liferayFileItems);
        }
    } catch (Exception e) {
        UploadException uploadException = new UploadException(e);

        if (e instanceof FileUploadBase.FileSizeLimitExceededException
                || e instanceof FileUploadBase.SizeLimitExceededException) {

            uploadException.setExceededSizeLimit(true);
        }

        request.setAttribute(WebKeys.UPLOAD_EXCEPTION, uploadException);

        if (_log.isDebugEnabled()) {
            _log.debug(e, e);
        }
    }
}