org.springframework.http.HttpStatus#CONFLICT源码实例Demo

下面列出了org.springframework.http.HttpStatus#CONFLICT 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: gemini   文件: APIExceptionHandlerController.java
@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);
}
 
源代码2 项目: restful-booker-platform   文件: BookingService.java
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);
    }
}
 
源代码3 项目: iotplatform   文件: AuthController.java
@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);
}
 
源代码4 项目: training   文件: FriendController.java
@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);
}
 
源代码5 项目: syndesis   文件: TeiidOpenShiftClient.java
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);
}
 
源代码6 项目: dhis2-core   文件: BulkSmsGatewayTest.java
@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() );
}
 
源代码7 项目: openvidu   文件: RecordingManager.java
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;
	}
 
源代码8 项目: SMSC   文件: GenericExceptionHandler.java
/**
 * 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);
}
 
源代码9 项目: telekom-workflow-engine   文件: RestController.java
/**
 * 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 );
}
 
源代码10 项目: azure-gradle-plugins   文件: TodoListController.java
/**
 * 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;
}
 
源代码12 项目: metamodel-membrane   文件: RestErrorHandler.java
/**
 * [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();
}
 
源代码14 项目: spring-cloud-sleuth   文件: Issue362Tests.java
@RequestMapping("/not-ok")
@ResponseStatus(HttpStatus.CONFLICT)
public String notOk() throws InterruptedException, ExecutionException {
	return "Not OK";
}
 
源代码15 项目: flair-engine   文件: ExceptionTranslator.java
@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);
}
 
源代码17 项目: tutorials   文件: ExceptionTranslator.java
@ExceptionHandler(ConcurrencyFailureException.class)
@ResponseStatus(HttpStatus.CONFLICT)
@ResponseBody
public ErrorVM processConcurrencyError(ConcurrencyFailureException ex) {
    return new ErrorVM(ErrorConstants.ERR_CONCURRENCY_FAILURE);
}
 
源代码18 项目: QuizZz   文件: RestExceptionHandler.java
@ExceptionHandler(UserAlreadyExistsException.class)
@ResponseStatus(HttpStatus.CONFLICT)
@ResponseBody
public ErrorInfo userExists(HttpServletRequest req, Exception ex) {
	return new ErrorInfo(req.getRequestURL().toString(), ex, HttpStatus.CONFLICT.value());
}
 
源代码19 项目: spring-cloud-skipper   文件: ReleaseController.java
@ResponseStatus(value = HttpStatus.CONFLICT, reason = "Package deletion error")
@ExceptionHandler(PackageDeleteException.class)
public void handlePackageDeleteException() {
	// needed for server not to log 500 errors
}
 
源代码20 项目: c4sg-services   文件: C4SGController.java
@CrossOrigin
@ResponseStatus(HttpStatus.CONFLICT)
@ExceptionHandler(UserProjectException.class)
public MessageDTO exception(UserProjectException e) {
    return new MessageDTO(e.getMessage());
}