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:ar.com.zauber.commons.web.filter.JSONPRequestFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *//* w ww  . j av a 2 s.c om*/
public final void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain chain) throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        throw new ServletException("This filter can " + " only process HttpServletRequest requests");
    }

    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    final String callback = httpRequest.getParameter(callbackParameterName);

    if (StringUtils.isNotBlank(callback) && acceptsJSONP(httpRequest)) {
        ServletOutputStream out = response.getOutputStream();
        out.print(callback + "(");
        chain.doFilter(request, response);
        out.print(");");
        response.setContentType(responseContentType);
    } else {
        chain.doFilter(request, response);
    }
}

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

public void respondResult(ServletResponse response) {
    InputStream in = null;/*from   w  w w  .  j a  v  a 2 s .  c  om*/
    OutputStream output = null;
    try {
        response.setContentType(_contentType);
        if (_outputName != null && response instanceof HttpServletResponse) {
            HttpServletResponse resp = (HttpServletResponse) response;
            resp.setHeader("Content-Disposition", "attachment;filename=\"" + _outputName + "\"");
            resp.setHeader("Cache-Control", "public");
            resp.setHeader("Pragma", "public");
        }
        output = response.getOutputStream();
        File file = new File(_file);
        int length = -1;
        // Stream to the requester.
        byte[] bbuf = new byte[1024 * 1024];
        int len = 0;
        in = new FileInputStream(file);
        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            output.write(bbuf, 0, length);
            len += length;
        }
        response.setContentLength(len);
        output.flush();
    } catch (Exception e) {
        throw new CapException(e, getClass());
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(output);
    }

}

From source file:com.metamesh.opencms.rfs.RfsAwareDumpLoader.java

/**
 * @see org.opencms.loader.I_CmsResourceLoader#service(org.opencms.file.CmsObject, org.opencms.file.CmsResource, javax.servlet.ServletRequest, javax.servlet.ServletResponse)
 *//*from  ww w . j a  v  a  2  s  .  c o  m*/
public void service(CmsObject cms, CmsResource resource, ServletRequest req, ServletResponse res)
        throws CmsException, IOException {

    if (resource instanceof RfsCmsResource) {
        RfsCmsResource rfsFile = (RfsCmsResource) resource;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(rfsFile.getRfsFile());
            byte[] buffy = new byte[4096];
            int bytesRead;
            while ((bytesRead = fis.read(buffy)) >= 0) {
                res.getOutputStream().write(buffy, 0, bytesRead);
                res.getOutputStream().flush();
            }
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
    } else {
        super.service(cms, resource, req, res);
    }
}

From source file:de.micromata.genome.gwiki.page.gspt.ServletStandalonePageContext.java

@Override
public void initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL,
        boolean needsSession, int bufferSize, boolean autoFlush)
        throws IOException, IllegalStateException, IllegalArgumentException {

    this.request = (HttpServletRequest) request;
    this.response = (HttpServletResponse) response;
    this.servlet = (HttpServlet) servlet;
    PrintWriterPatched pout = new PrintWriterPatched(response.getOutputStream());
    GspJspWriter gsptWriter = new GspJspWriter(pout);
    this.writer = gsptWriter;
    this.servletCtx = this.servlet.getServletContext();
    this.session = this.request.getSession(false);

    this.resolver = new VariableResolver() {

        public Object resolveVariable(String key) throws ELException {
            return findAttribute(key);
        }//from   w  ww.j  a v a  2s.  com

    };
}

From source file:org.artifactory.webapp.servlet.ArtifactoryFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    // Redirect or forward if need
    for (RedirectionHandler redirectionHandler : redirectionHandlers) {
        if (redirectionHandler.shouldRedirect(request)) {
            redirectionHandler.redirect(request, response);
            return;
        }//from   www  . j a  va  2 s  .  c  om
    }
    if (filterConfig.getServletContext().getAttribute(DelayedInit.APPLICATION_CONTEXT_LOCK_KEY) != null) {
        String requestURI = ((HttpServletRequest) request).getRequestURI();
        if (requestURI.endsWith("artifactory-splash.gif")) {
            ((HttpServletResponse) response).setStatus(200);
            ServletOutputStream out = response.getOutputStream();
            ResourceUtils.copyResource("/artifactory-splash.gif", out, null, getClass());
            return;
        }
        response.setContentType("text/html");
        ((HttpServletResponse) response).setStatus(HttpStatus.SC_SERVICE_UNAVAILABLE);
        ServletOutputStream out = response.getOutputStream();
        ResourceUtils.copyResource("/startup.html", out, null, getClass());
        return;
    }
    try {
        ServletContext servletContext = filterConfig.getServletContext();
        ArtifactoryContext context = RequestUtils.getArtifactoryContext(servletContext);
        if (context == null) {
            respondFailedToInitialize(response);
            return;
        }
        bind(context);
        if (response instanceof HttpServletResponse) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            if (!httpResponse.containsHeader("Server")) {
                //Add the server header (curl -I http://localhost:8080/artifactory/)
                httpResponse.setHeader("Server", HttpUtils.getArtifactoryUserAgent());
            }

            // set the Artifactory instance id header
            String hostId = ContextHelper.get().beanForType(AddonsManager.class)
                    .addonByType(HaCommonAddon.class).getHostId();
            httpResponse.setHeader(ArtifactoryResponse.ARTIFACTORY_ID, hostId);

            String serverId = ContextHelper.get().getServerId();
            if (StringUtils.isNotBlank(serverId) && !HaCommonAddon.ARTIFACTORY_PRO.equals(serverId)) {
                httpResponse.setHeader(HaCommonAddon.ARTIFACTORY_NODE_ID, serverId);
            }
        }
        chain.doFilter(request, response);
    } finally {
        unbind();
    }
}

From source file:io.scigraph.services.jersey.dynamic.SwaggerFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    // Capture the output of the filter chain
    ByteArrayResponseWrapper wrappedResp = new ByteArrayResponseWrapper((HttpServletResponse) response);
    chain.doFilter(request, wrappedResp);
    if (isGzip(request)) {
        try (InputStream is = new ByteArrayInputStream(wrappedResp.getBytes());
                GZIPInputStream gis = new GZIPInputStream(is);
                ByteArrayOutputStream bs = new ByteArrayOutputStream();
                GZIPOutputStream gzos = new GZIPOutputStream(bs)) {
            byte[] newApi = writeDynamicResource(gis);
            gzos.write(newApi);/*from   w ww. ja  va  2 s .  c  o  m*/
            gzos.close();
            byte[] output = bs.toByteArray();
            response.setContentLength(output.length);
            response.getOutputStream().write(output);
        }
    } else {
        try (InputStream is = new ByteArrayInputStream(wrappedResp.getBytes());
                ByteArrayOutputStream bs = new ByteArrayOutputStream()) {
            byte[] newApi = writeDynamicResource(is);
            response.setContentLength(newApi.length);
            response.getOutputStream().write(newApi);
        }

    }
}

From source file:edu.sdsc.scigraph.services.jersey.dynamic.SwaggerFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    boolean gzip = isGzip(request);

    // Capture the output of the filter chain
    ByteArrayResponseWrapper wrappedResp = new ByteArrayResponseWrapper((HttpServletResponse) response);
    chain.doFilter(request, wrappedResp);
    if (gzip) {// w w w.ja  v a 2 s  . co m
        try (InputStream is = new ByteArrayInputStream(wrappedResp.getBytes());
                GZIPInputStream gis = new GZIPInputStream(is);
                ByteArrayOutputStream bs = new ByteArrayOutputStream();
                GZIPOutputStream gzos = new GZIPOutputStream(bs)) {
            byte[] newApi = writeDynamicResource(gis);
            gzos.write(newApi);
            gzos.close();
            byte[] output = bs.toByteArray();
            response.setContentLength(output.length);
            response.getOutputStream().write(output);
        }
    } else {
        try (InputStream is = new ByteArrayInputStream(wrappedResp.getBytes());
                ByteArrayOutputStream bs = new ByteArrayOutputStream()) {
            byte[] newApi = writeDynamicResource(is);
            response.setContentLength(newApi.length);
            response.getOutputStream().write(newApi);
        }

    }
}

From source file:edu.harvard.hms.dbmi.bd2k.irct.cl.filter.SessionFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc)
        throws IOException, ServletException {

    // Calls to the Security Service can go straight through
    if (!((HttpServletRequest) req).getPathInfo().startsWith("/securityService/")) {
        //Get the session and user information
        HttpSession session = ((HttpServletRequest) req).getSession();
        User user = (User) session.getAttribute("user");

        // Is a user already associated with a session?
        if (user == null) {

            // If no user is associated then validate the authorization
            // header
            String email = validateAuthorizationHeader((HttpServletRequest) req);

            if (email == null) {
                ((HttpServletResponse) res).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                res.getOutputStream().write("{\"message\":\"Session is not authorized\"}".getBytes());
                res.getOutputStream().close();
                return;
            }/*from ww w. jav a 2 s .co  m*/

            user = sc.getUser(email);
            Token token = new JWT(((HttpServletRequest) req).getHeader("Authorization"), "", "Bearer",
                    this.clientId);
            SecureSession secureSession = new SecureSession();
            secureSession.setToken(token);
            secureSession.setUser(user);

            session.setAttribute("user", user);
            session.setAttribute("token", token);
            session.setAttribute("secureSession", secureSession);

        }
    } else {
        String name = validateAuthorizationHeader((HttpServletRequest) req);

        if (name != null) {
            HttpSession session = ((HttpServletRequest) req).getSession();

            User user = sc.getUser(name);
            Token token = new JWT(((HttpServletRequest) req).getHeader("Authorization"), "", "Bearer",
                    this.clientId);
            SecureSession secureSession = new SecureSession();
            secureSession.setToken(token);
            secureSession.setUser(user);

            session.setAttribute("user", user);
            session.setAttribute("token", token);
            session.setAttribute("secureSession", secureSession);
        }

    }

    fc.doFilter(req, res);
}

From source file:org.openrepose.filters.translation.TranslationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!isInitialized) {
        LOG.error(//from   w  w  w.j a  va2  s  . com
                "Filter has not yet initialized... Please check your configuration files and your artifacts directory.");
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else {
        HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper((HttpServletRequest) request);
        HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(
                (HttpServletResponse) response, MUTABLE, MUTABLE, response.getOutputStream());

        final HandleRequestResult handleRequestResult = handleRequest(requestWrapper, responseWrapper);
        HttpServletRequestWrapper handleRequestWrapper = handleRequestResult.getRequest();
        HttpServletResponseWrapper handleResponseWrapper = handleRequestResult.getResponse();

        switch (handleRequestResult.getFilterAction()) {
        case NOT_SET:
            chain.doFilter(request, response);
            break;
        case PASS:
            chain.doFilter(handleRequestWrapper, handleResponseWrapper);
            handleResponseWrapper.commitToResponse();
            break;
        case PROCESS_RESPONSE:
            chain.doFilter(handleRequestWrapper, handleResponseWrapper);
            handleResponse(handleRequestWrapper, handleResponseWrapper);
            handleResponseWrapper.commitToResponse();
            break;
        case RETURN:
            break;
        }
    }
}

From source file:de.thorstenberger.taskmodel.view.webapp.filter.ExportPDFFilter.java

/**
 * Render the given xhtml document as pdf and write it to the response outputstream.
 *
 * @param dom//  w ww  .  java  2s  .c o m
 *            xhtml document
 * @param request
 * @param response
 * @throws IOException
 *             if the document could not get renderered
 */
private void renderPdf(final Document dom, final HttpServletRequest request, final ServletResponse response)
        throws IOException {
    final ITextRenderer renderer = new ITextRenderer(80 / 3f, 15);
    if (fontPath != null) {
        try {
            log.debug("Using unicode font at path " + fontPath);
            renderer.getFontResolver().addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        } catch (DocumentException e1) {
            e1.printStackTrace();
        }
    }
    renderer.setDocument(dom, getLocalURL(request));
    renderer.layout();

    response.setContentType("application/pdf");
    // set an appropriate filename
    ((HttpServletResponse) response).setHeader("Content-Disposition",
            "attachment; filename=" + request.getParameter(EXPORTFILENAME));

    try {
        renderer.createPDF(response.getOutputStream());
    } catch (final DocumentException e) {
        log.error("Could not render pdf.", e);
        // FIXME should we just return the original content?
        throw new IOException(e.getMessage());
    }
}