/**
  * Returns the groovy-all-*.jar that is used in the Eclipse project. We know there should only be
  * one specified in the header for org.codehaus.groovy right now.
  *
  * @return Returns the names of the jars that are exported by the org.codehaus.groovy project.
  * @throws BundleException
  */
 public static URL getExportedGroovyAllJar() {
   try {
     Bundle groovyBundle = CompilerUtils.getActiveGroovyBundle();
     if (groovyBundle == null) {
       throw new RuntimeException("Could not find groovy bundle");
     }
     Enumeration<URL> enu = groovyBundle.findEntries("lib", "groovy-all-*.jar", false);
     if (enu == null) {
       // in some versions of the plugin, the groovy-all jar is in the base directory of the
       // plugins
       enu = groovyBundle.findEntries("", "groovy-all-*.jar", false);
     }
     while (enu.hasMoreElements()) {
       URL jar = enu.nextElement();
       if (jar.getFile().indexOf("-sources") == -1
           && jar.getFile().indexOf("-javadoc") == -1
           && jar.getFile().indexOf("-eclipse") == -1) {
         // remove the "reference:/" protocol
         jar = resolve(jar);
         return jar;
       }
     }
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
   throw new RuntimeException("Could not find groovy all jar");
 }
 // Find files in the bundle without triggering resolve of it.
 private Enumeration<URL> findEntries(
     String baseDir, String fileNamePrefix, String fileNameSuffix) {
   Enumeration<URL> res;
   if (bundle.getState() == Bundle.INSTALLED) {
     final Enumeration<String> p = bundle.getEntryPaths(baseDir);
     if (p != null) {
       final Vector<URL> tmp = new Vector<URL>();
       while (p.hasMoreElements()) {
         final String path = p.nextElement();
         final int lastSlash = path.lastIndexOf('/');
         if (lastSlash > 0) {
           final String name = path.substring(lastSlash) + 1;
           if (name.startsWith(fileNamePrefix) && name.endsWith(fileNameSuffix)) {
             tmp.addElement(bundle.getEntry(path));
           }
         }
       }
       res = tmp.elements();
     } else {
       res = null;
     }
   } else {
     res = bundle.findEntries(locBaseDir, fileNamePrefix + "*" + fileNameSuffix, false);
   }
   return res;
 }
  public void initDefaultUsers() {
    Session session = null;
    try {
      session = repository.loginAdministrative(null);
      UserManager userManager = AccessControlUtil.getUserManager(session);

      // Apply default user properties from JSON files.
      Pattern fileNamePattern = Pattern.compile("/users/|\\.json");
      @SuppressWarnings("rawtypes")
      Enumeration entriesEnum = bundle.findEntries("users", "*.json", true);
      while (entriesEnum.hasMoreElements()) {
        Object entry = entriesEnum.nextElement();
        URL jsonUrl = new URL(entry.toString());
        String jsonFileName = jsonUrl.getFile();
        String authorizableId = fileNamePattern.matcher(jsonFileName).replaceAll("");
        Authorizable authorizable = userManager.getAuthorizable(authorizableId);
        if (authorizable != null) {
          applyJsonToAuthorizable(jsonUrl, authorizable, session);
          LOGGER.info("Initialized default authorizable {}", authorizableId);
        } else {
          LOGGER.warn("Configured default authorizable {} not found", authorizableId);
        }
      }
    } catch (RepositoryException e) {
      LOGGER.error("Could not configure default authorizables", e);
    } catch (IOException e) {
      LOGGER.error("Could not configure default authorizables", e);
    } finally {
      if (session != null) {
        session.logout();
      }
    }
  }
Beispiel #4
0
  @Override
  public ResourceKeys findResourceKeys(
      final ApplicationKey applicationKey,
      final String path,
      final String filePattern,
      boolean recurse) {
    ResourceKeys resourceKeys = null;
    final Application application = getActiveApplication(applicationKey);

    if (application != null) {
      Bundle bundle = application.getBundle();

      final Enumeration<URL> entries = bundle.findEntries(path, filePattern, recurse);

      if (entries != null) {
        final List<ResourceKey> resourceKeyList =
            Collections.list(entries)
                .stream()
                .map(resourceUrl -> ResourceKey.from(applicationKey, resourceUrl.getPath()))
                .collect(Collectors.toList());

        resourceKeys = ResourceKeys.from(resourceKeyList);
      }
    }

    if (resourceKeys == null) {
      resourceKeys = ResourceKeys.empty();
    }

    return resourceKeys;
  }
  private Map<String, Properties> getBundleDefaultProperties(long bundleId) throws IOException {
    Bundle bundle = bundleContext.getBundle(bundleId);
    // Find all property files in main bundle directory
    Enumeration<URL> enumeration = bundle.findEntries("", "*.properties", false);
    Map<String, Properties> allDefaultProperties = new LinkedHashMap<>();

    if (enumeration != null) {
      while (enumeration.hasMoreElements()) {
        InputStream is = null;
        URL url = enumeration.nextElement();
        try {
          is = url.openStream();
          Properties defaultBundleProperties = new Properties();
          defaultBundleProperties.load(is);
          if (!url.getFile().isEmpty()) {
            // We want to store plain filename, without unnecessary slash prefix
            allDefaultProperties.put(url.getFile().substring(1), defaultBundleProperties);
          }
        } catch (IOException e) {
          LOGGER.error("Error while reading or retrieving default properties", e);
        } finally {
          IOUtils.closeQuietly(is);
        }
      }
    }
    return allDefaultProperties;
  }
Beispiel #6
0
 public SampleReportsEntry(
     String[] filePattern,
     String entryname,
     String fragmentPath,
     SampleReportsEntry parentEntry,
     boolean isFile) {
   // this( "BIRT Examples", "/samplereports", null, false );
   // //$NON-NLS-1$//$NON-NLS-2$
   this(entryname, fragmentPath, parentEntry, false);
   this.isRoot = true;
   this.displayName = "BIRT Examples"; // $NON-NLS-1$
   // samplesBundle = Platform.getBundle( SAMPLE_REPORTS_HOST );
   if (samplesBundle != null) {
     if (filePattern != null && filePattern.length > 0) {
       for (int i = 0; i < filePattern.length; i++) {
         String[] patterns = filePattern[i].split(";"); // $NON-NLS-1$
         for (int j = 0; j < patterns.length; j++) {
           Enumeration enumeration = samplesBundle.findEntries(fragmentPath, patterns[j], true);
           while (enumeration != null && enumeration.hasMoreElements()) {
             URL element = (URL) enumeration.nextElement();
             String path =
                 element.getPath()
                     + (element.getRef() != null
                         ? "#" //$NON-NLS-1$
                             + element.getRef()
                         : ""); //$NON-NLS-1$
             String[] pathtoken = path.split("/"); // $NON-NLS-1$
             SampleReportsEntry parent = this;
             for (int m = 0; m < pathtoken.length; m++) {
               if (pathtoken[m].equals("")
                   || pathtoken[m].equals(
                       fragmentPath.substring(fragmentPath.indexOf('/') + 1))) // $NON-NLS-1$
               continue;
               SampleReportsEntry child = parent.getChild(pathtoken[m]);
               if (child == null) {
                 child =
                     new SampleReportsEntry(
                         pathtoken[m],
                         (parent.path.equals("/")
                                 ? "" //$NON-NLS-1$//$NON-NLS-2$
                                 : parent.path)
                             + "/" //$NON-NLS-1$
                             + pathtoken[m],
                         parent,
                         m == pathtoken.length - 1);
               }
               parent = child;
             }
           }
         }
       }
     }
   }
 }
 /**
  * finds and returns the extra jars that belong inside the Groovy Classpath Container
  *
  * @return jline, servlet-api, ivy, and commons-cli
  */
 public static URL[] getExtraJarsForClasspath() {
   try {
     Bundle groovyBundle = CompilerUtils.getActiveGroovyBundle();
     Enumeration<URL> enu = groovyBundle.findEntries("lib", "*.jar", false);
     if (enu == null) {
       // in some versions of the plugin, the groovy-all jar is in the
       // base directory of the plugins
       enu = groovyBundle.findEntries("", "*.jar", false);
     }
     List<URL> urls = new ArrayList<URL>(9);
     while (enu.hasMoreElements()) {
       URL jar = enu.nextElement();
       if (!jar.getFile().contains("groovy")) {
         // remove the "reference:/" protocol
         jar = resolve(jar);
         urls.add(jar);
       }
     }
     return urls.toArray(new URL[urls.size()]);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
 public static URL findDSLDFolder() {
   Bundle groovyBundle = CompilerUtils.getActiveGroovyBundle();
   Enumeration<URL> enu = groovyBundle.findEntries(".", "plugin_dsld_support", false);
   if (enu != null && enu.hasMoreElements()) {
     URL folder = enu.nextElement();
     // remove the "reference:/" protocol
     try {
       folder = resolve(folder);
       return folder;
     } catch (IOException e) {
       GroovyCore.logException("Exception when looking for DSLD folder", e);
     }
   }
   return null;
 }
  public URL getResource(String resourceName) {
    if (bundlePath != null) resourceName = bundlePath + resourceName;

    int lastSlash = resourceName.lastIndexOf('/');
    if (lastSlash == -1) return null;

    String path = resourceName.substring(0, lastSlash);
    if (path.length() == 0) path = "/"; // $NON-NLS-1$
    String file = sanitizeEntryName(resourceName.substring(lastSlash + 1));
    Enumeration entryPaths = bundle.findEntries(path, file, false);

    if (entryPaths != null && entryPaths.hasMoreElements()) return (URL) entryPaths.nextElement();

    return null;
  }
  public Set getResourcePaths(String path) {
    if (bundlePath != null) path = bundlePath + path;

    Enumeration entryPaths = bundle.findEntries(path, null, false);
    if (entryPaths == null) return null;

    Set result = new HashSet();
    while (entryPaths.hasMoreElements()) {
      URL entryURL = (URL) entryPaths.nextElement();
      String entryPath = entryURL.getFile();

      if (bundlePath == null) result.add(entryPath);
      else result.add(entryPath.substring(bundlePath.length()));
    }
    return result;
  }
  List<URL> repoUrlList(Bundle bundle) {

    List<URL> entryList = new ArrayList<URL>();

    Enumeration<URL> entryEnum = bundle.findEntries(META_PATH, "*." + EXT, false);

    if (entryEnum == null) {
      return entryList;
    }

    while (entryEnum.hasMoreElements()) {
      entryList.add(entryEnum.nextElement());
    }

    return entryList;
  }
  /**
   * Search the bundle for the given file name.
   *
   * @param fileName The name of the file to find.
   * @return A File object pointing to the requested file or null if the file wasn't found.
   */
  private File findFileInBundle(final String fileName) {
    Bundle bundle = FrameworkUtil.getBundle(classInBundle);
    Enumeration<URL> e = bundle.findEntries(BUNDLE_PATH, fileName, true);

    if (e == null || !e.hasMoreElements()) {
      return null;
    } else {
      try {
        // we found the requested file
        URL url = e.nextElement();
        return new File(FileLocator.toFileURL(url).getFile());
      } catch (IOException ex) {
        LOGGER.info("Could not locate packaged executable", ex);
        return null;
      }
    }
  }
  /** Initializes all plugin stores by inspecting all extensions. */
  public static void init() {
    if (Platform.isRunning()) {
      IExtensionPoint ep = Platform.getExtensionRegistry().getExtensionPoint(PLUGIN_STORE_EP_ID);
      IConfigurationElement[] entries = ep.getConfigurationElements();

      List<URI> existingURIs = new ArrayList<URI>();

      for (int i = 0; i < entries.length; i++) {
        String path = entries[i].getAttribute("folder");
        String bundleID = entries[i].getDeclaringExtension().getNamespaceIdentifier();
        Bundle bundle = Platform.getBundle(bundleID);

        String updateString = entries[i].getAttribute("update");
        boolean update = false;
        if ("true".equals(updateString) || "TRUE".equals(updateString)) {
          update = true;
        }

        if (path != null && bundle != null) {
          String storeURI = "/" + bundleID + "/" + path;
          while (storeURI.endsWith("/")) {
            storeURI = storeURI.substring(0, storeURI.length() - 1);
          }
          registerStore(URI.createPlatformPluginURI(storeURI, true));

          @SuppressWarnings("unchecked")
          Enumeration<URL> urlEnum = bundle.findEntries(path, null, true);
          while (urlEnum.hasMoreElements()) {
            URL url = urlEnum.nextElement();
            String uriString = url.toExternalForm();
            if (!uriString.endsWith("/") && !uriString.contains("/.")) {
              uriString = uriString.substring("bundleentry://".length());
              uriString = uriString.substring(uriString.indexOf("/"));
              uriString = "/" + bundleID + uriString;
              URI uri = URI.createPlatformPluginURI(uriString, true);
              addOrUpdateArtifact(uri, update);
              existingURIs.add(uri);
            }
          }
        }
      }

      removeOldArtifacts(existingURIs);
    }
  }
Beispiel #14
0
 @SuppressWarnings("unchecked")
 private Collection<URL> getBuiltinThemeURLs() {
   ThemePlugin themePlugin = ThemePlugin.getDefault();
   if (themePlugin == null) {
     return Collections.emptyList();
   }
   Bundle bundle = themePlugin.getBundle();
   if (bundle == null) {
     return Collections.emptyList();
   }
   List<URL> collection = new ArrayList<URL>();
   Enumeration<URL> enumeration =
       bundle.findEntries("themes", "*.properties", false); // $NON-NLS-1$ //$NON-NLS-2$
   while (enumeration.hasMoreElements()) {
     collection.add(enumeration.nextElement());
   }
   return collection;
 }
Beispiel #15
0
  public static void copyDirectory(File userDir, String bundleDirName, Bundle bundle) {

    Enumeration files = bundle.findEntries(bundleDirName, "*", true);
    Vector elements = new Vector();
    if (files != null) {
      while (files.hasMoreElements()) {
        URL o = (URL) files.nextElement();
        if (!o.getPath().endsWith("/")) elements.add(o);
      }
    }

    for (int i = 0; i < elements.size(); i++) {
      URL source = (URL) elements.get(i);
      try {
        URLConnection connection = source.openConnection();
        String path = source.getPath();
        String tail = path.substring(bundleDirName.length() + 1);
        File destination = new File(userDir.getAbsolutePath() + "/" + tail);
        if (tail.indexOf(".svn") > -1) {
          continue;
        }
        destination.getParentFile().mkdirs();
        InputStream in = null;
        OutputStream out = null;
        try {
          in = connection.getInputStream();
          out = new BufferedOutputStream(new FileOutputStream(destination));
          byte[] buf = new byte[1024];
          int len;
          while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
          }
        } finally {
          if (in != null) in.close();
          if (out != null) out.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
        // throw new
        // UserException(UserException.ERROR_COPYING_USER_BASE_DIRECTORY);
      }
    }
  }
 /**
  * Finds the template in the plug-in. Returns the template plug-in URI.
  *
  * @param bundleID is the plug-in ID
  * @param relativePath is the relative path of the template in the plug-in
  * @return the template URI
  * @throws IOException
  * @generated
  */
 @SuppressWarnings({"unused"})
 private URI getTemplateURI(String bundleID, IPath relativePath) throws IOException {
   Bundle bundle = Platform.getBundle(bundleID);
   if (bundle == null) {
     // no need to go any further
     return URI.createPlatformResourceURI(
         new Path(bundleID).append(relativePath).toString(), false);
   }
   URL url = bundle.getEntry(relativePath.toString());
   if (url == null && relativePath.segmentCount() > 1) {
     Enumeration<URL> entries = bundle.findEntries("/", "*.emtl", true);
     if (entries != null) {
       String[] segmentsRelativePath = relativePath.segments();
       while (url == null && entries.hasMoreElements()) {
         URL entry = entries.nextElement();
         IPath path = new Path(entry.getPath());
         if (path.segmentCount() > relativePath.segmentCount()) {
           path = path.removeFirstSegments(path.segmentCount() - relativePath.segmentCount());
         }
         String[] segmentsPath = path.segments();
         boolean equals = segmentsPath.length == segmentsRelativePath.length;
         for (int i = 0; equals && i < segmentsPath.length; i++) {
           equals = segmentsPath[i].equals(segmentsRelativePath[i]);
         }
         if (equals) {
           url = bundle.getEntry(entry.getPath());
         }
       }
     }
   }
   URI result;
   if (url != null) {
     result =
         URI.createPlatformPluginURI(
             new Path(bundleID).append(new Path(url.getPath())).toString(), false);
   } else {
     result =
         URI.createPlatformResourceURI(new Path(bundleID).append(relativePath).toString(), false);
   }
   return result;
 }
  @SuppressWarnings("rawtypes")
  @Test
  public void testEEFParsing() {
    result = new StringBuffer();

    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); // $NON-NLS-1$
    Date date = new Date();
    result.append("###############################################\n"); // $NON-NLS-1$
    result.append("# CST Parsing test on EEF - " + dateFormat.format(date) + '\n'); // $NON-NLS-1$
    result.append("###############################################\n"); // $NON-NLS-1$

    Enumeration entries = bundle.findEntries("/", "*.mtl", true); // $NON-NLS-1$ //$NON-NLS-2$
    if (entries != null) {
      while (entries.hasMoreElements()) {
        Object element = entries.nextElement();
        if (element instanceof URL) {
          URL url = (URL) element;
          try {
            result.append("#File: " + url.getPath() + '\n'); // $NON-NLS-1$
            InputStream stream = url.openStream();
            BufferedReader reader =
                new BufferedReader(new InputStreamReader(stream, "UTF-8")); // $NON-NLS-1$
            String line = ""; // $NON-NLS-1$
            StringBuffer sb = new StringBuffer();

            while ((line = reader.readLine()) != null) {
              sb.append(line).append("\n"); // $NON-NLS-1$
            }

            testParsingPerformance(sb);
          } catch (IOException e) {
            fail();
          }
        }
      }

      System.err.println(result.toString());
    } else {
      fail("No entries found"); // $NON-NLS-1$
    }
  }
  /**
   * Finds component descriptors based on descriptor location.
   *
   * @param bundle bundle to search for descriptor files
   * @param descriptorLocation descriptor location
   * @return array of descriptors or empty array if none found
   */
  static URL[] findDescriptors(final Bundle bundle, final String descriptorLocation) {
    if (bundle == null || descriptorLocation == null || descriptorLocation.trim().length() == 0) {
      return new URL[0];
    }

    // for compatibility with previoues versions (<= 1.0.8) use getResource() for non wildcarded
    // entries
    if (descriptorLocation.indexOf("*") == -1) {
      final URL descriptor = bundle.getResource(descriptorLocation);
      if (descriptor == null) {
        return new URL[0];
      }
      return new URL[] {descriptor};
    }

    // split pattern and path
    final int lios = descriptorLocation.lastIndexOf("/");
    final String path;
    final String filePattern;
    if (lios > 0) {
      path = descriptorLocation.substring(0, lios);
      filePattern = descriptorLocation.substring(lios + 1);
    } else {
      path = "/";
      filePattern = descriptorLocation;
    }

    // find the entries
    final Enumeration entries = bundle.findEntries(path, filePattern, false);
    if (entries == null || !entries.hasMoreElements()) {
      return new URL[0];
    }

    // create the result list
    List urls = new ArrayList();
    while (entries.hasMoreElements()) {
      urls.add(entries.nextElement());
    }
    return (URL[]) urls.toArray(new URL[urls.size()]);
  }
 public void start() throws Exception {
   Bundle bundleToScan = bundleContext.getBundle();
   Enumeration<?> findEntries = bundleToScan.findEntries("", "*.class", true);
   if (findEntries == null) {
     LOGGER.error(
         new StringBuilder()
             .append(
                 "We've found an error which you should really give a shot but which does not ")
             .append(
                 "interrupt your runtime. Nevertheless we assume that this one is definitely an ")
             .append(
                 "error so give it a shot! OK, the problem is that you entered the bundle with the ")
             .append(
                 "symbolic name {} the blueprint/spring entry to scan for automount annotations. ")
             .append(
                 "Nevertheless this bundle you would like to have scanned has NO classes! Either ")
             .append(
                 "the anotation is wrong or you messed up something during the build of your bundle!")
             .toString(),
         bundleToScan.getSymbolicName());
     return;
   }
   while (findEntries.hasMoreElements()) {
     String className = calculateClassName((URL) findEntries.nextElement());
     Class<?> candidateClass = bundleToScan.loadClass(className);
     if (!Page.class.isAssignableFrom(candidateClass)) {
       continue;
     }
     @SuppressWarnings("unchecked")
     Class<? extends Page> pageClass = (Class<? extends Page>) candidateClass;
     PaxWicketMountPoint mountPoint = pageClass.getAnnotation(PaxWicketMountPoint.class);
     if (mountPoint != null) {
       DefaultPageMounter mountPointRegistration =
           new DefaultPageMounter(applicationName, bundleContext);
       mountPointRegistration.addMountPoint(mountPoint.mountPoint(), pageClass);
       mountPointRegistration.register();
       mountPointRegistrations.add(mountPointRegistration);
     }
   }
 }
  Enumeration<URL> getEndpointDescriptionURLs(Bundle b) {
    String origDir = getRemoteServicesDir(b);

    // Split origDir into dir and file pattern
    String filePattern = "*.xml";
    String dir;
    if (origDir.endsWith("/")) {
      dir = origDir.substring(0, origDir.length() - 1);
    } else {
      int idx = origDir.lastIndexOf('/');
      if (idx >= 0 & origDir.length() > idx) {
        filePattern = origDir.substring(idx + 1);
        dir = origDir.substring(0, idx);
      } else {
        filePattern = origDir;
        dir = "";
      }
    }

    Enumeration<URL> urls = b.findEntries(dir, filePattern, false);
    return (urls == null) ? Collections.enumeration(new ArrayList<URL>()) : urls;
  }
    /**
     * @param parentSuite
     * @param bundle
     * @return
     */
    private static void collectTests(TestSuite parentSuite, Bundle bundle) {

      Enumeration<URL> entries =
          bundle.findEntries("/", "AllTests.class", true); // $NON-NLS-1$ //$NON-NLS-2$
      if (entries == null || !entries.hasMoreElements()) {
        TestDesignerPlugin.logWarning(
            "No AllTests class in bundle " + bundle.getSymbolicName()); // $NON-NLS-1$
        return;
      }

      TestSuite suite = new TestSuite(bundle.getSymbolicName());

      while (entries.hasMoreElements()) {
        URL element = entries.nextElement();

        try {
          URL url = FileLocator.toFileURL(element);
          String className = convertToClassName(url);

          TestDesignerPlugin.logInfo("Test class name: " + className); // $NON-NLS-1$

          Class<?> klazz = loadClassFromBundle(bundle, className);

          SuiteClasses suiteClasses = klazz.getAnnotation(SuiteClasses.class);
          for (Class<?> suiteKlazz : suiteClasses.value()) {
            if (TestCase.class.isAssignableFrom(suiteKlazz)) {
              addJUnit3TestClass(suite, (Class<? extends TestCase>) suiteKlazz);
            } else {
              addJUnit4TestClass(suite, suiteKlazz);
            }
          }

          parentSuite.addTest(suite);
        } catch (Exception ex) {
          TestDesignerPlugin.logException(ex);
        }
      }
    }
  /**
   * Returns the URL of the resource at the given path in the given bundle.
   *
   * @param bundle The bundle in which we will look for the resource
   * @param pathSeparator The path separator
   * @param resourcePath The path of the resource in the bundle
   * @return the URL of the resource at the given path in the given bundle
   * @throws IOException This will be thrown if we fail to convert bundle-scheme URIs into
   *     file-scheme URIs.
   */
  private static URL getBundleResourceURL(Bundle bundle, String pathSeparator, String resourcePath)
      throws IOException {
    URL resourceURL = null;
    Enumeration<?> emtlFiles = bundle.findEntries(pathSeparator, resourcePath, true);
    if (emtlFiles != null && emtlFiles.hasMoreElements()) {
      resourceURL = (URL) emtlFiles.nextElement();
    }

    // We haven't found the URL of the resource, let's check if we have an absolute URL instead of
    // the
    // name of the resource. Fix for [336109] and [325351].
    if (resourceURL == null) {
      Enumeration<?> resources = bundle.getResources(resourcePath);
      if (resources != null && resources.hasMoreElements()) {
        resourceURL = (URL) resources.nextElement();
      }
    }

    // This can only be a bundle-scheme URL if we found the URL. Convert it to file or jar scheme
    if (resourceURL != null) {
      resourceURL = FileLocator.resolve(resourceURL);
    }
    return resourceURL;
  }
  /** Final pass - create connector infos. */
  private List<ConnectorInfo> createConnectorInfo(
      Bundle parsed, List<ManifestEntry> manifestEnties) {
    List<ConnectorInfo> rv = new ArrayList<ConnectorInfo>();
    Enumeration<URL> classFiles = parsed.findEntries("/", "*.class", true);
    List<URL> propertyFiles = Collections.list(parsed.findEntries("/", "*.properties", true));

    String frameworkVersion = null;
    String bundleName = null;
    String bundleVersion = null;

    for (ManifestEntry entry : manifestEnties) {
      if (ConnectorManifestScanner.ATT_FRAMEWORK_VERSION.equals(entry.getKey())) {
        frameworkVersion = entry.getValue();
      } else if (ConnectorManifestScanner.ATT_BUNDLE_NAME.equals(entry.getKey())) {
        bundleName = entry.getValue();
      } else if (ConnectorManifestScanner.ATT_BUNDLE_VERSION.equals(entry.getKey())) {
        bundleVersion = entry.getValue();
      }
    }

    if (FrameworkUtil.getFrameworkVersion().compareTo(Version.parse(frameworkVersion)) < 0) {
      String message =
          "Bundle "
              + parsed.getLocation()
              + " requests an unrecognized framework version "
              + frameworkVersion
              + " but available is "
              + FrameworkUtil.getFrameworkVersion().getVersion();
      throw new ConfigurationException(message);
    }

    if (StringUtil.isBlank(bundleName) || StringUtil.isBlank(bundleVersion)) {
      return rv;
    }

    while (classFiles.hasMoreElements()) {

      Class<?> connectorClass = null;
      ConnectorClass options = null;
      String name = classFiles.nextElement().getFile();

      String className = name.substring(1, name.length() - ".class".length());
      className = className.replace('/', '.');
      try {
        connectorClass = parsed.loadClass(className);
        options = connectorClass.getAnnotation(ConnectorClass.class);
      } catch (Throwable e) {
        // probe for the class. this might not be an error since it
        // might be from a bundle
        // fragment ( a bundle only included by other bundles ).
        // However, we should definitely warn
        logger.warn(
            "Unable to load class {} from bundle {}. Class will be ignored and will not be listed in list of connectors.",
            new Object[] {className, parsed.getLocation()},
            e);
      }

      if (connectorClass != null && options != null) {
        if (!Connector.class.isAssignableFrom(connectorClass)) {
          throw new ConfigurationException(
              "Class " + connectorClass + " does not implement " + Connector.class.getName());
        }
        final LocalConnectorInfoImpl info = new LocalConnectorInfoImpl();
        info.setConnectorClass(connectorClass.asSubclass(Connector.class));
        try {
          info.setConnectorConfigurationClass(options.configurationClass());
          info.setConnectorDisplayNameKey(options.displayNameKey());
          info.setConnectorCategoryKey(options.categoryKey());
          info.setConnectorKey(
              new ConnectorKey(bundleName, bundleVersion, connectorClass.getName()));
          ConnectorMessagesImpl messages =
              loadMessageCatalog(propertyFiles, parsed, info.getConnectorClass());
          info.setMessages(messages);
          info.setDefaultAPIConfiguration(createDefaultAPIConfiguration(info));
          rv.add(info);
        } catch (final NoClassDefFoundError e) {
          logger.warn(
              "Unable to load configuration class of connector {} from bundle {}. Class will be ignored and will not be listed in list of connectors.",
              logger.isDebugEnabled()
                  ? new Object[] {connectorClass, parsed.getLocation(), e}
                  : new Object[] {connectorClass, parsed.getLocation()});
        } catch (final TypeNotPresentException e) {
          logger.warn(
              "Unable to load configuration class of connector {} from bundle {}. Class will be ignored and will not be listed in list of connectors.",
              logger.isDebugEnabled()
                  ? new Object[] {connectorClass, parsed.getLocation(), e}
                  : new Object[] {connectorClass, parsed.getLocation()});
        }
      }
    }
    return rv;
  }
Beispiel #24
0
  private static void initializeLautRunner() {
    String lautRunnerPath = System.getProperty(LAUT_PATH);

    if (lautRunnerPath != null) {
      File lautRunnerFile = new File(lautRunnerPath);

      if (!lautRunnerFile.exists()) {
        lautRunnerPath = null;
      }
    }

    if (lautRunnerPath == null) {
      try {
        final Bundle lautRunnerBundle = AlloyCore.getDefault().getBundle();
        URL lautUrl = null;

        if (lautRunnerBundle == null) {
          AlloyCore.logError("Unable to find laut bundle.");
        } else {
          final Enumeration<URL> lautEntries =
              lautRunnerBundle.findEntries("/" + LAUT_ENTRY, "/", false);

          if (lautEntries == null || !lautEntries.hasMoreElements()) {
            final Enumeration<URL> lautZipEntries =
                lautRunnerBundle.findEntries("/", LAUT_ZIP, false);

            if (lautZipEntries != null && lautZipEntries.hasMoreElements()) {
              final File lautZipFile =
                  new File(FileLocator.toFileURL(lautZipEntries.nextElement()).getFile());

              final File lautBundleDir = lautZipFile.getParentFile();

              File lautDir = new File(lautBundleDir, LAUT_ENTRY);

              if (!lautBundleDir.canWrite()) {
                lautDir = AlloyCore.getDefault().getStateLocation().append(LAUT_ENTRY).toFile();

                FileUtil.deleteDir(lautDir, true);
              }

              ZipUtil.unzip(lautZipFile, lautDir.getParentFile());

              new File(lautBundleDir, "laut").renameTo(lautDir);

              final Enumeration<URL> lautPathEntries =
                  lautRunnerBundle.findEntries("/" + LAUT_ENTRY, "/", false);
              lautUrl = lautPathEntries.nextElement();
            }
          } else {
            lautUrl = lautEntries.nextElement();
          }

          if (lautUrl != null) {
            final File lautRunnerDir = new File(FileLocator.toFileURL(lautUrl).getFile());
            final String lautRunnerDirPath = lautRunnerDir.getAbsolutePath();

            System.setProperty(LAUT_PATH, lautRunnerDirPath);
            setSDKExecutableFlags(new Path(lautRunnerDirPath));
          }
        }
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
  /** @see WebXmlParser#parse(InputStream) */
  public WebApp parse(final Bundle bundle, final InputStream inputStream) {
    final WebApp webApp = new WebApp(); // changed to final because of inner
    // class.
    try {
      final Element rootElement = getRootElement(inputStream);
      if (rootElement != null) {
        // webApp = new WebApp();
        // web-app attributes
        String version = getAttribute(rootElement, "version");
        Integer majorVersion = null;
        if (version != null && !version.isEmpty() && version.length() > 2) {
          LOG.debug("version found in web.xml - " + version);
          try {
            majorVersion = Integer.parseInt(version.split("\\.")[0]);
          } catch (NumberFormatException nfe) {
            // munch do nothing here stay with null therefore
            // annotation scanning is disabled.
          }
        } else if (version != null && !version.isEmpty() && version.length() > 0) {
          try {
            majorVersion = Integer.parseInt(version);
          } catch (NumberFormatException e) {
            // munch do nothing here stay with null....
          }
        }
        Boolean metaDataComplete =
            Boolean.parseBoolean(getAttribute(rootElement, "metadata-complete", "false"));
        webApp.setMetaDataComplete(metaDataComplete);
        LOG.debug("metadata-complete is: " + metaDataComplete);
        // web-app elements
        webApp.setDisplayName(getTextContent(getChild(rootElement, "display-name")));
        parseContextParams(rootElement, webApp);
        parseSessionConfig(rootElement, webApp);
        parseServlets(rootElement, webApp);
        parseFilters(rootElement, webApp);
        parseListeners(rootElement, webApp);
        parseErrorPages(rootElement, webApp);
        parseWelcomeFiles(rootElement, webApp);
        parseMimeMappings(rootElement, webApp);
        parseSecurity(rootElement, webApp);

        LOG.debug("scanninf for ServletContainerInitializers");

        ServiceLoader<ServletContainerInitializer> serviceLoader =
            ServiceLoader.load(
                ServletContainerInitializer.class, bundle.getClass().getClassLoader());
        if (serviceLoader != null) {
          LOG.debug("ServletContainerInitializers found");
          while (serviceLoader.iterator().hasNext()) {
            // for (ServletContainerInitializer service :
            // serviceLoader) {
            ServletContainerInitializer service = null;
            try {
              bundle.loadClass(ServletContainerInitializer.class.getName());
              Object obj = serviceLoader.iterator().next();
              if (obj instanceof ServletContainerInitializer)
                service = (ServletContainerInitializer) obj;
              else continue;
            } catch (ServiceConfigurationError e) {
              LOG.error("ServiceConfigurationError loading ServletContainerInitializer", e);
              continue;
            } catch (ClassNotFoundException e) {
              LOG.error("ServiceConfigurationError loading ServletContainerInitializer", e);
              continue;
            }
            WebAppServletContainerInitializer webAppServletContainerInitializer =
                new WebAppServletContainerInitializer();
            webAppServletContainerInitializer.setServletContainerInitializer(service);
            if (!webApp.getMetaDataComplete() && majorVersion != null && majorVersion >= 3) {
              HandlesTypes annotation = service.getClass().getAnnotation(HandlesTypes.class);
              Class[] classes;
              if (annotation != null) {
                // add annotated classes to service
                classes = annotation.value();
                webAppServletContainerInitializer.setClasses(classes);
              }
            }
            webApp.addServletContainerInitializer(webAppServletContainerInitializer);
          }
        }

        if (!webApp.getMetaDataComplete() && majorVersion != null && majorVersion >= 3) {
          LOG.debug("metadata-complete is either false or not set");

          LOG.debug("scanning for annotated classes");
          Enumeration<?> clazzes = bundle.findEntries("/", "*.class", true);

          for (; clazzes.hasMoreElements(); ) {
            URL clazzUrl = (URL) clazzes.nextElement();
            Class<?> clazz;
            String clazzFile = clazzUrl.getFile();
            LOG.debug("Class file found at :" + clazzFile);
            if (clazzFile.startsWith("/WEB-INF/classes"))
              clazzFile = clazzFile.replaceFirst("/WEB-INF/classes", "");
            else if (clazzFile.startsWith("/WEB-INF/lib"))
              clazzFile = clazzFile.replaceFirst("/WEB-INF/lib", "");
            String clazzName =
                clazzFile.replaceAll("/", ".").replaceAll(".class", "").replaceFirst(".", "");
            try {
              clazz = bundle.loadClass(clazzName);
            } catch (ClassNotFoundException e) {
              LOG.debug("Class {} not found", clazzName);
              continue;
            }
            if (clazz.isAnnotationPresent(WebServlet.class)) {
              LOG.debug("found WebServlet annotation on class: " + clazz);
              WebServletAnnotationScanner annonScanner =
                  new WebServletAnnotationScanner(bundle, clazz.getCanonicalName());
              annonScanner.scan(webApp);
            } else if (clazz.isAnnotationPresent(WebFilter.class)) {
              LOG.debug("found WebFilter annotation on class: " + clazz);
              WebFilterAnnotationScanner filterScanner =
                  new WebFilterAnnotationScanner(bundle, clazz.getCanonicalName());
              filterScanner.scan(webApp);
            } else if (clazz.isAnnotationPresent(WebListener.class)) {
              LOG.debug("found WebListener annotation on class: " + clazz);
              addWebListener(webApp, clazz.getSimpleName());
            }
          }
          LOG.debug("class scanning done");
        }

        // special handling for finding JSF Context listeners wrapped in
        // *.tld files
        Enumeration tldEntries = bundle.getResources("*.tld");
        // Enumeration tldEntries = bundle.findEntries("/", "*.tld",
        // true);
        while (tldEntries != null && tldEntries.hasMoreElements()) {
          URL url = (URL) tldEntries.nextElement();
          Element rootTld = getRootElement(url.openStream());
          if (rootTld != null) {
            parseListeners(rootTld, webApp);
          }
        }

      } else {
        LOG.warn("The parsed web.xml does not have a root element");
        return null;
      }
    } catch (ParserConfigurationException ignore) {
      LOG.error("Cannot parse web.xml", ignore);
    } catch (IOException ignore) {
      LOG.error("Cannot parse web.xml", ignore);
    } catch (SAXException ignore) {
      LOG.error("Cannot parse web.xml", ignore);
    }
    return webApp;
  }
  /**
   * Registers the namespace plugin handler if this bundle defines handler mapping or schema mapping
   * resources.
   *
   * <p>This method considers only the bundle space and not the class space.
   *
   * @param bundle target bundle
   * @param isLazyBundle indicator if the bundle analyzed is lazily activated
   */
  public void maybeAddNamespaceHandlerFor(Bundle bundle, boolean isLazyBundle) {
    // Ignore system bundle
    if (OsgiBundleUtils.isSystemBundle(bundle)) {
      return;
    }

    // Ignore non-wired Spring DM bundles
    if ("org.springframework.osgi.core".equals(bundle.getSymbolicName())
        && !bundle.equals(BundleUtils.getDMCoreBundle(context))) {
      return;
    }

    boolean debug = log.isDebugEnabled();
    boolean trace = log.isTraceEnabled();
    // FIXME: Blueprint uber bundle temporary hack
    // since embedded libraries are not discovered by findEntries and inlining them doesn't work
    // (due to resource classes such as namespace handler definitions)
    // we use getResource

    boolean hasHandlers = false, hasSchemas = false;

    if (trace) {
      log.trace("Inspecting bundle " + bundle + " for Spring namespaces");
    }
    // extender/RFC 124 bundle
    if (context.getBundle().equals(bundle)) {

      try {
        Enumeration<?> handlers = bundle.getResources(META_INF + SPRING_HANDLERS);
        Enumeration<?> schemas = bundle.getResources(META_INF + SPRING_SCHEMAS);

        hasHandlers = handlers != null;
        hasSchemas = schemas != null;

        if (hasHandlers && debug) {
          log.debug("Found namespace handlers: " + Collections.list(schemas));
        }
      } catch (IOException ioe) {
        log.warn("Cannot discover own namespaces", ioe);
      }
    } else {
      hasHandlers = bundle.findEntries(META_INF, SPRING_HANDLERS, false) != null;
      hasSchemas = bundle.findEntries(META_INF, SPRING_SCHEMAS, false) != null;
    }

    // if the bundle defines handlers
    if (hasHandlers) {

      if (trace) log.trace("Bundle " + bundle + " provides Spring namespace handlers...");

      if (isLazyBundle) {
        this.namespacePlugins.addPlugin(bundle, isLazyBundle, true);
      } else {
        // check type compatibility between the bundle's and spring-extender's spring version
        if (hasCompatibleNamespaceType(bundle)) {
          this.namespacePlugins.addPlugin(bundle, isLazyBundle, false);
        } else {
          if (debug)
            log.debug(
                "Bundle ["
                    + OsgiStringUtils.nullSafeNameAndSymName(bundle)
                    + "] declares namespace handlers but is not compatible with extender ["
                    + extenderInfo
                    + "]; ignoring...");
        }
      }
    } else {
      // bundle declares only schemas, add it though the handlers might not be compatible...
      if (hasSchemas) {
        this.namespacePlugins.addPlugin(bundle, isLazyBundle, false);
        if (trace) log.trace("Bundle " + bundle + " provides Spring schemas...");
      }
    }
  }
  /**
   * Constructs a new <code>ExtenderConfiguration</code> instance. Locates the extender
   * configuration, creates an application context which will returned the extender items.
   *
   * @param bundleContext extender OSGi bundle context
   */
  public ExtenderConfiguration(BundleContext bundleContext, Log log) {
    this.log = log;
    Bundle bundle = bundleContext.getBundle();
    Properties properties = new Properties(createDefaultProperties());

    Enumeration<?> enm = bundle.findEntries(EXTENDER_CFG_LOCATION, XML_PATTERN, false);

    if (enm == null) {
      log.info("No custom extender configuration detected; using defaults...");

      synchronized (lock) {
        taskExecutor = createDefaultTaskExecutor();
        shutdownTaskExecutor = createDefaultShutdownTaskExecutor();
        eventMulticaster = createDefaultEventMulticaster();
        contextCreator = createDefaultApplicationContextCreator();
        contextEventListener = createDefaultApplicationContextListener();
      }
      classLoader = BundleDelegatingClassLoader.createBundleClassLoaderFor(bundle);
    } else {
      String[] configs = copyEnumerationToList(enm);

      log.info(
          "Detected extender custom configurations at " + ObjectUtils.nullSafeToString(configs));
      // create OSGi specific XML context
      ConfigurableOsgiBundleApplicationContext extenderAppCtx =
          new OsgiBundleXmlApplicationContext(configs);
      extenderAppCtx.setBundleContext(bundleContext);
      extenderAppCtx.refresh();

      synchronized (lock) {
        extenderConfiguration = extenderAppCtx;
        // initialize beans
        taskExecutor =
            extenderConfiguration.containsBean(TASK_EXECUTOR_NAME)
                ? (TaskExecutor)
                    extenderConfiguration.getBean(TASK_EXECUTOR_NAME, TaskExecutor.class)
                : createDefaultTaskExecutor();

        shutdownTaskExecutor =
            extenderConfiguration.containsBean(SHUTDOWN_TASK_EXECUTOR_NAME)
                ? (TaskExecutor)
                    extenderConfiguration.getBean(SHUTDOWN_TASK_EXECUTOR_NAME, TaskExecutor.class)
                : createDefaultShutdownTaskExecutor();

        eventMulticaster =
            extenderConfiguration.containsBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)
                ? (OsgiBundleApplicationContextEventMulticaster)
                    extenderConfiguration.getBean(
                        APPLICATION_EVENT_MULTICASTER_BEAN_NAME,
                        OsgiBundleApplicationContextEventMulticaster.class)
                : createDefaultEventMulticaster();

        contextCreator =
            extenderConfiguration.containsBean(CONTEXT_CREATOR_NAME)
                ? (OsgiApplicationContextCreator)
                    extenderConfiguration.getBean(
                        CONTEXT_CREATOR_NAME, OsgiApplicationContextCreator.class)
                : createDefaultApplicationContextCreator();

        contextEventListener =
            extenderConfiguration.containsBean(CONTEXT_LISTENER_NAME)
                ? (OsgiBundleApplicationContextListener)
                    extenderConfiguration.getBean(
                        CONTEXT_LISTENER_NAME, OsgiBundleApplicationContextListener.class)
                : createDefaultApplicationContextListener();
      }

      // get post processors
      postProcessors.addAll(
          extenderConfiguration.getBeansOfType(OsgiBeanFactoryPostProcessor.class).values());

      // get dependency factories
      dependencyFactories.addAll(
          extenderConfiguration.getBeansOfType(OsgiServiceDependencyFactory.class).values());

      classLoader = extenderConfiguration.getClassLoader();
      // extender properties using the defaults as backup
      if (extenderConfiguration.containsBean(PROPERTIES_NAME)) {
        Properties customProperties =
            (Properties) extenderConfiguration.getBean(PROPERTIES_NAME, Properties.class);
        Enumeration<?> propertyKey = customProperties.propertyNames();
        while (propertyKey.hasMoreElements()) {
          String property = (String) propertyKey.nextElement();
          properties.setProperty(property, customProperties.getProperty(property));
        }
      }
    }

    synchronized (lock) {
      shutdownWaitTime = getShutdownWaitTime(properties);
      dependencyWaitTime = getDependencyWaitTime(properties);
      processAnnotation = getProcessAnnotations(properties);
    }

    // load default dependency factories
    addDefaultDependencyFactories();

    // allow post processing
    contextCreator = postProcess(contextCreator);
  }