1 19 package org.netbeans.mdr; 20 21 import org.netbeans.api.mdr.CreationFailedException; 22 import org.netbeans.api.mdr.MDRepository; 23 import org.netbeans.api.mdr.events.ExtentEvent; 24 import org.netbeans.api.mdr.events.MDRChangeEvent; 25 import org.netbeans.api.mdr.events.MDRChangeListener; 26 import org.netbeans.mdr.handlers.BaseObjectHandler; 27 import org.netbeans.mdr.handlers.ImmutableList; 28 import org.netbeans.mdr.handlers.InstanceHandler; 29 import org.netbeans.mdr.handlers.gen.TagSupport; 30 import org.netbeans.mdr.persistence.MOFID; 31 import org.netbeans.mdr.persistence.StorageBadRequestException; 32 import org.netbeans.mdr.persistence.StorageException; 33 import org.netbeans.mdr.persistence.btreeimpl.btreestorage.BtreeFactory; 34 import org.netbeans.mdr.storagemodel.*; 35 import org.netbeans.mdr.storagemodel.StorableClass.AttributeDescriptor; 36 import org.netbeans.mdr.util.DebugException; 37 import org.netbeans.mdr.util.Logger; 38 import org.netbeans.mdr.util.MountFailedException; 39 import org.netbeans.mdr.util.TransactionMutex; 40 import org.openide.util.Lookup; 41 import javax.jmi.model.*; 42 import javax.jmi.reflect.*; 43 import javax.jmi.xmi.XmiReader; 44 import java.lang.ref.ReferenceQueue ; 45 import java.lang.ref.WeakReference ; 46 import java.lang.reflect.Constructor ; 47 import java.lang.reflect.InvocationTargetException ; 48 import java.net.URL ; 49 import java.util.*; 50 51 55 public class NBMDRepositoryImpl implements MDRepository { 56 57 58 59 60 61 63 private static final URL MOF_XML_URL = ModelPackage.class.getResource("resources/mof.xml"); 64 private static final URL BOOTMOF_XML_URL = ModelPackage.class.getResource("resources/mof.xml"); 65 66 private static final String TAGID_INDEX = "org.netbeans.attributeIndex"; 67 68 private static final String PARAM_STORAGE_CLASS = "storage"; 69 70 private static final String TRANSIENT_TAG_ID = "org.netbeans.mdr.transient"; 71 private static final String TAG_VALUE_TRUE = "true"; 72 73 public static final String BOOT_MOF = "BootMOF"; 74 public static final String PURE_MOF = "MOF"; 75 76 77 78 79 80 private MdrStorage mdrStorage = null; 81 82 private Map classProxies = null; 83 private Map associationProxies = null; 84 private Map classProxiesMofIds = null; 85 86 private int waitCount = 0; 87 88 private final Map parameters; 89 90 private Map constructorCache = new HashMap(); 91 private Set shutdownListeners = new HashSet(); 92 93 94 95 96 97 101 private final Map facilityCache = new FacilityCache(); 102 103 104 105 106 107 128 public NBMDRepositoryImpl() { 129 Properties props = System.getProperties(); 130 String storageClass = props.getProperty("org.netbeans.mdr.storagemodel.StorageFactoryClassName", "org.netbeans.mdr.persistence.btreeimpl.btreestorage.BtreeFactory"); 131 String storageFile = props.getProperty("org.netbeans.mdr.persistence.Dir"); 132 String storageUUID = props.getProperty("org.netbeans.mdr.persistence.UUID"); 133 134 Logger.getDefault().log("Storage factory: " + storageClass); 135 136 parameters = new HashMap(); 137 parameters.put("storage", storageClass); 138 parameters.put(BtreeFactory.STORAGE_FILE_NAME, storageFile); 139 parameters.put(BtreeFactory.STORAGE_UUID, storageUUID); 140 141 for (Enumeration e = props.propertyNames(); e.hasMoreElements();) { 142 String name = (String ) e.nextElement(); 143 if (name.startsWith("MDRStorageProperty.")) { 144 parameters.put(name.substring(19), props.getProperty(name)); 145 } 146 } 147 } 149 150 159 public NBMDRepositoryImpl(Map parameters) { 160 Logger.getDefault().log("Creating MDRepository implementation ..."); 161 this.parameters = parameters; 162 } 164 165 166 167 168 169 173 public void addListener(MDRChangeListener listener) { 174 addListener(listener, MDRChangeEvent.EVENTMASK_ALL); 175 } 176 177 181 public void addListener(MDRChangeListener listener, int mask) { 182 initCheck(); 183 mdrStorage.getEventNotifier().REPOSITORY.addListener(listener, mask, mdrStorage); 184 } 185 186 189 public void removeListener(MDRChangeListener listener) { 190 initCheck(); 191 mdrStorage.getEventNotifier().REPOSITORY.removeListener(listener, mdrStorage); 192 } 193 194 198 public void removeListener(MDRChangeListener listener, int mask) { 199 initCheck(); 200 mdrStorage.getEventNotifier().REPOSITORY.removeListener(listener, mask, mdrStorage); 201 } 202 203 public void enableEvents() { 204 initCheck(); 205 mdrStorage.enableEvents(); 206 } 207 208 public void disableEvents() { 209 beginTrans(false); 210 mdrStorage.disableEvents(); 211 endTrans(); 212 } 213 214 public MdrStorage getMdrStorage() { 215 initCheck(); 216 return mdrStorage; 217 } 218 219 220 221 222 223 public TransactionMutex getTransactionMutex() { 224 initCheck(); 225 return mdrStorage.getRepositoryMutex(); 226 } 227 228 public void beginTrans(boolean writeAccess) { 229 synchronized (this) { 230 initCheck(); 231 waitCount++; 232 } 233 try { 234 mdrStorage.getRepositoryMutex().enter(writeAccess); 235 } catch (RuntimeException e) { 236 decrementWait(); 237 throw e; 238 } catch (Error e) { 239 decrementWait(); 240 throw e; 241 } 242 } 243 244 private synchronized void decrementWait() { 245 waitCount--; 246 } 247 248 public void endTrans() { 249 endTrans(false); 250 } 251 252 public void endTrans(boolean rollback) { 253 initCheck(); 254 try { 255 if (mdrStorage.getRepositoryMutex().leave(rollback)) { 256 mdrStorage.enableEvents(); 257 } 258 } catch (RuntimeException e) { 259 mdrStorage.enableEvents(); 260 throw e; 261 } catch (Error e) { 262 mdrStorage.enableEvents(); 263 throw e; 264 } finally { 265 decrementWait(); 266 } 267 } 268 269 273 public RefPackage createExtent(String substName) throws CreationFailedException { 274 return createExtent(substName, null); 275 } 276 277 284 public RefPackage createExtent(String substName, RefObject metaPackage) throws CreationFailedException { 285 return createExtent(substName, metaPackage, null); 286 } 287 288 296 public RefPackage createExtent(String substName, RefObject metaPackage, RefPackage[] existingInstances) throws CreationFailedException { 297 return createExtent(substName, metaPackage, existingInstances, null); 298 } 299 300 305 public RefPackage getExtent(String name) { 306 StorablePackage pkg; 307 308 initCheck(); 309 310 beginTrans(false); 311 try { 312 313 try { 314 pkg = mdrStorage.getContextOutermostPackage(name); 316 } catch (NullPointerException e) { 317 pkg = null; 318 } catch ( StorageBadRequestException e ) { 319 pkg = null; 320 } catch ( StorageException e ) { 321 throw new DebugException("Storage exception: " + e); 322 } 323 return (RefPackage) getHandler(pkg); 325 } finally { 326 endTrans(); 327 } 328 } 329 330 public boolean renameExtent(RefPackage extent, String newName) { 331 initCheck(); 332 333 boolean fail = true; 334 beginTrans(true); 335 try { 336 boolean result = mdrStorage.renameContext(((BaseObjectHandler) extent)._getMofId(), newName); 337 fail = false; 338 return result; 339 } catch (StorageException e) { 340 throw new DebugException("Renaming failed: " + e); 341 } finally { 342 endTrans(fail); 343 } 344 } 345 346 352 public String [] getExtentNames() { 353 initCheck(); 354 355 String result[] = new String [0]; 356 beginTrans(false); 357 try { 358 result = (String []) mdrStorage.getContexts().toArray(result); 359 return result; 360 } catch (StorageException e) { 361 throw (DebugException) Logger.getDefault().annotate(new DebugException(), e); 362 } finally { 363 endTrans(); 364 } 365 } 366 367 370 public RefBaseObject getByMofId(String mofId) { 371 return getByMofId(MOFID.fromString(mofId)); 372 } 373 374 public RefBaseObject getByMofId(MOFID mofId) { 375 initCheck(); 376 beginTrans(false); 377 try { 378 StorableBaseObject storable = mdrStorage.getObject(mofId); 379 return getHandler(storable); 380 } catch (StorageException e) { 381 } finally { 383 endTrans(); 384 } 385 return null; 386 } 387 388 public void removeHandler(MOFID mofId) { 389 synchronized (facilityCache) { 390 facilityCache.remove(mofId); 391 } 392 } 393 394 public void addHandler(BaseObjectHandler handler) { 395 StorableBaseObject s = handler._getDelegate(); 396 MOFID mofId = s.getMofId(); 397 Object lock = s.getMdrStorage().getStorageByMofId(mofId); 398 if (lock == null) 399 lock = facilityCache; 400 401 synchronized (lock) { 402 synchronized (facilityCache) { 403 facilityCache.put(mofId, handler); 404 } 405 } 406 } 407 408 411 public synchronized void shutdown() { 412 if (mdrStorage != null) { 413 try { 414 while (waitCount > 0) { 415 try { 416 this.wait(100); 417 } catch (InterruptedException e) { 418 Logger.getDefault().notify(Logger.INFORMATIONAL, e); 419 } 420 } 421 mdrStorage.shutDown(); 422 } catch (StorageException e) { 423 throw (DebugException) Logger.getDefault().annotate(new DebugException(), e); 424 } finally { 425 mdrStorage = null; 426 } 427 } 428 notifyShutdownListeners(); 429 notifyShutdownStep(); 430 } 431 432 433 434 435 436 public String toString() { 437 StringBuffer sb = new StringBuffer ("IDE MOF Repository"); 438 return sb.toString(); 439 } 440 441 442 443 444 445 454 public RefPackage createExtent(String substName, RefObject metaPackage, RefPackage[] existingInstances, String storageId) throws CreationFailedException { 455 initCheck(); 456 457 RefPackage result; 458 459 boolean fail = true; 460 if (metaPackage == null) { 461 metaPackage = getMOFModelPackage(); 462 } 463 464 beginTrans(true); 465 try { 466 if (getExtent(substName) != null) { 467 throw new CreationFailedException("Package extent named \'" + substName + "\' already exists."); 468 } 469 if (mdrStorage.eventsEnabled()) { 470 ExtentEvent event = new ExtentEvent( 471 this, 472 ExtentEvent.EVENT_EXTENT_CREATE, 473 substName, 474 metaPackage, 475 new ImmutableList(existingInstances) 476 ); 477 mdrStorage.getEventNotifier().REPOSITORY.firePlannedChange(mdrStorage, event); 478 } 479 Map instancesToCluster = new HashMap(); 480 481 classProxies = new HashMap(); 483 associationProxies = new HashMap(); 484 classProxiesMofIds = new HashMap(); 485 486 if (existingInstances != null) { 487 for (int i = 0; i < existingInstances.length; i++) { 488 collectPackageInstances(existingInstances[i], instancesToCluster); 489 } 490 } 491 try { 492 instantiatePackage(substName, null, (MofPackage) metaPackage, instancesToCluster, storageId, false); 493 } catch (RuntimeException e) { 494 throw (CreationFailedException) Logger.getDefault().annotate(new CreationFailedException("Cannot instantiate package because of unexpected exception: " + e), e); 495 } 496 497 classProxies = null; 498 associationProxies = null; 499 classProxiesMofIds = null; 500 501 result = getExtent(substName); 502 if (result == null) { 503 throw new CreationFailedException("Cannot find created package."); 504 } 505 506 fail = false; 507 } finally { 508 endTrans(fail); 509 } 510 511 return result; 512 } 513 514 515 516 517 518 528 public String mountStorage(String storageFactoryClass, Map properties) throws MountFailedException { 529 boolean failed = true; 530 beginTrans(true); 531 try { 532 String storageId = this.mdrStorage.mountStorage(storageFactoryClass, properties); 534 failed = false; 535 return storageId; 536 }catch (Exception e) { 537 e.printStackTrace(); 538 throw new MountFailedException("Partition mount failed.", e); 539 } 540 finally { 541 endTrans(failed); 542 } 543 } 544 545 553 public void unmountStorage(String storageId) { 554 boolean failed = true; 555 beginTrans(true); 556 try { 557 if (mdrStorage.eventsEnabled()) { 558 Collection c = mdrStorage.getContexts(storageId); 559 for (Iterator it = c.iterator(); it.hasNext();) { 560 String extentName = (String )it.next(); 561 RefPackage pkg = this.getExtent(extentName); 562 ExtentEvent event = new ExtentEvent(pkg, ExtentEvent.EVENT_EXTENT_DELETE, extentName, pkg.refMetaObject(), null); 563 this.mdrStorage.getEventNotifier().PACKAGE.firePlannedChange(pkg, event); 564 } 565 } 566 this.mdrStorage.unmountStorage(storageId); 567 failed = false; 568 }catch (StorageException e) { 569 throw new DebugException("Unmounting failed: "+e.toString()); 570 } 571 finally { 572 endTrans(failed); 573 } 574 } 575 576 577 578 579 580 583 public String getMOFInstanceName() { 584 return PURE_MOF; 585 } 586 587 public String getParameter(String name) { 588 return (String ) parameters.get(name); 589 } 590 591 592 593 594 595 599 public void freeCache() { 600 facilityCache.clear(); 601 } 602 603 public RefBaseObject getHandler(MOFID mofId) { 604 synchronized (facilityCache) { 605 return (BaseObjectHandler) (facilityCache.get(mofId)); 606 } 607 } 608 609 615 public RefBaseObject getHandler(StorableBaseObject s) { 616 if (s == null) { 617 return null; 618 } 619 620 RefBaseObject refBO = getHandler(s.getMofId()); 621 if (refBO == null) { 622 Class ifc = BaseObjectHandler.resolveClass(s); 623 refBO = getHandler(s, ifc); 624 } 625 return refBO; 626 } 627 628 635 public RefBaseObject getHandler(StorableBaseObject s, Class ifc) { 636 if (s == null) { 637 return null; 638 } 639 640 641 Class cl = BaseObjectHandler.getHandlerClass(ifc, s); 642 643 try { 644 Class cls = s.getClass(); 645 if (cls.equals (TransientStorableClass.class)) { 646 cls = StorableClass.class; 647 } 648 else if (cls.equals (TransientStorableObject.class)) { 649 cls = StorableObject.class; 650 } 651 else if (cls.equals (TransientStorableAssociation.class)) { 652 cls = StorableAssociation.class; 653 } 654 else if ((cls != StorableObject.class) && (StorableObject.class.isAssignableFrom(cls))) { 655 cls = StorableObject.class; 656 } 657 658 MOFID mofId = s.getMofId(); 659 Object lock = s.getMdrStorage().getStorageByMofId(mofId); 660 if (lock == null) 661 lock = facilityCache; 662 663 synchronized (lock) { 664 synchronized (facilityCache) { 665 Object oldRecord = facilityCache.get(mofId); 666 if (oldRecord == null) { 667 Constructor cons = (Constructor ) constructorCache.get(cl); 668 669 if (cons == null) { 670 cons = cl.getConstructor(new Class [] {cls}); 671 constructorCache.put(cl,cons); 672 } 673 oldRecord = cons.newInstance(new Object [] {s}); 674 facilityCache.put(mofId, oldRecord); 675 } 676 return (BaseObjectHandler) oldRecord; 677 } 678 } 679 } catch (NoSuchMethodException e) { 680 throw (DebugException) Logger.getDefault().annotate(new DebugException(), e); 681 } catch (IllegalAccessException e) { 682 throw (DebugException) Logger.getDefault().annotate(new DebugException(), e); 683 } catch (InstantiationException e) { 684 throw (DebugException) Logger.getDefault().annotate(new DebugException(), e); 685 } catch (InvocationTargetException e) { 686 throw (DebugException) Logger.getDefault().annotate(new DebugException(), e); 687 } 688 } 689 690 691 692 693 694 public void addShutdownListener(ShutdownListener listener) { 695 synchronized (shutdownListeners) { 696 shutdownListeners.add(listener); 697 } 698 } 699 700 public void removeShutdownListener(ShutdownListener listener) { 701 synchronized (shutdownListeners) { 702 shutdownListeners.remove(listener); 703 } 704 } 705 706 private void notifyShutdownListeners() { 707 synchronized (shutdownListeners) { 708 for (Iterator iter = shutdownListeners.iterator(); iter.hasNext();) { 709 ShutdownListener listener = (ShutdownListener) iter.next(); 710 listener.shutdown(); 711 } 712 } 713 } 714 715 public int getShutdownSteps() { 716 return mdrStorage != null ? mdrStorage.getShutdownSteps() + 1 : 1; 717 } 718 719 public void notifyShutdownStep() { 720 synchronized (shutdownListeners) { 721 for (Iterator iter = shutdownListeners.iterator(); iter.hasNext();) { 722 ShutdownListener listener = (ShutdownListener) iter.next(); 723 listener.stepFinished(); 724 } 725 } 726 } 727 728 729 730 731 732 734 private MofPackage getMOFModelPackage() { 735 ModelPackage mofPackage = (ModelPackage) getExtent(getMOFInstanceName()); 736 MofPackage result; 737 738 for (Iterator it = mofPackage.getMofPackage().refAllOfClass().iterator(); it.hasNext();) { 739 result = (MofPackage) it.next(); 740 if (result.getName().equals("Model")) { 741 return result; 742 } 743 } 744 745 return null; 746 } 747 748 753 private synchronized void initCheck() { 754 if (mdrStorage == null) { 755 String storageClass = (String ) parameters.get(PARAM_STORAGE_CLASS); 756 757 mdrStorage = new MdrStorage(this, storageClass, this.parameters); 758 try { 759 Logger.getDefault().log("initializing..."); 760 if (!mdrStorage.init()) { 762 Logger.getDefault().log("booting..."); 763 boot(); 765 } 766 return; 767 } catch (StorageException e) { 768 throw (DebugException) Logger.getDefault().annotate(new DebugException("Fatal error: Repository boot/initialization failed with message: " + e.getMessage()), e); 769 } 770 } 771 } 772 773 774 775 776 777 789 private void collectPackageInstances(RefPackage pkg, Map packages) throws CreationFailedException { 790 Object result = packages.put(((BaseObjectHandler)pkg.refMetaObject())._getDelegate().getMofId(), pkg); 791 if (result != null && !result.equals(pkg)) { 792 throw new CreationFailedException("The provided list of existing package instances contains duplicities."); 793 } 794 for (Iterator it = pkg.refAllPackages().iterator(); it.hasNext();) { 795 RefPackage nested = (RefPackage) it.next(); 796 collectPackageInstances(nested, packages); 797 } 798 } 799 800 808 private RefPackage instantiatePackage(String substName, StorablePackage immediatePackage, MofPackage metaPackage, Map clusteredInstances, String storageId, boolean clustered) { 809 StorablePackage newPackage = createPackageHandler(metaPackage, immediatePackage, substName, storageId, clustered); 811 RefPackage result = (RefPackage) getHandler(newPackage); 812 Logger.getDefault().log("new package: " + newPackage.getMofId() + ", metapackage: " + metaPackage.refMofId()); 813 814 Set localAssocProxies = new HashSet(); 815 List localClassProxies = new ArrayList(); 816 instantiatePackageContent(metaPackage, newPackage, clusteredInstances, localClassProxies, localAssocProxies, storageId); 817 resolveSuperclasses(metaPackage, localClassProxies); 818 resolveAssociations(localAssocProxies); 819 820 return result; 821 } 822 823 private void resolveAssociations(Collection localAssocProxies) { 824 try { 825 for (Iterator it = localAssocProxies.iterator(); it.hasNext();) { 826 MOFID saMofId = (MOFID) it.next(); 827 StorableAssociation sa = (StorableAssociation) mdrStorage.getObject(saMofId); 828 if (!((Association) getHandler(sa.getMetaObject())).isDerived()) { 829 Object metaCls = ((AssociationEnd) getByMofId(sa.getEnd1Id())).getType(); 830 StorableClass cls = (StorableClass) classProxies.get(metaCls); 831 cls.addAssociationEnd(saMofId, sa.getEnd1Name(), sa.isAggregateA()); 832 metaCls = ((AssociationEnd) getByMofId(sa.getEnd2Id())).getType(); 833 cls = (StorableClass) classProxies.get(metaCls); 834 if (cls != null) { 835 cls.addAssociationEnd(saMofId, sa.getEnd2Name(), sa.isAggregateB()); 836 } 837 } 838 } 839 } catch (StorageException e) { 840 throw (DebugException) Logger.getDefault().annotate(new DebugException(), e); 841 } 842 } 843 844 847 private void resolveSuperclasses(MofPackage metaPackage, List localClassProxies) { 848 StorableClass sc; 849 ModelElement me; 850 AssociationEnd end; 851 StorableClass current; 852 MofClass cls; 853 List indexTags; 854 855 Map indexes = new HashMap (); 856 if (!localClassProxies.isEmpty ()) { 857 ModelPackage modelPackage = (ModelPackage) metaPackage.refImmediatePackage(); 858 Iterator iter = modelPackage.getTag ().refAllOfClass ().iterator (); 859 while (iter.hasNext ()) { 860 Tag tag = (Tag) iter.next (); 861 if (TAGID_INDEX.equals (tag.getTagId ())) { 862 Iterator elements = tag.getElements ().iterator (); 863 MofClass tempOwner = null, owner = null; 864 boolean oneClass = true; 865 while (elements.hasNext ()) { 866 ModelElement elem = (ModelElement) elements.next (); 867 if (elem instanceof MofClass) { 868 oneClass = true; 869 owner = (MofClass) elem; 870 break; 871 } else { 872 if (elem instanceof Attribute) 873 tempOwner = (MofClass) elem.getContainer (); 874 else if (elem instanceof AssociationEnd) 875 tempOwner = (MofClass) ((AssociationEnd) elem).otherEnd ().getType (); 876 if ((owner == null) && (tempOwner != null)) 877 owner = tempOwner; 878 else 879 oneClass = oneClass && (owner == tempOwner); 880 } 881 } if ((owner != null) && oneClass) { 883 List tags = (List) indexes.get (owner); 884 if (tags == null) 885 indexes.put (owner, tags = new LinkedList ()); 886 tags.add (tag); 887 } 888 } } } 892 for (Iterator it = localClassProxies.iterator(); it.hasNext();) { 893 sc = (StorableClass) it.next(); 894 try { 895 cls = (MofClass) getHandler(sc.getMetaObject()); 896 } catch (StorageException e) { 897 throw (DebugException) Logger.getDefault().annotate(new DebugException(), e); 898 } 899 for (Iterator supers = cls.getSupertypes().iterator(); supers.hasNext();) { 900 Object superMeta = supers.next(); 901 current = ((StorableClass) classProxies.get(superMeta)); 902 if (current == null) { 903 throw new DebugException("Package definition is incomplete: class " + cls.getName() + " super = " + ((superMeta instanceof MofClass) ? ((MofClass) superMeta).getName() : superMeta)); 904 } 905 sc.addSuperclass(current.getMofId()); 906 current.addSubclass(sc.getMofId()); 907 } 908 for (Iterator contents = cls.getContents().iterator(); contents.hasNext();) { 909 me = (ModelElement) contents.next(); 910 if (me instanceof Reference ) { 911 end = ((Reference ) me).getExposedEnd(); 912 sc.addReferenceDescriptor(((BaseObjectHandler)me)._getDelegate().getMofId(), me.getName(), (MOFID) associationProxies.get(((BaseObjectHandler)end.getContainer())._getDelegate().getMofId()), end.getName()); 914 } 915 } indexTags = (List) indexes.get (cls); 917 if (indexTags != null) { 918 try { 919 sc.buildAdditionalIndexes (indexTags, associationProxies); 920 } catch (StorageException e) { 921 throw new DebugException ("Storage exception: " + e); 922 } 923 } 924 } 926 Class iface[] = new Class [1]; 927 for (Iterator it = localClassProxies.iterator(); it.hasNext();) { 928 sc = (StorableClass) it.next(); 929 try { 930 iface[0] = null; 931 sc.initInstanceSuperclass(iface); 932 sc.initClassSuperclass(null); 933 } catch (Exception e) { 934 throw (DebugException) Logger.getDefault().annotate(new DebugException(), e); 935 } 936 } 937 } 938 939 946 private void instantiatePackageContent(MofPackage metaPackage, StorablePackage newPackage, Map clusteredInstances, List localClassProxies, Set localAssocProxies, String storageId) { 947 Iterator superTypes = metaPackage.allSupertypes().iterator(); 948 boolean thisTypeNotProcessed = true; 949 while (thisTypeNotProcessed || superTypes.hasNext()) { 950 Iterator it; 951 if (thisTypeNotProcessed) { 952 it = metaPackage.getContents().iterator(); 953 thisTypeNotProcessed = false; 954 } else 955 it = ((MofPackage) superTypes.next()).getContents().iterator(); 956 957 while (it.hasNext()) { 958 Object o = it.next(); 959 ModelElement element = (ModelElement) o; 960 961 if (element instanceof MofClass) { 962 createClassProxyHandler((MofClass) element, newPackage, localClassProxies); 963 } else if (element instanceof Association) { 964 Association assoc = (Association) element; 965 966 Collection content = assoc.getContents(); 967 int i = 0; 968 AssociationEnd ends[] = new AssociationEnd[2]; 969 for(Iterator cit = content.iterator(); i < 2 && cit.hasNext();) { 970 ModelElement containedElement = (ModelElement) cit.next(); 971 if (containedElement instanceof AssociationEnd) { 972 ends[i++] = (AssociationEnd) containedElement; 973 } 974 } 975 boolean orderA, orderB, uniqueA, uniqueB, aggrA, aggrB, indexedA, indexedB; 977 int minA, maxA, minB, maxB; 978 Class typeA, typeB; 979 980 minA = ends[0].getMultiplicity().getLower(); 981 maxA = ends[0].getMultiplicity().getUpper(); 982 minB = ends[1].getMultiplicity().getLower(); 983 maxB = ends[1].getMultiplicity().getUpper(); 984 try { 985 typeA = BaseObjectHandler.resolveInterface(TagSupport.getDataTypeName((StorableObject)((InstanceHandler)ends[0].getType())._getDelegate())); 986 typeB = BaseObjectHandler.resolveInterface(TagSupport.getDataTypeName((StorableObject)((InstanceHandler)ends[1].getType())._getDelegate())); 987 } catch (java.lang.Exception e) { 988 throw (DebugException) Logger.getDefault().annotate(new DebugException(), e); 989 } 990 orderA = (ends[0].getMultiplicity().isOrdered()); 991 orderB = (ends[1].getMultiplicity().isOrdered()); 992 uniqueA = (ends[0].getMultiplicity().isUnique()); 993 uniqueB = (ends[1].getMultiplicity().isUnique()); 994 995 aggrA = ends[0].getAggregation().equals(AggregationKindEnum.COMPOSITE); 996 aggrB = ends[1].getAggregation().equals(AggregationKindEnum.COMPOSITE); 997 998 indexedA = TagSupport.getTagValue((StorableObject) ((BaseObjectHandler) ends[0])._getDelegate(), TAGID_INDEX) != null; 999 indexedB = TagSupport.getTagValue((StorableObject) ((BaseObjectHandler) ends[1])._getDelegate(), TAGID_INDEX) != null; 1000 if (TagSupport.getTagValue((StorableObject) ((BaseObjectHandler) ends[0].getType())._getDelegate(), TRANSIENT_TAG_ID, "").equals(TAG_VALUE_TRUE) 1001 || TagSupport.getTagValue((StorableObject) ((BaseObjectHandler) ends[1].getType())._getDelegate(), TRANSIENT_TAG_ID, "").equals(TAG_VALUE_TRUE)) { 1002 createTransientAssociationHandler((Association) element, newPackage, ends[0].getName(), ((BaseObjectHandler)ends[0])._getDelegate().getMofId(), ends[1].getName(),((BaseObjectHandler)ends[1])._getDelegate().getMofId(), typeA, typeB, minA, maxA, minB, maxB, orderA, orderB, uniqueA, uniqueB, aggrA, aggrB, localAssocProxies); 1003 } 1004 else { 1005 createAssociationHandler((Association) element, newPackage, ends[0].getName(), ((BaseObjectHandler)ends[0])._getDelegate().getMofId(), ends[1].getName(), ((BaseObjectHandler)ends[1])._getDelegate().getMofId(), typeA, typeB, minA, maxA, minB, maxB, orderA, orderB, uniqueA, uniqueB, aggrA, aggrB, indexedA, indexedB, localAssocProxies); 1006 } 1007 1008 } else if (element instanceof MofPackage) { 1009 StorablePackage pkg = createPackageHandler((MofPackage) element, newPackage, null, storageId, false); 1012 instantiatePackageContent((MofPackage) element, pkg, clusteredInstances, localClassProxies, localAssocProxies, storageId); 1013 } else if (element instanceof Import) { 1014 Import imp = (Import) element; 1015 ModelElement metaElement = imp.getImportedNamespace(); 1016 if (metaElement instanceof MofPackage) { 1017 MofPackage metaPkg = (MofPackage) metaElement; 1018 collectDTDescriptors(storageId, metaPkg, new HashSet()); 1019 if (imp.isClustered()) { 1020 RefPackage pkg = (RefPackage) clusteredInstances.get(((BaseObjectHandler)metaPkg)._getDelegate().getMofId()); 1021 if (pkg == null) { 1022 pkg = instantiatePackage(null, newPackage, metaPkg, clusteredInstances, storageId, true); 1023 clusteredInstances.put(((BaseObjectHandler)metaPkg)._getDelegate().getMofId(), pkg); 1024 } else { 1025 collectAllProxies(pkg); 1026 } 1027 try { 1028 newPackage.clusterPackage(imp.getName(), ((BaseObjectHandler)pkg)._getDelegate().getMofId()); 1029 } catch (StorageException e) { 1030 throw (DebugException) Logger.getDefault().annotate(new DebugException(), e); 1031 } 1032 } } else if (metaElement instanceof EnumerationType) { 1034 createDTDescriptor(storageId, (EnumerationType) metaElement); 1035 } else if (metaElement instanceof StructureType) { 1036 createDTDescriptor(storageId, (StructureType) metaElement); 1037 } else if (metaElement instanceof MofClass) { 1038 collectDTDescriptors(storageId, (MofClass) metaElement, new HashSet()); 1039 } 1040 } } } } 1044 1045 private void collectDTDescriptors(String storageId, GeneralizableElement metaElement, Set visited) { 1046 Iterator superTypes = metaElement.allSupertypes().iterator(); 1047 boolean thisTypeNotProcessed = true; 1048 while (thisTypeNotProcessed || superTypes.hasNext()) { 1049 Iterator it; 1050 if (thisTypeNotProcessed) { 1051 it = metaElement.getContents().iterator(); 1052 thisTypeNotProcessed = false; 1053 } else { 1054 GeneralizableElement ge = (GeneralizableElement) superTypes.next(); 1055 if (!visited.add(ge)) continue; 1056 it = ge.getContents().iterator(); 1057 } 1058 1059 collectDTDescriptors(storageId, it, visited); 1060 } 1061 } 1062 1063 private void collectDTDescriptors(String storageId, Iterator it, Set visited) { 1064 while (it.hasNext()) { 1065 Object element = it.next(); 1066 if (element instanceof MofPackage || element instanceof MofClass) { 1067 if (visited.add(element)) { 1068 collectDTDescriptors(storageId, (GeneralizableElement) element, visited); 1069 } 1070 } else if (element instanceof EnumerationType) { 1071 createDTDescriptor(storageId, (EnumerationType) element); 1072 } else if (element instanceof StructureType) { 1073 createDTDescriptor(storageId, (StructureType) element); 1074 } 1075 } 1076 } 1077 1078 1085 private void collectAllProxies(RefPackage pkg) { 1086 for (Iterator it = pkg.refAllAssociations().iterator(); it.hasNext();) { 1087 RefAssociation assoc = (RefAssociation) it.next(); 1088 if (associationProxies.put(((BaseObjectHandler)assoc.refMetaObject())._getDelegate().getMofId(), ((BaseObjectHandler)assoc)._getDelegate().getMofId()) != null) { 1089 return; 1091 } 1092 } 1093 1094 for (Iterator it = pkg.refAllClasses().iterator(); it.hasNext();) { 1095 RefClass cls = (RefClass) it.next(); 1096 if (classProxiesMofIds.put(((BaseObjectHandler)cls.refMetaObject())._getDelegate().getMofId(), ((BaseObjectHandler)cls)._getDelegate().getMofId()) != null) { 1097 return; 1099 } 1100 classProxies.put(cls.refMetaObject(), ((BaseObjectHandler) cls)._getDelegate()); 1101 } 1102 1103 for (Iterator it = pkg.refAllPackages().iterator(); it.hasNext();) { 1104 collectAllProxies((RefPackage) it.next()); 1105 } 1106 } 1107 1108 1109 1110 1111 1113 1114 private StorablePackage createPackageHandler(MofPackage metaObject,StorablePackage immediatePackage, String context, String storageId, boolean clustered) { 1115 try { 1116 Map datatypes = new HashMap(); 1117 Iterator supers = null; 1119 1120 while (supers == null || supers.hasNext()) { 1121 MofPackage metaPackage; 1122 if (supers == null) { 1123 supers = metaObject.allSupertypes().iterator(); 1124 metaPackage = metaObject; 1125 } else { 1126 metaPackage = (MofPackage) supers.next(); 1127 } 1128 for (Iterator it = metaPackage.getContents().iterator(); it.hasNext();) { 1129 ModelElement element = (ModelElement) it.next(); 1130 if (element instanceof EnumerationType) { 1131 datatypes.put(element.getName(), createDTDescriptor(storageId, (EnumerationType) element)); 1132 } else if (element instanceof StructureType) { 1133 datatypes.put(element.getName(), createDTDescriptor(storageId, (StructureType) element)); 1134 } 1135 } 1136 } 1137 1138 StorablePackage result = null; 1139 if (storageId != null) { 1140 result = new StorablePackage(mdrStorage, immediatePackage == null ? null : immediatePackage.getMofId(), ((BaseObjectHandler)metaObject)._getDelegate().getMofId(), context, datatypes, storageId); 1141 } 1142 else { 1143 result = new StorablePackage(mdrStorage, immediatePackage == null ? null : immediatePackage.getMofId(), ((BaseObjectHandler)metaObject)._getDelegate().getMofId(), context, datatypes); 1144 } 1145 if (immediatePackage != null && !clustered) { 1146 immediatePackage.addPackage(metaObject.getName(), result.getMofId()); 1147 } 1148 1149 return result; 1150 } catch ( StorageException e ) { 1151 throw new DebugException("Storage exception: " + e.getMessage()); 1152 } 1153 } 1154 1155 private DatatypeDescriptor createDTDescriptor(String storageId, EnumerationType e) { 1156 List members = new ArrayList(e.getLabels()); 1157 String ifcName = TagSupport.getTypeFullName((StorableObject) ((BaseObjectHandler) e)._getDelegate()); 1158 return new DatatypeDescriptor(mdrStorage, members, ifcName, storageId); 1159 } 1160 1161 private DatatypeDescriptor createDTDescriptor(String storageId, StructureType struct) { 1162 ModelElement me; 1163 List members = new ArrayList(); 1164 List memberTypes = new ArrayList(); 1165 1166 for (Iterator it2 = struct.getContents().iterator(); it2.hasNext();) { 1167 me = (ModelElement) it2.next(); 1168 if (me instanceof StructureField) { 1169 members.add(me.getName()); 1170 try { 1171 memberTypes.add(BaseObjectHandler.resolveInterface(TagSupport.getDataTypeName((StorableObject) ((BaseObjectHandler) ((StructureField) me).getType())._getDelegate()))); 1172 } catch (ClassNotFoundException e) { 1173 throw (DebugException) Logger.getDefault().annotate(new DebugException(), e); 1174 } 1175 } 1176 } 1177 String ifcName = TagSupport.getTypeFullName((StorableObject) ((BaseObjectHandler) struct)._getDelegate()); 1178 return new DatatypeDescriptor(mdrStorage, struct.getQualifiedName(), members, memberTypes, ifcName, storageId); 1179 } 1180 1181 1182 private StorableClass createClassProxyHandler(MofClass metaObject, StorablePackage immediatePackage, List localClassProxies) { 1183 ModelElement element; 1184 StorableClass storable; 1185 boolean classDerived = false; 1186 boolean instanceDerived = false; 1187 boolean isDerived = false; 1188 1189 try { 1190 ArrayList attrDescs = new ArrayList(); 1191 ArrayList clAttrDescs = new ArrayList(); 1192 Map datatypes = new HashMap(); 1193 for (Iterator it = metaObject.getContents().iterator(); it.hasNext();) { 1195 element = (ModelElement) it.next(); 1196 if (element instanceof Attribute) { 1197 Attribute attr = (Attribute) element; 1198 isDerived = attr.isDerived(); 1199 if (!isDerived) { 1200 Class type; 1201 try { 1202 type = BaseObjectHandler.resolveInterface(TagSupport.getDataTypeName((StorableObject)((InstanceHandler)attr.getType())._getDelegate())); 1203 } catch (java.lang.Exception e) { 1204 throw (DebugException) Logger.getDefault().annotate(new DebugException(), e); 1205 } 1206 AttributeDescriptor desc = new AttributeDescriptor(mdrStorage, ((BaseObjectHandler)attr)._getDelegate().getMofId(), attr.getName(), type, attr.getMultiplicity().getLower(), attr.getMultiplicity().getUpper(), attr.getMultiplicity().isUnique(), attr.getMultiplicity().isOrdered(), attr.isChangeable(), MdrStorage.getStorageIdFromMofId(immediatePackage.getMofId())); 1207 if (ScopeKindEnum.INSTANCE_LEVEL.equals(attr.getScope())) { 1208 attrDescs.add(desc); 1209 } else { 1210 clAttrDescs.add(desc); 1211 } 1212 } 1213 } else if (element instanceof Operation) { 1214 isDerived = true; 1215 } else { 1216 if (element instanceof EnumerationType) { 1217 List members = new ArrayList(((EnumerationType) element).getLabels()); 1218 String ifcName = TagSupport.getTypeFullName((StorableObject) ((BaseObjectHandler) element)._getDelegate()); 1219 datatypes.put(element.getName(), new DatatypeDescriptor(mdrStorage, members, ifcName, MdrStorage.getStorageIdFromMofId(immediatePackage.getMofId()))); 1220 } else if (element instanceof StructureType) { 1221 ModelElement me; 1222 List members = new ArrayList(); 1223 List memberTypes = new ArrayList(); 1224 1225 for (Iterator it2 = ((StructureType) element).getContents().iterator(); it2.hasNext();) { 1226 me = (ModelElement) it2.next(); 1227 if (me instanceof StructureField) { 1228 members.add(me.getName()); 1229 try { 1230 memberTypes.add(BaseObjectHandler.resolveInterface(TagSupport.getDataTypeName((StorableObject) ((BaseObjectHandler) ((StructureField) me).getType())._getDelegate()))); 1231 } catch (ClassNotFoundException e) { 1232 throw (DebugException) Logger.getDefault().annotate(new DebugException(), e); 1233 } 1234 } 1235 } 1236 String ifcName = TagSupport.getTypeFullName((StorableObject) ((BaseObjectHandler) element)._getDelegate()); 1237 datatypes.put(element.getName(), new DatatypeDescriptor(mdrStorage, element.getQualifiedName(), members, memberTypes, ifcName, MdrStorage.getStorageIdFromMofId(immediatePackage.getMofId()))); 1238 } 1239 isDerived = false; 1240 } 1241 1242 if (isDerived) { 1243 if (((Feature) element).getScope().equals(ScopeKindEnum.CLASSIFIER_LEVEL)) { 1244 classDerived = true; 1245 } else { 1246 instanceDerived = true; 1247 } 1248 } 1249 } 1250 String tagValue = TagSupport.getTagValue((StorableObject) ((BaseObjectHandler) metaObject)._getDelegate(), TRANSIENT_TAG_ID, ""); 1251 if (tagValue.equals(TAG_VALUE_TRUE)) { 1252 storable = new TransientStorableClass(mdrStorage, immediatePackage.getMofId(), 1253 ((BaseObjectHandler)metaObject)._getDelegate().getMofId(), attrDescs, clAttrDescs, datatypes, classDerived, 1254 instanceDerived, metaObject.isSingleton(), metaObject.isAbstract()); 1255 } 1256 else { 1257 storable = new StorableClass(mdrStorage, immediatePackage.getMofId(), 1258 ((BaseObjectHandler)metaObject)._getDelegate().getMofId(), attrDescs, clAttrDescs, datatypes, classDerived, 1259 instanceDerived, metaObject.isSingleton(), metaObject.isAbstract()); 1260 } 1261 1262 immediatePackage.addClass(metaObject.getName(), storable.getMofId()); 1263 classProxies.put(metaObject, storable); 1264 classProxiesMofIds.put(((BaseObjectHandler)metaObject)._getDelegate().getMofId(), storable.getMofId()); 1265 localClassProxies.add(storable); 1266 return storable; 1267 } catch ( StorageException e ) { 1268 throw (DebugException) Logger.getDefault().annotate(new DebugException(), e); 1269 } 1270 } 1271 1272 1273 private StorableAssociation createAssociationHandler(Association metaObject, StorablePackage immediatePackage, String assocationEnd1, MOFID assocEnd1MofId, String assocationEnd2, MOFID assocEnd2MofId, Class type1, Class type2, int min1, int max1, int min2, int max2, boolean isOrdered1, boolean isOrdered2, boolean isUnique1, boolean isUnique2, boolean isAggr1, boolean isAggr2, boolean isIndexed1, boolean isIndexed2, Set localAssocProxies) { 1274 try { 1275 StorableAssociation result = new StorableAssociation( 1276 mdrStorage, 1277 immediatePackage.getMofId(), 1278 ((BaseObjectHandler)metaObject)._getDelegate().getMofId(), 1279 assocationEnd1, assocEnd1MofId, assocationEnd2, assocEnd2MofId, 1280 type1, type2, 1281 min1, max1, min2, max2, 1282 isOrdered1, isOrdered2, 1283 isUnique1, isUnique2, 1284 isAggr1, isAggr2, 1285 isIndexed1, isIndexed2); 1286 immediatePackage.addAssociation(metaObject.getName(), result.getMofId()); 1287 associationProxies.put(((BaseObjectHandler)metaObject)._getDelegate().getMofId(), result.getMofId()); 1288 localAssocProxies.add(result.getMofId()); 1289 return result; 1290 } catch ( StorageException e ) { 1291 throw new DebugException("Storage exception: " + e); 1292 } 1293 } 1294 1295 private StorableAssociation createTransientAssociationHandler(Association metaObject, StorablePackage immediatePackage, String assocationEnd1, MOFID assocEnd1MofId, String assocationEnd2, MOFID assocEnd2MofId, Class type1, Class type2, int min1, int max1, int min2, int max2, boolean isOrdered1, boolean isOrdered2, boolean isUnique1, boolean isUnique2, boolean isAggr1, boolean isAggr2, Set localAssocProxies) { 1296 1297 try { 1298 StorableAssociation result = new TransientStorableAssociation( 1299 mdrStorage, 1300 immediatePackage.getMofId(), 1301 ((BaseObjectHandler)metaObject)._getDelegate().getMofId(), 1302 assocationEnd1, assocEnd1MofId, assocationEnd2, assocEnd2MofId, 1303 type1, type2, 1304 min1, max1, min2, max2, 1305 isOrdered1, isOrdered2, 1306 isUnique1, isUnique2, 1307 isAggr1, isAggr2); 1308 immediatePackage.addAssociation(metaObject.getName(), result.getMofId()); 1309 associationProxies.put(((BaseObjectHandler)metaObject)._getDelegate().getMofId(), result.getMofId()); 1310 localAssocProxies.add(result.getMofId()); 1311 return result; 1312 } catch ( StorageException e ) { 1313 throw new DebugException("Storage exception: " + e); 1314 } 1315 } 1316 1317 1318 1319 1320 1321 1324 private void boot() { 1325 boolean fail = true; 1326 Logger.getDefault().log( "Booting repository ..." ); 1327 mdrStorage.setBooting(true); 1328 beginTrans(true); 1329 try { 1330 installFakeMof(); 1331 installPureMof(); 1332 fail = false; 1333 } catch (Throwable e) { 1334 Logger.getDefault().notify(Logger.INFORMATIONAL, e); 1335 } finally { 1336 mdrStorage.setBooting(false); 1337 endTrans(fail); 1338 } 1339 } 1340 1341 1343 private void installFakeMof() { 1344 Logger.getDefault().log("Creating boot MOF metamodel ..."); 1345 1346 createBootMOF(); 1347 if (getExtent(BOOT_MOF) == null) { 1348 throw new DebugException("Cannot create instance of BOOT_MOF: Fatal error during bootstrapping."); 1349 } 1350 } 1351 1352 1354 private void installPureMof() { 1355 Logger.getDefault().log("Installing pure MOF Metamodel ... "); 1356 1357 try { 1358 Logger.getDefault().log("Parsing MOF model to DOM represtentation ...."); 1359 ModelPackage modelPackage = (ModelPackage) createExtent(PURE_MOF, getBMModelPackage()); 1360 XmiReader xmiReader = (XmiReader) Lookup.getDefault().lookup(XmiReader.class); 1361 xmiReader.read(MOF_XML_URL.toString(), modelPackage); 1362 mdrStorage.rebuildMofContext(); 1363 } catch (Exception e) { 1364 throw (DebugException) Logger.getDefault().annotate(new DebugException("Boot failed."), e); 1365 } 1366 } 1367 1368 1375 private MofPackage getBMModelPackage() { 1376 MofPackage result; 1377 for (Iterator it = ((ModelPackage) getExtent(BOOT_MOF)).getMofPackage().refAllOfClass().iterator(); it.hasNext();) { 1378 result = (MofPackage) it.next(); 1379 if (result.getName().equals("Model")) { 1380 return result; 1381 } 1382 } 1383 return null; 1384 } 1385 1386 1388 private void createBootMOF() { 1389 try { 1390 BootReader br = new BootReader(mdrStorage, BOOTMOF_XML_URL); 1391 br.read(); 1392 } catch (Exception e) { 1393 throw (DebugException) Logger.getDefault().annotate(new DebugException("Unable to read MOF XMI: " + e.getMessage()), e); 1394 } 1395 } 1396 1397 1398 1399 1400 1401 1403 private static class FacilityCache extends HashMap { 1404 private final ReferenceQueue queue = new ReferenceQueue (); 1405 private boolean cleaningUp = false; 1406 1407 private class HandlerReference extends WeakReference { 1408 private MOFID mofId; 1409 private RefBaseObject baseObject; 1411 1412 public HandlerReference(BaseObjectHandler handler) { 1413 super(handler, queue); 1414 1415 mofId = handler._getMofId(); 1416 1417 if (handler.refImmediatePackage() instanceof javax.jmi.model.ModelPackage || !(handler instanceof RefObject)) { 1418 baseObject = handler; 1420 } else { 1421 baseObject = null; 1423 } 1424 } 1425 1426 public MOFID getProxyMofId() { 1427 return mofId; 1428 } 1429 } 1430 1431 private void cleanUp() { 1432 assert !cleaningUp; 1433 HandlerReference reference; 1434 cleaningUp = true; 1435 try { 1436 while ((reference = (HandlerReference) queue.poll()) != null) { 1437 MOFID mofId = reference.getProxyMofId(); 1439 java.lang.ref.Reference currentRef = (java.lang.ref.Reference ) super.remove(mofId); 1440 if (currentRef != null && currentRef != reference && currentRef.get() != null) { 1441 super.put(mofId, currentRef); 1442 } 1443 } 1444 } finally { 1445 cleaningUp = false; 1446 } 1447 } 1448 1449 public Object put(Object key, Object value) { 1450 cleanUp(); 1451 Object result = super.put(key, new HandlerReference((BaseObjectHandler) value)); 1452 assert result == null || ((HandlerReference) result).get() == null : "replacing non-null reference"; 1453 return null; 1454 } 1455 1456 public Object remove(Object key) { 1457 cleanUp(); 1458 Object result = super.remove(key); 1459 return result == null ? null : ((HandlerReference) result).get(); 1460 } 1461 1462 public Object get(Object key) { 1463 cleanUp(); 1464 Object result = super.get(key); 1465 return result == null ? null : ((HandlerReference) result).get(); 1466 } 1467 } 1468 1469 1470 1471 1472 1473 public interface ShutdownListener { 1474 public void shutdown(); 1475 1476 public void stepFinished(); 1477 } 1478 1479 1480} 1481 | Popular Tags |