List of usage examples for org.apache.http.conn.ssl TrustStrategy TrustStrategy
TrustStrategy
From source file:com.groupon.odo.proxylib.BackupService.java
/** * Restore configuration from backup data * * @param streamData InputStream for configuration to restore * @return true if succeeded, false if operation failed *///from w ww .j av a 2 s . c o m public boolean restoreBackupData(InputStream streamData) { // convert stream to string java.util.Scanner s = new java.util.Scanner(streamData).useDelimiter("\\A"); String data = s.hasNext() ? s.next() : ""; // parse JSON ObjectMapper mapper = new ObjectMapper(); Backup backupData = null; try { backupData = mapper.readValue(data, Backup.class); } catch (Exception e) { logger.error("Could not parse input data: {}, {}", e.getClass(), e.getMessage()); return false; } // TODO: validate json against a schema for safety // GROUPS try { logger.info("Number of groups: {}", backupData.getGroups().size()); for (Group group : backupData.getGroups()) { // determine if group already exists.. if not then add it Integer groupId = PathOverrideService.getInstance().getGroupIdFromName(group.getName()); if (groupId == null) { groupId = PathOverrideService.getInstance().addGroup(group.getName()); } // get all methods from the group.. we are going to remove ones that don't exist in the new configuration List<Method> originalMethods = EditService.getInstance().getMethodsFromGroupId(groupId, null); for (Method originalMethod : originalMethods) { Boolean matchInImportGroup = false; int importCount = 0; for (Method importMethod : group.getMethods()) { if (originalMethod.getClassName().equals(importMethod.getClassName()) && originalMethod.getMethodName().equals(importMethod.getMethodName())) { matchInImportGroup = true; break; } importCount++; } if (!matchInImportGroup) { // remove it from current database since it is a delta to the current import PathOverrideService.getInstance().removeOverride(originalMethod.getId()); } else { // remove from import list since it already exists group.getMethods().remove(importCount); } } // add methods to groups for (Method method : group.getMethods()) { PathOverrideService.getInstance().createOverride(groupId, method.getMethodName(), method.getClassName()); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // PROFILES try { logger.info("Number of profiles: {}", backupData.getProfiles().size()); // remove all servers // don't care about deltas here.. we'll just recreate them all // removed default servers (belong to group id=0) ServerRedirectService.getInstance().deleteServerGroup(0); for (com.groupon.odo.proxylib.models.backup.Profile profile : backupData.getProfiles()) { // see if a profile with this name already exists Integer profileId = ProfileService.getInstance().getIdFromName(profile.getName()); com.groupon.odo.proxylib.models.Profile newProfile; if (profileId == null) { // create new profile newProfile = ProfileService.getInstance().add(profile.getName()); } else { // get the existing profile newProfile = ProfileService.getInstance().findProfile(profileId); } // add new servers if (profile.getServers() != null) { for (ServerRedirect server : profile.getServers()) { ServerRedirectService.getInstance().addServerRedirect(server.getRegion(), server.getSrcUrl(), server.getDestUrl(), server.getHostHeader(), newProfile.getId(), 0); } } // remove all server groups for (ServerGroup group : ServerRedirectService.getInstance() .tableServerGroups(newProfile.getId())) { ServerRedirectService.getInstance().deleteServerGroup(group.getId()); } // add new server groups if (profile.getServerGroups() != null) { for (ServerGroup group : profile.getServerGroups()) { int groupId = ServerRedirectService.getInstance().addServerGroup(group.getName(), newProfile.getId()); for (ServerRedirect server : group.getServers()) { ServerRedirectService.getInstance().addServerRedirect(server.getRegion(), server.getSrcUrl(), server.getDestUrl(), server.getHostHeader(), newProfile.getId(), groupId); } } } // remove all paths // don't care about deltas here.. we'll just recreate them all for (EndpointOverride path : PathOverrideService.getInstance().getPaths(newProfile.getId(), Constants.PROFILE_CLIENT_DEFAULT_ID, null)) { PathOverrideService.getInstance().removePath(path.getPathId()); } // add new paths if (profile.getPaths() != null) { for (EndpointOverride path : profile.getPaths()) { int pathId = PathOverrideService.getInstance().addPathnameToProfile(newProfile.getId(), path.getPathName(), path.getPath()); PathOverrideService.getInstance().setContentType(pathId, path.getContentType()); PathOverrideService.getInstance().setRequestType(pathId, path.getRequestType()); PathOverrideService.getInstance().setGlobal(pathId, path.getGlobal()); // add groups to path for (String groupName : path.getGroupNames()) { int groupId = PathOverrideService.getInstance().getGroupIdFromName(groupName); PathOverrideService.getInstance().AddGroupByNumber(newProfile.getId(), pathId, groupId); } } } // set active ClientService.getInstance().updateActive(newProfile.getId(), Constants.PROFILE_CLIENT_DEFAULT_ID, profile.getActive()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // SCRIPTS try { // delete all scripts for (Script script : ScriptService.getInstance().getScripts()) { ScriptService.getInstance().removeScript(script.getId()); } // add scripts for (Script script : backupData.getScripts()) { ScriptService.getInstance().addScript(script.getName(), script.getScript()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // tell http/https proxies to reload plugins try { org.apache.http.conn.ssl.SSLSocketFactory sslsf = new org.apache.http.conn.ssl.SSLSocketFactory( new TrustStrategy() { @Override public boolean isTrusted(final X509Certificate[] chain, String authType) throws CertificateException { // ignore SSL cert issues return true; } }); HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; sslsf.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); for (String connectstring : getConnectorStrings("https_proxy")) { HttpGet request = new HttpGet(connectstring + "/proxy/reload"); HttpClient httpClient = new org.apache.http.impl.client.DefaultHttpClient(); String[] parts = connectstring.split(":"); httpClient.getConnectionManager().getSchemeRegistry() .register(new org.apache.http.conn.scheme.Scheme("https", Integer.parseInt(parts[parts.length - 1]), sslsf)); HttpResponse response = httpClient.execute(request); } } catch (Exception e) { e.printStackTrace(); logger.info("Exception caught during proxy reload. Things may be in an inconsistent state."); } // restart plugin service for this process PluginManager.destroy(); return true; }
From source file:fr.eolya.utils.http.HttpLoader.java
/** * @param /*from w ww . j a v a2 s . c om*/ * @return */ private HttpClient getHttpClient(String url) { try { // ClientConnectionManager SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); registry.register(new Scheme("https", 443, sf)); ClientConnectionManager ccm = new PoolingClientConnectionManager(registry); // Params HttpParams httpParams = getHttpParams(); // DefaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(ccm, httpParams); // Proxy setProxy(httpClient, url, proxyHost, proxyPort, proxyExclude, proxyUserName, proxyPassword); // if (StringUtils.isNotEmpty(proxyHost)) { // if (StringUtils.isNotEmpty(proxyUserName) && StringUtils.isNotEmpty(proxyPassword)) { // httpClient.getCredentialsProvider().setCredentials( // new AuthScope(proxyHost,Integer.valueOf(proxyPort)), // new UsernamePasswordCredentials(proxyUserName, proxyPassword)); // } // HttpHost proxy = new HttpHost(proxyHost,Integer.valueOf(proxyPort)); // httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy); // } else { // httpClient.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY); // } // Cookies if (cookies != null) { CookieStore cookieStore = new BasicCookieStore(); Iterator<Entry<String, String>> it = cookies.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next(); BasicClientCookie cookie = new BasicClientCookie(pairs.getKey(), pairs.getValue()); //cookie.setDomain("your domain"); cookie.setPath("/"); cookieStore.addCookie(cookie); } httpClient.setCookieStore(cookieStore); } return new DecompressingHttpClient(httpClient); } catch (Exception e) { return new DecompressingHttpClient(new DefaultHttpClient()); } }
From source file:org.jenkinsci.plugins.bitbucketNotifier.BitbucketNotifier.java
/** * Helper in place to allow us to define out HttpClient SSL context * * @param ignoreUnverifiedSSL/* w w w . j a va 2 s .com*/ * @param credentials * @return * @throws UnrecoverableKeyException * @throws NoSuchAlgorithmException * @throws KeyStoreException * @throws KeyManagementException */ private SSLContext buildSslContext(boolean ignoreUnverifiedSSL, Credentials credentials) throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { SSLContextBuilder customContext = SSLContexts.custom(); if (credentials instanceof CertificateCredentials) { customContext = customContext.loadKeyMaterial(((CertificateCredentials) credentials).getKeyStore(), ((CertificateCredentials) credentials).getPassword().getPlainText().toCharArray()); } if (ignoreUnverifiedSSL) { TrustStrategy easyStrategy = new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }; customContext = customContext.loadTrustMaterial(null, easyStrategy); } return customContext.useTLS().build(); }
From source file:ch.admin.hermes.etl.load.cmis.AlfrescoCMISClient.java
/** * Liefert einen Http Client wo alle Zertifikate erlaubt sind. Vermeidet Zertifikatfehler. * @return DefaultHttpClient//from ww w .j a va 2 s . co m */ private DefaultHttpClient getHttpClient() { try { HttpParams httpParams = new BasicHttpParams(); SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); registry.register(new Scheme("https", 443, sf)); return new DefaultHttpClient(httpParams); } catch (Exception e) { return new DefaultHttpClient(); } }
From source file:com.kixeye.chassis.transport.HttpTransportTest.java
@Test public void testHttpServiceWithJsonWithHTTPSAndHTTP() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("http.enabled", "true"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.hostname", "localhost"); properties.put("https.enabled", "true"); properties.put("https.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("https.hostname", "localhost"); properties.put("https.selfSigned", "true"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(TestRestService.class); try {/*w w w . j ava 2 s .c om*/ context.refresh(); final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class); SSLContextBuilder builder = SSLContexts.custom(); builder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); SSLContext sslContext = builder.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() { @Override public void verify(String host, SSLSocket ssl) throws IOException { } @Override public void verify(String host, X509Certificate cert) throws SSLException { } @Override public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { } @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("https", sslsf) .register("http", new PlainConnectionSocketFactory()).build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(HttpClients.custom().setConnectionManager(cm).build()); RestTemplate httpClient = new RestTemplate(requestFactory); httpClient.setErrorHandler(new ResponseErrorHandler() { public boolean hasError(ClientHttpResponse response) throws IOException { return response.getRawStatusCode() == HttpStatus.OK.value(); } public void handleError(ClientHttpResponse response) throws IOException { } }); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>( Lists.newArrayList(new SerDeHttpMessageConverter(serDe)))); TestObject response = httpClient.getForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.postForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), new TestObject("more stuff"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.getForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.getForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/getFuture"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.getForObject( new URI("https://localhost:" + properties.get("https.port") + "/stuff/getObservable"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); ResponseEntity<ServiceError> error = httpClient.postForEntity( new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code); error = httpClient.getForEntity( new URI("https://localhost:" + properties.get("https.port") + "/stuff/expectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode()); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description); error = httpClient.getForEntity( new URI("https://localhost:" + properties.get("https.port") + "/stuff/unexpectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code); response = httpClient.getForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.postForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject("stuff"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); response = httpClient.getForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.getForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/getFuture"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); response = httpClient.getForObject( new URI("http://localhost:" + properties.get("http.port") + "/stuff/getObservable"), TestObject.class); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); error = httpClient.postForEntity(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code); error = httpClient.getForEntity( new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode()); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code); Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description); error = httpClient.getForEntity( new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"), ServiceError.class); Assert.assertNotNull(response); Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode()); Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code); } finally { context.close(); } }
From source file:org.pepstock.jem.commands.util.HttpUtil.java
/** * It builds a {@link SSLConnectionSocketFactory} if SSL is needed. * //w w w . j av a2s. c o m * @return the {@link SSLConnectionSocketFactory} for SSL purposes. * @throws KeyManagementException * @throws UnrecoverableKeyException * @throws NoSuchAlgorithmException * @throws KeyStoreException * @see SSLConnectionSocketFactory */ private static SSLConnectionSocketFactory buildSSLConnectionSocketFactory() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException { TrustStrategy ts = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { // always true to avoid certificate unknown exception return true; } }; SSLContextBuilder builder = SSLContexts.custom(); builder.loadTrustMaterial(null, ts); SSLContext sslContext = builder.build(); return new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); }
From source file:gov.nih.nci.nbia.StandaloneDMDispatcher.java
private static List<String> connectAndReadFromURL(URL url) { List<String> data = null; DefaultHttpClient httpClient = null; TrustStrategy easyStrategy = new TrustStrategy() { @Override//from ww w . j ava 2s.c o m public boolean isTrusted(X509Certificate[] certificate, String authType) throws CertificateException { return true; } }; try { SSLSocketFactory sslsf = new SSLSocketFactory(easyStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme httpsScheme = new Scheme("https", 443, sslsf); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); ClientConnectionManager ccm = new ThreadSafeClientConnManager(schemeRegistry); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 50000); HttpConnectionParams.setSoTimeout(httpParams, new Integer(12000)); httpClient = new DefaultHttpClient(ccm, httpParams); httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(schemeRegistry, ProxySelector.getDefault())); // // Additions by lrt for tcia - // // attempt to reduce errors going through a Coyote Point // Equalizer load balance switch httpClient.getParams().setParameter("http.socket.timeout", new Integer(12000)); httpClient.getParams().setParameter("http.socket.receivebuffer", new Integer(16384)); httpClient.getParams().setParameter("http.tcp.nodelay", true); httpClient.getParams().setParameter("http.connection.stalecheck", false); // // end lrt additions HttpPost httpPostMethod = new HttpPost(url.toString()); List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>(); postParams.add(new BasicNameValuePair(osParam, os)); UrlEncodedFormEntity query = new UrlEncodedFormEntity(postParams); httpPostMethod.setEntity(query); HttpResponse response = httpClient.execute(httpPostMethod); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode == HttpStatus.SC_OK) { InputStream inputStream = response.getEntity().getContent(); data = IOUtils.readLines(inputStream); } else { JOptionPane.showMessageDialog(null, "Incorrect response from server: " + responseCode); } } catch (java.net.ConnectException e) { String note = "Connection error 1 while connecting to " + url.toString() + ":\n" + getProxyInfo(); //+ checkListeningPort("127.0.0.1", 8888); printStackTraceToDialog(note, e); //JOptionPane.showMessageDialog(null, "Connection error 1: " + e.getMessage()); e.printStackTrace(); } catch (MalformedURLException e) { String note = "Connection error 2 while connecting to " + url.toString() + ":\n"; printStackTraceToDialog(note, e); //JOptionPane.showMessageDialog(null, "Connection error 2: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { String note = "Connection error 3 while connecting to " + url.toString() + ":\n"; printStackTraceToDialog(note, e); //JOptionPane.showMessageDialog(null, "Connection error 3: " + e.getMessage()); e.printStackTrace(); } catch (KeyManagementException e) { String note = "Connection error 4 while connecting to " + url.toString() + ":\n"; printStackTraceToDialog(note, e); //JOptionPane.showMessageDialog(null, "Connection error 4: " + e.getMessage()); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { String note = "Connection error 5 while connecting to " + url.toString() + ":\n"; printStackTraceToDialog(note, e); //JOptionPane.showMessageDialog(null, "Connection error 5: " + e.getMessage()); e.printStackTrace(); } catch (KeyStoreException e) { String note = "Connection error 6 while connecting to " + url.toString() + ":\n"; printStackTraceToDialog(note, e); //JOptionPane.showMessageDialog(null, "Connection error 6: " + e.getMessage()); e.printStackTrace(); } catch (UnrecoverableKeyException e) { String note = "Connection error 7 while connecting to " + url.toString() + ":\n"; printStackTraceToDialog(note, e); //JOptionPane.showMessageDialog(null, "Connection error 7: " + e.getMessage()); e.printStackTrace(); } finally { if (httpClient != null) { httpClient.getConnectionManager().shutdown(); } } return data; }
From source file:org.syncany.plugins.php.PhpTransferManager.java
@SuppressWarnings("deprecation") private CloseableHttpClient getHttpClient() { try {/*w ww . j a v a 2s . com*/ @SuppressWarnings("deprecation") SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (lastSite != null && !lastSite.equals("")) { Preferences prefs = Preferences.userRoot().node(this.getClass().getName()); int prevr = prefs.getInt(lastSite, -1); if (prevr == -1) { int r = JOptionPane.showConfirmDialog(null, lastSite + "'s SSL certificate is not trusted, do you want to accept it?", "Accept SSL Certificate?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); logger.warning(lastSite + " not trusted, user answered " + r); prevr = r; prefs.putInt(lastSite, r); } logger.warning(lastSite + " not trusted, registered user answer: " + prevr); if (prevr == 0) { return true; } else { return false; } } else { return false; } } }); @SuppressWarnings("deprecation") SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("https", 443, sf)); @SuppressWarnings("deprecation") ClientConnectionManager ccm = new ThreadSafeClientConnManager(registry); return new DefaultHttpClient(ccm); } catch (Exception e) { return new DefaultHttpClient(); } }
From source file:nl.armatiek.xslweb.configuration.WebApp.java
public CloseableHttpClient getHttpClient() { if (httpClient == null) { PoolingHttpClientConnectionManager cm; if (Context.getInstance().getTrustAllCerts()) { try { SSLContextBuilder scb = SSLContexts.custom(); scb.loadTrustMaterial(null, new TrustStrategy() { @Override/* w w w. j a v a 2 s . co m*/ public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); SSLContext sslContext = scb.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("https", sslsf) .register("http", new PlainConnectionSocketFactory()).build(); cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry); } catch (Exception e) { logger.warn("Could not set HttpClient to trust all SSL certificates", e); cm = new PoolingHttpClientConnectionManager(); } } else { cm = new PoolingHttpClientConnectionManager(); } cm.setMaxTotal(200); cm.setDefaultMaxPerRoute(20); HttpHost localhost = new HttpHost("localhost", 80); cm.setMaxPerRoute(new HttpRoute(localhost), 50); HttpClientBuilder builder = HttpClients.custom().setConnectionManager(cm); builder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())); builder.setDefaultCookieStore(new BasicCookieStore()); httpClient = builder.build(); } return httpClient; }
From source file:org.opendedup.sdfs.filestore.cloud.BatchAwsS3ChunkStore.java
@Override public void init(Element config) throws IOException { this.name = Main.cloudBucket.toLowerCase(); this.staged_sync_location.mkdirs(); try {/*from ww w . j a v a 2s.co m*/ if (config.hasAttribute("default-bucket-location")) { bucketLocation = RegionUtils.getRegion(config.getAttribute("default-bucket-location")); } if (config.hasAttribute("connection-check-interval")) { this.checkInterval = Integer.parseInt(config.getAttribute("connection-check-interval")); } if (config.hasAttribute("block-size")) { int sz = (int) StringUtils.parseSize(config.getAttribute("block-size")); HashBlobArchive.MAX_LEN = sz; } if (config.hasAttribute("allow-sync")) { HashBlobArchive.allowSync = Boolean.parseBoolean(config.getAttribute("allow-sync")); if (config.hasAttribute("sync-check-schedule")) { try { new SyncFSScheduler(config.getAttribute("sync-check-schedule")); } catch (Exception e) { SDFSLogger.getLog().error("unable to start sync scheduler", e); } } } if (config.hasAttribute("upload-thread-sleep-time")) { int tm = Integer.parseInt(config.getAttribute("upload-thread-sleep-time")); HashBlobArchive.THREAD_SLEEP_TIME = tm; } if (config.hasAttribute("cache-writes")) { HashBlobArchive.cacheWrites = Boolean.parseBoolean(config.getAttribute("cache-writes")); } if (config.hasAttribute("cache-reads")) { HashBlobArchive.cacheReads = Boolean.parseBoolean(config.getAttribute("cache-reads")); } if (config.hasAttribute("sync-files")) { boolean syncf = Boolean.parseBoolean(config.getAttribute("sync-files")); if (syncf) { new FileReplicationService(this); } } int rsp = 0; int wsp = 0; if (config.hasAttribute("read-speed")) { rsp = Integer.parseInt(config.getAttribute("read-speed")); } if (config.hasAttribute("write-speed")) { wsp = Integer.parseInt(config.getAttribute("write-speed")); } if (config.hasAttribute("local-cache-size")) { long sz = StringUtils.parseSize(config.getAttribute("local-cache-size")); HashBlobArchive.setLocalCacheSize(sz); } if (config.hasAttribute("metadata-version")) { this.mdVersion = Integer.parseInt(config.getAttribute("metadata-version")); } if (config.hasAttribute("map-cache-size")) { int sz = Integer.parseInt(config.getAttribute("map-cache-size")); HashBlobArchive.MAP_CACHE_SIZE = sz; } if (config.hasAttribute("io-threads")) { int sz = Integer.parseInt(config.getAttribute("io-threads")); Main.dseIOThreads = sz; } if (config.hasAttribute("clustered")) { this.clustered = Boolean.parseBoolean(config.getAttribute("clustered")); } if (config.hasAttribute("delete-unclaimed")) { this.deleteUnclaimed = Boolean.parseBoolean(config.getAttribute("delete-unclaimed")); } if (config.hasAttribute("glacier-archive-days")) { this.glacierDays = Integer.parseInt(config.getAttribute("glacier-archive-days")); if (this.glacierDays > 0) Main.checkArchiveOnRead = true; } if (config.hasAttribute("infrequent-access-days")) { this.infrequentAccess = Integer.parseInt(config.getAttribute("infrequent-access-days")); } if (config.hasAttribute("simple-s3")) { EncyptUtils.baseEncode = Boolean.parseBoolean(config.getAttribute("simple-s3")); this.simpleS3 = true; } if (config.hasAttribute("md5-sum")) { this.md5sum = Boolean.parseBoolean(config.getAttribute("md5-sum")); if (!this.md5sum) { System.setProperty("com.amazonaws.services.s3.disableGetObjectMD5Validation", "true"); System.setProperty("com.amazonaws.services.s3.disablePutObjectMD5Validation", "true"); } } ClientConfiguration clientConfig = new ClientConfiguration(); if (config.hasAttribute("use-v4-signer")) { boolean v4s = Boolean.parseBoolean(config.getAttribute("use-v4-signer")); if (v4s) { clientConfig.setSignerOverride("AWSS3V4SignerType"); } } if (config.hasAttribute("use-basic-signer")) { boolean v4s = Boolean.parseBoolean(config.getAttribute("use-basic-signer")); if (v4s) { clientConfig.setSignerOverride("S3SignerType"); } } clientConfig.setMaxConnections(Main.dseIOThreads * 2); clientConfig.setConnectionTimeout(10000); clientConfig.setSocketTimeout(10000); String s3Target = null; if (config.getElementsByTagName("connection-props").getLength() > 0) { Element el = (Element) config.getElementsByTagName("connection-props").item(0); if (el.hasAttribute("connection-timeout")) clientConfig.setConnectionTimeout(Integer.parseInt(el.getAttribute("connection-timeout"))); if (el.hasAttribute("socket-timeout")) clientConfig.setSocketTimeout(Integer.parseInt(el.getAttribute("socket-timeout"))); if (el.hasAttribute("local-address")) clientConfig.setLocalAddress(InetAddress.getByName(el.getAttribute("local-address"))); if (el.hasAttribute("max-retry")) clientConfig.setMaxErrorRetry(Integer.parseInt(el.getAttribute("max-retry"))); if (el.hasAttribute("protocol")) { String pr = el.getAttribute("protocol"); if (pr.equalsIgnoreCase("http")) clientConfig.setProtocol(Protocol.HTTP); else clientConfig.setProtocol(Protocol.HTTPS); } if (el.hasAttribute("s3-target")) { s3Target = el.getAttribute("s3-target"); } if (el.hasAttribute("proxy-host")) { clientConfig.setProxyHost(el.getAttribute("proxy-host")); } if (el.hasAttribute("proxy-domain")) { clientConfig.setProxyDomain(el.getAttribute("proxy-domain")); } if (el.hasAttribute("proxy-password")) { clientConfig.setProxyPassword(el.getAttribute("proxy-password")); } if (el.hasAttribute("proxy-port")) { clientConfig.setProxyPort(Integer.parseInt(el.getAttribute("proxy-port"))); } if (el.hasAttribute("proxy-username")) { clientConfig.setProxyUsername(el.getAttribute("proxy-username")); } } if (s3Target != null && s3Target.toLowerCase().startsWith("https")) { TrustStrategy acceptingTrustStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] certificate, String authType) { return true; } }; SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); clientConfig.getApacheHttpClientConfig().withSslSocketFactory(sf); } if (awsCredentials != null) s3Service = new AmazonS3Client(awsCredentials, clientConfig); else s3Service = new AmazonS3Client(new InstanceProfileCredentialsProvider(), clientConfig); if (bucketLocation != null) { s3Service.setRegion(bucketLocation); System.out.println("bucketLocation=" + bucketLocation.toString()); } if (s3Target != null) { s3Service.setEndpoint(s3Target); System.out.println("target=" + s3Target); } if (config.hasAttribute("disableDNSBucket")) { s3Service.setS3ClientOptions(new S3ClientOptions() .withPathStyleAccess(Boolean.parseBoolean(config.getAttribute("disableDNSBucket"))) .disableChunkedEncoding()); System.out.println( "disableDNSBucket=" + Boolean.parseBoolean(config.getAttribute("disableDNSBucket"))); } if (!s3Service.doesBucketExist(this.name)) { s3Service.createBucket(this.name); SDFSLogger.getLog().info("created new store " + name); ObjectMetadata md = new ObjectMetadata(); md.addUserMetadata("currentsize", "0"); md.addUserMetadata("currentcompressedsize", "0"); md.addUserMetadata("clustered", "true"); md.addUserMetadata("lastupdate", Long.toString(System.currentTimeMillis())); md.addUserMetadata("hostname", InetAddress.getLocalHost().getHostName()); md.addUserMetadata("port", Integer.toString(Main.sdfsCliPort)); this.clustered = true; byte[] sz = Long.toString(System.currentTimeMillis()).getBytes(); if (md5sum) { String mds = BaseEncoding.base64().encode(ServiceUtils.computeMD5Hash(sz)); md.setContentMD5(mds); } md.setContentLength(sz.length); this.binm = "bucketinfo/" + EncyptUtils.encHashArchiveName(Main.DSEID, Main.chunkStoreEncryptionEnabled); s3Service.putObject(this.name, binm, new ByteArrayInputStream(sz), md); } else { Map<String, String> obj = null; ObjectMetadata omd = null; try { omd = s3Service.getObjectMetadata(this.name, binm); obj = omd.getUserMetadata(); obj.get("currentsize"); } catch (Exception e) { omd = null; SDFSLogger.getLog().debug("unable to find bucketinfo object", e); } if (omd == null) { try { this.binm = "bucketinfo/" + EncyptUtils.encHashArchiveName(Main.DSEID, Main.chunkStoreEncryptionEnabled); omd = s3Service.getObjectMetadata(this.name, binm); obj = omd.getUserMetadata(); obj.get("currentsize"); } catch (Exception e) { omd = null; SDFSLogger.getLog().debug("unable to find bucketinfo object", e); } } if (omd == null) { ObjectMetadata md = new ObjectMetadata(); md.addUserMetadata("currentsize", "0"); md.addUserMetadata("currentcompressedsize", "0"); md.addUserMetadata("clustered", "true"); md.addUserMetadata("lastupdate", Long.toString(System.currentTimeMillis())); md.addUserMetadata("hostname", InetAddress.getLocalHost().getHostName()); md.addUserMetadata("port", Integer.toString(Main.sdfsCliPort)); this.clustered = true; this.binm = "bucketinfo/" + EncyptUtils.encHashArchiveName(Main.DSEID, Main.chunkStoreEncryptionEnabled); byte[] sz = Long.toString(System.currentTimeMillis()).getBytes(); if (md5sum) { String mds = BaseEncoding.base64().encode(ServiceUtils.computeMD5Hash(sz)); md.setContentMD5(mds); } md.setContentLength(sz.length); s3Service.putObject(this.name, binm, new ByteArrayInputStream(sz), md); } else { if (obj.containsKey("currentsize")) { long cl = Long.parseLong((String) obj.get("currentsize")); if (cl >= 0) { HashBlobArchive.currentLength.set(cl); } else SDFSLogger.getLog().warn("The S3 objectstore DSE did not close correctly len=" + cl); } else { SDFSLogger.getLog().warn( "The S3 objectstore DSE did not close correctly. Metadata tag currentsize was not added"); } if (obj.containsKey("currentcompressedsize")) { long cl = Long.parseLong((String) obj.get("currentcompressedsize")); if (cl >= 0) { HashBlobArchive.compressedLength.set(cl); } else SDFSLogger.getLog().warn("The S3 objectstore DSE did not close correctly clen=" + cl); } else { SDFSLogger.getLog().warn( "The S3 objectstore DSE did not close correctly. Metadata tag currentsize was not added"); } if (obj.containsKey("clustered")) { this.clustered = Boolean.parseBoolean(obj.get("clustered")); } else this.clustered = false; obj.put("clustered", Boolean.toString(this.clustered)); omd.setUserMetadata(obj); try { updateObject(binm, omd); } catch (Exception e) { SDFSLogger.getLog().warn("unable to update bucket info in init", e); SDFSLogger.getLog().info("created new store " + name); ObjectMetadata md = new ObjectMetadata(); md.addUserMetadata("currentsize", "0"); md.addUserMetadata("lastupdate", Long.toString(System.currentTimeMillis())); md.addUserMetadata("currentcompressedsize", "0"); md.addUserMetadata("clustered", Boolean.toString(this.clustered)); md.addUserMetadata("hostname", InetAddress.getLocalHost().getHostName()); md.addUserMetadata("port", Integer.toString(Main.sdfsCliPort)); byte[] sz = Long.toString(System.currentTimeMillis()).getBytes(); if (md5sum) { String mds = BaseEncoding.base64().encode(ServiceUtils.computeMD5Hash(sz)); md.setContentMD5(mds); } md.setContentLength(sz.length); s3Service.putObject(this.name, binm, new ByteArrayInputStream(sz), md); } } } ArrayList<Transition> trs = new ArrayList<Transition>(); if (this.glacierDays > 0 && s3Target == null) { Transition transToArchive = new Transition().withDays(this.glacierDays) .withStorageClass(StorageClass.Glacier); trs.add(transToArchive); } if (this.infrequentAccess > 0 && s3Target == null) { Transition transToArchive = new Transition().withDays(this.infrequentAccess) .withStorageClass(StorageClass.StandardInfrequentAccess); trs.add(transToArchive); } if (trs.size() > 0) { BucketLifecycleConfiguration.Rule ruleArchiveAndExpire = new BucketLifecycleConfiguration.Rule() .withId("SDFS Automated Archive Rule for Block Data").withPrefix("blocks/") .withTransitions(trs).withStatus(BucketLifecycleConfiguration.ENABLED.toString()); List<BucketLifecycleConfiguration.Rule> rules = new ArrayList<BucketLifecycleConfiguration.Rule>(); rules.add(ruleArchiveAndExpire); BucketLifecycleConfiguration configuration = new BucketLifecycleConfiguration().withRules(rules); // Save configuration. s3Service.setBucketLifecycleConfiguration(this.name, configuration); } else if (s3Target == null) { s3Service.deleteBucketLifecycleConfiguration(this.name); } HashBlobArchive.init(this); HashBlobArchive.setReadSpeed(rsp); HashBlobArchive.setWriteSpeed(wsp); Thread th = new Thread(this); th.start(); } catch (Exception e) { SDFSLogger.getLog().error("unable to start service", e); throw new IOException(e); } }