Example usage for javax.servlet.http HttpServletResponse setContentLengthLong

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

Introduction

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

Prototype

public void setContentLengthLong(long 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.eclipse.vorto.repository.web.ModelGenerationController.java

@ApiOperation(value = "Generate code for a specified platform")
@RequestMapping(value = "/{namespace}/{name}/{version:.+}/{serviceKey}", method = RequestMethod.GET)
public void generate(@ApiParam(value = "Namespace", required = true) final @PathVariable String namespace,
        @ApiParam(value = "Name", required = true) final @PathVariable String name,
        @ApiParam(value = "Version", required = true) final @PathVariable String version,
        @ApiParam(value = "Service Key - Platform", required = true) @PathVariable String serviceKey,
        @ApiParam(value = "Response", required = true) final HttpServletResponse response) {
    Objects.requireNonNull(namespace, "namespace must not be null");
    Objects.requireNonNull(name, "name must not be null");
    Objects.requireNonNull(version, "version must not be null");

    GeneratedOutput generatedOutput = generatorService.generate(new ModelId(name, namespace, version),
            serviceKey);//from w  ww. ja  v  a2 s.c o  m
    response.setHeader(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + generatedOutput.getFileName());
    response.setContentLengthLong(generatedOutput.getSize());
    response.setContentType(APPLICATION_OCTET_STREAM);
    try {
        IOUtils.copy(new ByteArrayInputStream(generatedOutput.getContent()), response.getOutputStream());
        response.flushBuffer();
    } catch (IOException e) {
        throw new RuntimeException("Error copying file.", e);
    }
}

From source file:eu.creatingfuture.propeller.webLoader.servlets.WebRequestServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.addHeader("Access-Control-Allow-Origin", "*");
    String getUrl = req.getParameter("get");
    if (getUrl == null) {
        resp.sendError(400);//  w w w  .j a  v  a2s .  com
        return;
    }
    logger.info(getUrl);
    URL url;
    HttpURLConnection connection = null;
    try {
        url = new URL(getUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setUseCaches(false);

        resp.setContentType(connection.getContentType());
        resp.setContentLengthLong(connection.getContentLengthLong());
        logger.log(Level.INFO, "Content length: {0} response code: {1} content type: {2}", new Object[] {
                connection.getContentLengthLong(), connection.getResponseCode(), connection.getContentType() });
        resp.setStatus(connection.getResponseCode());
        IOUtils.copy(connection.getInputStream(), resp.getOutputStream());
    } catch (IOException ioe) {
        resp.sendError(500, ioe.getMessage());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:org.springframework.web.servlet.resource.ResourceHttpRequestHandler.java

/**
 * Set headers on the given servlet response.
 * Called for GET requests as well as HEAD requests.
 * @param response current servlet response
 * @param resource the identified resource (never {@code null})
 * @param mediaType the resource's media type (never {@code null})
 * @throws IOException in case of errors while setting the headers
 */// w  ww  . jav  a 2s . c  o m
protected void setHeaders(HttpServletResponse response, Resource resource, @Nullable MediaType mediaType)
        throws IOException {

    long length = resource.contentLength();
    if (length > Integer.MAX_VALUE) {
        response.setContentLengthLong(length);
    } else {
        response.setContentLength((int) length);
    }

    if (mediaType != null) {
        response.setContentType(mediaType.toString());
    }
    if (resource instanceof HttpResource) {
        HttpHeaders resourceHeaders = ((HttpResource) resource).getResponseHeaders();
        for (Map.Entry<String, List<String>> entry : resourceHeaders.entrySet()) {
            String headerName = entry.getKey();
            boolean first = true;
            for (String headerValue : entry.getValue()) {
                if (first) {
                    response.setHeader(headerName, headerValue);
                } else {
                    response.addHeader(headerName, headerValue);
                }
                first = false;
            }
        }
    }
    response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
}

From source file:com.formkiq.core.api.FeedsController.java

/**
 * Gets a Feed and transfers XML to JSON.
 * @param request {@link HttpServletRequest}
 * @param response {@link HttpServletResponse}
 * @throws IOException IOException//from  www.j  a  v a  2 s .  c  om
 * @throws InvalidFeedUrlException InvalidFeedUrlException
 */
@RequestMapping(value = API_FEEDS_GET)
public void get(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, InvalidFeedUrlException {

    getApiVersion(request);

    Map<String, String[]> map = request.getParameterMap();

    String url = getParameter(map, "url", true).trim();

    ResponseEntity<String> entity = this.feedService.get(url);

    String body = entity.getBody();

    if (this.feedService.isXMLContentType(entity.getHeaders())) {

        body = this.feedService.toJSONFromXML(body);

    } else if (!this.feedService.isJSONContentType(entity.getHeaders())) {

        List<String> contentTypes = entity.getHeaders().get("content-type");
        String ct = !contentTypes.isEmpty() ? contentTypes.get(0) : "unknown content type";
        throw new InvalidFeedUrlException("Invalid content-type " + ct + " for " + url);
    }

    response.setContentType("application/json");
    response.setContentLengthLong(body.length());
    IOUtils.write(body, response.getOutputStream(), Strings.CHARSET_UTF8);
}

From source file:com.formkiq.core.service.workflow.WorkflowServiceImpl.java

@Override
public ModelAndView actions(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {

    WebFlow flow = FlowManager.get(request);

    Map<String, String[]> parameterMap = request.getParameterMap();

    if (parameterMap.containsKey("_eventId_print")) {
        return getModelAndView(flow, DEFAULT_PDF_VIEW);
    }//ww w .  ja v a2 s  .c o  m

    byte[] bytes = generatePDF(request, flow);

    response.setContentType("application/pdf");
    response.setContentLengthLong(bytes.length);
    IOUtils.write(bytes, response.getOutputStream());
    response.getOutputStream().flush();

    return null;
}

From source file:org.cirdles.webServices.ambapo.AmbapoServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*w  w  w  .j  a va  2 s .  co  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/csv");
    response.setHeader("Content-Disposition", "attachment; filename=converted-file.csv");

    String conversionType = ServletRequestUtils.getStringParameter(request, "conversionType", "LatLongtoUTM");
    Part filePart = request.getPart("ambapoFile");

    String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
    InputStream fileStream = filePart.getInputStream();
    File myFile = new File(fileName);

    AmbapoFileHandlerService handler = new AmbapoFileHandlerService();
    String fileExt = FilenameUtils.getExtension(fileName);

    try {
        File convertedFile = null;
        if (fileExt.equals("csv")) {
            convertedFile = handler.convertFile(fileName, fileStream, conversionType).toFile();
            response.setContentLengthLong(convertedFile.length());
            IOUtils.copy(new FileInputStream(convertedFile), response.getOutputStream());
        }

        else {
        }

    } catch (Exception e) {
        System.err.println(e);
    }

}

From source file:foam.nanos.servlet.ImageServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // get path//  ww w .  ja v a2 s.  c  o m
    String cwd = System.getProperty("user.dir");
    String[] paths = getServletConfig().getInitParameter("paths").split(":");
    String reqPath = req.getRequestURI().replaceFirst("/?images/?", "/");

    // enumerate each file path
    for (int i = 0; i < paths.length; i++) {
        File src = new File(cwd + "/" + paths[i] + reqPath);
        if (src.isFile() && src.canRead()
                && src.getCanonicalPath().startsWith(new File(paths[i]).getCanonicalPath())) {
            String ext = EXTS.get(FilenameUtils.getExtension(src.getName()));
            try (BufferedInputStream is = new BufferedInputStream(new FileInputStream(src))) {
                resp.setContentType(!SafetyUtil.isEmpty(ext) ? ext : DEFAULT_EXT);
                resp.setHeader("Content-Disposition",
                        "filename=\"" + StringEscapeUtils.escapeHtml4(src.getName()) + "\"");
                resp.setContentLengthLong(src.length());

                IOUtils.copy(is, resp.getOutputStream());
                return;
            }
        }
    }

    resp.sendError(resp.SC_NOT_FOUND);
}

From source file:sg.ncl.DataController.java

private ResponseExtractor<Void> getResponseExtractor(final HttpServletResponse httpResponse) {
    return response -> {
        String content = response.getHeaders().get("Content-Disposition").get(0);
        httpResponse.setContentType("application/octet-stream");
        httpResponse.setContentLengthLong(Long.parseLong(response.getHeaders().get("Content-Length").get(0)));
        httpResponse.setHeader("Content-Disposition", content);
        IOUtils.copy(response.getBody(), httpResponse.getOutputStream());
        httpResponse.flushBuffer();//from   w  w w  .  ja v  a2  s  . c o m
        return null;
    };
}

From source file:com.nms.mediastore.servlet.VideoServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from  w w w  . j  a  va 2s .c om
 * @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 {
    String uuid = request.getParameter("id");
    if (Validator.isNotNull(uuid)) {
        VideoLink link;
        FileEntry videoFile = null;
        try {
            if (uuid.equals(DEFAULT_ID)) {
                Video video = videoService.getDefault();
                videoFile = video.getVideoFile();
            } else {
                link = linkService.findByUUID(uuid);
                videoFile = link.getVideo().getVideoFile();
            }
        } catch (Exception e) {
            LOG.log(Level.WARNING, "Video link not found or expirated uuid = {0} and ERROR: {1}",
                    new Object[] { uuid, e.toString() });
        }

        if (videoFile != null && Validator.isNotNull(videoFile.getUri())) {
            File in = new File(AppConfig.getFileStorePath() + videoFile.getUri());
            if (in.exists()) {
                response.setContentType(videoFile.getContentType());
                response.setContentLengthLong(videoFile.getSize());
                response.setHeader("Content-Disposition",
                        "attachment;filename=\"" + videoFile.getName() + "\"");
                try (OutputStream out = response.getOutputStream()) {
                    FileUtils.copyFile(in, out);
                }
            } else {
                LOG.log(Level.WARNING, "Video file not found = {0}",
                        new Object[] { AppConfig.getFileStorePath() + videoFile.getUri() });
            }
        } else {
            LOG.log(Level.WARNING, "Video file not found = {0}", new Object[] { uuid });
        }
    }
}

From source file:de.codecentric.boot.admin.zuul.filters.post.SendResponseFilter.java

private void addResponseHeaders() {
    RequestContext context = RequestContext.getCurrentContext();
    HttpServletResponse servletResponse = context.getResponse();
    List<Pair<String, String>> zuulResponseHeaders = context.getZuulResponseHeaders();
    @SuppressWarnings("unchecked")
    List<String> rd = (List<String>) RequestContext.getCurrentContext().get("routingDebug");
    if (rd != null) {
        StringBuilder debugHeader = new StringBuilder();
        for (String it : rd) {
            debugHeader.append("[[[" + it + "]]]");
        }/*from   www .jav a 2s . c o  m*/
        if (INCLUDE_DEBUG_HEADER.get()) {
            servletResponse.addHeader("X-Zuul-Debug-Header", debugHeader.toString());
        }
    }
    if (zuulResponseHeaders != null) {
        for (Pair<String, String> it : zuulResponseHeaders) {
            servletResponse.addHeader(it.first(), it.second());
        }
    }
    RequestContext ctx = RequestContext.getCurrentContext();
    Long contentLength = ctx.getOriginContentLength();
    // Only inserts Content-Length if origin provides it and origin response is not
    // gzipped
    if (SET_CONTENT_LENGTH.get()) {
        if (contentLength != null && !ctx.getResponseGZipped()) {
            servletResponse.setContentLengthLong(contentLength);
        }
    }
}