Example usage for javax.servlet.http HttpServletResponse setContentLength

List of usage examples for javax.servlet.http HttpServletResponse setContentLength

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse setContentLength.

Prototype

public void setContentLength(int len);

Source Link

Document

Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header.

Usage

From source file:org.dspace.app.webui.cris.servlet.ResearcherPictureServlet.java

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

    String idString = req.getPathInfo();
    String[] pathInfo = idString.split("/", 2);
    String authorityKey = pathInfo[1];

    Integer id = ResearcherPageUtils.getRealPersistentIdentifier(authorityKey, ResearcherPage.class);

    if (id == null) {

        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//w w  w.j  ava 2  s  .  c o m
    }

    ResearcherPage rp = ResearcherPageUtils.getCrisObject(id, ResearcherPage.class);
    File file = new File(ConfigurationManager.getProperty(CrisConstants.CFG_MODULE, "researcherpage.file.path")
            + File.separatorChar + JDynATagLibraryFunctions.getFileFolder(rp.getPict().getValue())
            + File.separatorChar + JDynATagLibraryFunctions.getFileName(rp.getPict().getValue()));

    InputStream is = null;
    try {
        is = new FileInputStream(file);

        response.setContentType(req.getSession().getServletContext().getMimeType(file.getName()));
        Long len = file.length();
        response.setContentLength(len.intValue());
        response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
        FileCopyUtils.copy(is, response.getOutputStream());
        response.getOutputStream().flush();
    } finally {
        if (is != null) {
            IOUtils.closeQuietly(is);
        }

    }

}

From source file:com.exedio.cope.live.MediaServlet.java

void doRequest(final HttpServletRequest request, final HttpServletResponse response, final Anchor anchor) {
    final String featureID = request.getParameter(FEATURE);
    if (featureID == null)
        throw new NullPointerException();
    final Media feature = (Media) model.getFeature(featureID);
    if (feature == null)
        throw new NullPointerException(featureID);

    final String itemID = request.getParameter(ITEM);
    if (itemID == null)
        throw new NullPointerException();

    final Item item;
    try {/*from   ww  w.j  av  a2  s  .  com*/
        startTransaction("media(" + featureID + ',' + itemID + ')');
        item = model.getItem(itemID);
        model.commit();
    } catch (final NoSuchIDException e) {
        throw new RuntimeException(e);
    } finally {
        model.rollbackIfNotCommitted();
    }

    final FileItem fi = anchor.getModification(feature, item);
    if (fi == null)
        throw new NullPointerException(featureID + '-' + itemID);
    response.setContentType(fi.getContentType());
    response.setContentLength((int) fi.getSize());

    InputStream in = null;
    ServletOutputStream out = null;
    try {
        in = fi.getInputStream();
        out = response.getOutputStream();

        final byte[] b = new byte[20 * 1024];
        for (int len = in.read(b); len >= 0; len = in.read(b))
            out.write(b, 0, len);
    } catch (final IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:gr.abiss.calipso.controller.AbstractServiceBasedRestController.java

@RequestMapping(value = "{subjectId}/uploads/{propertyName}/files/{id}", method = RequestMethod.GET)
public void getFile(HttpServletResponse response, @PathVariable String subjectId,
        @PathVariable String propertyName, @PathVariable String id) {
    Configuration config = ConfigurationFactory.getConfiguration();
    String fileUploadDirectory = config.getString(ConfigurationFactory.FILES_DIR);
    BinaryFile file = binaryFileService.findById(id);
    File fileFile = new File(fileUploadDirectory + file.getParentPath() + "/" + file.getNewFilename());
    response.setContentType(file.getContentType());
    response.setContentLength(file.getSize().intValue());
    try {//from  w w w . ja v a2 s. c  o  m
        InputStream is = new FileInputStream(fileFile);
        IOUtils.copy(is, response.getOutputStream());
    } catch (IOException e) {
        LOGGER.error("Could not show picture " + id, e);
    }
}

From source file:jp.co.opentone.bsol.framework.web.view.util.ViewHelper.java

protected void setDownloadResponseHeader(HttpServletRequest request, HttpServletResponse response,
        String fileName, boolean downloadByRealName, int length) {
    setContentType(response, fileName);// w w w . j  a v a 2 s . c om
    setHeaderFileName(request, response, fileName, downloadByRealName);
    response.addHeader("Accept-Ranges", "none"); // For Acrobat Reader 7.0

    if (length > 0) {
        response.setContentLength(length);
    }
}

From source file:org.shredzone.commons.gravatar.GravatarCacheServlet.java

@Override
protected void doService(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    Matcher m = HASH_PATTERN.matcher(req.getPathInfo());
    if (!m.matches()) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*from w ww  .j a v a 2s . c  om*/
    }

    String hash = m.group(1);

    GravatarService gs = getWebApplicationContext().getBean("gravatarService", GravatarService.class);
    File gravatarFile = gs.fetchGravatar(hash);

    long modifiedSinceTs = -1;
    try {
        modifiedSinceTs = req.getDateHeader("If-Modified-Since");
    } catch (IllegalArgumentException ex) {
        // As stated in RFC2616 Sec. 14.25, an invalid date will just be ignored.
    }

    if (modifiedSinceTs >= 0 && (modifiedSinceTs / 1000L) == (gravatarFile.lastModified() / 1000L)) {
        // The image has not been modified since last request
        resp.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    long size = gravatarFile.length();
    if (size > 0 && size <= Integer.MAX_VALUE) {
        // Cast to int is safe
        resp.setContentLength((int) size);
    }

    resp.setContentType("image/png");
    resp.setDateHeader("Date", System.currentTimeMillis());
    resp.setDateHeader("Last-Modified", gravatarFile.lastModified());

    try (InputStream in = new FileInputStream(gravatarFile)) {
        FileCopyUtils.copy(in, resp.getOutputStream());
    }
}

From source file:UrlServlet.java

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

    //get the 'file' parameter
    String fileName = (String) request.getParameter("file");
    if (fileName == null || fileName.equals(""))
        throw new ServletException("Invalid or non-existent file parameter in UrlServlet servlet.");

    if (fileName.indexOf(".pdf") == -1)
        fileName = fileName + ".pdf";

    URL pdfDir = null;//from  w w w .j a  v  a2s.c o  m
    URLConnection urlConn = null;
    ServletOutputStream stream = null;
    BufferedInputStream buf = null;
    try {

        pdfDir = new URL(getServletContext().getInitParameter("remote-pdf-dir") + fileName);

    } catch (MalformedURLException mue) {

        throw new ServletException(mue.getMessage());
    }
    try {

        stream = response.getOutputStream();

        //set response headers
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=" + fileName);

        urlConn = pdfDir.openConnection();
        response.setContentLength((int) urlConn.getContentLength());

        buf = new BufferedInputStream(urlConn.getInputStream());
        int readBytes = 0;

        //read from the file; write to the ServletOutputStream
        while ((readBytes = buf.read()) != -1)
            stream.write(readBytes);
    } catch (IOException ioe) {
        throw new ServletException(ioe.getMessage());
    } finally {
        if (stream != null)
            stream.close();
        if (buf != null)
            buf.close();
    }
}

From source file:gr.abiss.calipso.controller.AbstractServiceBasedRestController.java

@RequestMapping(value = "{subjectId}/uploads/{propertyName}/thumbs/{id}", method = RequestMethod.GET)
public void thumbnail(HttpServletResponse response, @PathVariable String subjectId,
        @PathVariable String propertyName, @PathVariable String id) {
    Configuration config = ConfigurationFactory.getConfiguration();
    String fileUploadDirectory = config.getString(ConfigurationFactory.FILES_DIR);
    BinaryFile file = binaryFileService.findById(id);
    File fileFile = new File(fileUploadDirectory + file.getParentPath() + "/" + file.getThumbnailFilename());
    response.setContentType(file.getContentType());
    response.setContentLength(file.getThumbnailSize().intValue());
    try {/*w  ww.j a  va 2s. c om*/
        InputStream is = new FileInputStream(fileFile);
        IOUtils.copy(is, response.getOutputStream());
    } catch (IOException e) {
        LOGGER.error("Could not show thumbnail " + id, e);
    }
}

From source file:net.cbtltd.server.UploadFileService.java

private void sendResponse(HttpServletResponse response, FormResponse details) {
    try {/*from   w  w  w  . j  a v  a2s .  com*/
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("text/plain");

        String msg = details.getStatus() + "," + (details.getReason() == null ? "" : details.getReason());
        LOG.debug("sendResponse " + msg);
        response.setContentLength(msg.length());
        response.getWriter().print(msg);
        response.getWriter().flush();
    } catch (Throwable x) {
        MonitorService.log(x);
    }
}

From source file:com.npower.dl.SoftwareDownloadServlet.java

public void doDownload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestUri = request.getRequestURI();
    log.info("Download Service: Download Content: uri: " + requestUri);

    String packageID = parserPackageID(requestUri);
    ManagementBeanFactory factory = null;
    try {/*  ww w .j a v  a2 s.com*/
        factory = ManagementBeanFactory.newInstance(EngineConfig.getProperties());
        SoftwareBean bean = factory.createSoftwareBean();
        SoftwarePackage pkg = bean.getPackageByID(Long.parseLong(packageID));
        if (pkg == null) {
            throw new DMException("Could not found download package by package ID: " + packageID);
        }
        InputStream ins = pkg.getBinary().getBinaryBlob().getBinaryStream();
        if (pkg.getSize() > 0) {
            response.setContentType(pkg.getMimeType());
            response.setContentLength(pkg.getSize());
            OutputStream out = response.getOutputStream();
            byte[] buf = new byte[1024];
            int len = ins.read(buf);
            while (len > 0) {
                out.write(buf, 0, len);
                len = ins.read(buf);
            }
            out.flush();
            //out.close();
        }
    } catch (Exception ex) {
        throw new ServletException(ex);
    } finally {
        if (factory != null) {
            factory.release();
        }
    }
}

From source file:com.qcadoo.view.internal.controllers.FileResolverController.java

@RequestMapping(value = "{tenantId:\\d+}/{firstLevel:\\d+}/{secondLevel:\\d+}/{fileName}", method = RequestMethod.GET)
public void resolve(final HttpServletRequest request, final HttpServletResponse response,
        @PathVariable("tenantId") final String tenantId) {
    String path = fileService.getPathFromUrl(request.getRequestURI());

    boolean removeFileAfterProcessing = request.getParameterMap().containsKey("clean");

    if (Integer.valueOf(tenantId) != MultiTenantUtil.getCurrentTenantId()) {
        try {//w  w  w  . j  a v a 2  s  . c  o m
            response.sendRedirect("/error.html?code=404");
        } catch (IOException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }

    InputStream input = null;

    try {
        input = fileService.getInputStream(path);

        if (input == null) {
            response.sendRedirect("/error.html?code=404");
        } else {
            OutputStream output = response.getOutputStream();

            int bytes = IOUtils.copy(input, output);

            response.setHeader("Content-disposition", "inline; filename=" + fileService.getName(path));
            response.setContentType(fileService.getContentType(path));
            response.setContentLength(bytes);

            output.flush();
        }
    } catch (IOException e) {
        IOUtils.closeQuietly(input);
        throw new IllegalStateException(e.getMessage(), e);
    }

    if (removeFileAfterProcessing) {
        fileService.remove(path);
    }
}