Example usage for org.springframework.web.client RestClientException RestClientException

List of usage examples for org.springframework.web.client RestClientException RestClientException

Introduction

In this page you can find the example usage for org.springframework.web.client RestClientException RestClientException.

Prototype

public RestClientException(String msg) 

Source Link

Document

Construct a new instance of RestClientException with the given message.

Usage

From source file:gateway.test.AlertTriggerTests.java

/**
 * Test GET /trigger/*from  w w w.j  a v  a2s  .c om*/
 */
@Test
public void testListTriggers() {
    // Mock Response
    when(restTemplate.getForObject(anyString(), eq(String.class))).thenReturn("Trigger");

    // Test
    ResponseEntity<?> response = alertTriggerController.getTriggers(0, 10, null, "test", user);

    // Verify
    assertTrue(response.getBody().toString().equals("Trigger"));
    assertTrue(response.getStatusCode().equals(HttpStatus.OK));

    // Test Exception
    when(restTemplate.getForObject(anyString(), eq(String.class)))
            .thenThrow(new RestClientException("Trigger Error"));
    response = alertTriggerController.getTriggers(0, 10, null, "test", user);
    assertTrue(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR));
    assertTrue(response.getBody() instanceof ErrorResponse);
    assertTrue(((ErrorResponse) response.getBody()).message.contains("Trigger Error"));
}

From source file:com.netflix.genie.web.tasks.leader.ClusterCheckerTaskUnitTests.java

/**
 * Make sure run method works./*from  w ww .j  a v  a 2s .co  m*/
 *
 * @throws IOException    on error
 * @throws GenieException on error
 */
@Test
public void canRun() throws IOException, GenieException {
    final String host1 = UUID.randomUUID().toString();
    final String host2 = UUID.randomUUID().toString();
    final String host3 = UUID.randomUUID().toString();

    // Mock the 9 invocations for 3 calls to run
    Mockito.when(this.restTemplate.getForObject(Mockito.anyString(), Mockito.anyObject())).thenReturn("")
            .thenThrow(new RestClientException("blah")).thenReturn("").thenReturn("")
            .thenThrow(new RestClientException("blah")).thenReturn("").thenReturn("")
            .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "",
                    ("{\"status\":\"OUT_OF_SERVICE\", \"genie\": { \"status\": \"OUT_OF_SERVICE\"}, "
                            + "\"db\": { \"status\": \"OUT_OF_SERVICE\"}}").getBytes(StandardCharsets.UTF_8),
                    StandardCharsets.UTF_8))
            .thenReturn("").thenReturn("")
            .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "",
                    ("{\"status\":\"OUT_OF_SERVICE\", \"genie\": { \"status\": \"OUT_OF_SERVICE\"}, "
                            + "\"db\": { \"status\": \"OUT_OF_SERVICE\"}}").getBytes(StandardCharsets.UTF_8),
                    StandardCharsets.UTF_8))
            .thenReturn("").thenReturn("")
            .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "",
                    ("{\"status\":\"OUT_OF_SERVICE\", \"genie\": { \"status\": \"OUT_OF_SERVICE\"}, "
                            + "\"db\": { \"status\": \"UP\"}}").getBytes(StandardCharsets.UTF_8),
                    StandardCharsets.UTF_8))
            .thenReturn("").thenReturn("")
            .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "",
                    ("{\"status\":\"OUT_OF_SERVICE\", \"genie\": { \"status\": \"OUT_OF_SERVICE\"}, "
                            + "\"db\": { \"status\": \"OUT_OF_SERVICE\"}}").getBytes(StandardCharsets.UTF_8),
                    StandardCharsets.UTF_8))
            .thenReturn("");

    final List<String> hostsRunningJobs = Lists.newArrayList(this.hostName, host1, host2, host3);
    Mockito.when(this.jobSearchService.getAllHostsWithActiveJobs()).thenReturn(hostsRunningJobs);

    final Job job1 = Mockito.mock(Job.class);
    final String job1Id = UUID.randomUUID().toString();
    Mockito.when(job1.getId()).thenReturn(Optional.of(job1Id));
    final Job job2 = Mockito.mock(Job.class);
    final String job2Id = UUID.randomUUID().toString();
    Mockito.when(job2.getId()).thenReturn(Optional.of(job2Id));
    final Job job3 = Mockito.mock(Job.class);
    final String job3Id = UUID.randomUUID().toString();
    Mockito.when(job3.getId()).thenReturn(Optional.of(job3Id));
    final Job job4 = Mockito.mock(Job.class);
    final String job4Id = UUID.randomUUID().toString();
    Mockito.when(job4.getId()).thenReturn(Optional.of(job4Id));

    Mockito.when(this.jobSearchService.getAllActiveJobsOnHost(host2)).thenReturn(Sets.newHashSet(job1, job2));
    Mockito.when(this.jobSearchService.getAllActiveJobsOnHost(host3)).thenReturn(Sets.newHashSet(job3, job4));

    Mockito.doThrow(new RuntimeException("blah")).doNothing().when(this.jobPersistenceService)
            .setJobCompletionInformation(Mockito.eq(job1Id), Mockito.eq(JobExecution.LOST_EXIT_CODE),
                    Mockito.eq(JobStatus.FAILED), Mockito.anyString(), Mockito.eq(null), Mockito.eq(null));

    this.task.run();
    Assert.assertThat(this.task.getErrorCountsSize(), Matchers.is(1));
    this.task.run();
    Assert.assertThat(this.task.getErrorCountsSize(), Matchers.is(1));
    this.task.run();
    Assert.assertThat(this.task.getErrorCountsSize(), Matchers.is(1));
    this.task.run();
    Assert.assertThat(this.task.getErrorCountsSize(), Matchers.is(0));
    this.task.run();
    Assert.assertThat(this.task.getErrorCountsSize(), Matchers.is(0));
    this.task.run();
    Assert.assertThat(this.task.getErrorCountsSize(), Matchers.is(1));

    Mockito.verify(this.jobPersistenceService, Mockito.times(2)).setJobCompletionInformation(Mockito.eq(job1Id),
            Mockito.eq(JobExecution.LOST_EXIT_CODE), Mockito.eq(JobStatus.FAILED), Mockito.anyString(),
            Mockito.eq(null), Mockito.eq(null));
    Mockito.verify(this.jobPersistenceService, Mockito.atLeast(1)).setJobCompletionInformation(
            Mockito.eq(job2Id), Mockito.eq(JobExecution.LOST_EXIT_CODE), Mockito.eq(JobStatus.FAILED),
            Mockito.anyString(), Mockito.eq(null), Mockito.eq(null));
    Mockito.verify(this.lostJobCounter, Mockito.atLeast(2)).increment();
    Mockito.verify(this.unableToUpdateJobCounter, Mockito.times(1)).increment();
}

From source file:com.dominion.salud.mpr.negocio.service.integracion.impl.BuzonOutServiceImpl.java

/**
 *
 *//*from  w w  w .  j  a  va2s .  c o  m*/
@Override
@Scheduled(cron = "${mpr.task.buzon.out.process.messages}")
public void processMessages() {
    List<BuzonOut> buzonOuts = buzonOutRepository.findAllNoProcesados();
    if (buzonOuts != null && !buzonOuts.isEmpty()) {
        logger.debug("Se han obtenido " + buzonOuts.size() + " mensajes para procesar");

        int contador = 0;
        Iterator<BuzonOut> iterador = buzonOuts.iterator();
        while (iterador.hasNext()) {
            contador++;
            BuzonOut buzonOut = iterador.next();
            buzonOut.setFechaPro(new Date());

            try {
                logger.debug("     Procesando mensaje " + contador + "(" + buzonOut.getIdMensaje() + ") de "
                        + buzonOuts.size());

                if (StringUtils.isBlank(buzonOut.getCentros().getUrl())) {
                    throw new Exception("No se ha indicado la URL de destino (" + buzonOut.getCentros().getUrl()
                            + ") para el centro (" + buzonOut.getCentros().getCodCentro() + ") "
                            + buzonOut.getCentros().getTxtCentro());
                }

                logger.debug("          Iniciando el envio a: " + buzonOut.getCentros().getUrl());
                String response = "";
                switch (buzonOut.getTipo()) {
                case "ZFN_O13": //Acuerdo
                    RestTemplate restTemplate = new RestTemplate();
                    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

                    try {
                        logger.debug("          Enviando el mensaje " + contador + "(" + buzonOut.getIdMensaje()
                                + ") de " + buzonOuts.size());
                        response = restTemplate.postForObject(new URI(buzonOut.getCentros().getUrl()),
                                buzonOut.getMensaje(), String.class);
                        logger.debug("          Respuesta recibida: " + response);
                    } catch (URISyntaxException | RestClientException e) {
                        throw new RestClientException("No se ha podido enviar el mensaje al destinatario ["
                                + buzonOut.toString() + "]: "
                                + (StringUtils.isNotBlank(e.getMessage()) ? e.getMessage() : e.toString()));
                    }
                    break;
                default:
                    logger.error("No se reconoce el formato del mensaje: " + buzonOut.getTipo());
                    throw new Exception("No se reconoce el formato del mensaje: " + buzonOut.getTipo());
                }

                //Evalua la respuesta recibida
                try {
                    logger.debug("          Procesando al respuesta del mensaje " + contador + "("
                            + buzonOut.getIdMensaje() + ") de " + buzonOuts.size());
                    ACK ack = (ACK) new ER7Parser().parse(response);
                    if (!StringUtils.equals(ack.getMSA().getAcknowledgmentCode().getValue(), "AA")
                            && !StringUtils.equals(ack.getMSA().getAcknowledgmentCode().getValue(), "CA")) { //AA - Application Accept o CA - Commit Accept
                        logger.error("Se han producido errores al procesar el mensaje " + contador + "("
                                + buzonOut.getIdMensaje() + ") de " + buzonOuts.size() + " en destino: "
                                + ack.getERR().getDiagnosticInformation().getValue());
                        throw new Exception(ack.getERR().getDiagnosticInformation().getValue());
                    }
                    buzonOut.setEstado(AbstractIntegracionEntity.MENSAJE_PROCESADO);
                } catch (HL7Exception e) {
                    logger.error("No se ha podido procesar la respuesta del mensaje " + contador + "("
                            + buzonOut.getIdMensaje() + ") de " + buzonOuts.size() + ": " + e.getMessage());
                    throw new Exception("No se ha podido procesar la respuesta del mensaje " + contador + "("
                            + buzonOut.getIdMensaje() + ") de " + buzonOuts.size() + ": " + e.getMessage());
                }
            } catch (Exception e) {
                logger.error((StringUtils.isNotBlank(e.getMessage()) ? e.getMessage() : e.toString()));
                buzonOut.setEstado(AbstractIntegracionEntity.MENSAJE_ERRONEO);

                //BuzonErrores
                BuzonErrores buzonErrores = new BuzonErrores();
                buzonErrores.setBuzonOut(buzonOut);
                buzonErrores.setEstado(AbstractIntegracionEntity.MENSAJE_NO_PROCESADO);
                buzonErrores.setFechaError(new Date());
                buzonErrores.setMensaje("<b>SE HAN PRODUCIDO ERRORES AL PROCESAR EL MENSAJE (Saliente)</b><br>"
                        + (StringUtils.isNotBlank(e.getMessage()) ? e.getMessage() : e.toString()));
                buzonErroresService.save(buzonErrores);
            } finally {
                buzonOutRepository.save(buzonOut);
            }
        }
    }
}

From source file:org.trustedanalytics.servicebroker.h2o.service.H2oProvisionerClientTest.java

@Test
public void deprovisionInstance_provisionerEndsWithException_exceptionThrown() throws Exception {
    // arrange/*from   w  w w.ja v  a  2 s .c  om*/
    expectedException.expect(ServiceBrokerException.class);
    expectedException.expectMessage("Unable to deprovision h2o for: " + INSTANCE_ID);
    when(h2oRestMock.deleteH2oInstance(INSTANCE_ID, YARN_CONF)).thenThrow(new RestClientException(""));

    // act
    h2oProvisioner.deprovisionInstance(INSTANCE_ID);
}

From source file:gateway.test.AlertTriggerTests.java

/**
 * Test GET /trigger/{triggerId}/*from w w  w . j a v  a 2s .  co m*/
 */
@Test
public void testGetTrigger() {
    // Mock Response
    when(restTemplate.getForObject(anyString(), eq(String.class))).thenReturn("Trigger");

    // Test
    ResponseEntity<?> response = alertTriggerController.getTrigger("triggerId", user);

    // Verify
    assertTrue(response.getBody().toString().equals("Trigger"));
    assertTrue(response.getStatusCode().equals(HttpStatus.OK));

    // Test Exception
    when(restTemplate.getForObject(anyString(), eq(String.class)))
            .thenThrow(new RestClientException("Trigger Error"));
    response = alertTriggerController.getTrigger("triggerId", user);
    assertTrue(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR));
    assertTrue(response.getBody() instanceof ErrorResponse);
    assertTrue(((ErrorResponse) response.getBody()).message.contains("Trigger Error"));
}

From source file:gateway.test.EventTests.java

/**
 * Test POST /event//from w w w. j a v a  2 s . c  o m
 */
@Test
public void testFireEvent() {
    // Mock Response
    when(restTemplate.postForObject(anyString(), any(), eq(String.class))).thenReturn(any(String.class));

    // Test
    ResponseEntity<?> response = eventController.fireEvent(new Event(), user);

    // Verify
    assertTrue(response.getStatusCode().equals(HttpStatus.CREATED));

    // Test REST Exception
    when(restTemplate.postForObject(anyString(), any(), eq(String.class)))
            .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, WORKFLOW_ERROR));
    response = eventController.fireEvent(new Event(), user);
    assertTrue(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR));

    // Test Exception
    when(restTemplate.postForObject(anyString(), any(), eq(String.class)))
            .thenThrow(new RestClientException("event error"));
    response = eventController.fireEvent(new Event(), user);
    assertTrue(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR));
    assertTrue(response.getBody() instanceof ErrorResponse);
    assertTrue(((ErrorResponse) response.getBody()).message.contains("event error"));
}

From source file:com.sastix.cms.common.client.exception.CommonExceptionHandler.java

/**
 * This default implementation throws a {@link HttpClientErrorException} if the response status code
 * is {@link HttpStatus.Series#CLIENT_ERROR}, a {@link HttpServerErrorException}
 * if it is {@link HttpStatus.Series#SERVER_ERROR},
 * and a {@link RestClientException} in other cases.
 *///from w w w .ja  v  a 2s .com
@Override
public void handleError(ClientHttpResponse response) throws IOException, RestClientException {
    HttpStatus statusCode = getHttpStatusCode(response);
    switch (statusCode.series()) {
    case CLIENT_ERROR:
        final byte[] responseBody = getResponseBody(response);
        final Charset charset = getCharset(response);
        final String statusText = response.getStatusText();
        final HttpHeaders httpHeaders = response.getHeaders();
        final RestErrorDTO errorDTO;

        try {
            errorDTO = objectMapper.readValue(new String(responseBody, charset), RestErrorDTO.class);
            LOG.error("Exception: " + errorDTO.toString());
        } catch (final Exception e) {
            //Wasn't able to map String on ErrorDTO.
            //It is an Unknown Exception
            //Throw Default Exception
            final HttpClientErrorException clientErrorException = new HttpClientErrorException(statusCode,
                    statusText, httpHeaders, responseBody, charset);
            LOG.error("Unknown Exception: " + clientErrorException.getMessage());
            throw clientErrorException;
        }

        if (exceptionClasses.containsKey(errorDTO.getException())) {
            throw (exceptionClasses.get(errorDTO.getException())).create(errorDTO.getMessage());
        } else {
            throw new HttpClientErrorException(statusCode, statusText, httpHeaders, responseBody, charset);
        }

    case SERVER_ERROR:
        throw new HttpServerErrorException(statusCode, response.getStatusText(), response.getHeaders(),
                getResponseBody(response), getCharset(response));
    default:
        throw new RestClientException("Unknown status code [" + statusCode + "]");
    }
}

From source file:org.openmrs.module.webservices.rest.resource.BillResource.java

@Override
public Bill save(Bill bill) {
    //TODO: Test all the ways that this could fail

    if (bill.getId() == null) {
        if (bill.getCashier() == null) {
            Provider cashier = getCurrentCashier(bill);
            if (cashier == null) {
                throw new RestClientException("Couldn't find Provider for the current user ("
                        + Context.getAuthenticatedUser().getName() + ")");
            }/*  w  ww. j  av a 2  s  .co  m*/

            bill.setCashier(cashier);
        }

        if (bill.getCashPoint() == null) {
            loadBillCashPoint(bill);
        }

        // Now that all all attributes have been set (i.e., payments and bill status) we can check to see if the bill
        // is fully paid.
        bill.checkPaidAndUpdateStatus();
        if (bill.getStatus() == null) {
            bill.setStatus(BillStatus.PENDING);
        }
    }

    return super.save(bill);
}

From source file:de.codecentric.boot.admin.services.ApplicationRegistratorTest.java

@SuppressWarnings("rawtypes")
@Test/*from   w w w . j  a  va  2  s. com*/
public void register_multiple_one_failure() {
    adminProps.setRegisterOnce(false);

    when(restTemplate.postForEntity(isA(String.class), isA(HttpEntity.class), eq(Map.class)))
            .thenReturn(new ResponseEntity<Map>(Collections.singletonMap("id", "-id-"), HttpStatus.CREATED))
            .thenThrow(new RestClientException("Error"));

    assertTrue(registrator.register());

    verify(restTemplate).postForEntity("http://sba:8080/api/applications",
            new HttpEntity<>(Application.create("AppName").withHealthUrl("http://localhost:8080/health")
                    .withManagementUrl("http://localhost:8080/mgmt").withServiceUrl("http://localhost:8080")
                    .build(), headers),
            Map.class);

    verify(restTemplate).postForEntity("http://sba2:8080/api/applications",
            new HttpEntity<>(Application.create("AppName").withHealthUrl("http://localhost:8080/health")
                    .withManagementUrl("http://localhost:8080/mgmt").withServiceUrl("http://localhost:8080")
                    .build(), headers),
            Map.class);
}