예제 #1
1
 public void computeImports() throws CoreException {
   // some existing imports may valid and can be preserved
   Vector preservedImports = new Vector(fImports.size());
   // new imports
   ArrayList newImports = new ArrayList();
   IPluginModelBase model = null;
   for (int i = 0; i < fPlugins.size(); i++) {
     IFeaturePlugin fp = (IFeaturePlugin) fPlugins.get(i);
     ModelEntry entry = PluginRegistry.findEntry(fp.getId());
     if (entry == null) continue;
     IPluginModelBase[] models = entry.getActiveModels();
     for (int j = 0; j < models.length; j++) {
       IPluginModelBase m = models[j];
       if (fp.getVersion().equals(m.getPluginBase().getVersion())
           || fp.getVersion().equals("0.0.0")) // $NON-NLS-1$
       model = m;
     }
     if (model != null) {
       addPluginImports(preservedImports, newImports, model.getPluginBase());
       if (model.isFragmentModel()) {
         BundleDescription desc = model.getBundleDescription();
         if (desc == null) continue;
         HostSpecification hostSpec = desc.getHost();
         String id = hostSpec.getName();
         String version = null;
         int match = IMatchRules.NONE;
         VersionRange versionRange = hostSpec.getVersionRange();
         if (!(versionRange == null || VersionRange.emptyRange.equals(versionRange))) {
           version =
               versionRange.getMinimum() != null ? versionRange.getMinimum().toString() : null;
           match = PluginBase.getMatchRule(versionRange);
         }
         addNewDependency(id, version, match, preservedImports, newImports);
       }
     }
   }
   // preserve imports of features
   for (int i = 0; i < fImports.size(); i++) {
     IFeatureImport iimport = (IFeatureImport) fImports.get(i);
     if (iimport.getType() == IFeatureImport.FEATURE) preservedImports.add(iimport);
   }
   // removed = old - preserved
   Vector removedImports = ((Vector) fImports.clone());
   removedImports.removeAll(preservedImports);
   // perform remove
   fImports = preservedImports;
   if (removedImports.size() > 0) {
     fireStructureChanged(
         (IFeatureImport[]) removedImports.toArray(new IFeatureImport[removedImports.size()]),
         IModelChangedEvent.REMOVE);
   }
   // perform add
   if (newImports.size() > 0) {
     fImports.addAll(newImports);
     fireStructureChanged(
         (IFeatureImport[]) newImports.toArray(new IFeatureImport[newImports.size()]),
         IModelChangedEvent.INSERT);
   }
 }
  /** {@inheritDoc} */
  public List<ServiceDetector> getDetectorsForForeignSource(final String foreignSourceName) {
    final ForeignSource foreignSource =
        m_foreignSourceRepository.getForeignSource(foreignSourceName);
    assertNotNull(foreignSource, "Expected a foreignSource with name %s", foreignSourceName);

    final List<PluginConfig> detectorConfigs = foreignSource.getDetectors();
    if (detectorConfigs == null) {
      return new ArrayList<ServiceDetector>(m_pluginRegistry.getAllPlugins(ServiceDetector.class));
    }

    final List<ServiceDetector> detectors = new ArrayList<ServiceDetector>(detectorConfigs.size());
    for (final PluginConfig detectorConfig : detectorConfigs) {
      final ServiceDetector detector =
          m_pluginRegistry.getPluginInstance(ServiceDetector.class, detectorConfig);
      if (detector == null) {
        errorf(this, "Configured plugin does not exist: %s", detectorConfig);
      } else {
        detector.setServiceName(detectorConfig.getName());
        detector.init();
        detectors.add(detector);
      }
    }

    return detectors;
  }
 private IPluginModelBase findModel(IAdaptable object) {
   if (object instanceof IJavaProject) object = ((IJavaProject) object).getProject();
   if (object instanceof IProject) return PluginRegistry.findModel((IProject) object);
   if (object instanceof PersistablePluginObject) {
     return PluginRegistry.findModel(((PersistablePluginObject) object).getPluginID());
   }
   return null;
 }
 @Test
 public void testPluginRegistry() throws InstantiationException, IllegalAccessException {
   PluginRegistry registry = ImageTilerApplication.createPluginRegistry();
   //        assertEquals(GemSVGTile.class,
   // registry.getNewInstance(ImageTilerApplication.PLUGIN_TYPE_TILE, "Gem").getClass());
   //        assertEquals(CircleStrategy.class,
   // registry.getNewInstance(ImageTilerApplication.PLUGIN_TYPE_STRATEGY, "Circle").getClass());
   assertNull(registry.getNewInstance(ITContext.PLUGIN_TYPE_STRATEGY, "Oval"));
   assertNull(registry.getNewInstance("NoSuchType", "Thing"));
 }
  private boolean isCustomPropertiesPlugin(String nodeName) throws CruiseControlException {
    if (customPropertiesPlugins.contains(nodeName)) {
      return true;
    }

    boolean isPropetiesPlugin =
        rootPlugins.isPluginRegistered(nodeName)
            && PropertiesPlugin.class.isAssignableFrom(rootPlugins.getPluginClass(nodeName));

    if (isPropetiesPlugin) {
      customPropertiesPlugins.add(nodeName);
    }

    return isPropetiesPlugin;
  }
 /**
  * Validates that the version of the given plug-in is available in the registry. Adds a warning if
  * the plug-in could not be found.
  *
  * @param plugin xml element describing the plug-in to look for in the registry
  * @param attr set of element attributes
  */
 private void validateVersion(Element plugin, Attr attr) {
   String id = plugin.getAttribute("id"); // $NON-NLS-1$
   String version = plugin.getAttribute("version"); // $NON-NLS-1$
   if (id.trim().length() == 0
       || version.trim().length() == 0
       || version.equals("0.0.0")) // $NON-NLS-1$
   return;
   ModelEntry entry = PluginRegistry.findEntry(id);
   if (entry != null) {
     IPluginModelBase[] allModels = entry.getActiveModels();
     for (int i = 0; i < allModels.length; i++) {
       IPluginModelBase availablePlugin = allModels[i];
       if (id.equals(availablePlugin.getPluginBase().getId())) {
         if (version.equals(availablePlugin.getPluginBase().getVersion())) {
           return;
         }
       }
     }
   }
   report(
       NLS.bind(
           PDECoreMessages.Builders_Feature_mismatchPluginVersion, new String[] {version, id}),
       getLine(plugin, attr.getName()),
       CompilerFlags.WARNING,
       PDEMarkerFactory.CAT_OTHER);
 }
  /**
   * getPluginsForForeignSource
   *
   * @param pluginClass a {@link java.lang.Class} object.
   * @param foreignSourceName a {@link java.lang.String} object.
   * @param <T> a T object.
   * @return a {@link java.util.List} object.
   */
  public <T> List<T> getPluginsForForeignSource(
      final Class<T> pluginClass, final String foreignSourceName) {
    final ForeignSource foreignSource =
        m_foreignSourceRepository.getForeignSource(foreignSourceName);
    assertNotNull(foreignSource, "Expected a foreignSource with name %s", foreignSourceName);

    final List<PluginConfig> configs = foreignSource.getPolicies();
    if (configs == null) {
      return Collections.emptyList();
    }

    final List<T> plugins = new ArrayList<T>(configs.size());
    for (final PluginConfig config : configs) {
      final T plugin = m_pluginRegistry.getPluginInstance(pluginClass, config);
      if (plugin == null) {
        LogUtils.tracef(
            this,
            "Configured plugin is not appropropriate for policy class %s: %s",
            pluginClass,
            config);
      } else {
        plugins.add(plugin);
      }
    }

    return plugins;
  }
  public void search(
      ISearchRequestor requestor, QuerySpecification querySpecification, IProgressMonitor monitor)
      throws CoreException {

    if (querySpecification.getLimitTo() != S_LIMIT_REF
        && querySpecification.getLimitTo() != S_LIMIT_ALL) return;

    String search;
    if (querySpecification instanceof ElementQuerySpecification) {
      IJavaElement element = ((ElementQuerySpecification) querySpecification).getElement();
      if (element instanceof IType) search = ((IType) element).getFullyQualifiedName('.');
      else search = element.getElementName();
      int type = element.getElementType();
      if (type == IJavaElement.TYPE) fSearchFor = S_FOR_TYPES;
      else if (type == IJavaElement.PACKAGE_FRAGMENT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT)
        fSearchFor = S_FOR_PACKAGES;
    } else {
      fSearchFor = ((PatternQuerySpecification) querySpecification).getSearchFor();
      search = ((PatternQuerySpecification) querySpecification).getPattern();
    }
    if (fSearchFor != S_FOR_TYPES && fSearchFor != S_FOR_PACKAGES) return;
    fSearchPattern = PatternConstructor.createPattern(search, true);
    fSearchRequestor = requestor;

    IPath[] enclosingPaths = querySpecification.getScope().enclosingProjectsAndJars();
    IPluginModelBase[] pluginModels = PluginRegistry.getWorkspaceModels();
    monitor.beginTask(PDEUIMessages.ClassSearchParticipant_taskMessage, pluginModels.length);
    for (int i = 0; i < pluginModels.length; i++) {
      IProject project = pluginModels[i].getUnderlyingResource().getProject();
      if (!monitor.isCanceled() && encloses(enclosingPaths, project.getFullPath()))
        searchProject(project, monitor);
    }
  }
 private void initializePluginModel() {
   IPluginModelBase base = PluginRegistry.findModel(getPluginProject());
   // should never happen
   if (base == null) return;
   if (base instanceof IBundlePluginModelBase)
     fExtensionsModel = ((IBundlePluginModelBase) base).getExtensionsModel();
   else fExtensionsModel = base;
 }
 private void handleCustomRootProperty(final Element childElement) throws CruiseControlException {
   ProjectXMLHelper.registerCustomProperty(
       rootProperties,
       childElement,
       fileResolver,
       FAIL_UPON_MISSING_PROPERTY,
       PluginRegistry.createRegistry(rootPlugins));
 }
 /**
  * Unloads the plugin. The effectively shuts the plugin down and removes it from the
  * PluginRegistry's resource loaders.
  *
  * @throws Exception
  */
 public synchronized void unload() throws Exception {
   if (plugin != null) {
     plugin.stop();
     // it's important that the plugin be removed from the resource loading system after shutdown
     // in
     // case the plugin needs to access the resource loader during shutdown
     registry.removeResourceLoader(plugin.getName());
   }
   loaded = false;
 }
예제 #12
0
 private void initializeModel(IStructuredSelection selection) {
   Object selected = selection.getFirstElement();
   if (selected instanceof IAdaptable) {
     IResource resource = (IResource) ((IAdaptable) selected).getAdapter(IResource.class);
     if (resource != null) {
       IProject project = resource.getProject();
       fModel = PluginRegistry.findModel(project);
     }
   }
 }
 /**
  * Loads the plugin from the PluginLoader. This will also start the Plugin and add it to the
  * PluginRegistry's resoure loaders.
  */
 public synchronized void load() throws Exception {
   plugin = loader.load();
   plugin.setSuppressStartupFailure(suppressStartupFailure);
   // it's important that the plugin is added to the resource loading system prior to startup
   // because
   // startup may need to grab services
   registry.addResourceLoader(plugin);
   plugin.start();
   loaded = true;
 }
 private boolean isProjectTemplate(Element pluginElement) {
   String pluginName = pluginElement.getAttributeValue("name");
   String pluginClassName = pluginElement.getAttributeValue("classname");
   if (pluginClassName == null) {
     pluginClassName = rootPlugins.getPluginClassname(pluginName);
   }
   try {
     Class pluginClass = rootPlugins.instanciatePluginClass(pluginClassName, pluginName);
     return ProjectInterface.class.isAssignableFrom(pluginClass);
   } catch (CruiseControlException e) {
     // this is only triggered by tests today, when a class is not
     // loadable.
     // I didn't want to propagate the exception
     // in case something like Distributed CC requires a class to not be
     // loadable locally at this point...
     LOG.warn(
         "Couldn't check if the plugin " + pluginName + " is an instance of ProjectInterface", e);
     return false;
   }
 }
 private void handleRootPlugin(Element pluginElement) throws CruiseControlException {
   String pluginName = pluginElement.getAttributeValue("name");
   if (pluginName == null) {
     LOG.warn("Config contains plugin without a name-attribute, ignoring it");
     return;
   }
   if (isProjectTemplate(pluginElement)) {
     handleNodeProperties(pluginElement, pluginName);
   }
   rootPlugins.register(pluginElement);
 }
  private CruiseControlConfig(final Element includedElement, final CruiseControlConfig parent)
      throws CruiseControlException {

    this.controller = parent.controller;
    xmlResolver = parent.xmlResolver;
    fileResolver = parent.fileResolver;
    rootPlugins = PluginRegistry.createRegistry(parent.rootPlugins);
    rootProperties = new HashMap<String, String>(parent.rootProperties);
    templatePluginProperties = new HashMap<String, List>(parent.templatePluginProperties);

    parse(includedElement);
  }
  private void validateUnpack(Element parent) {
    int severity = CompilerFlags.getFlag(fProject, CompilerFlags.F_UNRESOLVED_PLUGINS);
    if (severity == CompilerFlags.IGNORE) {
      return;
    }
    if (severity == CompilerFlags.ERROR) {
      // this might not be an error, so max the flag at WARNING level.
      severity = CompilerFlags.WARNING;
    }
    String unpack = parent.getAttribute("unpack"); // $NON-NLS-1$
    IPluginModelBase pModel = PluginRegistry.findModel(parent.getAttribute("id")); // $NON-NLS-1$
    if (pModel == null) {
      return;
    }

    if (pModel instanceof IBundlePluginModel) {
      IBundlePluginModel bModel = (IBundlePluginModel) pModel;
      IManifestHeader header =
          bModel
              .getBundleModel()
              .getBundle()
              .getManifestHeader(ICoreConstants.ECLIPSE_BUNDLE_SHAPE);
      if (header != null) {
        String value = header.getValue();
        String unpackValue =
            "true".equals(unpack) ? "jar" : "dir"; // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        if (value != null && !value.equalsIgnoreCase(unpackValue)) {
          String message =
              NLS.bind(
                  PDECoreMessages.Builders_Feature_mismatchUnpackBundleShape,
                  (new String[] {
                    "unpack=" + unpack, parent.getAttribute("id"), "Eclipse-BundleShape: " + value
                  })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
          report(message, getLine(parent), severity, PDEMarkerFactory.CAT_OTHER);
        }
      }
    }

    if ("true".equals(unpack)
        && !CoreUtility.guessUnpack(pModel.getBundleDescription())) { // $NON-NLS-1$
      String message =
          NLS.bind(
              PDECoreMessages.Builders_Feature_missingUnpackFalse,
              (new String[] {
                parent.getAttribute("id"), "unpack=\"false\""
              })); //$NON-NLS-1$ //$NON-NLS-2$
      report(message, getLine(parent), severity, PDEMarkerFactory.CAT_OTHER);
    }
  }
예제 #18
0
 private static String getServletBridgeAbsolutePath() {
   String result = null;
   ModelEntry entry = PluginRegistry.findEntry(Validator.SERVLET_BRIDGE_ID);
   if (entry != null) {
     IPluginModelBase[] targetModels = entry.getExternalModels();
     for (int i = 0; i < targetModels.length && result == null; i++) {
       IPluginModelBase bridgeModel = targetModels[i];
       String libLocation = bridgeModel.getInstallLocation();
       if (libLocation != null && libLocation.toLowerCase().indexOf(".jar") != -1) // $NON-NLS-1$
       {
         result = libLocation;
       }
     }
   }
   return result;
 }
 private void validatePluginID(Element element, Attr attr, boolean isFragment) {
   String id = attr.getValue();
   if (!validatePluginID(element, attr)) {
     return;
   }
   int severity = CompilerFlags.getFlag(fProject, CompilerFlags.F_UNRESOLVED_PLUGINS);
   if (severity != CompilerFlags.IGNORE) {
     IPluginModelBase model = PluginRegistry.findModel(id);
     if (model == null
         || !model.isEnabled()
         || (isFragment && !model.isFragmentModel())
         || (!isFragment && model.isFragmentModel())) {
       report(
           NLS.bind(PDECoreMessages.Builders_Feature_reference, id),
           getLine(element, attr.getName()),
           severity,
           PDEMarkerFactory.CAT_OTHER);
     }
   }
 }
  private void initialize() {
    if (fWorkingSet != null) {
      HashSet<String> set = new HashSet<String>();
      IAdaptable[] elements = fWorkingSet.getElements();
      for (int i = 0; i < elements.length; i++) {
        if (elements[i] instanceof PersistablePluginObject)
          set.add(((PersistablePluginObject) elements[i]).getPluginID());
      }

      IPluginModelBase[] bases = PluginRegistry.getAllModels();
      for (int i = 0; i < bases.length; i++) {

        String id = bases[i].getPluginBase().getId();
        if (id == null) continue;
        if (set.contains(id)) {
          fTree.getCheckboxTreeViewer().setChecked(bases[i], true);
          set.remove(id);
        }
        if (set.isEmpty()) break;
      }
      fWorkingSetName.setText(fWorkingSet.getName());
    }
  }
  protected void doIncludeVersions(NameVersionDescriptor[] descriptions) throws Exception {
    String bsn = MULTI_VERSION_LOW_DESCRIPTION.getId();

    IPath extras = extractMultiVersionPlugins();
    ITargetDefinition target = getNewTarget();
    ITargetLocation container = getTargetService().newDirectoryLocation(extras.toOSString());
    target.setTargetLocations(new ITargetLocation[] {container});
    target.setIncluded(descriptions);
    try {
      getTargetService().saveTargetDefinition(target);
      setTargetPlatform(target);
      IPluginModelBase[] models = PluginRegistry.getExternalModels();
      Set enabled = new HashSet();
      for (int i = 0; i < models.length; i++) {
        IPluginModelBase pm = models[i];
        if (pm.getBundleDescription().getSymbolicName().equals(bsn)) {
          NameVersionDescriptor desc =
              new NameVersionDescriptor(
                  pm.getPluginBase().getId(), pm.getPluginBase().getVersion());
          if (pm.isEnabled()) {
            enabled.add(desc);
          }
        }
      }
      if (descriptions == null) {

      } else {
        assertEquals("Wrong number of enabled bundles", descriptions.length, enabled.size());
        for (int i = 0; i < descriptions.length; i++) {
          assertTrue("Missing bundle", enabled.contains(descriptions[i]));
        }
      }
    } finally {
      getTargetService().deleteTarget(target.getHandle());
      resetTargetPlatform();
    }
  }
예제 #22
0
 /**
  * This attempts to load plugins from the directory given
  *
  * @param dirName plugin directory to load
  * @throws NITFException
  */
 public static void loadPluginDir(String dirName) throws NITFException {
   PluginRegistry.loadPluginDir(dirName);
 }
 private boolean isProject(String nodeName) throws CruiseControlException {
   return rootPlugins.isPluginRegistered(nodeName)
       && ProjectInterface.class.isAssignableFrom(rootPlugins.getPluginClass(nodeName));
 }
예제 #24
0
 public DependencyExtentOperation(IProject project, String importID, ISearchResult searchResult) {
   fSearchResult = (DependencyExtentSearchResult) searchResult;
   fProject = project;
   fImportID = importID;
   fModel = PluginRegistry.findModel(project);
 }
예제 #25
0
  /**
   * Creates a new TRE of the given type. The tag is the TRE tag (such as "JITCID"). The id is the
   * identifier of the TREDescription. Each TREDescription has its own identifier pertaining to a
   * specific revision, etc. Many TREs will not have a revision, so you can leave the id null.
   *
   * @param tag the type of TRE to create
   * @param id the id of the TRE Description to use, or null to use the default
   * @throws NITFException if tag is an unkown type
   */
  public TRE(String tag, String id) throws NITFException {
    if (!PluginRegistry.canHandleTRE(tag))
      throw new NITFException("TRE Handler cannot be found for this TRE: " + tag);

    construct(tag, id);
  }
 public Object[] getElements(Object inputElement) {
   return PluginRegistry.getAllModels();
 }
/** @author <a href="mailto:[email protected]">Jerome Lacoste</a> */
@Description(
    "The root element of the configuration, acting as a container to the rest of "
        + "the configuration elements.")
public class CruiseControlConfig {
  private static final Logger LOG = Logger.getLogger(CruiseControlConfig.class);

  public static final String LABEL_INCREMENTER = "labelincrementer";

  public static final boolean FAIL_UPON_MISSING_PROPERTY = false;

  private static final Set<String> KNOWN_ROOT_CHILD_NAMES = new HashSet<String>();

  static {
    KNOWN_ROOT_CHILD_NAMES.add("include.projects");
    KNOWN_ROOT_CHILD_NAMES.add("property");
    KNOWN_ROOT_CHILD_NAMES.add("plugin");
    KNOWN_ROOT_CHILD_NAMES.add("system");
    KNOWN_ROOT_CHILD_NAMES.add("dashboard");
  }

  private Map<String, String> rootProperties = new HashMap<String, String>();
  /** Properties of a particular node. Mapped by the node name. Doesn't handle rootProperties yet */
  private Map<String, List> templatePluginProperties = new HashMap<String, List>();

  private PluginRegistry rootPlugins = PluginRegistry.createRegistry();
  private final Map<String, ProjectInterface> projects =
      new LinkedHashMap<String, ProjectInterface>();
  // for test purposes only
  private final Map<String, PluginRegistry> projectPluginRegistries =
      new TreeMap<String, PluginRegistry>();

  private final XmlResolver xmlResolver;
  private final FileResolver fileResolver;

  private SystemPlugin system;

  public int getMaxNbThreads() {
    if (system != null) {
      if (system.getConfig() != null) {
        if (system.getConfig().getThreads() != null) {
          return system.getConfig().getThreads().getCount();
        }
      }
    }
    return 1;
  }

  private final CruiseControlController controller;

  private final Set<String> customPropertiesPlugins = new HashSet<String>();

  public CruiseControlConfig(final Element ccElement) throws CruiseControlException {
    this(ccElement, null, null, null);
  }

  public CruiseControlConfig(final Element ccElement, final CruiseControlController controller)
      throws CruiseControlException {

    this(ccElement, null, null, controller);
  }

  public CruiseControlConfig(
      final Element ccElement, final XmlResolver xmlResolver, final FileResolver fileResolver)
      throws CruiseControlException {
    this(ccElement, xmlResolver, fileResolver, null);
  }

  public CruiseControlConfig(
      final Element ccElement,
      final XmlResolver xmlResolver,
      final FileResolver fileResolver,
      final CruiseControlController controller)
      throws CruiseControlException {
    this.xmlResolver = xmlResolver;
    this.fileResolver = fileResolver;
    this.controller = controller;
    parse(ccElement);
  }

  private void parse(final Element ccElement) throws CruiseControlException {
    // parse properties and plugins first, so their order in the config file
    // doesn't matter
    for (final Object o : ccElement.getChildren("property")) {
      handleRootProperty((Element) o);
    }
    for (final Object o : ccElement.getChildren("plugin")) {
      handleRootPlugin((Element) o);
    }

    // handle custom properties after plugin registration and before projects
    for (final Object o : ccElement.getChildren()) {
      final Element childElement = (Element) o;
      final String nodeName = childElement.getName();
      if (KNOWN_ROOT_CHILD_NAMES.contains(nodeName)
          || "system".equals(nodeName)
          || isProject(nodeName)) {
        continue;
      }
      if (isCustomPropertiesPlugin(nodeName)) {
        handleCustomRootProperty(childElement);
      }
    }

    for (final Object o : ccElement.getChildren("include.projects")) {
      handleIncludedProjects((Element) o);
    }
    for (final Object o : ccElement.getChildren("dashboard")) {
      handleDashboard((Element) o);
    }

    // other childNodes must be projects or the <system> node
    for (final Object o : ccElement.getChildren()) {
      final Element childElement = (Element) o;
      final String nodeName = childElement.getName();
      if (isProject(nodeName)) {
        handleProject(childElement);
      } else if ("system".equals(nodeName)) {
        add((SystemPlugin) new ProjectXMLHelper().configurePlugin(childElement, false));
      } else if (!KNOWN_ROOT_CHILD_NAMES.contains(nodeName)
          && !customPropertiesPlugins.contains(nodeName)) {
        throw new CruiseControlException("cannot handle child of <" + nodeName + ">");
      }
    }
  }

  private CruiseControlConfig(final Element includedElement, final CruiseControlConfig parent)
      throws CruiseControlException {

    this.controller = parent.controller;
    xmlResolver = parent.xmlResolver;
    fileResolver = parent.fileResolver;
    rootPlugins = PluginRegistry.createRegistry(parent.rootPlugins);
    rootProperties = new HashMap<String, String>(parent.rootProperties);
    templatePluginProperties = new HashMap<String, List>(parent.templatePluginProperties);

    parse(includedElement);
  }

  private void handleIncludedProjects(Element includeElement) {
    String path = includeElement.getAttributeValue("file");
    if (path == null) {
      LOG.warn("include.projects element missing file attribute. Skipping.");
    }
    if (xmlResolver == null) {
      LOG.debug(
          "xmlResolver not available; skipping include.projects element. ok if validating config.");
      return;
    }
    try {
      IncludeProjectsPlugin includeProjects =
          (IncludeProjectsPlugin)
              new ProjectXMLHelper(rootProperties, this.getRootPlugins())
                  .configurePlugin(includeElement, FAIL_UPON_MISSING_PROPERTY);
      add(includeProjects);
    } catch (CruiseControlException e) {
      LOG.error("Exception including file " + path, e);
    }
  }

  private void handleDashboard(Element dashboardElement) throws CruiseControlException {
    DashboardConfigurationPlugin dashboard =
        (DashboardConfigurationPlugin)
            new ProjectXMLHelper(rootProperties, getRootPlugins())
                .configurePlugin(dashboardElement, FAIL_UPON_MISSING_PROPERTY);
    dashboard.setController(controller);
    dashboard.validate();
    dashboard.startPostingToDashboard();
  }

  private boolean isCustomPropertiesPlugin(String nodeName) throws CruiseControlException {
    if (customPropertiesPlugins.contains(nodeName)) {
      return true;
    }

    boolean isPropetiesPlugin =
        rootPlugins.isPluginRegistered(nodeName)
            && PropertiesPlugin.class.isAssignableFrom(rootPlugins.getPluginClass(nodeName));

    if (isPropetiesPlugin) {
      customPropertiesPlugins.add(nodeName);
    }

    return isPropetiesPlugin;
  }

  private boolean isProject(String nodeName) throws CruiseControlException {
    return rootPlugins.isPluginRegistered(nodeName)
        && ProjectInterface.class.isAssignableFrom(rootPlugins.getPluginClass(nodeName));
  }

  private boolean isProjectTemplate(Element pluginElement) {
    String pluginName = pluginElement.getAttributeValue("name");
    String pluginClassName = pluginElement.getAttributeValue("classname");
    if (pluginClassName == null) {
      pluginClassName = rootPlugins.getPluginClassname(pluginName);
    }
    try {
      Class pluginClass = rootPlugins.instanciatePluginClass(pluginClassName, pluginName);
      return ProjectInterface.class.isAssignableFrom(pluginClass);
    } catch (CruiseControlException e) {
      // this is only triggered by tests today, when a class is not
      // loadable.
      // I didn't want to propagate the exception
      // in case something like Distributed CC requires a class to not be
      // loadable locally at this point...
      LOG.warn(
          "Couldn't check if the plugin " + pluginName + " is an instance of ProjectInterface", e);
      return false;
    }
  }

  private void handleRootPlugin(Element pluginElement) throws CruiseControlException {
    String pluginName = pluginElement.getAttributeValue("name");
    if (pluginName == null) {
      LOG.warn("Config contains plugin without a name-attribute, ignoring it");
      return;
    }
    if (isProjectTemplate(pluginElement)) {
      handleNodeProperties(pluginElement, pluginName);
    }
    rootPlugins.register(pluginElement);
  }

  private void handleNodeProperties(final Element pluginElement, final String pluginName) {
    final List<Object> properties = new ArrayList<Object>();
    for (final Object o : pluginElement.getChildren("property")) {
      properties.add(o);
    }
    if (properties.size() > 0) {
      templatePluginProperties.put(pluginName, properties);
    }
    pluginElement.removeChildren("property");
  }

  private void handleRootProperty(final Element childElement) throws CruiseControlException {
    ProjectXMLHelper.registerProperty(rootProperties, childElement, FAIL_UPON_MISSING_PROPERTY);
  }

  private void handleCustomRootProperty(final Element childElement) throws CruiseControlException {
    ProjectXMLHelper.registerCustomProperty(
        rootProperties,
        childElement,
        fileResolver,
        FAIL_UPON_MISSING_PROPERTY,
        PluginRegistry.createRegistry(rootPlugins));
  }

  /**
   * @param project other project to add
   * @throws CruiseControlException when something breaks
   */
  @Description("Add projects defined in other configuration files.")
  public void add(final IncludeProjectsPlugin project) throws CruiseControlException {
    final String file = project.getFile();
    final String path =
        Util.parsePropertiesInString(rootProperties, file, FAIL_UPON_MISSING_PROPERTY);
    LOG.debug("getting included projects from " + path);
    final Element includedElement = xmlResolver.getElement(path);
    final CruiseControlConfig includedConfig = new CruiseControlConfig(includedElement, this);
    final Set<String> includedProjectNames = includedConfig.getProjectNames();
    for (final String name : includedProjectNames) {
      if (projects.containsKey(name)) {
        final String message =
            "Project " + name + " included from " + path + " is a duplicate name. Omitting.";
        LOG.error(message);
      }
      projects.put(name, includedConfig.getProject(name));
    }
  }

  /** @param system system place holder plugin */
  @Description(
      "Currently just a placeholder for the <code>&lt;configuration&gt;</code> element, which in "
          + "its turn is just a placeholder for the <code>&lt;threads&gt;</code> element. We expect that "
          + "in the future, more system-level features can be configured under this "
          + "element.")
  @Cardinality(min = 0, max = 1)
  public void add(final SystemPlugin system) {
    this.system = system;
  }

  /**
   * @param plugin only for gendoc
   * @deprecated exists only for gendoc, should not be called.
   */
  @Description("Registers a classname with an alias.")
  public void add(final PluginPlugin plugin) {
    // FIXME this is empty today for the documentation to be generated properly
    throw new IllegalStateException("GenDoc-only method should not be invoked.");
  }

  /**
   * @param project only for gendoc
   * @deprecated exists only for gendoc, should not be called.
   */
  @Description("Defines a basic unit of work.")
  @Cardinality(min = 1, max = -1)
  public void add(final ProjectInterface project) {
    // FIXME this is empty today for the documentation to be generated properly
    throw new IllegalStateException("GenDoc-only method should not be invoked.");
  }

  /**
   * @param plugin only for gendoc
   * @deprecated exists only for gendoc, should not be called.
   */
  @Description("Defines a name/value pair used in configuration.")
  public void add(final DefaultPropertiesPlugin plugin) {
    // FIXME currently only declared for documentation generation purposes
    throw new IllegalStateException("GenDoc-only method should not be invoked.");
  }

  /**
   * @param dashboard only for gendoc
   * @deprecated exists only for gendoc, should not be called.
   */
  @Description("Configures dashboard-related settings.")
  @Cardinality(min = 0, max = 1)
  public void add(final DashboardConfigurationPlugin dashboard) {
    // FIXME this is empty today for the documentation to be generated properly
    throw new IllegalStateException("GenDoc-only method should not be invoked.");
  }

  private void handleProject(final Element projectElement) throws CruiseControlException {

    final String projectName = getProjectName(projectElement);

    if (projects.containsKey(projectName)) {
      final String duplicateEntriesMessage =
          "Duplicate entries in config file for project name " + projectName;
      throw new CruiseControlException(duplicateEntriesMessage);
    }

    // property handling is a little bit dirty here.
    // we have a set of properties mostly resolved in the rootProperties
    // and a child set of properties
    // it is possible that the rootProperties contain references to child
    // properties
    // in particular the project.name one
    final MapWithParent nonFullyResolvedProjectProperties = new MapWithParent(rootProperties);
    // Register the project's name as a built-in property
    LOG.debug("Setting property \"project.name\" to \"" + projectName + "\".");
    nonFullyResolvedProjectProperties.put("project.name", projectName);

    // handle project templates properties
    final List projectTemplateProperties = templatePluginProperties.get(projectElement.getName());
    if (projectTemplateProperties != null) {
      for (final Object projectTemplateProperty : projectTemplateProperties) {
        final Element element = (Element) projectTemplateProperty;
        ProjectXMLHelper.registerProperty(
            nonFullyResolvedProjectProperties, element, FAIL_UPON_MISSING_PROPERTY);
      }
    }

    // Register any project specific properties
    for (final Object o : projectElement.getChildren("property")) {
      final Element propertyElement = (Element) o;
      ProjectXMLHelper.registerProperty(
          nonFullyResolvedProjectProperties, propertyElement, FAIL_UPON_MISSING_PROPERTY);
    }

    // add the resolved rootProperties to the project's properties
    final Map<String, String> thisProperties = nonFullyResolvedProjectProperties.thisMap;
    for (final String key : rootProperties.keySet()) {
      if (!thisProperties.containsKey(key)) {
        final String value = rootProperties.get(key);
        thisProperties.put(key, Util.parsePropertiesInString(thisProperties, value, false));
      }
    }

    // Parse the entire element tree, expanding all property macros
    ProjectXMLHelper.parsePropertiesInElement(
        projectElement, thisProperties, FAIL_UPON_MISSING_PROPERTY);

    // Register any custom plugins
    final PluginRegistry projectPlugins = PluginRegistry.createRegistry(rootPlugins);
    for (final Object o : projectElement.getChildren("plugin")) {
      final Element element = (Element) o;
      // final PluginPlugin plugin = (PluginPlugin)
      new ProjectXMLHelper().configurePlugin(element, false);
      // projectPlugins.register(plugin);
      projectPlugins.register(element);
      // add(plugin);
    }

    projectElement.removeChildren("property");
    projectElement.removeChildren("plugin");

    LOG.debug("**************** configuring project " + projectName + " *******************");
    ProjectHelper projectHelper =
        new ProjectXMLHelper(thisProperties, projectPlugins, fileResolver, controller);

    final ProjectInterface project;
    try {
      project = (ProjectInterface) projectHelper.configurePlugin(projectElement, false);
    } catch (CruiseControlException e) {
      throw new CruiseControlException("error configuring project " + projectName, e);
    }

    // Why call method that is a no-op, and exists only for gendoc purposes?
    // add(project);

    project.validate();
    LOG.debug("**************** end configuring project " + projectName + " *******************");

    this.projects.put(projectName, project);
    this.projectPluginRegistries.put(projectName, projectPlugins);
  }

  private String getProjectName(final Element childElement) throws CruiseControlException {
    if (!isProject(childElement.getName())) {
      throw new IllegalStateException(
          "Invalid Node <" + childElement.getName() + "> (not a project)");
    }
    final String rawName = childElement.getAttribute("name").getValue();
    return Util.parsePropertiesInString(rootProperties, rawName, false);
  }

  public ProjectInterface getProject(String name) {
    return this.projects.get(name);
  }

  public Set<String> getProjectNames() {
    return Collections.unmodifiableSet(this.projects.keySet());
  }

  public PluginRegistry getRootPlugins() {
    return rootPlugins;
  }

  public PluginRegistry getProjectPlugins(String name) {
    return this.projectPluginRegistries.get(name);
  }

  // Unfortunately it seems like the commons-collection CompositeMap doesn't
  // fit that role
  // at least size is not implemented the way I want it.
  // TODO is there a clean way to do without this?
  private static class MapWithParent implements Map<String, String> {
    private final Map<String, String> parent;
    private final Map<String, String> thisMap;

    MapWithParent(Map<String, String> parent) {
      this.parent = parent;
      this.thisMap = new HashMap<String, String>();
    }

    public int size() {
      int size = thisMap.size();
      if (parent != null) {
        final Set<String> keys = parent.keySet();
        for (final String key : keys) {
          if (!thisMap.containsKey(key)) {
            size++;
          }
        }
      }
      return size;
    }

    public boolean isEmpty() {
      boolean parentIsEmpty = parent == null || parent.isEmpty();
      return parentIsEmpty && thisMap.isEmpty();
    }

    public boolean containsKey(Object key) {
      return thisMap.containsKey(key) || (parent != null && parent.containsKey(key));
    }

    public boolean containsValue(Object value) {
      return thisMap.containsValue(value) || (parent != null && parent.containsValue(value));
    }

    public String get(Object key) {
      String value = thisMap.get(key);
      if (value == null && parent != null) {
        value = parent.get(key);
      }
      return value;
    }

    public String put(String o, String o1) {
      return thisMap.put(o, o1);
    }

    public String remove(Object key) {
      throw new UnsupportedOperationException("'remove' not supported on MapWithParent");
    }

    public void putAll(Map<? extends String, ? extends String> map) {
      thisMap.putAll(map);
    }

    public void clear() {
      throw new UnsupportedOperationException("'clear' not supported on MapWithParent");
    }

    public Set<String> keySet() {
      Set<String> keys = new HashSet<String>(thisMap.keySet());
      if (parent != null) {
        keys.addAll(parent.keySet());
      }
      return keys;
    }

    public Collection<String> values() {
      throw new UnsupportedOperationException("not implemented");
      /*
       * we have to support the Map contract. Back the returned values.
       * Mmmmm
       */
      /*
       * Collection values = thisMap.values(); if (parent != null) { Set
       * keys = parent.keySet(); List parentValues = new ArrayList(); for
       * (Iterator iterator = keys.iterator(); iterator.hasNext();) {
       * String key = (String) iterator.next(); if (!
       * thisMap.containsKey(key)) { parentValues.add(parent.get(key)); } } }
       * return values;
       */
    }

    public Set<Map.Entry<String, String>> entrySet() {
      final Set<Map.Entry<String, String>> entries =
          new HashSet<Map.Entry<String, String>>(thisMap.entrySet());
      if (parent != null) {
        entries.addAll(parent.entrySet());
      }
      return entries;
    }
  }
}
  private void handleProject(final Element projectElement) throws CruiseControlException {

    final String projectName = getProjectName(projectElement);

    if (projects.containsKey(projectName)) {
      final String duplicateEntriesMessage =
          "Duplicate entries in config file for project name " + projectName;
      throw new CruiseControlException(duplicateEntriesMessage);
    }

    // property handling is a little bit dirty here.
    // we have a set of properties mostly resolved in the rootProperties
    // and a child set of properties
    // it is possible that the rootProperties contain references to child
    // properties
    // in particular the project.name one
    final MapWithParent nonFullyResolvedProjectProperties = new MapWithParent(rootProperties);
    // Register the project's name as a built-in property
    LOG.debug("Setting property \"project.name\" to \"" + projectName + "\".");
    nonFullyResolvedProjectProperties.put("project.name", projectName);

    // handle project templates properties
    final List projectTemplateProperties = templatePluginProperties.get(projectElement.getName());
    if (projectTemplateProperties != null) {
      for (final Object projectTemplateProperty : projectTemplateProperties) {
        final Element element = (Element) projectTemplateProperty;
        ProjectXMLHelper.registerProperty(
            nonFullyResolvedProjectProperties, element, FAIL_UPON_MISSING_PROPERTY);
      }
    }

    // Register any project specific properties
    for (final Object o : projectElement.getChildren("property")) {
      final Element propertyElement = (Element) o;
      ProjectXMLHelper.registerProperty(
          nonFullyResolvedProjectProperties, propertyElement, FAIL_UPON_MISSING_PROPERTY);
    }

    // add the resolved rootProperties to the project's properties
    final Map<String, String> thisProperties = nonFullyResolvedProjectProperties.thisMap;
    for (final String key : rootProperties.keySet()) {
      if (!thisProperties.containsKey(key)) {
        final String value = rootProperties.get(key);
        thisProperties.put(key, Util.parsePropertiesInString(thisProperties, value, false));
      }
    }

    // Parse the entire element tree, expanding all property macros
    ProjectXMLHelper.parsePropertiesInElement(
        projectElement, thisProperties, FAIL_UPON_MISSING_PROPERTY);

    // Register any custom plugins
    final PluginRegistry projectPlugins = PluginRegistry.createRegistry(rootPlugins);
    for (final Object o : projectElement.getChildren("plugin")) {
      final Element element = (Element) o;
      // final PluginPlugin plugin = (PluginPlugin)
      new ProjectXMLHelper().configurePlugin(element, false);
      // projectPlugins.register(plugin);
      projectPlugins.register(element);
      // add(plugin);
    }

    projectElement.removeChildren("property");
    projectElement.removeChildren("plugin");

    LOG.debug("**************** configuring project " + projectName + " *******************");
    ProjectHelper projectHelper =
        new ProjectXMLHelper(thisProperties, projectPlugins, fileResolver, controller);

    final ProjectInterface project;
    try {
      project = (ProjectInterface) projectHelper.configurePlugin(projectElement, false);
    } catch (CruiseControlException e) {
      throw new CruiseControlException("error configuring project " + projectName, e);
    }

    // Why call method that is a no-op, and exists only for gendoc purposes?
    // add(project);

    project.validate();
    LOG.debug("**************** end configuring project " + projectName + " *******************");

    this.projects.put(projectName, project);
    this.projectPluginRegistries.put(projectName, projectPlugins);
  }
예제 #29
0
 protected PluginRegistry createPluginRegistry(PluginRegistry parentRegistry) {
   return parentRegistry.createChild(project.getClassLoaderScope().createChild("plugins").lock());
 }
예제 #30
0
 public IPluginModelBase getReferencedModel(IFeaturePlugin reference) {
   IPluginModelBase model = PluginRegistry.findModel(reference.getId());
   return (model != null && model.isEnabled()) ? model : null;
 }