Example usage for javax.servlet ServletOutputStream flush

List of usage examples for javax.servlet ServletOutputStream flush

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:com.mkmeier.quickerbooks.ProcessSquare.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*from  ww  w  . ja v a  2 s  . c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        showForm(request, response);
    } else {

        ServletFileUploader up = new ServletFileUploader();
        up.parseRequest(request);

        File file = up.getFileMap().get("squareTxn");

        int incomeAcctNum = Integer.parseInt(up.getFieldMap().get("incomeAcct"));
        int feeAcctNum = Integer.parseInt(up.getFieldMap().get("feeAcct"));
        int depositAcctNum = Integer.parseInt(up.getFieldMap().get("depositAcct"));

        QbAccount incomeAcct = getAccount(incomeAcctNum);
        QbAccount feeAcct = getAccount(feeAcctNum);
        QbAccount depositAcct = getAccount(depositAcctNum);

        SquareParser sp = new SquareParser(file);
        List<SquareTxn> txns;

        try {
            txns = sp.parse();
        } catch (SquareException ex) {
            throw new ServletException(ex);
        }

        SquareToIif squareToIif = new SquareToIif(txns, incomeAcct, feeAcct, depositAcct);
        File iifFile = squareToIif.getIifFile();

        response.setHeader("Content-Disposition", "attachement; filename=\"iifFile.iif\"");
        ServletOutputStream out = response.getOutputStream();
        FileInputStream in = new FileInputStream(iifFile);
        byte[] buffer = new byte[4096];
        int length;
        while ((length = in.read(buffer)) > 0) {
            out.write(buffer, 0, length);
        }
        in.close();
        out.flush();

        //       PrintWriter out = response.getWriter();
        //       for (SquareTxn txn : txns) {
        //      out.println(txn.toString());
        //       }
    }
}

From source file:com.jd.survey.web.settings.InvitationController.java

/**
 *  exports a sample invitations comma delimited file
 * @param dataSetId/* w  ww  . j  ava  2  s .  co  m*/
 * @param principal
 * @param response
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/example", produces = "text/html")
public void getExampleCsvFile(Principal principal, HttpServletResponse response) {
    try {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(messageSource.getMessage(FIRST_NAME_MESSAGE, null, LocaleContextHolder.getLocale())
                .replace(",", ""));
        stringBuilder.append(",");
        stringBuilder.append(messageSource
                .getMessage(MIDDLE_NAME_MESSAGE, null, LocaleContextHolder.getLocale()).replace(",", ""));
        stringBuilder.append(",");
        stringBuilder.append(messageSource.getMessage(LAST_NAME_MESSAGE, null, LocaleContextHolder.getLocale())
                .replace(",", ""));
        stringBuilder.append(",");
        stringBuilder.append(messageSource.getMessage(EMAIL_MESSAGE, null, LocaleContextHolder.getLocale())
                .replace(",", ""));
        stringBuilder.append("\n");
        stringBuilder.append("a,b,c,abc@jdsoft.com\n");
        //response.setContentType("text/html; charset=utf-8");
        response.setContentType("application/octet-stream");
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Content-Disposition", "inline;filename=Invitationsexample.csv");
        ServletOutputStream servletOutputStream = response.getOutputStream();
        servletOutputStream.write(stringBuilder.toString().getBytes("UTF-8"));
        servletOutputStream.flush();

    }

    catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:org.betaconceptframework.astroboa.resourceapi.filter.CmsDefinitionFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    String repositoryId = null;/*from w w w  . j  a va 2s  . co m*/
    String definitionFullPath = null;

    String requiredURIRegularExpression = "^" + httpServletRequest.getContextPath()
            + CONTENT_OBJECT_TYPE_DEFINITION_FILTER_PREFIX + "/" + "repository/(.+)" + // group 1
            "/" + "definitionFullPath/(.+{1,300})" // group 2
    ;

    Pattern requiredURIPattern = Pattern.compile(requiredURIRegularExpression);
    Matcher uriMatcher = requiredURIPattern.matcher(httpServletRequest.getRequestURI());

    if (!uriMatcher.matches()) {
        logger.warn("Invalid request " + httpServletRequest.getRequestURI());
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
    } else {

        repositoryId = uriMatcher.group(1);

        definitionFullPath = uriMatcher.group(2);

        if (StringUtils.isBlank(definitionFullPath)) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        }

        String filename = (definitionFullPath.endsWith(".xsd") ? definitionFullPath
                : definitionFullPath + ".xsd");

        repositoryService.loginAsAnonymous(repositoryId);

        String definitionSchema = definitionService.getCmsDefinition(definitionFullPath,
                ResourceRepresentationType.XSD, true);

        if (definitionSchema == null) {
            logger.warn("Definition service retuned null for " + httpServletRequest.getRequestURI());
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        } else {

            try {

                ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();

                httpServletResponse.setCharacterEncoding("UTF-8");
                httpServletResponse.setContentType("text/xml");
                httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + filename);

                servletOutputStream.write(definitionSchema.getBytes());

                servletOutputStream.flush();

            } catch (Exception e) {
                logger.error("", e);
                httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        }
    }

}

From source file:org.activiti.app.rest.idm.IdmProfileResource.java

@RequestMapping(value = "/profile-picture", method = RequestMethod.GET)
public void getProfilePicture(HttpServletResponse response) {
    try {//from   w  ww.  j ava  2 s  . c om
        Picture picture = identityService.getUserPicture(SecurityUtils.getCurrentUserId());
        response.setContentType(picture.getMimeType());
        ServletOutputStream servletOutputStream = response.getOutputStream();
        BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(picture.getBytes()));

        byte[] buffer = new byte[32384];
        while (true) {
            int count = in.read(buffer);
            if (count == -1)
                break;
            servletOutputStream.write(buffer, 0, count);
        }

        // Flush and close stream
        servletOutputStream.flush();
        servletOutputStream.close();
    } catch (Exception e) {
        throw new InternalServerErrorException("Could not get profile picture", e);
    }
}

From source file:eu.freme.broker.tools.internationalization.EInternationalizationFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    if (!(req instanceof HttpServletRequest) || !(res instanceof HttpServletResponse)) {
        chain.doFilter(req, res);/*from w  ww. j a v  a2  s .c o  m*/
        return;
    }

    HttpServletRequest httpRequest = (HttpServletRequest) req;
    HttpServletResponse httpResponse = (HttpServletResponse) res;

    if (httpRequest.getMethod().equals("OPTIONS")) {
        chain.doFilter(req, res);
        return;
    }

    String uri = httpRequest.getRequestURI();
    for (Pattern pattern : endpointBlacklistRegex) {
        if (pattern.matcher(uri).matches()) {
            chain.doFilter(req, res);
            return;
        }
    }

    String informat = getInformat(httpRequest);
    String outformat = getOutformat(httpRequest);

    if (outformat != null && (informat == null || !outformat.equals(informat))) {
        Exception exception = new BadRequestException("Can only convert to outformat \"" + outformat
                + "\" when informat is also \"" + outformat + "\"");
        exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception);
        return;
    }

    if (outformat != null && !outputFormats.contains(outformat)) {
        Exception exception = new BadRequestException("\"" + outformat + "\" is not a valid output format");
        exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception);
        return;
    }

    if (informat == null) {
        chain.doFilter(req, res);
        return;
    }

    boolean roundtripping = false;
    if (outformat != null) {
        roundtripping = true;
        logger.debug("convert from " + informat + " to " + outformat);
    } else {
        logger.debug("convert input from " + informat + " to nif");
    }

    // do conversion of informat to nif
    // create BodySwappingServletRequest

    String inputQueryString = req.getParameter("input");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try (InputStream requestInputStream = inputQueryString == null ? /*
                                                                     * read
                                                                     * data
                                                                     * from
                                                                     * request
                                                                     * body
                                                                     */req.getInputStream()
            : /*
              * read data from query string input
              * parameter
              */new ReaderInputStream(new StringReader(inputQueryString), "UTF-8")) {
        // copy request content to buffer
        IOUtils.copy(requestInputStream, baos);
    }

    // create request wrapper that converts the body of the request from the
    // original format to turtle
    Reader nif;

    byte[] baosData = baos.toByteArray();
    if (baosData.length == 0) {
        Exception exception = new BadRequestException("No input data found in request.");
        exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception);
        return;
    }

    ByteArrayInputStream bais = new ByteArrayInputStream(baosData);
    try {
        nif = eInternationalizationApi.convertToTurtle(bais, informat.toLowerCase());
    } catch (ConversionException e) {
        logger.error("Error", e);
        throw new InternalServerErrorException("Conversion from \"" + informat + "\" to NIF failed");
    }

    BodySwappingServletRequest bssr = new BodySwappingServletRequest((HttpServletRequest) req, nif,
            roundtripping);

    if (!roundtripping) {
        chain.doFilter(bssr, res);
        return;
    }

    ConversionHttpServletResponseWrapper dummyResponse;

    try {
        dummyResponse = new ConversionHttpServletResponseWrapper(httpResponse, eInternationalizationApi,
                new ByteArrayInputStream(baosData), informat, outformat);

        chain.doFilter(bssr, dummyResponse);

        ServletOutputStream sos = httpResponse.getOutputStream();

        byte[] data = dummyResponse.writeBackToClient();
        httpResponse.setContentLength(data.length);
        sos.write(data);
        sos.flush();
        sos.close();

    } catch (ConversionException e) {
        e.printStackTrace();
        // exceptionHandlerService.writeExceptionToResponse((HttpServletResponse)res,new
        // InternalServerErrorException());
    }
}

From source file:org.inbio.ait.web.ajax.controller.SelectAllController.java

private ModelAndView writeReponse(HttpServletRequest request, HttpServletResponse response, List<Polygon> pList)
        throws Exception {

    response.setCharacterEncoding("ISO-8859-1");
    response.setContentType("text/xml");
    // Binary output
    ServletOutputStream out = response.getOutputStream();

    if (pList != null) {
        StringBuilder result = new StringBuilder();
        result.append("<?xml version='1.0' encoding='ISO-8859-1'?><response>");
        for (Polygon p : pList) {
            result.append("<polygon><id>" + p.getId() + "</id>");
            result.append("<name>" + p.getName() + "</name></polygon>");
        }//  w  w  w .jav a2s  . c  o m
        result.append("</response>");
        out.println(result.toString());
    }

    out.flush();
    out.close();

    return null;
}

From source file:annis.gui.servlets.BinaryServlet.java

private void writeStepByStep(int offset, int completeLength, WebResource binaryRes, ServletOutputStream out)
        throws IOException {
    int remaining = completeLength;
    while (remaining > 0) {
        int stepLength = Math.min(MAX_LENGTH, remaining);

        AnnisBinary bin = binaryRes.path("" + offset).path("" + stepLength).get(AnnisBinary.class);
        Validate.isTrue(bin.getLength() == stepLength);

        out.write(bin.getBytes());/*from w ww.j a  va  2  s. co m*/
        out.flush();

        offset += stepLength;
        remaining = remaining - stepLength;
    }
}

From source file:hudson.jbpm.PluginImpl.java

/**
 * Draws a JPEG for a process definition
 * /*from  w  w w . java 2  s.com*/
 * @param req
 * @param rsp
 * @param processDefinition
 * @throws IOException
 */
public void doProcessDefinitionImage(StaplerRequest req, StaplerResponse rsp,
        @QueryParameter("processDefinition") long processDefinition) throws IOException {

    JbpmContext context = getCurrentJbpmContext();
    ProcessDefinition definition = context.getGraphSession().getProcessDefinition(processDefinition);
    FileDefinition fd = definition.getFileDefinition();
    byte[] bytes = fd.getBytes("processimage.jpg");
    rsp.setContentType("image/jpeg");
    ServletOutputStream output = rsp.getOutputStream();

    BufferedImage loaded = ImageIO.read(new ByteArrayInputStream(bytes));
    BufferedImage aimg = new BufferedImage(loaded.getWidth(), loaded.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D g = aimg.createGraphics();
    g.drawImage(loaded, null, 0, 0);
    g.dispose();
    ImageIO.write(aimg, "jpg", output);
    output.flush();
    output.close();
}

From source file:com.jd.survey.web.settings.DataSetController.java

/**
 * exports a dataset to a comma delimited file
 * @param dataSetId/*w  w w  .j a  v a  2  s.  c  om*/
 * @param principal
 * @param response
 */

@RequestMapping(value = "/{id}", params = "export", produces = "text/html")
public void export(@PathVariable("id") Long dataSetId, Principal principal, HttpServletResponse response) {
    try {

        String commaDelimtedString = surveySettingsService.exportDatasetItemsToCommaDelimited(dataSetId);
        //response.setContentType("text/html; charset=utf-8");
        response.setContentType("application/octet-stream");
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Content-Disposition", "inline;filename=dataSetItems" + dataSetId + ".csv");
        ServletOutputStream servletOutputStream = response.getOutputStream();
        servletOutputStream.write(commaDelimtedString.getBytes("UTF-8"));
        servletOutputStream.flush();

    }

    catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:org.apache.cxf.fediz.spring.web.FederationSignOutCleanupFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    String wa = request.getParameter(FederationConstants.PARAM_ACTION);
    if (FederationConstants.ACTION_SIGNOUT_CLEANUP.equals(wa)) {
        if (request instanceof HttpServletRequest) {
            ((HttpServletRequest) request).getSession().invalidate();
        }/*from w  w  w  . j av a2  s  .  c o m*/

        final ServletOutputStream responseOutputStream = response.getOutputStream();
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("logout.jpg");
        if (inputStream == null) {
            LOG.warn("Could not write logout.jpg");
            return;
        }
        int read = 0;
        byte[] buf = new byte[1024];
        while ((read = inputStream.read(buf)) != -1) {
            responseOutputStream.write(buf, 0, read);
        }
        inputStream.close();
        responseOutputStream.flush();
    } else {
        chain.doFilter(request, response);
    }
}