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:cpabe.controladores.UploadDecriptacaoServlet.java

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

    String fileName = request.getParameter("fileName");
    if (fileName == null || fileName.equals("")) {
        throw new ServletException("O nome do arquivo no pode ser null ou vazio.");
    }// w  w w.  j av  a2  s.  co  m
    File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName);
    if (!file.exists()) {
        throw new ServletException("O arquivo desejado no existe no Servidor.");
    }
    System.out.println("File location on server::" + file.getAbsolutePath());
    ServletContext ctx = getServletContext();
    InputStream fis = new FileInputStream(file);
    String mimeType = ctx.getMimeType(file.getAbsolutePath());
    response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
    response.setContentLength((int) file.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

    ServletOutputStream os = response.getOutputStream();
    byte[] bufferData = new byte[1024];
    int read = 0;
    while ((read = fis.read(bufferData)) != -1) {
        os.write(bufferData, 0, read);
    }
    os.flush();
    os.close();
    fis.close();
    System.out.println("File downloaded at client successfully");
}

From source file:com.Uploader.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*from w w  w  . j  av a  2s  .  c o m*/
 * @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 {
    //  processRequest(request, response);
    String fileName = request.getParameter("fileName");
    if (fileName == null || fileName.equals("")) {
        throw new ServletException("File Name can't be null or empty");
    }
    File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName);
    if (!file.exists()) {
        throw new ServletException("File doesn't exists on server.");
    }
    System.out.println("File location on server::" + file.getAbsolutePath());
    ServletContext ctx = getServletContext();
    InputStream fis = new FileInputStream(file);
    String mimeType = ctx.getMimeType(file.getAbsolutePath());
    response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
    response.setContentLength((int) file.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

    ServletOutputStream os = response.getOutputStream();
    byte[] bufferData = new byte[1024];
    int read = 0;
    while ((read = fis.read(bufferData)) != -1) {
        os.write(bufferData, 0, read);
    }
    os.flush();
    os.close();
    fis.close();
    System.out.println("File downloaded at client successfully");
}

From source file:com.smartgwt.extensions.fileuploader.server.DownloadServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response) {
    // url: /thinkspace/download/project/2/.....
    String path = request.getPathInfo();
    String[] items = path.split("/");
    if (items.length < 3 || !items[1].equals("project")) {
        // if no path info then nothing can be downloaded
        reportError(response);/*from   w  w w .j a  va 2s. com*/
        return;
    }
    InputStream in = null;
    try {
        int pid = Integer.parseInt(items[2]);
        /*           Project project = ProjectService.get().getProjectById(pid);
                   String contextName = project.getContext();
                 ProjectState state = (ProjectState) request.getSession().getAttribute(contextName);
                 if (state == null) {
                    // if no state then user has not authenticated
                    reportError(response);
                    return;
                 }
        */
        // only files in lib directories can be downloaded
        boolean hasPermission = false;
        for (int i = items.length - 1; i > 2; i--) {
            if (items[i].equals("lib")) {
                hasPermission = true;
                break;
            }
        }
        if (!hasPermission) {
            reportError(response);
            return;
        }
        /*          File f = state.getFileManager().getFile(path);
                  String type = ContentService.get().getContentType(path);
                  response.setContentType(type);
                  response.setContentLength((int)f.length());
                  response.setHeader("Content-Disposition", "inline; filename="+Util.encode(f.getName()));
                  response.setHeader("Last-Modified",hdf.format(new Date(f.lastModified())));
                  in = new BufferedInputStream(new FileInputStream(f));
        */ ServletOutputStream out = response.getOutputStream();
        byte[] buf = new byte[8192];
        int len = 0;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        out.close();
        out.flush();
    } catch (Exception e) {
        reportError(response);
        log.error(e);
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (Exception e) {
            }
        ;
    }
}

From source file:org.primeframework.mvc.action.result.StreamResult.java

/**
 * {@inheritDoc}/*from   w  w  w  . j a  v  a  2  s  .  c  om*/
 */
public void execute(Stream stream) throws IOException, ServletException {
    ActionInvocation current = actionInvocationStore.getCurrent();
    Object action = current.action;
    String property = stream.property();
    String length = expand(stream.length(), action, false);
    String name = expand(stream.name(), action, true);
    String type = expand(stream.type(), action, false);

    Object object = expressionEvaluator.getValue(property, action);
    if (object == null || !(object instanceof InputStream)) {
        throw new PrimeException("Invalid property [" + property + "] for Stream result. This "
                + "property returned null or an Object that is not an InputStream.");
    }

    response.setContentType(type);

    if (StringUtils.isNotBlank(length)) {
        response.setContentLength(Integer.parseInt(length));
    }

    if (StringUtils.isNotBlank(name)) {
        response.setHeader("Content-Disposition", "attachment; filename=\"" + name + "\"");
    }

    if (!isCurrentActionHeadRequest(current)) {
        InputStream is = (InputStream) object;
        ServletOutputStream sos = response.getOutputStream();
        try {
            // Then output the file
            byte[] b = new byte[8192];
            int len;
            while ((len = is.read(b)) != -1) {
                sos.write(b, 0, len);
            }
        } finally {
            sos.flush();
            sos.close();
        }
    }
}

From source file:org.intermine.web.struts.FileDownloadAction.java

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    //        String path = "WEB-INF/lib/";
    //        String fileName = "intermine-webservice-client.jar";

    try {/*from ww w.j  a v a 2s  . c o  m*/
        String path = request.getParameter("path");
        String fileName = request.getParameter("fileName");
        String mimeType = request.getParameter("mimeType");
        String mimeExtension = request.getParameter("mimeExtension");

        if (!fileIsPermitted(fileName)) {
            response.sendError(401);
            return null;
        }

        //          String contextPath = getServlet().getServletContext().getRealPath("/");
        //          String filePath = contextPath + path + fileName;
        //          File file = new File(filePath);
        //          FileOutputStream fos = new FileOutputStream(file);

        // Read the file into a input stream
        InputStream is = getServlet().getServletContext().getResourceAsStream(path + fileName);

        if (is == null) {
            response.sendError(404);
            return null;
        }

        // MIME type
        if (fileName.endsWith(mimeExtension)) {
            response.setContentType(mimeType);
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);
        }

        ServletOutputStream sos = response.getOutputStream();

        byte[] buff = new byte[2048];
        int bytesRead;

        while (-1 != (bytesRead = is.read(buff, 0, buff.length))) {
            sos.write(buff, 0, bytesRead);
        }

        is.close();
        sos.close();
    } catch (Exception e) {
        e.printStackTrace();
        recordError(new ActionMessage("api.fileDownloadFailed"), request);
        return mapping.findForward("api");
    }

    return null;
}

From source file:eu.europa.ejusticeportal.dss.controller.action.DownloadSignedPdf.java

/**
 * Writes the PDF document to the browser
 * @param sf the container//from ww w.  j a  v a2  s  .c  om
 * @param response the response
 * @throws IOException 
 */
private void writeRaw(SignedForm sf, HttpServletResponse response) throws IOException {

    InputStream is = new ByteArrayInputStream(sf.getDocument());
    ServletOutputStream outs = null;
    try {
        outs = response.getOutputStream();
        int r = 0;
        byte[] chunk = new byte[8192];
        while ((r = is.read(chunk)) != -1) {
            outs.write(chunk, 0, r);
        }
        outs.flush();
    } finally {
        IOUtils.closeQuietly(outs);
    }

}

From source file:com.arcadian.loginservlet.CourseContentServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getParameter("filename") != null) {
        String fileName = request.getParameter("filename");
        File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName);
        System.out.println("File location on server::" + file.getAbsolutePath());
        ServletContext ctx = getServletContext();
        InputStream fis = new FileInputStream(file);
        String mimeType = ctx.getMimeType(file.getAbsolutePath());
        System.out.println("mime type=" + mimeType);
        response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

        ServletOutputStream os = response.getOutputStream();
        byte[] bufferData = new byte[102400];
        int read = 0;
        while ((read = fis.read(bufferData)) != -1) {
            os.write(bufferData, 0, read);
        }//from   w w  w  . j av a2 s  .  c  om
        os.flush();
        os.close();
        fis.close();
        System.out.println("File downloaded at client successfully");
    }
    processRequest(request, response);
}

From source file:org.commoncrawl.service.listcrawler.ProxyServlet.java

private static void sendCrawlURLResponse(final HttpServletRequest req, final HttpServletResponse response,
        CrawlURL url, String renderAs, AsyncResponse responseObject, long requestStartTime) throws IOException {

    if (url.getLastAttemptResult() == CrawlURL.CrawlResult.SUCCESS) {

        // remove default headers ... 
        response.setHeader("Date", null);
        response.setHeader("Server", null);
        // set the result code ... 
        response.setStatus(200);/*from  www  .j  ava  2  s. com*/

        if (renderAs.equals(PROXY_RENDER_TYPE_TEXT)) {

            response.setHeader("content-type", "text/plain");

            // parse headers ... 
            NIOHttpHeaders headers = NIOHttpHeaders.parseHttpHeaders(url.getHeaders());

            PrintWriter writer = response.getWriter();

            writer.write(PROXY_HEADER_SOURCE + ":origin\n");
            writer.write(PROXY_HEADER_ORIG_STATUS + ":" + headers.getValue(0) + "\n");
            writer.write(PROXY_HEADER_TIMER + ":" + (System.currentTimeMillis() - requestStartTime) + "MS\n");
            writer.write(PROXY_HEADER_FINALURL + ":"
                    + (((url.getFlags() & CrawlURL.Flags.IsRedirected) != 0) ? url.getRedirectURL()
                            : url.getUrl())
                    + "\n");

            // and put then in a map ... 
            Map<String, List<String>> headerItems = NIOHttpHeaders.parseHttpHeaders(url.getHeaders())
                    .getHeaders();

            writer.write("content-length:" + Integer.toString(url.getContentRaw().getCount()) + "\n");

            // pull out content encoding if it is set ...
            String contentEncoding = headers.findValue("content-encoding");

            if (contentEncoding != null) {
                writer.write("content-encoding:" + contentEncoding + "\n");
            }

            String truncationFlags = "";
            if ((url.getFlags() & CrawlURL.Flags.TruncatedDuringDownload) != 0) {
                truncationFlags += ArcFileItem.Flags.toString(ArcFileItem.Flags.TruncatedInDownload);
            }
            if (truncationFlags.length() != 0) {
                writer.write(PROXY_HEADER_TRUNCATION + ":" + truncationFlags + "\n");
            }

            // now walk remaining headers ... 
            for (Map.Entry<String, List<String>> entry : headerItems.entrySet()) {
                // if not in exclusion list ... 
                if (entry.getKey() != null && entry.getKey().length() != 0) {
                    if (!dontProxyHeaders.contains(entry.getKey().toLowerCase())) {
                        // and it has values ... 
                        if (entry.getValue() != null) {
                            for (String value : entry.getValue()) {
                                writer.write(entry.getKey() + ":" + value + "\n");
                            }
                        }
                    } else {
                        if (entry.getKey().equalsIgnoreCase("content-length") && entry.getValue() != null) {
                            writer.write(
                                    PROXY_HEADER_ORIGINAL_CONTENT_LEN + ":" + entry.getValue().get(0) + "\n");
                        }
                    }
                }
            }
            writer.write("\n");

            int contentLength = url.getContentRaw().getCount();
            byte contentData[] = url.getContentRaw().getReadOnlyBytes();

            if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
                UnzipResult result = GZIPUtils.unzipBestEffort(contentData,
                        CrawlEnvironment.CONTENT_SIZE_LIMIT);
                if (result != null) {
                    contentData = result.data.get();
                    contentLength = result.data.getCount();
                }
            }

            BufferedReader bufferedReader = readerForCharset(headers, contentData, contentLength, writer);

            try {
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    writer.println(line);
                }
            } finally {
                bufferedReader.close();
            }
            writer.flush();
        } else {

            response.setHeader(PROXY_HEADER_SOURCE, "origin");
            response.setHeader(PROXY_HEADER_TIMER, (System.currentTimeMillis() - requestStartTime) + "MS");
            response.setHeader(PROXY_HEADER_FINALURL,
                    (((url.getFlags() & CrawlURL.Flags.IsRedirected) != 0) ? url.getRedirectURL()
                            : url.getUrl()));

            // parse headers ... 
            NIOHttpHeaders headers = NIOHttpHeaders.parseHttpHeaders(url.getHeaders());
            // and put then in a map ... 
            Map<String, List<String>> headerItems = NIOHttpHeaders.parseHttpHeaders(url.getHeaders())
                    .getHeaders();

            // set the content length ... 
            response.setHeader("content-length", Integer.toString(url.getContentRaw().getCount()));

            String truncationFlags = "";
            if ((url.getFlags() & CrawlURL.Flags.TruncatedDuringDownload) != 0) {
                truncationFlags += ArcFileItem.Flags.toString(ArcFileItem.Flags.TruncatedInDownload);
            }
            if (truncationFlags.length() != 0) {
                response.setHeader(PROXY_HEADER_TRUNCATION, truncationFlags);
            }

            // pull out content encoding if it is set ...
            String contentEncoding = headers.findValue("content-encoding");

            if (contentEncoding != null) {
                response.setHeader("content-encoding", contentEncoding);
            }

            // now walk remaining headers ... 
            for (Map.Entry<String, List<String>> entry : headerItems.entrySet()) {
                // if not in exclusion list ... 
                if (entry.getKey() != null && entry.getKey().length() != 0) {
                    if (!dontProxyHeaders.contains(entry.getKey().toLowerCase())) {
                        // and it has values ... 
                        if (entry.getValue() != null) {
                            for (String value : entry.getValue()) {
                                response.setHeader(entry.getKey(), value);
                            }
                        }
                    } else {
                        if (entry.getKey().equalsIgnoreCase("content-length") && entry.getValue() != null) {
                            response.setHeader(PROXY_HEADER_ORIGINAL_CONTENT_LEN, entry.getValue().get(0));
                        }
                    }

                }
            }

            ServletOutputStream responseOutputStream = response.getOutputStream();
            // write out content bytes 
            responseOutputStream.write(url.getContentRaw().getReadOnlyBytes(), 0,
                    url.getContentRaw().getCount());
        }
    }
    // otherwise failed for some other reason ... 
    else {
        /*
        ProxyServer.getSingleton().logProxyFailure(500, CrawlURL.FailureReason.toString(url.getLastAttemptFailureReason()) + " - " + url.getLastAttemptFailureDetail(),
            url.getUrl(),
            url.getRedirectURL(),
            requestStartTime);
        */
        // report the reason ... 
        response.sendError(500, CrawlURL.FailureReason.toString(url.getLastAttemptFailureReason()) + " - "
                + url.getLastAttemptFailureDetail());
    }
}

From source file:coria2015.server.ContentServlet.java

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

    final URL url;
    IMAGE_URI = "/recipe/image/";
    if (request.getRequestURI().startsWith(IMAGE_URI)) {

        String recipeName = URLDecoder.decode(request.getRequestURI().substring(IMAGE_URI.length()), "UTF-8")
                .replace(" ", "-");
        String name = recipeImages.get(recipeName);
        File file = new File(imagePath, name);
        url = file.toURI().toURL();//from www . j a v a2 s.  c  o m
    } else {
        url = ContentServlet.class.getResource(format("/web%s", request.getRequestURI()));
    }

    if (url != null) {
        FileSystemManager fsManager = VFS.getManager();
        FileObject file = fsManager.resolveFile(url.toExternalForm());
        if (file.getType() == FileType.FOLDER) {
            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
            response.setHeader("Location", format("%sindex.html", request.getRequestURI()));
            return;
        }

        String filename = url.getFile();
        if (filename.endsWith(".html"))
            response.setContentType("text/html");
        else if (filename.endsWith(".png"))
            response.setContentType("image/png");
        else if (filename.endsWith(".css"))
            response.setContentType("text/css");
        response.setStatus(HttpServletResponse.SC_OK);

        final ServletOutputStream out = response.getOutputStream();
        InputStream in = url.openStream();
        byte[] buffer = new byte[8192];
        int read;
        while ((read = in.read(buffer)) > 0) {
            out.write(buffer, 0, read);
        }
        out.flush();
        in.close();
        return;
    }

    // Not found
    error404(request, response);

}

From source file:cz.incad.kramerius.audio.servlets.ServletAudioHttpRequestForwarder.java

private void forwardData(InputStream input, ServletOutputStream output) {
    try {/*ww  w  .  j av  a2s .  co  m*/
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesForwarded;
        while ((bytesForwarded = input.read(buffer)) != -1) {
            output.write(buffer, 0, bytesForwarded);
        }
    } catch (IOException ex) {
        if (ex.getCause() != null && ex.getCause() instanceof SocketException
                && (ex.getCause().getMessage().equals(CONNECTION_RESET)
                        || ex.getCause().getMessage().equals(BROKEN_PIPE))) {
            LOGGER.warning("Connection reset probably by client (or by repository)");
        } else {
            if (!"ClientAbortException".equals(ex.getClass().getSimpleName())) {
                LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
            }
        }
    } finally {
        try {
            LOGGER.fine("closing connection to repository");
            input.close();
            //output stream should not be closed here because it is closed by container. 
            //If closed here, for example filters won't be able to write to stream anymore
        } catch (IOException ex1) {
            LOGGER.log(Level.SEVERE, "Failed to close connection to repository", ex1);
        }
    }
}