下面列出了org.springframework.http.HttpStatus#NOT_MODIFIED 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Indicates whether the response has a message body.
* <p>Implementation returns {@code false} for:
* <ul>
* <li>a response status of {@code 1XX}, {@code 204} or {@code 304}</li>
* <li>a {@code Content-Length} header of {@code 0}</li>
* </ul>
* @return {@code true} if the response has a message body, {@code false} otherwise
* @throws IOException in case of I/O errors
*/
public boolean hasMessageBody() throws IOException {
try {
HttpStatus responseStatus = getStatusCode();
if (responseStatus.is1xxInformational() || responseStatus == HttpStatus.NO_CONTENT ||
responseStatus == HttpStatus.NOT_MODIFIED) {
return false;
}
}
catch (IllegalArgumentException ex) {
// Ignore - unknown HTTP status code...
}
if (getHeaders().getContentLength() == 0) {
return false;
}
return true;
}
@RequestMapping(value= "/mapping", method = RequestMethod.POST)
public ResponseEntity<?> postClassMapping(JwtAuthenticationToken token, @RequestBody ClassMapping cm) {
UserContext userContext = (UserContext) token.getPrincipal();
ClassMapping classMapping;
ClassMapping existingClassMapping = mongoClassMappingRepository
.findByTenantIdAndOrganizationIdAndClassExternalId(userContext.getTenantId(), userContext.getOrgId(), cm.getClassExternalId());
if (existingClassMapping == null) {
classMapping
= new ClassMapping.Builder()
.withClassExternalId(cm.getClassExternalId())
.withClassSourcedId(cm.getClassSourcedId())
.withDateLastModified(Instant.now())
.withOrganizationId(userContext.getOrgId())
.withTenantId(userContext.getTenantId())
.build();
ClassMapping saved = mongoClassMappingRepository.save(classMapping);
return new ResponseEntity<>(saved, null, HttpStatus.CREATED);
}
return new ResponseEntity<>(existingClassMapping, null, HttpStatus.NOT_MODIFIED);
}
@RequestMapping(value= "/mapping", method = RequestMethod.POST)
public ResponseEntity<?> postUserMapping(JwtAuthenticationToken token, @RequestBody UserMapping um) {
UserContext userContext = (UserContext) token.getPrincipal();
UserMapping existingUserMapping = mongoUserMappingRepository
.findByTenantIdAndOrganizationIdAndUserExternalIdIgnoreCase(userContext.getTenantId(), userContext.getOrgId(), um.getUserExternalId());
if (existingUserMapping == null) {
UserMapping userMapping
= new UserMapping.Builder()
.withUserExternalId(um.getUserExternalId())
.withUserSourcedId(um.getUserSourcedId())
.withDateLastModified(Instant.now())
.withOrganizationId(userContext.getOrgId())
.withTenantId(userContext.getTenantId())
.build();
UserMapping saved = mongoUserMappingRepository.save(userMapping);
return new ResponseEntity<>(saved, null, HttpStatus.CREATED);
}
return new ResponseEntity<>(existingUserMapping, null, HttpStatus.NOT_MODIFIED);
}
@Test
public void handleReturnTypeNotModified() throws Exception {
long currentTime = new Date().getTime();
long oneMinuteAgo = currentTime - (1000 * 60);
String etagValue = "\"deadb33f8badf00d\"";
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setDate(HttpHeaders.LAST_MODIFIED, oneMinuteAgo);
responseHeaders.set(HttpHeaders.ETAG, etagValue);
ResponseEntity<String> returnValue = new ResponseEntity<String>("body", responseHeaders, HttpStatus.NOT_MODIFIED);
given(messageConverter.canWrite(String.class, null)).willReturn(true);
given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
given(messageConverter.canWrite(String.class, MediaType.TEXT_PLAIN)).willReturn(true);
processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
assertResponseNotModified();
assertEquals(1, servletResponse.getHeaderValues(HttpHeaders.LAST_MODIFIED).size());
assertEquals(dateFormat.format(oneMinuteAgo), servletResponse.getHeader(HttpHeaders.LAST_MODIFIED));
assertEquals(1, servletResponse.getHeaderValues(HttpHeaders.ETAG).size());
assertEquals(etagValue, servletResponse.getHeader(HttpHeaders.ETAG));
}
public void pollInternal() {
HttpHeaders requestHeaders = new HttpHeaders();
if (lastModified != null) {
requestHeaders.set(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified));
}
HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
ResponseEntity<OrderFeed> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, OrderFeed.class);
if (response.getStatusCode() != HttpStatus.NOT_MODIFIED) {
log.trace("data has been modified");
OrderFeed feed = response.getBody();
for (OrderFeedEntry entry : feed.getOrders()) {
if ((lastModified == null) || (entry.getUpdated().after(lastModified))) {
Bonus bonus = restTemplate
.getForEntity(entry.getLink(), Bonus.class).getBody();
log.trace("saving bonus {}", bonus.getId());
bonusService.calculateBonus(bonus);
}
}
if (response.getHeaders().getFirst("Last-Modified") != null) {
lastModified = DateUtils.parseDate(response.getHeaders().getFirst(HttpHeaders.LAST_MODIFIED));
log.trace("Last-Modified header {}", lastModified);
}
} else {
log.trace("no new data");
}
}
public void pollInternal() {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set(HttpHeaders.ACCEPT, "*/*");
if (lastModified != null) {
requestHeaders.set(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified));
}
HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
ResponseEntity<OrderFeed> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, OrderFeed.class);
if (response.getStatusCode() != HttpStatus.NOT_MODIFIED) {
log.trace("data has been modified");
OrderFeed feed = response.getBody();
for (OrderFeedEntry entry : feed.getOrders()) {
if ((lastModified == null) || (entry.getUpdated().after(lastModified))) {
Shipment shipping = restTemplate
.getForEntity(entry.getLink(), Shipment.class).getBody();
log.trace("saving shipping {}", shipping.getId());
shipmentService.ship(shipping);
}
}
if (response.getHeaders().getFirst("Last-Modified") != null) {
lastModified = DateUtils.parseDate(response.getHeaders().getFirst(HttpHeaders.LAST_MODIFIED));
log.trace("Last-Modified header {}", lastModified);
}
} else {
log.trace("no new data");
}
}
public void pollInternal() {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set(HttpHeaders.ACCEPT, "*/*");
if (lastModified != null) {
requestHeaders.set(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified));
}
HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
ResponseEntity<OrderFeed> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, OrderFeed.class);
if (response.getStatusCode() != HttpStatus.NOT_MODIFIED) {
log.trace("data has been modified");
OrderFeed feed = response.getBody();
for (OrderFeedEntry entry : feed.getOrders()) {
if ((lastModified == null) || (entry.getUpdated().after(lastModified))) {
Invoice invoice = restTemplate
.getForEntity(entry.getLink(), Invoice.class).getBody();
log.trace("saving invoice {}", invoice.getId());
invoiceService.generateInvoice(invoice);
}
}
if (response.getHeaders().getFirst(HttpHeaders.LAST_MODIFIED) != null) {
lastModified = DateUtils.parseDate(response.getHeaders().getFirst(HttpHeaders.LAST_MODIFIED));
log.trace("Last-Modified header {}", lastModified);
}
} else {
log.trace("no new data");
}
}
/**
* Indicates whether the response has a message body.
* <p>Implementation returns {@code false} for:
* <ul>
* <li>a response status of {@code 1XX}, {@code 204} or {@code 304}</li>
* <li>a {@code Content-Length} header of {@code 0}</li>
* </ul>
* @return {@code true} if the response has a message body, {@code false} otherwise
* @throws IOException in case of I/O errors
*/
public boolean hasMessageBody() throws IOException {
HttpStatus status = HttpStatus.resolve(getRawStatusCode());
if (status != null && (status.is1xxInformational() || status == HttpStatus.NO_CONTENT ||
status == HttpStatus.NOT_MODIFIED)) {
return false;
}
if (getHeaders().getContentLength() == 0) {
return false;
}
return true;
}
/**
* Indicates whether the response has a message body.
* <p>Implementation returns {@code false} for:
* <ul>
* <li>a response status of {@code 1XX}, {@code 204} or {@code 304}</li>
* <li>a {@code Content-Length} header of {@code 0}</li>
* </ul>
* @return {@code true} if the response has a message body, {@code false} otherwise
* @throws IOException in case of I/O errors
*/
public boolean hasMessageBody() throws IOException {
HttpStatus status = HttpStatus.resolve(getRawStatusCode());
if (status != null && (status.is1xxInformational() || status == HttpStatus.NO_CONTENT ||
status == HttpStatus.NOT_MODIFIED)) {
return false;
}
if (getHeaders().getContentLength() == 0) {
return false;
}
return true;
}
public void pollInternal() {
HttpHeaders requestHeaders = new HttpHeaders();
if (lastModified != null) {
requestHeaders.set(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified));
}
HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
ResponseEntity<Feed> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Feed.class);
if (response.getStatusCode() != HttpStatus.NOT_MODIFIED) {
log.trace("data has been modified");
Feed feed = response.getBody();
for (Entry entry : feed.getEntries()) {
if ((lastModified == null) || (entry.getUpdated().after(lastModified))) {
Invoice invoice = restTemplate
.getForEntity(entry.getContents().get(0).getSrc(), Invoice.class).getBody();
log.trace("saving invoice {}", invoice.getId());
invoiceService.generateInvoice(invoice);
}
}
if (response.getHeaders().getFirst(HttpHeaders.LAST_MODIFIED) != null) {
lastModified = DateUtils.parseDate(response.getHeaders().getFirst(HttpHeaders.LAST_MODIFIED));
log.trace("Last-Modified header {}", lastModified);
}
} else {
log.trace("no new data");
}
}
public void pollInternal() {
HttpHeaders requestHeaders = new HttpHeaders();
if (lastModified != null) {
requestHeaders.set(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified));
}
HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
ResponseEntity<Feed> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Feed.class);
if (response.getStatusCode() != HttpStatus.NOT_MODIFIED) {
log.trace("data has been modified");
Feed feed = response.getBody();
for (Entry entry : feed.getEntries()) {
if ((lastModified == null) || (entry.getUpdated().after(lastModified))) {
Shipment shipping = restTemplate
.getForEntity(entry.getContents().get(0).getSrc(), Shipment.class).getBody();
log.trace("saving shipping {}", shipping.getId());
shipmentService.ship(shipping);
}
}
if (response.getHeaders().getFirst("Last-Modified") != null) {
lastModified = DateUtils.parseDate(response.getHeaders().getFirst(HttpHeaders.LAST_MODIFIED));
log.trace("Last-Modified header {}", lastModified);
}
} else {
log.trace("no new data");
}
}
/**
* Indicates whether the response has a message body.
* <p>Implementation returns {@code false} for:
* <ul>
* <li>a response status of {@code 1XX}, {@code 204} or {@code 304}</li>
* <li>a {@code Content-Length} header of {@code 0}</li>
* </ul>
* @return {@code true} if the response has a message body, {@code false} otherwise
* @throws IOException in case of I/O errors
*/
public boolean hasMessageBody() throws IOException {
HttpStatus responseStatus = this.getStatusCode();
if (responseStatus.is1xxInformational() || responseStatus == HttpStatus.NO_CONTENT ||
responseStatus == HttpStatus.NOT_MODIFIED) {
return false;
}
else if (this.getHeaders().getContentLength() == 0) {
return false;
}
return true;
}
@Secured({Authorities.ADMIN_ROLE, SecuredType.CLUSTER_ADMIN})
@RequestMapping(value = "/{cluster}", method = PUT)
public void createCluster(@PathVariable("cluster") String name, @RequestBody(required = false) UiClusterEditablePart data) {
log.info("about to create cluster: [{}], {}", name, data);
AtomicBoolean flag = new AtomicBoolean(false);// we can not use primitives in closure
NodesGroup cluster = discoveryStorage.getOrCreateCluster(name, (ccc) -> {
String type = null;
if (data != null) {
type = data.getType();
}
if (type == null) {
type = NodesGroupConfig.TYPE_SWARM;
}
AbstractNodesGroupConfig<?> gc = ccc.createConfig(type);
if(data != null) {
ClusterConfigImpl.Builder config = data.getConfig();
if(gc instanceof DockerBasedClusterConfig && config != null) {
config.setCluster(name); // we must fix name of cluster
((DockerBasedClusterConfig)gc).setConfig(config.build());
}
data.toCluster(gc);
}
ccc.setMustValidated(true);
flag.set(true);
return gc;
});
if(!flag.get()) {
throw new HttpException(HttpStatus.NOT_MODIFIED, "Cluster '" + name + "' is already exists.");
}
log.info("Cluster created: {}", cluster);
cluster.flush();
}
public ResponseEntity<Object> checkAuthorization(Object o, User u){
if(o == null){
//The object does not exist
return new ResponseEntity<>(HttpStatus.NOT_MODIFIED);
}
if(!this.user.getLoggedUser().equals(u)){
//The teacher is not authorized to edit it if he is not its owner
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
return null;
}
private ResponseEntity<Object> checkAuthorization(Object o, User u){
if(o == null){
//The object does not exist
return new ResponseEntity<>(HttpStatus.NOT_MODIFIED);
}
if(!this.user.getLoggedUser().equals(u)){
//The teacher is not authorized to edit it if he is not its owner
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
return null;
}
@RequestMapping(value = "/changePassword", method = RequestMethod.PUT)
public ResponseEntity<Object> changePassword(@RequestBody String[] userData) {
System.out.println("Changing password...");
ResponseEntity<Object> authorized = authorizationService.checkBackendLogged();
if (authorized != null){
return authorized;
};
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
//If the stored current password and the given current password match
if(encoder.matches(userData[0], user.getLoggedUser().getPasswordHash())) {
//If the password has a valid format (at least 8 characters long and contains one uppercase, one lowercase and a number)
if (userData[1].matches(this.passRegex)){
System.out.println("Password successfully changed");
User modifiedUser = userRepository.findByName(user.getLoggedUser().getName());
modifiedUser.setPasswordHash(encoder.encode(userData[1]));
userRepository.save(modifiedUser);
return new ResponseEntity<>(true, HttpStatus.OK);
}
else{
System.out.println("New password NOT valid");
return new ResponseEntity<>(HttpStatus.NOT_MODIFIED);
}
} else {
System.out.println("Invalid current password");
return new ResponseEntity<>(HttpStatus.CONFLICT);
}
}
@RequestMapping(value = "/edit/file-group/course/{courseId}", method = RequestMethod.PUT)
public ResponseEntity<Object> modifyFileGroup(@RequestBody FileGroup fileGroup, @PathVariable(value="courseId") String courseId) {
ResponseEntity<Object> authorized = authorizationService.checkBackendLogged();
if (authorized != null){
return authorized;
};
long id_course = -1;
try{
id_course = Long.parseLong(courseId);
}catch(NumberFormatException e){
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
Course c = courseRepository.findOne(id_course);
ResponseEntity<Object> teacherAuthorized = authorizationService.checkAuthorization(c, c.getTeacher());
if (teacherAuthorized != null) { // If the user is not the teacher of the course
return teacherAuthorized;
} else {
FileGroup fg = fileGroupRepository.findOne(fileGroup.getId());
if (fg != null){
fg.setTitle(fileGroup.getTitle());
fileGroupRepository.save(fg);
//Returning the root FileGroup of the added file
return new ResponseEntity<>(this.getRootFileGroup(fg), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_MODIFIED);
}
}
}
@Scheduled(fixedDelay = 15000)
public void poll() {
HttpHeaders requestHeaders = new HttpHeaders();
if (lastModified != null) {
requestHeaders.set("If-Modified-Since", DateUtils.formatDate(lastModified));
}
HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
ResponseEntity<Feed> response = restTemplate.exchange(creditDecisionFeed, HttpMethod.GET, requestEntity, Feed.class);
if (response.getStatusCode() != HttpStatus.NOT_MODIFIED) {
Feed feed = response.getBody();
Date lastUpdateInFeed = null;
for (Entry entry : feed.getEntries()) {
String applicationNumber = entry.getSummary().getValue();
if ((lastModified == null) || (entry.getUpdated().after(lastModified))) {
log.info(applicationNumber + " is new, updating the status");
CreditApplicationStatus applicationStatus = repository.findByApplicationNumber(applicationNumber);
if (applicationStatus != null) {
applicationStatus.setApproved(true);
repository.save(applicationStatus);
}
if ((lastUpdateInFeed == null) || (entry.getUpdated().after(lastUpdateInFeed))) {
lastUpdateInFeed = entry.getUpdated();
}
}
}
if (response.getHeaders().getFirst("Last-Modified") != null) {
lastModified = DateUtils.parseDate(response.getHeaders().getFirst("Last-Modified"));
log.info("LastModified header {}", lastModified);
} else {
if (lastUpdateInFeed != null) {
lastModified = lastUpdateInFeed;
log.info("Last in feed {}", lastModified);
}
}
}
}
@RequestMapping(value = "/edit/file/file-group/{fileGroupId}/course/{courseId}", method = RequestMethod.PUT)
public ResponseEntity<Object> modifyFile(
@RequestBody File file,
@PathVariable(value="fileGroupId") String fileGroupId,
@PathVariable(value="courseId") String courseId)
{
ResponseEntity<Object> authorized = authorizationService.checkBackendLogged();
if (authorized != null){
return authorized;
};
long id_fileGroup = -1;
long id_course = -1;
try{
id_fileGroup = Long.parseLong(fileGroupId);
id_course = Long.parseLong(courseId);
}catch(NumberFormatException e){
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
Course c = courseRepository.findOne(id_course);
ResponseEntity<Object> teacherAuthorized = authorizationService.checkAuthorization(c, c.getTeacher());
if (teacherAuthorized != null) { // If the user is not the teacher of the course
return teacherAuthorized;
} else {
FileGroup fg = fileGroupRepository.findOne(id_fileGroup);
if (fg != null){
for (int i = 0; i < fg.getFiles().size(); i++){
if (fg.getFiles().get(i).getId() == file.getId()){
fg.getFiles().get(i).setName(file.getName());
fileGroupRepository.save(fg);
//Returning the root FileGroup of the added file
return new ResponseEntity<>(this.getRootFileGroup(fg), HttpStatus.OK);
}
}
return new ResponseEntity<>(HttpStatus.NOT_MODIFIED);
} else {
return new ResponseEntity<>(HttpStatus.NOT_MODIFIED);
}
}
}
@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);
}