下面列出了org.osgi.framework.Bundle#findEntries ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private List<Class> allPossibleCandidateClassesInBundle(Bundle bundle) {
List<Class> candidateClasses = new ArrayList<>();
Enumeration<URL> entries = bundle.findEntries("/", "*.class", true);
while (entries.hasMoreElements()) {
String entryPath = entries.nextElement().getFile();
if (isInvalidPath(entryPath)) {
continue;
}
Class<?> candidateClass = loadClass(bundle, entryPath);
if (candidateClass != null && isValidClass(candidateClass)) {
candidateClasses.add(candidateClass);
}
}
return candidateClasses;
}
private Collection<URL> getBuiltinThemeURLs()
{
ThemePlugin themePlugin = ThemePlugin.getDefault();
if (themePlugin == null)
{
return Collections.emptyList();
}
Bundle bundle = themePlugin.getBundle();
if (bundle == null)
{
return Collections.emptyList();
}
ArrayList<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());
}
collection.trimToSize();
return collection;
}
public Set<String> getUIResourcePaths(String name) {
Set<String> result = new HashSet<String>();
//Searching the resourceBundle for the given bundle resource paths.
String resourcePath = CarbonUIUtil.getBundleResourcePath(name);
Bundle resourceBundle = bundleResourceMap.get(resourcePath);
if (resourceBundle != null) {
Enumeration e = resourceBundle.findEntries(bundleResourcePath + name, null, false);
if (e != null) {
while (e.hasMoreElements()) {
URL entryURL = (URL) e.nextElement();
result.add(entryURL.getFile().substring(bundleResourcePath.length()));
}
}
}
return result;
}
@SuppressWarnings({ "rawtypes" })
private void addEntries(Bundle bundle, String path, String filePattern, List<URL> pathList) {
Enumeration e = bundle.findEntries(path, filePattern, false);
while (e != null && e.hasMoreElements()) {
URL u = (URL) e.nextElement();
URL override = getOverrideURL(bundle, u, path);
if (override == null) {
pathList.add(u);
} else {
pathList.add(override);
}
}
}
private static boolean isResolved(Bundle b) {
if (b.getState() == Bundle.INSTALLED) {
// try to ask for a known resource which is known to resolve
// the bundle
b.findEntries("META-INF", "MANIFEST.MF", false); // NOI18N
}
return b.getState() != Bundle.INSTALLED;
}
public static URL getResourceURL(Bundle bundle, String path) {
int fileNameIndex = path.lastIndexOf('/');
String fileName = path.substring(fileNameIndex+1);
path = path.substring(0, fileNameIndex+1);
// see http://www.osgi.org/javadoc/r4v42/org/osgi/framework/Bundle.html
// #findEntries%28java.lang.String,%20java.lang.String,%20boolean%29
Enumeration<?> urls = bundle.findEntries(path, fileName, false/*recursive*/);
if( null != urls && urls.hasMoreElements() ){
URL url = (URL) urls.nextElement();
if( null != url ){
return url;
}
}
return null; // no match, 404 not found.
}
/**
* This method provides common functionality for {@link ModuleTypeProvider} and {@link TemplateProvider} to process
* the bundles. For {@link RuleResourceBundleImporter} this method is overridden.
* <p>
* Checks for availability of the needed {@link Parser}. If it is not available - the bundle is added into
* {@link #waitingProviders} and the execution of the method ends.
* <p>
* If it is available, the execution of the method continues with checking if the version of the bundle is changed.
* If the version is changed - removes persistence of old variants of the objects, provided by this bundle.
* <p>
* Continues with loading the new version of these objects. If this bundle is added for the very first time, only
* loads the provided objects.
* <p>
* The loading can fail because of {@link IOException}.
*
* @param bundle it is a {@link Bundle} which has to be processed, because it provides resources for automation
* objects.
*/
protected void processAutomationProvider(Bundle bundle) {
Enumeration<URL> urlEnum = null;
try {
if (bundle.getState() != Bundle.UNINSTALLED) {
urlEnum = bundle.findEntries(path, null, true);
}
} catch (IllegalStateException e) {
logger.debug("Can't read from resource of bundle with ID {}. The bundle is uninstalled.",
bundle.getBundleId(), e);
processAutomationProviderUninstalled(bundle);
}
Vendor vendor = new Vendor(bundle.getSymbolicName(), bundle.getVersion().toString());
List<String> previousPortfolio = getPreviousPortfolio(vendor);
List<String> newPortfolio = new LinkedList<String>();
if (urlEnum != null) {
while (urlEnum.hasMoreElements()) {
URL url = urlEnum.nextElement();
if (url.getPath().endsWith(File.separator)) {
continue;
}
String parserType = getParserType(url);
Parser<E> parser = parsers.get(parserType);
updateWaitingProviders(parser, bundle, url);
if (parser != null) {
Set<E> parsedObjects = parseData(parser, url, bundle);
if (parsedObjects != null && !parsedObjects.isEmpty()) {
addNewProvidedObjects(newPortfolio, previousPortfolio, parsedObjects);
}
}
}
putNewPortfolio(vendor, newPortfolio);
}
removeUninstalledObjects(previousPortfolio, newPortfolio);
}
/**
* Initialization of RCP internal location of standard modules
*/
private void initInternalLibraryPath()
{
try
{
final Bundle bundle = Platform.getBundle(BuiltInModuleHelper.BUNDLE_ID);
Enumeration<URL> installedInternalModules = bundle
.findEntries(BuiltInModuleHelper.STANDARD_MODULES_PATH, BuiltInModuleHelper.STANDARD_MODULES, true);
if (installedInternalModules == null) {
// Toolbox is running from inside Eclipse (dev mode) and the StandardModules are
// found in a slightly different location.
installedInternalModules = bundle.findEntries(
File.separator + "src" + File.separator + BuiltInModuleHelper.STANDARD_MODULES_PATH,
BuiltInModuleHelper.STANDARD_MODULES, true);
}
while (installedInternalModules.hasMoreElements())
{
final URL library = installedInternalModules.nextElement();
if (library != null)
{
// add external (resolved) URL
final String path = FileLocator.resolve(library).getPath();
libraryPathEntries.add(path);
}
}
} catch (IOException e)
{
e.printStackTrace();
}
}
/**
* This method provides common functionality for {@link ModuleTypeProvider} and {@link TemplateProvider} to process
* the bundles. For {@link RuleResourceBundleImporter} this method is overridden.
* <p>
* Checks for availability of the needed {@link Parser}. If it is not available - the bundle is added into
* {@link #waitingProviders} and the execution of the method ends.
* <p>
* If it is available, the execution of the method continues with checking if the version of the bundle is changed.
* If the version is changed - removes persistence of old variants of the objects, provided by this bundle.
* <p>
* Continues with loading the new version of these objects. If this bundle is added for the very first time, only
* loads the provided objects.
* <p>
* The loading can fail because of {@link IOException}.
*
* @param bundle it is a {@link Bundle} which has to be processed, because it provides resources for automation
* objects.
*/
protected void processAutomationProvider(Bundle bundle) {
Enumeration<URL> urlEnum = null;
try {
if (bundle.getState() != Bundle.UNINSTALLED) {
urlEnum = bundle.findEntries(path, null, true);
}
} catch (IllegalStateException e) {
logger.debug("Can't read from resource of bundle with ID {}. The bundle is uninstalled.",
bundle.getBundleId(), e);
processAutomationProviderUninstalled(bundle);
}
Vendor vendor = new Vendor(bundle.getSymbolicName(), bundle.getVersion().toString());
List<String> previousPortfolio = getPreviousPortfolio(vendor);
List<String> newPortfolio = new LinkedList<>();
if (urlEnum != null) {
while (urlEnum.hasMoreElements()) {
URL url = urlEnum.nextElement();
if (url.getPath().endsWith(File.separator)) {
continue;
}
String parserType = getParserType(url);
Parser<E> parser = parsers.get(parserType);
updateWaitingProviders(parser, bundle, url);
if (parser != null) {
Set<E> parsedObjects = parseData(parser, url, bundle);
if (!parsedObjects.isEmpty()) {
addNewProvidedObjects(newPortfolio, previousPortfolio, parsedObjects);
}
}
}
putNewPortfolio(vendor, newPortfolio);
}
removeUninstalledObjects(previousPortfolio, newPortfolio);
}
/**
* This method provides functionality for processing the bundles with rule resources.
* <p>
* Checks for availability of the needed {@link Parser} and for availability of the rules managing service. If one
* of them is not available - the bundle is added into {@link #waitingProviders} and the execution of the method
* ends.
* <p>
* Continues with loading the rules. If a rule already exists, it is updated, otherwise it is added.
* <p>
* The loading can fail because of {@link IOException}.
*
* @param bundle
* it is a {@link Bundle} which has to be processed, because it provides resources for automation rules.
*/
@Override
protected void processAutomationProvider(Bundle bundle) {
Vendor vendor = new Vendor(bundle.getSymbolicName(), bundle.getVersion().toString());
logger.debug("Parse rules from bundle '{}' ", bundle.getSymbolicName());
Enumeration<URL> urlEnum = null;
try {
if (bundle.getState() != Bundle.UNINSTALLED) {
urlEnum = bundle.findEntries(path, null, true);
}
} catch (IllegalStateException e) {
logger.debug("Can't read from resource of bundle with ID {}. The bundle is uninstalled.",
bundle.getBundleId(), e);
processAutomationProviderUninstalled(bundle);
}
if (urlEnum != null) {
while (urlEnum.hasMoreElements()) {
URL url = urlEnum.nextElement();
if (getPreviousPortfolio(vendor) != null
&& (waitingProviders.get(bundle) == null || !waitingProviders.get(bundle).contains(url))) {
return;
}
if (url.getPath().endsWith(File.separator)) {
continue;
}
String parserType = getParserType(url);
Parser<Rule> parser = parsers.get(parserType);
updateWaitingProviders(parser, bundle, url);
if (parser != null) {
Set<Rule> parsedObjects = parseData(parser, url, bundle);
if (!parsedObjects.isEmpty()) {
addNewProvidedObjects(Collections.emptyList(), Collections.emptyList(), parsedObjects);
}
}
}
putNewPortfolio(vendor, Collections.emptyList());
}
}
private void processBundle(Bundle bundle) {
if (isNotFragment(bundle)) {
Enumeration<URL> xmlDocumentPaths = bundle.findEntries(xmlDirectory, "*.xml", true);
if (xmlDocumentPaths != null) {
Collection<URL> filteredPaths = filterPatches(xmlDocumentPaths, bundle);
parseDocuments(bundle, filteredPaths);
}
}
finishBundle(bundle);
}
private void processBundle(Bundle bundle) {
if (isNotFragment(bundle)) {
Enumeration<URL> xmlDocumentPaths = bundle.findEntries(xmlDirectory, "*.xml", true);
if (xmlDocumentPaths != null) {
Collection<URL> filteredPaths = filterPatches(xmlDocumentPaths, bundle);
parseDocuments(bundle, filteredPaths);
}
}
finishBundle(bundle);
}
/**
* A bundle just arrived (and / or just becomes ACTIVE). We need to check if it contains 'webjar libraries'.
*
* @param bundle the bundle
* @param bundleEvent the event
* @return the list of webjar found in the bundle, empty if none.
*/
@Override
public synchronized List<BundleWebJarLib> addingBundle(Bundle bundle, BundleEvent bundleEvent) {
Enumeration<URL> e = bundle.findEntries(WEBJAR_LOCATION, "*", true);
if (e == null) {
// No match
return Collections.emptyList();
}
List<BundleWebJarLib> list = new ArrayList<>();
while (e.hasMoreElements()) {
String path = e.nextElement().getPath();
if (path.endsWith("/")) {
Matcher matcher = WEBJAR_ROOT_REGEX.matcher(path);
if (matcher.matches()) {
String name = matcher.group(1);
String version = matcher.group(2);
final BundleWebJarLib lib = new BundleWebJarLib(name, version, bundle);
logger().info("Web Jar library ({}) found in {} [{}]", lib,
bundle.getSymbolicName(),
bundle.getBundleId());
list.add(lib);
}
}
}
addWebJarLibs(list);
return list;
}
/**
* 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("unchecked")
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;
}
public void addBundleResourcePaths(Bundle bundle) {
List<String> resourcePathList = new LinkedList<String>();
Enumeration entries = bundle.findEntries("web", "*", false);
while (entries != null && entries.hasMoreElements()) {
URL url = (URL) entries.nextElement();
String path = url.getPath();
if (path.endsWith("/")) {
String bundleResourcePath = path.substring("/web/".length(), path.length() - 1);
bundleResourceMap.put(bundleResourcePath, bundle);
resourcePathList.add(bundleResourcePath);
}
}
inverseBundleResourceMap.put(bundle,resourcePathList);
}
public void testActivation() throws Exception {
ModuleSystem ms = Main.getModuleSystem();
mgr = ms.getManager();
mgr.mutexPrivileged().enterWriteAccess();
int checks = 0;
System.setProperty("activated.checkentries", "/org/test/x.txt");
try {
m1 = mgr.create(simpleModule, null, false, false, false);
mgr.enable(m1);
Class<?> main = m1.getClassLoader().loadClass("org.activate.Main");
Object s = main.getField("start").get(null);
assertNotNull("Bundle started, its context provided", s);
BundleContext bc = (BundleContext)s;
StringBuilder sb = new StringBuilder();
for (Bundle b : bc.getBundles()) {
URL root = b.getEntry("/");
if (root == null) {
sb.append("No root URL for ").append(b.getSymbolicName()).append("\n");
}
Enumeration<URL> en = b.findEntries("/", null, true);
if (en == null) {
sb.append("No entries for ").append(b.getSymbolicName()).append("\n");
continue;
}
while (en.hasMoreElements()) {
URL u = en.nextElement();
final String ef = u.toExternalForm();
int pref = ef.indexOf("/org/");
int last = ef.lastIndexOf("/");
if (pref != -1 && last != -1) {
String entry = ef.substring(pref + 1, last + 1);
assertTrue("/ is at the end", entry.endsWith("/"));
checks++;
final URL found = b.getEntry(entry);
assertNotNull("Entry found " + entry + " in " + b.getSymbolicName(), found);
URL notFound = b.getEntry("non/existent/entry/");
assertNull("Entries for non-existing entries are not found", notFound);
}
}
}
if (sb.length() > 0) {
fail(sb.toString());
}
if (checks == 0) {
fail("There shall be some checks for entries");
}
String text = System.getProperty("activated.entry");
assertEquals("Ahoj", text);
String localURL = System.getProperty("activated.entry.local");
assertNotNull("bundleentry read OK", localURL);
assertTrue("external file is referred as file:/.... = " + localURL, localURL.startsWith("file:/"));
assertEquals("Ahoj", readLine(localURL));
String fileURL = System.getProperty("activated.entry.file");
assertNotNull("fileURL found", fileURL);
assertTrue("file:/..... = " + fileURL, fileURL.startsWith("file:/"));
assertEquals("Ahoj", readLine(fileURL));
mgr.disable(m1);
Object e = main.getField("stop").get(null);
assertNotNull("Bundle stopped, its context provided", e);
} finally {
mgr.mutexPrivileged().exitWriteAccess();
}
}
/**
* 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 ( final String bundleID, final IPath relativePath ) throws IOException
{
final 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 )
{
final Enumeration<URL> entries = bundle.findEntries ( "/", "*.emtl", true );
if ( entries != null )
{
final String[] segmentsRelativePath = relativePath.segments ();
while ( url == null && entries.hasMoreElements () )
{
final URL entry = entries.nextElement ();
IPath path = new Path ( entry.getPath () );
if ( path.segmentCount () > relativePath.segmentCount () )
{
path = path.removeFirstSegments ( path.segmentCount () - relativePath.segmentCount () );
}
final 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;
}
private static URL getBaseURL(Bundle bundle, String bundleName) {
Enumeration<URL> entries = bundle.findEntries("/", bundleName, true);
return entries != null ? entries.nextElement() : null;
}
void appendResourceHTML(final StringBuffer sb, final ResourceUrl resUrl)
{
final Bundle bundle = Activator.getTargetBC_getBundle(resUrl.getBid());
sb.append("<html>");
sb.append("<table border=0 width=\"100%\">");
final Enumeration<URL> resEnum =
bundle.findEntries(resUrl.getPath(), resUrl.getFilenamePattern(), true);
while (resEnum.hasMoreElements()) {
final URL url = resEnum.nextElement();
sb.append("<tr><td width=\"100%\" bgcolor=\"#eeeeee\">");
JHTMLBundle.startFont(sb, "-1");
sb.append("#" + bundle.getBundleId() + " " + url.getPath());
JHTMLBundle.stopFont(sb);
sb.append("</td>\n");
sb.append("</tr>\n");
sb.append("<tr>");
sb.append("<td>");
sb.append("<pre>");
JHTMLBundle.startFont(sb, "-1");
try {
final byte[] bytes = Util.readStream(url.openStream());
String value = new String(bytes);
value = Strings.replace(value, "<", "<");
value = Strings.replace(value, ">", ">");
if (resUrl.isSCR()) {
// Break down component start tag into 4 pieces:
// $1 <scr:component .* name="
// $2 XMLNS prefix part in $1 if present
// $3 the actual component name
// $4 " .*>
final Pattern p =
Pattern
.compile("(<(\\w*?:)?component\\s.*?name\\s*=\\s*\")([^\"]*)(\".*?>)",
Pattern.DOTALL);
final Matcher m = p.matcher(value);
final StringBuffer sb2 = new StringBuffer();
while (m.find()) {
final StringBuffer sb3 = new StringBuffer();
sb3.setLength(0);
sb3.append("$1");
new SCRHTMLDisplayer.ScrUrl(m.group(3)).scrLink(sb3, m.group(3));
sb3.append("$4");
m.appendReplacement(sb2, sb3.toString());
}
m.appendTail(sb2);
value = sb2.toString();
}
sb.append(value);
} catch (final Exception e) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
sb.append(sw.toString());
}
JHTMLBundle.stopFont(sb);
sb.append("</pre>");
sb.append("</td>");
sb.append("</tr>");
}
sb.append("</table>");
sb.append("</html>");
}
@Override
public int start(final List<String> args) throws IOException {
final Injector injector = HeadlessSimulationLoader.preloadGAMA();
final GamlModelBuilder builder = createBuilder(injector);
final int[] count = { 0 };
final int[] code = { 0, 0 };
final Multimap<Bundle, String> plugins = GamaBundleLoader.getPluginsWithModels();
final List<URL> allURLs = new ArrayList<>();
for (final Bundle bundle : plugins.keySet()) {
for (final String entry : plugins.get(bundle)) {
final Enumeration<URL> urls = bundle.findEntries(entry, "*", true);
if (urls != null) {
while (urls.hasMoreElements()) {
final URL url = urls.nextElement();
if (isModel(url)) {
final URL resolvedFileURL = FileLocator.toFileURL(url);
allURLs.add(resolvedFileURL);
}
}
}
}
}
builder.loadURLs(allURLs);
// allURLs.forEach(u -> validate(builder, count, code, u));
final Map<String, Exception> errors = new HashMap<>();
allURLs.forEach(u -> validateAndRun(builder, errors, count, code, u, true, 1));
DEBUG.OUT("" + count[0] + " GAMA models compiled in built-in library and plugins. " + code[0]
+ " compilation errors found");
DEBUG.SECTION("SUMMARY");
errors.forEach((name, ex) -> DEBUG.OUT(name + " = " + ex.toString()));
DEBUG.SECTION("SUMMARY");
// code[1] = code[0];
// code[0] = 0;
// count[0] = 0;
// final Multimap<Bundle, String> tests = GamaBundleLoader.getPluginsWithTests();
// allURLs = new ArrayList<>();
// for (final Bundle bundle : tests.keySet()) {
// for (final String entry : tests.get(bundle)) {
// final Enumeration<URL> urls = bundle.findEntries(entry, "*", true);
// if (urls != null)
// while (urls.hasMoreElements()) {
// final URL url = urls.nextElement();
// if (isModel(url)) {
// final URL resolvedFileURL = FileLocator.toFileURL(url);
// allURLs.add(resolvedFileURL);
// }
// }
// }
// }
// builder.loadURLs(allURLs);
//
// allURLs.forEach(u -> validate(builder, count, code, u));
//
// DEBUG.OUT("" + count[0] + " GAMA tests compiled in built-in library and plugins. " + code[0]
// + " compilation errors found");
//
// DEBUG.OUT(code[0] + code[1]);
return code[0] + code[1];
}