1 24 package org.ofbiz.base.util; 25 26 import java.io.IOException ; 27 import java.net.HttpURLConnection ; 28 import java.net.URL ; 29 import java.net.URLConnection ; 30 import java.security.GeneralSecurityException ; 31 32 import javax.net.ssl.*; 33 34 41 public class URLConnector { 42 43 public static final String module = URLConnector.class.getName(); 44 45 private URLConnection connection = null; 46 private URL url = null; 47 private String clientCertAlias = null; 48 private boolean timedOut = false; 49 50 protected URLConnector() {} 51 protected URLConnector(URL url, String clientCertAlias) { 52 this.clientCertAlias = clientCertAlias; 53 this.url = url; 54 } 55 56 protected synchronized URLConnection openConnection(int timeout) throws IOException { 57 Thread t = new Thread (new URLConnectorThread()); 58 t.start(); 59 60 try { 61 this.wait(timeout); 62 } catch (InterruptedException e) { 63 if (connection == null) { 64 timedOut = true; 65 } else { 66 close(connection); 67 } 68 throw new IOException ("Connection never established"); 69 } 70 71 if (connection != null) { 72 return connection; 73 } else { 74 timedOut = true; 75 throw new IOException ("Connection timed out"); 76 } 77 } 78 79 public static URLConnection openConnection(URL url) throws IOException { 80 return openConnection(url, 30000); 81 } 82 83 public static URLConnection openConnection(URL url, int timeout) throws IOException { 84 return openConnection(url, timeout, null); 85 } 86 87 public static URLConnection openConnection(URL url, String clientCertAlias) throws IOException { 88 return openConnection(url, 30000, clientCertAlias); 89 } 90 91 public static URLConnection openConnection(URL url, int timeout, String clientCertAlias) throws IOException { 92 URLConnector uc = new URLConnector(url, clientCertAlias); 93 return uc.openConnection(timeout); 94 } 95 96 private class URLConnectorThread implements Runnable { 98 public void run() { 99 URLConnection con = null; 100 try { 101 con = url.openConnection(); 102 if ("HTTPS".equalsIgnoreCase(url.getProtocol())) { 103 HttpsURLConnection scon = (HttpsURLConnection) con; 104 try { 105 scon.setSSLSocketFactory(SSLUtil.getSSLSocketFactory(clientCertAlias)); 106 } catch (GeneralSecurityException gse) { 107 Debug.logError(gse, module); 108 } 109 } 110 } catch (IOException e) { 111 Debug.logError(e, module); 112 } 113 114 synchronized (URLConnector.this) { 115 if (timedOut && con != null) { 116 close(con); 117 } else { 118 connection = con; 119 URLConnector.this.notify(); 120 } 121 } 122 } 123 } 124 125 private static void close(URLConnection con) { 127 if (con instanceof HttpURLConnection ) { 128 ((HttpURLConnection ) con).disconnect(); 129 } 130 } 131 } 132 | Popular Tags |