1 11 package org.eclipse.osgi.framework.internal.core; 12 13 import java.io.*; 14 import java.lang.reflect.*; 15 import java.net.*; 16 import java.security.*; 17 import java.util.*; 18 import org.eclipse.core.runtime.internal.adaptor.ContextFinder; 19 import org.eclipse.osgi.framework.adaptor.*; 20 import org.eclipse.osgi.framework.debug.Debug; 21 import org.eclipse.osgi.framework.eventmgr.*; 22 import org.eclipse.osgi.framework.internal.protocol.ContentHandlerFactory; 23 import org.eclipse.osgi.framework.internal.protocol.StreamHandlerFactory; 24 import org.eclipse.osgi.framework.log.FrameworkLog; 25 import org.eclipse.osgi.framework.log.FrameworkLogEntry; 26 import org.eclipse.osgi.framework.util.SecureAction; 27 import org.eclipse.osgi.internal.profile.Profile; 28 import org.eclipse.osgi.util.ManifestElement; 29 import org.eclipse.osgi.util.NLS; 30 import org.osgi.framework.*; 31 32 35 public class Framework implements EventDispatcher, EventPublisher { 36 private static final String PROP_CONTEXTCLASSLOADER_PARENT = "osgi.contextClassLoaderParent"; private static final String CONTEXTCLASSLOADER_PARENT_APP = "app"; private static final String CONTEXTCLASSLOADER_PARENT_EXT = "ext"; private static final String CONTEXTCLASSLOADER_PARENT_BOOT = "boot"; private static final String CONTEXTCLASSLOADER_PARENT_FWK = "fwk"; 43 private static String J2SE = "J2SE-"; private static String JAVASE = "JavaSE-"; private static String PROFILE_EXT = ".profile"; 47 protected FrameworkAdaptor adaptor; 48 52 protected Properties properties; 53 54 protected boolean active; 55 56 protected BundleRepository bundles; 57 58 protected PackageAdminImpl packageAdmin; 59 60 protected PermissionAdminImpl permissionAdmin; 61 65 protected StartLevelManager startLevelManager; 66 67 protected ServiceRegistry serviceRegistry; 69 protected long serviceid; 70 71 78 79 protected EventListeners bundleEvent; 80 protected static final int BUNDLEEVENT = 1; 81 82 protected EventListeners bundleEventSync; 83 protected static final int BUNDLEEVENTSYNC = 2; 84 85 protected EventListeners serviceEvent; 86 protected static final int SERVICEEVENT = 3; 87 88 protected EventListeners frameworkEvent; 89 protected static final int FRAMEWORKEVENT = 4; 90 protected static final int BATCHEVENT_BEGIN = Integer.MIN_VALUE + 1; 91 protected static final int BATCHEVENT_END = Integer.MIN_VALUE; 92 93 protected EventManager eventManager; 94 95 protected Hashtable installLock; 96 97 protected SystemBundle systemBundle; 98 String [] bootDelegation; 99 String [] bootDelegationStems; 100 boolean bootDelegateAll = false; 101 boolean contextBootDelegation = "true".equals(FrameworkProperties.getProperty("osgi.context.bootdelegation", "true")); boolean compatibiltyBootDelegation = false; 103 104 107 protected static AliasMapper aliasMapper = new AliasMapper(); 108 protected ConditionalPermissionAdminImpl condPermAdmin; 109 SecureAction secureAction = (SecureAction) AccessController.doPrivileged(SecureAction.createSecureAction()); 110 private HashMap adminPermissions = new HashMap(); 112 113 private StreamHandlerFactory streamHandlerFactory; 115 private ContentHandlerFactory contentHandlerFactory; 116 117 121 static { 122 Class c; 123 c = GetDataFileAction.class; 124 c.getName(); } 126 127 static class GetDataFileAction implements PrivilegedAction { 128 private AbstractBundle bundle; 129 private String filename; 130 131 public GetDataFileAction(AbstractBundle bundle, String filename) { 132 this.bundle = bundle; 133 this.filename= filename; 134 } 135 136 public Object run() { 137 return bundle.getBundleData().getDataFile(filename); 138 } 139 } 140 141 146 public Framework(FrameworkAdaptor adaptor) { 147 initialize(adaptor); 148 } 149 150 155 protected void initialize(FrameworkAdaptor adaptor) { 156 if (Profile.PROFILE && Profile.STARTUP) 157 Profile.logEnter("Framework.initialze()", null); long start = System.currentTimeMillis(); 159 this.adaptor = adaptor; 160 active = false; 161 installSecurityManager(); 162 if (Debug.DEBUG && Debug.DEBUG_SECURITY) { 163 Debug.println("SecurityManager: " + System.getSecurityManager()); Debug.println("ProtectionDomain of Framework.class: \n" + this.getClass().getProtectionDomain()); } 166 setNLSFrameworkLog(); 167 initializeContextFinder(); 169 170 adaptor.initialize(this); 171 if (Profile.PROFILE && Profile.STARTUP) 172 Profile.logTime("Framework.initialze()", "adapter initialized"); try { 174 adaptor.initializeStorage(); 175 } catch (IOException e) { 176 e.printStackTrace(); 177 throw new RuntimeException (e.getMessage()); 178 } 179 if (Profile.PROFILE && Profile.STARTUP) 180 Profile.logTime("Framework.initialze()", "adapter storage initialized"); 185 initializeProperties(adaptor.getProperties()); 186 187 packageAdmin = new PackageAdminImpl(this); 188 SecurityManager sm = System.getSecurityManager(); 189 if (sm != null) { 190 try { 191 permissionAdmin = new PermissionAdminImpl(this, adaptor.getPermissionStorage()); 192 } catch (IOException e) { 193 e.printStackTrace(); 194 throw new RuntimeException (e.getMessage()); 195 } 196 try { 197 condPermAdmin = new ConditionalPermissionAdminImpl(this, adaptor.getPermissionStorage()); 198 } catch (IOException e) { 199 e.printStackTrace(); 200 throw new RuntimeException (e.getMessage()); 201 } 202 } 203 if (Profile.PROFILE && Profile.STARTUP) 204 Profile.logTime("Framework.initialze()", "done init props & new PermissionAdminImpl"); startLevelManager = new StartLevelManager(this); 206 207 eventManager = new EventManager("Framework Event Dispatcher"); bundleEvent = new EventListeners(); 209 bundleEventSync = new EventListeners(); 210 serviceEvent = new EventListeners(); 211 frameworkEvent = new EventListeners(); 212 if (Profile.PROFILE && Profile.STARTUP) 213 Profile.logTime("Framework.initialze()", "done new EventManager"); 215 serviceid = 1; 216 serviceRegistry = adaptor.getServiceRegistry(); 217 installLock = new Hashtable(10); 221 222 createSystemBundle(); 223 loadVMProfile(); setBootDelegation(); if (Profile.PROFILE && Profile.STARTUP) 226 Profile.logTime("Framework.initialze()", "done createSystemBundle"); 228 installURLStreamHandlerFactory(systemBundle.context, adaptor); 229 230 installContentHandlerFactory(systemBundle.context, adaptor); 231 if (Profile.PROFILE && Profile.STARTUP) 232 Profile.logTime("Framework.initialze()", "done new URLStream/Content HandlerFactory"); 234 BundleData[] bundleDatas = adaptor.getInstalledBundles(); 235 bundles = new BundleRepository(bundleDatas == null ? 10 : bundleDatas.length + 1); 236 237 bundles.add(systemBundle); 238 if (bundleDatas != null) { 239 for (int i = 0; i < bundleDatas.length; i++) { 240 try { 241 AbstractBundle bundle = AbstractBundle.createBundle(bundleDatas[i], this); 242 bundles.add(bundle); 243 } catch (BundleException be) { 244 publishFrameworkEvent(FrameworkEvent.ERROR, systemBundle, be); 246 } 247 } 248 } 249 if (Debug.DEBUG && Debug.DEBUG_GENERAL) 250 System.out.println("Initialize the framework: " + (System.currentTimeMillis() - start)); if (Profile.PROFILE && Profile.STARTUP) 252 Profile.logExit("Framework.initialize()"); } 254 255 private void setNLSFrameworkLog() { 256 try { 257 Field frameworkLogField = NLS.class.getDeclaredField("frameworkLog"); frameworkLogField.setAccessible(true); 259 frameworkLogField.set(null, adaptor.getFrameworkLog()); 260 } catch (Exception e) { 261 adaptor.getFrameworkLog().log(new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, FrameworkLogEntry.ERROR, 0, e.getMessage(), 0, e, null)); 262 } 263 } 264 265 private void createSystemBundle() { 266 try { 267 systemBundle = new SystemBundle(this); 268 } catch (BundleException e) { e.printStackTrace(); 270 throw new RuntimeException (NLS.bind(Msg.OSGI_SYSTEMBUNDLE_CREATE_EXCEPTION, e.getMessage())); 271 } 272 } 273 274 279 protected void initializeProperties(Properties adaptorProperties) { 280 properties = FrameworkProperties.getProperties(); 281 Enumeration enumKeys = adaptorProperties.propertyNames(); 282 while (enumKeys.hasMoreElements()) { 283 String key = (String ) enumKeys.nextElement(); 284 if (properties.getProperty(key) == null) { 285 properties.put(key, adaptorProperties.getProperty(key)); 286 } 287 } 288 properties.put(Constants.FRAMEWORK_VENDOR, Constants.OSGI_FRAMEWORK_VENDOR); 289 properties.put(Constants.FRAMEWORK_VERSION, Constants.OSGI_FRAMEWORK_VERSION); 290 String value = properties.getProperty(Constants.FRAMEWORK_PROCESSOR); 291 if (value == null) { 292 value = properties.getProperty(Constants.JVM_OS_ARCH); 293 if (value != null) { 294 properties.put(Constants.FRAMEWORK_PROCESSOR, value); 295 } 296 } 297 value = properties.getProperty(Constants.FRAMEWORK_OS_NAME); 298 if (value == null) { 299 value = properties.getProperty(Constants.JVM_OS_NAME); 300 try { 301 String canonicalValue = (String ) aliasMapper.aliasOSName(value); 302 if (canonicalValue != null) { 303 value = canonicalValue; 304 } 305 } catch (ClassCastException ex) { 306 } 310 if (value != null) { 311 properties.put(Constants.FRAMEWORK_OS_NAME, value); 312 } 313 } 314 value = properties.getProperty(Constants.FRAMEWORK_OS_VERSION); 315 if (value == null) { 316 value = properties.getProperty(Constants.JVM_OS_VERSION); 317 if (value != null) { 318 int space = value.indexOf(' '); 319 if (space > 0) { 320 value = value.substring(0, space); 321 } 322 properties.put(Constants.FRAMEWORK_OS_VERSION, value); 323 } 324 } 325 value = properties.getProperty(Constants.FRAMEWORK_LANGUAGE); 326 if (value == null) 327 properties.put(Constants.FRAMEWORK_LANGUAGE, Locale.getDefault().getLanguage()); 329 properties.put(Constants.SUPPORTS_FRAMEWORK_FRAGMENT, "true"); 331 properties.put(Constants.SUPPORTS_FRAMEWORK_REQUIREBUNDLE, "true"); 332 } 333 334 private void setBootDelegation() { 335 compatibiltyBootDelegation = "true".equals(FrameworkProperties.getProperty(Constants.OSGI_COMPATIBILITY_BOOTDELEGATION)); String bootDelegationProp = properties.getProperty(Constants.OSGI_BOOTDELEGATION); 339 if (bootDelegationProp == null) 340 return; 341 if (bootDelegationProp.trim().length() == 0) 342 return; 343 String [] bootPackages = ManifestElement.getArrayFromList(bootDelegationProp); 344 ArrayList exactMatch = new ArrayList(bootPackages.length); 345 ArrayList stemMatch = new ArrayList(bootPackages.length); 346 for (int i = 0; i < bootPackages.length; i++) { 347 if (bootPackages[i].equals("*")) { bootDelegateAll = true; 349 return; 350 } else if (bootPackages[i].endsWith("*")) { if (bootPackages[i].length() > 2 && bootPackages[i].endsWith(".*")) stemMatch.add(bootPackages[i].substring(0, bootPackages[i].length() - 1)); 353 } else { 354 exactMatch.add(bootPackages[i]); 355 } 356 } 357 if (exactMatch.size() > 0) 358 bootDelegation = (String []) exactMatch.toArray(new String [exactMatch.size()]); 359 if (stemMatch.size() > 0) 360 bootDelegationStems = (String []) stemMatch.toArray(new String [stemMatch.size()]); 361 } 362 363 private void loadVMProfile() { 364 Properties profileProps = findVMProfile(); 365 String systemExports = properties.getProperty(Constants.OSGI_FRAMEWORK_SYSTEM_PACKAGES); 366 if (systemExports == null) { 368 systemExports = profileProps.getProperty(Constants.OSGI_FRAMEWORK_SYSTEM_PACKAGES); 369 if (systemExports != null) 370 properties.put(Constants.OSGI_FRAMEWORK_SYSTEM_PACKAGES, systemExports); 371 } 372 String type = properties.getProperty(Constants.OSGI_JAVA_PROFILE_BOOTDELEGATION); String profileBootDelegation = profileProps.getProperty(Constants.OSGI_BOOTDELEGATION); 375 if (Constants.OSGI_BOOTDELEGATION_OVERRIDE.equals(type)) { 376 if (profileBootDelegation == null) 377 properties.remove(Constants.OSGI_BOOTDELEGATION); else 379 properties.put(Constants.OSGI_BOOTDELEGATION, profileBootDelegation); } else if (Constants.OSGI_BOOTDELEGATION_NONE.equals(type)) 381 properties.remove(Constants.OSGI_BOOTDELEGATION); if (properties.getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT) == null) { 384 String ee = profileProps.getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT, profileProps.getProperty(Constants.OSGI_JAVA_PROFILE_NAME)); 386 if (ee != null) 387 properties.put(Constants.FRAMEWORK_EXECUTIONENVIRONMENT, ee); 388 } 389 } 390 391 private Properties findVMProfile() { 392 Properties result = new Properties(); 393 String j2meConfig = properties.getProperty(Constants.J2ME_MICROEDITION_CONFIGURATION); 395 String j2meProfiles = properties.getProperty(Constants.J2ME_MICROEDITION_PROFILES); 396 String vmProfile = null; 397 String javaEdition = null; 398 Version javaVersion = null; 399 if (j2meConfig != null && j2meConfig.length() > 0 && j2meProfiles != null && j2meProfiles.length() > 0) { 400 String [] j2meProfileList = ManifestElement.getArrayFromList(j2meProfiles, " "); if (j2meProfileList != null && j2meProfileList.length > 0) 404 vmProfile = j2meConfig + '_' + j2meProfileList[j2meProfileList.length - 1]; 405 } else { 406 String javaSpecVersion = properties.getProperty("java.specification.version"); if (javaSpecVersion != null) { 414 StringTokenizer st = new StringTokenizer(javaSpecVersion, " _-"); javaSpecVersion = st.nextToken(); 416 String javaSpecName = properties.getProperty("java.specification.name"); if ("J2ME Foundation Specification".equals(javaSpecName)) vmProfile = "CDC-" + javaSpecVersion + "_Foundation-" + javaSpecVersion; else { 420 Version v16 = new Version("1.6"); javaEdition = J2SE; 423 try { 424 javaVersion = new Version(javaSpecVersion); 425 if (v16.compareTo(javaVersion) <= 0) 426 javaEdition = JAVASE; 427 } catch (IllegalArgumentException e) { 428 } 430 vmProfile = javaEdition + javaSpecVersion; 431 } 432 } 433 } 434 URL url = null; 435 String propJavaProfile = FrameworkProperties.getProperty(Constants.OSGI_JAVA_PROFILE); 437 if (propJavaProfile != null) 438 try { 439 url = new URL(propJavaProfile); 441 } catch (MalformedURLException e1) { 442 url = findInSystemBundle(propJavaProfile); 444 } 445 if (url == null && vmProfile != null) { 446 String javaProfile = vmProfile + PROFILE_EXT; 448 url = findInSystemBundle(javaProfile); 449 if (url == null) 450 url = getNextBestProfile(javaEdition, javaVersion); 451 } 452 if (url == null) 453 url = findInSystemBundle("OSGi_Minimum-1.1.profile"); if (url != null) { 456 InputStream in = null; 457 try { 458 in = url.openStream(); 459 result.load(new BufferedInputStream(in)); 460 } catch (IOException e) { 461 } finally { 463 if (in != null) 464 try { 465 in.close(); 466 } catch (IOException ee) { 467 } 469 } 470 } 471 if (result.getProperty(Constants.OSGI_JAVA_PROFILE_NAME) == null) 473 if (vmProfile != null) 474 result.put(Constants.OSGI_JAVA_PROFILE_NAME, vmProfile.replace('_', '/')); 475 else 476 result.put(Constants.OSGI_JAVA_PROFILE_NAME, "OSGi/Minimum-1.1"); return result; 479 } 480 481 private URL getNextBestProfile(String javaEdition, Version javaVersion) { 482 if (javaVersion == null || (javaEdition != J2SE && javaEdition != JAVASE)) 483 return null; URL bestProfile = findNextBestProfile(javaEdition, javaVersion); 485 if (bestProfile == null && javaEdition == JAVASE) 486 bestProfile = findNextBestProfile(J2SE, javaVersion); 488 return bestProfile; 489 } 490 491 private URL findNextBestProfile(String javaEdition, Version javaVersion) { 492 URL result = null; 493 int minor = javaVersion.getMinor(); 494 do { 495 result = findInSystemBundle(javaEdition + javaVersion.getMajor() + "." + minor + PROFILE_EXT); minor = minor - 1; 497 } while (result == null && minor > 0); 498 return result; 499 } 500 501 private URL findInSystemBundle(String entry) { 502 URL result = systemBundle.getEntry(entry); 503 if (result == null) { 504 ClassLoader loader=getClass().getClassLoader(); 506 result = loader==null ? ClassLoader.getSystemResource(entry) : loader.getResource(entry); 507 } 508 return result; 509 } 510 511 515 protected boolean isActive() { 516 return (active); 517 } 518 519 523 public synchronized void close() { 524 if (active) { 525 shutdown(); 526 } 527 synchronized (bundles) { 528 List allBundles = bundles.getBundles(); 529 int size = allBundles.size(); 530 for (int i = 0; i < size; i++) { 531 AbstractBundle bundle = (AbstractBundle) allBundles.get(i); 532 bundle.close(); 533 } 534 bundles.removeAllBundles(); 535 } 536 serviceRegistry = null; 537 if (bundleEvent != null) { 538 bundleEvent.removeAllListeners(); 539 bundleEvent = null; 540 } 541 if (bundleEventSync != null) { 542 bundleEventSync.removeAllListeners(); 543 bundleEventSync = null; 544 } 545 if (serviceEvent != null) { 546 serviceEvent.removeAllListeners(); 547 serviceEvent = null; 548 } 549 if (frameworkEvent != null) { 550 frameworkEvent.removeAllListeners(); 551 frameworkEvent = null; 552 } 553 if (eventManager != null) { 554 eventManager.close(); 555 eventManager = null; 556 } 557 permissionAdmin = null; 558 condPermAdmin = null; 559 packageAdmin = null; 560 adaptor = null; 561 uninstallURLStreamHandlerFactory(); 562 uninstallContentHandlerFactory(); 563 } 564 565 577 public synchronized void launch() { 578 579 if (active) { 580 return; 581 } 582 583 active = true; 584 585 if (Debug.DEBUG && Debug.DEBUG_GENERAL) { 586 Debug.println("Trying to launch framework"); } 588 systemBundle.resume(); 589 } 590 591 601 public synchronized void shutdown() { 602 603 if (!active) { 604 return; 605 } 606 610 systemBundle.state = AbstractBundle.STOPPING; 611 publishBundleEvent(BundleEvent.STOPPING, systemBundle); 613 try { 614 adaptor.frameworkStopping(systemBundle.getContext()); 615 } catch (Throwable t) { 616 publishFrameworkEvent(FrameworkEvent.ERROR, systemBundle, t); 617 } 618 619 if (Debug.DEBUG && Debug.DEBUG_GENERAL) { 620 Debug.println("Trying to shutdown Framework"); } 622 systemBundle.suspend(); 623 try { 624 adaptor.compactStorage(); 625 } catch (IOException e) { 626 publishFrameworkEvent(FrameworkEvent.ERROR, systemBundle, e); 627 } 628 629 active = false; 630 } 631 632 637 AbstractBundle createAndVerifyBundle(BundleData bundledata) throws BundleException { 638 if (bundledata.getSymbolicName() != null) { 640 AbstractBundle installedBundle = getBundleBySymbolicName(bundledata.getSymbolicName(), bundledata.getVersion()); 641 if (installedBundle != null && installedBundle.getBundleId() != bundledata.getBundleID()) { 642 throw new BundleException(NLS.bind(Msg.BUNDLE_INSTALL_SAME_UNIQUEID, new Object [] {installedBundle.getSymbolicName(), installedBundle.getVersion().toString(), installedBundle.getLocation()})); 643 } 644 } 645 verifyExecutionEnvironment(bundledata.getManifest()); 646 return AbstractBundle.createBundle(bundledata, this); 647 } 648 649 661 protected boolean verifyExecutionEnvironment(Dictionary manifest) throws BundleException { 662 if (!Boolean.valueOf(FrameworkProperties.getProperty(Constants.ECLIPSE_EE_INSTALL_VERIFY, Boolean.TRUE.toString())).booleanValue()) return true; 664 String headerValue = (String ) manifest.get(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT); 665 666 if (headerValue == null) { 667 return true; 668 } 669 ManifestElement[] bundleRequiredEE = ManifestElement.parseHeader(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT, headerValue); 670 if (bundleRequiredEE.length == 0) { 671 return true; 672 } 673 String systemEE = FrameworkProperties.getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT); 674 if (systemEE != null && !systemEE.equals("")) { ManifestElement[] systemEEs = ManifestElement.parseHeader(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT, systemEE); 676 for (int i = 0; i < systemEEs.length; i++) { 677 for (int j = 0; j < bundleRequiredEE.length; j++) { 678 if (systemEEs[i].getValue().equals(bundleRequiredEE[j].getValue())) { 679 return true; 680 } 681 } 682 } 683 } 684 685 StringBuffer bundleEE = new StringBuffer (25); 686 for (int i = 0; i < bundleRequiredEE.length; i++) { 687 if (i > 0) { 688 bundleEE.append(","); } 690 bundleEE.append(bundleRequiredEE[i].getValue()); 691 } 692 throw new BundleException(NLS.bind(Msg.BUNDLE_INSTALL_REQUIRED_EE_EXCEPTION, bundleEE.toString())); 693 } 694 695 722 public String getProperty(String key) { 723 return properties.getProperty(key); 724 } 725 726 755 protected String getProperty(String key, String def) { 756 return properties.getProperty(key, def); 757 } 758 759 769 protected Object setProperty(String key, String value) { 770 return properties.put(key, value); 771 } 772 773 784 public AbstractBundle installBundle(final String location) throws BundleException { 785 if (Debug.DEBUG && Debug.DEBUG_GENERAL) { 786 Debug.println("install from location: " + location); } 788 final AccessControlContext callerContext = AccessController.getContext(); 789 return installWorker(location, new PrivilegedExceptionAction() { 790 public Object run() throws BundleException { 791 792 URLConnection source = adaptor.mapLocationToURLConnection(location); 793 794 return installWorkerPrivileged(location, source, callerContext); 795 } 796 }); 797 } 798 799 814 protected AbstractBundle installBundle(final String location, final InputStream in) throws BundleException { 815 if (Debug.DEBUG && Debug.DEBUG_GENERAL) { 816 Debug.println("install from inputstream: " + location + ", " + in); } 818 final AccessControlContext callerContext = AccessController.getContext(); 819 return installWorker(location, new PrivilegedExceptionAction() { 820 public Object run() throws BundleException { 821 822 URLConnection source = new BundleSource(in); 823 824 return installWorkerPrivileged(location, source, callerContext); 825 } 826 }); 827 } 828 829 841 protected AbstractBundle installWorker(String location, PrivilegedExceptionAction action) throws BundleException { 842 synchronized (installLock) { 843 while (true) { 844 845 AbstractBundle bundle = getBundleByLocation(location); 846 847 if (bundle != null) { 848 return bundle; 849 } 850 Thread current = Thread.currentThread(); 851 852 Thread reservation = (Thread ) installLock.put(location, current); 853 854 if (reservation == null) { 855 856 break; 857 } 858 859 863 if (current.equals(reservation)) { 864 throw new BundleException(Msg.BUNDLE_INSTALL_RECURSION_EXCEPTION); 865 } 866 try { 867 868 installLock.wait(); 869 } catch (InterruptedException e) { 870 } 871 } 872 } 873 874 try { 875 AbstractBundle bundle = (AbstractBundle) AccessController.doPrivileged(action); 876 publishBundleEvent(BundleEvent.INSTALLED, bundle); 877 return bundle; 878 } catch (PrivilegedActionException e) { 879 if (e.getException() instanceof RuntimeException ) 880 throw (RuntimeException ) e.getException(); 881 throw (BundleException) e.getException(); 882 } finally { 883 synchronized (installLock) { 884 885 installLock.remove(location); 886 887 installLock.notifyAll(); 888 } 889 } 890 } 891 892 904 protected AbstractBundle installWorkerPrivileged(String location, URLConnection source, AccessControlContext callerContext) throws BundleException { 905 BundleOperation storage = adaptor.installBundle(location, source); 906 final AbstractBundle bundle; 907 try { 908 BundleData bundledata = storage.begin(); 909 bundle = createAndVerifyBundle(bundledata); 910 if (Debug.DEBUG) { 911 BundleWatcher bundleStats = adaptor.getBundleWatcher(); 912 if (bundleStats != null) 913 bundleStats.watchBundle(bundle, BundleWatcher.START_INSTALLING); 914 } 915 try { 916 String [] nativepaths = selectNativeCode(bundle); 921 if (nativepaths != null) { 922 bundledata.installNativeCode(nativepaths); 923 } 924 bundle.load(); 925 if (System.getSecurityManager() != null) { 926 final boolean extension = (bundledata.getType() & (BundleData.TYPE_BOOTCLASSPATH_EXTENSION | BundleData.TYPE_FRAMEWORK_EXTENSION)) != 0; 927 if (extension && !bundle.hasPermission(new AllPermission())) 929 throw new BundleException(Msg.BUNDLE_EXTENSION_PERMISSION, new SecurityException (Msg.BUNDLE_EXTENSION_PERMISSION)); 930 try { 931 AccessController.doPrivileged(new PrivilegedExceptionAction() { 932 public Object run() throws Exception { 933 checkAdminPermission(bundle, AdminPermission.LIFECYCLE); 934 if (extension) checkAdminPermission(bundle, AdminPermission.EXTENSIONLIFECYCLE); 936 return null; 937 } 938 }, callerContext); 939 } catch (PrivilegedActionException e) { 940 throw e.getException(); 941 } 942 } 943 storage.commit(false); 944 } catch (Throwable error) { 945 synchronized (bundles) { 946 bundle.unload(); 947 } 948 bundle.close(); 949 throw error; 950 } finally { 951 if (Debug.DEBUG) { 952 BundleWatcher bundleStats = adaptor.getBundleWatcher(); 953 if (bundleStats != null) 954 bundleStats.watchBundle(bundle, BundleWatcher.END_INSTALLING); 955 } 956 } 957 958 bundles.add(bundle); 959 } catch (Throwable t) { 960 try { 961 storage.undo(); 962 } catch (BundleException ee) { 963 publishFrameworkEvent(FrameworkEvent.ERROR, systemBundle, ee); 964 } 965 if (t instanceof SecurityException ) 966 throw (SecurityException ) t; 967 if (t instanceof BundleException) 968 throw (BundleException) t; 969 throw new BundleException(t.getMessage(), t); 970 } 971 return bundle; 972 } 973 974 985 String [] selectNativeCode(org.osgi.framework.Bundle bundle) throws BundleException { 986 String headerValue = (String ) ((AbstractBundle) bundle).getBundleData().getManifest().get(Constants.BUNDLE_NATIVECODE); 987 if (headerValue == null) { 988 return (null); 989 } 990 ManifestElement[] elements = ManifestElement.parseHeader(Constants.BUNDLE_NATIVECODE, headerValue); 991 ArrayList bundleNativeCodes = new ArrayList(elements.length); 992 int length = elements.length; 993 boolean optional = false; 994 if (elements[length - 1].getValue().equals("*")) { optional = true; 996 length--; 997 } 998 String processor = getProperty(Constants.FRAMEWORK_PROCESSOR); 999 String osname = getProperty(Constants.FRAMEWORK_OS_NAME); 1000 Version osversion; 1001 try { 1002 osversion = Version.parseVersion(getProperty(Constants.FRAMEWORK_OS_VERSION)); 1003 } catch (Exception e) { 1004 osversion = Version.emptyVersion; 1005 } 1006 String language = getProperty(Constants.FRAMEWORK_LANGUAGE); 1007 for (int i = 0; i < length; i++) { 1008 BundleNativeCode bnc = new BundleNativeCode(elements[i], (AbstractBundle) bundle); 1009 if (bnc.matchProcessorOSNameFilter(processor, osname) > 0 && bnc.matchOSVersion(osversion) != null && bnc.matchLanguage(language) > 0) 1014 bundleNativeCodes.add(bnc); 1015 } 1016 1017 if (bundleNativeCodes.size() == 0) 1018 return noMatches(optional); 1019 Iterator iter = bundleNativeCodes.iterator(); 1021 BundleNativeCode highestRanking = (BundleNativeCode) iter.next(); 1022 while (iter.hasNext()) { 1023 BundleNativeCode bnc = (BundleNativeCode) iter.next(); 1024 if (isBncGreaterThan(bnc, highestRanking, osversion, language)) 1025 highestRanking = bnc; 1026 } 1027 return highestRanking.getPaths(); 1028 } 1029 1030 private boolean isBncGreaterThan(BundleNativeCode candidate, BundleNativeCode highestRanking, Version version, String language) { 1031 Version currentHigh = highestRanking.matchOSVersion(version); 1032 Version candidateHigh = candidate.matchOSVersion(version); 1033 if (currentHigh.compareTo(candidateHigh) < 0) 1034 return true; 1035 if (highestRanking.matchLanguage(language) < candidate.matchLanguage(language)) 1036 return true; 1037 return false; 1038 } 1039 1040 1048 public AbstractBundle getBundle(long id) { 1050 synchronized (bundles) { 1051 return bundles.getBundle(id); 1052 } 1053 } 1054 1055 1064 public AbstractBundle getBundleBySymbolicName(String symbolicName, Version version) { 1065 synchronized (bundles) { 1066 return bundles.getBundle(symbolicName, version); 1067 } 1068 } 1069 1070 1078 protected BundleRepository getBundles() { 1079 return (bundles); 1080 } 1081 1082 1090 protected AbstractBundle[] getAllBundles() { 1091 synchronized (bundles) { 1092 List allBundles = bundles.getBundles(); 1093 int size = allBundles.size(); 1094 if (size == 0) { 1095 return (null); 1096 } 1097 AbstractBundle[] bundlelist = new AbstractBundle[size]; 1098 allBundles.toArray(bundlelist); 1099 return (bundlelist); 1100 } 1101 } 1102 1103 1109 protected void resumeBundle(AbstractBundle bundle) { 1110 if (bundle.isActive()) { 1111 return; 1113 } 1114 try { 1115 if (Debug.DEBUG && Debug.DEBUG_GENERAL) { 1116 Debug.println("Trying to resume bundle " + bundle); } 1118 bundle.resume(); 1119 } catch (BundleException be) { 1120 if (Debug.DEBUG && Debug.DEBUG_GENERAL) { 1121 Debug.println("Bundle resume exception: " + be.getMessage()); Debug.printStackTrace(be.getNestedException() == null ? be : be.getNestedException()); 1123 } 1124 publishFrameworkEvent(FrameworkEvent.ERROR, bundle, be); 1125 } 1126 } 1127 1128 1138 protected boolean suspendBundle(AbstractBundle bundle, boolean lock) { 1139 boolean changed = false; 1140 if (!bundle.isActive() || bundle.isFragment()) { 1141 return changed; 1143 } 1144 try { 1145 if (Debug.DEBUG && Debug.DEBUG_GENERAL) { 1146 Debug.println("Trying to suspend bundle " + bundle); } 1148 bundle.suspend(lock); 1149 } catch (BundleException be) { 1150 if (Debug.DEBUG && Debug.DEBUG_GENERAL) { 1151 Debug.println("Bundle suspend exception: " + be.getMessage()); Debug.printStackTrace(be.getNestedException() == null ? be : be.getNestedException()); 1153 } 1154 publishFrameworkEvent(FrameworkEvent.ERROR, bundle, be); 1155 } 1156 if (!bundle.isActive()) { 1157 changed = true; 1158 } 1159 return (changed); 1160 } 1161 1162 1170 protected AbstractBundle getBundleByLocation(String location) { 1171 synchronized (bundles) { 1172 final String finalLocation = location; 1175 1176 return (AbstractBundle) AccessController.doPrivileged(new PrivilegedAction() { 1178 public Object run() { 1179 List allBundles = bundles.getBundles(); 1180 int size = allBundles.size(); 1181 for (int i = 0; i < size; i++) { 1182 AbstractBundle bundle = (AbstractBundle) allBundles.get(i); 1183 if (finalLocation.equals(bundle.getLocation())) { 1184 return (bundle); 1185 } 1186 } 1187 return (null); 1188 } 1189 }); 1190 } 1191 } 1192 1193 1201 protected AbstractBundle[] getBundleBySymbolicName(String symbolicName) { 1202 synchronized (bundles) { 1203 return bundles.getBundles(symbolicName); 1204 } 1205 } 1206 1207 1263 protected ServiceReference[] getServiceReferences(String clazz, String filterstring, BundleContextImpl context, boolean allservices) throws InvalidSyntaxException { 1264 FilterImpl filter = (filterstring == null) ? null : new FilterImpl(filterstring); 1265 ServiceReference[] services = null; 1266 if (clazz != null) { 1267 try { 1268 checkGetServicePermission(clazz); 1269 } catch (SecurityException se) { 1270 return (null); 1271 } 1272 } 1273 synchronized (serviceRegistry) { 1274 services = serviceRegistry.lookupServiceReferences(clazz, filter); 1275 if (services == null) { 1276 return null; 1277 } 1278 int removed = 0; 1279 for (int i = services.length - 1; i >= 0; i--) { 1280 ServiceReferenceImpl ref = (ServiceReferenceImpl) services[i]; 1281 String [] classes = ref.getClasses(); 1282 if (allservices || context.isAssignableTo((ServiceReferenceImpl) services[i])) { 1283 if (clazz == null) 1284 try { 1285 checkGetServicePermission(classes); 1286 } catch (SecurityException se) { 1287 services[i] = null; 1288 removed++; 1289 } 1290 } else { 1291 services[i] = null; 1292 removed++; 1293 } 1294 } 1295 if (removed > 0) { 1296 ServiceReference[] temp = services; 1297 services = new ServiceReference[temp.length - removed]; 1298 for (int i = temp.length - 1; i >= 0; i--) { 1299 if (temp[i] == null) 1300 removed--; 1301 else 1302 services[i - removed] = temp[i]; 1303 } 1304 } 1305 1306 } 1307 return services == null || services.length == 0 ? null : services; 1308 } 1309 1310 1316 protected long getNextServiceId() { 1317 long id = serviceid; 1318 serviceid++; 1319 return (id); 1320 } 1321 1322 1333 protected File getDataFile(final AbstractBundle bundle, final String filename) { 1334 return (File) AccessController.doPrivileged(new GetDataFileAction(bundle, filename)); 1335 } 1336 1337 1340 protected void checkAdminPermission(Bundle bundle, String action) { 1341 SecurityManager sm = System.getSecurityManager(); 1342 if (sm != null) 1343 sm.checkPermission(getAdminPermission(bundle, action)); 1344 } 1345 1346 private AdminPermission getAdminPermission(Bundle bundle, String action) { 1349 synchronized(adminPermissions) { 1350 Long ID = new Long (bundle.getBundleId()); 1351 HashMap bundlePermissions = (HashMap) adminPermissions.get(ID); 1352 if (bundlePermissions == null) { 1353 bundlePermissions = new HashMap(); 1354 adminPermissions.put(ID, bundlePermissions); 1355 } 1356 AdminPermission result = (AdminPermission) bundlePermissions.get(action); 1357 if (result == null) { 1358 result = new AdminPermission(bundle, action); 1359 bundlePermissions.put(action, result); 1360 } 1361 return result; 1362 } 1363 } 1364 1365 1370 protected void checkRegisterServicePermission(String [] names) { 1371 SecurityManager sm = System.getSecurityManager(); 1372 if (sm != null) { 1373 int len = names.length; 1374 for (int i = 0; i < len; i++) { 1375 sm.checkPermission(new ServicePermission(names[i], ServicePermission.REGISTER)); 1376 } 1377 } 1378 } 1379 1380 1385 protected void checkGetServicePermission(String [] names) { 1386 SecurityManager sm = System.getSecurityManager(); 1387 if (sm != null) { 1388 SecurityException se = null; 1389 int len = names.length; 1390 for (int i = 0; i < len; i++) { 1391 try { 1392 sm.checkPermission(new ServicePermission(names[i], ServicePermission.GET)); 1393 return; 1394 } catch (SecurityException e) { 1395 se = e; 1396 } 1397 } 1398 throw se; 1399 } 1400 } 1401 1402 1405 protected void checkGetServicePermission(String name) { 1406 SecurityManager sm = System.getSecurityManager(); 1407 if (sm != null) { 1408 sm.checkPermission(new ServicePermission(name, ServicePermission.GET)); 1409 } 1410 } 1411 1412 1416 protected void installSecurityManager() { 1417 String securityManager = System.getProperty("java.security.manager"); if (securityManager != null) { 1419 SecurityManager sm = System.getSecurityManager(); 1420 if (sm == null) { 1421 if (securityManager.length() < 1) { 1422 securityManager = "java.lang.SecurityManager"; } 1424 try { 1425 Class clazz = Class.forName(securityManager); 1426 sm = (SecurityManager ) clazz.newInstance(); 1427 if (Debug.DEBUG && Debug.DEBUG_SECURITY) { 1428 Debug.println("Setting SecurityManager to: " + sm); } 1430 System.setSecurityManager(sm); 1431 return; 1432 } catch (ClassNotFoundException e) { 1433 } catch (ClassCastException e) { 1435 } catch (InstantiationException e) { 1437 } catch (IllegalAccessException e) { 1439 } 1441 throw new NoClassDefFoundError (securityManager); 1442 } 1443 } 1444 } 1445 1446 1456 public void publishFrameworkEvent(int type, org.osgi.framework.Bundle bundle, Throwable throwable) { 1457 if (frameworkEvent != null) { 1458 if (bundle == null) 1459 bundle = systemBundle; 1460 final FrameworkEvent event = new FrameworkEvent(type, bundle, throwable); 1461 if (System.getSecurityManager() == null) { 1462 publishFrameworkEventPrivileged(event); 1463 } else { 1464 AccessController.doPrivileged(new PrivilegedAction() { 1465 public Object run() { 1466 publishFrameworkEventPrivileged(event); 1467 return null; 1468 } 1469 }); 1470 } 1471 } 1472 } 1473 1474 public void publishFrameworkEventPrivileged(FrameworkEvent event) { 1475 1476 if (event.getType() == FrameworkEvent.ERROR) { 1477 FrameworkLog frameworkLog = adaptor.getFrameworkLog(); 1478 if (frameworkLog != null) 1479 frameworkLog.log(event); 1480 } 1481 1482 ListenerQueue listeners = new ListenerQueue(eventManager); 1483 1484 ListenerQueue contexts = new ListenerQueue(eventManager); 1485 1486 synchronized (frameworkEvent) { 1487 1488 contexts.queueListeners(frameworkEvent, this); 1489 1490 contexts.dispatchEventSynchronous(FRAMEWORKEVENT, listeners); 1491 } 1492 1493 listeners.dispatchEventAsynchronous(FRAMEWORKEVENT, event); 1494 } 1495 1496 1505 public void publishBundleEvent(int type, org.osgi.framework.Bundle bundle) { 1506 if ((bundleEventSync != null) || (bundleEvent != null)) { 1507 final BundleEvent event = new BundleEvent(type, bundle); 1508 if (System.getSecurityManager() == null) { 1509 publishBundleEventPrivileged(event); 1510 } else { 1511 AccessController.doPrivileged(new PrivilegedAction() { 1512 public Object run() { 1513 publishBundleEventPrivileged(event); 1514 return null; 1515 } 1516 }); 1517 } 1518 } 1519 } 1520 1521 public void publishBundleEventPrivileged(BundleEvent event) { 1522 1526 1527 ListenerQueue listenersSync = null; 1528 if (bundleEventSync != null) { 1529 1530 listenersSync = new ListenerQueue(eventManager); 1531 1532 ListenerQueue contexts = new ListenerQueue(eventManager); 1533 1534 synchronized (bundleEventSync) { 1535 1536 contexts.queueListeners(bundleEventSync, this); 1537 1538 contexts.dispatchEventSynchronous(BUNDLEEVENTSYNC, listenersSync); 1539 } 1540 } 1541 1542 ListenerQueue listenersAsync = null; 1543 if (bundleEvent != null && (event.getType() & (BundleEvent.STARTING | BundleEvent.STOPPING | BundleEvent.LAZY_ACTIVATION)) == 0) { 1544 1545 listenersAsync = new ListenerQueue(eventManager); 1546 1547 ListenerQueue contexts = new ListenerQueue(eventManager); 1548 1549 synchronized (bundleEvent) { 1550 1551 contexts.queueListeners(bundleEvent, this); 1552 1553 contexts.dispatchEventSynchronous(BUNDLEEVENT, listenersAsync); 1554 } 1555 } 1556 1557 if (listenersSync != null) { 1558 listenersSync.dispatchEventSynchronous(BUNDLEEVENTSYNC, event); 1559 } 1560 1561 if (listenersAsync != null) { 1562 listenersAsync.dispatchEventAsynchronous(BUNDLEEVENT, event); 1563 } 1564 } 1565 1566 1574 public void publishServiceEvent(int type, org.osgi.framework.ServiceReference reference) { 1575 if (serviceEvent != null) { 1576 final ServiceEvent event = new ServiceEvent(type, reference); 1577 if (System.getSecurityManager() == null) { 1578 publishServiceEventPrivileged(event); 1579 } else { 1580 AccessController.doPrivileged(new PrivilegedAction() { 1581 public Object run() { 1582 publishServiceEventPrivileged(event); 1583 return null; 1584 } 1585 }); 1586 } 1587 } 1588 } 1589 1590 public void publishServiceEventPrivileged(ServiceEvent event) { 1591 1592 ListenerQueue listeners = new ListenerQueue(eventManager); 1593 1594 ListenerQueue contexts = new ListenerQueue(eventManager); 1595 1596 synchronized (serviceEvent) { 1597 1598 contexts.queueListeners(serviceEvent, this); 1599 1600 contexts.dispatchEventSynchronous(SERVICEEVENT, listeners); 1601 } 1602 1603 listeners.dispatchEventSynchronous(SERVICEEVENT, event); 1604 } 1605 1606 1618 public void dispatchEvent(Object l, Object lo, int action, Object object) { 1619 try { 1620 BundleContextImpl context = (BundleContextImpl) l; 1621 if (context.isValid()) { 1622 ListenerQueue queue = (ListenerQueue) object; 1623 switch (action) { 1624 case BUNDLEEVENT : { 1625 queue.queueListeners(context.bundleEvent, context); 1626 break; 1627 } 1628 case BUNDLEEVENTSYNC : { 1629 queue.queueListeners(context.bundleEventSync, context); 1630 break; 1631 } 1632 case SERVICEEVENT : { 1633 queue.queueListeners(context.serviceEvent, context); 1634 break; 1635 } 1636 case FRAMEWORKEVENT : { 1637 queue.queueListeners(context.frameworkEvent, context); 1638 break; 1639 } 1640 } 1641 } 1642 } catch (Throwable t) { 1643 if (Debug.DEBUG && Debug.DEBUG_GENERAL) { 1644 Debug.println("Exception in Top level event dispatcher: " + t.getMessage()); Debug.printStackTrace(t); 1646 } 1647 adaptor.handleRuntimeError(t); 1649 publisherror: { 1650 if (action == FRAMEWORKEVENT) { 1651 FrameworkEvent event = (FrameworkEvent) object; 1652 if (event.getType() == FrameworkEvent.ERROR) { 1653 break publisherror; 1654 } 1655 } 1656 BundleContextImpl context = (BundleContextImpl) l; 1657 publishFrameworkEvent(FrameworkEvent.ERROR, context.bundle, t); 1658 } 1659 } 1660 } 1661 1662 private String [] noMatches(boolean optional) throws BundleException { 1663 if (optional) { 1664 return null; 1665 } 1666 throw new BundleException(Msg.BUNDLE_NATIVECODE_MATCH_EXCEPTION); 1667 } 1668 1669 private void initializeContextFinder() { 1670 Thread current = Thread.currentThread(); 1671 Throwable error = null; 1672 try { 1673 ClassLoader parent = null; 1674 String type = FrameworkProperties.getProperty(PROP_CONTEXTCLASSLOADER_PARENT); 1676 if (CONTEXTCLASSLOADER_PARENT_APP.equals(type)) 1677 parent = ClassLoader.getSystemClassLoader(); 1678 else if (CONTEXTCLASSLOADER_PARENT_BOOT.equals(type)) 1679 parent = null; 1680 else if (CONTEXTCLASSLOADER_PARENT_FWK.equals(type)) 1681 parent = Framework.class.getClassLoader(); 1682 else if (CONTEXTCLASSLOADER_PARENT_EXT.equals(type)) { 1683 ClassLoader appCL = ClassLoader.getSystemClassLoader(); 1684 if (appCL != null) 1685 parent = appCL.getParent(); 1686 } else { Method getContextClassLoader = Thread .class.getMethod("getContextClassLoader", null); parent = (ClassLoader ) getContextClassLoader.invoke(current, null); 1689 } 1690 Method setContextClassLoader = Thread .class.getMethod("setContextClassLoader", new Class [] {ClassLoader .class}); Object [] params = new Object [] {new ContextFinder(parent)}; 1692 setContextClassLoader.invoke(current, params); 1693 return; 1694 } catch (SecurityException e) { 1695 error = e; 1697 } catch (NoSuchMethodException e) { 1698 return; } catch (IllegalArgumentException e) { 1701 error = e; 1703 } catch (IllegalAccessException e) { 1704 error = e; 1706 } catch (InvocationTargetException e) { 1707 error = e.getTargetException(); 1709 } 1710 FrameworkLogEntry entry = new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, FrameworkLogEntry.INFO, 0, NLS.bind(Msg.CANNOT_SET_CONTEXTFINDER, null), 0, error, null); 1711 adaptor.getFrameworkLog().log(entry); 1712 } 1713 1714 private static Field getStaticField(Class clazz, Class type) { 1715 Field[] fields = clazz.getDeclaredFields(); 1716 for (int i = 0; i < fields.length; i++) 1717 if (Modifier.isStatic(fields[i].getModifiers()) && fields[i].getType().equals(type)) { 1718 fields[i].setAccessible(true); 1719 return fields[i]; 1720 } 1721 return null; 1722 } 1723 1724 private void installContentHandlerFactory(BundleContext context, FrameworkAdaptor frameworkAdaptor) { 1725 ContentHandlerFactory chf = new ContentHandlerFactory(context, frameworkAdaptor); 1726 try { 1727 URLConnection.setContentHandlerFactory(chf); 1729 } catch (Error err) { 1730 try { 1732 forceContentHandlerFactory(chf); 1733 } catch (Exception ex) { 1734 adaptor.getFrameworkLog().log(new FrameworkEvent(FrameworkEvent.ERROR, context.getBundle(), ex)); 1736 throw err; 1737 } 1738 } 1739 contentHandlerFactory = chf; 1740 } 1741 1742 private static void forceContentHandlerFactory(ContentHandlerFactory chf) throws Exception { 1743 Field factoryField = getStaticField(URLConnection.class, java.net.ContentHandlerFactory .class); 1744 if (factoryField == null) 1745 throw new Exception ("Could not find ContentHandlerFactory field"); synchronized(URLConnection.class) { 1747 java.net.ContentHandlerFactory factory = (java.net.ContentHandlerFactory ) factoryField.get(null); 1748 1751 if (factory != null) { 1752 try { 1753 factory.getClass().getMethod("isMultiplexing", null); Method register = factory.getClass().getMethod("register", new Class [] {Object .class}); register.invoke(factory, new Object [] {chf}); 1756 } catch (NoSuchMethodException e) { 1757 chf.setParentFactory(factory); 1759 factory = chf; 1760 } 1761 } 1762 factoryField.set(null, null); 1764 resetContentHandlers(); 1767 URLConnection.setContentHandlerFactory(factory); 1768 } 1769 } 1770 1771 private void uninstallContentHandlerFactory() { 1772 try { 1773 Field factoryField = getStaticField(URLConnection.class, java.net.ContentHandlerFactory .class); 1774 if (factoryField == null) 1775 return; synchronized(URLConnection.class) { 1777 java.net.ContentHandlerFactory factory = (java.net.ContentHandlerFactory ) factoryField.get(null); 1778 1779 if (factory == contentHandlerFactory) { 1780 factory = (java.net.ContentHandlerFactory ) contentHandlerFactory.designateSuccessor(); 1781 } else { 1782 Method unregister = factory.getClass().getMethod("unregister", new Class [] {Object .class}); unregister.invoke(factory, new Object [] {contentHandlerFactory}); 1784 } 1785 factoryField.set(null, null); 1787 resetContentHandlers(); 1795 if (factory != null) 1796 URLConnection.setContentHandlerFactory(factory); 1797 } 1798 } catch (Exception e) { 1799 } 1801 } 1802 1803 private static void resetContentHandlers() throws IllegalAccessException { 1804 Field handlersField = getStaticField(URLConnection.class, Hashtable.class); 1805 if (handlersField != null) { 1806 Hashtable handlers = (Hashtable) handlersField.get(null); 1807 if (handlers != null) 1808 handlers.clear(); 1809 } 1810 } 1811 1812 private void installURLStreamHandlerFactory(BundleContext context, FrameworkAdaptor frameworkAdaptor) { 1813 StreamHandlerFactory shf = new StreamHandlerFactory(context, frameworkAdaptor); 1814 try { 1815 URL.setURLStreamHandlerFactory(shf); 1817 } catch (Error err) { 1818 try { 1819 forceURLStreamHandlerFactory(shf); 1821 } catch (Exception ex) { 1822 adaptor.getFrameworkLog().log(new FrameworkEvent(FrameworkEvent.ERROR, context.getBundle(), ex)); 1823 throw err; 1824 } 1825 } 1826 streamHandlerFactory = shf; 1827 } 1828 1829 private static void forceURLStreamHandlerFactory(StreamHandlerFactory shf) throws Exception { 1830 Field factoryField = getStaticField(URL.class, URLStreamHandlerFactory.class); 1831 if (factoryField == null) 1832 throw new Exception ("Could not find URLStreamHandlerFactory field"); Object lock = getURLStreamHandlerFactoryLock(); 1835 synchronized(lock) { 1836 URLStreamHandlerFactory factory = (URLStreamHandlerFactory) factoryField.get(null); 1837 if (factory != null) { 1840 try { 1841 factory.getClass().getMethod("isMultiplexing", null); Method register = factory.getClass().getMethod("register", new Class [] {Object .class}); register.invoke(factory, new Object [] {shf}); 1844 } catch (NoSuchMethodException e) { 1845 shf.setParentFactory(factory); 1847 factory = shf; 1848 } 1849 } 1850 factoryField.set(null, null); 1851 resetURLStreamHandlers(); 1854 URL.setURLStreamHandlerFactory(factory); 1855 } 1856 } 1857 1858 private void uninstallURLStreamHandlerFactory() { 1859 try { 1860 Field factoryField = getStaticField(URL.class, URLStreamHandlerFactory.class); 1861 if (factoryField == null) 1862 return; Object lock = getURLStreamHandlerFactoryLock(); 1864 synchronized (lock) { 1865 URLStreamHandlerFactory factory = (URLStreamHandlerFactory) factoryField.get(null); 1866 if (factory == streamHandlerFactory) { 1867 factory = (URLStreamHandlerFactory) streamHandlerFactory.designateSuccessor(); 1868 } else { 1869 Method unregister = factory.getClass().getMethod("unregister", new Class [] {Object .class}); unregister.invoke(factory, new Object [] {streamHandlerFactory}); 1871 } 1872 factoryField.set(null, null); 1873 resetURLStreamHandlers(); 1879 if (factory != null) 1880 URL.setURLStreamHandlerFactory(factory); 1881 } 1882 } catch (Exception e) { 1883 } 1885 } 1886 1887 private static Object getURLStreamHandlerFactoryLock() throws IllegalAccessException { 1888 Object lock; 1889 try { 1890 Field streamHandlerLockField = URL.class.getDeclaredField("streamHandlerLock"); streamHandlerLockField.setAccessible(true); 1892 lock = streamHandlerLockField.get(null); 1893 } catch (NoSuchFieldException noField) { 1894 lock = URL.class; 1896 } 1897 return lock; 1898 } 1899 1900 private static void resetURLStreamHandlers() throws IllegalAccessException { 1901 Field handlersField = getStaticField(URL.class, Hashtable.class); 1902 if (handlersField != null) { 1903 Hashtable handlers = (Hashtable) handlersField.get(null); 1904 if (handlers != null) 1905 handlers.clear(); 1906 } 1907 } 1908} 1909 | Popular Tags |