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:es.juntadeandalucia.panelGestion.presentacion.controlador.impl.GIController.java

public void getRAFile(Service service) {
    String errorMessage = null;/*  w w w. ja v a2  s .co m*/

    ServletOutputStream os = null;

    try {
        // configures the response
        String fileNameWithExtension = racontroller.getFileNameWithExtension(service);
        HttpServletResponse response = (HttpServletResponse) externalCtx.getResponse();
        response.setContentType("text/xml");
        response.addHeader("Content-disposition",
                "attachment; filename=\"".concat(fileNameWithExtension).concat("\""));

        // gets the configuration file
        InputStream is = racontroller.getConfigurationFile(service);

        os = response.getOutputStream();

        IOUtils.copy(is, os);

        os.flush();
        os.close();

        is.close();

        facesContext.responseComplete();
    } catch (IOException e) {
        errorMessage = "Error al comprimir los archivos de configuracin: " + e.getLocalizedMessage();
    } catch (Exception e) {
        errorMessage = "Error en la descarga de la configuracin: " + e.getLocalizedMessage();
    } finally {
        try {
            if (os != null) {
                os.flush();
                os.close();
            }
        } catch (IOException e) {
            errorMessage = "Error al comprimir los archivos de configuracin: " + e.getLocalizedMessage();
        }
    }

    if (errorMessage != null) {
        StatusMessages.instance().add(Severity.ERROR, errorMessage);
        log.error(errorMessage);
    }
}

From source file:eu.earthobservatory.org.StrabonEndpoint.DescribeBean.java

/**
 * Processes the request made by a client of the endpoint that uses it as a service. 
 * //  ww  w  .  j  a v a 2s.c  om
 * @param request
 * @param response
 * @throws IOException 
 */
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    ServletOutputStream out = response.getOutputStream();

    // get the RDF format (we check only the Accept header)
    RDFFormat format = RDFFormat.forMIMEType(request.getHeader("accept"));

    // get the query
    String query = request.getParameter("query");

    // check for required parameters
    if (format == null || query == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.print(ResponseMessages.getXMLHeader());
        out.print(ResponseMessages.getXMLException(PARAM_ERROR));
        out.print(ResponseMessages.getXMLFooter());

    } else {
        // decode the query
        query = URLDecoder.decode(request.getParameter("query"), "UTF-8");

        response.setContentType(format.getDefaultMIMEType());
        response.setHeader("Content-Disposition", "attachment; filename=describe."
                + format.getDefaultFileExtension() + "; " + format.getCharset());

        try {
            strabonWrapper.describe(query, format.getName(), out);
            response.setStatus(HttpServletResponse.SC_OK);

        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.print(ResponseMessages.getXMLHeader());
            out.print(ResponseMessages.getXMLException(e.getMessage()));
            out.print(ResponseMessages.getXMLFooter());
        }
    }

    out.flush();
}

From source file:com.duroty.application.mail.actions.AttachmentAction.java

/**
 * DOCUMENT ME!//from ww  w. j a  va  2 s . c  om
 *
 * @param request DOCUMENT ME!
 * @param response DOCUMENT ME!
 *
 * @throws ServletException DOCUMENT ME!
 * @throws IOException DOCUMENT ME!
 */
protected void doDownload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    DataInputStream in = null;
    ByteArrayInputStream bais = null;
    ServletOutputStream op = null;

    try {
        String mid = request.getParameter("mid");
        String part = request.getParameter("part");

        Mail filesInstance = getMailInstance(request);

        MailPartObj obj = filesInstance.getAttachment(mid, part);

        int length = 0;
        op = response.getOutputStream();

        String mimetype = obj.getContentType();

        //
        //  Set the response and go!
        //
        //  Yes, I know that the RFC says 'attachment'.  Unfortunately, IE has a typo
        //  in it somewhere, and Netscape seems to accept this typing as well.
        //
        response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
        response.setContentLength((int) obj.getSize());
        response.setHeader("Content-Disposition", "attachement; filename=\"" + obj.getName() + "\"");
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "max-age=0");

        //
        //  Stream to the requester.
        //
        byte[] bbuf = new byte[1024];
        bais = new ByteArrayInputStream(obj.getAttachent());
        in = new DataInputStream(bais);

        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            op.write(bbuf, 0, length);
        }
    } catch (Exception ex) {
    } finally {
        try {
            op.flush();
        } catch (Exception ex) {
        }

        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(op);
    }
}

From source file:com.duroty.application.files.actions.DownloadFileAction.java

/**
 * DOCUMENT ME!//from  w ww.j  a  va 2 s.  com
 *
 * @param request DOCUMENT ME!
 * @param response DOCUMENT ME!
 *
 * @throws ServletException DOCUMENT ME!
 * @throws IOException DOCUMENT ME!
 */
protected void doDownload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    DataInputStream in = null;
    ByteArrayInputStream bais = null;
    ServletOutputStream op = null;

    try {
        String mid = request.getParameter("mid");
        String part = request.getParameter("part");

        Files filesInstance = getFilesInstance(request);

        MailPartObj obj = filesInstance.getAttachment(mid, part);

        int length = 0;
        op = response.getOutputStream();

        String mimetype = obj.getContentType();

        //
        //  Set the response and go!
        //
        //  Yes, I know that the RFC says 'attachment'.  Unfortunately, IE has a typo
        //  in it somewhere, and Netscape seems to accept this typing as well.
        //
        response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
        response.setContentLength((int) obj.getSize());
        response.setHeader("Content-Disposition", "attachement; filename=\"" + obj.getName() + "\"");
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "max-age=0");

        //
        //  Stream to the requester.
        //
        byte[] bbuf = new byte[1024];
        bais = new ByteArrayInputStream(obj.getAttachent());
        in = new DataInputStream(bais);

        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            op.write(bbuf, 0, length);
        }
    } catch (Exception ex) {
    } finally {
        try {
            op.flush();
        } catch (Exception ex) {
        }

        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(op);
    }
}

From source file:com.ephesoft.dcma.gwt.foldermanager.server.UploadDownloadFilesServlet.java

private void downloadFile(HttpServletResponse response, String currentFileDownloadPath) {
    LOG.info(DOWNLOADING_FILE_FROM_PATH + currentFileDownloadPath);
    DataInputStream inputStream = null;
    ServletOutputStream outStream = null;
    try {/*  ww  w  .  j av  a2s .c  om*/
        outStream = response.getOutputStream();
        File file = new File(currentFileDownloadPath);
        int length = 0;
        String mimetype = APPLICATION_OCTET_STREAM;
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());
        String fileName = file.getName();
        response.setHeader(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + fileName + CLOSING_QUOTES);
        byte[] byteBuffer = new byte[1024];
        inputStream = new DataInputStream(new FileInputStream(file));
        length = inputStream.read(byteBuffer);
        while ((inputStream != null) && (length != -1)) {
            outStream.write(byteBuffer, 0, length);
            length = inputStream.read(byteBuffer);
        }
        LOG.info(DOWNLOAD_COMPLETED_FOR_FILEPATH + currentFileDownloadPath);
    } catch (IOException e) {
        LOG.error(EXCEPTION_OCCURED_WHILE_DOWNLOADING_A_FILE_FROM_THE_FILE_PATH + currentFileDownloadPath);
        LOG.error(e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                LOG.error(UNABLE_TO_CLOSE_INPUT_STREAM_FOR_FILE_DOWNLOAD);
            }
        }
        if (outStream != null) {
            try {
                outStream.flush();
            } catch (IOException e) {
                LOG.error(UNABLE_TO_FLUSH_OUTPUT_STREAM_FOR_DOWNLOAD);
            }
            try {
                outStream.close();
            } catch (IOException e) {
                LOG.error(UNABLE_TO_CLOSE_OUTPUT_STREAM_FOR_DOWNLOAD);
            }

        }
    }
}

From source file:org.appcelerator.transport.AjaxServiceTransportServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ////from  w  w  w .java2s.c  o m
    // make sure we check the integrity of the request before we continue
    //
    if (!validate(req, resp)) {
        LOG.warn("security validation failed for request=" + req + " from " + req.getRemoteAddr());
        return;
    }

    String type = req.getContentType();
    int idx = type.indexOf(';');

    if (idx > 0) {
        type = type.substring(0, idx);
    }

    try {
        // decode the incoming request
        ArrayList<Message> requests = new ArrayList<Message>(1);
        ArrayList<Message> responses = new ArrayList<Message>(1);

        ServiceMarshaller.getMarshaller(type).decode(req.getInputStream(), requests);

        if (requests.isEmpty()) {
            // no incoming messages, just return accepted header
            resp.setHeader("Content-Length", "0");
            resp.setContentType("text/plain;charset=UTF-8");
            resp.setStatus(HttpServletResponse.SC_ACCEPTED);
            return;
        }

        HttpSession session = req.getSession();
        InetAddress address = InetAddress.getByName(req.getRemoteAddr());
        //String instanceid = req.getParameter("instanceid");

        for (Message request : requests) {
            request.setUser(req.getUserPrincipal());
            request.setSession(session);
            request.setAddress(address);
            request.setServletRequest(req);

            //FIXME => refactor this out
            if (request.getType().equals(MessageType.APPCELERATOR_STATUS_REPORT)) {
                IMessageDataObject data = (IMessageDataObject) request.getData();
                data.put("remoteaddr", req.getRemoteAddr());
                data.put("remotehost", req.getRemoteHost());
                data.put("remoteuser", req.getRemoteUser());
            }

            ServiceRegistry.dispatch(request, responses);
        }

        if (responses.isEmpty()) {
            // no response messages, just return accepted header
            resp.setHeader("Content-Length", "0");
            resp.setContentType("text/plain;charset=UTF-8");
            resp.setStatus(HttpServletResponse.SC_ACCEPTED);
            return;
        }

        // setup the response
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setHeader("Connection", "Keep-Alive");
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-control", "no-cache, no-store, private, must-revalidate");
        resp.setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");

        // encode the responses
        ServletOutputStream output = resp.getOutputStream();
        ByteArrayOutputStream bout = new ByteArrayOutputStream(1000);
        String responseType = ServiceMarshaller.getMarshaller(type).encode(responses, req.getSession().getId(),
                bout);
        byte buf[] = bout.toByteArray();
        ByteArrayInputStream bin = new ByteArrayInputStream(buf);

        resp.setContentType(responseType);

        // do gzip encoding if browser supports it and if length > 1000 bytes
        String ae = req.getHeader("accept-encoding");
        if (ae != null && ae.indexOf("gzip") != -1 && buf.length > 1000) {
            resp.setHeader("Content-Encoding", "gzip");
            //a Vary: Accept-Encoding HTTP response header to alert proxies that a cached response should be sent only to 
            //clients that send the appropriate Accept-Encoding request header. This prevents compressed content from being sent 
            //to a client that will not understand it.
            resp.addHeader("Vary", "Accept-Encoding");
            GZIPOutputStream gzip = new GZIPOutputStream(output, buf.length);
            Util.copy(bin, gzip);
            gzip.flush();
            gzip.finish();
        } else {
            resp.setContentLength(buf.length);
            Util.copy(bin, output);
        }
        output.flush();
    } catch (Throwable e) {
        LOG.error("Error handling incoming POST request", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

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

/**
  * Gets mailing components//from   w w  w  . j a  va 2s  . c o m
  * TYPE_IMAGE: if component not empty, write it into response
  * <br><br>
  * TYPE_HOSTED_IMAGE: if component not empty, write it into response
  * <br><br>
  * TYPE_THUMBMAIL_IMAGE: if component not empty, write it into response
  * <br><br>
  * TYPE_ATTACHMENT: create preview <br>
  *          write component into response
  * <br><br>
  * TYPE_PERSONALIZED_ATTACHMENT: create preview <br>
  *          write component into response
  * <br><br>
  */
@Override
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {

    ServletOutputStream out = null;
    long len = 0;
    int compId = 0;

    if (!AgnUtils.isUserLoggedIn(req)) {
        return;
    }

    try {
        compId = Integer.parseInt(req.getParameter("compID"));
    } catch (Exception e) {
        logger.warn("Error converting "
                + (req.getParameter("compID") != null ? "'" + req.getParameter("compID") + "'"
                        : req.getParameter("compID"))
                + " to integer", e);
        return;
    }

    if (compId == 0) {
        return;
    }

    int customerID = 0;

    String customerIDStr = req.getParameter("customerID");
    if (StringUtils.isNumeric(customerIDStr)) {
        customerID = Integer.parseInt(customerIDStr);
    }

    MailingComponentDao mDao = (MailingComponentDao) WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext()).getBean("MailingComponentDao");

    MailingComponent comp = mDao.getMailingComponent(compId, AgnUtils.getCompanyID(req));

    if (comp != null) {

        switch (comp.getType()) {
        case MailingComponent.TYPE_IMAGE:
        case MailingComponent.TYPE_HOSTED_IMAGE:
            if (comp.getBinaryBlock() != null) {
                res.setContentType(comp.getMimeType());
                out = res.getOutputStream();
                out.write(comp.getBinaryBlock());
                out.flush();
                out.close();
            }
            break;
        case MailingComponent.TYPE_THUMBMAIL_IMAGE:
            if (comp.getBinaryBlock() != null) {
                res.setContentType(comp.getMimeType());
                out = res.getOutputStream();
                out.write(comp.getBinaryBlock());
                out.flush();
                out.close();
            }
            break;
        case MailingComponent.TYPE_ATTACHMENT:
        case MailingComponent.TYPE_PERSONALIZED_ATTACHMENT:
            res.setHeader("Content-Disposition", "attachment; filename=" + comp.getComponentName() + ";");
            out = res.getOutputStream();
            ApplicationContext applicationContext = WebApplicationContextUtils
                    .getWebApplicationContext(getServletContext());
            Preview preview = ((PreviewFactory) applicationContext.getBean("PreviewFactory")).createPreview();

            byte[] attachment = null;
            int mailingID = comp.getMailingID();

            if (comp.getType() == MailingComponent.TYPE_PERSONALIZED_ATTACHMENT) {
                Page page = null;
                if (customerID == 0) { // no customerID is available, take the 1st available test recipient
                    RecipientDao recipientDao = (RecipientDao) applicationContext.getBean("RecipientDao");
                    Map<Integer, String> recipientList = recipientDao
                            .getAdminAndTestRecipientsDescription(comp.getCompanyID(), mailingID);
                    customerID = recipientList.keySet().iterator().next();
                }
                page = preview.makePreview(mailingID, customerID, false);
                attachment = page.getAttachment(comp.getComponentName());

            } else {
                attachment = comp.getBinaryBlock();
            }

            len = attachment.length;
            res.setContentLength((int) len);
            out.write(attachment);
            out.flush();
            out.close();
            break;
        }
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.teacher.onlineTests.TestsManagementAction.java

public ActionForward downloadTestMarks(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws FenixActionException {
    final String distributedTestCode = getStringFromRequest(request, "distributedTestCode");
    String result = null;// w  ww . ja v  a  2 s .c o  m
    try {
        if (distributedTestCode != null) {
            result = ReadDistributedTestMarksToString.runReadDistributedTestMarksToString(
                    getExecutionCourse(request).getExternalId(), distributedTestCode);
        } else {
            result = ReadDistributedTestMarksToString.runReadDistributedTestMarksToString(
                    getExecutionCourse(request).getExternalId(),
                    request.getParameterValues("distributedTestCodes"));
        }
    } catch (FenixServiceException e) {
        throw new FenixActionException(e);
    }
    try {
        ServletOutputStream writer = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment; filename=pauta.xls");
        writer.print(result);
        writer.flush();
        response.flushBuffer();
    } catch (IOException e) {
        throw new FenixActionException();
    }
    return null;
}

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

/**
 * Returns the survey logo image binary  
 * @param departmentId//from  w  ww  .  ja va  2 s  . c o m
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/qr/{id}", produces = "text/html")
public void getSurveyQRCode(@PathVariable("id") Long surveyDefinitionId, Model uiModel, Principal principal,
        HttpServletRequest httpServletRequest, HttpServletResponse response) {
    try {
        uiModel.asMap().clear();
        User user = userService.user_findByLogin(principal.getName());
        //Check if the user is authorized
        if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            throw (new RuntimeException("Unauthorized access to logo"));
        }

        SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(surveyDefinitionId);
        //String surveyLink =messageSource.getMessage(EXTERNAL_SITE_BASE_URL, null, LocaleContextHolder.getLocale());
        String surveyLink = externalBaseUrl;
        if (surveyDefinition.getIsPublic()) {
            if (surveyLink.endsWith("/")) {
                surveyLink = surveyLink + "open/" + surveyDefinitionId + "?list";
            } else {
                surveyLink = surveyLink + "/open/" + surveyDefinitionId + "?list";
            }
        } else {
            if (surveyLink.endsWith("/")) {
                surveyLink = surveyLink + "private/" + surveyDefinitionId + "?list";
            } else {
                surveyLink = surveyLink + "/private/" + surveyDefinitionId + "?list";
            }
        }

        response.setContentType("image/png");
        ServletOutputStream servletOutputStream = response.getOutputStream();

        QRCodeWriter writer = new QRCodeWriter();
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = writer.encode(surveyLink, BarcodeFormat.QR_CODE, 600, 600);
            MatrixToImageWriter.writeToStream(bitMatrix, "png", servletOutputStream);

        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        servletOutputStream.flush();

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

From source file:org.openmrs.module.pmtct.util.FileExporter.java

/**
 * Auto generated method comment//from www  . j av  a  2 s. c  om
 * 
 * @param request
 * @param response
 * @param patientList
 * @param filename
 * @param title
 * @throws Exception
 */
public void exportToCSVFile(HttpServletRequest request, HttpServletResponse response, List<Object> patientList,
        String filename, String title) throws Exception {
    ServletOutputStream outputStream = null;
    try {
        outputStream = response.getOutputStream();
        Patient p;
        PatientService ps = Context.getPatientService();

        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        outputStream.println("" + title);
        outputStream.println("Number of Patients: " + patientList.size());
        outputStream.println();
        outputStream.println("No.,Identifier, Names, Gender, BirthDay, Enrollment Date, HIV Status");
        outputStream.println();

        int ids = 0;

        for (Object patient : patientList) {
            Object[] o = (Object[]) patient;
            p = ps.getPatient(Integer.parseInt(o[0].toString()));
            ids += 1;
            outputStream.println(ids + "," + p.getActiveIdentifiers().get(0).getIdentifier() + ","
                    + p.getPersonName() + "," + p.getGender() + "," + sdf.format(p.getBirthdate()) + ","
                    + o[3].toString() + ","
                    + pmtctTag.lastObsValueByConceptId(p.getPatientId(), PMTCTConstants.RESULT_OF_HIV_TEST));
        }

        outputStream.flush();
    } catch (Exception e) {
        log.error(e.getMessage());
    } finally {
        if (null != outputStream)
            outputStream.close();
    }
}