/** Fixes the imported library's system package guids with those base's. */
  public static void fixImportLibrarySystemPackageGUIDs(
      MethodLibrary baseLibrary, MethodLibrary importLibraty) {
    HashMap pluginsMap = new HashMap();
    List plugins = baseLibrary.getMethodPlugins();
    for (int i = 0; i < plugins.size(); i++) {
      MethodPlugin plugin = (MethodPlugin) plugins.get(i);
      pluginsMap.put(plugin.getGuid(), plugin);
    }
    if (pluginsMap.isEmpty()) {
      return;
    }

    List importPluginsToFix = new ArrayList();
    List importPlugins = importLibraty.getMethodPlugins();
    for (int i = 0; i < importPlugins.size(); i++) {
      MethodPlugin plugin = (MethodPlugin) importPlugins.get(i);
      if (pluginsMap.containsKey(plugin.getGuid())) {
        importPluginsToFix.add(plugin);
      }
    }

    for (int i = 0; i < importPluginsToFix.size(); i++) {
      MethodPlugin importPlugin = (MethodPlugin) importPluginsToFix.get(i);
      MethodPlugin basePlugin = (MethodPlugin) pluginsMap.get(importPlugin.getGuid());
      if (basePlugin == null) {
        continue;
      }
      List importPackages = TngUtil.getAllSystemPackages(importPlugin);
      HashMap importPackageMap = new HashMap();
      for (int j = 0; j < importPackages.size(); j++) {
        MethodElement importPackage = (MethodElement) importPackages.get(j);
        importPackageMap.put(importPackage.getName(), importPackage);
      }

      List basePackages = TngUtil.getAllSystemPackages(basePlugin);
      for (int j = 0; j < basePackages.size(); j++) {
        MethodElement basePackage = (MethodElement) basePackages.get(j);
        MethodElement importPackage = (MethodElement) importPackageMap.get(basePackage.getName());
        if (importPackage == null) {
          continue;
        }
        String guid = basePackage.getGuid();
        if (!importPackage.getGuid().equals(guid)) {
          importPackage.setGuid(guid);
        }
      }
    }
  }
  /**
   * Removes the resource changed listener to the managed method library resource and method
   * plug-ins.
   */
  protected void removeResourceChangedListeners() {
    if (library == null || library.eResource() == null) {
      return;
    }

    library.eResource().eAdapters().remove(resourceChangedListener);

    for (Iterator iter = library.getMethodPlugins().iterator(); iter.hasNext(); ) {
      MethodPlugin plugin = (MethodPlugin) iter.next();
      plugin.eResource().eAdapters().remove(resourceChangedListener);
    }

    for (Iterator it = library.getPredefinedConfigurations().iterator(); it.hasNext(); ) {
      MethodConfiguration config = (MethodConfiguration) it.next();
      config.eResource().eAdapters().remove(resourceChangedListener);
    }
  }
 /** Collects elements in lib that may have type changes */
 public static void collectPotentialTypeChanged(MethodLibrary lib, HashMap map) {
   for (Iterator it = lib.eAllContents(); it.hasNext(); ) {
     Object obj = it.next();
     if (obj instanceof Guidance || obj instanceof Activity) {
       MethodElement elem = (MethodElement) obj;
       map.put(elem.getGuid(), elem);
     }
   }
 }
  /**
   * Checks whether the managed method library is read only.
   *
   * @return <code>true</code> if the method library is read only
   */
  public boolean isMethodLibraryReadOnly() {
    if (debug) {
      DebugTrace.print(this, "isMethodLibraryReadOnly"); // $NON-NLS-1$
    }

    URI libraryURI = library.eResource().getURI();
    if (libraryURI.isFile()) {
      File libraryXMIFile = new File(libraryURI.toFileString());
      return libraryXMIFile.exists() && !libraryXMIFile.canWrite();
    }
    return false;
  }
  /**
   * Closes the managed method library.
   *
   * @return a method library
   * @throw <code>LibraryServiceException</code> if an error occurs while performing the operation
   */
  public void closeMethodLibrary() throws LibraryServiceException {
    if (debug) {
      String msg =
          "library="
              + library
              + ", memory on entry=" //$NON-NLS-1$ //$NON-NLS-2$
              + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
      DebugTrace.print(this, "closeMethodLibrary", msg); // $NON-NLS-1$
    }

    // String libPath = LibraryService.getInstance()
    // .getCurrentMethodLibraryPath();
    File libFile = new File(library.eResource().getURI().toFileString());
    String libPath = libFile.getParentFile().getAbsolutePath();

    // remove the configuration managers associated with this library
    LibraryService.getInstance().removeConfigurationManagers(library);

    removeResourceChangedListeners();

    // Clear the temp layout resources.
    LayoutResources.clear();

    Suppression.clearCachedSuppressions();

    TngUtil.umaItemProviderAdapterFactory.dispose();

    ILibraryResourceSet resourceSet = (ILibraryResourceSet) editingDomain.getResourceSet();
    resourceSet.unload();

    try {
      // Close the method library project file.
      MethodLibraryProject.closeProject(libPath, null);
    } catch (Exception e) {
      throw new LibraryServiceException(e);
    }

    RefreshJob.getInstance().reset();

    // Activates the garbage collector.
    Runtime.getRuntime().gc();

    if (debug) {
      String msg =
          "library="
              + library
              + ", memory on exit=" //$NON-NLS-1$ //$NON-NLS-2$
              + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
      DebugTrace.print(this, "closeMethodLibrary", msg); // $NON-NLS-1$
    }
  }
  /** Adds a resource changed listener to the managed method library resources. */
  protected void addResourceChangedListeners() {
    if (library == null || library.eResource() == null) {
      return;
    }

    if (!library.eResource().eAdapters().contains(resourceChangedListener)) {
      library.eResource().eAdapters().add(resourceChangedListener);
    }

    for (Iterator it = library.getMethodPlugins().iterator(); it.hasNext(); ) {
      MethodPlugin plugin = (MethodPlugin) it.next();
      if (!plugin.eResource().eAdapters().contains(resourceChangedListener)) {
        plugin.eResource().eAdapters().add(resourceChangedListener);
      }
    }

    for (Iterator it = library.getPredefinedConfigurations().iterator(); it.hasNext(); ) {
      MethodConfiguration config = (MethodConfiguration) it.next();
      if (!config.eResource().eAdapters().contains(resourceChangedListener)) {
        config.eResource().eAdapters().add(resourceChangedListener);
      }
    }
  }
  /**
   * Gets the relative URI of a method element in the managed method library.
   *
   * @param element a method element
   * @return a relative URI
   */
  public URI getElementRelativeURI(MethodElement element) {
    if (debug) {
      DebugTrace.print(
          this, "getElementRelativeURI", "element=" + element); // $NON-NLS-1$ //$NON-NLS-2$
    }

    if (element != null) {
      Resource resource = library.eResource();
      if (resource != null) {
        URI libraryURI = resource.getURI();
        URI elementURI = element.eResource().getURI();
        return elementURI.deresolve(libraryURI);
      }
    }
    return null;
  }
 /**
  * Gets a method element from the managed method library.
  *
  * @param guid the method element's GUID.
  * @return a method element of <code>null</code>
  */
 public MethodElement getMethodElement(String guid) {
   // this printed out too much useless information, comment out
   //		if (debug) {
   //			DebugTrace.print(this, "getMethodElement", "guid=" + guid); //$NON-NLS-1$ //$NON-NLS-2$
   //		}
   if (guid == null) {
     return null;
   }
   try {
     ILibraryResourceSet resourceSet = (ILibraryResourceSet) library.eResource().getResourceSet();
     if (resourceSet != null) {
       return (MethodElement) resourceSet.getEObject(guid);
     }
   } catch (Throwable th) {
     // Log error here
     th.printStackTrace();
   }
   return null;
 }
  /** Analyzes the imported library with respect to the base library. */
  public void analyze(IProgressMonitor monitor) {
    try {
      if (monitor != null) {
        monitor.setTaskName(ImportResources.ConfigurationImportService_MSG0);
      }

      data.getErrorInfo().clear();

      // Prepare the library files.
      String path = data.llData.getParentFolder();
      if (path.indexOf(File.separator + LibraryDocument.libraryFile) < 0) {
        path += File.separator + LibraryDocument.libraryFile;
      }
      File importingLibPath = new File(path);

      boolean isLibraryFile = true;
      if (!importingLibPath.exists()) {
        importingLibPath = new File(importingLibPath.getParentFile(), LibraryDocument.exportFile);
        isLibraryFile = false;
      }

      if (!importingLibPath.exists()) {
        data.getErrorInfo()
            .addError(
                NLS.bind(
                    ImportResources.ConfigurationImportService_MSG1, importingLibPath.getParent()));
        return;
      }

      boolean handleVersion = isLibraryFile;
      if (handleVersion) {
        upGradeInfo =
            new ConfigurationImportService.UpgradeInfo(
                UpgradeCallerInfo.upgradeImportConfig, importingLibPath);
        if (!handleToolVersion(importingLibPath, upGradeInfo)) {
          String errMsg = upGradeInfo.getErrorMsg();
          if (errMsg == null || errMsg.length() == 0) {
            errMsg = ImportResources.ImportConfigurationWizard_ERR_Import_configuration;
          }
          data.getErrorInfo().addError(NLS.bind(errMsg, importingLibPath.getParent()));
          return;
        }
        if (upGradeInfo.getCopiedLibFile() != null) {
          importingLibPath = upGradeInfo.getCopiedLibFile();
        }
      }

      importingLibDoc = new LibraryDocument(importingLibPath);

      boolean isConfigSpecs = importingLibDoc.isConfigSpecsOnly();

      if (isConfigSpecs) {

        specsMgr = new ConfigSpecsImportManager();

        // Scan the library file for configuration information.
        data.specs = specsMgr.getConfigSpecs(importingLibDoc);

      } else {
        if (!isLibraryFile) {
          data.getErrorInfo()
              .addError(
                  NLS.bind(
                      ImportResources.ConfigurationImportService_MSG1,
                      importingLibPath.getParent()));
          return;
        }
        data.specs = null;

        // Open the library and compare the difference.

        // need to open and close the library to have the project resources initialized properly
        String libDir = importingLibPath.getParentFile().getAbsolutePath();

        String projectName =
            "Configuration Import Project (" //$NON-NLS-1$
                + Integer.toHexString(libDir.hashCode())
                + ")"; //$NON-NLS-1$

        MethodLibraryProject.openProject(libDir, projectName, monitor);
        try {
          MethodLibrary importLibraty = LibraryUtil.loadLibrary(importingLibPath.getAbsolutePath());
          MethodLibrary baseLibrary = LibraryService.getInstance().getCurrentMethodLibrary();

          handleTypeChanges(baseLibrary, importLibraty);

          String baseLibDir = null;
          try { // Not neccessary, but prevent introducing any potential regression due to this
                // change
            File bFile = new File(baseLibrary.eResource().getURI().toFileString()).getParentFile();
            ;
            baseLibDir = bFile.getAbsolutePath();
          } catch (Throwable e) {
          }
          if (libDir.equalsIgnoreCase(baseLibDir)) {
            data.getErrorInfo()
                .addError(
                    NLS.bind(
                        ImportResources.ConfigurationImportService_MSG2,
                        importingLibPath.getParent()));
            return;
          }

          fixImportLibrarySystemPackageGUIDs(baseLibrary, importLibraty);

          diffMgr = new LibraryDiffManager(baseLibrary, importLibraty);
          diffMgr.buildDiffTree();

          if (localDebug) {
            diffMgr.rootDiffTree.debugDump();
          }

        } catch (RuntimeException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        MethodLibraryProject.closeProject(libDir, monitor);
        MethodLibraryProject.deleteProject(libDir, monitor);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  private Collection doReloadResources(Collection resources) {
    if (debug) {
      DebugTrace.print(this, "reloadResources"); // $NON-NLS-1$
    }
    if (library == null) {
      return Collections.EMPTY_LIST;
    }

    // check if resources to reload contains any elements cached in
    // LibraryService
    // to update them
    //
    LibraryService libSvc = (LibraryService) LibraryService.getInstance();
    Resource currentLibResource = null;
    ILibraryManager currentLibMgr = null;
    Resource currentConfigResource = null;
    MethodConfiguration currentConfig = null;
    List configResources = new ArrayList();
    List configs = new ArrayList();
    for (Iterator iter = resources.iterator(); iter.hasNext(); ) {
      Resource resource = (Resource) iter.next();
      MethodElement e = PersistenceUtil.getMethodElement(resource);
      if (e == libSvc.getCurrentMethodLibrary()) {
        currentLibMgr = libSvc.getCurrentLibraryManager();
        currentLibResource = resource;
      } else if (e == libSvc.getCurrentMethodConfiguration()) {
        currentConfigResource = resource;
        currentConfig = libSvc.getCurrentMethodConfiguration();
      } else if (e instanceof MethodConfiguration) {
        configResources.add(resource);
        configs.add(e);
      }
    }

    ILibraryResourceSet resourceSet = (ILibraryResourceSet) library.eResource().getResourceSet();
    Collection reloadedResources = resourceSet.reloadResources(resources);
    if (!reloadedResources.isEmpty()) {
      if (currentLibResource != null || currentConfigResource != null) {
        // update cached elements in LibraryService and this library
        // manager
        //
        for (Iterator iter = reloadedResources.iterator(); iter.hasNext(); ) {
          Resource resource = (Resource) iter.next();
          if (resource == currentLibResource) {
            MethodElement e = PersistenceUtil.getMethodElement(resource);
            if (e instanceof MethodLibrary) {
              MethodLibrary newLib = (MethodLibrary) e;
              libSvc.setCurrentMethodLibrary(newLib);
              if (currentLibMgr instanceof AbstractLibraryManager) {
                libSvc.removeLibraryManager(currentLibMgr);
                ((AbstractLibraryManager) currentLibMgr).updateMethodLibrary(newLib);
                libSvc.setLibraryManager(currentLibMgr);
              }
            }
          }
          if (resource == currentConfigResource) {
            MethodElement e = PersistenceUtil.getMethodElement(resource);
            if (e instanceof MethodConfiguration) {
              // remove config manager of old current config
              //
              libSvc.removeConfigurationManager(currentConfig);
              MethodConfiguration config = (MethodConfiguration) e;
              libSvc.setCurrentMethodConfiguration(config);
            }
          } else if (!configResources.isEmpty()) {
            int id = configResources.indexOf(resource);
            if (id != -1) {
              // remove config manager of old config
              //
              libSvc.removeConfigurationManager((MethodConfiguration) configs.get(id));
            }
          }
        }
      }

      // TODO: Review implementation.
      Suppression.cleanUp();
    }
    return reloadedResources;
  }
 /**
  * Gets the managed method library resource.
  *
  * @return a method library resource.
  */
 protected Resource getMethodLibraryResource() {
   return library != null ? library.eResource() : null;
 }