Example usage for javax.servlet ServletResponse getOutputStream

List of usage examples for javax.servlet ServletResponse getOutputStream

Introduction

In this page you can find the example usage for javax.servlet ServletResponse getOutputStream.

Prototype

public ServletOutputStream getOutputStream() throws IOException;

Source Link

Document

Returns a ServletOutputStream suitable for writing binary data in the response.

Usage

From source file:com.iisigroup.cap.component.impl.ByteArrayDownloadResult.java

@Override
public void respondResult(ServletResponse response) {
    int length = -1;
    InputStream in = null;//ww  w . j  av  a 2 s  .  com
    OutputStream output = null;
    try {
        response.setContentType(getContentType());
        response.setContentLength(_byteArray.length);
        if (getOutputName() != null && response instanceof HttpServletResponse) {
            HttpServletResponse resp = (HttpServletResponse) response;
            HttpServletRequest req = (HttpServletRequest) _request.getServletRequest();
            String userAgent = req.getHeader("USER-AGENT");
            if (StringUtils.contains(userAgent, "MSIE")) {
                resp.setHeader("Content-Disposition", "attachment; filename=\"" + _outputName + "\"");
            } else {
                resp.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + _outputName);
            }
            resp.setHeader("Cache-Control", "public");
            resp.setHeader("Pragma", "public");
        }
        output = response.getOutputStream();
        // Stream to the requester.
        byte[] bbuf = new byte[1024 * 1024];

        in = new ByteArrayInputStream(_byteArray);
        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            output.write(bbuf, 0, length);
        }
        output.flush();
    } catch (IOException e) {
        e.getMessage();
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(output);
    }
}

From source file:com.mirantis.cachemod.filter.CacheFilter.java

public void writeCacheToResponse(CacheEntry cacheEntry, ServletResponse response, boolean fragment)
        throws IOException {

    if (cacheEntry.getContentType() != null) {
        response.setContentType(cacheEntry.getContentType());
    }// w w w .j av  a  2s  .  co  m

    if (!fragment) {

        if (response instanceof HttpServletResponse) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;

            if (cacheEntry.getLastModified() != -1) {
                httpResponse.setDateHeader("Last-Modified", cacheEntry.getLastModified());
            }

            if (cacheEntry.getExpires() != Long.MAX_VALUE) {
                httpResponse.setDateHeader("Expires", cacheEntry.getExpires());
            }

            if (cacheEntry.getMaxAge() != -1) {
                if (cacheEntry.getMaxAge() < 0) { // set max-age based on life time
                    long currentMaxAge = -cacheEntry.getMaxAge() / 1000 - System.currentTimeMillis() / 1000;
                    if (currentMaxAge < 0) {
                        currentMaxAge = 0;
                    }
                    httpResponse.addHeader("Cache-Control", "max-age=" + currentMaxAge);
                } else {
                    httpResponse.addHeader("Cache-Control", "max-age=" + cacheEntry.getMaxAge());
                }
            }

        }
    }

    if (cacheEntry.getLocale() != null) {
        response.setLocale(cacheEntry.getLocale());
    }

    OutputStream out = new BufferedOutputStream(response.getOutputStream());
    response.setContentLength(cacheEntry.getContent().length);
    out.write(cacheEntry.getContent());
    out.flush();
}

From source file:cc.kune.core.server.searcheable.SearchEngineServletFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException, DefaultException {
    if (filterConfig == null) {
        return;// w w  w  .j  a  v a2 s  .com
    }

    if (request instanceof HttpServletRequest) {

        final HttpServletRequest httpReq = (HttpServletRequest) request;
        final StringBuffer url = httpReq.getRequestURL();

        final String queryString = httpReq.getQueryString();

        if ((queryString != null) && (queryString.contains(SiteParameters.ESCAPED_FRAGMENT_PARAMETER))) {
            if (!enabled) {
                final HttpServletResponse httpRes = (HttpServletResponse) response;
                httpRes.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                        "Search Engine service disabled temporally");
                return;
            }
            // rewrite the URL back to the original #! version
            // remember to unescape any %XX characters
            final String urlWithEscapedFragment = request
                    .getParameter(SiteParameters.ESCAPED_FRAGMENT_PARAMETER);
            final String newUrl = url.append("?").append(queryString).toString()
                    .replaceFirst(SiteParameters.ESCAPED_FRAGMENT_PARAMETER, SiteParameters.NO_UA_CHECK)
                    .replaceFirst("/ws", "") + "#" + urlWithEscapedFragment;

            LOG.info("New url with hash: " + newUrl);

            final String page = "In development";
            // return the snapshot
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=UTF-8");
            response.getOutputStream().write(page.getBytes());
        } else {
            try {
                // not an _escaped_fragment_ URL, so move up the chain of
                // servlet (filters)
                chain.doFilter(request, response);
            } catch (final ServletException e) {
                LOG.error("Servlet exception caught: " + e);
            }
        }
    }
}

From source file:com.bluexml.xforms.chiba.XFormsFilter.java

@Override
public void doFilter(ServletRequest srvRequest, ServletResponse srvResponse, FilterChain filterChain)
        throws IOException, ServletException {

    //ensure correct Request encoding
    if (srvRequest.getCharacterEncoding() == null) {
        srvRequest.setCharacterEncoding(defaultRequestEncoding);
    }/* ww  w  . j a v a  2s. c om*/

    HttpServletRequest request = (HttpServletRequest) srvRequest;

    HttpServletResponse response = (HttpServletResponse) srvResponse;
    HttpSession session = request.getSession(true);

    if ("GET".equalsIgnoreCase(request.getMethod()) && request.getParameter("submissionResponse") != null) {
        doSubmissionResponse(request, response);
    } else {

        /* before servlet request */
        if (isXFormUpdateRequest(request)) {
            LOG.info("Start Update XForm");

            try {
                XFormsSession xFormsSession = WebUtil.getXFormsSession(request, session);
                xFormsSession.setRequest(request);
                xFormsSession.setResponse(response);
                xFormsSession.handleRequest();
            } catch (XFormsException e) {
                throw new ServletException(e);
            }
            LOG.info("End Update XForm");
        } else {

            /* do servlet request */
            LOG.info("Passing to Chain");
            BufferedHttpServletResponseWrapper bufResponse = new BufferedHttpServletResponseWrapper(
                    (HttpServletResponse) srvResponse);
            filterChain.doFilter(srvRequest, bufResponse);
            LOG.info("Returned from Chain");

            // response is already committed to the client, so nothing is to
            // be done
            if (bufResponse.isCommitted())
                return;

            //set mode of operation (scripted/nonscripted) by config
            if (this.mode == null)
                this.mode = "true";

            if (this.mode.equalsIgnoreCase("true")) {
                request.setAttribute(WebFactory.SCRIPTED, "true");
            } else if (this.mode.equalsIgnoreCase("false")) {
                request.setAttribute(WebFactory.SCRIPTED, "false");
            }

            /* dealing with response from chain */
            if (handleResponseBody(request, bufResponse)) {
                byte[] data = prepareData(bufResponse);
                if (data.length > 0) {
                    request.setAttribute(WebFactory.XFORMS_INPUTSTREAM, new ByteArrayInputStream(data));
                }
            }

            if (handleRequestAttributes(request)) {
                bufResponse.getOutputStream().close();
                LOG.info("Start Filter XForm");

                XFormsSession xFormsSession = null;
                try {
                    XFormsSessionManager sessionManager = DefaultXFormsSessionManagerImpl
                            .getXFormsSessionManager();
                    xFormsSession = sessionManager.createXFormsSession(request, response, session);
                    xFormsSession.setBaseURI(request.getRequestURL().toString());
                    xFormsSession.setXForms();
                    xFormsSession.init();

                    // FIXME patch for upload
                    XFormsSessionBase xFormsSessionBase = (XFormsSessionBase) xFormsSession;
                    reconfigure(xFormsSessionBase);

                    xFormsSession.handleRequest();
                } catch (Exception e) {
                    LOG.error(e.getMessage(), e);
                    if (xFormsSession != null) {
                        xFormsSession.close(e);
                    }
                    throw new ServletException(e.getMessage());
                }

                LOG.info("End Render XForm");
            } else {
                srvResponse.getOutputStream().write(bufResponse.getData());
                srvResponse.getOutputStream().close();
            }
        }
    }
}

From source file:org.xmlactions.web.conceal.HttpPager.java

public void processPage(ServletRequest request, ServletResponse response, String page)
        throws ServletException, IOException {
    IExecContext execContext = null;/*from  ww w  .j a va2  s  . c om*/
    if (response instanceof HttpServletResponse && request instanceof HttpServletRequest) {
        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;

            execContext = setupExecContext(httpServletRequest, httpServletResponse);

            String pageName = httpServletRequest.getServletPath();

            if (pageName.indexOf("axelconfig") > 0) {
                PrintWriter out = response.getWriter();
                out.print(buildInfo(httpServletRequest, httpServletResponse));
                out.close();
                return;
            }

            if (!pageName.endsWith(".ajax")) {

                String alternatePage = processPrePages(execContext, httpServletRequest, httpServletResponse);
                if ("stop".equals(execContext.getString("pre.page.stop"))) {
                    execContext.put("pre.page.stop", "");
                    response.setContentType("text/html;charset=UTF-8");

                    PrintWriter out = response.getWriter();
                    out.print(alternatePage);
                    out.close();
                }
            }

            log.debug("contextPath:" + httpServletRequest.getContextPath());
            log.debug("URI:" + httpServletRequest.getRequestURI());
            log.debug("root:" + realPath + " page:" + pageName + " wrapperPage:" + wrapperPage);
            log.debug(HttpSessionInfo.sysInfo(httpServletRequest));
            Action action;
            if (pageName.endsWith(".ajax")) {
                page = processAjaxCall(httpServletRequest, httpServletResponse,
                        pageName.substring(1, pageName.length() - ".ajax".length()), execContext);
                page = StrSubstitutor.replace(page, execContext);
            } else if (pageName.endsWith(".bin") || pageName.endsWith(".pdfbin")) {
                String pn = null;
                if (pageName.endsWith(".pdfbin")) {
                    pn = pageName.substring(1, pageName.length() - ".pdfbin".length());
                } else {
                    pn = pageName.substring(1, pageName.length() - ".bin".length());
                }
                page = processAjaxCall(httpServletRequest, httpServletResponse, pn, execContext);

                if (page.startsWith("EX:")) {
                    PrintWriter out = response.getWriter();
                    out.print(page);
                    out.close();
                } else {
                    byte[] image = (byte[]) execContext.get("image");
                    if (pageName.endsWith(".pdfbin")) {
                        String outputPdfFileName = execContext.getString("outputFileName");
                        String ex = serviceJasperPdfRequest(httpServletResponse, image, outputPdfFileName);
                        if (ex != null) {
                            PrintWriter out = response.getWriter();
                            out.print(page);
                            out.close();
                        }
                        return;
                    } else {

                        String responseType = execContext.getString("response_type");
                        if (StringUtils.isEmpty(responseType)) {
                            responseType = "image/png";
                        }
                        response.setContentType(responseType);

                        processPostPages(execContext, httpServletRequest, httpServletResponse);

                        InputStream in = new ByteArrayInputStream(image);
                        OutputStream out = response.getOutputStream();

                        // Copy the contents of the file to the output
                        // stream
                        byte[] buf = new byte[1024];
                        int count = 0;
                        while ((count = in.read(buf)) >= 0) {
                            out.write(buf, 0, count);
                        }
                        in.close();
                        out.close();
                    }
                    return;
                }
            } else {
                if (pageName.startsWith("/:")) {
                    String wrapperPageName = null;
                    int secondColon = pageName.indexOf(':', 2);
                    if (secondColon >= 0) {
                        wrapperPageName = pageName.substring(2, secondColon);
                        execContext.put("inner_page", "/" + pageName.substring(secondColon + 1));
                    } else {
                        if (StringUtils.isEmpty(wrapperPage)) {
                            throw new ServletException("No wrapper page set, why use :");
                        }
                        wrapperPageName = wrapperPage;
                        execContext.put("inner_page", "/" + pageName.substring(2));
                    }
                    // insert the requested page into the wrapper page
                    action = new Action(realPath, wrapperPageName, nameSpace);
                } else {
                    if (StringUtils.isNotEmpty(wrapperPage)) {
                        // we have a base wrapper page defined
                        execContext.put("inner_page", "/" + pageName);
                        action = new Action(realPath, wrapperPage, nameSpace);
                    } else {
                        if (pageName.indexOf("show_axel_config") >= 0) {
                            page = AxelConfig.getAxelConfig(execContext);
                            log.info(page);
                            page = "Config Copied to Log";
                            action = null;
                        } else {
                            // if we don't have a wrapper page we show the requested page
                            action = new Action(realPath, pageName, nameSpace);
                        }
                    }
                }
                if (action != null) {
                    if (StringUtils.isNotEmpty(page)) {
                        page = action.processPage(execContext, page);
                    } else {
                        page = action.processPage(execContext);
                    }
                }
            }

            log.debug("URI:" + httpServletRequest.getRequestURI());
            // log.debug("page:" + page);
            Object object = execContext.get(ActionConst.NO_STR_SUBST);
            // log.debug(ActionConst.NO_STR_SUBST + ":[" + object + "]");
            execContext.put(ActionConst.NO_STR_SUBST, null);

            if (pageName.toLowerCase().endsWith("soap")) {
                response.setContentType(IExecContext.CONTENT_TYPE_XML);

            } else if (pageName.toLowerCase().endsWith("json")) {
                response.setContentType(IExecContext.CONTENT_TYPE_JSON);

            } else {
                response.setContentType(IExecContext.CONTENT_TYPE_HTML);
            }

            processPostPages(execContext, httpServletRequest, httpServletResponse);

            // = = =
            // check if there is a contentType value stored in the execContext.  This could have been set by one of the actions such as an action that wants to return a JSON data.
            // = = =
            String contentType = execContext.getString(IExecContext.CONTENT_TYPE_KEY);
            if (StringUtils.isNotBlank(contentType)) {
                response.setContentType(contentType);
                //               if (contentType.equals(IExecContext.CONTENT_TYPE_JSON) || contentType.equals(IExecContext.CONTENT_TYPE_XML)) {
                //                  if (response instanceof HttpServletResponse) {
                //                     ((HttpServletResponse)response).setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1
                //                     ((HttpServletResponse)response).setHeader("Pragma", "no-cache"); // HTTP 1.0
                //                     ((HttpServletResponse)response).setDateHeader("Expires", 0); // Proxies.
                //                  }
                //               }
            }
            execContext.remove("content_type");
            PrintWriter out = response.getWriter();
            out.print(page);
            out.close();

        } catch (Throwable t) {
            // TODO review this, use a better way for reporting the error.
            log.info(t.getMessage(), t);
            throw new ServletException(t);
        } finally {
            if (execContext != null) {
                execContext.saveToPersistence();
                RequestExecContext.remove();
            }
        }
    } else {
        String msg = "Not processing page. Must be HttpServletRequest not [" + request.getClass().getName()
                + "] and HttpServletResponse not [" + response.getClass().getName() + "]";

        log.info(msg);
        throw new ServletException(msg);
    }
}

From source file:de.betterform.agent.web.filter.XFormsFilter.java

/**
 * The actual filtering method//  w  ww .j  ava 2s. c  o  m
 * todo: add request attribute to set baseURI 
 *
 * @see http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/Filter.html#doFilter(javax.servlet.ServletRequest,%20javax.servlet.ServletResponse,%20javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest srvRequest, ServletResponse srvResponse, FilterChain filterChain)
        throws IOException, ServletException {

    //ensure correct Request encoding
    if (srvRequest.getCharacterEncoding() == null) {
        srvRequest.setCharacterEncoding(defaultRequestEncoding);
    }

    HttpServletRequest request = (HttpServletRequest) srvRequest;
    HttpServletResponse response = (HttpServletResponse) srvResponse;
    HttpSession session = request.getSession(true);

    /*
    if header "betterform-internal is present this means that the internal http client of the processor is the
    originator of the incoming request. Since this may not be processed we skip these requests by
    simply calling the servlet chain.
            
    As the contenttype may not be present for such requests we have to determine the mimetype by the file ending
    of the requested resource.
    */

    //Check if  MEDIATYPE is set if so we will handle response as XForms
    if (request.getHeader(BetterFORMConstants.BETTERFORM_INTERNAL) != null) {
        LOG.warn("Request from internal betterForm HTTP Client arrived in XFormsFilter");
        String requestURI = request.getRequestURI();

        String mimeType = webFactory.getServletContext().getMimeType(requestURI);

        if (LOG.isDebugEnabled()) {
            LOG.debug("request URI: " + requestURI);
            LOG.debug("mimeType: " + mimeType);
        }

        if (mimeType != null) {
            srvResponse.setContentType(mimeType);
        } else {
            LOG.warn("no contenttype set for internal request");
            //                throw new ServletException("Contenttype of " + requestURI + " unknown. Please configure your webcontainer appropriately.");
        }

        filterChain.doFilter(srvRequest, srvResponse);
        return;
    }

    if (request.getParameter("source") != null) {
        srvResponse.setContentType("text/plain");
        // override setContentType to keep "text/plain" as content type.
        HttpServletResponseWrapper resp = new HttpServletResponseWrapper((HttpServletResponse) srvResponse) {
            public void setContentType(String s) {
                return;
            }
        };
        filterChain.doFilter(srvRequest, resp);
        return;
    }

    if (request.getParameter("isUpload") != null) {
        //Got an upload...
        handleUpload(request, response, session);
        //TODO: XFORMS  PROCESSING: do we need to exit?
    } else if ("GET".equalsIgnoreCase(request.getMethod())
            && request.getParameter(BetterFORMConstants.SUBMISSION_RESPONSE) != null) {
        doSubmissionReplaceAll(request, response);
    } else if ("GET".equalsIgnoreCase(request.getMethod())
            && request.getParameter(BetterFORMConstants.SUBMISSION_RESPONSE_XFORMS) != null) {
        doSubmissionReplaceAllXForms(request, response, session);
    } else {
        /* do servlet request */
        LOG.info("Passing to Chain");
        BufferedHttpServletResponseWrapper bufResponse = new BufferedHttpServletResponseWrapper(
                (HttpServletResponse) srvResponse);
        filterChain.doFilter(srvRequest, bufResponse);
        LOG.info("Returned from Chain");

        //handleResponse(srvResponse, request, response, session, bufResponse, webFactory);

        // response is contains no betterFORM relevant content so it is not buffered and cannot be processed
        if (!bufResponse.isBuffered()) {
            return;
        }

        // response is already committed to the client, so nothing is to
        // be done
        if (bufResponse.isCommitted()) {
            return;
        }

        //pass to request object
        request.setAttribute(WebFactory.USER_AGENT, XFormsFilter.USERAGENT);

        /* dealing with response from chain */
        if (handleResponseBody(request, bufResponse)) {
            byte[] data = prepareData(bufResponse);
            if (data.length > 0) {
                request.setAttribute(WebFactory.XFORMS_INPUTSTREAM, new ByteArrayInputStream(data));
            }
        }

        if (handleRequestAttributes(request)) {
            bufResponse.getOutputStream().close();
            LOG.info("Start Filter XForm");
            processXForms(request, response, session);
            LOG.info("End Render XForm");
        } else {
            srvResponse.getOutputStream().write(bufResponse.getData());
            srvResponse.getOutputStream().close();
        }
    }
}

From source file:net.yacy.http.servlets.SolrSelectServlet.java

@Override
public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException {

    HttpServletRequest hrequest = (HttpServletRequest) request;
    HttpServletResponse hresponse = (HttpServletResponse) response;
    SolrQueryRequest req = null;/*w w w. j  av a 2 s .c  om*/

    final Method reqMethod = Method.getMethod(hrequest.getMethod());

    Writer out = null;
    try {
        // prepare request to solr
        MultiMapSolrParams mmsp = SolrRequestParsers.parseQueryString(hrequest.getQueryString());

        Switchboard sb = Switchboard.getSwitchboard();
        // TODO: isUserInRole needs a login to jetty container (not done automatically on admin from localhost)
        boolean authenticated = hrequest.isUserInRole(UserDB.AccessRight.ADMIN_RIGHT.toString());

        // count remote searches if this was part of a p2p search
        if (mmsp.getMap().containsKey("partitions")) {
            final int partitions = mmsp.getInt("partitions", 30);
            sb.searchQueriesGlobal += 1.0f / partitions; // increase query counter
        }

        // get the ranking profile id
        int profileNr = mmsp.getInt("profileNr", 0);

        // rename post fields according to result style
        String querystring = "";
        if (!mmsp.getMap().containsKey(CommonParams.Q) && mmsp.getMap().containsKey(CommonParams.QUERY)) {
            querystring = mmsp.get(CommonParams.QUERY, "");
            mmsp.getMap().remove(CommonParams.QUERY);
            QueryModifier modifier = new QueryModifier(0);
            querystring = modifier.parse(querystring);
            modifier.apply(mmsp);
            QueryGoal qg = new QueryGoal(querystring);
            StringBuilder solrQ = qg.collectionTextQuery();
            mmsp.getMap().put(CommonParams.Q, new String[] { solrQ.toString() }); // sru patch

            // experimental p2p enrichment if flag to do so is set
            /*
            final String p2pQuery = querystring;
            new Thread() {
            @Override
            public void run() {
                FederateSearchManager.getManager().query(p2pQuery);
            }
            }.start();
            */
        }
        String q = mmsp.get(CommonParams.Q, "");
        if (querystring.length() == 0)
            querystring = q;
        if (!mmsp.getMap().containsKey(CommonParams.START)) {
            int startRecord = mmsp.getFieldInt("startRecord", null, 0);
            mmsp.getMap().remove("startRecord");
            mmsp.getMap().put(CommonParams.START, new String[] { Integer.toString(startRecord) }); // sru patch
        }
        if (!mmsp.getMap().containsKey(CommonParams.ROWS)) {
            int maximumRecords = mmsp.getFieldInt("maximumRecords", null, 10);
            mmsp.getMap().remove("maximumRecords");
            mmsp.getMap().put(CommonParams.ROWS, new String[] { Integer.toString(maximumRecords) }); // sru patch
        }
        mmsp.getMap().put(CommonParams.ROWS, new String[] { Integer
                .toString(Math.min(mmsp.getInt(CommonParams.ROWS, 10), (authenticated) ? 100000000 : 100)) });

        // set ranking according to profile number if ranking attributes are not given in the request
        Ranking ranking = sb.index.fulltext().getDefaultConfiguration().getRanking(profileNr);
        if (!mmsp.getMap().containsKey(CommonParams.SORT) && !mmsp.getMap().containsKey(DisMaxParams.BQ)
                && !mmsp.getMap().containsKey(DisMaxParams.BF) && !mmsp.getMap().containsKey("boost")) {
            if (!mmsp.getMap().containsKey("defType"))
                mmsp.getMap().put("defType", new String[] { "edismax" });
            String fq = ranking.getFilterQuery();
            String bq = ranking.getBoostQuery();
            String bf = ranking.getBoostFunction();
            if (fq.length() > 0)
                mmsp.getMap().put(CommonParams.FQ, new String[] { fq });
            if (bq.length() > 0)
                mmsp.getMap().put(DisMaxParams.BQ, StringUtils.split(bq, "\t\n\r\f")); // bq split into multiple query params, allowing space in single query
            if (bf.length() > 0)
                mmsp.getMap().put("boost", new String[] { bf }); // a boost function extension, see http://wiki.apache.org/solr/ExtendedDisMax#bf_.28Boost_Function.2C_additive.29
        }

        // get a response writer for the result
        String wt = mmsp.get(CommonParams.WT, "xml"); // maybe use /solr/select?q=*:*&start=0&rows=10&wt=exml
        QueryResponseWriter responseWriter = RESPONSE_WRITER.get(wt);
        if (responseWriter == null)
            throw new ServletException("no response writer");
        if (responseWriter instanceof OpensearchResponseWriter) {
            // set the title every time, it is possible that it has changed
            final String promoteSearchPageGreeting = (sb
                    .getConfigBool(SwitchboardConstants.GREETING_NETWORK_NAME, false))
                            ? sb.getConfig("network.unit.description", "")
                            : sb.getConfig(SwitchboardConstants.GREETING, "");
            ((OpensearchResponseWriter) responseWriter).setTitle(promoteSearchPageGreeting);
        }

        // if this is a call to YaCys special search formats, enhance the query with field assignments
        if ((responseWriter instanceof YJsonResponseWriter
                || responseWriter instanceof OpensearchResponseWriter)
                && "true".equals(mmsp.get("hl", "true"))) {
            // add options for snippet generation
            if (!mmsp.getMap().containsKey("hl.q"))
                mmsp.getMap().put("hl.q", new String[] { q });
            if (!mmsp.getMap().containsKey("hl.fl"))
                mmsp.getMap().put("hl.fl",
                        new String[] { CollectionSchema.description_txt.getSolrFieldName() + ","
                                + CollectionSchema.h4_txt.getSolrFieldName() + ","
                                + CollectionSchema.h3_txt.getSolrFieldName() + ","
                                + CollectionSchema.h2_txt.getSolrFieldName() + ","
                                + CollectionSchema.h1_txt.getSolrFieldName() + ","
                                + CollectionSchema.text_t.getSolrFieldName() });
            if (!mmsp.getMap().containsKey("hl.alternateField"))
                mmsp.getMap().put("hl.alternateField",
                        new String[] { CollectionSchema.description_txt.getSolrFieldName() });
            if (!mmsp.getMap().containsKey("hl.simple.pre"))
                mmsp.getMap().put("hl.simple.pre", new String[] { "<b>" });
            if (!mmsp.getMap().containsKey("hl.simple.post"))
                mmsp.getMap().put("hl.simple.post", new String[] { "</b>" });
            if (!mmsp.getMap().containsKey("hl.fragsize"))
                mmsp.getMap().put("hl.fragsize",
                        new String[] { Integer.toString(SearchEvent.SNIPPET_MAX_LENGTH) });
            if (!mmsp.getMap().containsKey("fl"))
                mmsp.getMap().put("fl",
                        new String[] { CollectionSchema.sku.getSolrFieldName() + "," + CollectionSchema.title
                                + "," + CollectionSchema.description_txt.getSolrFieldName() + ","
                                + CollectionSchema.id.getSolrFieldName() + ","
                                + CollectionSchema.url_paths_sxt.getSolrFieldName() + ","
                                + CollectionSchema.last_modified.getSolrFieldName() + ","
                                + CollectionSchema.size_i.getSolrFieldName() + ","
                                + CollectionSchema.url_protocol_s.getSolrFieldName() + ","
                                + CollectionSchema.url_file_ext_s.getSolrFieldName() });
        }

        // get the embedded connector
        String requestURI = hrequest.getRequestURI();
        boolean defaultConnector = (requestURI.startsWith("/solr/" + WebgraphSchema.CORE_NAME)) ? false
                : requestURI.startsWith("/solr/" + CollectionSchema.CORE_NAME)
                        || mmsp.get("core", CollectionSchema.CORE_NAME).equals(CollectionSchema.CORE_NAME);
        mmsp.getMap().remove("core");
        SolrConnector connector = defaultConnector ? sb.index.fulltext().getDefaultEmbeddedConnector()
                : sb.index.fulltext().getEmbeddedConnector(WebgraphSchema.CORE_NAME);
        if (connector == null) {
            connector = defaultConnector ? sb.index.fulltext().getDefaultConnector()
                    : sb.index.fulltext().getConnectorForRead(WebgraphSchema.CORE_NAME);
        }
        if (connector == null)
            throw new ServletException("no core");

        // add default queryfield parameter according to local ranking config (or defaultfield)
        if (ranking != null) { // ranking normally never null
            final String qf = ranking.getQueryFields();
            if (qf.length() > 4) { // make sure qf has content (else use df)
                addParam(DisMaxParams.QF, qf, mmsp.getMap()); // add QF that we set to be best suited for our index
                // TODO: if every peer applies a decent QF itself, this can be reverted to getMap().put()
            } else {
                mmsp.getMap().put(CommonParams.DF, new String[] { CollectionSchema.text_t.getSolrFieldName() });
            }
        } else {
            mmsp.getMap().put(CommonParams.DF, new String[] { CollectionSchema.text_t.getSolrFieldName() });
        }

        // do the solr request, generate facets if we use a special YaCy format
        final SolrQueryResponse rsp;
        if (connector instanceof EmbeddedSolrConnector) {
            req = ((EmbeddedSolrConnector) connector).request(mmsp);
            rsp = ((EmbeddedSolrConnector) connector).query(req);

            // prepare response
            hresponse.setHeader("Cache-Control", "no-cache, no-store");
            HttpCacheHeaderUtil.checkHttpCachingVeto(rsp, hresponse, reqMethod);

            // check error
            if (rsp.getException() != null) {
                AccessTracker.addToDump(querystring, "0", new Date());
                sendError(hresponse, rsp.getException());
                return;
            }

            NamedList<?> values = rsp.getValues();
            DocList r = ((ResultContext) values.get("response")).docs;
            int numFound = r.matches();
            AccessTracker.addToDump(querystring, Integer.toString(numFound), new Date());

            // write response header
            final String contentType = responseWriter.getContentType(req, rsp);
            if (null != contentType)
                response.setContentType(contentType);

            if (Method.HEAD == reqMethod) {
                return;
            }

            // write response body
            if (responseWriter instanceof BinaryResponseWriter) {
                ((BinaryResponseWriter) responseWriter).write(response.getOutputStream(), req, rsp);
            } else {
                out = new FastWriter(
                        new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8));
                responseWriter.write(out, req, rsp);
                out.flush();
            }
        } else {
            // write a 'faked' response using a call to the backend
            SolrDocumentList sdl = connector.getDocumentListByQuery(mmsp.getMap().get(CommonParams.Q)[0],
                    mmsp.getMap().get(CommonParams.SORT) == null ? null
                            : mmsp.getMap().get(CommonParams.SORT)[0],
                    Integer.parseInt(mmsp.getMap().get(CommonParams.START)[0]),
                    Integer.parseInt(mmsp.getMap().get(CommonParams.ROWS)[0]),
                    mmsp.getMap().get(CommonParams.FL));
            OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream());
            EnhancedXMLResponseWriter.write(osw, req, sdl);
            osw.close();
        }
    } catch (final Throwable ex) {
        sendError(hresponse, ex);
    } finally {
        if (req != null) {
            req.close();
        }
        SolrRequestInfo.clearRequestInfo();
        if (out != null)
            try {
                out.close();
            } catch (final IOException e1) {
            }
    }
}

From source file:org.apache.catalina.core.ApplicationDispatcher.java

private void doForward(ServletRequest request, ServletResponse response) throws ServletException, IOException {

    // Reset any output that has been buffered, but keep headers/cookies
    if (response.isCommitted()) {
        if (log.isDebugEnabled())
            log.debug("  Forward on committed response --> ISE");
        throw new IllegalStateException(sm.getString("applicationDispatcher.forward.ise"));
    }//from  w  w  w  . ja v a  2 s . c  o m
    try {
        response.resetBuffer();
    } catch (IllegalStateException e) {
        if (log.isDebugEnabled())
            log.debug("  Forward resetBuffer() returned ISE: " + e);
        throw e;
    }

    // Set up to handle the specified request and response
    setup(request, response, false);

    // Identify the HTTP-specific request and response objects (if any)
    HttpServletRequest hrequest = null;
    if (request instanceof HttpServletRequest)
        hrequest = (HttpServletRequest) request;
    HttpServletResponse hresponse = null;
    if (response instanceof HttpServletResponse)
        hresponse = (HttpServletResponse) response;

    // Handle a non-HTTP forward by passing the existing request/response
    if ((hrequest == null) || (hresponse == null)) {

        if (log.isDebugEnabled())
            log.debug(" Non-HTTP Forward");

        processRequest(hrequest, hresponse);

    }

    // Handle an HTTP named dispatcher forward
    else if ((servletPath == null) && (pathInfo == null)) {

        if (log.isDebugEnabled())
            log.debug(" Named Dispatcher Forward");

        processRequest(request, response);

    }

    // Handle an HTTP path-based forward
    else {

        if (log.isDebugEnabled())
            log.debug(" Path Based Forward");

        ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest();
        String contextPath = context.getPath();
        wrequest.setContextPath(contextPath);
        wrequest.setRequestURI(requestURI);
        wrequest.setServletPath(servletPath);
        wrequest.setPathInfo(pathInfo);

        wrequest.setAttribute(Globals.FORWARD_REQUEST_URI_ATTR, hrequest.getRequestURI());
        wrequest.setAttribute(Globals.FORWARD_CONTEXT_PATH_ATTR, hrequest.getContextPath());
        wrequest.setAttribute(Globals.FORWARD_SERVLET_PATH_ATTR, hrequest.getServletPath());
        wrequest.setAttribute(Globals.FORWARD_PATH_INFO_ATTR, hrequest.getPathInfo());
        wrequest.setAttribute(Globals.FORWARD_QUERY_STRING_ATTR, hrequest.getQueryString());

        if (queryString != null) {
            wrequest.setQueryString(queryString);
            wrequest.setQueryParams(queryString);
        }

        processRequest(request, response);
        unwrapRequest();

    }

    // This is not a real close in order to support error processing
    if (log.isDebugEnabled())
        log.debug(" Disabling the response for futher output");

    if (response instanceof ResponseFacade) {
        ((ResponseFacade) response).finish();
    } else {
        // Servlet SRV.6.2.2. The Resquest/Response may have been wrapped
        // and may no longer be instance of RequestFacade 
        if (log.isDebugEnabled()) {
            log.debug(" The Response is vehiculed using a wrapper: " + response.getClass().getName());
        }

        // Close anyway
        try {
            PrintWriter writer = response.getWriter();
            writer.close();
        } catch (IllegalStateException e) {
            try {
                ServletOutputStream stream = response.getOutputStream();
                stream.close();
            } catch (IllegalStateException f) {
                ;
            } catch (IOException f) {
                ;
            }
        } catch (IOException e) {
            ;
        }
    }

}

From source file:org.apache.openejb.arquillian.tests.filterenventry.PojoServletFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws ServletException, IOException {
    String name = req.getParameter("name");
    if (StringUtils.isEmpty(name)) {
        name = "OpenEJB";
    }/*ww w  .j av  a  2  s .c  om*/

    if (car != null) {
        resp.getOutputStream().println(car.drive(name));
    }
    if (localCompany != null) {
        resp.getOutputStream().println("Local: " + localCompany.employ(name));
    }
    if (market != null) {
        resp.getOutputStream().println(market.shop(name));
    }
    if (connectionPool != null) {
        resp.getOutputStream().println("Connection Pool: " + connectionPool);
    }
    if (startCount != null) {
        resp.getOutputStream().println("Start Count: " + startCount);
    }
    if (initSize != null) {
        resp.getOutputStream().println("Init Size: " + initSize);
    }
    if (totalQuantity != null) {
        resp.getOutputStream().println("Total Quantity: " + totalQuantity);
    }
    if (enableEmail != null) {
        resp.getOutputStream().println("Enable Email: " + enableEmail);
    }
    if (optionDefault != null) {
        resp.getOutputStream().println("Option Default: " + optionDefault);
    }
    if (StringUtils.isNotEmpty(returnEmail) && returnEmail.equals("tomee@apache.org")) {
        resp.getOutputStream().println(returnEmail);
    }
    if (auditWriter != null) {
        resp.getOutputStream().println(auditWriter.getClass().getName());
    }
    if (defaultCode != null) {
        resp.getOutputStream().println("DefaultCode: " + defaultCode);
    }
}

From source file:org.apache.wiki.ui.WikiJSPFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws ServletException, IOException {
    WatchDog w = m_engine.getCurrentWatchDog();
    try {//from   www.jav a 2s  . c o  m
        NDC.push(m_engine.getApplicationName() + ":" + ((HttpServletRequest) request).getRequestURI());

        w.enterState("Filtering for URL " + ((HttpServletRequest) request).getRequestURI(), 90);
        HttpServletResponseWrapper responseWrapper;

        if (m_useOutputStream) {
            log.debug("Using ByteArrayResponseWrapper");
            responseWrapper = new ByteArrayResponseWrapper((HttpServletResponse) response, m_wiki_encoding);
        } else {
            log.debug("Using MyServletResponseWrapper");
            responseWrapper = new MyServletResponseWrapper((HttpServletResponse) response, m_wiki_encoding);
        }

        // fire PAGE_REQUESTED event
        String pagename = DefaultURLConstructor.parsePageFromURL((HttpServletRequest) request,
                response.getCharacterEncoding());
        fireEvent(WikiPageEvent.PAGE_REQUESTED, pagename);

        super.doFilter(request, responseWrapper, chain);

        // The response is now complete. Lets replace the markers now.

        // WikiContext is only available after doFilter! (That is after
        //   interpreting the jsp)

        try {
            w.enterState("Delivering response", 30);
            WikiContext wikiContext = getWikiContext(request);
            String r = filter(wikiContext, responseWrapper);

            if (m_useOutputStream) {
                OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(),
                        response.getCharacterEncoding());
                out.write(r);
                out.flush();
                out.close();
            } else {
                response.getWriter().write(r);
            }

            // Clean up the UI messages and loggers
            if (wikiContext != null) {
                wikiContext.getWikiSession().clearMessages();
            }

            // fire PAGE_DELIVERED event
            fireEvent(WikiPageEvent.PAGE_DELIVERED, pagename);

        } finally {
            w.exitState();
        }
    } finally {
        w.exitState();
        NDC.pop();
        NDC.remove();
    }
}