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:ro.fils.angularspring.controller.ProjectsController.java

@RequestMapping(method = RequestMethod.GET, value = "/downloadPDF")
public void downloadPDF(HttpServletRequest request, HttpServletResponse response)
        throws FileNotFoundException, IOException, BadElementException {
    ServletContext context = request.getServletContext();
    String appPath = context.getRealPath("");
    String fullPath = appPath + "Projects.pdf";
    PDFCreator creator = new PDFCreator();
    projectConverter = new ProjectConverter();
    creator.saveAsPDF(//from w  ww  .  j a v a 2  s  .c om
            projectConverter.readAll(
                    projectsDocumentRepository.findOne(ConnectionUtils.PROJECTS_COLLECTION).getContent()),
            fullPath);
    System.out.println("appPath = " + appPath);

    File downloadFile = new File(fullPath);
    FileInputStream inputStream = new FileInputStream(downloadFile);

    // get MIME type of the file
    String mimeType = context.getMimeType(fullPath);
    if (mimeType == null) {
        // set to binary type if MIME mapping not found
        mimeType = "application/octet-stream";
    }
    System.out.println("MIME type: " + mimeType);

    // set content attributes for the response
    response.setContentType(mimeType);
    response.setContentLength((int) downloadFile.length());

    // set headers for the response
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
    response.setHeader(headerKey, headerValue);

    // get output stream of the response
    OutputStream outStream = response.getOutputStream();

    byte[] buffer = new byte[BUFFER_SIZE];
    int bytesRead = -1;

    // write bytes read from the input stream into the output stream
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
    }

    inputStream.close();
    outStream.close();

}

From source file:com.kurento.kmf.repository.internal.http.RepositoryHttpServlet.java

private void setContentLength(HttpServletResponse response, long length) {
    if (debug > 0) {
        log("contentLength=" + length);
    }//from   w w  w  . j a  v a  2s . c o  m

    if (length < Integer.MAX_VALUE) {
        response.setContentLength((int) length);
    } else {
        // Set the content-length as String to be able to use a long
        response.setHeader("content-length", "" + length);
    }
}

From source file:io.fabric8.maven.proxy.impl.MavenProxyServletSupportTest.java

private void testDownload(Handler serverHandler) throws Exception {
    final String old = System.getProperty("karaf.data");
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    FileUtils.deleteDirectory(new File("target/tmp"));

    Server server = new Server(0);
    server.setHandler(serverHandler);/*  w ww  .j  ava  2s .  c o m*/
    server.start();

    try {
        int localPort = server.getConnectors()[0].getLocalPort();
        List<String> remoteRepos = Arrays.asList("http://relevant.not/maven2@id=central");
        RuntimeProperties props = new MockRuntimeProperties();
        // TODO: local repo should point to target/tmp
        MavenResolver resolver = createResolver("target/tmp", remoteRepos, "http", "localhost", localPort,
                "fuse", "fuse", null);
        MavenDownloadProxyServlet servlet = new MavenDownloadProxyServlet(resolver, props, projectDeployer, 5);

        AsyncContext context = EasyMock.createMock(AsyncContext.class);

        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        EasyMock.expect(request.getPathInfo())
                .andReturn("org.apache.camel/camel-core/2.13.0/camel-core-2.13.0-sources.jar");
        EasyMock.expect(request.startAsync()).andReturn(context);
        context.setTimeout(EasyMock.anyInt());
        EasyMock.expectLastCall();

        HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        EasyMock.expect(response.getOutputStream()).andReturn(new ServletOutputStream() {
            @Override
            public void write(int b) throws IOException {
                baos.write(b);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                baos.write(b, off, len);
            }
        }).anyTimes();
        response.setStatus(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentLength(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentType((String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();
        response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong());
        EasyMock.expectLastCall().anyTimes();
        response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();

        final CountDownLatch latch = new CountDownLatch(1);
        context.complete();
        EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
            @Override
            public Object answer() throws Throwable {
                latch.countDown();
                return null;
            }
        });

        EasyMock.makeThreadSafe(context, true);
        EasyMock.replay(request, response, context);

        servlet.start();
        servlet.doGet(request, response);

        latch.await();

        Assert.assertArrayEquals(new byte[] { 0x42 }, baos.toByteArray());

        EasyMock.verify(request, response, context);
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}

From source file:com.google.appinventor.server.WebAppLaunchServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    String userId = userInfoProvider.getUserId();
    String launchFile;/* w  w  w  .j  a  va2 s.c  om*/

    try {
        String uri = req.getRequestURI();
        // First, call split with no limit parameter.
        String[] uriComponents = uri.split("/");
        String launchKind = uriComponents[REQUEST_INDEX];

        if (launchKind.equals(ServerLayout.WEBAPP_FILE)) {
            uriComponents = uri.split("/", SPLIT_LIMIT_FILE);
            if (FILE_PATH_INDEX > uriComponents.length) {
                throw CrashReport.createAndLogError(LOG, req, null,
                        new IllegalArgumentException("Missing web app file path."));
            }
            String fileName = uriComponents[FILE_PATH_INDEX];
            launchFile = storageIo.downloadUserFile(userId, fileName, "UTF-8");

        } else {
            throw CrashReport.createAndLogError(LOG, req, null,
                    new IllegalArgumentException("Unknown launch kind: " + launchKind));
        }

    } catch (IllegalArgumentException e) {
        throw CrashReport.createAndLogError(LOG, req, null, e);
    }

    byte[] content = launchFile.getBytes();
    // Set http response information
    resp.setStatus(HttpServletResponse.SC_OK);
    resp.setContentType("text/html");
    resp.setContentLength(launchFile.length());

    // Attach download data
    ServletOutputStream out = resp.getOutputStream();
    out.write(content);
    out.close();
}

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.Default.java

protected void sendDirectory(HttpServletRequest request, HttpServletResponse response, Resource resource,
        boolean parent) throws IOException {
    if (!_dirAllowed) {
        response.sendError(HttpResponse.__403_Forbidden);
        return;/*from ww w .  j a  va2 s.c o m*/
    }

    byte[] data = null;
    if (resource instanceof CachedResource)
        data = ((CachedResource) resource).getCachedData();

    if (data == null) {
        String base = URI.addPaths(request.getRequestURI(), "/");
        String dir = resource.getListHTML(base, parent);
        if (dir == null) {
            response.sendError(HttpResponse.__403_Forbidden, "No directory");
            return;
        }
        data = dir.getBytes("UTF-8");
        if (resource instanceof CachedResource)
            ((CachedResource) resource).setCachedData(data);
    }

    response.setContentType("text/html; charset=UTF-8");
    response.setContentLength(data.length);

    if (!request.getMethod().equals(HttpRequest.__HEAD))
        response.getOutputStream().write(data);
}

From source file:org.geoserver.ows.AbstractURLPublisher.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    URL url = getUrl(request);//from   w  w  w  .  j  a va2s. c  om

    // if not found return a 404
    if (url == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }

    File file = DataUtilities.urlToFile(url);
    if (file != null && file.exists() && file.isDirectory()) {
        String uri = request.getRequestURI().toString();
        uri += uri.endsWith("/") ? "index.html" : "/index.html";

        response.addHeader("Location", uri);
        response.sendError(HttpServletResponse.SC_MOVED_TEMPORARILY);

        return null;
    }

    // set the mime if known by the servlet container, set nothing otherwise
    // (Tomcat behaves like this when it does not recognize the file format)
    String mime = getServletContext().getMimeType(new File(url.getFile()).getName());
    if (mime != null) {
        response.setContentType(mime);
    }

    // set the content length and content type
    URLConnection connection = null;
    InputStream input = null;
    try {
        connection = url.openConnection();
        long length = connection.getContentLength();
        if (length > 0 && length <= Integer.MAX_VALUE) {
            response.setContentLength((int) length);
        }

        long lastModified = connection.getLastModified();
        if (lastModified > 0) {
            SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss", Locale.ENGLISH);
            format.setTimeZone(TimeZone.getTimeZone("GMT"));
            String formatted = format.format(new Date(lastModified)) + " GMT";
            response.setHeader("Last-Modified", formatted);
        }

        // Guessing the charset (and closing the stream)
        EncodingInfo encInfo = null;
        OutputStream output = null;
        final byte[] b4 = new byte[4];
        int count = 0;
        // open the output
        input = connection.getInputStream();

        // Read the first four bytes, and determine charset encoding
        count = input.read(b4);
        encInfo = XmlCharsetDetector.getEncodingName(b4, count);
        response.setCharacterEncoding(encInfo.getEncoding() != null ? encInfo.getEncoding() : "UTF-8");

        // send out the first four bytes read
        output = response.getOutputStream();
        output.write(b4, 0, count);

        // copy the content to the output
        byte[] buffer = new byte[8192];
        int n = -1;
        while ((n = input.read(buffer)) != -1) {
            output.write(buffer, 0, n);
        }
    } finally {
        if (input != null)
            input.close();
    }

    return null;
}

From source file:architecture.ee.web.spring.controller.DownloadController.java

@RequestMapping(value = "/images/{imageId:[\\p{Digit}]+}/{filename:.+}", method = RequestMethod.GET)
@ResponseBody//w ww.  ja  va  2  s.co  m
public void donwloadImage(@PathVariable("imageId") Long imageId, @PathVariable("filename") String filename,
        @RequestParam(value = "width", defaultValue = "0", required = false) Integer width,
        @RequestParam(value = "height", defaultValue = "0", required = false) Integer height,
        HttpServletResponse response) throws IOException {
    try {
        if (imageId > 0 && StringUtils.isNotEmpty(filename)) {
            Image image = imageManager.getImage(imageId);
            User user = SecurityHelper.getUser();
            if (hasPermissions(image, user) && StringUtils.equals(filename, image.getName())) {
                InputStream input;
                String contentType;
                int contentLength;
                if (width > 0 && width > 0) {
                    input = imageManager.getImageThumbnailInputStream(image, width, height);
                    contentType = image.getThumbnailContentType();
                    contentLength = image.getThumbnailSize();
                } else {
                    input = imageManager.getImageInputStream(image);
                    contentType = image.getContentType();
                    contentLength = image.getSize();
                }
                response.setContentType(contentType);
                response.setContentLength(contentLength);
                IOUtils.copy(input, response.getOutputStream());
                response.flushBuffer();
            } else {
                throw new NotFoundException();
            }
        } else {
            throw new NotFoundException();
        }
    } catch (NotFoundException e) {
        response.sendError(404);
    }
}

From source file:biz.astute.test.simulator.rest.SimulatorRestHandler.java

/**
 * {@inheritDoc}//w w  w .j a v a  2  s. co m
 */
@Override
public final void handle(final String pTarget, final Request pBaseRequest, final HttpServletRequest pRequest,
        final HttpServletResponse pResponse) throws IOException, ServletException {

    // Lets set the default
    pResponse.setContentType("text/plain");

    try {

        DataResourceInterface dataResourceInterface = DataResourceFactory
                .getDataResource(new RequestContext(pRequest, pResponse));

        for (String header : dataResourceInterface
                .getProperties(DataResourceInterface.HEADER_RESPONSE_PREFIX)) {
            pResponse.setHeader(header.substring(DataResourceInterface.HEADER_RESPONSE_PREFIX.length() + 1),
                    dataResourceInterface.getPropertyValue(header));
        }

        String status = dataResourceInterface.getPropertyValue(DataResourceInterface.RESPONSE_STATUS);
        if (StringUtils.isEmpty(status)) {
            status = Integer.toString(HttpStatus.OK_200);
        }
        pResponse.setStatus(Integer.parseInt(status));
        String val = dataResourceInterface.getPropertyValue(DataResourceInterface.DATA_RESPONSE_VALUE);
        if (val == null) {

            try (InputStream inStream = dataResourceInterface
                    .getResourceData(DataResourceInterface.DATA_RESPONSE_RESOURCE);) {
                if (inStream != null) {
                    OutputStream outStream = pResponse.getOutputStream();
                    pResponse.setContentLength(IOUtils.copy(inStream, outStream));
                    outStream.flush();
                }
            }
        } else {
            pResponse.getWriter().print(val);
        }

    } catch (DataResourceException | NoSuchAlgorithmException execp) {
        LOGGER.log(Level.SEVERE, "Error Processing " + pRequest.getRequestURL(), execp);
        pResponse.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
        pResponse.getWriter()
                .print("Error Processing " + pRequest.getRequestURL() + " - " + execp.getMessage());
    }
    pResponse.flushBuffer();
    pBaseRequest.setHandled(true);
}

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

public void doDownloadDescriptor(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestUrl = request.getRequestURL().toString();
    String requestUri = request.getRequestURI();
    log.info("Download Service: Download Descriptor: url: " + requestUrl);
    log.info("Download Service: Download Descriptor: uri: " + requestUri);

    String downloadID = DownloadFactory.parserDownloadID(requestUri);

    log.info("Download Service: Request download ID: " + downloadID);

    DownloadFactory ddFactory = DownloadFactory.newInstance();
    DownloadDescriptor descriptor = ddFactory.getDownloadDescriptor(downloadID);

    try {/*from  w  w w  .  j  av a2 s.  co  m*/
        String serverURL = DownloadFactory.getServerURL(requestUrl);
        String baseURL = serverURL + request.getContextPath() + "/dl";

        //String baseURL = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
        //                + request.getContextPath() + "/dl";

        descriptor.setDownloadURI(baseURL + "/" + DownloadFactory.OPERATION_DOWNLOAD);
        descriptor.setInstallNotifyURI(baseURL + "/" + DownloadFactory.OPERARION_INSTALL_NOTIFICATION);

        String content = descriptor.getContent();
        response.setContentType(descriptor.getContentType());
        response.setContentLength(content.length());

        OutputStream out = response.getOutputStream();
        out.write(content.getBytes("UTF-8"));
        out.flush();
        out.close();

        log.debug("Download Descriptor Content: " + content);
    } catch (Exception ex) {
        throw new ServletException(ex);
    } finally {
    }
}

From source file:org.wallride.web.support.MediaHttpRequestHandler.java

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    checkAndPrepare(request, response, true);

    Map<String, Object> pathVariables = (Map<String, Object>) request
            .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
    String key = (String) pathVariables.get("key");

    Media media = mediaService.getMedia(key);
    int width = ServletRequestUtils.getIntParameter(request, "w", 0);
    int height = ServletRequestUtils.getIntParameter(request, "h", 0);
    int mode = ServletRequestUtils.getIntParameter(request, "m", 0);

    Resource resource = readResource(media, width, height, Media.ResizeMode.values()[mode]);

    if (resource == null) {
        logger.debug("No matching resource found - returning 404");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*  w  ww . ja  v a  2 s.co m*/
    }
    if (new ServletWebRequest(request, response).checkNotModified(resource.lastModified())) {
        logger.debug("Resource not modified - returning 304");
        return;
    }

    long length = resource.contentLength();
    if (length > Integer.MAX_VALUE) {
        throw new IOException("Resource content too long (beyond Integer.MAX_VALUE): " + resource);
    }

    response.setContentLength((int) length);
    response.setContentType(media.getMimeType());
    if (!"image".equals(MediaType.parseMediaType(media.getMimeType()).getType())) {
        response.setHeader("Content-Disposition",
                "attachment;filename*=utf-8''" + URLEncoder.encode(media.getOriginalName(), "UTF-8"));
    }

    FileCopyUtils.copy(resource.getInputStream(), response.getOutputStream());
}