Example usage for org.springframework.web.context.request WebRequest checkNotModified

List of usage examples for org.springframework.web.context.request WebRequest checkNotModified

Introduction

In this page you can find the example usage for org.springframework.web.context.request WebRequest checkNotModified.

Prototype

boolean checkNotModified(String etag);

Source Link

Document

Check whether the requested resource has been modified given the supplied ETag (entity tag), as determined by the application.

Usage

From source file:ru.org.linux.topic.TopicController.java

private static boolean checkLastModified(WebRequest webRequest, Topic message) {
    try {/*  w  w w. j  a  v  a 2  s .com*/
        return webRequest.checkNotModified(message.getLastModified().getTime());
    } catch (IllegalArgumentException ignored) {
        return false;
    }
}

From source file:org.ng200.openolympus.controller.TranslationController.java

@RequestMapping(value = "/translation")
public Map<String, String> strings(WebRequest webRequest, @RequestParam("lang") String lang) {
    if (webRequest.checkNotModified(this.messageSource.getLastModified())) {
        return null;
    }//from  w  w  w. ja v  a  2  s . c  om
    final HashMap<String, String> map = new HashMap<>();
    for (final Entry<Object, Object> e : this.messageSource.getKeys(new Locale(lang)).entrySet()) {
        map.put(e.getKey().toString(), e.getValue().toString());
    }
    return map;
}

From source file:org.craftercms.core.controller.rest.ContentStoreRestController.java

private boolean checkNotModified(long lastModifiedTimestamp, WebRequest request, HttpServletResponse response) {
    response.setHeader(CACHE_CONTROL_HEADER_NAME, MUST_REVALIDATE_HEADER_VALUE);

    return request.checkNotModified(lastModifiedTimestamp);
}

From source file:github.priyatam.springrest.resource.PolicyResource.java

@RequestMapping(method = RequestMethod.GET, value = "/policy/{policyNum}")
@ResponseBody//w ww  .j  a v  a2s.com
public ResponseEntity<Policy> get(@PathVariable String policyNum, WebRequest request) {
    logger.debug("Retrieving Policy :" + policyNum);

    if (request.checkNotModified(resourceHelper.lastModified(policyNum))) {
        // shortcut exit - no further processing necessary
        return null;
    }

    // Load Policy
    Policy policy = persistenceHelper.loadPolicy(policyNum);
    if (policy == null) {
        logger.warn("No Policy found");
        return new ResponseEntity<Policy>(null, new HttpHeaders(), HttpStatus.NOT_FOUND);
    }

    // Convert to Restful Resource, update ETag and HATEOAS references
    responseBuilder.toPolicy(policy);

    return new ResponseEntity<Policy>(policy, HttpStatus.OK);
}

From source file:com.goldengekko.meetr.web.EndpointsController.java

@RestReturn(value = JEndpoints.class, code = { @RestCode(code = 200, description = "OK", message = "OK") })
@RequestMapping(method = RequestMethod.GET)
@ResponseBody/*w w  w .j a  va2s. c  o m*/
public JEndpoints getEndpoints(WebRequest webRequest) throws ParseException {
    Date updatedDate = FORMATTER.parse(updatedYYYYMMddHHmmss);
    final JEndpoints body = new JEndpoints(apiUrl, signinUrl, oauthUrl, updatedDate.getTime());

    final long lastModified = body.getUpdatedDate();
    if (webRequest.checkNotModified(lastModified)) {
        // shortcut exit - no further processing necessary
        return null;
    }

    return body;
}

From source file:com.orangeandbronze.jblubble.sample.PersonController.java

@RequestMapping(method = RequestMethod.GET, value = "/{id}/photo")
public void servePhoto(@PathVariable("id") String id, WebRequest webRequest, HttpServletResponse response)
        throws BlobstoreException, IOException {
    Person person = getPersonById(id);//w  w  w . j  a  va  2  s. co m
    if (person != null) {
        BlobKey photoId = person.getPhotoId();
        if (photoId != null) {
            BlobInfo blobInfo = blobstoreService.getBlobInfo(photoId);
            if (webRequest.checkNotModified(blobInfo.getDateCreated().getTime())) {
                return;
            }
            response.setContentType(blobInfo.getContentType());
            // In Servlet API 3.1, use #setContentLengthLong(long)
            response.setContentLength((int) blobInfo.getSize());
            response.setDateHeader("Last-Modified", blobInfo.getDateCreated().getTime());
            // response.addHeader("Cache-Control", "must-revalidate, max-age=3600");
            blobstoreService.serveBlob(photoId, response.getOutputStream());
            return;
        }
    }
    throw new IllegalArgumentException();
}

From source file:bjerne.gallery.controller.GalleryController.java

/**
 * Method used to return the binary of a gallery file (
 * {@link GalleryFile#getActualFile()} ). This method handles 304 redirects
 * (if file has not changed) and range headers if requested by browser. The
 * range parts is particularly important for videos. The correct response
 * status is set depending on the circumstances.
 * <p>//from  w  w  w.j a  v  a 2s. c o m
 * NOTE: the range logic should NOT be considered a complete implementation
 * - it's a bare minimum for making requests for byte ranges work.
 * 
 * @param request
 *            Request
 * @param galleryFile
 *            Gallery file
 * @return The binary of the gallery file, or a 304 redirect, or a part of
 *         the file.
 * @throws IOException
 *             If there is an issue accessing the binary file.
 */
private ResponseEntity<InputStreamResource> returnResource(WebRequest request, GalleryFile galleryFile)
        throws IOException {
    LOG.debug("Entering returnResource()");
    if (request.checkNotModified(galleryFile.getActualFile().lastModified())) {
        return null;
    }
    File file = galleryFile.getActualFile();
    String contentType = galleryFile.getContentType();
    String rangeHeader = request.getHeader(HttpHeaders.RANGE);
    long[] ranges = getRangesFromHeader(rangeHeader);
    long startPosition = ranges[0];
    long fileTotalSize = file.length();
    long endPosition = ranges[1] != 0 ? ranges[1] : fileTotalSize - 1;
    long contentLength = endPosition - startPosition + 1;
    LOG.debug("contentLength: {}, file length: {}", contentLength, fileTotalSize);

    LOG.debug("Returning resource {} as inputstream. Start position: {}", file.getCanonicalPath(),
            startPosition);
    InputStream boundedInputStream = new BoundedInputStream(new FileInputStream(file), endPosition + 1);

    InputStream is = new BufferedInputStream(boundedInputStream, 65536);
    InputStreamResource inputStreamResource = new InputStreamResource(is);
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentLength(contentLength);
    responseHeaders.setContentType(MediaType.valueOf(contentType));
    responseHeaders.add(HttpHeaders.ACCEPT_RANGES, "bytes");
    if (StringUtils.isNotBlank(rangeHeader)) {
        is.skip(startPosition);
        String contentRangeResponseHeader = "bytes " + startPosition + "-" + endPosition + "/" + fileTotalSize;
        responseHeaders.add(HttpHeaders.CONTENT_RANGE, contentRangeResponseHeader);
        LOG.debug("{} was not null but {}. Adding header {} to response: {}", HttpHeaders.RANGE, rangeHeader,
                HttpHeaders.CONTENT_RANGE, contentRangeResponseHeader);
    }
    HttpStatus status = (startPosition == 0 && contentLength == fileTotalSize) ? HttpStatus.OK
            : HttpStatus.PARTIAL_CONTENT;
    LOG.debug("Returning {}. Status: {}, content-type: {}, {}: {}, contentLength: {}", file, status,
            contentType, HttpHeaders.CONTENT_RANGE, responseHeaders.get(HttpHeaders.CONTENT_RANGE),
            contentLength);
    return new ResponseEntity<InputStreamResource>(inputStreamResource, responseHeaders, status);
}

From source file:org.focusns.web.modules.profile.ProjectUserWidget.java

@RequestMapping("/user-avatar/download")
public ResponseEntity<byte[]> doAvatar(@RequestParam Long userId, @RequestParam(required = false) Boolean temp,
        @RequestParam(required = false) Integer width, @RequestParam(required = false) Integer height,
        WebRequest webRequest) throws IOException {
    ////  w  ww  .  j  a  va  2  s  .  c  o  m
    boolean notModified = false;
    InputStream inputStream = null;
    //
    ProjectUser projectUser = projectUserService.getProjectUser(userId);
    Object[] avatarCoordinates = CoordinateHelper.getAvatarCoordinates(projectUser);
    if (temp != null && temp.booleanValue()) {
        long lastModified = storageService.checkTempResource(avatarCoordinates);
        if (lastModified > 0 && webRequest.checkNotModified(lastModified)) {
            notModified = true;
        } else {
            inputStream = storageService.loadTempResource(avatarCoordinates);
        }
    } else if (width == null || height == null) {
        long lastModified = storageService.checkResource(avatarCoordinates);
        if (lastModified > 0 && webRequest.checkNotModified(lastModified)) {
            notModified = true;
        } else {
            inputStream = storageService.loadResource(avatarCoordinates);
        }
    } else {
        Object size = width + "x" + height;
        long lastModified = storageService.checkSizedResource(size, avatarCoordinates);
        if (lastModified > 0 && webRequest.checkNotModified(lastModified)) {
            notModified = true;
        } else {
            inputStream = storageService.loadSizedResource(size, avatarCoordinates);
        }
    }
    //
    if (notModified) {
        return new ResponseEntity<byte[]>(HttpStatus.NOT_MODIFIED);
    }
    //
    return WebUtils.getResponseEntity(FileCopyUtils.copyToByteArray(inputStream), MediaType.IMAGE_PNG);
}

From source file:com.vmware.appfactory.application.controller.AppApiController.java

/**
 * Get a single application, in our own JSON format.
 *
 * @param id Application ID./*from   w  ww  .  j av  a2  s  .c om*/
 * @return
 */
@ResponseBody
@RequestMapping(value = "/apps/{id}", method = RequestMethod.GET)
@Nullable
public Application getApplication(@PathVariable Long id, @Nonnull WebRequest webRequest)
        throws AfNotFoundException {
    // Finding lastUpdated on this table is slower than fetching the record by PK.
    Application app = _daoFactory.getApplicationDao().find(id);
    if (app == null) {
        throw new AfNotFoundException("Invalid app Id " + id);
    }
    long lastModified = app.getModified();
    if (0 != lastModified && webRequest.checkNotModified(lastModified)) {
        // shortcut exit - no further processing necessary
        return null;
    }

    return app;
}

From source file:org.fao.geonet.api.groups.GroupsApi.java

/**
 * Writes the group logo image to the response. If no image is found it
 * writes a 1x1 transparent PNG. If the request contain cache related
 * headers it checks if the resource has changed and return a 304 Not
 * Modified response if not changed.//ww  w  . j  a  v  a 2s. com
 *
 * @param groupId    the group identifier.
 * @param webRequest the web request.
 * @param request    the native HTTP Request.
 * @param response   the servlet response.
 * @throws ResourceNotFoundException if no group exists with groupId.
 */
@ApiOperation(value = "Get the group logo image.", nickname = "get", notes = API_GET_LOGO_NOTE)
@RequestMapping(value = "/{groupId}/logo", method = RequestMethod.GET)
public void getGroupLogo(
        @ApiParam(value = "Group identifier", required = true) @PathVariable(value = "groupId") final Integer groupId,
        @ApiIgnore final WebRequest webRequest, HttpServletRequest request, HttpServletResponse response)
        throws ResourceNotFoundException {

    Locale locale = languageUtils.parseAcceptLanguage(request.getLocales());

    ApplicationContext context = ApplicationContextHolder.get();
    ServiceContext serviceContext = ApiUtils.createServiceContext(request, locale.getISO3Country());
    if (context == null) {
        throw new RuntimeException("ServiceContext not available");
    }

    GroupRepository groupRepository = context.getBean(GroupRepository.class);

    Group group = groupRepository.findOne(groupId);
    if (group == null) {
        throw new ResourceNotFoundException(
                messages.getMessage("api.groups.group_not_found", new Object[] { groupId }, locale));
    }
    try {
        final Path logosDir = Resources.locateLogosDir(serviceContext);
        final Path harvesterLogosDir = Resources.locateHarvesterLogosDir(serviceContext);
        final String logoUUID = group.getLogo();
        Path imagePath = null;
        FileTime lastModifiedTime = null;
        if (StringUtils.isNotBlank(logoUUID) && !logoUUID.startsWith("http://")
                && !logoUUID.startsWith("https//")) {
            imagePath = Resources.findImagePath(logoUUID, logosDir);
            if (imagePath == null) {
                imagePath = Resources.findImagePath(logoUUID, harvesterLogosDir);
            }
            if (imagePath != null) {
                lastModifiedTime = Files.getLastModifiedTime(imagePath);
                if (webRequest.checkNotModified(lastModifiedTime.toMillis())) {
                    // webRequest.checkNotModified sets the right HTTP headers
                    response.setDateHeader("Expires", System.currentTimeMillis() + SIX_HOURS * 1000L);

                    return;
                }
                response.setContentType(AttachmentsApi.getFileContentType(imagePath));
                response.setContentLength((int) Files.size(imagePath));
                response.addHeader("Cache-Control", "max-age=" + SIX_HOURS + ", public");
                response.setDateHeader("Expires", System.currentTimeMillis() + SIX_HOURS * 1000L);
                FileUtils.copyFile(imagePath.toFile(), response.getOutputStream());
            }
        }

        if (imagePath == null) {
            // no logo image found. Return a transparent 1x1 png
            lastModifiedTime = FileTime.fromMillis(0);
            if (webRequest.checkNotModified(lastModifiedTime.toMillis())) {
                return;
            }
            response.setContentType("image/png");
            response.setContentLength(TRANSPARENT_1_X_1_PNG.length);
            response.addHeader("Cache-Control", "max-age=" + SIX_HOURS + ", public");
            response.getOutputStream().write(TRANSPARENT_1_X_1_PNG);
        }

    } catch (IOException e) {
        Log.error(LOGGER,
                String.format("There was an error accessing the logo of the group with id '%d'", groupId));
        throw new RuntimeException(e);
    }
}