Java Code Examples for org.springframework.http.HttpStatus#CONFLICT

The following examples show how to use org.springframework.http.HttpStatus#CONFLICT . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: APIExceptionHandlerController.java    From gemini with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 2
Source File: BookingService.java    From restful-booker-platform with GNU General Public License v3.0 6 votes vote down vote up
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);
    }
}
 
Example 3
Source File: TeiidOpenShiftClient.java    From syndesis with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 4
Source File: FriendController.java    From training with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 5
Source File: AuthController.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 6
Source File: RecordingManager.java    From openvidu with Apache License 2.0 5 votes vote down vote up
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;
	}
 
Example 7
Source File: BulkSmsGatewayTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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() );
}
 
Example 8
Source File: GenericExceptionHandler.java    From SMSC with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 9
Source File: RestController.java    From telekom-workflow-engine with MIT License 5 votes vote down vote up
/**
 * 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 );
}
 
Example 10
Source File: RestErrorHandler.java    From metamodel-membrane with Apache License 2.0 5 votes vote down vote up
/**
 * [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());
}
 
Example 11
Source File: TodoListController.java    From azure-gradle-plugins with MIT License 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 12
Source File: DefaultExceptionHandler.java    From spring-rest-server with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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;
}
 
Example 13
Source File: C4SGController.java    From c4sg-services with MIT License 4 votes vote down vote up
@CrossOrigin
@ResponseStatus(HttpStatus.CONFLICT)
@ExceptionHandler(UserProjectException.class)
public MessageDTO exception(UserProjectException e) {
    return new MessageDTO(e.getMessage());
}
 
Example 14
Source File: ReleaseController.java    From spring-cloud-skipper with Apache License 2.0 4 votes vote down vote up
@ResponseStatus(value = HttpStatus.CONFLICT, reason = "Package deletion error")
@ExceptionHandler(PackageDeleteException.class)
public void handlePackageDeleteException() {
	// needed for server not to log 500 errors
}
 
Example 15
Source File: RestExceptionHandler.java    From QuizZz with MIT License 4 votes vote down vote up
@ExceptionHandler(UserAlreadyExistsException.class)
@ResponseStatus(HttpStatus.CONFLICT)
@ResponseBody
public ErrorInfo userExists(HttpServletRequest req, Exception ex) {
	return new ErrorInfo(req.getRequestURL().toString(), ex, HttpStatus.CONFLICT.value());
}
 
Example 16
Source File: ExceptionTranslator.java    From tutorials with MIT License 4 votes vote down vote up
@ExceptionHandler(ConcurrencyFailureException.class)
@ResponseStatus(HttpStatus.CONFLICT)
@ResponseBody
public ErrorVM processConcurrencyError(ConcurrencyFailureException ex) {
    return new ErrorVM(ErrorConstants.ERR_CONCURRENCY_FAILURE);
}
 
Example 17
Source File: HttpClientErrorException.java    From java-technology-stack with MIT License 4 votes vote down vote up
Conflict(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
	super(HttpStatus.CONFLICT, statusText, headers, body, charset);
}
 
Example 18
Source File: ExceptionTranslator.java    From flair-engine with Apache License 2.0 4 votes vote down vote up
@ExceptionHandler(ConcurrencyFailureException.class)
@ResponseStatus(HttpStatus.CONFLICT)
@ResponseBody
public ErrorVM processConcurrencyError(ConcurrencyFailureException ex) {
    return new ErrorVM(ErrorConstants.ERR_CONCURRENCY_FAILURE);
}
 
Example 19
Source File: Issue362Tests.java    From spring-cloud-sleuth with Apache License 2.0 4 votes vote down vote up
@RequestMapping("/not-ok")
@ResponseStatus(HttpStatus.CONFLICT)
public String notOk() throws InterruptedException, ExecutionException {
	return "Not OK";
}
 
Example 20
Source File: ErrorAdvice.java    From Microservices-with-Spring-Cloud with MIT License 4 votes vote down vote up
@ExceptionHandler(OptimisticLockingFailureException.class)
@ResponseStatus(HttpStatus.CONFLICT)
public @ResponseBody
String elementNotFound(OptimisticLockingFailureException e) {
    return "Conflict! " + e.getMessage();
}