Example usage for javax.servlet ServletOutputStream close

List of usage examples for javax.servlet ServletOutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with this stream.

Usage

From source file:org.codelabor.system.file.web.spring.controller.FileController.java

@RequestMapping("/download")
public void download(@RequestHeader("User-Agent") String userAgent, @RequestParam("fileId") String fileId,
        HttpServletResponse response) throws Exception {
    FileDTO fileDTO = fileManager.selectFileByFileId(fileId);
    logger.debug("fileDTO: {}", fileDTO);

    String repositoryPath = fileDTO.getRepositoryPath();
    String uniqueFilename = fileDTO.getUniqueFilename();
    String realFilename = fileDTO.getRealFilename();
    InputStream inputStream = null;

    StringBuilder sb = new StringBuilder();
    if (StringUtils.isNotEmpty(repositoryPath)) {
        // FILE_SYSTEM
        sb.append(repositoryPath);/*  w  w  w  .ja  va2 s .  c  om*/
        if (!repositoryPath.endsWith(File.separator)) {
            sb.append(File.separator);
        }
        sb.append(uniqueFilename);
        File file = new File(sb.toString());
        inputStream = new FileInputStream(file);
    } else {
        // DATABASE
        byte[] bytes = new byte[] {};
        if (fileDTO.getFileSize() > 0) {
            bytes = fileDTO.getBytes();
        }
        inputStream = new ByteArrayInputStream(bytes);

    }
    // set response contenttype, header
    String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8");
    logger.debug("realFilename: {}", realFilename);
    logger.debug("encodedRealFilename: {}", encodedRealFilename);

    response.setContentType(org.codelabor.system.file.FileConstants.CONTENT_TYPE);
    sb.setLength(0);
    if (userAgent.indexOf("MSIE5.5") > -1) {
        sb.append("filename=");
    } else {
        sb.append("attachment; filename=");
    }
    sb.append(encodedRealFilename);
    response.setHeader(HttpResponseHeaderConstants.CONTENT_DISPOSITION, sb.toString());
    logger.debug("header: {}", sb.toString());
    logger.debug("character encoding: {}", response.getCharacterEncoding());
    logger.debug("content type: {}", response.getContentType());
    logger.debug("bufferSize: {}", response.getBufferSize());
    logger.debug("locale: {}", response.getLocale());

    BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream);
    ServletOutputStream servletOutputStream = response.getOutputStream();
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream);
    int bytesRead;
    byte buffer[] = new byte[2048];
    while ((bytesRead = bufferdInputStream.read(buffer)) != -1) {
        bufferedOutputStream.write(buffer, 0, bytesRead);
    }
    // flush stream
    bufferedOutputStream.flush();

    // close stream
    inputStream.close();
    bufferdInputStream.close();
    servletOutputStream.close();
    bufferedOutputStream.close();
}

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  .  j  a  va 2 s  .c  om*/
    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:ai.h2o.servicebuilder.MakeWarServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Long startTime = System.currentTimeMillis();
    File tmpDir = null;/*from  w  w w .  ja  v a  2 s . co  m*/
    try {
        //create temp directory
        tmpDir = createTempDirectory("makeWar");
        logger.info("tmpDir {}", tmpDir);

        //  create output directories
        File webInfDir = new File(tmpDir.getPath(), "WEB-INF");
        if (!webInfDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF)");
        File outDir = new File(webInfDir.getPath(), "classes");
        if (!outDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF/classes)");
        File libDir = new File(webInfDir.getPath(), "lib");
        if (!libDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF/lib)");

        // get input files
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        String pojofile = null;
        String jarfile = null;
        String prejarfile = null;
        String deepwaterjarfile = null;
        String rawfile = null;
        String predictorClassName = null;
        String transformerClassName = null;
        ArrayList<String> pojos = new ArrayList<String>();
        ArrayList<String> rawfiles = new ArrayList<String>();
        for (FileItem i : items) {
            String field = i.getFieldName();
            String filename = i.getName();
            if (filename != null && filename.length() > 0) { // file fields
                if (field.equals("pojo")) {
                    pojofile = filename;
                    pojos.add(pojofile);
                    predictorClassName = filename.replace(".java", "");
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename));
                    logger.info("added pojo model {}", filename);
                }
                if (field.equals("jar")) {
                    jarfile = "WEB-INF" + File.separator + "lib" + File.separator + filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename));
                }
                if (field.equals("deepwater")) {
                    deepwaterjarfile = "WEB-INF" + File.separator + "lib" + File.separator + filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename));
                }
                if (field.equals("prejar")) {
                    prejarfile = "WEB-INF" + File.separator + "lib" + File.separator + filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename));
                }
                if (field.equals("mojo")) { // a raw model zip file, a mojo file
                    rawfile = filename;
                    rawfiles.add(rawfile);
                    predictorClassName = filename.replace(".zip", "");
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename));
                    logger.info("added mojo model {}", filename);
                }
            } else { // form text field
                if (field.equals("preclass")) {
                    transformerClassName = i.getString();
                }
            }
        }
        logger.debug("genmodeljar {}  deepwaterjar {}  pojo {}  raw {}", jarfile, deepwaterjarfile, pojofile,
                rawfile);
        if ((pojofile == null || jarfile == null) && (rawfile == null || jarfile == null))
            throw new Exception("need either pojo and genmodel jar, or raw file and genmodel jar ");

        logger.info("prejar {}  preclass {}", prejarfile, transformerClassName);
        if (prejarfile != null && transformerClassName == null
                || prejarfile == null && transformerClassName != null)
            throw new Exception("need both prejar and preclass");

        if (pojofile != null) {
            // Compile the pojo
            String jarfiles = jarfile;
            if (deepwaterjarfile != null)
                jarfiles += ":" + deepwaterjarfile;
            runCmd(tmpDir,
                    Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION,
                            "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp", jarfiles, "-d", outDir.getPath(),
                            pojofile),
                    "Compilation of pojo failed");
            logger.info("compiled pojo {}", pojofile);
        }

        if (servletPath == null)
            throw new Exception("servletPath is null");

        FileUtils.copyDirectoryToDirectory(new File(servletPath, "extra"), tmpDir);
        String extraPath = "extra" + File.separator;
        String webInfPath = extraPath + File.separator + "WEB-INF" + File.separator;
        String srcPath = extraPath + "src" + File.separator;

        if (transformerClassName == null)
            copyExtraFile(servletPath, extraPath, tmpDir, "index.html", "index.html");
        else
            copyExtraFile(servletPath, extraPath, tmpDir, "jarindex.html", "index.html");
        copyExtraFile(servletPath, extraPath, tmpDir, "jquery.js", "jquery.js");
        copyExtraFile(servletPath, extraPath, tmpDir, "predict.js", "predict.js");
        copyExtraFile(servletPath, extraPath, tmpDir, "custom.css", "custom.css");
        copyExtraFile(servletPath, webInfPath, webInfDir, "web-predict.xml", "web.xml");
        FileUtils.copyDirectoryToDirectory(new File(servletPath, webInfPath + "lib"), webInfDir);
        FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "bootstrap"), tmpDir);
        FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "fonts"), tmpDir);

        // change the class name in the predictor template file to the predictor we have
        String replaceTransform;
        if (transformerClassName == null)
            replaceTransform = "null";
        else
            replaceTransform = "new " + transformerClassName + "()";

        String modelCode = null;
        if (!pojos.isEmpty()) {
            FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), pojos);
            modelCode = "null";
        } else if (!rawfiles.isEmpty()) {
            FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), rawfiles);
            modelCode = "MojoModel.load(fileName)";
        }
        InstantiateJavaTemplateFile(tmpDir, modelCode, predictorClassName, replaceTransform, null,
                srcPath + "ServletUtil-TEMPLATE.java", "ServletUtil.java");

        copyExtraFile(servletPath, srcPath, tmpDir, "PredictServlet.java", "PredictServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "PredictBinaryServlet.java", "PredictBinaryServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "InfoServlet.java", "InfoServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "StatsServlet.java", "StatsServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "PingServlet.java", "PingServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "Transform.java", "Transform.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "Logging.java", "Logging.java");

        // compile extra
        List<String> cmd = Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source",
                JAVA_TARGET_VERSION, "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp",
                "WEB-INF/lib/*:WEB-INF/classes:extra/WEB-INF/lib/*", "-d", outDir.getPath(),
                "PredictServlet.java", "PredictBinaryServlet.java", "InfoServlet.java", "StatsServlet.java",
                "ServletUtil.java", "PingServlet.java", "Transform.java", "Logging.java");
        runCmd(tmpDir, cmd, "Compilation of extra failed");

        // create the war jar file
        Collection<File> filesc = FileUtils.listFilesAndDirs(webInfDir, TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
        filesc.add(new File(tmpDir, "index.html"));
        filesc.add(new File(tmpDir, "jquery.js"));
        filesc.add(new File(tmpDir, "predict.js"));
        filesc.add(new File(tmpDir, "custom.css"));
        filesc.add(new File(tmpDir, "modelnames.txt"));
        for (String m : pojos) {
            filesc.add(new File(tmpDir, m));
        }
        for (String m : rawfiles) {
            filesc.add(new File(tmpDir, m));
        }
        Collection<File> dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "bootstrap"),
                TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
        filesc.addAll(dirc);
        dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "fonts"), TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
        filesc.addAll(dirc);

        File[] files = filesc.toArray(new File[] {});
        if (files.length == 0)
            throw new Exception("Can't list compiler output files (out)");

        byte[] resjar = createJarArchiveByteArray(files, tmpDir.getPath() + File.separator);
        if (resjar == null)
            throw new Exception("Can't create war of compiler output");
        logger.info("war created from {} files, size {}", files.length, resjar.length);

        // send jar back
        ServletOutputStream sout = response.getOutputStream();
        response.setContentType("application/octet-stream");
        String outputFilename = predictorClassName.length() > 0 ? predictorClassName : "h2o-predictor";
        response.setHeader("Content-disposition", "attachment; filename=" + outputFilename + ".war");
        response.setContentLength(resjar.length);
        sout.write(resjar);
        sout.close();
        response.setStatus(HttpServletResponse.SC_OK);

        Long elapsedMs = System.currentTimeMillis() - startTime;
        logger.info("Done war creation in {} ms", elapsedMs);
    } catch (Exception e) {
        logger.error("doPost failed ", e);
        // send the error message back
        String message = e.getMessage();
        if (message == null)
            message = "no message";
        logger.error(message);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().write(message);
        response.getWriter().write(Arrays.toString(e.getStackTrace()));
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
        // if the temp directory is still there we delete it
        if (tmpDir != null && tmpDir.exists()) {
            try {
                FileUtils.deleteDirectory(tmpDir);
            } catch (IOException e) {
                logger.error("Can't delete tmp directory");
            }
        }
    }

}

From source file:org.freeeed.ep.web.controller.FileDownloadController.java

@Override
public ModelAndView execute() {
    String result = (String) valueStack.get("file");
    String resultFile = workDir + File.separator + result;

    File toDownload = new File(resultFile);

    try {//  w  w w .j  av a2  s.c  o  m
        int length = 0;
        ServletOutputStream outStream = response.getOutputStream();
        String mimetype = "application/octet-stream";

        response.setContentType(mimetype);
        response.setContentLength((int) toDownload.length());
        String fileName = toDownload.getName();

        // sets HTTP header
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

        byte[] byteBuffer = new byte[1024];
        DataInputStream in = new DataInputStream(new FileInputStream(toDownload));

        // reads the file's bytes and writes them to the response stream
        while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
            outStream.write(byteBuffer, 0, length);
        }

        in.close();
        outStream.close();
    } catch (Exception e) {
        log.error("Problem sending cotent", e);
        valueStack.put("error", true);
    }

    return new ModelAndView(WebConstants.DOWNLOAD_RESULT);
}

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

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request// ww  w .  j  a va2  s .  com
 *            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:edu.cornell.mannlib.vitro.webapp.filestorage.serving.FileServingServlet.java

@Override
protected void doGet(HttpServletRequest rawRequest, HttpServletResponse response)
        throws ServletException, IOException {
    VitroRequest request = new VitroRequest(rawRequest);

    // Use the alias URL to get the URI of the bytestream object.
    String path = request.getServletPath() + request.getPathInfo();
    log.debug("Path is '" + path + "'");

    /*/*from   w w w  .  j a va 2 s.  c  o  m*/
     * Get the mime type and an InputStream from the file. If we can't, use
     * the dummy image file instead.
     */
    InputStream in;
    String mimeType = null;
    try {
        FileInfo fileInfo = figureFileInfo(request.getWebappDaoFactory(), path);
        mimeType = fileInfo.getMimeType();

        String actualFilename = findAndValidateFilename(fileInfo, path);

        in = openImageInputStream(fileInfo, actualFilename);
    } catch (FileServingException e) {
        log.info("Failed to serve the file at '" + path + "' -- " + e);
        in = openMissingLinkImage(request);
        mimeType = "image/png";
    } catch (Exception e) {
        log.warn("Failed to serve the file at '" + path + "' -- " + e);
        in = openMissingLinkImage(request);
        mimeType = "image/png";
    }

    /*
     * Everything is ready. Set the status and the content type, and send
     * the image bytes.
     */
    response.setStatus(SC_OK);

    if (mimeType != null) {
        response.setContentType(mimeType);
    }

    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();
        byte[] buffer = new byte[8192];
        int howMany;
        while (-1 != (howMany = in.read(buffer))) {
            out.write(buffer, 0, howMany);
        }
    } catch (IOException e) {
        log.warn("Failed to serve the file", e);
    } finally {
        try {
            in.close();
        } catch (Exception e) {
            log.warn("Serving " + request.getRequestURI() + ". Failed to close input stream.", e);
        }
        if (out != null) {
            try {
                out.close();
            } catch (Exception e) {
                log.warn("Serving " + request.getRequestURI() + ". Failed to close output stream.", e);
            }
        }
    }
}

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

/**
 * DownloadFile/*from  w w  w.  j  a va  2 s. co  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:org.rhq.gui.content.ContentHTTPServlet.java

protected boolean writeDistributionFileBits(HttpServletRequest request, HttpServletResponse response,
        DistributionFile distFile) throws IOException {

    try {//w ww .j  a v  a2 s .  c o  m
        ServletOutputStream output = response.getOutputStream();
        response.setContentType("application/octet-stream");
        contentSourceMgr.outputDistributionFileBits(distFile, output);
        output.flush();
        output.close();
    } catch (IllegalStateException e) {
        log.error(e);
        return false;
    } catch (IOException e) {
        log.error(e);
        return false;
    }
    return true;
}

From source file:it.cnr.icar.eric.server.interfaces.rest.URLHandler.java

void writeRepositoryItem(ExtrinsicObjectType eo)
        throws IOException, RegistryException, ObjectNotFoundException {
    String id = eo.getId();/*from  ww  w .j av a  2 s. c  om*/
    ServerRequestContext context = new ServerRequestContext("URLHandler.writeRepositoryItem", null);

    try {
        RepositoryItem ri = QueryManagerFactory.getInstance().getQueryManager().getRepositoryItem(context, id);

        if (ri == null) {
            throw new ObjectNotFoundException(id,
                    ServerResourceBundle.getInstance().getString("message.repositoryItem"));
        } else {
            response.setContentType(eo.getMimeType());

            DataHandler dataHandler = ri.getDataHandler();
            ServletOutputStream sout = response.getOutputStream();
            InputStream fStream = dataHandler.getInputStream();
            int bytesSize = fStream.available();
            byte[] b = new byte[bytesSize];
            fStream.read(b);
            sout.write(b);
            sout.close();
        }
        context.commit();
        context = null;
    } finally {
        if (context != null) {
            context.rollback();
        }

    }
}

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 w w. ja  va2s . 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);
        }
    }
}