List of usage examples for org.apache.http.conn.ssl SSLSocketFactory SSLSocketFactory
public SSLSocketFactory(final KeyStore keystore, final String keystorePassword, final KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException
From source file:com.emc.cto.ridagent.rid.test.TestScript.java
public static String httpSend(String output, String destURL) throws ParserConfigurationException, SAXException { /* Set up TLS mutual authentication */ KeyStore keystore = null;/* w w w . j ava 2 s . co m*/ String docid = null; try { keystore = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } InputStream keystoreInput = null; try { keystoreInput = new FileInputStream(m_keystorePath); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { keystore.load(keystoreInput, m_keystorePassword.toCharArray()); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (logger.isDebugEnabled()) { logger.debug("Keystore has " + keystore.size() + " keys"); } } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } KeyStore truststore = null; try { truststore = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (KeyStoreException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } InputStream truststoreInput = null; try { truststoreInput = new FileInputStream(m_truststorePath); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { truststore.load(truststoreInput, m_truststorePassword.toCharArray()); } catch (NoSuchAlgorithmException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (CertificateException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } SchemeRegistry schemeRegistry = new SchemeRegistry(); SSLSocketFactory schemeSocketFactory = null; try { schemeSocketFactory = new SSLSocketFactory(keystore, m_keystorePassword, truststore); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecoverableKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } schemeRegistry.register(new Scheme(m_protocol, m_port, schemeSocketFactory)); final HttpParams httpParams = new BasicHttpParams(); DefaultHttpClient httpClient = new DefaultHttpClient(new BasicClientConnectionManager(schemeRegistry), httpParams); /* Prepare the request to send */ Map<String, Object> responseMap = new HashMap<String, Object>(); HttpEntity request = new StringEntity(output, ContentType.TEXT_XML); //Create POST method HttpPost postMethod = new HttpPost(destURL); postMethod.setHeader("User-Agent", "EMC RID System"); postMethod.setHeader("Content-Type", "text/xml"); postMethod.setEntity(request); /* POST the request and process the response */ HttpResponse httpResponse = null; int code; try { httpResponse = httpClient.execute(postMethod); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (httpResponse.getEntity() != null) { code = httpResponse.getStatusLine().getStatusCode(); try { InputStream xml = httpResponse.getEntity().getContent(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(xml); docid = doc.getElementsByTagName("iodef:IncidentID").item(0).getTextContent(); System.out.println("ID of the newly created document " + docid); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } responseMap.put("success", true); responseMap.put("statusCode", code); } else { responseMap.put("success", false); responseMap.put("errorMessage", "Send failed (fill in exception)"); } return docid; }
From source file:com.emc.cto.ridagent.rid.util.HTTPSender.java
public static Map<String, Object> httpSend(PipelineOutput output, String destURL) { /* Set up TLS mutual authentication */ KeyStore keystore = null;/* ww w. j ava2 s . co m*/ try { keystore = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } InputStream keystoreInput = null; try { keystoreInput = new FileInputStream(m_keystorePath); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { keystore.load(keystoreInput, m_keystorePassword.toCharArray()); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (logger.isDebugEnabled()) { logger.debug("Keystore has " + keystore.size() + " keys"); } } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } KeyStore truststore = null; try { truststore = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (KeyStoreException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } InputStream truststoreInput = null; try { truststoreInput = new FileInputStream(m_truststorePath); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { truststore.load(truststoreInput, m_truststorePassword.toCharArray()); } catch (NoSuchAlgorithmException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (CertificateException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { if (logger.isDebugEnabled()) { logger.debug("Truststore has " + truststore.size() + " keys"); } } catch (KeyStoreException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } SchemeRegistry schemeRegistry = new SchemeRegistry(); SSLSocketFactory schemeSocketFactory = null; try { schemeSocketFactory = new SSLSocketFactory(keystore, m_keystorePassword, truststore); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecoverableKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } schemeRegistry.register(new Scheme(m_protocol, m_port, schemeSocketFactory)); final HttpParams httpParams = new BasicHttpParams(); DefaultHttpClient httpClient = new DefaultHttpClient(new BasicClientConnectionManager(schemeRegistry), httpParams); /* Prepare the request to send */ String body = null; Map<String, Object> responseMap = new HashMap<String, Object>(); List<com.emc.documentum.xml.xproc.io.Source> sources = output.getSources(output.getPrimaryOutputPort()); if (sources != null && !sources.isEmpty()) { // pipeline should only return a single value - we return the first as the output Node node = sources.get(0).getNode(); InputStream is = sources.get(0).getInputStream(); Reader rdr = sources.get(0).getReader(); //For now we implement node only since we assume content is in the node if (node != null) { if (logger.isDebugEnabled()) { logger.debug("Node has content"); } body = Utilities.nodeToString(node); } else if (is != null) { if (logger.isDebugEnabled()) { logger.debug("Input stream has content"); } } else if (rdr != null) { if (logger.isDebugEnabled()) { logger.debug("Reader has content"); } } } HttpEntity request = new StringEntity(body, ContentType.TEXT_XML); //Create POST method HttpPost postMethod = new HttpPost(destURL); postMethod.setHeader("User-Agent", "EMC RID System"); postMethod.setHeader("Content-Type", "text/xml"); postMethod.setEntity(request); /* POST the request and process the response */ HttpResponse httpResponse = null; int code; String responseBody = null; try { httpResponse = httpClient.execute(postMethod); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (httpResponse.getEntity() != null) { code = httpResponse.getStatusLine().getStatusCode(); try { responseBody = EntityUtils.toString(httpResponse.getEntity()); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (logger.isDebugEnabled()) { logger.debug("Response status code: " + code); logger.debug("Reponse body =" + responseBody); } responseMap.put("success", true); responseMap.put("statusCode", code); responseMap.put("responseBody", responseBody); } else { responseMap.put("success", false); responseMap.put("errorMessage", "Send failed (fill in exception)"); } return responseMap; }
From source file:com.alliander.osgp.adapter.ws.smartmetering.infra.ws.WebServiceTemplateFactory.java
/** * @throws WebServiceSecurityException/*ww w .j a v a 2 s . co m*/ * if an error occurs while attempting to create a secured * connection. */ private HttpComponentsMessageSender webServiceMessageSender(final String keystore) throws WebServiceSecurityException { try { // Open keystore, assuming same identity final KeyStoreFactoryBean keyStoreFactory = new KeyStoreFactoryBean(); keyStoreFactory.setType(this.keyStoreType); keyStoreFactory.setLocation(new FileSystemResource(this.keyStoreLocation + "/" + keystore + ".pfx")); keyStoreFactory.setPassword(this.keyStorePassword); keyStoreFactory.afterPropertiesSet(); final KeyStore keyStore = keyStoreFactory.getObject(); if (keyStore == null || keyStore.size() == 0) { throw new KeyStoreException("Key store is empty"); } // Create HTTP sender and associate keystore to it final HttpComponentsMessageSender sender = new HttpComponentsMessageSender(); final HttpClient client = sender.getHttpClient(); final SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore, this.keyStorePassword, this.trustStoreFactory.getObject()); final Scheme scheme = new Scheme("https", 443, socketFactory); client.getConnectionManager().getSchemeRegistry().register(scheme); return sender; } catch (IOException | GeneralSecurityException e) { throw new WebServiceSecurityException("An exception occured while creating a secured connection.", e); } }
From source file:com.redblackit.web.client.X509HttpClientFactoryBean.java
/** * Ensure we have keystores and passwords defined. * //from w ww.j a v a 2s.com * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() */ @Override public void afterPropertiesSet() throws Exception { if (getKeyStore() == null || getKeyStore().length() == 0 || getKeyStoreType() == null || getKeyStoreType().length() == 0 || getKeyStorePassword() == null || getKeyStorePassword().length() == 0 || getTrustStore() == null || getTrustStore().length() == 0 || getTrustStoreType() == null || getTrustStoreType().length() == 0 || getTrustStorePassword() == null || getTrustStorePassword().length() == 0) { throw new IllegalArgumentException("Missing key/trust store info:" + this); } if (logger.isDebugEnabled()) { logger.debug("afterPropertiesSet:E:this=" + this); } try { final KeyStore keystore = KeyStore.getInstance(getKeyStoreType()); InputStream keystoreInput = new FileInputStream(ResourceUtils.getFile(getKeyStore())); keystore.load(keystoreInput, getKeyStorePassword().toCharArray()); KeyStore truststore = KeyStore.getInstance(getTrustStoreType()); InputStream truststoreInput = new FileInputStream(ResourceUtils.getFile(getTrustStore())); truststore.load(truststoreInput, getTrustStorePassword().toCharArray()); final SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", getHttpsPort(), new SSLSocketFactory(keystore, getKeyStorePassword(), truststore))); if (httpParams == null) { httpParams = new BasicHttpParams(); httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, DEFAULT_READ_TIMEOUT_MILLISECONDS); } httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(schemeRegistry), httpParams); if (logger.isDebugEnabled()) { logger.debug("afterPropertiesSet:R:this=" + this); } } catch (Throwable t) { throw new RuntimeException(this.toString(), t); } }
From source file:com.microsoft.exchange.impl.ExchangeWebServicesClient.java
@Override protected void initGateway() throws Exception { super.initGateway(); WebServiceMessageSender[] senders = getWebServiceTemplate().getMessageSenders(); for (WebServiceMessageSender sender : senders) { if (sender instanceof HttpComponentsMessageSender) { HttpComponentsMessageSender hSender = (HttpComponentsMessageSender) sender; ClientConnectionManager connectionManager = hSender.getHttpClient().getConnectionManager(); SchemeRegistry schemeRegistry = connectionManager.getSchemeRegistry(); SSLSocketFactory sf = new SSLSocketFactory(keyStore, safeToString(keyStorePassword), trustStore); Scheme https = new Scheme("https", 443, sf); schemeRegistry.register(https); }// w w w .j av a 2s . c o m } }
From source file:com.mhise.util.MHISEUtil.java
public static DefaultHttpClient initializeHTTPClient(Context ctx, KeyStore localTrustStore) { DefaultHttpClient httpClient = null; try {/*from w ww. j a va2s.c o m*/ SchemeRegistry schemeRegistry = new SchemeRegistry(); SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore, null, getServerKeyStore(Constants.HTTPS_URL_SVC)); sslSocketFactory.setHostnameVerifier((X509HostnameVerifier) SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); schemeRegistry.register(new Scheme("https", sslSocketFactory, 443)); HttpParams params = new BasicHttpParams(); ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); httpClient = new DefaultHttpClient(cm, params); } catch (Exception e) { // TODO: handle exception Logger.debug("MHISEUtil-->initializeHTTPClient -->", "" + e); } return httpClient; }
From source file:de.mendelson.comm.as2.send.MessageHttpUploader.java
private Scheme createHTTPSScheme() throws Exception { //cert store not set so far: take the preferences data if (this.certStore == null) { this.certStore = new KeystoreStorageImplFile(this.preferences.get(PreferencesAS2.KEYSTORE_HTTPS_SEND), this.preferences.get(PreferencesAS2.KEYSTORE_HTTPS_SEND_PASS).toCharArray(), BCCryptoHelper.KEYSTORE_JKS); this.trustStore = new KeystoreStorageImplFile(this.preferences.get(PreferencesAS2.KEYSTORE_HTTPS_SEND), this.preferences.get(PreferencesAS2.KEYSTORE_HTTPS_SEND_PASS).toCharArray(), BCCryptoHelper.KEYSTORE_JKS); }/*from ww w. j a v a2s . com*/ SSLSocketFactory socketFactory = new SSLSocketFactory(this.certStore.getKeystore(), new String(this.certStore.getKeystorePass()), this.trustStore.getKeystore()); socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return (new Scheme("https", socketFactory, 443)); }
From source file:ee.signwise.sdk.service.SignWiseConnection.java
/** * Send / receive json request/*from ww w.j a v a 2 s.c o m*/ * @param url service access location * @param request json request * @param method http method * @param nTimeout http timout in milliseconds * @return service sresponse * @throws IOException */ private byte[] callUrl(String url, String request, String method, int nTimeout) throws IOException, NoSuchAlgorithmException, NoSuchAlgorithmException, KeyStoreException, CertificateException, UnrecoverableKeyException, KeyManagementException { HttpClient client = new DefaultHttpClient(); HttpResponse response = null; //try { if (m_logger.isDebugEnabled()) m_logger.debug("Connecting to server url: " + url); if (m_logger.isDebugEnabled()) m_logger.debug("Using keystore " + m_keyStore.getFileName()); KeyStore keystore = KeyStore.getInstance(m_keyStore.getType()); keystore.load(new FileInputStream(m_keyStore.getFileName()), m_keyStore.getPassword().toCharArray()); KeyStore truststore = KeyStore.getInstance(m_trustStore.getType()); truststore.load(new FileInputStream(m_trustStore.getFileName()), m_trustStore.getPassword().toCharArray()); SSLSocketFactory sslsf = new SSLSocketFactory(keystore, m_keyStore.getPassword(), truststore); Scheme https = new Scheme("https", 443, sslsf); client.getConnectionManager().getSchemeRegistry().register(https); if (m_logger.isDebugEnabled()) m_logger.debug("Method: " + method + " JSON\n---\n" + request + "\n---\n"); if ("GET".equals(method)) { HttpGet get = new HttpGet(url); response = client.execute(get); //System.out.println(get.getStatusLine()); } else if ("POST".equals(method)) { HttpPost post = new HttpPost(url); post.addHeader("Accept", "application/json"); post.addHeader("content-type", "application/json"); post.setEntity(new StringEntity(request)); response = client.execute(post); //System.out.println(post.getStatusLine()); } else if ("PATCH".equals(method)) { HttpPatch patch = new HttpPatch(url); patch.setEntity(new StringEntity(request)); response = client.execute(patch); } else if ("DELETE".equals(method)) { HttpDelete del = new HttpDelete(url); //del.setEntity(new StringEntity(request)); response = client.execute(del); } //else // read the response ByteArrayOutputStream bos = new ByteArrayOutputStream(); if (response != null && response.getEntity().getContent() != null) { InputStream is = response.getEntity().getContent(); byte[] data = new byte[1024]; int nRead = 0; while ((nRead = is.read(data)) > 0) { bos.write(data, 0, nRead); } is.close(); } if (m_logger.isDebugEnabled()) m_logger.debug("Received: " + new String(bos.toByteArray())); /*} finally { }*/ return bos.toByteArray(); }