Java Code Examples for org.springframework.http.HttpHeaders#setCacheControl()

The following examples show how to use org.springframework.http.HttpHeaders#setCacheControl() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HeaderAssertionTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void cacheControl() {
	CacheControl control = CacheControl.maxAge(1, TimeUnit.HOURS).noTransform();

	HttpHeaders headers = new HttpHeaders();
	headers.setCacheControl(control.getHeaderValue());
	HeaderAssertions assertions = headerAssertions(headers);

	// Success
	assertions.cacheControl(control);

	try {
		assertions.cacheControl(CacheControl.noStore());
		fail("Wrong value expected");
	}
	catch (AssertionError error) {
		// Expected
	}
}
 
Example 2
Source File: TestCaseController.java    From android-uiconductor with Apache License 2.0 6 votes vote down vote up
@CrossOrigin(origins = "*")
@GetMapping("/getSavedResource")
public ResponseEntity<byte[]> getSavedResource(@RequestParam(value = "path") String path) {
  HttpStatus httpStatus = HttpStatus.OK;
  byte[] media = new byte[0];
  try (InputStream in =
      new FileInputStream(Paths.get(URLDecoder.decode(path, "UTF-8")).toString())) {
    media = ByteStreams.toByteArray(in);
  } catch (IOException e) {
    httpStatus = HttpStatus.NOT_FOUND;
    logger.warning("Cannot fetch image: " + path);
  }
  HttpHeaders headers = new HttpHeaders();
  headers.setCacheControl(CacheControl.noCache().getHeaderValue());
  headers.setContentType(MediaType.IMAGE_JPEG);
  return new ResponseEntity<>(media, headers, httpStatus);
}
 
Example 3
Source File: HeaderAssertionTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void cacheControl() {
	CacheControl control = CacheControl.maxAge(1, TimeUnit.HOURS).noTransform();

	HttpHeaders headers = new HttpHeaders();
	headers.setCacheControl(control.getHeaderValue());
	HeaderAssertions assertions = headerAssertions(headers);

	// Success
	assertions.cacheControl(control);

	try {
		assertions.cacheControl(CacheControl.noStore());
		fail("Wrong value expected");
	}
	catch (AssertionError error) {
		// Expected
	}
}
 
Example 4
Source File: WindowRestController.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 6 votes vote down vote up
@GetMapping("/{windowId}/{documentId}/print/{filename:.*}")
public ResponseEntity<byte[]> getDocumentPrint(
		@PathVariable("windowId") final String windowIdStr //
		, @PathVariable("documentId") final String documentIdStr //
		, @PathVariable("filename") final String filename)
{
	userSession.assertLoggedIn();

	final WindowId windowId = WindowId.fromJson(windowIdStr);
	final DocumentPath documentPath = DocumentPath.rootDocumentPath(windowId, documentIdStr);

	final DocumentPrint documentPrint = documentCollection.createDocumentPrint(documentPath);
	final byte[] reportData = documentPrint.getReportData();
	final String reportContentType = documentPrint.getReportContentType();

	final HttpHeaders headers = new HttpHeaders();
	headers.setContentType(MediaType.parseMediaType(reportContentType));
	headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"");
	headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
	final ResponseEntity<byte[]> response = new ResponseEntity<>(reportData, headers, HttpStatus.OK);
	return response;
}
 
Example 5
Source File: DocumentAttachmentsRestController.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 6 votes vote down vote up
private static ResponseEntity<byte[]> extractResponseEntryFromData(@NonNull final IDocumentAttachmentEntry entry)
{
	final String entryFilename = entry.getFilename();
	final byte[] entryData = entry.getData();
	if (entryData == null || entryData.length == 0)
	{
		throw new EntityNotFoundException("No attachment found")
				.setParameter("entry", entry)
				.setParameter("reason", "data is null or empty");
	}

	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;
}
 
Example 6
Source File: ICaptchaService.java    From mica with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 图片输出的头,避免验证码被缓存
 *
 * @return {HttpHeaders}
 */
default HttpHeaders getCaptchaHeaders() {
	HttpHeaders headers = new HttpHeaders();
	headers.setPragma("no-cache");
	headers.setCacheControl("no-cache");
	headers.setExpires(0);
	headers.setContentType(MediaType.IMAGE_JPEG);
	return headers;
}
 
Example 7
Source File: MigrationScriptRestController.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
private ResponseEntity<byte[]> getScript(@NonNull final Path scriptPath, final boolean inline)
{
	final String contentDispositionType = inline ? "inline" : "attachment";
	final byte[] content = getScriptContent(scriptPath);

	final HttpHeaders headers = new HttpHeaders();
	headers.setContentType(MediaType.TEXT_PLAIN);
	headers.set(HttpHeaders.CONTENT_DISPOSITION, contentDispositionType + "; filename=\"" + scriptPath.getFileName() + "\"");
	headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
	final ResponseEntity<byte[]> response = new ResponseEntity<>(content, headers, HttpStatus.OK);
	return response;
}
 
Example 8
Source File: ViewRestController.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
@GetMapping("/{viewId}/export/excel")
public ResponseEntity<Resource> exportToExcel(
		@PathVariable("windowId") final String windowIdStr,
		@PathVariable(PARAM_ViewId) final String viewIdStr,
		@RequestParam(name = "selectedIds", required = false) @ApiParam("comma separated IDs") final String selectedIdsListStr)
		throws Exception
{
	userSession.assertLoggedIn();

	final ViewId viewId = ViewId.ofViewIdString(viewIdStr, WindowId.fromJson(windowIdStr));

	final ExcelFormat excelFormat = ExcelFormats.getDefaultFormat();
	final File tmpFile = File.createTempFile("exportToExcel", "." + excelFormat.getFileExtension());

	try (final FileOutputStream out = new FileOutputStream(tmpFile))
	{
		ViewExcelExporter.builder()
				.excelFormat(excelFormat)
				.view(viewsRepo.getView(viewId))
				.rowIds(DocumentIdsSelection.ofCommaSeparatedString(selectedIdsListStr))
				.layout(viewsRepo.getViewLayout(viewId.getWindowId(), JSONViewDataType.grid, ViewProfileId.NULL))
				.language(userSession.getLanguage())
				.zoneId(userSession.getTimeZone())
				.build()
				.export(out);
	}

	final String filename = "report." + excelFormat.getFileExtension(); // TODO: use a better name
	final String contentType = MimeType.getMimeType(filename);
	final HttpHeaders headers = new HttpHeaders();
	headers.setContentType(MediaType.parseMediaType(contentType));
	headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"");
	headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");

	final ResponseEntity<Resource> response = new ResponseEntity<>(new InputStreamResource(new FileInputStream(tmpFile)), headers, HttpStatus.OK);
	return response;
}
 
Example 9
Source File: LetterRestController.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 10
Source File: ProcessRestController.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
@ApiOperation("Retrieves and serves a report that was previously created by a reporting process.")
@GetMapping("/{processId}/{pinstanceId}/print/{filename:.*}")
public ResponseEntity<byte[]> getReport(
		@PathVariable("processId") final String processIdStr,
		@PathVariable("pinstanceId") final String pinstanceIdStr,
		@PathVariable("filename") final String filename)
{
	final ProcessId processId = ProcessId.fromJson(processIdStr);
	final DocumentId pinstanceId = DocumentId.of(pinstanceIdStr);

	try (final MDCCloseable pinstanceMDC = TableRecordMDC.putTableRecordReference(I_AD_PInstance.Table_Name, PInstanceId.ofRepoIdOrNull(pinstanceId.toIntOr(-1)));
			final MDCCloseable processMDC = TableRecordMDC.putTableRecordReference(I_AD_Process.Table_Name, processId.toAdProcessId()))
	{
		userSession.assertLoggedIn();

		final IProcessInstancesRepository instancesRepository = getRepository(processId);
		final ProcessInstanceResult executionResult = instancesRepository.forProcessInstanceReadonly(pinstanceId, processInstance -> processInstance.getExecutionResult());

		final OpenReportAction action = executionResult.getAction(OpenReportAction.class);
		final String reportFilename = action.getFilename();
		final String reportContentType = action.getContentType();
		final byte[] reportData = action.getReportData();

		final String reportFilenameEffective = CoalesceUtil.coalesce(filename, reportFilename, "");

		final HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.parseMediaType(reportContentType));
		headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + reportFilenameEffective + "\"");
		headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
		final ResponseEntity<byte[]> response = new ResponseEntity<>(reportData, headers, HttpStatus.OK);
		return response;
	}
}
 
Example 11
Source File: MessageBundleController.java    From attic-rave with Apache License 2.0 5 votes vote down vote up
public MessageBundleController() {
    clientMessagesCache = new HashMap<Locale, String>();
    acceptHeaderLocaleResolver = new AcceptHeaderLocaleResolver();
    clientMessagesResponseHeaders = new HttpHeaders();

    // set the common response headers that will be used by the getClientMessages response
    clientMessagesResponseHeaders.setCacheControl("max-age=" + CLIENT_MESSAGE_BUNDLE_CACHE_CONTROL_MAX_AGE);
    clientMessagesResponseHeaders.setContentType(MediaType.parseMediaType(JAVASCRIPT_CONTENT_TYPE));
    Locale.setDefault(Locale.ENGLISH);
}
 
Example 12
Source File: MessageBundleControllerTest.java    From attic-rave with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {        
    messageBundleController = new MessageBundleController();
    request = new MockHttpServletRequest();

    expectedHeaders = new HttpHeaders();
    expectedHeaders.setCacheControl("max-age=" + EXPECTED_CLIENT_MESSAGE_BUNDLE_MAX_AGE);
    expectedHeaders.setContentType(MediaType.parseMediaType(EXPECTED_JAVASCRIPT_CONTENT_TYPE));
}
 
Example 13
Source File: PhotographController.java    From fenixedu-academic with GNU Lesser General Public License v3.0 4 votes vote down vote up
@RequestMapping(value = "{username:.+}", method = RequestMethod.GET)
public ResponseEntity<byte[]> get(@PathVariable String username, @RequestParam(value = "s", required = false,
        defaultValue = "100") Integer size, @RequestHeader(value = "If-None-Match", required = false) String ifNoneMatch)
        throws IOException {

    if (size <= 0) {
        size = 100;
    }
    if (size > 512) {
        size = 512;
    }

    User user = User.findByUsername(username);

    if (user != null && user.getPerson() != null) {
        final Photograph personalPhoto =
                user.getPerson().isPhotoAvailableToCurrentUser() ? user.getPerson().getPersonalPhoto() : null;

        HttpHeaders headers = new HttpHeaders();
        String etag = "W/\"" + (personalPhoto == null ? "mm-av" : personalPhoto.getExternalId()) + "-" + size + "\"";
        headers.setETag(etag);
        headers.setExpires(DateTime.now().plusWeeks(2).getMillis());
        headers.setCacheControl("max-age=1209600");

        if (etag.equals(ifNoneMatch)) {
            return new ResponseEntity<>(headers, HttpStatus.NOT_MODIFIED);
        }

        if (personalPhoto != null) {
            headers.set("Content-Type", personalPhoto.getOriginal().getPictureFileFormat().getMimeType());
            return new ResponseEntity<>(personalPhoto.getCustomAvatar(size, size, PictureMode.ZOOM), headers, HttpStatus.OK);
        } else {
            try (InputStream mm =
                    PhotographController.class.getClassLoader().getResourceAsStream("META-INF/resources/img/mysteryman.png")) {
                headers.set("Content-Type", "image/png");
                return new ResponseEntity<>(Avatar.process(mm, "image/png", size), headers, HttpStatus.OK);
            }
        }
    }

    throw BennuCoreDomainException.resourceNotFound(username);
}