List of usage examples for org.springframework.http HttpHeaders setCacheControl
public void setCacheControl(@Nullable String cacheControl)
From source file:de.metas.ui.web.window.controller.WindowRestController.java
@GetMapping("/{windowId}/{documentId}/attachments/{id}") public ResponseEntity<byte[]> getAttachmentById(@PathVariable("windowId") final int adWindowId // , @PathVariable("documentId") final String documentId // , @PathVariable("id") final int id) { userSession.assertLoggedIn();// w w w. ja va 2s. c o m final DocumentPath documentPath = DocumentPath.rootDocumentPath(DocumentType.Window, adWindowId, documentId); final Document document = documentCollection.getDocument(documentPath); final MAttachmentEntry entry = Services.get(IAttachmentBL.class).getEntryForModelById(document, id); if (entry == null) { throw new EntityNotFoundException("No attachment found (ID=" + id + ")"); } final String entryFilename = entry.getFilename(); final byte[] entryData = entry.getData(); if (entryData == null || entryData.length == 0) { throw new EntityNotFoundException("No attachment found (ID=" + id + ")"); } final String entryContentType = entry.getContentType(); final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType(entryContentType)); headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + entryFilename + "\""); headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); final ResponseEntity<byte[]> response = new ResponseEntity<>(entryData, headers, HttpStatus.OK); return response; }
From source file:de.blizzy.documentr.web.attachment.AttachmentController.java
@RequestMapping(value = "/{projectName:" + DocumentrConstants.PROJECT_NAME_PATTERN + "}/" + "{branchName:" + DocumentrConstants.BRANCH_NAME_PATTERN + "}/" + "{pagePath:" + DocumentrConstants.PAGE_PATH_URL_PATTERN + "}/" + "{name:.*}", method = { RequestMethod.GET, RequestMethod.HEAD }) @PreAuthorize("hasPagePermission(#projectName, #branchName, #pagePath, VIEW)") public ResponseEntity<byte[]> getAttachment(@PathVariable String projectName, @PathVariable String branchName, @PathVariable String pagePath, @PathVariable String name, @RequestParam(required = false) boolean download, HttpServletRequest request) throws IOException { try {//from w w w .j av a 2 s . co m pagePath = Util.toRealPagePath(pagePath); PageMetadata metadata = pageStore.getAttachmentMetadata(projectName, branchName, pagePath, name); HttpHeaders headers = new HttpHeaders(); long lastEdited = metadata.getLastEdited().getTime(); long authenticationCreated = AuthenticationUtil.getAuthenticationCreationTime(request.getSession()); long lastModified = Math.max(lastEdited, authenticationCreated); if (!download) { long projectEditTime = PageUtil.getProjectEditTime(projectName); if (projectEditTime >= 0) { lastModified = Math.max(lastModified, projectEditTime); } long modifiedSince = request.getDateHeader("If-Modified-Since"); //$NON-NLS-1$ if ((modifiedSince >= 0) && (lastModified <= modifiedSince)) { return new ResponseEntity<byte[]>(headers, HttpStatus.NOT_MODIFIED); } } headers.setLastModified(lastModified); headers.setExpires(0); headers.setCacheControl("must-revalidate, private"); //$NON-NLS-1$ if (download) { headers.set("Content-Disposition", //$NON-NLS-1$ "attachment; filename=\"" + name.replace('"', '_') + "\""); //$NON-NLS-1$ //$NON-NLS-2$ } Page attachment = pageStore.getAttachment(projectName, branchName, pagePath, name); headers.setContentType(MediaType.parseMediaType(attachment.getContentType())); return new ResponseEntity<byte[]>(attachment.getData().getData(), headers, HttpStatus.OK); } catch (PageNotFoundException e) { return new ResponseEntity<byte[]>(HttpStatus.NOT_FOUND); } }
From source file:de.metas.ui.web.letter.LetterRestController.java
private ResponseEntity<byte[]> createPDFResponseEntry(final byte[] pdfData) { final String pdfFilename = Services.get(IMsgBL.class).getMsg(Env.getCtx(), Letters.MSG_Letter); final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_PDF); headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + pdfFilename + "\""); headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); final ResponseEntity<byte[]> response = new ResponseEntity<>(pdfData, headers, HttpStatus.OK); return response; }
From source file:org.hoteia.qalingo.web.mvc.controller.customer.CustomerDocumentController.java
@RequestMapping(value = "/documents/**", method = RequestMethod.GET) public ResponseEntity<byte[]> customerDetails(final HttpServletRequest request, final Model model) throws Exception { final RequestData requestData = requestUtil.getRequestData(request); final String requestURL = request.getRequestURL().toString(); final Customer customer = requestData.getCustomer(); if (customer != null) { final List<OrderPurchase> orders = orderPurchaseService .findOrdersByCustomerId(customer.getId().toString()); for (Iterator<OrderPurchase> iterator = orders.iterator(); iterator.hasNext();) { OrderPurchase order = (OrderPurchase) iterator.next(); if (requestURL.contains(order.getPrefixHashFolder())) { String filename = null; String filePath = null; if (requestURL.contains(OrderDocumentType.ORDER_CONFIRMATION.getPropertyKey())) { filename = documentService.buildOrderConfirmationFileName(order); filePath = documentService.getOrderConfirmationFilePath(order); } else if (requestURL.contains(OrderDocumentType.SHIPPING_CONFIRMATION.getPropertyKey())) { filename = documentService.buildShippingConfirmationFileName(order); filePath = documentService.getShippingConfirmationFilePath(order); } else if (requestURL.contains(OrderDocumentType.INVOICE.getPropertyKey())) { filename = documentService.buildInvoiceFileName(order); filePath = documentService.getInvoiceFilePath(order); }/*from w w w . j a v a 2 s. c o m*/ if (StringUtils.isNotEmpty(filename) && StringUtils.isNotEmpty(filePath)) { Path path = Paths.get(filePath); byte[] contents = Files.readAllBytes(path); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType("application/pdf")); headers.setContentDispositionFormData(filename, filename); headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK); return response; } } } logger.warn("This request can't be display, customer " + customer.getEmail() + " is logged, but the Hash doesn't matched:" + requestURL); } else { logger.warn("This request can't be display, customer is not logged:" + requestURL); } return null; }
From source file:org.kuali.student.cm.course.service.impl.AbstractExportCourseHelperImpl.java
/** * Generates a response for the report.//from w w w . j a v a 2s .com * @return */ public ResponseEntity<byte[]> getResponseEntity() { byte[] bytes = getBytes(); HttpHeaders headers = new HttpHeaders(); /* * Setup the header for the response. */ if (isSaveDocument()) { // Try to persuade the agent to save the document (in accordance with http://tools.ietf.org/html/rfc2616#section-19.5.1) headers.setContentType(MediaType.parseMediaType("application/octet-stream")); String contentDisposition = String.format("attachment; filename=%s", getFileName()); headers.set("Content-Disposition", contentDisposition); } else { headers.setContentType(MediaType.parseMediaType(getExportFileType().getMimeType())); headers.setContentDispositionFormData(getFileName(), getFileName()); } headers.setCacheControl(CurriculumManagementConstants.Export.DOCUMENT_DOWNLOAD_CACHE_CONTROL); return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK); }
From source file:org.opentestsystem.authoring.testauth.rest.FileGroupController.java
private static HttpHeaders buildResponseHeaders(final int contentLength, final String filename, final String contentType) { final HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.clear();/*from ww w . j a va2 s . c o m*/ responseHeaders.add(org.apache.http.HttpHeaders.CONTENT_TYPE, contentType); responseHeaders.setPragma("public"); responseHeaders.setCacheControl("no-store, must-revalidate"); responseHeaders.setExpires(Long.valueOf("-1")); responseHeaders.setContentDispositionFormData("attachment", filename); responseHeaders.setContentLength(contentLength); responseHeaders.add(org.apache.http.HttpHeaders.ACCEPT_RANGES, "bytes"); return responseHeaders; }
From source file:org.opentestsystem.authoring.testauth.rest.PublishingRecordController.java
private HttpHeaders buildResponseHeaders(final int contentLength, final String filename) { final HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.clear();/* w ww . java 2 s .c o m*/ responseHeaders.add(org.apache.http.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE); responseHeaders.setPragma("public"); responseHeaders.setCacheControl("no-store, must-revalidate"); responseHeaders.setExpires(Long.valueOf("-1")); responseHeaders.setContentDispositionFormData("inline", filename); responseHeaders.setContentLength(contentLength); responseHeaders.add(org.apache.http.HttpHeaders.ACCEPT_RANGES, "bytes"); return responseHeaders; }
From source file:org.opentestsystem.authoring.testauth.rest.ScoringRuleController.java
private HttpHeaders buildResponseHeaders(final int contentLength, final String filename) { final HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.clear();/*from w w w . j a va 2 s . co m*/ responseHeaders.add(org.apache.http.HttpHeaders.CONTENT_TYPE, com.google.common.net.MediaType.CSV_UTF_8.toString()); responseHeaders.setPragma("public"); responseHeaders.setCacheControl("no-store, must-revalidate"); responseHeaders.setExpires(Long.valueOf("-1")); responseHeaders.setContentDispositionFormData("inline", filename); responseHeaders.setContentLength(contentLength); responseHeaders.add(org.apache.http.HttpHeaders.ACCEPT_RANGES, "bytes"); return responseHeaders; }
From source file:org.opentestsystem.authoring.testspecbank.rest.TestSpecificationController.java
private static HttpHeaders buildResponseHeaders(final int contentLength, final String filename) { final HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.clear();//from www .ja v a 2 s. com responseHeaders.add(org.apache.http.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE); responseHeaders.setPragma("public"); responseHeaders.setCacheControl("no-store, must-revalidate"); responseHeaders.setExpires(Long.valueOf("-1")); responseHeaders.setContentDispositionFormData("inline", filename); responseHeaders.setContentLength(contentLength); responseHeaders.add(org.apache.http.HttpHeaders.ACCEPT_RANGES, "bytes"); return responseHeaders; }
From source file:org.springframework.cloud.stream.app.http.source.DefaultMixedCaseContentTypeHttpHeaderMapper.java
private void setHttpHeader(HttpHeaders target, String name, Object value) { if (ACCEPT.equalsIgnoreCase(name)) { if (value instanceof Collection<?>) { Collection<?> values = (Collection<?>) value; if (!CollectionUtils.isEmpty(values)) { List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>(); for (Object type : values) { if (type instanceof MediaType) { acceptableMediaTypes.add((MediaType) type); } else if (type instanceof String) { acceptableMediaTypes.addAll(MediaType.parseMediaTypes((String) type)); } else { Class<?> clazz = (type != null) ? type.getClass() : null; throw new IllegalArgumentException( "Expected MediaType or String value for 'Accept' header value, but received: " + clazz); }/* w w w.j av a 2 s . com*/ } target.setAccept(acceptableMediaTypes); } } else if (value instanceof MediaType) { target.setAccept(Collections.singletonList((MediaType) value)); } else if (value instanceof String[]) { List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>(); for (String next : (String[]) value) { acceptableMediaTypes.add(MediaType.parseMediaType(next)); } target.setAccept(acceptableMediaTypes); } else if (value instanceof String) { target.setAccept(MediaType.parseMediaTypes((String) value)); } else { Class<?> clazz = (value != null) ? value.getClass() : null; throw new IllegalArgumentException( "Expected MediaType or String value for 'Accept' header value, but received: " + clazz); } } else if (ACCEPT_CHARSET.equalsIgnoreCase(name)) { if (value instanceof Collection<?>) { Collection<?> values = (Collection<?>) value; if (!CollectionUtils.isEmpty(values)) { List<Charset> acceptableCharsets = new ArrayList<Charset>(); for (Object charset : values) { if (charset instanceof Charset) { acceptableCharsets.add((Charset) charset); } else if (charset instanceof String) { acceptableCharsets.add(Charset.forName((String) charset)); } else { Class<?> clazz = (charset != null) ? charset.getClass() : null; throw new IllegalArgumentException( "Expected Charset or String value for 'Accept-Charset' header value, but received: " + clazz); } } target.setAcceptCharset(acceptableCharsets); } } else if (value instanceof Charset[] || value instanceof String[]) { List<Charset> acceptableCharsets = new ArrayList<Charset>(); Object[] values = ObjectUtils.toObjectArray(value); for (Object charset : values) { if (charset instanceof Charset) { acceptableCharsets.add((Charset) charset); } else if (charset instanceof String) { acceptableCharsets.add(Charset.forName((String) charset)); } } target.setAcceptCharset(acceptableCharsets); } else if (value instanceof Charset) { target.setAcceptCharset(Collections.singletonList((Charset) value)); } else if (value instanceof String) { String[] charsets = StringUtils.commaDelimitedListToStringArray((String) value); List<Charset> acceptableCharsets = new ArrayList<Charset>(); for (String charset : charsets) { acceptableCharsets.add(Charset.forName(charset.trim())); } target.setAcceptCharset(acceptableCharsets); } else { Class<?> clazz = (value != null) ? value.getClass() : null; throw new IllegalArgumentException( "Expected Charset or String value for 'Accept-Charset' header value, but received: " + clazz); } } else if (ALLOW.equalsIgnoreCase(name)) { if (value instanceof Collection<?>) { Collection<?> values = (Collection<?>) value; if (!CollectionUtils.isEmpty(values)) { Set<HttpMethod> allowedMethods = new HashSet<HttpMethod>(); for (Object method : values) { if (method instanceof HttpMethod) { allowedMethods.add((HttpMethod) method); } else if (method instanceof String) { allowedMethods.add(HttpMethod.valueOf((String) method)); } else { Class<?> clazz = (method != null) ? method.getClass() : null; throw new IllegalArgumentException( "Expected HttpMethod or String value for 'Allow' header value, but received: " + clazz); } } target.setAllow(allowedMethods); } } else { if (value instanceof HttpMethod) { target.setAllow(Collections.singleton((HttpMethod) value)); } else if (value instanceof HttpMethod[]) { Set<HttpMethod> allowedMethods = new HashSet<HttpMethod>(); Collections.addAll(allowedMethods, (HttpMethod[]) value); target.setAllow(allowedMethods); } else if (value instanceof String || value instanceof String[]) { String[] values = (value instanceof String[]) ? (String[]) value : StringUtils.commaDelimitedListToStringArray((String) value); Set<HttpMethod> allowedMethods = new HashSet<HttpMethod>(); for (String next : values) { allowedMethods.add(HttpMethod.valueOf(next.trim())); } target.setAllow(allowedMethods); } else { Class<?> clazz = (value != null) ? value.getClass() : null; throw new IllegalArgumentException( "Expected HttpMethod or String value for 'Allow' header value, but received: " + clazz); } } } else if (CACHE_CONTROL.equalsIgnoreCase(name)) { if (value instanceof String) { target.setCacheControl((String) value); } else { Class<?> clazz = (value != null) ? value.getClass() : null; throw new IllegalArgumentException( "Expected String value for 'Cache-Control' header value, but received: " + clazz); } } else if (CONTENT_LENGTH.equalsIgnoreCase(name)) { if (value instanceof Number) { target.setContentLength(((Number) value).longValue()); } else if (value instanceof String) { target.setContentLength(Long.parseLong((String) value)); } else { Class<?> clazz = (value != null) ? value.getClass() : null; throw new IllegalArgumentException( "Expected Number or String value for 'Content-Length' header value, but received: " + clazz); } } else if (MessageHeaders.CONTENT_TYPE.equalsIgnoreCase(name)) { if (value instanceof MediaType) { target.setContentType((MediaType) value); } else if (value instanceof String) { target.setContentType(MediaType.parseMediaType((String) value)); } else { Class<?> clazz = (value != null) ? value.getClass() : null; throw new IllegalArgumentException( "Expected MediaType or String value for 'Content-Type' header value, but received: " + clazz); } } else if (DATE.equalsIgnoreCase(name)) { if (value instanceof Date) { target.setDate(((Date) value).getTime()); } else if (value instanceof Number) { target.setDate(((Number) value).longValue()); } else if (value instanceof String) { try { target.setDate(Long.parseLong((String) value)); } catch (NumberFormatException e) { target.setDate(this.getFirstDate((String) value, DATE)); } } else { Class<?> clazz = (value != null) ? value.getClass() : null; throw new IllegalArgumentException( "Expected Date, Number, or String value for 'Date' header value, but received: " + clazz); } } else if (ETAG.equalsIgnoreCase(name)) { if (value instanceof String) { target.setETag((String) value); } else { Class<?> clazz = (value != null) ? value.getClass() : null; throw new IllegalArgumentException( "Expected String value for 'ETag' header value, but received: " + clazz); } } else if (EXPIRES.equalsIgnoreCase(name)) { if (value instanceof Date) { target.setExpires(((Date) value).getTime()); } else if (value instanceof Number) { target.setExpires(((Number) value).longValue()); } else if (value instanceof String) { try { target.setExpires(Long.parseLong((String) value)); } catch (NumberFormatException e) { target.setExpires(this.getFirstDate((String) value, EXPIRES)); } } else { Class<?> clazz = (value != null) ? value.getClass() : null; throw new IllegalArgumentException( "Expected Date, Number, or String value for 'Expires' header value, but received: " + clazz); } } else if (IF_MODIFIED_SINCE.equalsIgnoreCase(name)) { if (value instanceof Date) { target.setIfModifiedSince(((Date) value).getTime()); } else if (value instanceof Number) { target.setIfModifiedSince(((Number) value).longValue()); } else if (value instanceof String) { try { target.setIfModifiedSince(Long.parseLong((String) value)); } catch (NumberFormatException e) { target.setIfModifiedSince(this.getFirstDate((String) value, IF_MODIFIED_SINCE)); } } else { Class<?> clazz = (value != null) ? value.getClass() : null; throw new IllegalArgumentException( "Expected Date, Number, or String value for 'If-Modified-Since' header value, but received: " + clazz); } } else if (IF_UNMODIFIED_SINCE.equalsIgnoreCase(name)) { String ifUnmodifiedSinceValue = null; if (value instanceof Date) { ifUnmodifiedSinceValue = this.formatDate(((Date) value).getTime()); } else if (value instanceof Number) { ifUnmodifiedSinceValue = this.formatDate(((Number) value).longValue()); } else if (value instanceof String) { try { ifUnmodifiedSinceValue = this.formatDate(Long.parseLong((String) value)); } catch (NumberFormatException e) { long longValue = this.getFirstDate((String) value, IF_UNMODIFIED_SINCE); ifUnmodifiedSinceValue = this.formatDate(longValue); } } else { Class<?> clazz = (value != null) ? value.getClass() : null; throw new IllegalArgumentException( "Expected Date, Number, or String value for 'If-Unmodified-Since' header value, but received: " + clazz); } target.set(IF_UNMODIFIED_SINCE, ifUnmodifiedSinceValue); } else if (IF_NONE_MATCH.equalsIgnoreCase(name)) { if (value instanceof String) { target.setIfNoneMatch((String) value); } else if (value instanceof String[]) { String delmitedString = StringUtils.arrayToCommaDelimitedString((String[]) value); target.setIfNoneMatch(delmitedString); } else if (value instanceof Collection) { Collection<?> values = (Collection<?>) value; if (!CollectionUtils.isEmpty(values)) { List<String> ifNoneMatchList = new ArrayList<String>(); for (Object next : values) { if (next instanceof String) { ifNoneMatchList.add((String) next); } else { Class<?> clazz = (next != null) ? next.getClass() : null; throw new IllegalArgumentException( "Expected String value for 'If-None-Match' header value, but received: " + clazz); } } target.setIfNoneMatch(ifNoneMatchList); } } } else if (LAST_MODIFIED.equalsIgnoreCase(name)) { if (value instanceof Date) { target.setLastModified(((Date) value).getTime()); } else if (value instanceof Number) { target.setLastModified(((Number) value).longValue()); } else if (value instanceof String) { try { target.setLastModified(Long.parseLong((String) value)); } catch (NumberFormatException e) { target.setLastModified(this.getFirstDate((String) value, LAST_MODIFIED)); } } else { Class<?> clazz = (value != null) ? value.getClass() : null; throw new IllegalArgumentException( "Expected Date, Number, or String value for 'Last-Modified' header value, but received: " + clazz); } } else if (LOCATION.equalsIgnoreCase(name)) { if (value instanceof URI) { target.setLocation((URI) value); } else if (value instanceof String) { try { target.setLocation(new URI((String) value)); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } } else { Class<?> clazz = (value != null) ? value.getClass() : null; throw new IllegalArgumentException( "Expected URI or String value for 'Location' header value, but received: " + clazz); } } else if (PRAGMA.equalsIgnoreCase(name)) { if (value instanceof String) { target.setPragma((String) value); } else { Class<?> clazz = (value != null) ? value.getClass() : null; throw new IllegalArgumentException( "Expected String value for 'Pragma' header value, but received: " + clazz); } } else if (value instanceof String) { target.set(name, (String) value); } else if (value instanceof String[]) { for (String next : (String[]) value) { target.add(name, next); } } else if (value instanceof Iterable<?>) { for (Object next : (Iterable<?>) value) { String convertedValue = null; if (next instanceof String) { convertedValue = (String) next; } else { convertedValue = this.convertToString(value); } if (StringUtils.hasText(convertedValue)) { target.add(name, convertedValue); } else { logger.warn("Element of the header '" + name + "' with value '" + value + "' will not be set since it is not a String and no Converter is available. " + "Consider registering a Converter with ConversionService (e.g., <int:converter>)"); } } } else { String convertedValue = this.convertToString(value); if (StringUtils.hasText(convertedValue)) { target.set(name, convertedValue); } else { logger.warn("Header '" + name + "' with value '" + value + "' will not be set since it is not a String and no Converter is available. " + "Consider registering a Converter with ConversionService (e.g., <int:converter>)"); } } }