List of usage examples for org.springframework.http.client HttpComponentsClientHttpRequestFactory HttpComponentsClientHttpRequestFactory
public HttpComponentsClientHttpRequestFactory(HttpClient httpClient)
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);// w ww. ja v a2 s. co 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."); }
From source file:com.sitewhere.wso2.identity.scim.Wso2ScimAssetModule.java
/** * Creates a transport that allows missing certificates to be ignored. * //from www . j av a 2 s . c o m * @param username * @param password * @return */ protected ClientHttpRequestFactory createSecureTransport(String username, String password) { HostnameVerifier nullHostnameVerifier = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; HttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(nullHostnameVerifier) .setSSLContext(createContext()).build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(client); return requestFactory; }
From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitBusCleaner.java
@VisibleForTesting static RestTemplate buildRestTemplate(String adminUri, String user, String password) { BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(user, password)); HttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); // Set up pre-emptive basic Auth because the rabbit plugin doesn't currently support challenge/response for PUT // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local; from the apache docs... // auth cache BasicScheme basicAuth = new BasicScheme(); URI uri;/*from w ww . j av a 2 s. c o m*/ try { uri = new URI(adminUri); } catch (URISyntaxException e) { throw new RabbitAdminException("Invalid URI", e); } authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), basicAuth); // Add AuthCache to the execution context final HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient) { @Override protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { return localContext; } }); restTemplate.setMessageConverters( Collections.<HttpMessageConverter<?>>singletonList(new MappingJackson2HttpMessageConverter())); return restTemplate; }
From source file:com.appglu.android.AppGluSettings.java
/** * This is an extension point that can be used if you wish to extend or customize the {@link com.appglu.impl.AppGluTemplate}. *//* w w w. j a va 2s . c o m*/ protected AppGluTemplate createAppGluTemplate(final Context context) { return new AppGluTemplate(this.getApplicationKey(), this.getApplicationSecret(), this.getApplicationEnvironment(), this.getBaseUrl()) { protected ClientHttpRequestFactory createClientHttpRequestFactory() { AndroidHttpClient androidHttpClient = AndroidHttpClient.newInstance("Android-User-Agent", context); return new HttpComponentsClientHttpRequestFactory(androidHttpClient); } protected boolean shouldAddGzipRequestInterceptor() { return true; } }; }
From source file:org.mitre.openid.connect.client.AbstractOIDCAuthenticationFilter.java
/** * Handles the authorization grant response * /*from w ww . jav a 2 s.co m*/ * @param authorizationGrant * The Authorization grant code * @param request * The request from which to extract parameters and perform the * authentication * @return The authenticated user token, or null if authentication is * incomplete. * @throws Exception * @throws UnsupportedEncodingException */ protected Authentication handleAuthorizationGrantResponse(String authorizationGrant, HttpServletRequest request, OIDCServerConfiguration serverConfig) { final boolean debug = logger.isDebugEnabled(); // Handle Token Endpoint interaction HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter("http.socket.timeout", new Integer(httpSocketTimeout)); // // TODO: basic auth is untested (it wasn't working last I // tested) // UsernamePasswordCredentials credentials = new // UsernamePasswordCredentials(serverConfig.getClientId(), // serverConfig.getClientSecret()); // ((DefaultHttpClient) // httpClient).getCredentialsProvider().setCredentials(AuthScope.ANY, // credentials); // HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); RestTemplate restTemplate = new RestTemplate(factory); MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.add("grant_type", "authorization_code"); form.add("code", authorizationGrant); form.add("redirect_uri", AbstractOIDCAuthenticationFilter.buildRedirectURI(request, null)); // pass clientId and clientSecret in post of request form.add("client_id", serverConfig.getClientId()); form.add("client_secret", serverConfig.getClientSecret()); if (debug) { logger.debug("tokenEndpointURI = " + serverConfig.getTokenEndpointURI()); logger.debug("form = " + form); } ; String jsonString = null; try { jsonString = restTemplate.postForObject(serverConfig.getTokenEndpointURI(), form, String.class); } catch (HttpClientErrorException httpClientErrorException) { // Handle error logger.error("Token Endpoint error response: " + httpClientErrorException.getStatusText() + " : " + httpClientErrorException.getMessage()); throw new AuthenticationServiceException("Unable to obtain Access Token."); } logger.debug("from TokenEndpoint jsonString = " + jsonString); JsonElement jsonRoot = new JsonParser().parse(jsonString); if (jsonRoot.getAsJsonObject().get("error") != null) { // Handle error String error = jsonRoot.getAsJsonObject().get("error").getAsString(); logger.error("Token Endpoint returned: " + error); throw new AuthenticationServiceException( "Unable to obtain Access Token. Token Endpoint returned: " + error); } else { // Extract the id_token to insert into the // OpenIdConnectAuthenticationToken IdToken idToken = null; JwtSigningAndValidationService jwtValidator = getValidatorForServer(serverConfig); if (jsonRoot.getAsJsonObject().get("id_token") != null) { try { idToken = IdToken.parse(jsonRoot.getAsJsonObject().get("id_token").getAsString()); } catch (AuthenticationServiceException e) { // I suspect this could happen logger.error("Problem parsing id_token: " + e); // e.printStackTrace(); throw new AuthenticationServiceException( "Problem parsing id_token return from Token endpoint: " + e); } if (jwtValidator .validateSignature(jsonRoot.getAsJsonObject().get("id_token").getAsString()) == false) { throw new AuthenticationServiceException("Signature not validated"); } if (idToken.getClaims().getIssuer() == null) { throw new AuthenticationServiceException("Issuer is null"); } if (!idToken.getClaims().getIssuer().equals(serverConfig.getIssuer())) { throw new AuthenticationServiceException("Issuers do not match"); } if (jwtValidator.isJwtExpired(idToken)) { throw new AuthenticationServiceException("Id Token is expired"); } if (jwtValidator.validateIssuedAt(idToken) == false) { throw new AuthenticationServiceException("Id Token issuedAt failed"); } } else { // An error is unlikely, but it good security to check logger.error("Token Endpoint did not return an id_token"); throw new AuthenticationServiceException("Token Endpoint did not return an id_token"); } // Clients are required to compare nonce claim in ID token to // the nonce sent in the Authorization request. The client // stores this value as a signed session cookie to detect a // replay by third parties. // // See: OpenID Connect Messages Section 2.1.1 entitled "ID Token" // // http://openid.net/specs/openid-connect-messages-1_0.html#id_token // //String nonce = idToken.getClaims().getClaimAsString("nonce"); String nonce = idToken.getClaims().getNonce(); if (StringUtils.isBlank(nonce)) { logger.error("ID token did not contain a nonce claim."); throw new AuthenticationServiceException("ID token did not contain a nonce claim."); } Cookie nonceSignatureCookie = WebUtils.getCookie(request, NONCE_SIGNATURE_COOKIE_NAME); if (nonceSignatureCookie != null) { String sigText = nonceSignatureCookie.getValue(); if (sigText != null && !sigText.isEmpty()) { if (!verify(signer, publicKey, nonce, sigText)) { logger.error("Possible replay attack detected! " + "The comparison of the nonce in the returned " + "ID Token to the signed session " + NONCE_SIGNATURE_COOKIE_NAME + " failed."); throw new AuthenticationServiceException("Possible replay attack detected! " + "The comparison of the nonce in the returned " + "ID Token to the signed session " + NONCE_SIGNATURE_COOKIE_NAME + " failed."); } } else { logger.error(NONCE_SIGNATURE_COOKIE_NAME + " cookie was found but value was null or empty"); throw new AuthenticationServiceException( NONCE_SIGNATURE_COOKIE_NAME + " cookie was found but value was null or empty"); } } else { logger.error(NONCE_SIGNATURE_COOKIE_NAME + " cookie was not found."); throw new AuthenticationServiceException(NONCE_SIGNATURE_COOKIE_NAME + " cookie was not found."); } // pull the user_id out as a claim on the id_token String userId = idToken.getTokenClaims().getUserId(); // construct an OpenIdConnectAuthenticationToken and return // a Authentication object w/the userId and the idToken OpenIdConnectAuthenticationToken token = new OpenIdConnectAuthenticationToken(userId, idToken); Authentication authentication = this.getAuthenticationManager().authenticate(token); return authentication; } }
From source file:org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests.java
@Test public void sslDisabled() throws Exception { AbstractServletWebServerFactory factory = getFactory(); Ssl ssl = getSsl(null, "password", "classpath:test.jks"); ssl.setEnabled(false);/*from www . ja va2s. com*/ factory.setSsl(ssl); this.webServer = factory .getWebServer(new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello")); this.webServer.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); this.thrown.expect(SSLException.class); getResponse(getLocalUrl("https", "/hello"), requestFactory); }
From source file:org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests.java
@Test public void sslGetScheme() throws Exception { // gh-2232 AbstractServletWebServerFactory factory = getFactory(); factory.setSsl(getSsl(null, "password", "src/test/resources/test.jks")); this.webServer = factory .getWebServer(new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello")); this.webServer.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient);/* w ww. j a v a2 s . c om*/ assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory)).contains("scheme=https"); }
From source file:org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests.java
@Test public void sslKeyAlias() throws Exception { AbstractServletWebServerFactory factory = getFactory(); Ssl ssl = getSsl(null, "password", "test-alias", "src/test/resources/test.jks"); factory.setSsl(ssl);/* ww w .j a v a 2 s . co m*/ ServletRegistrationBean<ExampleServlet> registration = new ServletRegistrationBean<>( new ExampleServlet(true, false), "/hello"); this.webServer = factory.getWebServer(registration); this.webServer.start(); TrustStrategy trustStrategy = new SerialNumberValidatingTrustSelfSignedStrategy("77e7c302"); SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, trustStrategy).build(); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)) .build(); String response = getResponse(getLocalUrl("https", "/hello"), new HttpComponentsClientHttpRequestFactory(httpClient)); assertThat(response).contains("scheme=https"); }