org.springframework.http.HttpHeaders#setCacheControl ( )源码实例Demo

下面列出了org.springframework.http.HttpHeaders#setCacheControl ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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
	}
}
 
源代码2 项目: android-uiconductor   文件: TestCaseController.java
@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);
}
 
@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
	}
}
 
@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;
}
 
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;
}
 
源代码6 项目: mica   文件: ICaptchaService.java
/**
 * 图片输出的头,避免验证码被缓存
 *
 * @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;
}
 
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;
}
 
@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;
}
 
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;
}
 
@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;
	}
}
 
源代码11 项目: attic-rave   文件: MessageBundleController.java
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);
}
 
源代码12 项目: attic-rave   文件: MessageBundleControllerTest.java
@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));
}
 
源代码13 项目: fenixedu-academic   文件: PhotographController.java
@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);
}