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:org.wso2.carbon.registry.app.ResourceServlet.java

/**
 * Logic that will be executed for a get request.
 *
 * @param request  the HTTP Servlet request.
 * @param response the HTTP Servlet response.
 *
 * @throws IOException if an error occurred.
 *//* w  ww  .  jav a  2 s.c o  m*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {
        String uri = request.getRequestURI();
        int idx = uri.indexOf("resource");
        String path = uri.substring(idx + 8);
        if (path == null) {
            String msg = "Could not get the resource content. Path is not specified.";
            log.error(msg);
            response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
            return;
        }

        Resource resource;
        try {
            UserRegistry registry = Utils.getRegistry(request);
            try {
                path = new URI(path).normalize().toString();
            } catch (URISyntaxException e) {
                log.error("Unable to normalize requested resource path: " + path, e);
            }
            String decodedPath = URLDecoder.decode(path, RegistryConstants.DEFAULT_CHARSET_ENCODING);

            CurrentSession.setUserRealm(registry.getUserRealm());
            CurrentSession.setUser(registry.getUserName());
            try {
                if (!AuthorizationUtils.authorize(
                        RegistryUtils.getAbsolutePath(registry.getRegistryContext(), decodedPath),
                        ActionConstants.GET)) {
                    response.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED);
                    response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\"");
                    return;
                }
                resource = registry.get(decodedPath);
            } finally {
                CurrentSession.removeUserRealm();
                CurrentSession.removeUser();
            }
        } catch (AuthorizationFailedException e) {
            log.error(e.getMessage());
            response.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED);
            response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\"");
            return;
        } catch (RegistryException e) {
            String msg = "Error retrieving the resource " + path + ". " + e.getMessage();
            log.error(msg, e);
            throw e;
        }

        if (resource instanceof Collection) {
            String msg = "Could not get the resource content. Path " + path + " refers to a collection.";
            log.error(msg);
            response.setStatus(HttpURLConnection.HTTP_NOT_IMPLEMENTED);
            return;
        }

        // date based conditional get
        long ifModifiedSinceValue = request.getDateHeader("If-Modified-Since");
        long lastModifiedValue = resource.getLastModified().getTime();
        if (ifModifiedSinceValue > 0) {
            // convert the time values from milliseconds to seconds
            ifModifiedSinceValue /= 1000;
            lastModifiedValue /= 1000;

            /* condition to check we have latest updates in terms of dates */
            if (ifModifiedSinceValue >= lastModifiedValue) {
                /* no need to response with data */
                response.setStatus(HttpURLConnection.HTTP_NOT_MODIFIED);
                return;
            }
        }
        response.setDateHeader("Last-Modified", lastModifiedValue);

        // eTag based conditional get
        String ifNonMatchValue = request.getHeader("if-none-match");
        String currentETag = Utils.calculateEntityTag(resource);
        if (ifNonMatchValue != null) {
            if (ifNonMatchValue.equals(currentETag)) {
                /* the version is not modified */
                response.setStatus(HttpURLConnection.HTTP_NOT_MODIFIED);
                return;
            }
        }
        response.setHeader("ETag", currentETag);

        if (resource.getMediaType() != null && resource.getMediaType().length() > 0) {
            response.setContentType(resource.getMediaType());
        } else {
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + RegistryUtils.getResourceName(path));
            response.setContentType("application/download");
        }

        InputStream contentStream = null;
        if (resource.getContent() != null) {
            contentStream = resource.getContentStream();
        }
        if (contentStream != null) {

            try {
                ServletOutputStream servletOutputStream = response.getOutputStream();
                byte[] contentChunk = new byte[RegistryConstants.DEFAULT_BUFFER_SIZE];
                int byteCount;
                while ((byteCount = contentStream.read(contentChunk)) != -1) {
                    servletOutputStream.write(contentChunk, 0, byteCount);
                }

                response.flushBuffer();
                servletOutputStream.flush();

            } finally {
                contentStream.close();
            }

        } else {
            Object content = resource.getContent();
            if (content != null) {

                if (content instanceof byte[]) {
                    ServletOutputStream servletOutputStream = response.getOutputStream();
                    servletOutputStream.write((byte[]) content);
                    response.flushBuffer();
                    servletOutputStream.flush();
                } else {
                    PrintWriter writer = response.getWriter();
                    writer.write(content.toString());
                    writer.flush();
                }
            }
        }

        resource.discard();

    } catch (RegistryException e) {
        String msg = "Failed to get resource content. " + e.getMessage();
        log.error(msg, e);
        response.setStatus(HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
}

From source file:net.nan21.dnet.core.web.controller.AbstractDnetController.java

protected void sendFile(InputStream inputStream, ServletOutputStream outputStream, int bufferSize)
        throws IOException {
    try {/*from  w w  w.  j av  a2  s  .co  m*/
        byte[] buf = new byte[bufferSize];
        int bytesRead;
        while ((bytesRead = inputStream.read(buf)) != -1) {
            outputStream.write(buf, 0, bytesRead);
        }
    } finally {
        if (inputStream != null)
            inputStream.close();
    }
    outputStream.flush();
}

From source file:com.all.tracker.controllers.VersionController.java

private void sendFile(File updateFile, ServletOutputStream outputStream) throws Exception {
    FileInputStream fis = null;//from   w w  w. ja  v  a 2  s .c o  m
    try {

        byte[] readBytes = new byte[1024 * 4];
        int amountBytesRead;
        fis = fileInputStreamFactory.create(updateFile);

        while ((amountBytesRead = fis.read(readBytes)) != -1) {
            outputStream.write(readBytes, 0, amountBytesRead);
        }

    } catch (Exception e) {
        throw e;
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                // ignore
            }
        }
        try {
            outputStream.close();
        } catch (IOException e) {
            // ignore
        }
        fis = null;
        outputStream = null;
    }
}

From source file:eu.europa.ec.eci.oct.webcommons.controller.fileserving.FileServingController.java

@RequestMapping(method = RequestMethod.GET)
protected void doGet(Model model, HttpServletRequest request, HttpServletResponse response)
        throws OCTException {
    ServedFile file;/*from ww w .j  a va  2s.com*/
    try {
        file = getFile(request, response);
    } catch (RequestHandledTransparentlyException re) {
        // we have already redirected, no need to proceed
        return;
    }

    ServletOutputStream out;
    InputStream in = null;
    try {
        out = response.getOutputStream();
        in = file.getIs();

        String mimeType = file.getContentType();
        response.setContentType(mimeType);
        if (file.isAttachment()) {
            response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getFileName() + "\"");
        }

        final byte[] bytes = new byte[FILEBUFFERSIZE];
        int bytesRead;
        while ((bytesRead = in.read(bytes)) != -1) {
            out.write(bytes, 0, bytesRead);
        }

    } catch (IOException e) {
        logger.error("I/O exception occured", e);
        throw new OCTException("I/O exception occured", e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                logger.warn("I/O exception occured while closing input stream", e);
                logger.warn("... will continue anyway");
            }
        }
    }
}

From source file:sys.core.manager.RecursosManager.java

public void viewArchivo(String archivo) {
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
    response.setContentType("application/force-download");
    response.addHeader("Content-Disposition", "attachment; filename=\"" + archivo + "\"");
    ApplicationMBean applicationMBean = (ApplicationMBean) WebServletContextListener.getApplicationContext()
            .getBean("applicationMBean");
    byte[] buf = new byte[1024];
    try {/*  w w  w  .  ja  v  a2s .  co  m*/
        File file = new File(applicationMBean.getRutaArchivos() + archivo);
        long length = file.length();
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
        ServletOutputStream out = response.getOutputStream();
        response.setContentLength((int) length);
        while ((in != null) && ((length = in.read(buf)) != -1)) {
            out.write(buf, 0, (int) length);
        }
        in.close();
        out.close();
    } catch (Exception exc) {
        logger.error(exc);
    }
}

From source file:psef.handler.ProjectGetHandler.java

public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws PsefException {
    //1. get the project metadata
    try {//from   w w  w  .j a  v a 2  s.co  m
        Connection conn = Connector.getConnection();
        docid = request.getParameter(Params.DOCID);
        if (docid == null || docid.length() == 0)
            throw new PsefException("Missing docid");
        String project = conn.getFromDb(Database.PROJECTS, docid);
        JSONObject jObj = (JSONObject) JSONValue.parse(project);
        String site_url = (String) jObj.get(JSONKeys.SITE_URL);
        // 2. create the temporary directory
        if (site_url != null) {
            File tempDir = new File(System.getProperty("java.io.tmpdir"));
            URL siteU = new URL(site_url);
            root = new File(tempDir, getLastPart(siteU));
            if (!root.exists())
                root.mkdir();
            URL current = new URL(site_url);
            String path = urlDiff(siteU, current);
            // 2. get the home page and parse it
            writeUrlContents(site_url, path);
            File archive = tarRoot();
            response.setContentType("application/gzip");
            ServletOutputStream sos = response.getOutputStream();
            byte[] buffer = new byte[BUF_SIZE];
            FileInputStream fis = new FileInputStream(archive);
            BufferedInputStream bis = new BufferedInputStream(fis, BUF_SIZE);
            while (bis.available() > 0) {
                int amt = bis.available();
                amt = (amt > BUF_SIZE) ? BUF_SIZE : amt;
                bis.read(buffer, 0, amt);
                sos.write(buffer, 0, amt);
            }
        } else
            throw new Exception("project doesn't have a site_url");
    } catch (Exception e) {
        throw new PsefException(e);
    }
}

From source file:net.nan21.dnet.core.web.controller.AbstractDnetController.java

protected void sendFile(File file, ServletOutputStream outputStream, int bufferSize) throws IOException {
    InputStream in = null;/*www. j a  v  a  2  s .co m*/
    try {
        in = new BufferedInputStream(new FileInputStream(file));
        byte[] buf = new byte[bufferSize];
        int bytesRead;
        while ((bytesRead = in.read(buf)) != -1) {
            outputStream.write(buf, 0, bytesRead);
        }
    } finally {
        if (in != null)
            in.close();
    }
    outputStream.flush();
}

From source file:edu.umn.cs.spatialHadoop.nasa.ShahedServer.java

/**
 * Tries to load the given resource name frmo class path if it exists.
 * Used to serve static files such as HTML pages, images and JavaScript files.
 * @param target/*  w  ww  . j a  va  2s  . c o m*/
 * @param response
 * @throws IOException
 */
private void tryToLoadStaticResource(String target, HttpServletResponse response) throws IOException {
    LOG.info("Loading resource " + target);
    // Try to load this resource as a static page
    InputStream resource = getClass().getResourceAsStream("/webapps/static/shahedfrontend" + target);
    if (resource == null) {
        reportError(response, "Cannot load resource '" + target + "'", 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 (target.endsWith(".js")) {
        response.setContentType("application/javascript");
    } else if (target.endsWith(".css")) {
        response.setContentType("text/css");
    } else {
        response.setContentType(URLConnection.guessContentTypeFromName(target));
    }
    final DateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss ZZZ");
    final long year = 1000L * 60 * 60 * 24 * 365;
    // Expires in a year
    response.addHeader("Expires", format.format(new Date().getTime() + year));
}

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

/**
 * Tries to load the given resource name frmo class path if it exists. Used to
 * serve static files such as HTML pages, images and JavaScript files.
 * //from  w w w.jav  a2 s .  co  m
 * @param target
 * @param response
 * @throws IOException
 */
private void tryToLoadStaticResource(String target, HttpServletResponse response) throws IOException {
    LOG.info("Loading resource " + target);
    // Try to load this resource as a static page
    InputStream resource = getClass().getResourceAsStream("/webapps/static/hadoopviz" + target);
    if (resource == null) {
        reportError(response, "Cannot load resource '" + target + "'", 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 (target.endsWith(".js")) {
        response.setContentType("application/javascript");
    } else if (target.endsWith(".css")) {
        response.setContentType("text/css");
    } else {
        response.setContentType(URLConnection.guessContentTypeFromName(target));
    }
}