List of usage examples for org.springframework.http.client ClientHttpResponse getStatusCode
HttpStatus getStatusCode() throws IOException;
From source file:de.blizzy.documentr.system.Downloader.java
String getTextFromUrl(String url, Charset encoding) throws IOException { ClientHttpResponse response = null; try {//from w w w . j av a 2 s . c om SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setConnectTimeout((int) TIMEOUT); requestFactory.setReadTimeout((int) TIMEOUT); ClientHttpRequest request = requestFactory.createRequest(URI.create(url), HttpMethod.GET); response = request.execute(); HttpStatus status = response.getStatusCode(); if (status.series() == Series.SUCCESSFUL) { return IOUtils.toString(response.getBody(), encoding); } } finally { if (response != null) { response.close(); } } return null; }
From source file:fi.helsinki.opintoni.integration.interceptor.OodiExceptionInterceptorTest.java
@Test(expected = RestClientServiceException.class) public void thatRestClientServiceExceptionIsThrown() throws Exception { HttpRequest httpRequest = mock(HttpRequest.class); ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); ClientHttpResponse clientHttpResponse = mock(ClientHttpResponse.class); JsonHttpStatus jsonHttpStatus = mock(JsonHttpStatus.class); when(objectMapper.readValue(any(InputStream.class), eq(JsonHttpStatus.class))).thenReturn(jsonHttpStatus); when(jsonHttpStatus.is5xxError()).thenReturn(true); when(execution.execute(eq(httpRequest), any())).thenReturn(clientHttpResponse); when(env.acceptsProfiles(Matchers.<String>anyVararg())).thenReturn(true); when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.OK); when(httpRequest.getURI()).thenReturn(new URI("https://oprek.helsinki.fi")); oodiExceptionInterceptor.intercept(httpRequest, new byte[0], execution); }
From source file:com.goldengekko.meetr.service.sugarcrm.SugarCRMClient.java
public String getToken(String user, String password) { LOG.debug("Get SugarCRM token"); if (null == user || null == password || user.isEmpty() || password.isEmpty()) { LOG.info("User and password must be provided when creating token"); throw new BadRequestException(ERR_MISSING_USER_PASSWORD, "User and password must be provided when creating token"); }// www .j a v a2 s .c o m String data = String.format( "{\"user_auth\":{\"user_name\":\"%s\",\"password\":\"%s\",\"version\":\"%s\"},\"application_name\":\"%s\"}", this.user, md5Hash(this.password), "1.0", "Meeter"); //LOG.debug("Send login with data:{}", data); this.token = TEMPLATE.execute(this.sugarCRMUrl + PARAM_TEMPLATE, HttpMethod.GET, new RequestCallback() { @Override public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException { LOG.debug("Sending login request with url:{}", clientHttpRequest.getURI().toURL().toExternalForm()); } }, new ResponseExtractor<String>() { @Override public String extractData(ClientHttpResponse clientHttpResponse) throws IOException { LOG.debug("Response with http code:{}", clientHttpResponse.getStatusCode().value()); if (clientHttpResponse.getStatusCode() == HttpStatus.OK) { SugarCRMLoginResponse response = MAPPER.readValue(clientHttpResponse.getBody(), SugarCRMLoginResponse.class); LOG.debug("Response:{}", response); if (!response.hasError()) { return response.getId(); } else if (response.isInvalidCredentials()) { LOG.info("SugarCRM login failed with invalid credentials", new StringHttpMessageConverter().read(String.class, clientHttpResponse)); throw new RestException(ERR_SUGAR_LOGIN_FAILED, HttpStatus.FORBIDDEN, "SugarCRM login failed with invalid credentials"); } else { LOG.info("SugarCRM login failed with unknown reason:{}", new StringHttpMessageConverter().read(String.class, clientHttpResponse)); throw new RestException(ERR_SUGAR_LOGIN_FAILED, HttpStatus.FORBIDDEN, "SugarCRM login failed with unknown reason"); } } else { // If the SugarCRM does not respond with 200 throw http 503 LOG.warn("SugarCRM is responding with http code:{}", clientHttpResponse.getStatusCode().value()); throw new RestException(ERR_SUGAR_NOT_AVAILABLE, HttpStatus.SERVICE_UNAVAILABLE, "SugarCRM request failed"); } } }, "login", "json", "json", data); LOG.debug("Got token:{}", this.token); return this.token; }
From source file:org.spring.data.gemfire.rest.GemFireRestInterfaceTest.java
@SuppressWarnings("deprecation") private RestTemplate setErrorHandler(final RestTemplate restTemplate) { restTemplate.setErrorHandler(new ResponseErrorHandler() { private final Set<HttpStatus> errorStatuses = new HashSet<>(); /* non-static */ { errorStatuses.add(HttpStatus.BAD_REQUEST); errorStatuses.add(HttpStatus.UNAUTHORIZED); errorStatuses.add(HttpStatus.FORBIDDEN); errorStatuses.add(HttpStatus.NOT_FOUND); errorStatuses.add(HttpStatus.METHOD_NOT_ALLOWED); errorStatuses.add(HttpStatus.NOT_ACCEPTABLE); errorStatuses.add(HttpStatus.REQUEST_TIMEOUT); errorStatuses.add(HttpStatus.CONFLICT); errorStatuses.add(HttpStatus.REQUEST_ENTITY_TOO_LARGE); errorStatuses.add(HttpStatus.REQUEST_URI_TOO_LONG); errorStatuses.add(HttpStatus.UNSUPPORTED_MEDIA_TYPE); errorStatuses.add(HttpStatus.TOO_MANY_REQUESTS); errorStatuses.add(HttpStatus.INTERNAL_SERVER_ERROR); errorStatuses.add(HttpStatus.NOT_IMPLEMENTED); errorStatuses.add(HttpStatus.BAD_GATEWAY); errorStatuses.add(HttpStatus.SERVICE_UNAVAILABLE); }// w w w.ja v a2s. c o m @Override public boolean hasError(final ClientHttpResponse response) throws IOException { return errorStatuses.contains(response.getStatusCode()); } @Override public void handleError(final ClientHttpResponse response) throws IOException { System.err.printf("%1$d - %2$s%n", response.getRawStatusCode(), response.getStatusText()); System.err.println(readBody(response)); } private String readBody(final ClientHttpResponse response) throws IOException { BufferedReader responseBodyReader = null; try { responseBodyReader = new BufferedReader(new InputStreamReader(response.getBody())); StringBuilder buffer = new StringBuilder(); String line; while ((line = responseBodyReader.readLine()) != null) { buffer.append(line).append(System.getProperty("line.separator")); } return buffer.toString().trim(); } finally { FileSystemUtils.close(responseBodyReader); } } }); return restTemplate; }
From source file:sparklr.common.AbstractAuthorizationCodeProviderTests.java
@BeforeOAuth2Context public void setupAccessTokenProvider() { accessTokenProvider = new AuthorizationCodeAccessTokenProvider() { private ResponseExtractor<OAuth2AccessToken> extractor = super.getResponseExtractor(); private ResponseExtractor<ResponseEntity<Void>> authExtractor = super.getAuthorizationResponseExtractor(); private ResponseErrorHandler errorHandler = super.getResponseErrorHandler(); @Override//from ww w .j a v a 2s .c o m protected ResponseErrorHandler getResponseErrorHandler() { return new DefaultResponseErrorHandler() { public void handleError(ClientHttpResponse response) throws IOException { response.getHeaders(); response.getStatusCode(); tokenEndpointResponse = response; errorHandler.handleError(response); } }; } @Override protected ResponseExtractor<OAuth2AccessToken> getResponseExtractor() { return new ResponseExtractor<OAuth2AccessToken>() { public OAuth2AccessToken extractData(ClientHttpResponse response) throws IOException { try { response.getHeaders(); response.getStatusCode(); tokenEndpointResponse = response; return extractor.extractData(response); } catch (ResourceAccessException e) { return null; } } }; } @Override protected ResponseExtractor<ResponseEntity<Void>> getAuthorizationResponseExtractor() { return new ResponseExtractor<ResponseEntity<Void>>() { public ResponseEntity<Void> extractData(ClientHttpResponse response) throws IOException { response.getHeaders(); response.getStatusCode(); tokenEndpointResponse = response; return authExtractor.extractData(response); } }; } }; context.setAccessTokenProvider(accessTokenProvider); }
From source file:fi.helsinki.opintoni.integration.interceptor.OodiExceptionInterceptor.java
@Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { ClientHttpResponse response = execution.execute(request, body); /*/*from w w w .j av a 2 s.c o m*/ * The following code cannot be run with test profile, because it uses MockClientHttpResponse * that does not allow getBody() to be called multiple times even when using BufferingClientHttpRequestFactory */ if (env.acceptsProfiles(Constants.SPRING_PROFILE_LOCAL_DEVELOPMENT, Constants.SPRING_PROFILE_DEMO, Constants.SPRING_PROFILE_QA, Constants.SPRING_PROFILE_PRODUCTION)) { if (HttpStatus.OK.equals(response.getStatusCode())) { JsonHttpStatus jsonHttpStatus = objectMapper.readValue(response.getBody(), JsonHttpStatus.class); if (jsonHttpStatus.is5xxError()) { throw new RestClientServiceException( String.format("%s returned a %s response", request.getURI(), jsonHttpStatus.status)); } } } return response; }
From source file:com.goldengekko.meetr.service.sugarcrm.SugarCRMClient.java
@Override public CursorPage<DmContact> getPage(int pageSize, String cursorKey) { LOG.debug("SugarCRM client, get contacts. Token:{}", token); // Check that we have a token if (null == this.token || null == token) { throw new RestException(ERR_SUGAR_INVALID_TOKEN, HttpStatus.FORBIDDEN, "Token missing, app must generate token first"); }/*from w w w. j a v a2 s . co m*/ // If the cursor is null start from the beginning if (null == cursorKey) { cursorKey = "0"; } // The request // {"session":"f9psqc1rgd2iuri76u3v17aul1","module_name":"Contacts","query":"","order_by":"","offset":1,"select_fields":["id","name"],"link_name_to_fields_array":[],"max_results":2,"deleted":0,"Favorites":0} String data = String.format( "{\"session\":\"%s\",\"module_name\":\"Contacts\",\"query\":\"\",\"order_by\":\"\",\"offset\":%s,\"select_fields\":[\"id\",\"first_name\",\"last_name\",\"email\",\"phone_work\",\"primary_address_street\",\"primary_address_city\",\"primary_address_country\",\"primary_address_postalcode\"],\"link_name_to_fields_array\":[],\"max_results\":%s,\"deleted\":0,\"Favorites\":0}", this.token, cursorKey.toString(), pageSize); LOG.debug("get contacts with data:{}", data); SugarCRMContactsResponse contacts = TEMPLATE.execute(this.sugarCRMUrl + PARAM_TEMPLATE, HttpMethod.GET, new RequestCallback() { @Override public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException { LOG.debug("Sending get contact request with url:{}", clientHttpRequest.getURI().toURL().toExternalForm()); } }, new ResponseExtractor<SugarCRMContactsResponse>() { @Override public SugarCRMContactsResponse extractData(ClientHttpResponse clientHttpResponse) throws IOException { LOG.debug("Response with http code:{}", clientHttpResponse.getStatusCode().value()); if (clientHttpResponse.getStatusCode() == HttpStatus.OK) { SugarCRMContactsResponse response = MAPPER.readValue(clientHttpResponse.getBody(), SugarCRMContactsResponse.class); LOG.debug("Response:{}", response); if (!response.hasError()) { return response; } else if (response.isTokenInvalid()) { LOG.info("Get contacts failed, invalid token"); throw new RestException(ERR_SUGAR_INVALID_TOKEN, HttpStatus.FORBIDDEN, "SugarCRM get contacts failed, invalid token"); } else { LOG.info("SugarCRM get contacts failed with unknown reason:{}", new StringHttpMessageConverter().read(String.class, clientHttpResponse)); throw new RestException(ERR_SUGAR_GET_CONTACTS_FAILED, HttpStatus.SERVICE_UNAVAILABLE, "SugarCRM get contacts failed with unknown reason"); } } else { // If the SugarCRM does not respond with 200 throw http 503 LOG.warn("SugarCRM is responding with http code:{}", clientHttpResponse.getStatusCode().value()); throw new RestException(ERR_SUGAR_NOT_AVAILABLE, HttpStatus.SERVICE_UNAVAILABLE, "SugarCRM request failed"); } } }, "get_entry_list", "json", "json", data); LOG.debug("Got number of contacts:{}", contacts.getResult_count()); CursorPage<DmContact> page = convertToPage(contacts, pageSize); return page; }
From source file:nl.minbzk.dwr.zoeken.enricher.uploader.ElasticSearchResultUploader.java
/** * {@inheritDoc}//from w w w .ja va2 s . com */ @Override public void commit(final EnricherJob job) throws Exception { String flushUri = format("http://%s/%s/_flush", getElasticSearchUri(), job.getDatabaseName()); HttpStatus status = operations.execute(flushUri, HttpMethod.POST, null, new ResponseExtractor<HttpStatus>() { @Override public HttpStatus extractData(final ClientHttpResponse response) throws IOException { return response.getStatusCode(); } }, null); if (status.value() != HttpStatus.OK.value()) logger.error("Not all shards could be flushed / committed"); else { if (logger.isInfoEnabled()) logger.info("All shards were successfully flushed / committed"); } }
From source file:com.evolveum.midpoint.notifications.impl.api.transports.SimpleSmsTransport.java
@Override public void send(Message message, String transportName, Event event, Task task, OperationResult parentResult) { OperationResult result = parentResult.createSubresult(DOT_CLASS + "send"); result.addArbitraryObjectCollectionAsParam("message recipient(s)", message.getTo()); result.addParam("message subject", message.getSubject()); SystemConfigurationType systemConfiguration = NotificationFunctionsImpl .getSystemConfiguration(cacheRepositoryService, result); if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null) { String msg = "No notifications are configured. SMS notification to " + message.getTo() + " will not be sent."; LOGGER.warn(msg);/*from w w w. j a v a2s . c o m*/ result.recordWarning(msg); return; } String smsConfigName = StringUtils.substringAfter(transportName, NAME + ":"); SmsConfigurationType found = null; for (SmsConfigurationType smsConfigurationType : systemConfiguration.getNotificationConfiguration() .getSms()) { if (StringUtils.isEmpty(smsConfigName) && smsConfigurationType.getName() == null || StringUtils.isNotEmpty(smsConfigName) && smsConfigName.equals(smsConfigurationType.getName())) { found = smsConfigurationType; break; } } if (found == null) { String msg = "SMS configuration '" + smsConfigName + "' not found. SMS notification to " + message.getTo() + " will not be sent."; LOGGER.warn(msg); result.recordWarning(msg); return; } SmsConfigurationType smsConfigurationType = found; String logToFile = smsConfigurationType.getLogToFile(); if (logToFile != null) { TransportUtil.logToFile(logToFile, TransportUtil.formatToFileNew(message, transportName), LOGGER); } String file = smsConfigurationType.getRedirectToFile(); if (file != null) { writeToFile(message, file, null, emptyList(), null, result); return; } if (smsConfigurationType.getGateway().isEmpty()) { String msg = "SMS gateway(s) are not defined, notification to " + message.getTo() + " will not be sent."; LOGGER.warn(msg); result.recordWarning(msg); return; } String from; if (message.getFrom() != null) { from = message.getFrom(); } else if (smsConfigurationType.getDefaultFrom() != null) { from = smsConfigurationType.getDefaultFrom(); } else { from = ""; } if (message.getTo().isEmpty()) { String msg = "There is no recipient to send the notification to."; LOGGER.warn(msg); result.recordWarning(msg); return; } List<String> to = message.getTo(); assert to.size() > 0; for (SmsGatewayConfigurationType smsGatewayConfigurationType : smsConfigurationType.getGateway()) { OperationResult resultForGateway = result.createSubresult(DOT_CLASS + "send.forGateway"); resultForGateway.addContext("gateway name", smsGatewayConfigurationType.getName()); try { ExpressionVariables variables = getDefaultVariables(from, to, message); HttpMethodType method = defaultIfNull(smsGatewayConfigurationType.getMethod(), HttpMethodType.GET); ExpressionType urlExpression = defaultIfNull(smsGatewayConfigurationType.getUrlExpression(), smsGatewayConfigurationType.getUrl()); String url = evaluateExpressionChecked(urlExpression, variables, "sms gateway request url", task, result); LOGGER.debug("Sending SMS to URL {} (method {})", url, method); if (url == null) { throw new IllegalArgumentException("No URL specified"); } List<String> headersList = evaluateExpressionsChecked( smsGatewayConfigurationType.getHeadersExpression(), variables, "sms gateway request headers", task, result); LOGGER.debug("Using request headers:\n{}", headersList); String encoding = defaultIfNull(smsGatewayConfigurationType.getBodyEncoding(), StandardCharsets.ISO_8859_1.name()); String body = evaluateExpressionChecked(smsGatewayConfigurationType.getBodyExpression(), variables, "sms gateway request body", task, result); LOGGER.debug("Using request body text (encoding: {}):\n{}", encoding, body); if (smsGatewayConfigurationType.getLogToFile() != null) { TransportUtil.logToFile(smsGatewayConfigurationType.getLogToFile(), formatToFile(message, url, headersList, body), LOGGER); } if (smsGatewayConfigurationType.getRedirectToFile() != null) { writeToFile(message, smsGatewayConfigurationType.getRedirectToFile(), url, headersList, body, resultForGateway); result.computeStatus(); return; } else { HttpClientBuilder builder = HttpClientBuilder.create(); String username = smsGatewayConfigurationType.getUsername(); ProtectedStringType password = smsGatewayConfigurationType.getPassword(); if (username != null) { CredentialsProvider provider = new BasicCredentialsProvider(); String plainPassword = password != null ? protector.decryptString(password) : null; UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, plainPassword); provider.setCredentials(AuthScope.ANY, credentials); builder = builder.setDefaultCredentialsProvider(provider); } HttpClient client = builder.build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( client); ClientHttpRequest request = requestFactory.createRequest(new URI(url), HttpUtil.toHttpMethod(method)); setHeaders(request, headersList); if (body != null) { request.getBody().write(body.getBytes(encoding)); } ClientHttpResponse response = request.execute(); LOGGER.debug("Result: " + response.getStatusCode() + "/" + response.getStatusText()); if (response.getStatusCode().series() != HttpStatus.Series.SUCCESSFUL) { throw new SystemException("SMS gateway communication failed: " + response.getStatusCode() + ": " + response.getStatusText()); } LOGGER.info("Message sent successfully to {} via gateway {}.", message.getTo(), smsGatewayConfigurationType.getName()); resultForGateway.recordSuccess(); result.recordSuccess(); return; } } catch (Throwable t) { String msg = "Couldn't send SMS to " + message.getTo() + " via " + smsGatewayConfigurationType.getName() + ", trying another gateway, if there is any"; LoggingUtils.logException(LOGGER, msg, t); resultForGateway.recordFatalError(msg, t); } } LOGGER.warn("No more SMS gateways to try, notification to " + message.getTo() + " will not be sent."); result.recordWarning("Notification to " + message.getTo() + " could not be sent."); }