KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > core > internal > net > ProxyManager


1 /*******************************************************************************
2  * Copyright (c) 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.core.internal.net;
12
13 import java.net.Authenticator JavaDoc;
14 import java.util.*;
15
16 import org.eclipse.core.net.proxy.*;
17 import org.eclipse.core.runtime.*;
18 import org.eclipse.core.runtime.preferences.IEclipsePreferences;
19 import org.eclipse.core.runtime.preferences.InstanceScope;
20 import org.eclipse.core.runtime.preferences.IEclipsePreferences.*;
21 import org.eclipse.osgi.util.NLS;
22 import org.osgi.service.prefs.BackingStoreException;
23 import org.osgi.service.prefs.Preferences;
24
25 public class ProxyManager implements IProxyService, IPreferenceChangeListener {
26     
27     private static final String JavaDoc PREF_HAS_MIGRATED = "org.eclipse.core.net.hasMigrated"; //$NON-NLS-1$
28

29     /**
30      * Preference constants used by Update to record the HTTP proxy
31      */

32     private static String JavaDoc HTTP_PROXY_HOST = "org.eclipse.update.core.proxy.host"; //$NON-NLS-1$
33
private static String JavaDoc HTTP_PROXY_PORT = "org.eclipse.update.core.proxy.port"; //$NON-NLS-1$
34
private static String JavaDoc HTTP_PROXY_ENABLE = "org.eclipse.update.core.proxy.enable"; //$NON-NLS-1$
35

36     private static final String JavaDoc PREF_NON_PROXIED_HOSTS = "nonProxiedHosts"; //$NON-NLS-1$
37
private static final String JavaDoc PREF_ENABLED = "proxiesEnabled"; //$NON-NLS-1$
38

39     private static IProxyService proxyManager;
40     
41     ListenerList listeners = new ListenerList(ListenerList.IDENTITY);
42     private String JavaDoc[] nonProxiedHosts;
43     private final ProxyType[] proxies = new ProxyType[] {
44             new ProxyType(IProxyData.HTTP_PROXY_TYPE),
45             new ProxyType(IProxyData.HTTPS_PROXY_TYPE),
46             new ProxyType(IProxyData.SOCKS_PROXY_TYPE)
47         };
48
49     /**
50      * Return the proxy manager.
51      * @return the proxy manager
52      */

53     public synchronized static IProxyService getProxyManager() {
54         if (proxyManager == null)
55             proxyManager = new ProxyManager();
56         return proxyManager;
57     }
58     
59     /* (non-Javadoc)
60      * @see org.eclipse.core.net.IProxyManager#addProxyChangeListener(org.eclipse.core.net.IProxyChangeListener)
61      */

62     public void addProxyChangeListener(IProxyChangeListener listener) {
63         listeners.add(listener);
64     }
65     
66     /* (non-Javadoc)
67      * @see org.eclipse.core.net.IProxyManager#removeProxyChangeListener(org.eclipse.core.net.IProxyChangeListener)
68      */

69     public void removeProxyChangeListener(IProxyChangeListener listener) {
70         listeners.remove(listener);
71     }
72     
73     private void fireChange(final IProxyChangeEvent event) {
74         Object JavaDoc[] l = listeners.getListeners();
75         for (int i = 0; i < l.length; i++) {
76             final IProxyChangeListener listener = (IProxyChangeListener)l[i];
77             SafeRunner.run(new ISafeRunnable() {
78                 public void run() throws Exception JavaDoc {
79                     listener.proxyInfoChanged(event);
80                 }
81                 public void handleException(Throwable JavaDoc exception) {
82                     // Logged by SafeRunner
83
}
84             });
85         }
86     }
87
88     /* (non-Javadoc)
89      * @see org.eclipse.core.net.IProxyManager#getNonProxiedHosts()
90      */

91     public synchronized String JavaDoc[] getNonProxiedHosts() {
92         if (nonProxiedHosts == null) {
93             String JavaDoc prop = Activator.getInstance().getInstancePreferences().get(PREF_NON_PROXIED_HOSTS, "localhost|127.0.0.1"); //$NON-NLS-1$
94
nonProxiedHosts = ProxyType.convertPropertyStringToHosts(prop);
95         }
96         if (nonProxiedHosts.length == 0)
97             return nonProxiedHosts;
98         String JavaDoc[] result = new String JavaDoc[nonProxiedHosts.length];
99         System.arraycopy(nonProxiedHosts, 0, result, 0, nonProxiedHosts.length );
100         return result;
101     }
102
103     /* (non-Javadoc)
104      * @see org.eclipse.core.net.IProxyManager#setNonProxiedHosts(java.lang.String[])
105      */

106     public void setNonProxiedHosts(String JavaDoc[] hosts) {
107         Assert.isNotNull(hosts);
108         for (int i = 0; i < hosts.length; i++) {
109             String JavaDoc host = hosts[i];
110             Assert.isNotNull(host);
111             Assert.isTrue(host.length() > 0);
112         }
113         String JavaDoc[] oldHosts = nonProxiedHosts;
114         nonProxiedHosts = hosts;
115         Activator.getInstance().getInstancePreferences().put(PREF_NON_PROXIED_HOSTS, ProxyType.convertHostsToPropertyString(nonProxiedHosts));
116         try {
117             Activator.getInstance().getInstancePreferences().flush();
118         } catch (BackingStoreException e) {
119             Activator.logError(
120                     "An error occurred while writing out the non-proxied hosts list", e); //$NON-NLS-1$
121
}
122         IProxyData[] data = getProxyData();
123         IProxyChangeEvent event = new ProxyChangeEvent(IProxyChangeEvent.NONPROXIED_HOSTS_CHANGED, oldHosts, getNonProxiedHosts(), data, new IProxyData[0]);
124         fireChange(event);
125     }
126
127     
128     public IProxyData[] getProxyData() {
129         IProxyData[] result = new IProxyData[proxies.length];
130         for (int i = 0; i < proxies.length; i++) {
131             ProxyType type = proxies[i];
132             result[i] = type.getProxyData(ProxyType.VERIFY_EQUAL);
133         }
134         return result;
135     }
136     
137     public void setProxyData(IProxyData[] proxies) {
138         doSetProxyData(proxies);
139     }
140     
141     private void doSetProxyData(IProxyData[] proxyDatas) {
142         IProxyData[] oldData = getProxyData();
143         String JavaDoc[] hosts = getNonProxiedHosts();
144         IProxyData[] changedProxies = internalSetProxyData(proxyDatas);
145         if (changedProxies.length > 0) {
146             IProxyChangeEvent event = new ProxyChangeEvent(IProxyChangeEvent.PROXY_SERVICE_ENABLEMENT_CHANGE, hosts, hosts, oldData, changedProxies);
147             fireChange(event);
148         }
149     }
150
151     private IProxyData[] internalSetProxyData(IProxyData[] proxyDatas) {
152         List result = new ArrayList();
153         for (int i = 0; i < proxyDatas.length; i++) {
154             IProxyData proxyData = proxyDatas[i];
155             ProxyType type = getType(proxyData);
156             if (type != null && type.setProxyData(proxyData, isProxiesEnabled())) {
157                 result.add(proxyData);
158             }
159         }
160         return (IProxyData[]) result.toArray(new IProxyData[result.size()]);
161     }
162
163     private ProxyType getType(IProxyData proxyData) {
164         for (int i = 0; i < proxies.length; i++) {
165             ProxyType type = proxies[i];
166             if (type.getName().equals(proxyData.getType())) {
167                 return type;
168             }
169         }
170         return null;
171     }
172
173     /* (non-Javadoc)
174      * @see org.eclipse.core.net.IProxyManager#isProxiesEnabled()
175      */

176     public boolean isProxiesEnabled() {
177         return Activator.getInstance().getInstancePreferences().getBoolean(PREF_ENABLED, false);
178     }
179
180     /* (non-Javadoc)
181      * @see org.eclipse.core.net.IProxyManager#setProxiesEnabled(boolean)
182      */

183     public void setProxiesEnabled(boolean enabled) {
184         boolean current = isProxiesEnabled();
185         if (current == enabled)
186             return;
187         // Setting the preference will trigger the system property update
188
// (see preferenceChange)
189
Activator.getInstance().getInstancePreferences().putBoolean(PREF_ENABLED, enabled);
190     }
191
192     private void internalSetEnabled(boolean enabled) {
193         Properties sysProps = System.getProperties();
194         sysProps.put("proxySet", enabled ? "true" : "false"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
195
updateSystemProperties();
196         try {
197             Activator.getInstance().getInstancePreferences().flush();
198         } catch (BackingStoreException e) {
199             Activator.logError(
200                     "An error occurred while writing out the enablement state", e); //$NON-NLS-1$
201
}
202         String JavaDoc[] hosts = getNonProxiedHosts();
203         IProxyData[] data = getProxyData();
204         IProxyChangeEvent event = new ProxyChangeEvent(IProxyChangeEvent.PROXY_DATA_CHANGED, hosts, hosts, data, data);
205         fireChange(event);
206     }
207
208     private void updateSystemProperties() {
209         for (int i = 0; i < proxies.length; i++) {
210             ProxyType type = proxies[i];
211             type.updateSystemProperties(internalGetProxyData(type.getName(), ProxyType.DO_NOT_VERIFY), isProxiesEnabled());
212         }
213     }
214
215     public void initialize() {
216         // First see if there is an http proxy to migrate
217
migrateUpdateHttpProxy(new InstanceScope().getNode(""), true); //$NON-NLS-1$
218
((IEclipsePreferences)Activator.getInstance().getInstancePreferences()).addPreferenceChangeListener(this);
219         // Now initialize each proxy type
220
for (int i = 0; i < proxies.length; i++) {
221             ProxyType type = proxies[i];
222             type.initialize(isProxiesEnabled());
223         }
224         registerAuthenticator();
225     }
226
227     public IProxyData getProxyData(String JavaDoc type) {
228         return internalGetProxyData(type, ProxyType.VERIFY_EQUAL);
229     }
230
231     private IProxyData internalGetProxyData(String JavaDoc type, int verifySystemProperties) {
232         for (int i = 0; i < proxies.length; i++) {
233             ProxyType pt = proxies[i];
234             if (pt.getName().equals(type)) {
235                 return pt.getProxyData(verifySystemProperties);
236             }
237         }
238         return null;
239     }
240
241     public IProxyData[] getProxyDataForHost(String JavaDoc host) {
242         if (isHostFiltered(host))
243             return new IProxyData[0];
244         IProxyData[] data = getProxyData();
245         List result = new ArrayList();
246         for (int i = 0; i < data.length; i++) {
247             IProxyData proxyData = data[i];
248             if (proxyData.getHost() != null)
249                 result.add(proxyData);
250         }
251         return (IProxyData[]) result.toArray(new IProxyData[result.size()]);
252     }
253
254     private boolean isHostFiltered(String JavaDoc host) {
255         String JavaDoc[] filters = getNonProxiedHosts();
256         for (int i = 0; i < filters.length; i++) {
257             String JavaDoc filter = filters[i];
258             if (matchesFilter(host, filter))
259                 return true;
260         }
261         return false;
262     }
263
264     private boolean matchesFilter(String JavaDoc host, String JavaDoc filter) {
265         StringMatcher matcher = new StringMatcher(filter, false, false);
266         return matcher.match(host);
267     }
268
269     /* (non-Javadoc)
270      * @see org.eclipse.net.core.IProxyManager#getProxyDataForHost(java.lang.String, java.lang.String)
271      */

272     public IProxyData getProxyDataForHost(String JavaDoc host, String JavaDoc type) {
273         IProxyData[] data = getProxyDataForHost(host);
274         for (int i = 0; i < data.length; i++) {
275             IProxyData proxyData = data[i];
276             if (proxyData.getType().equals(type) && proxyData.getHost() != null)
277                 return proxyData;
278         }
279         return null;
280     }
281     
282     private void registerAuthenticator() {
283         Authenticator JavaDoc a = getPluggedInAuthenticator();
284         if (a != null) {
285             Authenticator.setDefault(a);
286         }
287     }
288     
289     private Authenticator JavaDoc getPluggedInAuthenticator() {
290         IExtension[] extensions = Platform.getExtensionRegistry().getExtensionPoint(Activator.ID, Activator.PT_AUTHENTICATOR).getExtensions();
291         if (extensions.length == 0)
292             return null;
293         IExtension extension = extensions[0];
294         IConfigurationElement[] configs = extension.getConfigurationElements();
295         if (configs.length == 0) {
296             Activator.log(IStatus.ERROR, NLS.bind("Authenticator {0} is missing required fields", (new Object JavaDoc[] {extension.getUniqueIdentifier()})), null);//$NON-NLS-1$
297
return null;
298         }
299         try {
300             IConfigurationElement config = configs[0];
301             return (Authenticator JavaDoc) config.createExecutableExtension("class");//$NON-NLS-1$
302
} catch (CoreException ex) {
303             Activator.log(IStatus.ERROR, NLS.bind("Unable to instantiate authenticator {0}", (new Object JavaDoc[] {extension.getUniqueIdentifier()})), ex);//$NON-NLS-1$
304
return null;
305         }
306     }
307     
308     void migrateUpdateHttpProxy(Preferences node, boolean isInitialize) {
309         Preferences netPrefs = node.node(Activator.ID);
310         if (!netPrefs.getBoolean(PREF_HAS_MIGRATED, false)) {
311             // Only set the migration bit when initializing
312
if (isInitialize)
313                 netPrefs.putBoolean(PREF_HAS_MIGRATED, true);
314             Preferences updatePrefs = node.node("org.eclipse.update.core"); //$NON-NLS-1$
315
String JavaDoc httpProxyHost = getHostToMigrate(updatePrefs, isInitialize /* checkSystemProperties */);
316             int port = getPortToMigrate(updatePrefs, isInitialize /* checkSystemProperties */);
317             boolean httpProxyEnable = getEnablementToMigrate(updatePrefs, isInitialize /* checkSystemProperties */);
318             if (httpProxyHost != null) {
319                 ProxyData proxyData = new ProxyData(IProxyData.HTTP_PROXY_TYPE, httpProxyHost, port, false);
320                 ProxyType type = getType(proxyData);
321                 type.updatePreferencesIfMissing(netPrefs, proxyData);
322                 if (httpProxyEnable) {
323                     netPrefs.putBoolean(ProxyManager.PREF_ENABLED, true);
324                 }
325             }
326         }
327     }
328
329     private boolean getEnablementToMigrate(Preferences updatePrefs, boolean checkSystemProperties) {
330         boolean httpProxyEnable = false;
331         if (checkSystemProperties && updatePrefs.get(HTTP_PROXY_ENABLE, null) == null) {
332             httpProxyEnable = Boolean.getBoolean("http.proxySet"); //$NON-NLS-1$
333
} else {
334             httpProxyEnable = updatePrefs.getBoolean(HTTP_PROXY_ENABLE, false);
335             updatePrefs.remove(HTTP_PROXY_ENABLE);
336         }
337         return httpProxyEnable;
338     }
339
340     private int getPortToMigrate(Preferences updatePrefs, boolean checkSystemProperties) {
341         String JavaDoc httpProxyPort = updatePrefs.get(HTTP_PROXY_PORT, ""); //$NON-NLS-1$
342
if (checkSystemProperties && "".equals(httpProxyPort)) { //$NON-NLS-1$
343
httpProxyPort = System.getProperty("http.proxyPort", ""); //$NON-NLS-1$ //$NON-NLS-2$
344
}
345         updatePrefs.remove(HTTP_PROXY_PORT);
346         int port = -1;
347         if (httpProxyPort != null && !"".equals(httpProxyPort)) //$NON-NLS-1$
348
try {
349                 port = Integer.parseInt(httpProxyPort);
350             } catch (NumberFormatException JavaDoc e) {
351                 // Ignore
352
}
353         return port;
354     }
355
356     private String JavaDoc getHostToMigrate(Preferences updatePrefs, boolean checkSystemProperties) {
357         String JavaDoc httpProxyHost = updatePrefs.get(HTTP_PROXY_HOST, ""); //$NON-NLS-1$
358
if (checkSystemProperties && "".equals(httpProxyHost)) { //$NON-NLS-1$
359
httpProxyHost = System.getProperty("http.proxyHost", ""); //$NON-NLS-1$ //$NON-NLS-2$
360
}
361         if ("".equals(httpProxyHost)) //$NON-NLS-1$
362
httpProxyHost = null;
363         updatePrefs.remove(HTTP_PROXY_HOST);
364         return httpProxyHost;
365     }
366
367     public void preferenceChange(PreferenceChangeEvent event) {
368         if (event.getKey().equals(PREF_ENABLED)) {
369             internalSetEnabled(Activator.getInstance().getInstancePreferences().getBoolean(PREF_ENABLED, false));
370         }
371     }
372
373 }
374
Popular Tags