Java 类org.springframework.web.client.HttpServerErrorException 实例源码

项目:xm-commons    文件:ExceptionTranslator.java   
@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);
}
项目:desafio-pagarme    文件:Client.java   
/**
 * 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;
    }
}
项目:Persephone    文件:RestTemplateErrorHandler.java   
/**
 * 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);
}
项目:desafio-pagarme    文件:CardHandlerTest.java   
@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());
    }
}
项目:playground-scenario-generator    文件:EasyTravelScenarioService.java   
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;
}
项目:programmeren3    文件:QuestionAnswerController.java   
@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.");
    }
}
项目:spring4-understanding    文件:AbstractXhrTransport.java   
@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();
}
项目:spring4-understanding    文件:AbstractXhrTransport.java   
@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);
    }
}
项目:spring4-understanding    文件:RestTemplateXhrTransportTests.java   
@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);
}
项目:web-ui    文件:CustomAuthenticationProvider.java   
@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!");
    }
}
项目:web-ui    文件:UserController.java   
@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";
}
项目:web-ui    文件:AccountsController.java   
@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";
}
项目:web-ui    文件:TradeController.java   
@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";
}
项目:web-ui    文件:PortfolioController.java   
@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";
}
项目:spring-vault    文件:LifecycleAwareSessionManagerUnitTests.java   
@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));
}
项目:spring-vault    文件:LifecycleAwareSessionManagerUnitTests.java   
@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));
}
项目:charon-spring-boot-starter    文件:RetryingProperties.java   
@SuppressWarnings("unchecked")
public List<Class<? extends Throwable>> getExceptions() {
    if (isBlank(exceptions)) {
        return emptyList();
    }
    if (retryableExceptions.isEmpty()) {
        retryableExceptions = Stream.of(exceptions.split(","))
                .map(exceptionType -> {
                    try {
                        return (Class<? extends Throwable>) Class.forName(exceptionType.trim());
                    } catch (ClassNotFoundException e) {
                        throw new CharonException("Invalid retryable exception: " + exceptionType, e);
                    }
                })
                .collect(toList());
        if (clientHttpError) {
            retryableExceptions.add(HttpClientErrorException.class);
        }
        if (serverHttpError) {
            retryableExceptions.add(HttpServerErrorException.class);
        }
    }
    return retryableExceptions;
}
项目:springBootTrader-aos    文件:CustomAuthenticationProvider.java   
@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!");
    }
}
项目:springBootTrader-aos    文件:UserController.java   
@RequestMapping(value = "/", method = RequestMethod.GET)
public String showHome(Model model) {
    if (!model.containsAttribute("login")) {
        model.addAttribute("login", new AuthenticationRequest());
    }
    model.addAttribute("marketSummary", marketService.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";
}
项目:springBootTrader-aos    文件:TradeController.java   
@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());
        //TODO: add account summary?
        try {
            model.addAttribute("portfolio",marketService.getPortfolio(currentUserName));
        } catch (HttpServerErrorException e) {
            model.addAttribute("portfolioRetrievalError",e.getMessage());
        }
    }

    return "trade";
}
项目:springBootTrader-aos    文件:TradeController.java   
@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";
}
项目:springBootTrader-aos    文件:PortfolioController.java   
@RequestMapping(value = "/portfolio", method = RequestMethod.GET)
public String portfolio(Model model) {
    logger.debug("/portfolio");
    model.addAttribute("marketSummary", marketService.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";
}
项目:sw360rest    文件:DemoApplication.java   
public static void main(String[] args) throws Exception {
    String restServerURL = getEnv("SW360DEMO_REST_SERVER_URL", "http://localhost:8091");
    String authServerURL = getEnv("SW360DEMO_AUTH_SERVER_URL", "http://localhost:8090");
    String thriftServerURL = getEnv("SW360DEMO_THRIFT_SERVER_URL", "http://localhost:8080");
    String springDistLocation = getEnv("SW360DEMO_SPRING_DIST_LOCATION",
            System.getProperty("user.home") + "/spring-framework-4.3.5.RELEASE");

    DemoApplication demoClient = new DemoApplication(restServerURL, authServerURL, thriftServerURL, springDistLocation);
    try {
        demoClient.checkAndCreateAdminUser();
        demoClient.createSpringFramework();
    } catch (Exception e) {
        System.out.println("Something went wrong:");
        if (e instanceof HttpServerErrorException) {
            ObjectMapper mapper = new ObjectMapper();
            String errorJson = ((HttpServerErrorException) e).getResponseBodyAsString();
            Object jsonErrorObject = mapper.readValue(errorJson, Object.class);
            String errorPrettyPrinted = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonErrorObject);

            System.out.println(errorPrettyPrinted);
        } else {
            System.out.println(e.getMessage());
        }
    }
}
项目:db-dumper-service    文件:AbstractIntegrationWithRealCfClientTest.java   
protected void createService(CloudService cloudService) {
    try {
        logger.info("Creating service {} from {} with plan {} ", cloudService.getName(), cloudService.getLabel(), cloudService.getPlan());
        cfClientToPopulate.createService(cloudService);
        if (!this.isFinishedCreatingService(cloudService)) {
            fail("Cannot create service '" + cloudService.getName() + "'");
        }
    } catch (HttpServerErrorException e) {
        if (!e.getStatusCode().equals(HttpStatus.BAD_GATEWAY)) {
            throw e;
        } else {
            String skipMessage = "Bad gateway error, skipping test";
            this.reportIntegration.setSkipped(true);
            this.reportIntegration.setSkippedReason(skipMessage);
            assumeTrue(skipMessage, false);
        }
    }

}
项目:SIT    文件:SpringService.java   
/**
 * upodate the paths of an intervention
 * @param obj
 * @return
 */
public ResponseEntity<Intervention> updateInterventionPaths(Object[] obj, EPathOperation operation) {
    String url = null;
    if (operation == EPathOperation.CREATE){
        url = URL + "intervention/" + obj[0] + "/watchpath/create";
    } else if (operation == EPathOperation.UPDATE) {
        url = URL + "intervention/" + obj[0] + "/watchpath/update";
    } else {
        url = URL + "intervention/" + obj[0] + "/watchpath/delete";
    }
    try {
        return restTemplate.postForEntity(url, obj[1], Intervention.class);
    } catch (HttpServerErrorException e){
        Log.e(TAG, "erreur à l'update d'un path", e);
        throw e;
    }
}
项目:ml-app-deployer    文件:MgmtResponseErrorHandler.java   
@Override
 public void handleError(ClientHttpResponse response) throws IOException {
     try {
         super.handleError(response);
     } catch (HttpClientErrorException | HttpServerErrorException ex) {
String message = "Logging HTTP response body to assist with debugging: " + ex.getResponseBodyAsString();
if (HttpStatus.SERVICE_UNAVAILABLE.equals(ex.getStatusCode())) {
    if (logger.isDebugEnabled()) {
        logger.debug(message);
    }
}
         else if (logger.isErrorEnabled()) {
             logger.error(message);
         }
         throw ex;
     }
 }
项目:cf-SpringBootTrader    文件:CustomAuthenticationProvider.java   
@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!");
    }
}
项目:cf-SpringBootTrader    文件:UserController.java   
@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";
}
项目:cf-SpringBootTrader    文件:TradeController.java   
@RequestMapping(value = "/trade", method = RequestMethod.GET)
public String showTrade(Model model) {
    logger.debug("/trade.GET");

    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());
        //TODO: add account summary?
        try {
            model.addAttribute("portfolio",marketService.getPortfolio(currentUserName));
        } catch (HttpServerErrorException e) {
            model.addAttribute("portfolioRetrievalError",e.getMessage());
        }
    }

    return "trade";
}
项目:cf-SpringBootTrader    文件:TradeController.java   
@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";
}
项目:cf-SpringBootTrader    文件:PortfolioController.java   
@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";
}
项目:elpaaso-core    文件:CfAdapterImpl.java   
private InstancesInfo getInstancesWithTimeout(CloudFoundryOperations client, String appName) {
    int timeoutMs = 1 * 60 * 1000;
    long start = System.currentTimeMillis();
    while (true) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e1) {
            // ignore
        }
        try {
            return client.getApplicationInstances(appName);
        } catch (HttpServerErrorException e) {
            // error 500, keep waiting
        }
        long startWaitTime = System.currentTimeMillis() - start;
        if (startWaitTime > timeoutMs) {
            String msg = "Timed out waiting for app startup:" + startWaitTime + " ms (max is:" + timeoutMs + ")";
            logger.error(msg);
            throw new TechnicalException(msg);
        }
    }

}
项目:code-quality-game    文件:SonarDataRetriever.java   
@Override
public void accept(final String id) {
    try {
        int pageIndex = 1;
        int totalPages = 1;
        List<Issue> issues = new ArrayList<>();
        while (pageIndex <= totalPages) {
            RestTemplate restTemplate = new RestTemplate();
            HttpEntity<String> request = new HttpEntity<>(getHeaders());
            URI uri = getResolvedIssuesForAssignee(id, pageIndex);
            ResponseEntity<Issues> response = restTemplate.exchange(uri, HttpMethod.GET, request, Issues.class);
            if (pageIndex == 1) {
                Paging paging = response.getBody().getPaging();
                totalPages = paging.getTotal();
            }
            issues.addAll(response.getBody().getIssues());
            pageIndex++;
        }
        statsService.updateStats(id, issues);
    } catch (final HttpServerErrorException serverException) {
        log.error(serverException);
        throw serverException;
    }
}
项目:sinavi-jfw    文件:RestClientResponseErrorHandler.java   
/**
 * 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));
    }
}
项目:ozwillo-portal    文件:PortalDashboardService.java   
private DashboardApp toDashboardApp(Subscription sub) {
    try {
        ServiceEntry service = catalogStore.findService(sub.getServiceId());
        if (service == null) {
            return null;
        }

        DashboardApp app = new DashboardApp();
        app.setId(sub.getId());
        app.setServiceId(sub.getServiceId());
        app.setName(service.getName(RequestContextUtils.getLocale(request)));
        app.setIcon(imageService.getImageForURL(service.getIcon(RequestContextUtils.getLocale(request)), ImageFormat.PNG_64BY64, false));
        app.setUrl(service.getUrl());

        if (service.getNotificationUrl() != null) {
            app.setNotificationUrl(service.getNotificationUrl());
        }

        return app;
    } catch (HttpServerErrorException kernelException) {
        logger.error("Cannot load service from the Kernel for subscription {}, skipping.", sub);
        return null;
    }
}
项目:saos    文件:SourceCcjExternalRepositoryTest.java   
@Test(expected = HttpServerErrorException.class)
public void findJudgmentIds_ERROR_RESPONSE() {

    // given
    DateTime publicationDateFrom = new DateTime(2012, 04, 11, 12, 00);
    int pageNo = 2;
    int pageSize = 10;

    String url = "http://qwerty.pl?dddd=dddd";
    Mockito.when(urlFactory.createSourceJudgmentsUrl(Mockito.eq(pageNo), Mockito.eq(pageSize), Mockito.eq(publicationDateFrom))).thenReturn(url);
    mockServerErrorResponse(url);


    // execute
    sourceCcjExternalRepository.findJudgmentIds(pageNo, pageSize, publicationDateFrom);
}
项目:jsonrpc4j    文件:JsonRpcResponseErrorHandler.java   
@Override
public void handleError(ClientHttpResponse response)
        throws IOException {
    final 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 RestClientException("Unknown status code [" + statusCode + "]");
    }
}
项目:syndesis    文件:HttpServerErrorExceptionMapper.java   
@Override
public Response toResponse(HttpServerErrorException exception) {
    RestError error = new RestError(
            exception.getMessage(),
            exception.getMessage(),
            ErrorMap.from(new String(exception.getResponseBodyAsByteArray(), StandardCharsets.UTF_8)),
            exception.getStatusCode().value());
    return Response.status(exception.getStatusCode().value()).type(MediaType.APPLICATION_JSON_TYPE).entity(error).build();
}
项目:desafio-pagarme    文件:CardHandlerTest.java   
@Test
public void testCreateCard() {
    Card card = new Card();
    card.setHolderName("teste");
    card.setCardNumber("45646554");
    card.setCvv("46465");
    card.setExpirationDate("1218");
    try {
        card = handler.createCard(card);
    } catch (HttpServerErrorException | IOException e) {
        fail(e.getMessage());
    }
}
项目:desafio-pagarme    文件:CardHandlerTest.java   
@Test
public void testGetCard() {
    try {
        Card card = handler.getCard(5467l);
        assertEquals("45646554", card.getCardNumber());
    } catch (HttpServerErrorException e) {
        fail(e.getMessage());
    }
}