org.springframework.web.client.HttpServerErrorException Java Examples

The following examples show how to use org.springframework.web.client.HttpServerErrorException. 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: AbstractXhrTransport.java    From spring-analysis-note with MIT License 7 votes vote down vote up
@Override
public void executeSendRequest(URI url, HttpHeaders headers, TextMessage message) {
	if (logger.isTraceEnabled()) {
		logger.trace("Starting XHR send, url=" + url);
	}
	ResponseEntity<String> response = executeSendRequestInternal(url, headers, message);
	if (response.getStatusCode() != HttpStatus.NO_CONTENT) {
		if (logger.isErrorEnabled()) {
			logger.error("XHR send request (url=" + url + ") failed: " + response);
		}
		throw new HttpServerErrorException(response.getStatusCode());
	}
	if (logger.isTraceEnabled()) {
		logger.trace("XHR send request (url=" + url + ") response: " + response);
	}
}
 
Example #2
Source File: RestClientResponseErrorHandler.java    From sinavi-jfw with Apache License 2.0 6 votes vote down vote up
/**
 * HTTPステータスコード:5xx(サーバエラー)に対応した例外をスローします。ステータスコードと例外の対応は以下のとおりです。
 * @param statusCode HTTPステータス
 * @param response HTTPレスポンス
 * @throws IOException I/O例外
 */
protected void handleServerError(HttpStatus statusCode, ClientHttpResponse response) throws IOException {
    switch (statusCode) {
        case INTERNAL_SERVER_ERROR:
            if (L.isDebugEnabled()) {
                L.debug(Strings.substitute(R.getString("D-SPRINGMVC-REST-CLIENT-HANDLER#0011"), 
                    Maps.hash("status", statusCode.toString())
                        .map("message", getResponseBodyAsString(response))));
            }
            throw new InternalServerErrorException(response.getHeaders(), getResponseBody(response), getCharset(response));
        case SERVICE_UNAVAILABLE:
            if (L.isDebugEnabled()) {
                L.debug(Strings.substitute(R.getString("D-SPRINGMVC-REST-CLIENT-HANDLER#0012"), 
                    Maps.hash("status", statusCode.toString())
                        .map("message", getResponseBodyAsString(response))));
            }
            throw new ServiceUnavailableException(response.getHeaders(), getResponseBody(response), getCharset(response));
        default:
            if (L.isDebugEnabled()) {
                L.debug(Strings.substitute(R.getString("D-SPRINGMVC-REST-CLIENT-HANDLER#0013"), 
                    Maps.hash("status", statusCode.toString())
                        .map("message", getResponseBodyAsString(response))));
            }
            throw new HttpServerErrorException(statusCode, response.getStatusText(), response.getHeaders(), getResponseBody(response), getCharset(response));
    }
}
 
Example #3
Source File: AccountsController.java    From pivotal-bank-demo with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/accounts", method = RequestMethod.GET)
public String accounts(Model model) {
	logger.debug("/accounts");
	model.addAttribute("marketSummary", summaryService.getMarketSummary());
	
	//check if user is logged in!
	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	if (!(authentication instanceof AnonymousAuthenticationToken)) {
	    String currentUserName = authentication.getName();
	    logger.debug("accounts: User logged in: " + currentUserName);
	    
	    try {
	    	model.addAttribute("accounts",accountService.getAccounts(currentUserName));
	    } catch (HttpServerErrorException e) {
	    	logger.debug("error retrieving accounts: " + e.getMessage());
	    	model.addAttribute("accountsRetrievalError",e.getMessage());
	    }
	}
	
	return "accounts";
}
 
Example #4
Source File: CustomAuthenticationProvider.java    From pivotal-bank-demo with Apache License 2.0 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication)
		throws AuthenticationException {
	String name = authentication.getName();
	String password = authentication.getCredentials().toString();
	AuthenticationRequest request = new AuthenticationRequest();
	request.setUsername(name);
	request.setPassword(password);
	try {
		Map<String, Object> params = service.login(request);
		if (params != null) {
			List<GrantedAuthority> grantedAuths = new ArrayList<>();
			grantedAuths.add(new SimpleGrantedAuthority("USER"));
			Authentication auth = new UsernamePasswordAuthenticationToken(
					name, password, grantedAuths);
			return auth;
		} else {
			throw new BadCredentialsException("Username not found");
		}
	} catch (HttpServerErrorException e) {
		throw new BadCredentialsException("Login failed!");
	}
}
 
Example #5
Source File: RestTemplateXhrTransportTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void connectFailure() throws Exception {
	final HttpServerErrorException expected = new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR);
	RestOperations restTemplate = mock(RestOperations.class);
	given(restTemplate.execute((URI) any(), eq(HttpMethod.POST), any(), any())).willThrow(expected);

	final CountDownLatch latch = new CountDownLatch(1);
	connect(restTemplate).addCallback(
			new ListenableFutureCallback<WebSocketSession>() {
				@Override
				public void onSuccess(WebSocketSession result) {
				}
				@Override
				public void onFailure(Throwable ex) {
					if (ex == expected) {
						latch.countDown();
					}
				}
			}
	);
	verifyNoMoreInteractions(this.webSocketHandler);
}
 
Example #6
Source File: GatewayApplicationTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Test
public void testBrokerFileHostNotExist() {
    try {
        HttpHeaders headers = new HttpHeaders();
        headers.add("file_host", "not_exist");
        HttpEntity<?> requestEntity = new HttpEntity<>(headers);
        this.restTemplate.exchange(this.url + "/weevent-broker/admin/getVersion",
                HttpMethod.GET,
                requestEntity,
                String.class,
                new HashMap<>());

        Assert.fail();
    } catch (HttpServerErrorException.ServiceUnavailable e) {
        //503 Service Unavailable
        Assert.assertTrue(true);
    }
}
 
Example #7
Source File: AbstractXhrTransport.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public String executeInfoRequest(URI infoUrl, @Nullable HttpHeaders headers) {
	if (logger.isDebugEnabled()) {
		logger.debug("Executing SockJS Info request, url=" + infoUrl);
	}
	HttpHeaders infoRequestHeaders = new HttpHeaders();
	if (headers != null) {
		infoRequestHeaders.putAll(headers);
	}
	ResponseEntity<String> response = executeInfoRequestInternal(infoUrl, infoRequestHeaders);
	if (response.getStatusCode() != HttpStatus.OK) {
		if (logger.isErrorEnabled()) {
			logger.error("SockJS Info request (url=" + infoUrl + ") failed: " + response);
		}
		throw new HttpServerErrorException(response.getStatusCode());
	}
	if (logger.isTraceEnabled()) {
		logger.trace("SockJS Info request (url=" + infoUrl + ") response: " + response);
	}
	String result = response.getBody();
	return (result != null ? result : "");
}
 
Example #8
Source File: RestTemplateXhrTransportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void connectFailure() throws Exception {
	final HttpServerErrorException expected = new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR);
	RestOperations restTemplate = mock(RestOperations.class);
	given(restTemplate.execute((URI) any(), eq(HttpMethod.POST), any(), any())).willThrow(expected);

	final CountDownLatch latch = new CountDownLatch(1);
	connect(restTemplate).addCallback(
			new ListenableFutureCallback<WebSocketSession>() {
				@Override
				public void onSuccess(WebSocketSession result) {
				}
				@Override
				public void onFailure(Throwable ex) {
					if (ex == expected) {
						latch.countDown();
					}
				}
			}
	);
	verifyNoMoreInteractions(this.webSocketHandler);
}
 
Example #9
Source File: UserController.java    From pivotal-bank-demo with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/", method = RequestMethod.GET)
public String showHome(Model model) {
	if (!model.containsAttribute("login")) {
		model.addAttribute("login", new AuthenticationRequest());
	}
	model.addAttribute("marketSummary", summaryService.getMarketSummary());
	
	//check if user is logged in!
	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	if (!(authentication instanceof AnonymousAuthenticationToken)) {
	    String currentUserName = authentication.getName();
	    logger.debug("User logged in: " + currentUserName);
	    
	    try {
	    	model.addAttribute("accounts",accountService.getAccounts(currentUserName));
	    	model.addAttribute("portfolio",portfolioService.getPortfolio(currentUserName));
	    } catch (HttpServerErrorException e) {
	    	model.addAttribute("portfolioRetrievalError",e.getMessage());
	    }
	    User user = userService.getUser(currentUserName);
	    model.addAttribute("user", user);
	    model.addAttribute("accounts",accountService.getAccounts(currentUserName));
	}
	
	return "index";
}
 
Example #10
Source File: TradeController.java    From pivotal-bank-demo with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/trade", method = RequestMethod.GET)
public String showTrade(Model model) {
	logger.debug("/trade.GET");
	//model.addAttribute("marketSummary", marketService.getMarketSummary());
	
	model.addAttribute("search", new Search());
	//check if user is logged in!
	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	if (!(authentication instanceof AnonymousAuthenticationToken)) {
	    String currentUserName = authentication.getName();
	    logger.debug("User logged in: " + currentUserName);
	    model.addAttribute("order", new Order());
	    
	    try {
	    	model.addAttribute("portfolio",portfolioService.getPortfolio(currentUserName));
	    	model.addAttribute("accounts",accountService.getAccounts(currentUserName));
	    } catch (HttpServerErrorException e) {
	    	model.addAttribute("portfolioRetrievalError",e.getMessage());
	    }
	}
	
	return "trade";
}
 
Example #11
Source File: PortfolioController.java    From pivotal-bank-demo with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/portfolio", method = RequestMethod.GET)
public String portfolio(Model model) {
	logger.debug("/portfolio");
	model.addAttribute("marketSummary", summaryService.getMarketSummary());
	
	//check if user is logged in!
	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	if (!(authentication instanceof AnonymousAuthenticationToken)) {
	    String currentUserName = authentication.getName();
	    logger.debug("portfolio: User logged in: " + currentUserName);
	    
	    //TODO: add account summary.
	    try {
	    	model.addAttribute("portfolio",portfolioService.getPortfolio(currentUserName));
	    	model.addAttribute("accounts",accountService.getAccounts(currentUserName));
	    } catch (HttpServerErrorException e) {
	    	logger.debug("error retrieving portfolfio: " + e.getMessage());
	    	model.addAttribute("portfolioRetrievalError",e.getMessage());
	    }
	    model.addAttribute("order", new Order());
	}
	
	return "portfolio";
}
 
Example #12
Source File: PortfolioController.java    From cf-SpringBootTrader with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/portfolio", method = RequestMethod.GET)
public String portfolio(Model model) {
	logger.debug("/portfolio");
	model.addAttribute("marketSummary", summaryService.getMarketSummary());
	
	//check if user is logged in!
	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	if (!(authentication instanceof AnonymousAuthenticationToken)) {
	    String currentUserName = authentication.getName();
	    logger.debug("portfolio: User logged in: " + currentUserName);
	    
	    //TODO: add account summary.
	    try {
	    	model.addAttribute("portfolio",marketService.getPortfolio(currentUserName));
	    } catch (HttpServerErrorException e) {
	    	logger.debug("error retrieving portfolfio: " + e.getMessage());
	    	model.addAttribute("portfolioRetrievalError",e.getMessage());
	    }
	    model.addAttribute("order", new Order());
	}
	
	return "portfolio";
}
 
Example #13
Source File: GatewaySecurityService.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies JWT token validity and returns JWT token data
 *
 * @param token JWT token to be validated
 * @return JWT token data as {@link QueryResponse}
 */
public QueryResponse query(String token) {
    GatewayConfigProperties gatewayConfigProperties = gatewayClient.getGatewayConfigProperties();
    String uri = String.format("%s://%s%s", gatewayConfigProperties.getScheme(),
        gatewayConfigProperties.getHostname(), authConfigurationProperties.getGatewayQueryEndpoint());
    String cookie = String.format("%s=%s", authConfigurationProperties.getCookieProperties().getCookieName(), token);

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.COOKIE, cookie);

    try {
        ResponseEntity<QueryResponse> response = restTemplate.exchange(
            uri,
            HttpMethod.GET,
            new HttpEntity<>(headers),
            QueryResponse.class);

        return response.getBody();
    } catch (HttpClientErrorException | ResourceAccessException | HttpServerErrorException e) {
        responseHandler.handleBadResponse(e, ErrorType.TOKEN_NOT_VALID,
            "Can not access Gateway service. Uri '{}' returned: {}", uri, e.getMessage());
    }
    return null;
}
 
Example #14
Source File: TradeController.java    From cf-SpringBootTrader with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/order", method = RequestMethod.POST)
public String buy(Model model, @ModelAttribute("order") Order order) {
	model.addAttribute("search", new Search());
	
	// buy the order after setting attributes not set by the UI.
	//check if user is logged in!
			Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
			if (!(authentication instanceof AnonymousAuthenticationToken)) {
			    String currentUserName = authentication.getName();
			    logger.debug("/order ORDER: " + order);
			    order.setAccountId(currentUserName);
			    order.setCompletionDate(new Date());

			    Order result = marketService.sendOrder(order);
			    model.addAttribute("savedOrder", result);
			    model.addAttribute("order", new Order());
			    try {
			    	model.addAttribute("portfolio",marketService.getPortfolio(currentUserName));
			    } catch (HttpServerErrorException e) {
			    	model.addAttribute("portfolioRetrievalError",e.getMessage());
			    }
			} else {
				//should never get here!!!
			}
	return "trade";
}
 
Example #15
Source File: RequestBuilder.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Check the response result of the invocation
 *
 * @param response
 * @return
 * @throws Throwable
 */
protected InputStream checkResponse(HttpResponse response) throws Throwable {
    InputStream ris = null;

    if (null != response
            && null != response.getEntity()) {
        int code = response.getStatusLine().getStatusCode();

        // get the body input stream
        ris = response.getEntity().getContent();
        // check if the result of the call matches the expected one
        if (code == _endpopoint.getExpected()) {
            if (_debug) {
                logger.info("returned status: {}",response.getStatusLine().getStatusCode());
            }
        } else {
            if (_debug) {
                String body = IOUtils.toString(ris, "UTF-8");
                logger.info("unexpected status: {} \n Body: {}",response.getStatusLine().getStatusCode(),body);
            }
            throw new HttpServerErrorException(HttpStatus.valueOf(code), "Unexpected HTTP status returned: " + code);
        }
    }
    return ris;
}
 
Example #16
Source File: UserController.java    From cf-SpringBootTrader with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/", method = RequestMethod.GET)
public String showHome(Model model) {
	if (!model.containsAttribute("login")) {
		model.addAttribute("login", new AuthenticationRequest());
	}
	model.addAttribute("marketSummary", summaryService.getMarketSummary());
	
	//check if user is logged in!
	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	if (!(authentication instanceof AnonymousAuthenticationToken)) {
	    String currentUserName = authentication.getName();
	    logger.debug("User logged in: " + currentUserName);
	    
	    try {
	    	model.addAttribute("portfolio",marketService.getPortfolio(currentUserName));
	    } catch (HttpServerErrorException e) {
	    	model.addAttribute("portfolioRetrievalError",e.getMessage());
	    }
	    model.addAttribute("account",accountService.getAccount(currentUserName));
	}
	
	return "index";
}
 
Example #17
Source File: CustomAuthenticationProvider.java    From cf-SpringBootTrader with Apache License 2.0 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication)
		throws AuthenticationException {
	String name = authentication.getName();
	String password = authentication.getCredentials().toString();
	AuthenticationRequest request = new AuthenticationRequest();
	request.setUsername(name);
	request.setPassword(password);
	try {
		Map<String, Object> params = service.login(request);
		if (params != null) {
			List<GrantedAuthority> grantedAuths = new ArrayList<>();
			grantedAuths.add(new SimpleGrantedAuthority("USER"));
			Authentication auth = new UsernamePasswordAuthenticationToken(
					name, password, grantedAuths);
			return auth;
		} else {
			throw new BadCredentialsException("Username not found");
		}
	} catch (HttpServerErrorException e) {
		throw new BadCredentialsException("Login failed!");
	}
}
 
Example #18
Source File: HeimdallResponseErrorHandler.java    From heimdall with Apache License 2.0 6 votes vote down vote up
/**
 * This default implementation throws a {@link HttpClientErrorException} if the response status code
 * is {@link org.springframework.http.HttpStatus.Series#CLIENT_ERROR}, a {@link HttpServerErrorException}
 * if it is {@link org.springframework.http.HttpStatus.Series#SERVER_ERROR},
 * and a {@link RestClientException} in other cases.
 */
@Override
public void handleError(ClientHttpResponse response) throws IOException {
	HttpStatus statusCode = getHttpStatusCode(response);
	switch (statusCode.series()) {
		case CLIENT_ERROR:
			throw new HttpClientErrorException(statusCode, response.getStatusText(),
					response.getHeaders(), getResponseBody(response), getCharset(response));
		case SERVER_ERROR:
			throw new HttpServerErrorException(statusCode, response.getStatusText(),
					response.getHeaders(), getResponseBody(response), getCharset(response));
		default:
			throw new UnknownHttpStatusCodeException(statusCode.value(), response.getStatusText(),
					response.getHeaders(), getResponseBody(response), getCharset(response));
	}
}
 
Example #19
Source File: CustomRemoteTokenServices.java    From microservice-integration with MIT License 6 votes vote down vote up
private Map<String, Object> postForMap(String path, MultiValueMap<String, String> formData, HttpHeaders headers) {
    if (headers.getContentType() == null) {
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    }
    @SuppressWarnings("rawtypes")
    Map map = new HashMap();
    try {
        map = restTemplate.exchange(path, HttpMethod.POST,
                new HttpEntity<MultiValueMap<String, String>>(formData, headers), Map.class).getBody();
    } catch (HttpClientErrorException e1) {
        logger.error("catch token exception when check token!", e1);
        map.put(ERROR, e1.getStatusCode());

    } catch (HttpServerErrorException e2) {
        logger.error("catch no permission exception when check token!", e2);
        map.put(ERROR, e2.getStatusCode());

    } catch (Exception e) {
        logger.error("catch common exception when check token!", e);
    }

    @SuppressWarnings("unchecked")
    Map<String, Object> result = map;
    return result;
}
 
Example #20
Source File: AbstractXhrTransport.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public String executeInfoRequest(URI infoUrl, HttpHeaders headers) {
	if (logger.isDebugEnabled()) {
		logger.debug("Executing SockJS Info request, url=" + infoUrl);
	}
	HttpHeaders infoRequestHeaders = new HttpHeaders();
	infoRequestHeaders.putAll(getRequestHeaders());
	if (headers != null) {
		infoRequestHeaders.putAll(headers);
	}
	ResponseEntity<String> response = executeInfoRequestInternal(infoUrl, infoRequestHeaders);
	if (response.getStatusCode() != HttpStatus.OK) {
		if (logger.isErrorEnabled()) {
			logger.error("SockJS Info request (url=" + infoUrl + ") failed: " + response);
		}
		throw new HttpServerErrorException(response.getStatusCode());
	}
	if (logger.isTraceEnabled()) {
		logger.trace("SockJS Info request (url=" + infoUrl + ") response: " + response);
	}
	return response.getBody();
}
 
Example #21
Source File: AbstractXhrTransport.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void executeSendRequest(URI url, HttpHeaders headers, TextMessage message) {
	if (logger.isTraceEnabled()) {
		logger.trace("Starting XHR send, url=" + url);
	}
	ResponseEntity<String> response = executeSendRequestInternal(url, headers, message);
	if (response.getStatusCode() != HttpStatus.NO_CONTENT) {
		if (logger.isErrorEnabled()) {
			logger.error("XHR send request (url=" + url + ") failed: " + response);
		}
		throw new HttpServerErrorException(response.getStatusCode());
	}
	if (logger.isTraceEnabled()) {
		logger.trace("XHR send request (url=" + url + ") response: " + response);
	}
}
 
Example #22
Source File: RestTemplateXhrTransportTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void connectFailure() throws Exception {
	final HttpServerErrorException expected = new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR);
	RestOperations restTemplate = mock(RestOperations.class);
	given(restTemplate.execute((URI) any(), eq(HttpMethod.POST), any(), any())).willThrow(expected);

	final CountDownLatch latch = new CountDownLatch(1);
	connect(restTemplate).addCallback(
			new ListenableFutureCallback<WebSocketSession>() {
				@Override
				public void onSuccess(WebSocketSession result) {
				}
				@Override
				public void onFailure(Throwable ex) {
					if (ex == expected) {
						latch.countDown();
					}
				}
			}
	);
	verifyNoMoreInteractions(this.webSocketHandler);
}
 
Example #23
Source File: LifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldTranslateExceptionOnTokenRenewal() {

	when(this.clientAuthentication.login())
			.thenReturn(LoginToken.renewable("login".toCharArray(), Duration.ofMinutes(5)));
	when(this.restOperations.postForObject(anyString(), any(HttpEntity.class), any()))
			.thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "Some server error"));

	AtomicReference<AuthenticationErrorEvent> listener = new AtomicReference<>();
	this.sessionManager.addErrorListener(listener::set);

	this.sessionManager.getSessionToken();
	this.sessionManager.renewToken();

	assertThat(listener.get().getException()).isInstanceOf(VaultTokenRenewalException.class)
			.hasCauseInstanceOf(HttpServerErrorException.class)
			.hasMessageContaining("Cannot renew token: Status 500 Some server error");
}
 
Example #24
Source File: LifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void shouldNotThrowExceptionsOnRevokeErrors() {

	when(this.clientAuthentication.login()).thenReturn(LoginToken.of("login"));

	when(this.restOperations.postForObject(anyString(), any(), ArgumentMatchers.<Class>any()))
			.thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR));

	this.sessionManager.renewToken();
	this.sessionManager.destroy();

	verify(this.restOperations).postForObject(eq("auth/token/revoke-self"),
			eq(new HttpEntity<>(VaultHttpHeaders.from(LoginToken.of("login")))), any(Class.class));
	verify(this.listener).onAuthenticationEvent(any(AfterLoginEvent.class));
	verify(this.listener).onAuthenticationEvent(any(BeforeLoginTokenRevocationEvent.class));
	verifyNoMoreInteractions(this.listener);
	verify(this.errorListener).onAuthenticationError(any(LoginTokenRevocationFailedEvent.class));
}
 
Example #25
Source File: LifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void shouldNotReScheduleTokenRenewalAfterFailedRenewal() {

	when(this.clientAuthentication.login())
			.thenReturn(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)));
	when(this.restOperations.postForObject(anyString(), any(), ArgumentMatchers.<Class>any()))
			.thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR));

	ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);

	this.sessionManager.getSessionToken();
	verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));

	runnableCaptor.getValue().run();

	verify(this.taskScheduler, times(1)).schedule(any(Runnable.class), any(Trigger.class));
}
 
Example #26
Source File: AbstractXhrTransport.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public String executeInfoRequest(URI infoUrl, @Nullable HttpHeaders headers) {
	if (logger.isDebugEnabled()) {
		logger.debug("Executing SockJS Info request, url=" + infoUrl);
	}
	HttpHeaders infoRequestHeaders = new HttpHeaders();
	if (headers != null) {
		infoRequestHeaders.putAll(headers);
	}
	ResponseEntity<String> response = executeInfoRequestInternal(infoUrl, infoRequestHeaders);
	if (response.getStatusCode() != HttpStatus.OK) {
		if (logger.isErrorEnabled()) {
			logger.error("SockJS Info request (url=" + infoUrl + ") failed: " + response);
		}
		throw new HttpServerErrorException(response.getStatusCode());
	}
	if (logger.isTraceEnabled()) {
		logger.trace("SockJS Info request (url=" + infoUrl + ") response: " + response);
	}
	String result = response.getBody();
	return (result != null ? result : "");
}
 
Example #27
Source File: JettyXhrTransport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void onBegin(Response response) {
	if (response.getStatus() != 200) {
		HttpStatus status = HttpStatus.valueOf(response.getStatus());
		response.abort(new HttpServerErrorException(status, "Unexpected XHR receive status"));
	}
}
 
Example #28
Source File: RemoteVehicleDetailsServiceWireMockTest.java    From building-microservices with Apache License 2.0 5 votes vote down vote up
@Test
public void getVehicleDetailsWhenResultIServerErrorShouldThrowException()
		throws Exception {
	this.wireMock.stubFor(get(urlEqualTo("/vehicle/" + VIN + "/details"))
			.willReturn(aResponse().withStatus(500)));
	this.thrown.expect(HttpServerErrorException.class);
	this.service.getVehicleDetails(new VehicleIdentificationNumber(VIN));
}
 
Example #29
Source File: SockJsClientTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void connectInfoRequestFailure() throws URISyntaxException {
	HttpServerErrorException exception = new HttpServerErrorException(HttpStatus.SERVICE_UNAVAILABLE);
	given(this.infoReceiver.executeInfoRequest(any(), any())).willThrow(exception);
	this.sockJsClient.doHandshake(handler, URL).addCallback(this.connectCallback);
	verify(this.connectCallback).onFailure(exception);
	assertFalse(this.webSocketTransport.invoked());
	assertFalse(this.xhrTransport.invoked());
}
 
Example #30
Source File: RetryableRestOperationsTest.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Test
public void retryableRestOperationFailWithHttpServerErrorExceptionTest() {
	RestOperations restOperations = RestTemplateFactory.createCommonsHttpRestTemplate(10, 100, 5000, 5000, 10,
			RetryPolicyFactories.newRestOperationsRetryPolicyFactory(100));
	
	try {
		restOperations.getForObject(generateRequestURL("/httpservererrorexception"), String.class);
		fail();
	} catch (Exception e) {
		assertTrue(e instanceof HttpServerErrorException);
	}
}