Example usage for javax.servlet.http HttpServletResponse setHeader

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

Introduction

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

Prototype

public void setHeader(String name, String value);

Source Link

Document

Sets a response header with the given name and value.

Usage

From source file:de.otto.jsonhome.controller.JsonHomeController.java

@RequestMapping(produces = { "application/json" })
@ResponseBody/*from  w ww.j av  a2  s .  c om*/
public Map<String, ?> getAsApplicationJson(final HttpServletResponse response) {
    LOG.info("Returning json-home in application/json format.");
    // home document should be cached:
    response.setHeader("Cache-Control", "max-age=" + maxAge);
    response.setHeader("Vary", "Accept");
    return toRepresentation(jsonHomeSource.getJsonHome(), APPLICATION_JSON);
}

From source file:com.nagarro.core.v2.controller.BaseController.java

protected void setTotalCountHeader(final HttpServletResponse response, final PaginationData paginationDto) {
    if (paginationDto != null) {
        response.setHeader(HEADER_TOTAL_COUNT, String.valueOf(paginationDto.getTotalNumberOfResults()));
    }//from  w w w .  j a v a 2 s  . co  m
}

From source file:edu.cornell.library.scholars.webapp.controller.api.DistributeDataApiController.java

private void setCorsHeaders(HttpServletRequest req, HttpServletResponse resp) {
    log.debug("Setting CORS header for every request.");
    resp.setHeader("Access-Control-Allow-Origin", "*");
}

From source file:controllers.BaseParamController.java

@RequestMapping("/getXls")
public void getXls(Map<String, Object> model, HttpServletResponse response) throws Exception {
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=BaseParamMap.xls");
    baseParamService.getXls().write(response.getOutputStream());
}

From source file:httpUtils.HttpUtils.java

/**
 * Parse the request headers, build the response, stream back file
 * @param request/*from  www .  j a  v a2  s .co  m*/
 * @param response
 * @param dataStream
 * @param fileLength
 * @param fileName
 * @param fileLastModified
 * @param contentType
 * @return
 */
private static HttpServletResponse getFileAsStream(HttpServletRequest request, HttpServletResponse response,
        InputStream dataStream, long fileLength, String fileName, long fileLastModified, String contentType) {
    if (dataStream == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return response;
    }

    if (StringUtils.isEmpty(fileName) || fileLastModified == 0L) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return response;
    }

    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, fileName)) {
        response.setHeader("ETag", fileName);
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return response;
    }

    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > fileLastModified) {
        response.setHeader("ETag", fileName);
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return response;
    }

    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, fileName)) {
        response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
        return response;
    }

    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= fileLastModified) {
        response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
        return response;
    }

    Range full = new Range(0, fileLength - 1, fileLength);
    List<Range> ranges = new ArrayList<Range>();
    String range = request.getHeader("Range");
    if (range != null) {
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + fileLength);
            response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return response;
        }

        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(fileName)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range");
                if (ifRangeTime != -1) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        if (ranges.isEmpty()) {
            for (String part : range.substring(6).split(",")) {
                // Assuming a file with length of 100, the following
                // examples returns bytes at:
                // 50-80 (50 to 80), 40- (40 to length=100), -20
                // (length-20=80 to length=100).
                long start = sublong(part, 0, part.indexOf("-"));
                long end = sublong(part, part.indexOf("-") + 1, part.length());

                if (start == -1) {
                    start = fileLength - end;
                    end = fileLength - 1;
                } else if (end == -1 || end > fileLength - 1) {
                    end = fileLength - 1;
                }

                // Check if Range is syntactically valid. If not, then
                // return 416.
                if (start > end) {
                    response.setHeader("Content-Range", "bytes */" + fileLength); // Required
                    // in
                    // 416.
                    response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                    return response;
                }

                // Add range.
                ranges.add(new Range(start, end, fileLength));
            }
        }
    }

    // Get content type by file name and set content disposition.
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see:
    // http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    } else if (!contentType.startsWith("image")) {
        // Else, expect for images, determine content disposition. If
        // content type is supported by
        // the browser, then set to inline, else attachment which will pop a
        // 'save as' dialogue.
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(HttpUtils.DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", fileName);
    response.setDateHeader("Last-Modified", fileLastModified);
    response.setDateHeader("Expires", System.currentTimeMillis() + HttpUtils.DEFAULT_EXPIRE_TIME);

    // Send requested file (part(s)) to client
    // ------------------------------------------------

    // Prepare streams.
    InputStream input = null;
    OutputStream output = null;

    try {
        // Open streams.
        input = new BufferedInputStream(dataStream);
        output = response.getOutputStream();

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            Range r = full;
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            copy(input, output, fileLength, r.start, r.length);

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Copy single part range.
            copy(input, output, fileLength, r.start, r.length);

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + HttpUtils.MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Cast back to ServletOutputStream to get the easy println
            // methods.
            ServletOutputStream sos = (ServletOutputStream) output;

            // Copy multi part range.
            for (Range r : ranges) {
                // Add multipart boundary and header fields for every range.
                sos.println();
                sos.println("--" + HttpUtils.MULTIPART_BOUNDARY);
                sos.println("Content-Type: " + contentType);
                sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                // Copy single part range of multi part range.
                copy(input, output, fileLength, r.start, r.length);
            }

            // End with multipart boundary.
            sos.println();
            sos.println("--" + HttpUtils.MULTIPART_BOUNDARY + "--");
        }
    } catch (Exception e) {
        log.error("get file as stream failed", e);
    } finally {
        // Gently close streams.
        close(output);
        close(input);
        close(dataStream);
    }
    return response;
}

From source file:org.jasig.web.filter.SimpleCorsFilter.java

/**
 * Sets the headers to support CORS /*  w  w w  . jav  a 2  s .  com*/
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", allowOrigin);
    response.setHeader("Access-Control-Allow-Methods", allowMethod);
    response.setHeader("Access-Control-Max-Age", maxAge);
    response.setHeader("Access-Control-Allow-Headers", allowHeaders);
    chain.doFilter(req, res);
}

From source file:com.lbb.controller.FileUploadController.java

@RequestMapping("download.html")
public void download(String fileName, HttpServletResponse response) throws IOException {
    OutputStream os = response.getOutputStream();
    try {/*from  ww w  .  j  a  v a  2s  .com*/
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.setContentType("image/jpeg; charset=utf-8");
        os.write(FileUtils.readFileToByteArray(FileUpload.getFile(fileName)));
        os.flush();
    } finally {
        if (os != null) {
            os.close();
        }
    }
}

From source file:de.otto.jsonhome.controller.JsonHomeController.java

@RequestMapping(produces = { "application/json-home" })
@ResponseBody//w  w w  . j ava2s  .c  o m
public Map<String, ?> getAsApplicationJsonHome(final HttpServletResponse response) {
    LOG.info("Returning json-home in application/json-home format.");
    // home document should be cached:
    response.setHeader("Cache-Control", "max-age=" + maxAge);
    response.setHeader("Vary", "Accept");
    return toRepresentation(jsonHomeSource.getJsonHome(), APPLICATION_JSONHOME);
}

From source file:org.sventon.web.ctrl.RSSController.java

private void addResponseHeaders(HttpServletResponse response) {
    response.setContentType(mimeType);//from ww w  .  j av a 2 s  .c  om
    response.setHeader("Cache-Control", "no-cache");
}

From source file:com.demandware.vulnapp.challenge.impl.MD5Challenge.java

public Object handleChallengeRequest(DIVAServletRequestWrapper req) {
    String download = req.getParameter(DOWNLOAD_PARAM);
    if (!StringUtils.isBlank(download)) {
        HttpServletResponse response = req.getResponse();
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + this.b64WarLocation.getName());

        try (FileInputStream fileIn = new FileInputStream(this.b64WarLocation);
                ServletOutputStream out = response.getOutputStream()) {

            IOUtils.copy(fileIn, out);/*from w  w w. ja v a2 s. c  o m*/

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}