當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpServerErrorException類代碼示例

本文整理匯總了Java中org.springframework.web.client.HttpServerErrorException的典型用法代碼示例。如果您正苦於以下問題:Java HttpServerErrorException類的具體用法?Java HttpServerErrorException怎麽用?Java HttpServerErrorException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


HttpServerErrorException類屬於org.springframework.web.client包,在下文中一共展示了HttpServerErrorException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: processHttpServerError

import org.springframework.web.client.HttpServerErrorException; //導入依賴的package包/類
@ExceptionHandler(HttpServerErrorException.class)
@ResponseBody
public ResponseEntity<ErrorVM> processHttpServerError(HttpServerErrorException ex) {
    BodyBuilder builder;
    ErrorVM fieldErrorVM;
    HttpStatus responseStatus = ex.getStatusCode();
    if (responseStatus != null) {
        builder = ResponseEntity.status(responseStatus.value());
        fieldErrorVM = new ErrorVM(ERROR_PREFIX + responseStatus.value(), translate(ERROR_PREFIX
                                                                                        + responseStatus.value()));
    } else {
        builder = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);
        fieldErrorVM = new ErrorVM(ErrorConstants.ERR_INTERNAL_SERVER_ERROR,
                                   translate(ErrorConstants.ERR_INTERNAL_SERVER_ERROR));
    }
    return builder.body(fieldErrorVM);
}
 
開發者ID:xm-online,項目名稱:xm-commons,代碼行數:18,代碼來源:ExceptionTranslator.java

示例2: create

import org.springframework.web.client.HttpServerErrorException; //導入依賴的package包/類
/**
 * Creates the.
 *
 * @param <T> the generic type
 * @param obj the obj
 * @param class1 the class 1
 * @return the t
 * @throws IOException 
 * @throws JsonMappingException 
 * @throws JsonParseException 
 */
@SuppressWarnings("unchecked")
public <T> T create(Object obj, Class<T> class1) throws JsonParseException, JsonMappingException, IOException, HttpServerErrorException {
	try{
		String res 	= this.restTemplate.postForObject(getURI(class1), obj, String.class);
		if(res instanceof String){
			ObjectMapper mapper = new ObjectMapper();
			JsonNode obj2  		= mapper.readValue(res, JsonNode.class);
			return (T) mapper.readValue(obj2.toString(), class1);
		}else{
			return (T) obj;
		}
	}catch(HttpClientErrorException e){
		System.out.println("deu erro");
		System.out.println(e.getMessage());
		System.out.println(e.getResponseBodyAsString());
		return null;
	}
}
 
開發者ID:ac-silva,項目名稱:desafio-pagarme,代碼行數:30,代碼來源:Client.java

示例3: handle

import org.springframework.web.client.HttpServerErrorException; //導入依賴的package包/類
/**
 * Handles HTTP 3xx/4xx/5xx statuses
 */
public static ApplicationRuntimeException handle(Application app, String url, RestClientException ex) {

	// HTTP 5xx
	if(ex instanceof HttpServerErrorException) {
		HttpServerErrorException serverEx = ((HttpServerErrorException)ex);
		return new ApplicationRuntimeException(app, String.format("A server error happened while calling %s (HTTP %s)", url, serverEx.getRawStatusCode()));
	}
	// HTTP 4xx
	else if(ex instanceof HttpClientErrorException) {
		HttpClientErrorException clientEx = ((HttpClientErrorException)ex);
		return new ApplicationRuntimeException(app, String.format("Bad request on endpoint %s (HTTP %s)", url, clientEx.getRawStatusCode()));
	}
	// HTTP 3xx
	else if(ex instanceof HttpRedirectErrorException) {

		HttpRedirectErrorException redirectEx = ((HttpRedirectErrorException)ex);

		if(redirectEx.getStatusCode().series() == Series.REDIRECTION) {
			return new ApplicationRuntimeException(app, String.format("Endpoint %s is available but security might be enabled (HTTP %s)", url, redirectEx.getRawStatusCode() ));
		}
	}

	return handle(app, ex);
}
 
開發者ID:vianneyfaivre,項目名稱:Persephone,代碼行數:28,代碼來源:RestTemplateErrorHandler.java

示例4: setUp

import org.springframework.web.client.HttpServerErrorException; //導入依賴的package包/類
@Before
public void setUp(){
	MockitoAnnotations.initMocks(this);
	handler = new CardHandler(client);
	Card card = new Card();
	card.setId("card_cj1jrfgsx0002ln6eo1ggutly");
	card.setHolderName("teste");
	card.setCardNumber("45646554");
	card.setCvv("46465");
	card.setExpirationDate("1218");
	try {
		when(client.create(any(), eq(Card.class))).thenReturn(card);
		when(client.get(anyLong(), eq(Card.class))).thenReturn(card);
	} catch (HttpServerErrorException | IOException e) {
		fail(e.getMessage());
	}
}
 
開發者ID:ac-silva,項目名稱:desafio-pagarme,代碼行數:18,代碼來源:CardHandlerTest.java

示例5: setScenarioEnabled

import org.springframework.web.client.HttpServerErrorException; //導入依賴的package包/類
private boolean setScenarioEnabled(String scenarioId, boolean enabled) throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiUrl + CONFIGURATION_SERVICE + "/setPluginEnabled")
            .queryParam("name", scenarioId)
            .queryParam("enabled", enabled);

    HttpEntity<?> entity = new HttpEntity<>(headers);

    HttpEntity<String> response = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.GET, entity, String.class);

    if (!((ResponseEntity) response).getStatusCode().is2xxSuccessful()) {
        log.error("Response from plugin enable is not successful", response);
        throw new HttpServerErrorException(((ResponseEntity) response).getStatusCode());
    }

    return enabled;
}
 
開發者ID:opsgenie,項目名稱:playground-scenario-generator,代碼行數:20,代碼來源:EasyTravelScenarioService.java

示例6: showQuestion

import org.springframework.web.client.HttpServerErrorException; //導入依賴的package包/類
@GetMapping("/q/{questionId}")
public ModelAndView showQuestion(@PathVariable long questionId, @AuthenticationPrincipal CustomUserDetails userDetails) {
    QuestionAnswer question = this.questionAnswerService.getQuestion(questionId);
    if (question != null) {
        final Vote vote  = this.voteService.getVoteByUser(question, userDetails);
        final Map<QuestionAnswer, Vote> answersWithVotes = this.questionAnswerService.getAnswersWithUserVotes(question, userDetails);

        final QuestionAnswerDto questionDto = dtoMapper.toDto(question, vote);
        final List<QuestionAnswerDto> answerDtos = dtoMapper.toDto(answersWithVotes);

        final ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("show_question");
        modelAndView.getModel().put("question", questionDto);
        modelAndView.getModel().put("answers", answerDtos);
        return modelAndView;
    }
    else {
        // This would be a good way to handle this:
        throw new HttpServerErrorException(HttpStatus.NOT_FOUND, "QuestionAnswer with ID '" + questionId + "' not found.");

        // Alternatively, let this exceptions be picked up by AppWideExceptionHandler:
        //throw new QuestionNotFoundException("QuestionAnswer with ID '" + questionId + "' not found.");
    }
}
 
開發者ID:kdg-ti,項目名稱:programmeren3,代碼行數:25,代碼來源:QuestionAnswerController.java

示例7: executeInfoRequest

import org.springframework.web.client.HttpServerErrorException; //導入依賴的package包/類
@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();
}
 
開發者ID:langtianya,項目名稱:spring4-understanding,代碼行數:24,代碼來源:AbstractXhrTransport.java

示例8: executeSendRequest

import org.springframework.web.client.HttpServerErrorException; //導入依賴的package包/類
@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);
	}
}
 
開發者ID:langtianya,項目名稱:spring4-understanding,代碼行數:17,代碼來源:AbstractXhrTransport.java

示例9: connectFailure

import org.springframework.web.client.HttpServerErrorException; //導入依賴的package包/類
@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);
}
 
開發者ID:langtianya,項目名稱:spring4-understanding,代碼行數:23,代碼來源:RestTemplateXhrTransportTests.java

示例10: authenticate

import org.springframework.web.client.HttpServerErrorException; //導入依賴的package包/類
@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!");
	}
}
 
開發者ID:pivotal-bank,項目名稱:web-ui,代碼行數:24,代碼來源:CustomAuthenticationProvider.java

示例11: accounts

import org.springframework.web.client.HttpServerErrorException; //導入依賴的package包/類
@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";
}
 
開發者ID:pivotal-bank,項目名稱:web-ui,代碼行數:22,代碼來源:AccountsController.java

示例12: showTrade

import org.springframework.web.client.HttpServerErrorException; //導入依賴的package包/類
@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";
}
 
開發者ID:pivotal-bank,項目名稱:web-ui,代碼行數:24,代碼來源:TradeController.java

示例13: portfolio

import org.springframework.web.client.HttpServerErrorException; //導入依賴的package包/類
@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";
}
 
開發者ID:pivotal-bank,項目名稱:web-ui,代碼行數:25,代碼來源:PortfolioController.java

示例14: shouldNotThrowExceptionsOnRevokeErrors

import org.springframework.web.client.HttpServerErrorException; //導入依賴的package包/類
@Test
public void shouldNotThrowExceptionsOnRevokeErrors() {

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

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

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

	verify(restOperations)
			.postForObject(
					eq("auth/token/revoke-self"),
					eq(new HttpEntity<Object>(VaultHttpHeaders.from(LoginToken
							.of("login")))), any(Class.class));
}
 
開發者ID:spring-projects,項目名稱:spring-vault,代碼行數:20,代碼來源:LifecycleAwareSessionManagerUnitTests.java

示例15: shouldNotReScheduleTokenRenewalAfterFailedRenewal

import org.springframework.web.client.HttpServerErrorException; //導入依賴的package包/類
@Test
public void shouldNotReScheduleTokenRenewalAfterFailedRenewal() {

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

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

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

	runnableCaptor.getValue().run();

	verify(taskScheduler, times(1)).schedule(any(Runnable.class), any(Trigger.class));
}
 
開發者ID:spring-projects,項目名稱:spring-vault,代碼行數:20,代碼來源:LifecycleAwareSessionManagerUnitTests.java


注:本文中的org.springframework.web.client.HttpServerErrorException類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。