下面列出了org.springframework.http.HttpStatus#CONFLICT 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@ExceptionHandler(EntityRecordException.class)
public ResponseEntity<?> handleEntityFoundException(EntityRecordException exception) {
logger.error("EntityRecordException", exception);
HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
switch (exception.getErrorCode()) {
case MULTIPLE_LK_FOUND:
httpStatus = HttpStatus.CONFLICT;
break;
case LK_NOTFOUND:
case UUID_NOTFOUND:
case INSERTED_RECORD_NOT_FOUND:
httpStatus = HttpStatus.NOT_FOUND;
break;
}
return new ResponseEntity<>(new ApiError(httpStatus, exception.getErrorCodeName(), exception.getMessage()), httpStatus);
}
public BookingResult updateBooking(int bookingId, Booking bookingToUpdate, String token) throws SQLException {
if(authRequests.postCheckAuth(token)){
if(dateCheckValidator.isValid(bookingToUpdate.getBookingDates())) {
if (bookingDB.checkForBookingConflict(bookingToUpdate)) {
return new BookingResult(HttpStatus.CONFLICT);
} else {
CreatedBooking updatedBooking = bookingDB.update(bookingId, bookingToUpdate);
if(updatedBooking != null){
return new BookingResult(updatedBooking, HttpStatus.OK);
} else {
return new BookingResult(HttpStatus.NOT_FOUND);
}
}
} else {
return new BookingResult(HttpStatus.CONFLICT);
}
} else {
return new BookingResult(HttpStatus.FORBIDDEN);
}
}
@RequestMapping(value = "/noauth/resetPassword", params = { "resetToken" }, method = RequestMethod.GET)
public ResponseEntity<String> checkResetToken(
@RequestParam(value = "resetToken") String resetToken) {
HttpHeaders headers = new HttpHeaders();
HttpStatus responseStatus;
String resetPasswordURI = "/login/resetPassword";
UserCredentials userCredentials = userService.findUserCredentialsByResetToken(resetToken);
if (userCredentials != null) {
try {
URI location = new URI(resetPasswordURI + "?resetToken=" + resetToken);
headers.setLocation(location);
responseStatus = HttpStatus.SEE_OTHER;
} catch (URISyntaxException e) {
log.error("Unable to create URI with address [{}]", resetPasswordURI);
responseStatus = HttpStatus.BAD_REQUEST;
}
} else {
responseStatus = HttpStatus.CONFLICT;
}
return new ResponseEntity<>(headers, responseStatus);
}
@RequestMapping(path = "/users/{userId}/commands/addFriend", method = RequestMethod.POST)
public HttpEntity<?> addFriend(@PathVariable Long userId, @RequestParam("friendId") Long friendId) {
Friend friend;
// Check if friend relationship already exists
if (!friendRepository.existsByUserIdAndFriendId(userId, friendId)) {
friend = new Friend(userId, friendId);
// Save friend relationship
friendRepository.save(friend);
// Broadcast a new domain event
eventStream.output().send(MessageBuilder
.withPayload(new FriendEvent(friend, EventType.FRIEND_ADDED)).build());
} else {
return new ResponseEntity<>(HttpStatus.CONFLICT);
}
return new ResponseEntity<>(friend, HttpStatus.CREATED);
}
public void createDataSource(DefaultSyndesisDataSource scd) throws AdminException {
String syndesisName = scd.getSyndesisName();
debug(syndesisName, "Creating the Datasource of Type " + scd.getType());
if (scd.getTeiidName() == null) {
for (int i = 0; i < 3; i++) {
try {
String name = getUniqueTeiidName(scd, syndesisName);
scd.setTeiidName(name);
break;
} catch (PersistenceException | DataIntegrityViolationException ignored) {
//multiple pods are trying to assign a name simultaneously
//if we try again, then we'll just pickup whatever someone else set
}
}
if (scd.getTeiidName() == null) {
throw new ResponseStatusException(HttpStatus.CONFLICT);
}
}
//now that the name is set, we can create the properties
this.metadata.registerDataSource(scd);
}
@Test
public void testFailureCode()
{
ResponseEntity<String> errorResponse = new ResponseEntity<>( ERROR_RESPONSE_STRING, HttpStatus.CONFLICT );
when( restTemplate.exchange( any( String.class ), any( HttpMethod.class ) , any( HttpEntity.class ), eq( String.class ) ) )
.thenReturn( errorResponse );
OutboundMessageResponse status = bulkSmsGateway.send( SUBJECT, MESSAGE, recipients, smsGatewayConfig );
assertNotNull( status );
assertFalse( status.isOk() );
assertEquals( GatewayResponse.FAILED, status.getResponseObject() );
}
public HttpStatus deleteRecordingFromHost(String recordingId, boolean force) {
if (!force && (this.startedRecordings.containsKey(recordingId)
|| this.startingRecordings.containsKey(recordingId))) {
// Cannot delete an active recording
return HttpStatus.CONFLICT;
}
Recording recording = getRecordingFromHost(recordingId);
if (recording == null) {
return HttpStatus.NOT_FOUND;
}
if (io.openvidu.java.client.Recording.Status.stopped.equals(recording.getStatus())) {
// Recording is being downloaded from remote host
log.warn("Cancelling ongoing download process of recording {}", recording.getId());
this.recordingDownloader.cancelDownload(recording.getId());
}
File folder = new File(this.openviduConfig.getOpenViduRecordingPath());
File[] files = folder.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory() && files[i].getName().equals(recordingId)) {
// Correct folder. Delete it
try {
FileUtils.deleteDirectory(files[i]);
} catch (IOException e) {
log.error("Couldn't delete folder {}", files[i].getAbsolutePath());
}
break;
}
}
return HttpStatus.NO_CONTENT;
}
/**
* Method to handle with {@link RepositoryConstraintViolationException} and return response
* with http status and {@link Message} with error information.
*
* @param e the {@link RepositoryConstraintViolationException} to handle with
* @return the {@link ResponseEntity} with {@link Message}, http headers and status
*/
@ExceptionHandler({RepositoryConstraintViolationException.class})
ResponseEntity handleConstraintViolationException(RepositoryConstraintViolationException e) {
List<Message> messages = new ArrayList<>();
for (FieldError error : e.getErrors().getFieldErrors()) {
messages.add(new Message(messageSourceAccessor.getMessage(error.getDefaultMessage()), MessageType.ERROR, error.getField()));
}
return new ResponseEntity(messages, new HttpHeaders(), HttpStatus.CONFLICT);
}
/**
* Aborts, suspends or resumes a workflow instance.
*
* <pre>
* Request: POST /workflowInstance/{woinRefNum} {status: "ABORT"}
* Response: OK, {refNum: 1, workflowName: "credit.step1", workflowVersion: null, label1: "one", label2: null, status: ABORT}
* Response: NOT_FOUND, if no such workflow instance exists
* Response: CONFLICT, if the workflow's current status does not allow the requested status transition
* Response: BAD_REQUEST, if the new status is not allowed.
* </pre>
*/
@RequestMapping(method = RequestMethod.POST, value = "/workflowInstance/{woinRefNum}",
produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_XML_VALUE})
public ResponseEntity<WorkflowInstanceRestModel> updateIntance( @PathVariable long woinRefNum, @RequestBody UpdateInstanceStatusForm form ){
WorkflowInstanceState woin = facade.findWorkflowInstance( woinRefNum, true );
if( woin == null ){
return new ResponseEntity<>( HttpStatus.NOT_FOUND );
}
try{
if( WorkflowInstanceStatus.ABORT.name().equals( form.getStatus() ) ){
facade.abortWorkflowInstance( woinRefNum );
}
else if( WorkflowInstanceStatus.SUSPENDED.name().equals( form.getStatus() ) ){
facade.suspendWorkflowInstance( woinRefNum );
}
else if( WorkflowInstanceStatus.EXECUTING.name().equals( form.getStatus() ) ){
facade.resumeWorkflowInstance( woinRefNum );
}
else{
return new ResponseEntity<>( HttpStatus.BAD_REQUEST );
}
}
catch( UnexpectedStatusException e ){
return new ResponseEntity<>( HttpStatus.CONFLICT );
}
woin = facade.findWorkflowInstance( woinRefNum, true );
return new ResponseEntity<>( createInstanceModel( woin ), HttpStatus.OK );
}
/**
* HTTP POST NEW ONE
*/
@RequestMapping(value = "/api/todolist", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> addNewTodoItem(@RequestBody TodoItem item) {
try {
item.setID(UUID.randomUUID().toString());
todoItemRepository.save(item);
return new ResponseEntity<String>("Entity created", HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<String>("Entity creation failed", HttpStatus.CONFLICT);
}
}
@RequestMapping(produces = {Versions.V1_0, Versions.V2_0})
@ExceptionHandler(DataIntegrityViolationException.class)
@ResponseStatus(value = HttpStatus.CONFLICT)
public @ResponseBody Map<String, Object> handleDataIntegrityViolationException(DataIntegrityViolationException ex) throws IOException {
Map<String, Object> map = Maps.newHashMap();
map.put("error", "Data Integrity Error");
map.put("cause", ex.getCause().getCause().getLocalizedMessage());
return map;
}
/**
* [Entity] already exist exception handler method - mapped to CONFLICT.
*
* @param ex
* @return
*/
@ExceptionHandler({ TenantAlreadyExistException.class, DataSourceAlreadyExistException.class })
@ResponseStatus(HttpStatus.CONFLICT)
@ResponseBody
public RestErrorResponse processEntityAlreadyExist(AbstractIdentifierNamingException ex) {
return new RestErrorResponse(HttpStatus.CONFLICT.value(), "Already exist: " + ex.getIdentifier());
}
@ExceptionHandler(OptimisticLockingFailureException.class)
@ResponseStatus(HttpStatus.CONFLICT)
public @ResponseBody
String elementNotFound(OptimisticLockingFailureException e) {
return "Conflict! " + e.getMessage();
}
@RequestMapping("/not-ok")
@ResponseStatus(HttpStatus.CONFLICT)
public String notOk() throws InterruptedException, ExecutionException {
return "Not OK";
}
@ExceptionHandler(ConcurrencyFailureException.class)
@ResponseStatus(HttpStatus.CONFLICT)
@ResponseBody
public ErrorVM processConcurrencyError(ConcurrencyFailureException ex) {
return new ErrorVM(ErrorConstants.ERR_CONCURRENCY_FAILURE);
}
Conflict(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
super(HttpStatus.CONFLICT, statusText, headers, body, charset);
}
@ExceptionHandler(ConcurrencyFailureException.class)
@ResponseStatus(HttpStatus.CONFLICT)
@ResponseBody
public ErrorVM processConcurrencyError(ConcurrencyFailureException ex) {
return new ErrorVM(ErrorConstants.ERR_CONCURRENCY_FAILURE);
}
@ExceptionHandler(UserAlreadyExistsException.class)
@ResponseStatus(HttpStatus.CONFLICT)
@ResponseBody
public ErrorInfo userExists(HttpServletRequest req, Exception ex) {
return new ErrorInfo(req.getRequestURL().toString(), ex, HttpStatus.CONFLICT.value());
}
@ResponseStatus(value = HttpStatus.CONFLICT, reason = "Package deletion error")
@ExceptionHandler(PackageDeleteException.class)
public void handlePackageDeleteException() {
// needed for server not to log 500 errors
}
@CrossOrigin
@ResponseStatus(HttpStatus.CONFLICT)
@ExceptionHandler(UserProjectException.class)
public MessageDTO exception(UserProjectException e) {
return new MessageDTO(e.getMessage());
}