Search in sources :

Example 31 with HttpStatus

use of org.springframework.http.HttpStatus in project Flare-event-calendar by PollubCafe.

the class GlobalExceptionHandler method handleMethodArgumentNotValid.

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
    BindingResult bindingResult = ex.getBindingResult();
    List<ApiFieldError> apiFieldErrors = bindingResult.getFieldErrors().stream().map(fieldError -> new ApiFieldError(fieldError.getField(), fieldError.getDefaultMessage())).collect(toList());
    ApiErrorsView apiErrorsView = new ApiErrorsView(apiFieldErrors);
    return new ResponseEntity<>(apiErrorsView, HttpStatus.UNPROCESSABLE_ENTITY);
}
Also used : RegistrationException(pl.pollub.cs.pentagoncafe.flare.exception.registration.RegistrationException) SendingEmailException(pl.pollub.cs.pentagoncafe.flare.exception.sendingEmail.SendingEmailException) ObjectNotFoundException(pl.pollub.cs.pentagoncafe.flare.exception.ObjectNotFoundException) WebRequest(org.springframework.web.context.request.WebRequest) Autowired(org.springframework.beans.factory.annotation.Autowired) BindingResult(org.springframework.validation.BindingResult) ApiErrorsView(pl.pollub.cs.pentagoncafe.flare.exception.handler.error.ApiErrorsView) TooManyLoginAttempts(pl.pollub.cs.pentagoncafe.flare.exception.auth.TooManyLoginAttempts) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) EventCalendarApplication(pl.pollub.cs.pentagoncafe.flare.EventCalendarApplication) ControllerAdvice(org.springframework.web.bind.annotation.ControllerAdvice) Messages(pl.pollub.cs.pentagoncafe.flare.component.message.Messages) HttpHeaders(org.springframework.http.HttpHeaders) ResetPasswordException(pl.pollub.cs.pentagoncafe.flare.exception.ResetPasswordException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) ApiFieldError(pl.pollub.cs.pentagoncafe.flare.exception.handler.error.ApiFieldError) HttpStatus(org.springframework.http.HttpStatus) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) Logger(org.apache.logging.log4j.Logger) ResponseEntityExceptionHandler(org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler) ResponseEntity(org.springframework.http.ResponseEntity) LogManager(org.apache.logging.log4j.LogManager) BindingResult(org.springframework.validation.BindingResult) ResponseEntity(org.springframework.http.ResponseEntity) ApiErrorsView(pl.pollub.cs.pentagoncafe.flare.exception.handler.error.ApiErrorsView) ApiFieldError(pl.pollub.cs.pentagoncafe.flare.exception.handler.error.ApiFieldError)

Example 32 with HttpStatus

use of org.springframework.http.HttpStatus in project molgenis by molgenis.

the class ExceptionHandlerUtilsTest method testHandleExceptionNonHtmlRequest.

@Test
public void testHandleExceptionNonHtmlRequest() {
    HandlerMethod handlerMethod = mock(HandlerMethod.class);
    when(handlerMethod.hasMethodAnnotation(ResponseBody.class)).thenReturn(true);
    HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
    assertEquals(handleException(new Exception("message"), handlerMethod, httpStatus, null, PRODUCTION), new ResponseEntity<>(ErrorMessageResponse.create("message"), httpStatus));
}
Also used : HttpStatus(org.springframework.http.HttpStatus) HandlerMethod(org.springframework.web.method.HandlerMethod) Test(org.testng.annotations.Test)

Example 33 with HttpStatus

use of org.springframework.http.HttpStatus in project molgenis by molgenis.

the class ExceptionHandlerUtilsTest method testHandleExceptionHtmlRequest.

@SuppressWarnings("unchecked")
@Test
public void testHandleExceptionHtmlRequest() {
    HandlerMethod handlerMethod = mock(HandlerMethod.class);
    Class beanType = ExceptionHandlerUtils.class;
    when(handlerMethod.getBeanType()).thenReturn(beanType);
    HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
    Map<String, Object> expectedModel = new HashMap<>();
    expectedModel.put("errorMessageResponse", ErrorMessageResponse.create("message"));
    expectedModel.put("httpStatusCode", 500);
    ModelAndView expectedModelAndView = new ModelAndView("view-exception", expectedModel, httpStatus);
    Object modelAndView = handleException(new Exception("message"), handlerMethod, httpStatus, null, PRODUCTION);
    assertTrue(EqualsBuilder.reflectionEquals(modelAndView, expectedModelAndView));
}
Also used : HttpStatus(org.springframework.http.HttpStatus) HashMap(java.util.HashMap) ExceptionHandlerUtils(org.molgenis.web.exception.ExceptionHandlerUtils) ModelAndView(org.springframework.web.servlet.ModelAndView) HandlerMethod(org.springframework.web.method.HandlerMethod) Test(org.testng.annotations.Test)

Example 34 with HttpStatus

use of org.springframework.http.HttpStatus in project seldon-core by SeldonIO.

the class RestClientController method prediction.

@RequestMapping(value = "/api/v0.1/predictions", method = RequestMethod.POST, consumes = "application/json; charset=utf-8", produces = "application/json; charset=utf-8")
public ResponseEntity<String> prediction(RequestEntity<String> requestEntity, Principal principal) {
    String clientId = principal.getName();
    String json = requestEntity.getBody();
    logger.info(String.format("[%s] [%s] [%s] [%s]", "POST", requestEntity.getUrl().getPath(), clientId, json));
    SeldonMessage request;
    try {
        SeldonMessage.Builder builder = SeldonMessage.newBuilder();
        ProtoBufUtils.updateMessageBuilderFromJson(builder, requestEntity.getBody());
        request = builder.build();
    } catch (InvalidProtocolBufferException e) {
        logger.error("Bad request", e);
        throw new SeldonAPIException(ApiExceptionType.APIFE_INVALID_JSON, requestEntity.getBody());
    }
    HttpStatus httpStatus = HttpStatus.OK;
    // At present passes JSON string. Could use gRPC?
    String ret = predictionService.predict(json, clientId);
    SeldonMessage response;
    try {
        SeldonMessage.Builder builder = SeldonMessage.newBuilder();
        ProtoBufUtils.updateMessageBuilderFromJson(builder, ret);
        response = builder.build();
    } catch (InvalidProtocolBufferException e) {
        logger.error("Bad response", e);
        throw new SeldonAPIException(ApiExceptionType.APIFE_INVALID_RESPONSE_JSON, requestEntity.getBody());
    }
    kafkaProducer.send(clientId, RequestResponse.newBuilder().setRequest(request).setResponse(response).build());
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.APPLICATION_JSON);
    ResponseEntity<String> responseEntity = new ResponseEntity<String>(ret, responseHeaders, httpStatus);
    return responseEntity;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) SeldonMessage(io.seldon.protos.PredictionProtos.SeldonMessage) SeldonAPIException(io.seldon.apife.exception.SeldonAPIException) HttpStatus(org.springframework.http.HttpStatus) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 35 with HttpStatus

use of org.springframework.http.HttpStatus in project account-identity by cryptofiat.

the class AccountMapperController method authenticateIdCard.

@ApiOperation(value = "Associate created address with ID card")
@RequestMapping(method = POST, value = "/authorisations/idCards", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<AccountActivationResponse> authenticateIdCard(@Valid @RequestBody AuthenticateCommand authenticateCommand, Principal principal) throws JSONException, IOException {
    // if (!principal) throw SOME CUSTOM EXCEPTION OF CARD NOT PRESENT
    String ownerId = principal.getName();
    HttpStatus status = HttpStatus.OK;
    String txHash = new String();
    EthereumAccount account = new EthereumAccount();
    List<EthereumAccount> existingAccounts = accountManagementService.getAccountsByAccountAddress(Hex.toHexString(authenticateCommand.getAccountAddress()));
    if (existingAccounts.size() == 0) {
        account = accountManagementService.storeNewAccount(Hex.toHexString(authenticateCommand.getAccountAddress()), ownerId, AuthorisationType.ID_CARD);
        if (accountActivationEnabled) {
            try {
                txHash = ethereumService.activateEthereumAccount(account.getAddress());
                accountManagementService.markActivated(account, txHash);
            } catch (IOException e) {
                log.error("failed to activate account " + account.getAddress() + " on Ethereum", e);
                status = HttpStatus.INTERNAL_SERVER_ERROR;
            }
        }
    } else {
        log.error("Refusing to activate account: {0} binding(s) found already", existingAccounts.size());
        status = HttpStatus.BAD_REQUEST;
    }
    return new ResponseEntity<>(AccountActivationResponse.builder().authenticationStatus(AuthenticationStatus.LOGIN_SUCCESS.name()).ownerId(ownerId).transactionHash(txHash).escrowTransfers(clearEscrow(account)).build(), status);
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) HttpStatus(org.springframework.http.HttpStatus) IOException(java.io.IOException) EthereumAccount(eu.cryptoeuro.accountmapper.domain.EthereumAccount) ApiOperation(io.swagger.annotations.ApiOperation)

Aggregations

HttpStatus (org.springframework.http.HttpStatus)161 ResponseEntity (org.springframework.http.ResponseEntity)39 HttpHeaders (org.springframework.http.HttpHeaders)35 Test (org.junit.jupiter.api.Test)26 MediaType (org.springframework.http.MediaType)17 Mono (reactor.core.publisher.Mono)17 IOException (java.io.IOException)16 ExceptionHandler (org.springframework.web.bind.annotation.ExceptionHandler)14 Collections (java.util.Collections)13 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)13 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)13 URI (java.net.URI)12 List (java.util.List)11 Optional (java.util.Optional)11 Test (org.junit.Test)11 Map (java.util.Map)10 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)9 ClassPathResource (org.springframework.core.io.ClassPathResource)9 Resource (org.springframework.core.io.Resource)9 HashMap (java.util.HashMap)8