1   package com.atlassian.plugin.osgi.factory.transform.stage;
2   
3   import com.atlassian.plugin.osgi.factory.transform.PluginTransformationException;
4   import com.atlassian.plugin.osgi.factory.transform.TransformContext;
5   import com.atlassian.plugin.osgi.factory.transform.TransformStage;
6   import org.apache.commons.logging.Log;
7   import org.apache.commons.logging.LogFactory;
8   import org.dom4j.Attribute;
9   import org.dom4j.DocumentHelper;
10  import org.dom4j.XPath;
11  
12  import java.util.List;
13  
14  /**
15   * Scans the plugin descriptor for any "class" attribute, and ensures that it will be imported, if appropriate.
16   *
17   * @since 2.2.0
18   */
19  public class ScanDescriptorForHostClassesStage implements TransformStage
20  {
21      private static final Log log = LogFactory.getLog(ScanDescriptorForHostClassesStage.class);
22  
23      public void execute(TransformContext context) throws PluginTransformationException
24      {
25          XPath xpath = DocumentHelper.createXPath("//@class");
26          List<Attribute> attributes = xpath.selectNodes(context.getDescriptorDocument());
27          for (Attribute attr : attributes)
28          {
29              String className = attr.getValue();
30              int dotpos = className.lastIndexOf(".");
31              if (dotpos > -1)
32              {
33                  String pkg = className.substring(0, dotpos);
34                  String pkgPath = pkg.replace('.', '/') + '/';
35  
36                  // Only add an import if the system exports it and the plugin isn't using the package
37                  if (context.getSystemExports().isExported(pkg))
38                  {
39                      if (context.getPluginArtifact().doesResourceExist(pkgPath))
40                      {
41                          log.warn("The plugin '" + context.getPluginArtifact().toString() + "' uses a package '" +
42                                  pkg + "' that is also exported by the application.  It is highly recommended that the " +
43                                  "plugin use its own packages.");
44                      }
45                      else
46                      {
47                          context.getExtraImports().add(pkg);
48                      }
49                  }
50              }
51          }
52      }
53  }