Example usage for org.springframework.http HttpStatus NOT_MODIFIED

List of usage examples for org.springframework.http HttpStatus NOT_MODIFIED

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus NOT_MODIFIED.

Prototype

HttpStatus NOT_MODIFIED

To view the source code for org.springframework.http HttpStatus NOT_MODIFIED.

Click Source Link

Document

304 Not Modified .

Usage

From source file:net.eusashead.hateoas.hal.response.impl.HalResponseBuilderImplTest.java

@Test
public void testGetNotModified() {

    // Create a HEAD with an If-None-Match header
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/path/to/resource");
    request.addHeader("If-None-Match", "W/\"123456789\"");

    // Create a HalGetResponseBuilder
    HalResponseBuilderImpl builder = new HalResponseBuilderImpl(representationFactory, request);

    // Create a response with a Representation
    ResponseEntity<Representation> response = builder.withProperty("string", "String value")
            .etag(new Date(123456789l)).lastModified(new Date(123456789l)).expireIn(1000000).build();

    // Check we get a 304
    Assert.assertEquals(HttpStatus.NOT_MODIFIED, response.getStatusCode());

}

From source file:org.mythtv.service.dvr.v27.RecordedHelperV27.java

private void downloadRecorded(final Context context, final LocationProfile locationProfile)
        throws MythServiceApiRuntimeException, RemoteException, OperationApplicationException {
    Log.v(TAG, "downloadRecorded : enter");

    EtagInfoDelegate etag = mEtagDaoHelper.findByEndpointAndDataId(context, locationProfile, "GetRecordedList",
            "");/*ww w . j  ava2 s.co m*/
    Log.d(TAG, "downloadRecorded : etag=" + etag.getValue());

    ResponseEntity<ProgramList> responseEntity = mMythServicesTemplate.dvrOperations()
            .getRecordedList(Boolean.FALSE, null, null, null, null, null, etag);

    DateTime date = new DateTime(DateTimeZone.UTC);
    if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
        Log.i(TAG, "download : GetRecordedList returned 200 OK");
        ProgramList programList = responseEntity.getBody();

        if (null != programList.getPrograms()) {

            load(context, locationProfile, programList.getPrograms());

            if (null != etag.getValue()) {
                Log.i(TAG, "download : saving etag: " + etag.getValue());

                etag.setEndpoint("GetRecordedList");
                etag.setDate(date);
                etag.setMasterHostname(locationProfile.getHostname());
                etag.setLastModified(date);
                mEtagDaoHelper.save(context, locationProfile, etag);
            }

        }

    }

    if (responseEntity.getStatusCode().equals(HttpStatus.NOT_MODIFIED)) {
        Log.i(TAG, "download : GetRecordedList returned 304 Not Modified");

        if (null != etag.getValue()) {
            Log.i(TAG, "download : saving etag: " + etag.getValue());

            etag.setLastModified(date);
            mEtagDaoHelper.save(context, locationProfile, etag);
        }

    }

    Log.v(TAG, "downloadRecorded : exit");
}

From source file:net.eusashead.hateoas.hal.response.impl.HalResponseBuilderImplTest.java

@Test
public void testHeadNotModified() {

    // Create a HEAD with an If-None-Match header
    MockHttpServletRequest request = new MockHttpServletRequest("HEAD", "/path/to/resource");
    request.addHeader("If-None-Match", "W/\"123456789\"");

    // Create a HalGetResponseBuilder
    HalResponseBuilderImpl builder = new HalResponseBuilderImpl(representationFactory, request);

    // Create a response with a Representation
    ResponseEntity<Representation> response = builder.withProperty("string", "String value")
            .etag(new Date(123456789l)).lastModified(new Date(123456789l)).expireIn(1000000).build();

    // Check we get a 304
    Assert.assertEquals(HttpStatus.NOT_MODIFIED, response.getStatusCode());

}

From source file:org.mythtv.service.channel.v27.ChannelHelperV27.java

private ChannelInfo[] downloadChannels(final Context context, final LocationProfile locationProfile,
        final int sourceId) throws MythServiceApiRuntimeException {
    Log.v(TAG, "downloadChannels : enter");

    EtagInfoDelegate etag = mEtagDaoHelper.findByEndpointAndDataId(context, locationProfile,
            "GetChannelInfoList", String.valueOf(sourceId));

    ResponseEntity<ChannelInfoList> responseEntity = mMythServicesTemplate.channelOperations()
            .getChannelInfoList(sourceId, 0, null, etag);

    DateTime date = new DateTime(DateTimeZone.UTC);
    if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
        Log.i(TAG, "downloadChannels : GetChannelInfoList returned 200 OK");

        ChannelInfoList channelInfoList = responseEntity.getBody();
        if (null != channelInfoList) {

            etag.setEndpoint("GetChannelInfoList");
            etag.setDataId(sourceId);/*from  w  w w  . j a va  2  s.  c  om*/
            etag.setDate(date);
            etag.setMasterHostname(locationProfile.getHostname());
            etag.setLastModified(date);
            mEtagDaoHelper.save(context, locationProfile, etag);

            if (null != channelInfoList.getChannelInfos()) {
                Log.v(TAG, "downloadChannels : exit, returning channelInfos");

                return channelInfoList.getChannelInfos();
            }

        }

    }

    if (responseEntity.getStatusCode().equals(HttpStatus.NOT_MODIFIED)) {
        Log.i(TAG, "downloadChannels : GetChannelInfoList returned 304 Not Modified");

        etag.setLastModified(date);
        mEtagDaoHelper.save(context, locationProfile, etag);
    }

    Log.d(TAG, "downloadChannels : exit");
    return null;
}

From source file:com.github.ukase.web.UkaseController.java

private ResponseEntity<Object> translateState(boolean selectedTemplateUpdated) {
    if (selectedTemplateUpdated) {
        return new ResponseEntity<>("updated", HttpStatus.OK);
    } else {/*ww  w .ja  v a2s  .  co  m*/
        return new ResponseEntity<>(HttpStatus.NOT_MODIFIED);
    }
}

From source file:ch.wisv.areafiftylan.products.controller.OrderRestController.java

@ExceptionHandler(TicketNotFoundException.class)
public ResponseEntity<?> handleTicketNotFoundException(TicketNotFoundException e) {
    return createResponseEntity(HttpStatus.NOT_MODIFIED, e.getMessage());
}

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 .  java2 s .c  o  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:net.es.sense.rm.api.SenseRmController.java

private ResponseEntity<?> toResponseEntity(HttpHeaders headers, ResourceResponse rr) {
    if (rr == null) {
        return new ResponseEntity<>(headers, HttpStatus.INTERNAL_SERVER_ERROR);
    }//from   w  w w.j  a v a 2 s  .c  o  m

    switch (rr.getStatus()) {
    case NOT_MODIFIED:
        return new ResponseEntity<>(headers, HttpStatus.NOT_MODIFIED);

    default:
        Error.ErrorBuilder eb = Error.builder().error(rr.getStatus().getReasonPhrase());
        rr.getError().ifPresent(e -> eb.error_description(e));
        return new ResponseEntity<>(eb.build(), HttpStatus.valueOf(rr.getStatus().getStatusCode()));
    }
}

From source file:net.es.sense.rm.api.SenseRmController.java

/**
 * Returns the delta resource identified by deltaId.
 *
 * Operation: GET /api/sense/v1/deltas/{deltaId}
 *
 * @param accept Provides media types that are acceptable for the response. At the moment 'application/json' is the
 * supported response encoding./* w  w  w.  j  a v  a 2s. c  om*/
 * @param summary
 * @param ifModifiedSince The HTTP request may contain the If-Modified-Since header requesting all models with
 * creationTime after the specified date. The date must be specified in RFC 1123 format.
 * @param encode
 * @param model Specifies the model encoding to use (i.e. turtle, ttl, json-ld, etc).
 * @param deltaId Identifier of the target delta resource.
 * @return A RESTful response.
 */
@ApiOperation(value = "Get a specific SENSE topology model resource.", notes = "Returns SENSE topology model resource corresponding to the specified resource id.", response = DeltaResource.class)
@ApiResponses(value = {
        @ApiResponse(code = HttpConstants.OK_CODE, message = HttpConstants.OK_DELTA_MSG, response = DeltaResource.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_MODIFIED, message = HttpConstants.NOT_MODIFIED_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.BAD_REQUEST_CODE, message = HttpConstants.BAD_REQUEST_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.FORBIDDEN_CODE, message = HttpConstants.FORBIDDEN_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_FOUND_CODE, message = HttpConstants.NOT_FOUND_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_ACCEPTABLE_CODE, message = HttpConstants.NOT_ACCEPTABLE_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.INTERNAL_ERROR_CODE, message = HttpConstants.INTERNAL_ERROR_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }), })
@RequestMapping(value = "/deltas/{" + HttpConstants.DELTAID_NAME + "}", method = RequestMethod.GET, produces = {
        MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public ResponseEntity<?> getDelta(
        @RequestHeader(value = HttpConstants.ACCEPT_NAME, defaultValue = MediaType.APPLICATION_JSON_VALUE) @ApiParam(value = HttpConstants.ACCEPT_MSG, required = false) String accept,
        @RequestHeader(value = HttpConstants.IF_MODIFIED_SINCE_NAME, required = false) @ApiParam(value = HttpConstants.IF_MODIFIED_SINCE_MSG, required = false) String ifModifiedSince,
        @RequestParam(value = HttpConstants.SUMMARY_NAME, defaultValue = "false") @ApiParam(value = HttpConstants.SUMMARY_MSG, required = false) boolean summary,
        @RequestParam(value = HttpConstants.MODEL_NAME, defaultValue = HttpConstants.MODEL_TURTLE) @ApiParam(value = HttpConstants.MODEL_MSG, required = false) String model,
        @RequestParam(value = HttpConstants.ENCODE_NAME, defaultValue = "false") @ApiParam(value = HttpConstants.ENCODE_MSG, required = false) boolean encode,
        @PathVariable(HttpConstants.DELTAID_NAME) @ApiParam(value = HttpConstants.DELTAID_MSG, required = true) String deltaId) {

    // Get the requested resource URL.
    final URI location = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri();

    log.info("[SenseRmController] operation = {}, id = {}, accept = {}, ifModifiedSince = {}, model = {}",
            location, deltaId, accept, ifModifiedSince, model);

    // Parse the If-Modified-Since header if it is present.
    long ifms = parseIfModfiedSince(ifModifiedSince);

    // We need to return the current location of this resource in the response header.
    final HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Location", location.toASCIIString());

    try {
        // Query for the requested delta.
        DeltaResponse response = driver.getDelta(deltaId, model, ifms).get();
        if (response == null || response.getStatus() != Status.OK) {
            return toResponseEntity(headers, response);
        }

        DeltaResource d = response.getDelta().get();

        log.info("[SenseRmController] deltaId = {}, lastModified = {}, If-Modified-Since = {}", d.getId(),
                d.getLastModified(), ifModifiedSince);

        // Determine when this was last modified.
        long lastModified = XmlUtilities.xmlGregorianCalendar(d.getLastModified()).toGregorianCalendar()
                .getTimeInMillis();
        headers.setLastModified(lastModified);

        // Do we need to return this delta?
        if (lastModified <= ifms) {
            log.info("[SenseRmController] returning not modified, deltaId = {}", d.getId());
            return new ResponseEntity<>(headers, HttpStatus.NOT_MODIFIED);
        }

        d.setHref(location.toASCIIString());
        if (summary) {
            // If a summary resource view was requested we do not send back any models.
            d.setAddition(null);
            d.setReduction(null);
            d.setResult(null);
        } else if (encode) {
            // Compress and base64 encode the model contents if requested.
            d.setAddition(Encoder.encode(d.getAddition()));
            d.setReduction(Encoder.encode(d.getReduction()));
            d.setResult(Encoder.encode(d.getResult()));
        }

        log.info(
                "[SenseRmController] getDelta returning id = {}, creationTime = {}, queried If-Modified-Since = {}.",
                d.getId(), d.getLastModified(), ifModifiedSince);
        return new ResponseEntity<>(d, headers, HttpStatus.OK);
    } catch (InterruptedException | ExecutionException | IOException | DatatypeConfigurationException ex) {
        log.error("[SenseRmController] getDelta failed, deltaId = {}, ex = {}", deltaId, ex);
        Error error = Error.builder().error(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
                .error_description(ex.getMessage()).build();

        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.ambraproject.wombat.service.remote.CachedRemoteService.java

/**
 * Requests a stream, using the "If-Modified-Since" header in the request so that the object will only be returned if
 * it was modified after the given time.  Otherwise, the stream field of the returned object will be null.  This is
 * useful when results from the SOA service are being added to a cache, and we only want to retrieve the result if it
 * is newer than the version stored in the cache.
 *
 * @param target       the request to send the REST service
 * @param lastModified the object will be returned iff the SOA server indicates that it was modified after this
 *                     timestamp// w ww.  java 2  s  . c  om
 * @return a timestamped stream, or a null stream with non-null timestamp
 * @throws IOException
 */
private TimestampedResponse requestIfModifiedSince(HttpUriRequest target, Calendar lastModified)
        throws IOException {
    Preconditions.checkNotNull(lastModified);
    CloseableHttpResponse response = null;
    boolean returningStream = false;
    try {
        target.addHeader(HttpHeaders.IF_MODIFIED_SINCE, HttpDateUtil.format(lastModified));
        response = remoteService.getResponse(target);
        Header[] lastModifiedHeaders = response.getHeaders(HttpHeaders.LAST_MODIFIED);
        if (lastModifiedHeaders.length == 0) {
            TimestampedResponse timestamped = new TimestampedResponse(null, response);
            returningStream = true;
            return timestamped;
        }
        if (lastModifiedHeaders.length != 1) {
            throw new RuntimeException("Expecting 1 Last-Modified header, got " + lastModifiedHeaders.length);
        }
        Calendar resultLastModified = HttpDateUtil.parse(lastModifiedHeaders[0].getValue());

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.OK.value()) {
            TimestampedResponse timestamped = new TimestampedResponse(resultLastModified, response);
            returningStream = true;
            return timestamped;
        } else if (statusCode == HttpStatus.NOT_MODIFIED.value()) {
            return new TimestampedResponse(resultLastModified, null);
        } else {
            throw new RuntimeException("Unexpected status code " + statusCode);
        }
    } finally {
        if (!returningStream && response != null) {
            response.close();
        }
    }
}