Example usage for javax.servlet.http HttpServletResponse flushBuffer

List of usage examples for javax.servlet.http HttpServletResponse flushBuffer

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse flushBuffer.

Prototype

public void flushBuffer() throws IOException;

Source Link

Document

Forces any content in the buffer to be written to the client.

Usage

From source file:org.jasig.cas.support.oauth.web.OAuth20ProfileController.java

@Override
protected ModelAndView handleRequestInternal(final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    String accessToken = request.getParameter(OAuthConstants.ACCESS_TOKEN);
    if (StringUtils.isBlank(accessToken)) {
        final String authHeader = request.getHeader("Authorization");
        if (StringUtils.isNotBlank(authHeader) && authHeader.startsWith(OAuthConstants.BEARER_TOKEN + " ")) {
            accessToken = authHeader.substring(OAuthConstants.BEARER_TOKEN.length() + 1);
        }//from w  w  w  . jav a 2 s .  c o m
    }
    LOGGER.debug("{} : {}", OAuthConstants.ACCESS_TOKEN, accessToken);

    try (final JsonGenerator jsonGenerator = this.jsonFactory.createJsonGenerator(response.getWriter())) {
        response.setContentType("application/json");
        // accessToken is required
        if (StringUtils.isBlank(accessToken)) {
            LOGGER.error("Missing {}", OAuthConstants.ACCESS_TOKEN);
            jsonGenerator.writeStartObject();
            jsonGenerator.writeStringField("error", OAuthConstants.MISSING_ACCESS_TOKEN);
            jsonGenerator.writeEndObject();
            return null;
        }
        // get ticket granting ticket
        final TicketGrantingTicket ticketGrantingTicket = (TicketGrantingTicket) this.ticketRegistry
                .getTicket(accessToken);
        if (ticketGrantingTicket == null || ticketGrantingTicket.isExpired()) {
            LOGGER.error("expired accessToken : {}", accessToken);
            jsonGenerator.writeStartObject();
            jsonGenerator.writeStringField("error", OAuthConstants.EXPIRED_ACCESS_TOKEN);
            jsonGenerator.writeEndObject();
            return null;
        }
        // generate profile : identifier + attributes
        final Principal principal = ticketGrantingTicket.getAuthentication().getPrincipal();
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField(ID, principal.getId());
        jsonGenerator.writeArrayFieldStart(ATTRIBUTES);
        final Map<String, Object> attributes = principal.getAttributes();
        for (final Map.Entry<String, Object> entry : attributes.entrySet()) {
            jsonGenerator.writeStartObject();
            jsonGenerator.writeObjectField(entry.getKey(), entry.getValue());
            jsonGenerator.writeEndObject();
        }
        jsonGenerator.writeEndArray();
        jsonGenerator.writeEndObject();
        return null;
    } finally {
        response.flushBuffer();
    }
}

From source file:mapbuilder.ProxyRedirect.java

/***************************************************************************
 * Process the HTTP Get request/*ww w.  j  a  v a 2s.  c  o  m*/
 */
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {
        if (log.isDebugEnabled()) {
            Enumeration e = request.getHeaderNames();
            while (e.hasMoreElements()) {
                String name = (String) e.nextElement();
                String value = request.getHeader(name);
                log.debug("request header:" + name + ":" + value);
            }
        }

        // Transfer bytes from in to out
        log.debug("HTTP GET: transferring...");

        //execute the GET
        String serverUrl = request.getParameter("url");
        if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) {
            log.info("GET param serverUrl:" + serverUrl);
            HttpClient client = new HttpClient();
            GetMethod httpget = new GetMethod(serverUrl);
            client.executeMethod(httpget);

            if (log.isDebugEnabled()) {
                Header[] respHeaders = httpget.getResponseHeaders();
                for (int i = 0; i < respHeaders.length; ++i) {
                    String headerName = respHeaders[i].getName();
                    String headerValue = respHeaders[i].getValue();
                    log.debug("responseHeaders:" + headerName + "=" + headerValue);
                }
            }

            //dump response to out
            if (httpget.getStatusCode() == HttpStatus.SC_OK) {
                //force the response to have XML content type (WMS servers generally don't)
                response.setContentType("text/xml");
                String responseBody = httpget.getResponseBodyAsString().trim();
                // use encoding of the request or UTF8
                String encoding = request.getCharacterEncoding();
                if (encoding == null)
                    encoding = "UTF-8";
                response.setCharacterEncoding(encoding);
                log.info("responseEncoding:" + encoding);
                // do not set a content-length of the response (string length might not match the response byte size)
                //response.setContentLength(responseBody.length());
                log.info("responseBody:" + responseBody);
                PrintWriter out = response.getWriter();
                out.print(responseBody);
                response.flushBuffer();
            } else {
                log.error("Unexpected failure: " + httpget.getStatusLine().toString());
            }
            httpget.releaseConnection();
        } else {
            throw new ServletException("only HTTP(S) protocol supported");
        }

    } catch (Throwable e) {
        throw new ServletException(e);
    }
}

From source file:com.orange.clara.cloud.servicedbdumper.controllers.ManagerController.java

@RequestMapping(value = Routes.DOWNLOAD_DUMP_FILE_ROOT
        + "/{dumpFileId:[0-9]+}", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public @ResponseBody void download(@PathVariable Integer dumpFileId, HttpServletRequest request,
        HttpServletResponse resp, @RequestParam(value = "original", required = false) String original)
        throws IOException, DumpFileDeletedException {
    DatabaseDumpFile databaseDumpFile = getDatabaseDumpFile(dumpFileId);
    this.checkDbDumperServiceInstance(databaseDumpFile.getDbDumperServiceInstance());
    this.checkDatabaseDumpFile(databaseDumpFile);
    String userRequest = "";
    String passwordRequest = "";
    String authorization = request.getHeader("Authorization");
    if (authorization != null && authorization.startsWith("Basic")) {
        String base64Credentials = authorization.substring("Basic".length()).trim();
        String credentials = new String(Base64.getDecoder().decode(base64Credentials),
                Charset.forName("UTF-8"));
        String[] values = credentials.split(":", 2);
        userRequest = values[0];//from  ww  w .  j  a v  a 2s . c o m
        passwordRequest = values[1];
    } else {
        this.getErrorResponseEntityBasicAuth(resp);
        return;
    }

    if (!userRequest.equals(databaseDumpFile.getUser())
            || !passwordRequest.equals(databaseDumpFile.getPassword())) {
        this.getErrorResponseEntityBasicAuth(resp);
        return;
    }

    String fileName = DumpFileHelper.getFilePath(databaseDumpFile);
    resp.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
    resp.setContentLengthLong(this.filer.getContentLength(fileName));
    InputStream inputStream = null;
    if (original == null || original.isEmpty()) {
        inputStream = filer.retrieveWithOriginalStream(fileName);
    } else {
        inputStream = filer.retrieveWithStream(fileName);
        File file = new File(fileName);
        String[] filenames = file.getName().split("\\.");
        if (filenames.length >= 2) {
            fileName = filenames[0] + "." + filenames[1];
        }

    }
    inputStream = new BufferedInputStream(inputStream);
    File file = new File(fileName);
    resp.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

    OutputStream outputStream = null;
    outputStream = resp.getOutputStream();
    try {
        ByteStreams.copy(inputStream, outputStream);
    } finally {
        Closeables.closeQuietly(inputStream);
        outputStream.flush();
        resp.flushBuffer();
        Closeables.close(outputStream, true);
    }
}

From source file:org.motechproject.mobile.web.OXDFormDownloadServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  www . j ava2 s  .c om*/
 *
 * @param request  servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException      if an I/O error occurs
 */
@RequestMapping(method = RequestMethod.POST)
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Get our raw input and output streams
    InputStream input = request.getInputStream();
    OutputStream output = response.getOutputStream();

    // Wrap the streams for compression
    ZOutputStream zOutput = new ZOutputStream(output, JZlib.Z_BEST_COMPRESSION);

    // Wrap the streams so we can use logical types
    DataInputStream dataInput = new DataInputStream(input);
    DataOutputStream dataOutput = new DataOutputStream(zOutput);

    try {

        // Read the common submission data from mobile phone
        String name = dataInput.readUTF();
        String password = dataInput.readUTF();
        String serializer = dataInput.readUTF();
        String locale = dataInput.readUTF();

        byte action = dataInput.readByte();

        // TODO: add authentication, possible M6 enhancement

        log.info("downloading: name=" + name + ", password=" + password + ", serializer=" + serializer
                + ", locale=" + locale + ", action=" + action);

        EpihandyXformSerializer serObj = new EpihandyXformSerializer();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // Perform the action specified by the mobile phone
        try {
            if (action == ACTION_DOWNLOAD_STUDY_LIST) {
                serObj.serializeStudies(baos, studyService.getStudies());
            } else if (action == ACTION_DOWNLOAD_USERS_AND_FORMS) {

                serObj.serializeUsers(baos, userService.getUsers());

                int studyId = dataInput.readInt();
                String studyName = studyService.getStudyName(studyId);
                List<String> studyForms = formService.getStudyForms(studyId);

                serObj.serializeForms(baos, studyForms, studyId, studyName);

            }
        } catch (Exception e) {
            dataOutput.writeByte(RESPONSE_ERROR);
            throw new ServletException("failed to serialize data", e);
        }

        // Write out successful upload response
        dataOutput.writeByte(RESPONSE_SUCCESS);
        dataOutput.write(baos.toByteArray());
        response.setStatus(HttpServletResponse.SC_OK);

    } finally {
        // Should always do this
        dataOutput.flush();
        zOutput.finish();
        response.flushBuffer();
    }
}

From source file:org.nuxeo.ecm.platform.ui.web.auth.ntlm.NTLMAuthenticator.java

public static NtlmPasswordAuthentication negotiate(HttpServletRequest req, HttpServletResponse resp,
        boolean skipAuthentication) throws IOException, ServletException {
    log.debug("NTLM negotiation starts");

    String msg = req.getHeader("Authorization");

    log.debug("NTLM negotiation header = " + msg);
    NtlmPasswordAuthentication ntlm;/*from   w w w. j ava2s.c  om*/
    if (msg != null && msg.startsWith("NTLM ")) {
        HttpSession ssn = req.getSession();
        byte[] challenge;

        UniAddress dc;
        if (loadBalance) {
            NtlmChallenge chal = (NtlmChallenge) ssn.getAttribute(NTLM_HTTP_CHAL_SESSION_KEY);
            if (chal == null) {
                chal = SmbSession.getChallengeForDomain();
                ssn.setAttribute(NTLM_HTTP_CHAL_SESSION_KEY, chal);
            }
            dc = chal.dc;
            challenge = chal.challenge;
        } else {
            dc = UniAddress.getByName(domainController, true);
            dc = UniAddress.getByName(dc.getHostAddress(), true);
            challenge = SmbSession.getChallenge(dc);
        }

        ntlm = NtlmSsp.authenticate(req, resp, challenge);
        if (ntlm == null) {
            log.debug("NtlmSsp.authenticate returned null");
            return null;
        }

        log.debug("NtlmSsp.authenticate succeed");
        log.debug("Domain controller is " + dc.getHostName());
        if (ntlm.getDomain() != null) {
            log.debug("NtlmSsp.authenticate => domain = " + ntlm.getDomain());
        } else {
            log.debug("NtlmSsp.authenticate => null domain");
        }
        if (ntlm.getUsername() != null) {
            log.debug("NtlmSsp.authenticate => userName = " + ntlm.getUsername());
        } else {
            log.debug("NtlmSsp.authenticate => userName = null");
        }
        if (ntlm.getPassword() != null) {
            log.debug("NtlmSsp.authenticate => password = " + ntlm.getPassword());
        } else {
            log.debug("NtlmSsp.authenticate => password = null");
        }

        /* negotiation complete, remove the challenge object */
        ssn.removeAttribute(NTLM_HTTP_CHAL_SESSION_KEY);
        if (!skipAuthentication) {
            try {
                log.debug("Trying to logon NTLM session on dc " + dc.toString());
                SmbSession.logon(dc, ntlm);
                log.debug(ntlm + " successfully authenticated against " + dc);

            } catch (SmbAuthException sae) {

                log.error(ntlm.getName() + ": 0x" + jcifs.util.Hexdump.toHexString(sae.getNtStatus(), 8) + ": "
                        + sae);

                if (sae.getNtStatus() == NT_STATUS_ACCESS_VIOLATION) {
                    /*
                     * Server challenge no longer valid for externally supplied password hashes.
                     */
                    ssn = req.getSession(false);
                    if (ssn != null) {
                        ssn.removeAttribute(NTLM_HTTP_AUTH_SESSION_KEY);
                    }
                }
                resp.setHeader("WWW-Authenticate", "NTLM");
                resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                resp.setContentLength(0);
                resp.flushBuffer();
                return null;
            }
            req.getSession().setAttribute(NTLM_HTTP_AUTH_SESSION_KEY, ntlm);
        }
    } else {
        log.debug("NTLM negotiation header is null");
        return null;
    }
    return ntlm;
}

From source file:org.apache.axis.transport.http.AxisServlet.java

/**
 * write a message to the response, set appropriate headers for content
 * type..etc.//from www.j  ava2s .  com
 * @param res   response
 * @param responseMsg message to write
 * @throws AxisFault
 * @throws IOException if the response stream can not be written to
 */
private void sendResponse(String contentType, HttpServletResponse res, Message responseMsg)
        throws AxisFault, IOException {
    if (responseMsg == null) {
        res.setStatus(HttpServletResponse.SC_NO_CONTENT);
        if (isDebug) {
            log.debug("NO AXIS MESSAGE TO RETURN!");
            //String resp = Messages.getMessage("noData00");
            //res.setContentLength((int) resp.getBytes().length);
            //res.getWriter().print(resp);
        }
    } else {
        if (isDebug) {
            log.debug("Returned Content-Type:" + contentType);
            // log.debug("Returned Content-Length:" +
            //          responseMsg.getContentLength());
        }

        try {
            res.setContentType(contentType);

            /* My understand of Content-Length
             * HTTP 1.0
             *   -Required for requests, but optional for responses.
             * HTTP 1.1
             *  - Either Content-Length or HTTP Chunking is required.
             *   Most servlet engines will do chunking if content-length is not specified.
             *
             *
             */

            //if(clientVersion == HTTPConstants.HEADER_PROTOCOL_V10) //do chunking if necessary.
            //     res.setContentLength(responseMsg.getContentLength());

            responseMsg.writeTo(res.getOutputStream());
        } catch (SOAPException e) {
            logException(e);
        }
    }

    if (!res.isCommitted()) {
        res.flushBuffer(); // Force it right now.
    }
}

From source file:org.apache.chemistry.opencmis.server.impl.atompub.CmisAtomPubServlet.java

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

    CallContext context = null;/*ww w.j a v a  2 s  .  com*/
    try {
        // CSRF token check
        if (!METHOD_GET.equals(request.getMethod()) && !METHOD_HEAD.equals(request.getMethod())) {
            checkCsrfToken(request, response, false, false);
        }

        // split path
        String[] pathFragments = HttpUtils.splitPath(request);

        // create stream factory
        TempStoreOutputStreamFactory streamFactoy = TempStoreOutputStreamFactory
                .newInstance(getServiceFactory(), pathFragments.length > 0 ? pathFragments[0] : null, request);

        // treat HEAD requests
        if (METHOD_HEAD.equals(request.getMethod())) {
            request = new HEADHttpServletRequestWrapper(request);
            response = new NoBodyHttpServletResponseWrapper(response);
        } else {
            request = new QueryStringHttpServletRequestWrapper(request);
        }

        // set default headers
        response.addHeader("Cache-Control", "private, max-age=0");
        response.addHeader("Server", ServerVersion.OPENCMIS_SERVER);

        context = createContext(getServletContext(), request, response, streamFactoy);
        dispatch(context, request, response, pathFragments);
    } catch (Exception e) {
        if (e instanceof CmisUnauthorizedException) {
            response.setHeader("WWW-Authenticate", "Basic realm=\"CMIS\", charset=\"UTF-8\"");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization Required");
        } else if (e instanceof CmisPermissionDeniedException) {
            if ((context == null) || (context.getUsername() == null)) {
                response.setHeader("WWW-Authenticate", "Basic realm=\"CMIS\", charset=\"UTF-8\"");
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization Required");
            } else {
                response.sendError(getErrorCode((CmisPermissionDeniedException) e), e.getMessage());
            }
        } else {
            printError(e, request, response);
        }
    } finally {
        // we are done.
        try {
            response.flushBuffer();
        } catch (IOException ioe) {
            LOG.error("Could not flush resposne: {}", ioe.toString(), ioe);
        }
    }
}

From source file:org.ngrinder.script.controller.SvnDavController.java

/**
 * Request Handler./*from  w w w . j a  v a 2 s  .c om*/
 *
 * @param request  request
 * @param response response
 * @throws ServletException occurs when servlet has a problem.
 * @throws IOException      occurs when file system has a problem.
 */
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (LOGGER.isTraceEnabled()) {
        logRequest(request);
    }
    try {
        // To make it understand Asian Language..
        request = new MyHttpServletRequestWrapper(request);
        DAVRepositoryManager repositoryManager = new DAVRepositoryManager(getDAVConfig(), request);
        ServletDAVHandler handler = DAVHandlerFactory.createHandler(repositoryManager, request, response);
        handler.execute();
    } catch (DAVException de) {
        response.setContentType(XML_CONTENT_TYPE);
        handleError(de, response);
    } catch (SVNException svne) {
        StringWriter sw = new StringWriter();
        svne.printStackTrace(new PrintWriter(sw));

        /**
         * truncate status line if it is to long
         */
        String msg = sw.getBuffer().toString();
        if (msg.length() > 128) {
            msg = msg.substring(0, 128);
        }
        SVNErrorCode errorCode = svne.getErrorMessage().getErrorCode();
        if (errorCode == SVNErrorCode.FS_NOT_DIRECTORY || errorCode == SVNErrorCode.FS_NOT_FOUND
                || errorCode == SVNErrorCode.RA_DAV_PATH_NOT_FOUND) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        } else if (errorCode == SVNErrorCode.NO_AUTH_FILE_PATH) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, msg);
        } else if (errorCode == SVNErrorCode.RA_NOT_AUTHORIZED) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, msg);
        } else {
            String errorBody = generateStandardizedErrorBody(errorCode.getCode(), null, null,
                    svne.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType(XML_CONTENT_TYPE);
            response.getWriter().print(errorBody);
        }
    } catch (Throwable th) {
        StringWriter sw = new StringWriter();
        th.printStackTrace(new PrintWriter(sw));
        String msg = sw.getBuffer().toString();
        LOGGER.debug("Error in DavSVN Controller", th);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
    } finally {
        response.flushBuffer();
    }
}

From source file:org.agnitas.web.Rdir.java

/**
 * Servlet service-method, is invoked when user calls the servlet. Logs the click to DB and redirects recipient to actual link. Also invokes link action (if there is one) and mailing default click
 * action./*ww  w  .j a v  a  2 s.  c  o  m*/
 * 
 * @param req
 *            HTTP request. Should contain parameter "uid" - the encoded data of link/user (contains companyID, urlID, customerID, mailingID)
 * @param res
 *            HTTP response. If everything goes ok - the response sends redirect to actual link
 * @throws IOException
 *             if an input/output error occurs
 * @throws ServletException
 *             if a servlet exception occurs
 */
@Override
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    ApplicationContext con = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());

    try {
        // validate uid
        ExtensibleUID uid = getExtensibleUIDService().newUID();

        String param = req.getParameter("uid");
        if (param != null) {
            try {
                uid = getExtensibleUIDService().parse(param);
            } catch (UIDParseException e) {
                logger.warn("Error parsing UID: " + param + " (" + e.getMessage() + ")");
                logger.debug(e);
                return;
            }
        } else {
            logger.error("service: uid missing");
        }
        if (uid == null || uid.getCompanyID() == 0) {
            return;
        }

        Company aCompany = AgnUtils.getCompanyCache(uid.getCompanyID(), con);
        if (aCompany == null) {
            return;
        }

        /* TODO: check validateUID -> didn't recognize valid UIDs (maybe unittest) */
        /*
         * // TODO: Implement Helper class to validate the very old UIDs if(uid.validateUID(aCompany.getSecret()) == false) { logger.warn("uid invalid: "+param); return; }
         */

        TrackableLink aLink = (TrackableLink) urlCache.get(uid.getUrlID());
        if (aLink == null || aLink.getCompanyID() != uid.getCompanyID()) {
            // get link and do actions
            aLink = getTrackableLinkDao().getTrackableLink(uid.getUrlID(), uid.getCompanyID());
            if (aLink != null) {
                urlCache.put(uid.getUrlID(), aLink);
            }
        }

        // link is beeing personalized, replaces AGNUID
        String fullUrl = aLink.personalizeLink(uid.getCustomerID(), param, con);
        if (fullUrl == null) {
            logger.error("service: could not personalize link");
            return;
        }

        if (AgnUtils.getDefaultValue("redirection.status") == null
                || AgnUtils.getDefaultIntValue("redirection.status") == 302) {
            res.sendRedirect(fullUrl);
            // res.sendRedirect(aLink.getFullUrl());
        } else {
            res.setStatus(AgnUtils.getDefaultIntValue("redirection.status"));
            res.setHeader("Location", fullUrl);
            res.flushBuffer();
        }

        // log click in db
        if (!getTrackableLinkDao().logClickInDB(aLink, uid.getCustomerID(), req.getRemoteAddr())) {
            return;
        }

        int companyID = uid.getCompanyID();
        int mailingID = uid.getMailingID();
        int customerID = uid.getCustomerID();
        int clickActionID = getMailingDao().getMailingClickAction(mailingID, companyID);
        if (clickActionID != 0) {
            EmmAction emmAction = getEmmActionDao().getEmmAction(clickActionID, companyID);
            if (emmAction != null) {
                // execute configured actions
                CaseInsensitiveMap params = new CaseInsensitiveMap();
                params.put("requestParameters", AgnUtils.getReqParameters(req));
                params.put("_request", req);
                params.put("customerID", customerID);
                params.put("mailingID", mailingID);
                emmAction.executeActions(con, params);
            }
        }

        // execute configured actions
        CaseInsensitiveMap params = new CaseInsensitiveMap();
        params.put("requestParameters", AgnUtils.getReqParameters(req));
        params.put("_request", req);

        aLink.performLinkAction(params, uid.getCustomerID(), con);
    } catch (Exception e) {
        logger.error(e);
    }
}

From source file:org.jasig.ssp.web.api.reports.ReportBaseController.java

protected void renderJasperReport(HttpServletResponse response, Map<String, Object> reportParameters,
        Collection<R> reportResults, String reportViewUrl, String reportType, String reportName)
        throws JRException, IOException {

    SearchParameters.addReportDateToMap(reportParameters);
    final InputStream is = getClass().getResourceAsStream(reportViewUrl);
    final ByteArrayOutputStream os = new ByteArrayOutputStream();

    JRDataSource beanDS;//from   w  w w . ja va2 s  .  c om
    if (reportResults == null || reportResults.size() <= 0) {
        beanDS = new JREmptyDataSource();
    } else {
        beanDS = new JRBeanCollectionDataSource(reportResults);
    }

    if (REPORT_TYPE_PDF.equals(reportType)) {
        DefaultJasperReportsContext context = DefaultJasperReportsContext.getInstance();
        JRPropertiesUtil.getInstance(context).setProperty("net.sf.jasperreports.awt.ignore.missing.font",
                "true");
        JRPropertiesUtil.getInstance(context).setProperty("net.sf.jasperreports.default.font.name",
                "DejaVu Sans");
        JRPropertiesUtil.getInstance(context).setProperty("net.sf.jasperreports.default.pdf.embedded", "true");
        JRPropertiesUtil.getInstance(context).setProperty("net.sf.jasperreports.default.pdf.font.name",
                "DejaVu Sans");

        if (!(reportParameters.containsKey("realPath"))) {
            reportParameters.put("realPath", servletContext.getRealPath("/"));
        }
    }

    JasperFillManager.fillReportToStream(is, os, reportParameters, beanDS);
    final InputStream decodedInput = new ByteArrayInputStream(os.toByteArray());

    if (REPORT_TYPE_PDF.equals(reportType)) {
        response.setHeader("Content-disposition", "attachment; filename=" + reportName + "." + REPORT_TYPE_PDF);
        JasperExportManager.exportReportToPdfStream(decodedInput, response.getOutputStream());
    } else if ("csv".equals(reportType)) {
        writeCsvHttpResponseHeaders(response, reportName);

        final JRCsvExporter exporter = new JRCsvExporter();
        exporter.setParameter(JRExporterParameter.INPUT_STREAM, decodedInput);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
        exporter.setParameter(JRXlsAbstractExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);

        exporter.exportReport();
    }

    response.flushBuffer();
    is.close();
    os.close();
}