当前位置: 首页>>代码示例>>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;未经允许,请勿转载。