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:org.openrdf.http.server.repository.transaction.TransactionController.java

private ModelAndView getSparqlUpdateResult(RepositoryConnection conn, 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  w  w  .  j  a  v  a  2s  .co 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 = conn.getValueFactory().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 = conn.getValueFactory().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 = conn.getValueFactory().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 = conn.getValueFactory().createIRI(namedGraphURI);
                }
                dataset.addNamedGraph(uri);
            } catch (IllegalArgumentException e) {
                throw new ClientHTTPException(SC_BAD_REQUEST, "Illegal URI for named graph: " + namedGraphURI);
            }
        }
    }

    try {
        Update update = conn.prepareUpdate(queryLn, sparqlUpdateString, baseURI);

        update.setIncludeInferred(includeInferred);

        if (dataset != null) {
            update.setDataset(dataset);
        }

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

        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,
                        conn.getValueFactory());
                update.setBinding(bindingName, bindingValue);
            }
        }

        update.execute();

        return new ModelAndView(EmptySuccessView.getInstance());
    } catch (UpdateExecutionException 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:org.n52.ses.common.environment.SESMiniServlet.java

private void provideLandingPage(HttpServletRequest req, HttpServletResponse resp, ConfigurationRegistry conf)
        throws IOException, UnsupportedEncodingException {
    /*//www.j  a  v  a2  s. c o m
     * return landing page
     */
    if (this.landingPage != null) {
        resp.setContentType("text/html");
        synchronized (this) {
            printResponse(req, resp, this.landingPage);
        }

        return;
    }

    InputStreamReader isr = new InputStreamReader(getClass().getResourceAsStream("/landing_page.html"));
    BufferedReader br = new BufferedReader(isr);
    StringBuilder sb = new StringBuilder();

    while (br.ready()) {
        sb.append(br.readLine());
    }
    String html = sb.toString();

    String reqUrl = URLDecoder.decode(req.getRequestURL().toString(),
            (req.getCharacterEncoding() == null ? Charset.defaultCharset().name()
                    : req.getCharacterEncoding()));
    html = html.replace("[SES_URL]",
            reqUrl.substring(0, reqUrl.indexOf(req.getContextPath())) + req.getContextPath());

    /*
     * check if we are init yet
     */
    String sesPortTypeUrl, subMgrUrl, prmUrl = "";
    if (conf != null) {
        String defaulturi = conf.getEnvironment().getDefaultURI().substring(0,
                conf.getEnvironment().getDefaultURI().lastIndexOf("/services"));
        sesPortTypeUrl = defaulturi + "/services/" + SESNotificationProducer.CONTEXT_PATH;
        subMgrUrl = defaulturi + "/services/" + SESSubscriptionManager.CONTEXT_PATH;
        prmUrl = defaulturi + "/services/" + RegisterPublisher.RESOURCE_TYPE;

        conf.setSubscriptionManagerWsdl(subMgrUrl + "?wsdl");

        html = html.replace("<p id=\"ses-status\"><p>",
                "<p style=\"color:#0f0\">The service is active and available.</p>");

        html = html.replace("[GET_CAPS]",
                StringEscapeUtils.escapeHtml4(StartupInitServlet.getGetCapabilitiesRequest(sesPortTypeUrl)));
        /*
         * replace the url
         */
        synchronized (this) {
            if (this.landingPage == null) {
                this.landingPage = html.replace("[SES_PORT_TYPE_URL]", sesPortTypeUrl);
                this.landingPage = this.landingPage.replace("[SUB_MGR_URL]", subMgrUrl);
                this.landingPage = this.landingPage.replace("[PRM_URL]", prmUrl);

                resp.setContentType("text/html");
                printResponse(req, resp, this.landingPage);
            }

        }

    } else {
        /*
         * we do not have the config, warn the user
         */
        html = html.replace("<p id=\"ses-status\"><p>",
                "<p style=\"color:#f00\">The service is currently not available due to unfinished or failed initialization.</p>");

        resp.setContentType("text/html");
        printResponse(req, resp, html);
    }
}

From source file:net.bull.javamelody.TestMonitoringFilter.java

/** Test.
 * @throws ServletException e//  w ww .  j  a  v a 2  s .  c o m
 * @throws IOException e */
@Test
public void testDoFilterWithGWT() throws ServletException, IOException {
    final HttpServletRequest request = createNiceMock(HttpServletRequest.class);
    final String textGwtRpc = "text/x-gwt-rpc";
    expect(request.getContentType()).andReturn(textGwtRpc).anyTimes();
    expect(request.getInputStream()).andReturn(createInputStreamForString("1|2|3|4|5|6|7|8|9|10")).anyTimes();
    doFilter(request);

    final HttpServletRequest request2a = createNiceMock(HttpServletRequest.class);
    expect(request2a.getContentType()).andReturn("not/x-gwt-rpc").anyTimes();
    expect(request2a.getInputStream()).andReturn(createInputStreamForString("1|2|3|4|5|6|7|8|9|10")).anyTimes();
    doFilter(request2a);

    final HttpServletRequest request2b = createNiceMock(HttpServletRequest.class);
    expect(request2b.getContentType()).andReturn(textGwtRpc).anyTimes();
    expect(request2b.getInputStream()).andReturn(createInputStreamForString("1|2|3|4|5|6")).anyTimes();
    expect(request2b.getReader()).andReturn(new BufferedReader(new StringReader("1|2|3|4|5|6"))).anyTimes();
    replay(request2b);
    final PayloadNameRequestWrapper wrapper2b = new PayloadNameRequestWrapper(request2b);
    wrapper2b.getInputStream().read();
    wrapper2b.getReader().read();
    verify(request2b);

    final HttpServletRequest request2 = createNiceMock(HttpServletRequest.class);
    expect(request2.getContentType()).andReturn(textGwtRpc).anyTimes();
    expect(request2.getInputStream()).andReturn(createInputStreamForString("1|2|3|4|5|6||8|9|10")).anyTimes();
    expect(request2.getReader()).andReturn(new BufferedReader(new StringReader("1|2|3|4|5|6"))).anyTimes();
    replay(request2);
    final PayloadNameRequestWrapper wrapper2 = new PayloadNameRequestWrapper(request2);
    wrapper2.getInputStream().read();
    wrapper2.getReader().read();
    verify(request2);

    final HttpServletRequest request3 = createNiceMock(HttpServletRequest.class);
    expect(request3.getContentType()).andReturn(textGwtRpc).anyTimes();
    expect(request3.getCharacterEncoding()).andReturn("utf-8").anyTimes();
    expect(request3.getInputStream()).andReturn(createInputStreamForString("1|2|3|4|5|6||8|9|10")).anyTimes();
    expect(request3.getReader()).andReturn(new BufferedReader(new StringReader("1|2|3|4|5|6"))).anyTimes();
    replay(request3);
    final PayloadNameRequestWrapper wrapper3 = new PayloadNameRequestWrapper(request3);
    wrapper3.getInputStream().read();
    wrapper3.getInputStream().read();
    wrapper3.getReader().read();
    wrapper3.getReader().read();
    verify(request3);
}

From source file:net.openkoncept.vroom.VroomController.java

private void processRequestJSGenerate(HttpServletRequest request, HttpServletResponse response,
        String contextPath, String servletPath, String sessionId, String uri) throws IOException {
    StringBuffer sbScript = new StringBuffer();
    VroomScriptGenerator sg = new VroomScriptGenerator(VroomConfig.getInstance(), contextPath, servletPath,
            sessionId, uri);//from  ww w.j ava 2  s  .  c o m
    sbScript.append(sg.generateScript());
    String encoding = request.getHeader("response-encoding");
    if (encoding == null || encoding.trim().length() == 0) {
        encoding = request.getCharacterEncoding();
    }
    response.setContentType(JS_MIME_TYPE);
    if (encoding != null) {
        VroomUtilities.safeCall(response, "setCharacterEncoding", new Class[] { String.class },
                new Object[] { encoding });
        //            response.setCharacterEncoding(encoding);
    }
    PrintWriter out = null;
    try {
        out = response.getWriter();
        out.write(sbScript.toString());
    } finally {
        if (out != null) {
            out.close();
        }
    }

}

From source file:edu.stanford.muse.webapp.JSPHelper.java

/**
 * A VIP method.// www. j  a  v a  2  s . c om
 * reads email accounts and installs addressBook and emailDocs into session
 * useDefaultFolders: use the default folder for that fetcher if there are
 * no explicit folders in that fetcher.
 * throws out of memory error if it runs out of memory.
 * 
 * @throws JSONException
 * @throws IOException
 * @throws InterruptedException
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 * @throws NoDefaultFolderException
 * @throws Exception
 */
public static void fetchAndIndexEmails(Archive archive, MuseEmailFetcher m, HttpServletRequest request,
        HttpSession session, boolean downloadMessageText, boolean downloadAttachments,
        boolean useDefaultFolders) throws MessagingException, InterruptedException, IOException, JSONException,
        NoDefaultFolderException, CancelledException, OutOfMemoryError {
    // first thing, set up a static status so user doesn't see a stale status message
    session.setAttribute("statusProvider", new StaticStatusProvider("Starting up..."));

    checkContainer(request);
    String encoding = request.getCharacterEncoding();
    log.info("request parameter encoding is " + encoding);

    if (!downloadMessageText)
        if ("true".equalsIgnoreCase(request.getParameter("downloadMessageText"))) {
            downloadMessageText = true;
            log.info("Downloading message text because advanced option was set");
        }

    if (!downloadAttachments)
        if ("true".equalsIgnoreCase(request.getParameter("downloadAttachments"))) {
            downloadAttachments = true;
            downloadMessageText = true; // because text is needed for attachment wall -- otherwise we can't break out from piclens to browsing messages associated with a particular thumbnail
            log.info("Downloading attachments because advanced option was set");
        }

    String[] allFolders = request.getParameterValues("folder");
    if (allFolders != null) {
        // try to read folder strings, first checking for exceptions
        try {
            allFolders = JSPHelper.convertRequestParamsToUTF8(allFolders, true);
        } catch (UnsupportedEncodingException e) {
            // report exception and try to read whatever folders we can, ignoring the exception this time
            log.warn("Unsupported encoding exception: " + e);
            try {
                allFolders = JSPHelper.convertRequestParamsToUTF8(allFolders, false);
            } catch (UnsupportedEncodingException e1) {
                log.warn("Should not reach here!" + e1);
            }
        }
    }

    Map<String, String> requestMap = convertRequestToMap(request);
    Filter filter = Filter.parseFilter(requestMap);
    // if required, forceEncoding can go into fetch config
    //   String s = (String) session.getAttribute("forceEncoding");
    FetchConfig fc = new FetchConfig();
    fc.downloadMessages = downloadMessageText;
    fc.downloadAttachments = downloadAttachments;
    fc.filter = filter;

    archive.setBaseDir(getBaseDir(m, request));
    m.fetchAndIndexEmails(archive, allFolders, useDefaultFolders, fc, session);
    //make sure the archive is dumped at this point
    archive.close();
    archive.openForRead();

    //perform entity IE related tasks only if the message text is available
    if (downloadMessageText) {
        String modelFile = SequenceModel.MODEL_FILENAME;
        NERModel nerModel = (SequenceModel) session.getAttribute("ner");
        session.setAttribute("statusProvider",
                new StaticStatusProvider("Loading NER sequence model from resource: " + modelFile + "..."));
        try {
            if (System.getProperty("muse.dummy.ner") != null) {
                log.info("Using dummy NER model, all CIC patterns will be treated as valid entities");
                nerModel = new DummyNERModel();
            } else {
                log.info("Loading NER sequence model from: " + modelFile + " ...");
                nerModel = SequenceModel.loadModelFromRules(SequenceModel.RULES_DIRNAME);
            }
        } catch (IOException e) {
            Util.print_exception("Could not load the sequence model from: " + modelFile, e, log);
        }
        if (nerModel == null) {
            log.error("Could not load NER model from: " + modelFile);
        } else {
            NER ner = new NER(archive, nerModel);
            session.setAttribute("statusProvider", ner);
            ner.recognizeArchive();
            archive.processingMetadata.entityCounts = ner.stats.counts;
            log.info(ner.stats);
        }
        // archive.processingMetadata.numPotentiallySensitiveMessages = archive.numMatchesPresetQueries();
        log.info("Number of potentially sensitive messages "
                + archive.processingMetadata.numPotentiallySensitiveMessages);

        //Is there a reliable and more proper way of checking the mode it is running in?
        String logF = System.getProperty("muse.log");
        if (logF == null || logF.endsWith("epadd.log")) {
            try {
                //                InternalAuthorityAssigner assignauthorities = new InternalAuthorityAssigner();
                //                session.setAttribute("statusProvider", assignauthorities);
                //                assignauthorities.initialize(archive);
                //                if (!assignauthorities.isCancelled())
                //                    request.getSession().setAttribute("authorities", assignauthorities);
                //                else
                //                    assignauthorities = null;
                //                boolean success = assignauthorities.checkFeaturesIndex(archive, true);
                //                if (!success) {
                //                    log.warn("Could not build context mixtures for entities");
                //                } else
                //                    log.info("Successfully built context mixtures for entities");
            } catch (Exception e) {
                log.warn("Exception while building context mixtures", e);
            }
        }
    }
    // add the new stores
}

From source file:helma.servlet.AbstractServletClient.java

/**
 * Handle a request./*from   w  w  w  .  j  a v  a 2 s.com*/
 *
 * @param request ...
 * @param response ...
 *
 * @throws ServletException ...
 * @throws IOException ...
 */
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    RequestTrans reqtrans = new RequestTrans(request, response, getPathInfo(request));

    try {
        // get the character encoding
        String encoding = request.getCharacterEncoding();

        if (encoding == null) {
            // no encoding from request, use the application's charset
            encoding = getApplication().getCharset();
        }

        // read cookies
        Cookie[] reqCookies = request.getCookies();

        if (reqCookies != null) {
            for (int i = 0; i < reqCookies.length; i++) {
                try {
                    // get Cookies
                    String key = reqCookies[i].getName();

                    if (sessionCookieName.equals(key)) {
                        reqtrans.setSession(reqCookies[i].getValue());
                    }
                    reqtrans.setCookie(key, reqCookies[i]);
                } catch (Exception badCookie) {
                    log("Error setting cookie", badCookie);
                }
            }
        }

        // get the cookie domain to use for this response, if any.
        String resCookieDomain = cookieDomain;

        if (resCookieDomain != null) {
            // check if cookieDomain is valid for this response.
            // (note: cookieDomain is guaranteed to be lower case)
            // check for x-forwarded-for header, fix for bug 443
            String proxiedHost = request.getHeader("x-forwarded-host");
            if (proxiedHost != null) {
                if (proxiedHost.toLowerCase().indexOf(resCookieDomain) == -1) {
                    resCookieDomain = null;
                }
            } else {
                String host = (String) reqtrans.get("http_host");
                // http_host is guaranteed to be lower case 
                if (host != null && host.indexOf(resCookieDomain) == -1) {
                    resCookieDomain = null;
                }
            }
        }

        // check if session cookie is present and valid, creating it if not.
        checkSessionCookie(request, response, reqtrans, resCookieDomain);

        // read and set http parameters
        parseParameters(request, reqtrans, encoding);

        // read file uploads
        List uploads = null;
        ServletRequestContext reqcx = new ServletRequestContext(request);

        if (ServletFileUpload.isMultipartContent(reqcx)) {
            // get session for upload progress monitoring
            UploadStatus uploadStatus = getApplication().getUploadStatus(reqtrans);
            try {
                uploads = parseUploads(reqcx, reqtrans, uploadStatus, encoding);
            } catch (Exception upx) {
                log("Error in file upload", upx);
                String message;
                boolean tooLarge = (upx instanceof FileUploadBase.SizeLimitExceededException);
                if (tooLarge) {
                    message = "File upload size exceeds limit of " + uploadLimit + " kB";
                } else {
                    message = upx.getMessage();
                    if (message == null || message.length() == 0) {
                        message = upx.toString();
                    }
                }
                if (uploadStatus != null) {
                    uploadStatus.setError(message);
                }

                if (uploadSoftfail || uploadStatus != null) {
                    reqtrans.set("helma_upload_error", message);
                } else {
                    int errorCode = tooLarge ? HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE
                            : HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                    sendError(response, errorCode, "Error in file upload: " + message);
                    return;
                }
            }
        }

        ResponseTrans restrans = getApplication().execute(reqtrans);

        // delete uploads if any
        if (uploads != null) {
            for (int i = 0; i < uploads.size(); i++) {
                ((FileItem) uploads.get(i)).delete();
            }
        }

        // if the response was already written and committed by the application
        // we can skip this part and return
        if (response.isCommitted()) {
            return;
        }

        // set cookies
        if (restrans.countCookies() > 0) {
            CookieTrans[] resCookies = restrans.getCookies();

            for (int i = 0; i < resCookies.length; i++)
                try {
                    Cookie c = resCookies[i].getCookie("/", resCookieDomain);

                    response.addCookie(c);
                } catch (Exception x) {
                    getApplication().logEvent("Error adding cookie: " + x);
                }
        }

        // write response
        writeResponse(request, response, reqtrans, restrans);
    } catch (Exception x) {
        log("Exception in execute", x);
        try {
            if (debug) {
                sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server error: " + x);
            } else {
                sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "The server encountered an error while processing your request. "
                                + "Please check back later.");
            }
        } catch (IOException iox) {
            log("Exception in sendError", iox);
        }
    }
}

From source file:nl.b3p.commons.uploadProgress.ExtendedMultipartRequestHandler.java

/**
 * Parses the input stream and partitions the parsed items into a set of
 * form fields and a set of file items. In the process, the parsed items
 * are translated from Commons FileUpload <code>FileItem</code> instances
 * to Struts <code>FormFile</code> instances.
 *
 * @param request The multipart request to be processed.
 *
 * @throws ServletException if an unrecoverable error occurs.
 *//*from ww w  .  ja  v a  2 s  .c  o m*/
public void handleRequest(HttpServletRequest request) throws ServletException {
    // Get the app config for the current request.
    ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY);

    // Create and configure a DIskFileUpload instance.
    //everything thats added:
    UploadListener listener = new UploadListener(request, 1);
    FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
    ServletFileUpload upload = new ServletFileUpload(factory);

    // The following line is to support an "EncodingFilter"
    // see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=23255
    upload.setHeaderEncoding(request.getCharacterEncoding());
    // Set the maximum size before a FileUploadException will be thrown.
    upload.setSizeMax(getSizeMax(ac));
    // Set the maximum size that will be stored in memory.
    //upload.setSizeThreshold((int) getSizeThreshold(ac));
    // Set the the location for saving data on disk.
    //upload.setRepositoryPath(getRepositoryPath(ac));

    // Create the hash tables to be populated.
    elementsText = new Hashtable();
    elementsFile = new Hashtable();
    elementsAll = new Hashtable();

    // Parse the request into file items.
    List items = null;
    try {
        items = upload.parseRequest(request);
    } catch (DiskFileUpload.SizeLimitExceededException e) {
        // Special handling for uploads that are too big.
        request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE);
        return;
    } catch (FileUploadException e) {
        log.error("Failed to parse multipart request", e);
        throw new ServletException(e);
    }

    // Partition the items into form fields and files.
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.isFormField()) {
            addTextParameter(request, item);
        } else {
            addFileParameter(item);
        }
    }
}

From source file:org.dbflute.saflute.web.servlet.filter.RequestLoggingFilter.java

protected void buildRequestInfo(StringBuilder sb, HttpServletRequest request, HttpServletResponse response,
        boolean showResponse) {
    sb.append("Request class=" + request.getClass().getName());
    sb.append(", RequestedSessionId=").append(request.getRequestedSessionId());

    sb.append(LF).append(IND);//from w  w  w  . ja  v  a 2s  .  c om
    sb.append(", REQUEST_URI=").append(request.getRequestURI());
    sb.append(", SERVLET_PATH=").append(request.getServletPath());
    sb.append(", CharacterEncoding=" + request.getCharacterEncoding());
    sb.append(", ContentLength=").append(request.getContentLength());

    sb.append(LF).append(IND);
    sb.append(", ContentType=").append(request.getContentType());
    sb.append(", Locale=").append(request.getLocale());
    sb.append(", Locales=");
    final Enumeration<?> locales = request.getLocales();
    boolean first = true;
    while (locales.hasMoreElements()) {
        final Locale locale = (Locale) locales.nextElement();
        if (first) {
            first = false;
        } else {
            sb.append(", ");
        }
        sb.append(locale.toString());
    }
    sb.append(", Scheme=").append(request.getScheme());
    sb.append(", isSecure=").append(request.isSecure());

    sb.append(LF).append(IND);
    sb.append(", SERVER_PROTOCOL=").append(request.getProtocol());
    sb.append(", REMOTE_ADDR=").append(request.getRemoteAddr());
    sb.append(", REMOTE_HOST=").append(request.getRemoteHost());
    sb.append(", SERVER_NAME=").append(request.getServerName());
    sb.append(", SERVER_PORT=").append(request.getServerPort());

    sb.append(LF).append(IND);
    sb.append(", ContextPath=").append(request.getContextPath());
    sb.append(", REQUEST_METHOD=").append(request.getMethod());
    sb.append(", PathInfo=").append(request.getPathInfo());
    sb.append(", RemoteUser=").append(request.getRemoteUser());

    sb.append(LF).append(IND);
    sb.append(", REQUEST_URL=").append(request.getRequestURL());
    sb.append(LF).append(IND);
    sb.append(", QUERY_STRING=").append(request.getQueryString());
    if (showResponse) {
        sb.append(LF).append(IND);
        buildResponseInfo(sb, request, response);
    }

    sb.append(LF);
    buildRequestHeaders(sb, request);
    buildRequestParameters(sb, request);
    buildCookies(sb, request);
    buildRequestAttributes(sb, request);
    buildSessionAttributes(sb, request);
}

From source file:com.codeabovelab.dm.gateway.proxy.common.HttpProxy.java

private HttpEntity createEntity(HttpServletRequest servletRequest) throws IOException {
    final String contentType = servletRequest.getContentType();
    // body with 'application/x-www-form-urlencoded' is handled by tomcat therefore we cannot
    // obtain it through input stream and need some workaround
    if (ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType)) {
        List<NameValuePair> entries = new ArrayList<>();
        // obviously that we also copy params from url, but we cannot differentiate its
        Enumeration<String> names = servletRequest.getParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            entries.add(new BasicNameValuePair(name, servletRequest.getParameter(name)));
        }/*from ww w  .java2s.c om*/
        return new UrlEncodedFormEntity(entries, servletRequest.getCharacterEncoding());
    }

    // Add the input entity (streamed)
    //  note: we don't bother ensuring we close the servletInputStream since the container handles it
    return new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength(),
            ContentType.create(contentType));
}

From source file:org.apache.nifi.processors.standard.HandleHttpRequest.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    try {/*from   w w w  .  j a v a 2s . c o  m*/
        if (!initialized.get()) {
            initializeServer(context);
        }
    } catch (Exception e) {
        context.yield();
        throw new ProcessException("Failed to initialize the server", e);
    }

    final HttpRequestContainer container = containerQueue.poll();
    if (container == null) {
        return;
    }

    final long start = System.nanoTime();
    final HttpServletRequest request = container.getRequest();
    FlowFile flowFile = session.create();
    try {
        flowFile = session.importFrom(request.getInputStream(), flowFile);
    } catch (final IOException e) {
        getLogger().error("Failed to receive content from HTTP Request from {} due to {}",
                new Object[] { request.getRemoteAddr(), e });
        session.remove(flowFile);
        return;
    }

    final String charset = request.getCharacterEncoding() == null
            ? context.getProperty(URL_CHARACTER_SET).getValue()
            : request.getCharacterEncoding();

    final String contextIdentifier = UUID.randomUUID().toString();
    final Map<String, String> attributes = new HashMap<>();
    try {
        putAttribute(attributes, HTTPUtils.HTTP_CONTEXT_ID, contextIdentifier);
        putAttribute(attributes, "mime.type", request.getContentType());
        putAttribute(attributes, "http.servlet.path", request.getServletPath());
        putAttribute(attributes, "http.context.path", request.getContextPath());
        putAttribute(attributes, "http.method", request.getMethod());
        putAttribute(attributes, "http.local.addr", request.getLocalAddr());
        putAttribute(attributes, HTTPUtils.HTTP_LOCAL_NAME, request.getLocalName());
        final String queryString = request.getQueryString();
        if (queryString != null) {
            putAttribute(attributes, "http.query.string", URLDecoder.decode(queryString, charset));
        }
        putAttribute(attributes, HTTPUtils.HTTP_REMOTE_HOST, request.getRemoteHost());
        putAttribute(attributes, "http.remote.addr", request.getRemoteAddr());
        putAttribute(attributes, "http.remote.user", request.getRemoteUser());
        putAttribute(attributes, HTTPUtils.HTTP_REQUEST_URI, request.getRequestURI());
        putAttribute(attributes, "http.request.url", request.getRequestURL().toString());
        putAttribute(attributes, "http.auth.type", request.getAuthType());

        putAttribute(attributes, "http.requested.session.id", request.getRequestedSessionId());
        final DispatcherType dispatcherType = request.getDispatcherType();
        if (dispatcherType != null) {
            putAttribute(attributes, "http.dispatcher.type", dispatcherType.name());
        }
        putAttribute(attributes, "http.character.encoding", request.getCharacterEncoding());
        putAttribute(attributes, "http.locale", request.getLocale());
        putAttribute(attributes, "http.server.name", request.getServerName());
        putAttribute(attributes, HTTPUtils.HTTP_PORT, request.getServerPort());

        final Enumeration<String> paramEnumeration = request.getParameterNames();
        while (paramEnumeration.hasMoreElements()) {
            final String paramName = paramEnumeration.nextElement();
            final String value = request.getParameter(paramName);
            attributes.put("http.param." + paramName, value);
        }

        final Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (final Cookie cookie : cookies) {
                final String name = cookie.getName();
                final String cookiePrefix = "http.cookie." + name + ".";
                attributes.put(cookiePrefix + "value", cookie.getValue());
                attributes.put(cookiePrefix + "domain", cookie.getDomain());
                attributes.put(cookiePrefix + "path", cookie.getPath());
                attributes.put(cookiePrefix + "max.age", String.valueOf(cookie.getMaxAge()));
                attributes.put(cookiePrefix + "version", String.valueOf(cookie.getVersion()));
                attributes.put(cookiePrefix + "secure", String.valueOf(cookie.getSecure()));
            }
        }

        if (queryString != null) {
            final String[] params = URL_QUERY_PARAM_DELIMITER.split(queryString);
            for (final String keyValueString : params) {
                final int indexOf = keyValueString.indexOf("=");
                if (indexOf < 0) {
                    // no =, then it's just a key with no value
                    attributes.put("http.query.param." + URLDecoder.decode(keyValueString, charset), "");
                } else {
                    final String key = keyValueString.substring(0, indexOf);
                    final String value;

                    if (indexOf == keyValueString.length() - 1) {
                        value = "";
                    } else {
                        value = keyValueString.substring(indexOf + 1);
                    }

                    attributes.put("http.query.param." + URLDecoder.decode(key, charset),
                            URLDecoder.decode(value, charset));
                }
            }
        }
    } catch (final UnsupportedEncodingException uee) {
        throw new ProcessException("Invalid character encoding", uee); // won't happen because charset has been validated
    }

    final Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        final String headerValue = request.getHeader(headerName);
        putAttribute(attributes, "http.headers." + headerName, headerValue);
    }

    final Principal principal = request.getUserPrincipal();
    if (principal != null) {
        putAttribute(attributes, "http.principal.name", principal.getName());
    }

    final X509Certificate certs[] = (X509Certificate[]) request
            .getAttribute("javax.servlet.request.X509Certificate");
    final String subjectDn;
    if (certs != null && certs.length > 0) {
        final X509Certificate cert = certs[0];
        subjectDn = cert.getSubjectDN().getName();
        final String issuerDn = cert.getIssuerDN().getName();

        putAttribute(attributes, HTTPUtils.HTTP_SSL_CERT, subjectDn);
        putAttribute(attributes, "http.issuer.dn", issuerDn);
    } else {
        subjectDn = null;
    }

    flowFile = session.putAllAttributes(flowFile, attributes);

    final HttpContextMap contextMap = context.getProperty(HTTP_CONTEXT_MAP)
            .asControllerService(HttpContextMap.class);
    final boolean registered = contextMap.register(contextIdentifier, request, container.getResponse(),
            container.getContext());

    if (!registered) {
        getLogger().warn(
                "Received request from {} but could not process it because too many requests are already outstanding; responding with SERVICE_UNAVAILABLE",
                new Object[] { request.getRemoteAddr() });

        try {
            container.getResponse().setStatus(Status.SERVICE_UNAVAILABLE.getStatusCode());
            container.getResponse().flushBuffer();
            container.getContext().complete();
        } catch (final Exception e) {
            getLogger().warn("Failed to respond with SERVICE_UNAVAILABLE message to {} due to {}",
                    new Object[] { request.getRemoteAddr(), e });
        }

        session.remove(flowFile);
        return;
    }

    final long receiveMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
    session.getProvenanceReporter().receive(flowFile, HTTPUtils.getURI(attributes),
            "Received from " + request.getRemoteAddr() + (subjectDn == null ? "" : " with DN=" + subjectDn),
            receiveMillis);
    session.transfer(flowFile, REL_SUCCESS);
    getLogger().info("Transferring {} to 'success'; received from {}",
            new Object[] { flowFile, request.getRemoteAddr() });
}