Example usage for org.springframework.http HttpStatus CONFLICT

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

Introduction

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

Prototype

HttpStatus CONFLICT

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

Click Source Link

Document

409 Conflict .

Usage

From source file:com.mentat.rest.web.GamesController.java

@ExceptionHandler(IllegalTransitionException.class)
ResponseEntity<String> handleConflicts(Exception e) {
    return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT);
}

From source file:com.gazbert.bxbot.rest.api.StrategyConfigController.java

/**
 * Creates a new Strategy configuration.
 *
 * @param user the authenticated user./*from w  ww . j  a va 2  s .c  o  m*/
 * @param strategyId id of the Strategy config to create.
 * @param config the new Strategy config.
 * @return 201 'Created' HTTP status code if create successful, 409 'Conflict' HTTP status code if Strategy config already exists.
 */
@RequestMapping(value = "/strategy/{strategyId}", method = RequestMethod.POST)
ResponseEntity<?> createStrategy(@AuthenticationPrincipal User user, @PathVariable String strategyId,
        @RequestBody StrategyConfig config) {

    if (config == null || config.getId() == null || !strategyId.equals(config.getId())) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    final StrategyConfig createdConfig = strategyConfigService.createStrategy(config);
    if (createdConfig.getId() != null) {
        final HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{strategyId}")
                .buildAndExpand(createdConfig.getId()).toUri());
        return new ResponseEntity<>(null, httpHeaders, HttpStatus.CREATED);

    } else {
        return new ResponseEntity<>(HttpStatus.CONFLICT);
    }
}

From source file:storage.StorageServiceWrapperController.java

protected ResponseEntity<String> create(@Nonnull final String storageServiceId, @Nonnull final String context,
        @Nonnull final String key, @Nonnull final String value) {
    try {/*from  w  ww  .  j  a  v  a  2s  .c  o m*/
        final StorageService storageService = getStorageService(storageServiceId);
        if (storageService == null) {
            log.debug("Unable to find storage service with id '{}'", storageServiceId);
            return seleniumFriendlyResponse(HttpStatus.BAD_REQUEST);
        }

        log.debug("Creating in '{}' with context '{}' and key '{}'", storageServiceId, context, key);
        boolean success = storageService.create(context, key, value, null);
        log.debug("Create '{}' in '{}' with context '{}' and key '{}'", success, storageServiceId, context,
                key);

        if (success) {
            return seleniumFriendlyResponse(HttpStatus.CREATED);
        } else {
            return seleniumFriendlyResponse(HttpStatus.CONFLICT);
        }

    } catch (IOException e) {
        log.debug("An error occurred", e);
        return seleniumFriendlyResponse(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:com.yang.oa.commons.exception.DefaultRestErrorResolver.java

protected final Map<String, String> createDefaultExceptionMappingDefinitions() {

    Map<String, String> m = new LinkedHashMap<String, String>();

    // 400//from   w ww  .ja v a 2s .  c o m
    applyDef(m, HttpMessageNotReadableException.class, HttpStatus.BAD_REQUEST);
    applyDef(m, MissingServletRequestParameterException.class, HttpStatus.BAD_REQUEST);
    applyDef(m, TypeMismatchException.class, HttpStatus.BAD_REQUEST);
    applyDef(m, "javax.validation.ValidationException", HttpStatus.BAD_REQUEST);
    applyDef(m, JlException.class, HttpStatus.BAD_REQUEST);
    //401
    applyDef(m, org.apache.shiro.authz.UnauthorizedException.class, HttpStatus.UNAUTHORIZED);
    applyDef(m, org.apache.shiro.authz.UnauthenticatedException.class, HttpStatus.UNAUTHORIZED);
    // 404
    applyDef(m, NoSuchRequestHandlingMethodException.class, HttpStatus.NOT_FOUND);
    applyDef(m, "org.hibernate.ObjectNotFoundException", HttpStatus.NOT_FOUND);

    // 405
    applyDef(m, HttpRequestMethodNotSupportedException.class, HttpStatus.METHOD_NOT_ALLOWED);

    // 406
    applyDef(m, HttpMediaTypeNotAcceptableException.class, HttpStatus.NOT_ACCEPTABLE);

    // 409
    //can't use the class directly here as it may not be an available dependency:
    applyDef(m, "org.springframework.dao.DataIntegrityViolationException", HttpStatus.CONFLICT);

    // 415
    applyDef(m, HttpMediaTypeNotSupportedException.class, HttpStatus.UNSUPPORTED_MEDIA_TYPE);

    return m;
}

From source file:ch.wisv.areafiftylan.seats.controller.SeatRestController.java

/**
 * Reserve a seat without assigning a User to it. Can be used for Group reservations. Can only be done by Admins.
 *
 * @param seatReservationDTO DTO containing the seatLocation.
 *
 * @return Status message indicating the result
 *///from w w w . j  a va2  s  .c om
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(value = "seats/reservations", method = RequestMethod.POST)
ResponseEntity<?> reserveSingleSeat(@RequestBody SeatReservationDTO seatReservationDTO) {
    if (seatService.reserveSeat(seatReservationDTO.getGroup(), seatReservationDTO.getNumber())) {
        return createResponseEntity(HttpStatus.OK, "Seat successfully reserved");
    } else {
        return createResponseEntity(HttpStatus.CONFLICT, "Seat is already taken");
    }
}

From source file:net.ljcomputing.core.controler.GlobalExceptionController.java

/**
 * Handle all data integrity violation exceptions.
 *
 * @param req/*from w  w  w.  j av a  2  s  . c  o m*/
 *            the req
 * @param exception
 *            the exception
 * @return the error info
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
@ExceptionHandler(DataIntegrityViolationException.class)
@ResponseStatus(HttpStatus.CONFLICT)
public @ResponseBody ErrorInfo handleAllDataIntegrityViolationExceptions(HttpServletRequest req,
        Exception exception) {
    logger.error("The data sent for processing had errors {}:", req.getRequestURL().toString(), exception);

    if (exception.getMessage().contains("Unique property")) {
        return new ErrorInfo(getCurrentTimestamp(), HttpStatus.CONFLICT, req.getRequestURL().toString(),
                new Exception("The saved value already exists."));
    }

    return new ErrorInfo(getCurrentTimestamp(), HttpStatus.CONFLICT, req.getRequestURL().toString(), exception);
}

From source file:net.maritimecloud.identityregistry.controllers.UserController.java

/**
 * Creates a new User/*from   w  w w.j  a v  a  2  s . c  o m*/
 * 
 * @return a reply...
 * @throws McBasicRestException 
 */
@RequestMapping(value = "/api/org/{orgMrn}/user", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
@PreAuthorize("hasRole('USER_ADMIN') and @accessControlUtil.hasAccessToOrg(#orgMrn)")
public ResponseEntity<User> createUser(HttpServletRequest request, @PathVariable String orgMrn,
        @Valid @RequestBody User input, BindingResult bindingResult) throws McBasicRestException {
    ValidateUtil.hasErrors(bindingResult, request);
    Organization org = this.organizationService.getOrganizationByMrn(orgMrn);
    if (org != null) {
        // Check that the entity being created belongs to the organization
        if (!MrnUtil.getOrgShortNameFromOrgMrn(orgMrn)
                .equals(MrnUtil.getOrgShortNameFromEntityMrn(input.getMrn()))) {
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.MISSING_RIGHTS,
                    request.getServletPath());
        }
        // If the organization doesn't have its own Identity Provider we create the user in a special keycloak instance
        if ("test-idp".equals(org.getFederationType()) && (org.getIdentityProviderAttributes() == null
                || org.getIdentityProviderAttributes().isEmpty())) {
            String password = PasswordUtil.generatePassword();
            keycloakAU.init(KeycloakAdminUtil.USER_INSTANCE);
            try {
                keycloakAU.createUser(input.getMrn(), password, input.getFirstName(), input.getLastName(),
                        input.getEmail(), orgMrn, input.getPermissions(), true);
            } catch (DuplicatedKeycloakEntry dke) {
                throw new McBasicRestException(HttpStatus.CONFLICT, dke.getErrorMessage(),
                        request.getServletPath());
            } catch (IOException e) {
                throw new McBasicRestException(HttpStatus.INTERNAL_SERVER_ERROR,
                        MCIdRegConstants.ERROR_CREATING_KC_USER, request.getServletPath());
            }
            // Send email to user with credentials
            emailUtil.sendUserCreatedEmail(input.getEmail(), input.getFirstName() + " " + input.getLastName(),
                    input.getEmail(), password);
        }
        input.setIdOrganization(org.getId());
        try {
            User newUser = this.entityService.save(input);
            return new ResponseEntity<>(newUser, HttpStatus.OK);
        } catch (DataIntegrityViolationException e) {
            // If save to DB failed, remove the user from keycloak if it was created.
            if ("test-idp".equals(org.getFederationType()) && (org.getIdentityProviderAttributes() == null
                    || org.getIdentityProviderAttributes().isEmpty())) {
                keycloakAU.deleteUser(input.getEmail());
            }
            throw new McBasicRestException(HttpStatus.CONFLICT, e.getRootCause().getMessage(),
                    request.getServletPath());
        }
    } else {
        throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND,
                request.getServletPath());
    }
}

From source file:be.bittich.quote.controller.impl.DefaultExceptionHandler.java

@RequestMapping(produces = APPLICATION_JSON)
@ExceptionHandler(DuplicateKeyException.class)
@ResponseStatus(value = HttpStatus.CONFLICT)
public @ResponseBody Map<String, Object> handleDuplicateKeyException(DuplicateKeyException ex)
        throws IOException {
    Map<String, Object> map = newHashMap();
    map.put("error", "Duplicate Key Exception");
    map.put("cause", ex.getLocalizedMessage());
    map.put("supported", ex.getMessage());
    return map;/* ww  w  .  j a v  a 2s. c om*/
}

From source file:net.maritimecloud.identityregistry.controllers.ServiceController.java

/**
 * Creates a new Service//from   w  w w.j  a  v  a 2  s.co m
 * 
 * @return a reply...
 * @throws McBasicRestException 
 */
@RequestMapping(value = "/api/org/{orgMrn}/service", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
@PreAuthorize("hasRole('SERVICE_ADMIN') and @accessControlUtil.hasAccessToOrg(#orgMrn)")
public ResponseEntity<Service> createService(HttpServletRequest request, @PathVariable String orgMrn,
        @Valid @RequestBody Service input, BindingResult bindingResult) throws McBasicRestException {
    ValidateUtil.hasErrors(bindingResult, request);
    Organization org = this.organizationService.getOrganizationByMrn(orgMrn);
    if (org != null) {
        // Check that the entity being created belongs to the organization
        if (!MrnUtil.getOrgShortNameFromOrgMrn(orgMrn)
                .equals(MrnUtil.getOrgShortNameFromEntityMrn(input.getMrn()))) {
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.MISSING_RIGHTS,
                    request.getServletPath());
        }
        input.setIdOrganization(org.getId());
        // Setup a keycloak client for the service if needed
        if (input.getOidcAccessType() != null && !input.getOidcAccessType().trim().isEmpty()) {
            // Check if the redirect uri is set if access type is "bearer-only"
            if (!"bearer-only".equals(input.getOidcAccessType())
                    && (input.getOidcRedirectUri() == null || input.getOidcRedirectUri().trim().isEmpty())) {
                throw new McBasicRestException(HttpStatus.BAD_REQUEST,
                        MCIdRegConstants.OIDC_MISSING_REDIRECT_URL, request.getServletPath());
            }
            keycloakAU.init(KeycloakAdminUtil.BROKER_INSTANCE);
            input.setOidcClientId(input.getMrn());
            try {
                String clientSecret = keycloakAU.createClient(input.getMrn(), input.getOidcAccessType(),
                        input.getOidcRedirectUri());
                if ("confidential".equals(input.getOidcAccessType())) {
                    input.setOidcClientSecret(clientSecret);
                } else {
                    input.setOidcClientSecret(null);
                }
            } catch (IOException e) {
                throw new McBasicRestException(HttpStatus.INTERNAL_SERVER_ERROR,
                        MCIdRegConstants.ERROR_CREATING_KC_CLIENT, request.getServletPath());
            } catch (DuplicatedKeycloakEntry dke) {
                throw new McBasicRestException(HttpStatus.CONFLICT, dke.getErrorMessage(),
                        request.getServletPath());
            }
        } else {
            input.setOidcAccessType(null);
            input.setOidcClientId(null);
            input.setOidcClientSecret(null);
            input.setOidcRedirectUri(null);
        }
        try {
            Service newService = this.entityService.save(input);
            return new ResponseEntity<>(newService, HttpStatus.OK);
        } catch (DataIntegrityViolationException e) {
            // If save to DB failed, remove the client from keycloak if it was created.
            if (input.getOidcAccessType() != null && !input.getOidcAccessType().trim().isEmpty()) {
                keycloakAU.deleteClient(input.getMrn());
            }
            throw new McBasicRestException(HttpStatus.CONFLICT, e.getRootCause().getMessage(),
                    request.getServletPath());
        }
    } else {
        throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND,
                request.getServletPath());
    }
}

From source file:gob.mx.salud.api.util.ResponseWrapper.java

/**
 * Genera una respuesta fallida del tipo <b>409-CONFLICT</b>
 * @param message/*from w w w .j  av  a2  s .  c o m*/
 * @param data
 * @return {@code ResponseWrapper<T>}
 */
@SuppressWarnings("unchecked")
public ResponseWrapper<T> errorConflict(String message, List<ErrorDetail> data) {
    error(ResponseWrapper.ERROR, HttpStatus.CONFLICT.value(), message, (T) data);
    return this;
}