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

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

Introduction

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

Prototype

public HttpClientErrorException(HttpStatus statusCode) 

Source Link

Document

Constructor with a status code only.

Usage

From source file:org.openlmis.fulfillment.service.ObjReferenceExpanderTest.java

@Test
public void shouldNotFailIfResourceDoesNotExist() {
    when(restTemplate.exchange(any(URI.class), eq(HttpMethod.GET), any(RequestEntity.class), eq(Map.class)))
            .thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND));

    objReferenceExpander.expandDto(testDto, singleton(EXPANDED_OBJECT_REFERENCE_DTO_FIELD));

    assertNotNull(testDto);//w  w  w  .  j  a  va 2  s. co  m
    ExpandedObjectReferenceDto actual = testDto.getExpandedObjectReferenceDto();
    checkOriginalProperties(actual);

    // No expanded properties should be set
    assertNull(actual.getExpandedStringProperty());
    assertNull(actual.getExpandedListProperty());
    assertNull(actual.getExpandedUuidProperty());
    assertNull(actual.getExpandedNestedProperty());
}

From source file:org.trustedanalytics.h2oscoringengine.publisher.http.FilesDownloaderTest.java

@Test
public void download_serverResponseErrorOtherThan401And404_excpetionWithProperMessageThrown()
        throws IOException {
    // given/*from  www  .  j  ava  2  s. c o m*/
    FilesDownloader downloader = new FilesDownloader(testCredentials, restTemplateMock);
    HttpStatus expectedErrorStatus = HttpStatus.BAD_GATEWAY;
    String expectedExceptionMessage = "Server response status: " + expectedErrorStatus;

    // when
    when(restTemplateMock.exchange(testCredentials.getHost() + testResource, HttpMethod.GET,
            HttpCommunication.basicAuthRequest(testCredentials.getBasicAuthToken()), byte[].class))
                    .thenThrow(new HttpClientErrorException(expectedErrorStatus));

    // then
    thrown.expect(IOException.class);
    thrown.expectMessage(expectedExceptionMessage);
    downloader.download(testResource, testPath);
}

From source file:access.test.PiazzaEnvironmentTests.java

@Test
public void testResourcesCauseServerError() {
    Mockito.when(this.restTemplate.exchange(Mockito.endsWith("/workspaces/piazza.json"),
            Mockito.eq(HttpMethod.GET), Mockito.any(), Mockito.eq(String.class)))
            .thenThrow(new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR));

    Mockito.when(this.restTemplate.exchange(Mockito.endsWith("/datastores/piazza.json"),
            Mockito.eq(HttpMethod.GET), Mockito.any(), Mockito.eq(String.class)))
            .thenThrow(new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR));

    piazzaEnvironment.initializeEnvironment();
    assertTrue(true); // no error occurred
}

From source file:com.epl.ticketws.services.QueryService.java

public T query(String url, String method, String accept, Class<T> rc, Map<String, String> parameters) {

    try {/*from   ww w.  ja va2 s. c om*/
        URI uri = new URL(url).toURI();
        long timestamp = new Date().getTime();

        HttpMethod httpMethod;
        if (method.equalsIgnoreCase("post")) {
            httpMethod = HttpMethod.POST;
        } else {
            httpMethod = HttpMethod.GET;
        }

        String stringToSign = getStringToSign(uri, httpMethod.name(), timestamp, parameters);

        // logger.info("String to sign: " + stringToSign);
        String authorization = generate_HMAC_SHA1_Signature(stringToSign, password + license);
        // logger.info("Authorization string: " + authorization);

        // Setting Headers
        HttpHeaders headers = new HttpHeaders();
        if (accept.equalsIgnoreCase("json")) {
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        } else {
            headers.setAccept(Arrays.asList(MediaType.TEXT_XML));
        }

        headers.add("Authorization", authorization);
        headers.add("OB_DATE", "" + timestamp);
        headers.add("OB_Terminal", terminal);
        headers.add("OB_User", user);
        headers.add("OB_Channel", channel);
        headers.add("OB_POS", pos);
        headers.add("Content-Type", "application/x-www-form-urlencoded");

        HttpEntity<String> entity;

        if (httpMethod == HttpMethod.POST) {
            // Adding post parameters to POST body
            String parameterStringBody = getParametersAsString(parameters);
            entity = new HttpEntity<String>(parameterStringBody, headers);
            // logger.info("POST Body: " + parameterStringBody);
        } else {
            entity = new HttpEntity<String>(headers);
        }

        RestTemplate restTemplate = new RestTemplate(
                new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
        interceptors.add(new LoggingRequestInterceptor());
        restTemplate.setInterceptors(interceptors);

        // Converting to UTF-8. OB Rest replies in windows charset.
        //restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName(UTF_8)));

        if (accept.equalsIgnoreCase("json")) {
            restTemplate.getMessageConverters().add(0,
                    new org.springframework.http.converter.json.MappingJackson2HttpMessageConverter());
        } else {
            restTemplate.getMessageConverters().add(0,
                    new org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter());
        }

        ResponseEntity<T> response = restTemplate.exchange(uri, httpMethod, entity, rc);

        if (!response.getStatusCode().is2xxSuccessful())
            throw new HttpClientErrorException(response.getStatusCode());

        return response.getBody();
    } catch (HttpClientErrorException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (MalformedURLException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (SignatureException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (URISyntaxException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }
    return null;
}

From source file:org.trustedanalytics.user.invite.RegistrationsControllerTest.java

@Test(expected = HttpClientErrorException.class)
public void testAddUser_createUserHttpConnectionError_throwHttpError() {
    SecurityCode sc = new SecurityCode(USER_EMAIL, SECURITY_CODE);
    doReturn(sc).when(securityCodeService).verify(Matchers.anyString());
    RegistrationModel registration = new RegistrationModel();
    registration.setPassword("123456");
    registration.setOrg("abcdefgh");
    doReturn(true).when(accessInvitationsService).getOrgCreationEligibility(Matchers.anyString());
    doThrow(new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR)).when(invitationsService)
            .createUser(Matchers.anyString(), Matchers.anyString(), Matchers.anyString());

    sut.addUser(registration, SECURITY_CODE);
}

From source file:access.test.PiazzaEnvironmentTests.java

@Test
public void testResourceCreationServerError() {
    Mockito.when(this.restTemplate.exchange(Mockito.endsWith("/workspaces/piazza.json"),
            Mockito.eq(HttpMethod.GET), Mockito.any(), Mockito.eq(String.class)))
            .thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND));
    Mockito.when(this.restTemplate.exchange(Mockito.endsWith("/workspaces"), Mockito.eq(HttpMethod.POST),
            Mockito.any(), Mockito.eq(String.class)))
            .thenReturn(new ResponseEntity<>("{\"result\": \"all good\"}", HttpStatus.OK))
            .thenThrow(new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR))
            .thenThrow(new RuntimeException());
    Mockito.when(this.restTemplate.exchange(Mockito.endsWith("/workspaces/piazza.xml"),
            Mockito.eq(HttpMethod.PUT), Mockito.any(), Mockito.eq(String.class)))
            .thenThrow(new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR));

    Mockito.when(this.restTemplate.exchange(Mockito.endsWith("/datastores/piazza.json"),
            Mockito.eq(HttpMethod.GET), Mockito.any(), Mockito.eq(String.class)))
            .thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND));
    Mockito.when(this.restTemplate.exchange(Mockito.endsWith("/datastores"), Mockito.eq(HttpMethod.POST),
            Mockito.any(), Mockito.eq(String.class)))
            .thenThrow(new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR))
            .thenThrow(new RuntimeException());

    this.piazzaEnvironment.initializeEnvironment();
    this.piazzaEnvironment.initializeEnvironment();
    this.piazzaEnvironment.initializeEnvironment();
}

From source file:gov.fda.open.demo.service.FDADataProxyServiceImplTest.java

/**
 * Test get drug summary not found./*from   w  w w.  j a  va  2s. com*/
 */
@SuppressWarnings("serial")
@Test
@Loggable(LogLevel.OFF)
public void testGetDrugSummaryNotFound() {

    // Execute
    GetDrugAdverseSummaryRequest request = new GetDrugAdverseSummaryRequest(DRUG_NAME_2);

    // Setup Mock
    SearchTermBuilder searchParamBuilder = new SearchTermBuilder();
    searchParamBuilder.exists(request.getSummaryType().getField()).and()
            .appendTerm(MEDICINAL_PRODUCT, request.getDrugName()).and()
            .between(RECEIVED_DATE, request.getStartDate(), request.getEndDate());
    // build query String
    String searchTerm = searchParamBuilder.toString();

    StringBuilder drugURL = new StringBuilder(URI_VALUE);
    drugURL.append(FDADataProxyServiceImpl.DRUG_EVENT_SEARCH_URL);

    final Map<String, String> params = new HashMap<String, String>();
    params.put(SEARCH_KEY, searchTerm);
    params.put(APP_KEY, APP_VALUE);
    params.put(LIMIT_KEY, String.valueOf(100));
    params.put(SKIP_KEY, String.valueOf(0));

    URI httpUri = UriComponentsBuilder.fromHttpUrl(drugURL.toString()).buildAndExpand(params).toUri();

    // / Test case when HttpClientException is throw
    when(template.getForObject(httpUri, String.class))
            .thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND) {
                @Override
                public String getResponseBodyAsString() {
                    return "{ \"error\": { \"code\": \"NOT_FOUND\", \"message\": \"No matches found!\" } }";
                }
            });

    GetDrugAdverseSummaryResponse response = fdaDataProxyService.getDrugAdverseSummary(request);
    assertNotNull(response);
    assertFalse(response.isSuccess());
    assertNotNull(response.getErrorCode());
    assertNotNull(response.getMessage());

}

From source file:eionet.webq.web.interceptor.CdrAuthorizationInterceptorTest.java

private void restClientWillThrowException() {
    when(restOperations.postForEntity(anyString(), anyObject(), any(Class.class)))
            .thenThrow(new HttpClientErrorException(HttpStatus.UNAUTHORIZED));
}

From source file:com.netflix.genie.web.controllers.JobRestControllerUnitTests.java

/**
 * Makes sure if we do forward and get back an error we return it to the user.
 *
 * @throws IOException      on error// w  w w  . j ava  2  s  .  co  m
 * @throws ServletException on error
 * @throws GenieException   on error
 */
@Test
public void canRespondToKillRequestForwardError() throws IOException, ServletException, GenieException {
    this.jobsProperties.getForwarding().setEnabled(true);
    final String jobId = UUID.randomUUID().toString();
    final String forwardedFrom = null;
    final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

    Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer(UUID.randomUUID().toString()));
    Mockito.when(this.jobSearchService.getJobHost(jobId)).thenReturn(UUID.randomUUID().toString());

    final StatusLine statusLine = Mockito.mock(StatusLine.class);
    Mockito.when(statusLine.getStatusCode()).thenReturn(HttpStatus.NOT_FOUND.value());
    final HttpResponse forwardResponse = Mockito.mock(HttpResponse.class);
    Mockito.when(forwardResponse.getStatusLine()).thenReturn(statusLine);
    Mockito.when(this.restTemplate.execute(Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(),
            Mockito.anyString())).thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND));

    this.controller.killJob(jobId, forwardedFrom, request, response);

    Mockito.verify(response, Mockito.times(1)).sendError(Mockito.eq(HttpStatus.NOT_FOUND.value()),
            Mockito.anyString());
    Mockito.verify(this.jobSearchService, Mockito.times(1)).getJobHost(jobId);
    Mockito.verify(this.restTemplate, Mockito.times(1)).execute(Mockito.anyString(), Mockito.any(),
            Mockito.any(), Mockito.any(), Mockito.anyString());
}

From source file:com.ge.predix.uaa.token.lib.ZacTokenServiceTest.java

@SuppressWarnings("unchecked")
private OAuth2Authentication loadAuthentication(final String zoneName, final String zoneUserScope,
        final String requestUri, final List<String> nonZoneUriPatterns) {

    ZacTokenService zacTokenServices = new ZacTokenService();
    zacTokenServices.setServiceZoneHeaders(PREDIX_ZONE_HEADER_NAME);

    Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
    authorities.add(new SimpleGrantedAuthority(zoneUserScope));

    OAuth2Authentication oauth2Authentication = Mockito.mock(OAuth2Authentication.class);

    Mockito.when(oauth2Authentication.isAuthenticated()).thenReturn(true);
    FastTokenServices mockFTS = Mockito.mock(FastTokenServices.class);
    Mockito.doNothing().when(mockFTS).setUseHttps(true);
    Mockito.doNothing().when(mockFTS).setStoreClaims(true);
    Mockito.doNothing().when(mockFTS).setTrustedIssuers(Matchers.anyList());
    Mockito.when(oauth2Authentication.getAuthorities()).thenReturn(authorities);
    Mockito.when(mockFTS.loadAuthentication(Matchers.anyString())).thenReturn(oauth2Authentication);

    FastTokenServicesCreator mockFTSC = Mockito.mock(FastTokenServicesCreator.class);
    when(mockFTSC.newInstance()).thenReturn(mockFTS);

    zacTokenServices.setFastRemoteTokenServicesCreator(mockFTSC);
    zacTokenServices.setServiceBaseDomain(BASE_DOMAIN);
    zacTokenServices.setServiceId(SERVICEID);

    DefaultZoneConfiguration zoneConfig = new DefaultZoneConfiguration();

    List<String> trustedIssuers;
    // Non zone specific request, using default issuer
    if (StringUtils.isEmpty(zoneName)) {
        trustedIssuers = Arrays.asList(DEFAULT_TRUSTED_ISSUER);
        // Zone specific request, using the issuers returned by mockTrustedIssuersResponseEntity
    } else {//  w w  w .j  av  a2 s.c o  m
        trustedIssuers = ZONE_TRUSTED_ISSUERS;
    }
    zoneConfig.setTrustedIssuerIds(trustedIssuers);
    zacTokenServices.setDefaultZoneConfig(zoneConfig);
    zoneConfig.setAllowedUriPatterns(nonZoneUriPatterns);

    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    when(request.getServerName()).thenReturn("localhost");
    when(request.getHeader(PREDIX_ZONE_HEADER_NAME)).thenReturn(zoneName);
    when(request.getRequestURI()).thenReturn(requestUri);
    zacTokenServices.setRequest(request);
    RestTemplate restTemplateMock = Mockito.mock(RestTemplate.class);
    zacTokenServices.setOauth2RestTemplate(restTemplateMock);
    try {
        zacTokenServices.afterPropertiesSet();
    } catch (Exception e) {
        Assert.fail("Unexpected exception after properties set on zacTokenServices " + e.getMessage());
    }

    when(restTemplateMock.getForEntity("null/v1/registration/" + SERVICEID + "/" + ZONE, TrustedIssuers.class))
            .thenReturn(mockTrustedIssuersResponseEntity());

    when(restTemplateMock.getForEntity("null/v1/registration/" + SERVICEID + "/" + INVALID_ZONE,
            TrustedIssuers.class)).thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND));

    String accessToken = this.tokenUtil.mockAccessToken(600, zoneUserScope);
    OAuth2Authentication loadAuthentication = zacTokenServices.loadAuthentication(accessToken);

    // Making sure we are passing the right set of issuers to the FastTokenServices
    Mockito.verify(mockFTS).setTrustedIssuers(trustedIssuers);
    return loadAuthentication;
}