Example usage for javax.servlet ServletOutputStream write

List of usage examples for javax.servlet ServletOutputStream write

Introduction

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

Prototype

public void write(byte b[], int off, int len) throws IOException 

Source Link

Document

Writes len bytes from the specified byte array starting at offset off to this output stream.

Usage

From source file:edu.umn.cs.spatialHadoop.visualization.HadoopvizServer.java

/**
 * This method will handle each time a file need to be fetched from HDFS.
 * //from   www.  j a  v  a2  s.c o m
 * @param request
 * @param response
 */
private void handleHDFSFetch(HttpServletRequest request, HttpServletResponse response) {
    try {
        FileSystem fs = outputPath.getFileSystem(commonParams);
        String path = request.getRequestURI().replace("/hdfs", "");
        Path filePath = new Path(path);

        LOG.info("Fetching from " + path);

        FSDataInputStream resource;

        resource = fs.open(filePath);

        if (resource == null) {
            reportError(response, "Cannot load resource '" + filePath + "'", null);
            return;
        }
        byte[] buffer = new byte[1024 * 1024];
        ServletOutputStream outResponse = response.getOutputStream();
        int size;
        while ((size = resource.read(buffer)) != -1) {
            outResponse.write(buffer, 0, size);
        }
        resource.close();
        outResponse.close();
        response.setStatus(HttpServletResponse.SC_OK);
        if (filePath.toString().endsWith("png")) {
            response.setContentType("image/png");
        }
    } catch (Exception e) {
        System.out.println("error happened");
        e.printStackTrace();
        response.setContentType("text/plain;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

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

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request//w w w .j  a v a  2s. 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:org.efs.openreports.services.servlet.ReportServiceServlet.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*w w  w .jav a2 s. c  om*/
        ServletReportServiceInput reportInput = buildReportServiceInput(request);
        reportInput.setParameterMap(request.getParameterMap());

        ReportEngineOutput reportOutput = reportService.generateReport(reportInput);

        if (reportOutput instanceof QueryEngineOutput) {
            QueryEngineOutput queryReport = (QueryEngineOutput) reportOutput;

            request.getSession().setAttribute("properties", queryReport.getProperties());
            request.getSession().setAttribute("results", queryReport.getResults());
            request.getSession().setAttribute("reportName",
                    StringUtils.deleteWhitespace(reportInput.getReportName()));

            response.sendRedirect("report-viewer/query-report.jsp");

            //getServletContext().getRequestDispatcher("/report-viewer/query-report.jsp").forward(request, response);

            return;
        }

        ServletOutputStream out = response.getOutputStream();

        if (reportOutput.getContent() != null) {
            if (reportInput.getExportType() != ReportEngine.EXPORT_HTML) {
                response.setContentType(reportOutput.getContentType());
                response.setContentLength(reportOutput.getContent().length);
                response.setHeader("Content-disposition",
                        "inline; filename=" + StringUtils.deleteWhitespace(reportInput.getReportName())
                                + reportOutput.getContentExtension());
            }

            out.write(reportOutput.getContent(), 0, reportOutput.getContent().length);
        } else {
            out.write(reportOutput.getContentMessage().getBytes());
        }

        out.flush();
        out.close();
    } catch (Exception e) {
        response.getOutputStream().write(e.toString().getBytes());
    }
}

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 ww .  j a  va  2 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:org.gbif.portal.web.controller.download.DownloadController.java

/**
 * Download if file exists, otherwise redirect to link expired view.
 * /*ww  w  .  j a  v a2 s . c om*/
 * @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.portfolio.data.attachment.XSLService.java

void RetrieveAnswer(HttpURLConnection connection, HttpServletResponse response, String referer)
        throws MalformedURLException, IOException {
    /// Receive answer
    InputStream in;/*from  w w  w.  j a  va2  s. c o m*/
    try {
        in = connection.getInputStream();
    } catch (Exception e) {
        System.out.println(e.toString());
        in = connection.getErrorStream();
    }

    String ref = null;
    if (referer != null) {
        int first = referer.indexOf('/', 7);
        int last = referer.lastIndexOf('/');
        ref = referer.substring(first, last);
    }

    response.setContentType(connection.getContentType());
    response.setStatus(connection.getResponseCode());
    response.setContentLength(connection.getContentLength());

    /// Transfer headers
    Map<String, List<String>> headers = connection.getHeaderFields();
    int size = headers.size();
    for (int i = 1; i < size; ++i) {
        String key = connection.getHeaderFieldKey(i);
        String value = connection.getHeaderField(i);
        //         response.setHeader(key, value);
        response.addHeader(key, value);
    }

    /// Deal with correct path with set cookie
    List<String> setValues = headers.get("Set-Cookie");
    if (setValues != null) {
        String setVal = setValues.get(0);
        int pathPlace = setVal.indexOf("Path=");
        if (pathPlace > 0) {
            setVal = setVal.substring(0, pathPlace + 5); // Some assumption, may break
            setVal = setVal + ref;

            response.setHeader("Set-Cookie", setVal);
        }
    }

    /// Write back data
    DataInputStream stream = new DataInputStream(in);
    byte[] buffer = new byte[1024];
    //       int size;
    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();
        while ((size = stream.read(buffer, 0, buffer.length)) != -1)
            out.write(buffer, 0, size);

    } catch (Exception e) {
        System.out.println(e.toString());
        System.out.println("Writing messed up!");
    } finally {
        in.close();
        out.flush(); // close() should flush already, but Tomcat 5.5 doesn't
        out.close();
    }
}

From source file:fr.insalyon.creatis.vip.core.server.rpc.GetFileServiceImpl.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//from  w w  w . j  a  va 2  s. c  o m
        User user = CoreDAOFactory.getDAOFactory().getUserDAO()
                .getUserBySession(req.getParameter(CoreConstants.COOKIES_SESSION));

        String filepath = req.getParameter("filepath");

        if (filepath != null && !filepath.isEmpty()) {

            File file = new File(Server.getInstance().getWorkflowsPath() + filepath);

            boolean isDir = false;
            if (file.isDirectory()) {
                String zipName = file.getAbsolutePath() + ".zip";
                FolderZipper.zipFolder(file.getAbsolutePath(), zipName);
                filepath = zipName;
                file = new File(zipName);
                isDir = true;
            }

            logger.info("(" + user.getEmail() + ") Downloading file '" + filepath + "'.");
            int length = 0;
            ServletOutputStream op = resp.getOutputStream();
            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType(file.getName());

            resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
            resp.setContentLength((int) file.length());
            resp.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

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

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

            in.close();
            op.flush();
            op.close();

            if (isDir) {
                FileUtils.deleteQuietly(file);
            }
        }

    } catch (DAOException ex) {
        throw new ServletException(ex);
    }
}

From source file:org.ff4j.web.AdministrationConsoleServlet.java

/**
 * Build Http response when invoking export features.
 * /*from   w  w  w. j a  v a2 s. c om*/
 * @param res
 *            http response
 * @throws IOException
 *             error when building response
 */
private void buildResponseForExportFeature(HttpServletResponse res) throws IOException {
    InputStream in = new FeatureXmlParser().exportFeatures(getFf4j().getStore().readAll());
    ServletOutputStream sos = null;
    try {
        sos = res.getOutputStream();
        res.setContentType("text/xml");
        res.setHeader("Content-Disposition", "attachment; filename=\"ff4j.xml\"");
        // res.setContentLength()
        byte[] bbuf = new byte[BUFFER_SIZE];
        int length = 0;
        while ((in != null) && (length != -1)) {
            length = in.read(bbuf);
            sos.write(bbuf, 0, length);
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (sos != null) {
            sos.flush();
            sos.close();
        }
    }
}

From source file:com.viewer.controller.ViewerController.java

@RequestMapping(value = "/GetFile")
@ResponseBody/*w  w  w .  ja va  2s  .  com*/
private void GetFile(@RequestParam String path, Boolean getPdf, Boolean useHtmlBasedEngine,
        Boolean supportPageRotation, HttpServletResponse response) throws Exception {

    File file = new File(path);

    String displayName = path;
    String nameWithoutExtension = removeExtention(path);
    Stream fileStream;
    File newFile = new File(nameWithoutExtension + ".pdf");

    displayName = newFile.getPath();

    PdfFileOptions options = new PdfFileOptions();
    options.setGuid(path);

    FileContainer pdfFileResponse = _htmlHandler.getPdfFile(options);

    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + displayName + "\"");
    InputStream fileIn = pdfFileResponse.getStream();
    ServletOutputStream out = response.getOutputStream();

    byte[] outputByte = new byte[4096];
    while (fileIn.read(outputByte, 0, 4096) != -1) {
        out.write(outputByte, 0, 4096);
    }
    fileIn.close();
    out.flush();
    out.close();

}

From source file:org.vasanti.controller.DropZoneFileUpload.java

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

    if (request.getParameter("getfile") != null && !request.getParameter("getfile").isEmpty()) {
        File file = new File(ImagefileUploadPath, 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);
            }/*  w  ww. j  a v  a2s .c  om*/

            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(ImagefileUploadPath, request.getParameter("getthumb"));
        if (file.exists()) {
            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");
    }
}