Example usage for org.springframework.http HttpHeaders setCacheControl

List of usage examples for org.springframework.http HttpHeaders setCacheControl

Introduction

In this page you can find the example usage for org.springframework.http HttpHeaders setCacheControl.

Prototype

public void setCacheControl(@Nullable String cacheControl) 

Source Link

Document

Set the (new) value of the Cache-Control header.

Usage

From source file:org.lightadmin.core.web.util.ResponseUtils.java

public static HttpHeaders octetStreamResponseHeader(MediaType mediaType, long length, String eTag) {
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentLength(length);
    responseHeaders.setContentType(mediaType);
    responseHeaders.setCacheControl("max-age");
    if (isNotBlank(eTag)) {
        responseHeaders.setETag(eTag);//w w  w .  j  a v  a  2s.  c  o  m
    }
    responseHeaders.set("Content-Disposition", "inline; filename=\"file.jpg\"");
    return responseHeaders;
}

From source file:aiai.ai.launchpad.server.ServerController.java

private static HttpHeaders getHeader(long length) {
    HttpHeaders header = new HttpHeaders();
    header.setContentLength(length);/* w  w w .j  a v a2  s  .  co  m*/
    header.setCacheControl("max-age=0");
    header.setExpires(0);
    header.setPragma("no-cache");

    return header;
}

From source file:com.opopov.cloud.image.service.ImageStitchingServiceImpl.java

@Override
public DeferredResult<ResponseEntity<?>> getStitchedImage(@RequestBody ImageStitchingConfiguration config) {

    validator.validateConfig(config);/*from   ww  w .j a  v a  2 s  . com*/

    List<ListenableFuture<ResponseEntity<byte[]>>> futures = config.getUrlList().stream()
            .map(url -> remoteResource.getForEntity(url, byte[].class)).collect(Collectors.toList());

    //wrap the listenable futures into the completable futures
    //writing loop in pre-8 style, since it would be more concise compared to stream api in this case
    CompletableFuture[] imageFutures = new CompletableFuture[futures.size()];
    int taskIndex = 0;
    IndexMap indexMap = new IndexMap(config.getRowCount() * config.getColumnCount());
    for (ListenableFuture<ResponseEntity<byte[]>> f : futures) {
        imageFutures[taskIndex] = imageDataFromResponse(taskIndex, indexMap, utils.fromListenableFuture(f));
        taskIndex++;
    }

    CompletableFuture<Void> allDownloadedAndDecompressed = CompletableFuture.allOf(imageFutures);

    //Synchronous part - start - writing decompressed bytes to the large image
    final int DOWNLOAD_AND_DECOMPRESS_TIMEOUT = 30; //30 seconds for each of the individual tasks
    DeferredResult<ResponseEntity<?>> response = new DeferredResult<>();
    boolean allSuccessful = false;
    byte[] imageBytes = null;
    try {
        Void finishResult = allDownloadedAndDecompressed.get(DOWNLOAD_AND_DECOMPRESS_TIMEOUT, TimeUnit.SECONDS);

        imageBytes = combineImagesIntoStitchedImage(config, indexMap);

        HttpHeaders headers = new HttpHeaders();
        headers.setCacheControl(CacheControl.noCache().getHeaderValue());
        headers.setContentType(MediaType.IMAGE_JPEG);
        allSuccessful = true;
    } catch (InterruptedException | ExecutionException e) {
        // basically either download or decompression of the source image failed
        // just skip it then, we have no image to show
        response.setErrorResult(
                new SourceImageLoadException("Unable to load and decode one or more source images", e));
    } catch (TimeoutException e) {
        //send timeout response, via ImageLoadTimeoutException
        response.setErrorResult(new ImageLoadTimeoutException(
                String.format("Some of the images were not loaded and decoded before timeout of %d seconds",
                        DOWNLOAD_AND_DECOMPRESS_TIMEOUT),
                e

        ));
    } catch (IOException e) {
        response.setErrorResult(new ImageWriteException("Error writing image into output buffer", e));
    }

    //Synchronous part - end

    if (!allSuccessful) {
        //shoud not get here, some unknown error
        response.setErrorResult(
                new ImageLoadTimeoutException("Unknown error", new RuntimeException("Something went wrong")

                ));

        return response;
    }

    ResponseEntity<?> successResult = ResponseEntity.ok(imageBytes);
    response.setResult(successResult);

    return response;

}

From source file:de.metas.ui.web.upload.ImageRestController.java

@GetMapping("/{imageId}")
@ResponseBody/* w w w  .j  a va 2  s  . c  om*/
public ResponseEntity<byte[]> getImage(@PathVariable final int imageId) {
    userSession.assertLoggedIn();

    if (imageId <= 0) {
        throw new IllegalArgumentException("Invalid image id");
    }

    final MImage adImage = MImage.get(userSession.getCtx(), imageId);
    if (adImage == null || adImage.getAD_Image_ID() <= 0) {
        throw new EntityNotFoundException("Image id not found: " + imageId);
    }

    final boolean hasAccess = userSession.getUserRolePermissions().canView(adImage.getAD_Client_ID(),
            adImage.getAD_Org_ID(), I_AD_Image.Table_ID, adImage.getAD_Image_ID());
    if (!hasAccess) {
        throw new EntityNotFoundException("Image id not found: " + imageId);
    }

    final String imageName = adImage.getName();
    final byte[] imageData = adImage.getData();
    final String contentType = MimeType.getMimeType(imageName);

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType(contentType));
    headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + imageName + "\"");
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    final ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(imageData, headers, HttpStatus.OK);
    return response;
}

From source file:io.pivotal.receptor.client.ReceptorClient.java

@Override
public void upsertDomain(String domain, int ttl) {
    HttpHeaders headers = new HttpHeaders();
    if (ttl != 0) {
        headers.setCacheControl(String.format("max-age=%d", ttl));
    }//from   ww w.  j av  a  2  s. co  m
    HttpEntity<String> request = new HttpEntity<String>(headers);
    restTemplate.put("{baseUrl}/domains/{domain}", request, baseUrl, domain);
}

From source file:io.github.autsia.crowly.controllers.DashboardController.java

@RequestMapping(value = "/campaigns/export/{campaignId}", method = RequestMethod.GET)
public ResponseEntity<byte[]> export(@PathVariable("campaignId") String campaignId, ModelMap model)
        throws DocumentException {
    Document document = new Document();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, byteArrayOutputStream);
    document.open();//from   ww w .j  ava2s. co  m
    Gson gson = new Gson();
    String json = gson.toJson(mentionRepository.findByCampaignId(campaignId));
    document.add(new Paragraph(json));
    document.close();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers,
            HttpStatus.OK);
    return response;
}

From source file:com.alehuo.wepas2016projekti.controller.ImageController.java

/**
 * Hakee tietokannasta kuvan. Kuvan hakemisessa hydynnetn ETag
 * -otsaketta.//from  www .  j  a  v a  2  s .c o m
 *
 * @param a Autentikointi
 * @param imageUuid Kuvan UUID
 * @param ifNoneMatch If-None-Match -headeri vlimuistia varten
 * @return Kuva
 */
@RequestMapping(value = "/{imageUuid}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<byte[]> getImage(Authentication a, @PathVariable String imageUuid,
        @RequestHeader(required = false, value = "If-None-Match") String ifNoneMatch) {
    if (ifNoneMatch != null) {
        //            LOG.log(Level.INFO, "Kuva ''{0}'' loytyy kayttajan selaimen valimuistista eika sita tarvitse ladata. Kuvaa pyysi kayttaja ''{1}''", new Object[]{imageUuid, a.getName()});
        //Jos If-None-Match -headeri lytyy, niin lhet NOT MODIFIED vastaus
        return new ResponseEntity<>(HttpStatus.NOT_MODIFIED);
    }
    Image i = imageService.findOneImageByUuid(imageUuid);
    if (i != null && i.isVisible()) {
        //Luodaan ETag kuvalle
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(i.getContentType()));
        headers.setContentLength(i.getImageData().length);
        headers.setCacheControl("public");
        headers.setExpires(Long.MAX_VALUE);
        headers.setETag("\"" + imageUuid + "\"");
        //            LOG.log(Level.INFO, "Kuva ''{0}'' loytyi tietokannasta, ja sita pyysi kayttaja ''{1}''", new Object[]{imageUuid, a.getName()});
        //Palautetaan kuva uutena resurssina
        return new ResponseEntity<>(i.getImageData(), headers, HttpStatus.CREATED);
    } else {
        //Jos kuvaa ei lydy tietokannasta
        LOG.log(Level.WARNING, "Kuvaa ''{0}'' ei loytynyt tietokannasta, ja sita pyysi kayttaja ''{1}''",
                new Object[] { imageUuid, a.getName() });
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}

From source file:net.solarnetwork.node.setup.web.NodeCertificatesController.java

/**
 * Return a node's current certificate./*from   ww  w  .j a va2  s.  com*/
 * 
 * @return a map with the PEM encoded certificate on key {@code cert} if
 *         {@code download} is not <em>true</em>, otherwise the content is
 *         returned as a file attachment
 */
@RequestMapping(value = "/nodeCert", method = RequestMethod.GET)
@ResponseBody
public Object viewNodeCert(@RequestParam(value = "download", required = false) final Boolean download,
        @RequestParam(value = "chain", required = false) final Boolean asChain) {
    final String cert = (Boolean.TRUE.equals(asChain) ? pkiService.generateNodePKCS7CertificateChainString()
            : pkiService.generateNodePKCS7CertificateString());

    if (!Boolean.TRUE.equals(download)) {
        Map<String, Object> result = new HashMap<String, Object>(1);
        result.put("cert", cert);
        return result;
    }

    HttpHeaders headers = new HttpHeaders();
    headers.setContentLength(cert.length());
    headers.setContentType(MediaType.parseMediaType("application/x-pem-file"));
    headers.setLastModified(System.currentTimeMillis());
    headers.setCacheControl("no-cache");

    headers.set("Content-Disposition",
            "attachment; filename=solarnode-" + getIdentityService().getNodeId() + ".pem");

    return new ResponseEntity<String>(cert, headers, HttpStatus.OK);
}

From source file:de.metas.ui.web.process.ProcessRestController.java

@RequestMapping(value = "/{processId}/{pinstanceId}/print/{filename:.*}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getReport(@PathVariable("processId") final int processId_NOTUSED //
        , @PathVariable("pinstanceId") final int pinstanceId //
        , @PathVariable("filename") final String filename //
) {/*  w  w w.  j  a  v a2 s  .  c  om*/
    final ProcessInstanceResult executionResult = instancesRepository.forProcessInstanceReadonly(pinstanceId,
            processInstance -> processInstance.getExecutionResult());

    final String reportFilename = executionResult.getReportFilename();
    final String reportContentType = executionResult.getReportContentType();
    final byte[] reportData = executionResult.getReportData();

    final String reportFilenameEffective = Util.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;
}

From source file:de.metas.ui.web.window.controller.WindowRestController.java

@RequestMapping(value = "/{windowId}/{documentId}/print/{filename:.*}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getDocumentPrint(@PathVariable("windowId") final int adWindowId //
        , @PathVariable("documentId") final String documentId //
        , @PathVariable("filename") final String filename) {
    userSession.assertLoggedIn();//  w ww .ja v  a2  s .com

    final DocumentPath documentPath = DocumentPath.rootDocumentPath(DocumentType.Window, adWindowId,
            documentId);

    final Document document = documentCollection.getDocument(documentPath);
    final DocumentEntityDescriptor entityDescriptor = document.getEntityDescriptor();

    final ProcessExecutionResult processExecutionResult = ProcessInfo.builder().setCtx(userSession.getCtx())
            .setAD_Process_ID(entityDescriptor.getPrintProcessId())
            .setRecord(entityDescriptor.getTableName(), document.getDocumentIdAsInt()).setPrintPreview(true)
            .setJRDesiredOutputType(OutputType.PDF)
            //
            .buildAndPrepareExecution().onErrorThrowException().switchContextWhenRunning().executeSync()
            .getResult();

    final byte[] reportData = processExecutionResult.getReportData();
    final String reportContentType = processExecutionResult.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;
}