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:it.openprj.jValidator.spring.ExtraCheckCustomCodeValidator.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String code = request.getParameter("value");
    String name = request.getParameter("name");
    String addReq = request.getParameter("addReq");

    //TODO: take the result message from "locale"
    String result = null;/*  w  w w  .  ja  va 2 s .  co m*/
    ObjectMapper mapper = new ObjectMapper();
    ServletOutputStream out = null;
    response.setContentType("application/json");
    out = response.getOutputStream();
    if (StringUtils.isEmpty(code) || StringUtils.isEmpty(name)) {
        result = I18n.getMessage("error.extracheck.invaliddata");
    } else {
        name = name.trim();
        if (addReq.equalsIgnoreCase("true")) {
            ReadList list = checksTypeDao.findCustomCodeByName(name);
            if (list != null && CollectionUtils.isNotEmpty(list.getResults())) {
                result = I18n.getMessage("error.extracheck.name.alreadyexist");
                out.write(mapper.writeValueAsBytes(result));
                out.flush();
                out.close();
                return null;
            }
        }
        try {
            File sourceDir = new File(System.getProperty("java.io.tmpdir"), "jValidator/src");
            sourceDir.mkdirs();
            String classNamePack = name.replace('.', File.separatorChar);
            String srcFilePath = sourceDir + "" + File.separatorChar + classNamePack + ".java";
            File sourceFile = new File(srcFilePath);
            if (sourceFile.exists()) {
                sourceFile.delete();
            }
            FileUtils.writeStringToFile(new File(srcFilePath), code);
            DynamicClassLoader dynacode = DynamicClassLoader.getInstance();
            dynacode.addSourceDir(sourceDir);
            CustomCodeValidator customCodeValidator = (CustomCodeValidator) dynacode
                    .newProxyInstance(CustomCodeValidator.class, name);
            boolean isValid = false;
            if (customCodeValidator != null) {
                Class clazz = dynacode.getLoadedClass(name);
                if (clazz != null) {
                    Class[] interfaces = clazz.getInterfaces();
                    if (ArrayUtils.isNotEmpty(interfaces)) {
                        for (Class clz : interfaces) {
                            if ((clz.getName().equalsIgnoreCase(
                                    "it.openprj.jValidator.utils.validation.SingleValidation"))) {
                                isValid = true;
                            }
                        }
                    }
                }
            }
            if (isValid) {
                result = "Success";
            } else {
                result = I18n.getMessage("error.extracheck.wrongimpl");
            }
        } catch (Exception e) {
            result = "Failed. Reason:" + e.getMessage();
        }
    }
    out.write(mapper.writeValueAsBytes(result));
    out.flush();
    out.close();
    return null;
}

From source file:org.jahia.bin.DocumentConverter.java

private ModelAndView handlePost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileUpload fu = new FileUpload(request, settingsBean.getTmpContentDiskPath(), Integer.MAX_VALUE);
    if (fu.getFileItems().size() == 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No file was submitted");
        return null;
    }// ww  w .  j a v  a  2 s. com

    // take the first one
    DiskFileItem inputFile = fu.getFileItems().values().iterator().next();
    InputStream stream = null;
    String returnedMimeType = fu.getParameterValues("mimeType") != null ? fu.getParameterValues("mimeType")[0]
            : null;
    if (returnedMimeType == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing required parameter mimeType");
        return null;
    }

    try {
        ServletOutputStream outputStream = response.getOutputStream();

        stream = inputFile.getInputStream();
        // return a file
        response.setContentType(returnedMimeType);
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + FilenameUtils.getBaseName(inputFile.getName()) + "."
                        + converterService.getExtension(returnedMimeType) + "\"");

        converterService.convert(stream, inputFile.getContentType(), outputStream, returnedMimeType);

        try {
            outputStream.flush();
        } finally {
            outputStream.close();
        }
    } catch (Exception e) {
        logger.error(
                "Error converting uploaded file " + inputFile.getFieldName() + ". Cause: " + e.getMessage(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Exception occurred: " + e.getMessage());
    } finally {
        IOUtils.closeQuietly(stream);
        fu.disposeItems();
    }

    return null;
}

From source file:org.exist.webstart.JnlpWriter.java

/**
 * Send JAR or JAR.PACK.GZ file to end user.
 *
 * @param filename Name of JAR file/*from   w  w w  . ja  v a2s.co  m*/
 * @param response Object for writing to end user.
 * @throws java.io.IOException
 */
void sendJar(JnlpJarFiles jnlpFiles, String filename, HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    logger.debug("Send jar file " + filename);

    final File localFile = jnlpFiles.getJarFile(filename);
    if (localFile == null || !localFile.exists()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "Jar file '" + filename + "' not found.");
        return;
    }

    logger.debug("Actual file " + localFile.getAbsolutePath());

    if (localFile.getName().endsWith(".jar")) {
        //response.setHeader(CONTENT_ENCODING, JAR_MIME_TYPE);
        response.setContentType(JAR_MIME_TYPE);

    } else if (localFile.getName().endsWith(".jar.pack.gz")) {
        response.setHeader(CONTENT_ENCODING, PACK200_GZIP_ENCODING);
        response.setContentType(PACK_MIME_TYPE);
    }

    // It is very improbable that a 64 bit jar is needed, but
    // it is better to be ready
    // response.setContentLength(Integer.parseInt(Long.toString(localFile.length())));
    response.setHeader("Content-Length", Long.toString(localFile.length()));
    response.setDateHeader("Last-Modified", localFile.lastModified());

    final FileInputStream fis = new FileInputStream(localFile);
    final ServletOutputStream os = response.getOutputStream();

    try {
        // Transfer bytes from in to out
        final byte[] buf = new byte[4096];
        int len;
        while ((len = fis.read(buf)) > 0) {
            os.write(buf, 0, len);
        }

    } catch (final IllegalStateException ex) {
        logger.debug(ex.getMessage());

    } catch (final IOException ex) {
        logger.debug("Ignore IOException for '" + filename + "'");
    }

    os.flush();
    os.close();
    fis.close();
}

From source file:org.gbif.portal.web.controller.download.DownloadController.java

/**
 * Download if file exists, otherwise redirect to link expired view.
 * /*from   w w w  . ja va 2  s. com*/
 * @param response
 * @param file
 * @return
 * @throws FileNotFoundException
 * @throws IOException
 */
private ModelAndView downloadIfFileExists(HttpServletRequest request, HttpServletResponse response, File file)
        throws FileNotFoundException, IOException {

    try {
        if (file.exists()) {
            FileInputStream fInput = new FileInputStream(file);
            String contentTypeToUse = ServletRequestUtils.getStringParameter(request, "contentType",
                    contentType);
            response.setContentType(contentTypeToUse);
            if (setContentDisposition) {
                response.setHeader("Content-Disposition", "attachment; " + file.getName());
            }
            ServletOutputStream sOut = response.getOutputStream();
            response.setContentLength((int) file.length());
            byte[] buf = new byte[1024];
            int len;
            while ((len = fInput.read(buf)) > 0) {
                sOut.write(buf, 0, len);
            }
            sOut.flush();
        } else {
            return new ModelAndView(expiredView);
        }
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage(), e);
        return new ModelAndView(expiredView);
    }
    return null;
}

From source file:com.pdfhow.diff.UploadServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request//from   ww w . j  a va2s  .co  m
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getParameter("getfile") != null && !request.getParameter("getfile").isEmpty()) {
        File file = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("getfile"));
        if (file.exists()) {
            int bytes = 0;
            ServletOutputStream op = response.getOutputStream();

            response.setContentType(getMimeType(file));
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");

            byte[] bbuf = new byte[1024];
            DataInputStream in = new DataInputStream(new FileInputStream(file));

            while ((in != null) && ((bytes = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, bytes);
            }

            in.close();
            op.flush();
            op.close();
        }
    } else if (request.getParameter("delfile") != null && !request.getParameter("delfile").isEmpty()) {
        File file = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("delfile"));
        if (file.exists()) {
            file.delete(); // TODO:check and report success
        }
    } else if (request.getParameter("getthumb") != null && !request.getParameter("getthumb").isEmpty()) {
        File file = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("getthumb"));
        if (file.exists()) {
            System.out.println(file.getAbsolutePath());
            String mimetype = getMimeType(file);
            if (mimetype.endsWith("png") || mimetype.endsWith("jpeg") || mimetype.endsWith("jpg")
                    || mimetype.endsWith("gif")) {
                BufferedImage im = ImageIO.read(file);
                if (im != null) {
                    BufferedImage thumb = Scalr.resize(im, 75);
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    if (mimetype.endsWith("png")) {
                        ImageIO.write(thumb, "PNG", os);
                        response.setContentType("image/png");
                    } else if (mimetype.endsWith("jpeg")) {
                        ImageIO.write(thumb, "jpg", os);
                        response.setContentType("image/jpeg");
                    } else if (mimetype.endsWith("jpg")) {
                        ImageIO.write(thumb, "jpg", os);
                        response.setContentType("image/jpeg");
                    } else {
                        ImageIO.write(thumb, "GIF", os);
                        response.setContentType("image/gif");
                    }
                    ServletOutputStream srvos = response.getOutputStream();
                    response.setContentLength(os.size());
                    response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
                    os.writeTo(srvos);
                    srvos.flush();
                    srvos.close();
                }
            }
        } // TODO: check and report success
    } else {
        PrintWriter writer = response.getWriter();
        writer.write("call POST with multipart form data");
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.directiveCouncil.SummariesControlAction.java

/**
 * Method responsible for exporting 'departmentSummaryResume' to excel file
 * /* www  . ja v a  2  s . c  o m*/
 * @param mapping
 * @param actionForm
 * @param request
 * @param response
 * @return
 * @throws IOException
 */
public ActionForward exportInfoToExcel(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    String departmentID = request.getParameter("departmentID");
    String executionSemesterID = request.getParameter("executionSemesterID");
    String categoryControl = request.getParameter("categoryControl");

    final ExecutionSemester executionSemester = FenixFramework.getDomainObject(executionSemesterID);
    final Department department = FenixFramework.getDomainObject(departmentID);
    SummaryControlCategory summaryControlCategory = null;
    String controlCategory = null;
    if (!StringUtils.isEmpty(categoryControl)) {
        summaryControlCategory = SummaryControlCategory.valueOf(categoryControl);
        controlCategory = BundleUtil.getString(Bundle.ENUMERATION, summaryControlCategory.toString());
    } else {
        controlCategory = "0-100";
    }

    DepartmentSummaryElement departmentSummaryResume = getDepartmentSummaryResume(executionSemester,
            department);
    departmentSummaryResume.setSummaryControlCategory(summaryControlCategory);

    if (departmentSummaryResume != null) {
        String sigla = departmentSummaryResume.getDepartment().getAcronym();
        DateTime dt = new DateTime();
        DateTimeFormatter fmt = DateTimeFormat.forPattern("dd-MM-yyyy");
        String date = fmt.print(dt);

        final String filename = BundleUtil.getString(Bundle.APPLICATION, "link.summaries.control")
                .replaceAll(" ", "_") + "_" + controlCategory + "_" + sigla + "_" + date + ".xls";

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment; filename=" + filename);
        ServletOutputStream writer = response.getOutputStream();
        exportToXls(departmentSummaryResume, departmentSummaryResume.getDepartment(), executionSemester,
                writer);
        writer.flush();
        response.flushBuffer();
    }

    return null;
}

From source file:ispyb.client.common.shipping.UploadShipmentAction.java

/**
 * DownloadFile/*from   w w  w .  j a  va2 s .  c o  m*/
 * 
 * @param mapping
 * @param actForm
 * @param request
 * @param response
 * @return
 */
public ActionForward DownloadFile(ActionMapping mapping, ActionForm actForm, HttpServletRequest request,
        HttpServletResponse response) {

    ActionMessages errors = new ActionMessages();
    String fileType = request.getParameter(Constants.TEMPLATE_FILE_TYPE);

    if (fileType == null)
        fileType = this.mFileType;
    try {
        String targetUpload = new String("");
        String attachmentFilename = new String("");
        if (fileType.equals(Constants.TEMPLATE_FILE_TYPE_TEMPLATE)) {
            targetUpload = Constants.TEMPLATE_RELATIVE_PATH;
            targetUpload = request.getRealPath(targetUpload);
            attachmentFilename = Constants.TEMPLATE_XLS_FILENAME;
        }
        if (fileType.equals(Constants.TEMPLATE_FILE_TYPE_POPULATED_TEMPLATE)) {
            targetUpload = PopulateTemplate(request, true, false, false, null, null, false, 0, false, 0);
            attachmentFilename = PopulateTemplate(request, false, true, false, null, null, false, 0, false, 0);
        }
        if (fileType.equals(Constants.TEMPLATE_FILE_TYPE_POPULATED_TEMPLATE_ADVANCED)) {
            targetUpload = PopulateTemplate(request, true, false, true, null, null, false, 0, false, 0);
            attachmentFilename = PopulateTemplate(request, false, true, true, null, null, false, 0, false, 0);
        }
        if (fileType.equals(Constants.TEMPLATE_FILE_TYPE_EXPORT_SHIPPING)) {
            targetUpload = PopulateTemplate(request, true, false, false, null, null, false, 0, false, 0);
            attachmentFilename = PopulateTemplate(request, false, true, false, null, null, false, 0, false, 0);
        }
        if (fileType.equals(Constants.TEMPLATE_FILE_TYPE_POPULATED_TEMPLATE_FROM_SHIPMENT)) {
            Integer _shippingId = Integer.decode(request.getParameter(Constants.SHIPPING_ID));
            int shippingId = (_shippingId != null) ? _shippingId.intValue() : 0;
            targetUpload = PopulateTemplate(request, true, false, false, null, null, false, 0, true,
                    shippingId);
            attachmentFilename = PopulateTemplate(request, false, true, false, null, null, false, 0, true,
                    shippingId);
        }

        try {

            byte[] imageBytes = FileUtil.readBytes(targetUpload);
            response.setContentLength(imageBytes.length);
            ServletOutputStream out = response.getOutputStream();
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "max-age=0");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);

            out.write(imageBytes);
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.toString()));
        LOG.error(e.toString());
        saveErrors(request, errors);
        return mapping.findForward("error");
    }

    return null;
}

From source file:com.jd.survey.web.survey.PrivateSurveyController.java

/**
 * Returns the survey logo image binary  
 * @param departmentId// ww w.  jav a  2 s.  c o m
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN", "ROLE_SURVEY_PARTICIPANT" })
@RequestMapping(value = "/logo/{id}", produces = "text/html")
public void getSurveyLogo(@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.userIsAuthorizedToCreateSurvey(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"));
        } else {
            SurveyDefinition surveyDefinition = surveySettingsService
                    .surveyDefinition_findById(surveyDefinitionId);
            //response.setContentType("image/png");
            ServletOutputStream servletOutputStream = response.getOutputStream();
            servletOutputStream.write(surveyDefinition.getLogo());
            servletOutputStream.flush();
        }

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

From source file:org.jamwiki.servlets.ImageServlet.java

/**
 * Serve a file from the filesystem.  This is less efficient than serving the file
 * directly via Tomcat or Apache, but allows files to be stored outside of the
 * webapp and thus keeps wiki data (files) separate from application code.
 *///w  w w  .  jav  a2s.c  o  m
private void streamFileFromFileSystem(File file, HttpServletResponse response)
        throws ServletException, IOException {
    ServletOutputStream out = null;
    InputStream in = null;
    if (file.isDirectory() || !file.canRead()) {
        logger.debug("File does not exist: " + file.getAbsolutePath());
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    String mimeType = getServletContext().getMimeType(file.getAbsolutePath());
    if (mimeType == null) {
        mimeType = WikiFile.UNKNOWN_MIME_TYPE;
    }
    try {
        response.setContentType(mimeType);
        response.setContentLength((int) file.length());
        out = response.getOutputStream();
        in = new FileInputStream(file);
        IOUtils.copy(in, out);
        out.flush();
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:com.yunda.htmlsnap.web.api.HtmlSnapController.java

@RequestMapping(method = RequestMethod.GET)
public void snap(@RequestParam("htmlUrl") String htmlUrl, @RequestParam("imgType") String imgType,
        HttpServletRequest request, HttpServletResponse response) {
    logger.info("?:" + htmlUrl);
    //JavaHost.printAllVirtualDns();
    response.setContentType("image/" + imgType);
    response.setHeader("Content-Type", "image/" + imgType);
    boolean flag = false;
    ServletOutputStream sos = null;
    if (StringUtils.isNotBlank(htmlUrl)) {
        BrowserService browserService = null;
        try {/*  w  ww . ja va 2s . co  m*/
            browserService = BrowserFactory.getBrowerService();
            sos = response.getOutputStream();
            flag = browserService.generatePng(URLDecoder.decode(htmlUrl, "UTF-8"), sos, imgType);
        } catch (IOException e) {
            logger.error("??:" + e);
        } finally {
            BrowserFactory.recycleService(browserService);
        }
    }
    logger.info("?" + flag);
    if (!flag) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    if (null != sos) {
        try {
            sos.flush();
            sos.close();
        } catch (IOException e1) {
            logger.error("?", e1);
        }
    }
}