本文整理汇总了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);
}
示例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;
}
}
示例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);
}
示例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());
}
}
示例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;
}
示例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.");
}
}
示例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();
}
示例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);
}
}
示例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);
}
示例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!");
}
}
示例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";
}
示例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";
}
示例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";
}
示例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));
}
示例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));
}