Search in sources :

Example 1 with ModuleClassLoader

use of org.eclipse.osgi.internal.loader.ModuleClassLoader in project rt.equinox.framework by eclipse.

the class EquinoxBundle method getResource.

@Override
public URL getResource(String name) {
    try {
        equinoxContainer.checkAdminPermission(this, AdminPermission.RESOURCE);
    } catch (SecurityException e) {
        return null;
    }
    checkValid();
    if (isFragment()) {
        return null;
    }
    ModuleClassLoader classLoader = getModuleClassLoader(false);
    if (classLoader != null) {
        return classLoader.getResource(name);
    }
    return new ClasspathManager((Generation) module.getCurrentRevision().getRevisionInfo(), null).findLocalResource(name);
}
Also used : ClasspathManager(org.eclipse.osgi.internal.loader.classpath.ClasspathManager) Generation(org.eclipse.osgi.storage.BundleInfo.Generation) ModuleClassLoader(org.eclipse.osgi.internal.loader.ModuleClassLoader)

Example 2 with ModuleClassLoader

use of org.eclipse.osgi.internal.loader.ModuleClassLoader in project knime-core by knime.

the class EclipseUtil method findClasses.

/**
 * Searches the given class loader for classes that match the given class filter. This method is capable of
 * searching through Eclipse plug-ins but it will not recursivly search dependencies.
 *
 * @param filter a filter for classes
 * @param classLoader the class loader that should be used for searching
 * @return a collection with matching classes
 * @throws IOException if an I/O error occurs while scanning the class path
 * @since 2.12
 */
public static Collection<Class<?>> findClasses(final ClassFilter filter, final ClassLoader classLoader) throws IOException {
    List<URL> classPathUrls = new ArrayList<>();
    if (classLoader instanceof ModuleClassLoader) {
        ModuleClassLoader cl = (ModuleClassLoader) classLoader;
        ClasspathManager cpm = cl.getClasspathManager();
        for (ClasspathEntry e : cpm.getHostClasspathEntries()) {
            BundleFile bf = e.getBundleFile();
            classPathUrls.add(bf.getEntry("").getLocalURL());
        }
    } else if (classLoader instanceof URLClassLoader) {
        URLClassLoader cl = (URLClassLoader) classLoader;
        for (URL u : cl.getURLs()) {
            classPathUrls.add(u);
        }
    } else {
        FileLocator.toFileURL(classLoader.getResource(""));
    }
    // filter classpath for nested entries
    for (Iterator<URL> it = classPathUrls.iterator(); it.hasNext(); ) {
        URL url1 = it.next();
        for (URL url2 : classPathUrls) {
            if ((url1 != url2) && url2.getPath().startsWith(url1.getPath())) {
                it.remove();
                break;
            }
        }
    }
    List<Class<?>> classes = new ArrayList<>();
    for (URL url : classPathUrls) {
        if ("file".equals(url.getProtocol())) {
            String path = url.getPath();
            // path = path.replaceFirst(Pattern.quote(classPath) + "$", "");
            collectInDirectory(new File(path), "", filter, classes, classLoader);
        } else if ("jar".equals(url.getProtocol())) {
            String path = url.getPath().replaceFirst("^file:", "").replaceFirst("\\!.+$", "");
            collectInJar(new JarFile(path), filter, classes, classLoader);
        } else {
            throw new IllegalStateException("Cannot read from protocol '" + url.getProtocol() + "'");
        }
    }
    return classes;
}
Also used : ClasspathManager(org.eclipse.osgi.internal.loader.classpath.ClasspathManager) ModuleClassLoader(org.eclipse.osgi.internal.loader.ModuleClassLoader) ArrayList(java.util.ArrayList) JarFile(java.util.jar.JarFile) URL(java.net.URL) URLClassLoader(java.net.URLClassLoader) ClasspathEntry(org.eclipse.osgi.internal.loader.classpath.ClasspathEntry) BundleFile(org.eclipse.osgi.storage.bundlefile.BundleFile) JarFile(java.util.jar.JarFile) BundleFile(org.eclipse.osgi.storage.bundlefile.BundleFile) File(java.io.File)

Example 3 with ModuleClassLoader

use of org.eclipse.osgi.internal.loader.ModuleClassLoader in project rt.equinox.framework by eclipse.

the class ClassLoadingBundleTests method testLoaderUninstalledBundle.

public void testLoaderUninstalledBundle() throws BundleException, IOException {
    String testResourcePath = "testResource";
    // $NON-NLS-1$
    File config = OSGiTestsActivator.getContext().getDataFile(getName());
    Map<String, String> testHeaders = new HashMap<String, String>();
    testHeaders.put(Constants.BUNDLE_MANIFESTVERSION, "2");
    testHeaders.put(Constants.BUNDLE_SYMBOLICNAME, getName());
    config.mkdirs();
    File testBundleFile = SystemBundleTests.createBundle(config, getName(), testHeaders, Collections.singletonMap(testResourcePath, "testValue"));
    Bundle test = getContext().installBundle(getName(), new FileInputStream(testBundleFile));
    test.start();
    BundleWiring wiring = test.adapt(BundleWiring.class);
    assertNotNull("No wiring found.", wiring);
    ModuleClassLoader bundleClassLoader = (ModuleClassLoader) wiring.getClassLoader();
    URL testResource = bundleClassLoader.findLocalResource(testResourcePath);
    assertNotNull("No test resource found.", testResource);
    test.update(new FileInputStream(testBundleFile));
    testResource = bundleClassLoader.findLocalResource(testResourcePath);
    assertNull("Found resource.", testResource);
    Object[] expectedFrameworkEvents = new Object[] { new FrameworkEvent(FrameworkEvent.INFO, test, null) };
    Object[] actualFrameworkEvents = frameworkListenerResults.getResults(1);
    compareResults(expectedFrameworkEvents, actualFrameworkEvents);
    wiring = test.adapt(BundleWiring.class);
    assertNotNull("No wiring found.", wiring);
    bundleClassLoader = (ModuleClassLoader) wiring.getClassLoader();
    testResource = bundleClassLoader.findLocalResource(testResourcePath);
    assertNotNull("No test resource found.", testResource);
    test.uninstall();
    testResource = bundleClassLoader.findLocalResource(testResourcePath);
    assertNull("Found resource.", testResource);
    actualFrameworkEvents = frameworkListenerResults.getResults(1);
    compareResults(expectedFrameworkEvents, actualFrameworkEvents);
}
Also used : HashMap(java.util.HashMap) FrameworkEvent(org.osgi.framework.FrameworkEvent) Bundle(org.osgi.framework.Bundle) ModuleClassLoader(org.eclipse.osgi.internal.loader.ModuleClassLoader) BundleWiring(org.osgi.framework.wiring.BundleWiring) File(java.io.File) FileInputStream(java.io.FileInputStream) URL(java.net.URL)

Example 4 with ModuleClassLoader

use of org.eclipse.osgi.internal.loader.ModuleClassLoader in project knime-core by knime.

the class JavaSnippet method resolveBuildPathForJavaType.

/**
 * Get file and jar urls required for compiling with given java type
 */
private static synchronized Set<File> resolveBuildPathForJavaType(final Class<?> javaType) {
    if (javaType.isPrimitive()) {
        return Collections.emptySet();
    }
    final Set<File> javaTypeCache = CLASSPATH_FOR_CLASS_CACHE.get(javaType);
    if (javaTypeCache != null) {
        return javaTypeCache;
    }
    final Set<File> result = new LinkedHashSet<>();
    final Set<URL> urls = new LinkedHashSet<>();
    ClassUtil.streamForClassHierarchy(javaType).filter(c -> c.getClassLoader() instanceof ModuleClassLoader).flatMap(c -> {
        final ModuleClassLoader moduleClassLoader = (ModuleClassLoader) c.getClassLoader();
        return Arrays.stream(moduleClassLoader.getClasspathManager().getHostClasspathEntries());
    }).forEach(entry -> {
        final BundleFile file = entry.getBundleFile();
        try {
            final URL url = file.getBaseFile().toURI().toURL();
            urls.add(url);
        } catch (MalformedURLException e) {
            LOGGER.error("Could not resolve URL for bundle file \"" + file.toString() + "\" while assembling build path for custom java type \"" + javaType.getName() + "\"");
        }
        result.add(file.getBaseFile());
    });
    /* Check whether the java snippet compiler can later find the class with this classpath */
    try (final URLClassLoader classpathClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]))) {
        classpathClassLoader.loadClass(javaType.getName());
    } catch (NoClassDefFoundError | ClassNotFoundException e) {
        LOGGER.error("Classpath for \"" + javaType.getName() + "\" could not be assembled.", e);
        // indicate that this type should not be provided in java snippet
        return null;
    } catch (IOException e) {
        // thrown by URLClassLoader.close()
        LOGGER.error("Unable to close classloader used for testing of custom type classpath.", e);
    }
    if (result.contains(null)) {
        throw new IllegalStateException("Couldn't assemble classpath for custom type \"" + javaType + "\", illegal <null> value in list:\n  " + result.stream().map(f -> f == null ? "<NULL>" : f.getAbsolutePath()).collect(Collectors.joining("\n  ")));
    }
    CLASSPATH_FOR_CLASS_CACHE.put(javaType, result);
    return result;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Arrays(java.util.Arrays) RowKey(org.knime.core.data.RowKey) Parser(org.fife.ui.rsyntaxtextarea.parser.Parser) CanceledExecutionException(org.knime.core.node.CanceledExecutionException) JavaSnippetSettings(org.knime.base.node.jsnippet.util.JavaSnippetSettings) CollectionConverterFactory(org.knime.core.data.convert.java.CollectionConverterFactory) JavaSnippetDocument(org.knime.base.node.jsnippet.guarded.JavaSnippetDocument) URLClassLoader(java.net.URLClassLoader) ConverterUtil(org.knime.base.node.jsnippet.type.ConverterUtil) Map(java.util.Map) EclipseFileObject(org.eclipse.jdt.internal.compiler.tool.EclipseFileObject) JavaSnippetUtil(org.knime.base.node.jsnippet.util.JavaSnippetUtil) MultiParentClassLoader(org.knime.core.data.convert.util.MultiParentClassLoader) Set(java.util.Set) BadLocationException(javax.swing.text.BadLocationException) StandardCharsets(java.nio.charset.StandardCharsets) DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) JavaFileObject(javax.tools.JavaFileObject) JavaFieldList(org.knime.base.node.jsnippet.util.JavaFieldList) Stream(java.util.stream.Stream) Type(org.knime.base.node.jsnippet.expression.Type) JavaToDataCellConverterRegistry(org.knime.core.data.convert.datacell.JavaToDataCellConverterRegistry) Kind(javax.tools.JavaFileObject.Kind) FlowVariable(org.knime.core.node.workflow.FlowVariable) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) BundleNamespace(org.osgi.framework.namespace.BundleNamespace) JavaSnippetFields(org.knime.base.node.jsnippet.util.JavaSnippetFields) DocumentEvent(javax.swing.event.DocumentEvent) DataCell(org.knime.core.data.DataCell) LinkedHashSet(java.util.LinkedHashSet) InCol(org.knime.base.node.jsnippet.util.field.InCol) ClassUtil(org.knime.core.data.convert.util.ClassUtil) DefaultRow(org.knime.core.data.def.DefaultRow) JavaSnippetTemplate(org.knime.base.node.jsnippet.template.JavaSnippetTemplate) ValidationReport(org.knime.base.node.jsnippet.util.ValidationReport) KNIMEConstants(org.knime.core.node.KNIMEConstants) BufferedWriter(java.io.BufferedWriter) StringWriter(java.io.StringWriter) GUARDED_FIELDS(org.knime.base.node.jsnippet.guarded.JavaSnippetDocument.GUARDED_FIELDS) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) Field(java.lang.reflect.Field) FlowVariableException(org.knime.base.node.jsnippet.expression.FlowVariableException) File(java.io.File) DataRow(org.knime.core.data.DataRow) DataCellToJavaConverterRegistry(org.knime.core.data.convert.java.DataCellToJavaConverterRegistry) OutCol(org.knime.base.node.jsnippet.util.field.OutCol) GuardedDocument(org.knime.base.node.jsnippet.guarded.GuardedDocument) Platform(org.eclipse.core.runtime.Platform) FileUtil(org.knime.core.util.FileUtil) DataType(org.knime.core.data.DataType) DocumentListener(javax.swing.event.DocumentListener) ModuleClassLoader(org.eclipse.osgi.internal.loader.ModuleClassLoader) InvalidSettingsException(org.knime.core.node.InvalidSettingsException) URL(java.net.URL) Abort(org.knime.base.node.jsnippet.expression.Abort) GUARDED_BODY_END(org.knime.base.node.jsnippet.guarded.JavaSnippetDocument.GUARDED_BODY_END) ArrayToCollectionConverterFactory(org.knime.core.data.convert.datacell.ArrayToCollectionConverterFactory) DataCellToJavaConverterFactory(org.knime.core.data.convert.java.DataCellToJavaConverterFactory) JSnippet(org.knime.base.node.jsnippet.util.JSnippet) OutVar(org.knime.base.node.jsnippet.util.field.OutVar) CompilationTask(javax.tools.JavaCompiler.CompilationTask) AbstractJSnippet(org.knime.base.node.jsnippet.expression.AbstractJSnippet) DataColumnSpec(org.knime.core.data.DataColumnSpec) GUARDED_IMPORTS(org.knime.base.node.jsnippet.guarded.JavaSnippetDocument.GUARDED_IMPORTS) Locale(java.util.Locale) Diagnostic(javax.tools.Diagnostic) FlowVariableRepository(org.knime.base.node.jsnippet.util.FlowVariableRepository) Cell(org.knime.base.node.jsnippet.expression.Cell) Bundle(org.osgi.framework.Bundle) DiagnosticCollector(javax.tools.DiagnosticCollector) GUARDED_BODY_START(org.knime.base.node.jsnippet.guarded.JavaSnippetDocument.GUARDED_BODY_START) Collection(java.util.Collection) JavaField(org.knime.base.node.jsnippet.util.field.JavaField) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Collectors(java.util.stream.Collectors) ColumnException(org.knime.base.node.jsnippet.expression.ColumnException) Objects(java.util.Objects) List(java.util.List) BufferedDataTable(org.knime.core.node.BufferedDataTable) Writer(java.io.Writer) OutColList(org.knime.base.node.jsnippet.util.JavaFieldList.OutColList) Optional(java.util.Optional) Document(javax.swing.text.Document) DateAndTimeCell(org.knime.core.data.date.DateAndTimeCell) GuardedSection(org.knime.base.node.jsnippet.guarded.GuardedSection) DataTableSpec(org.knime.core.data.DataTableSpec) TypeException(org.knime.base.node.jsnippet.expression.TypeException) JavaSnippetCompiler(org.knime.base.node.jsnippet.util.JavaSnippetCompiler) JavaToDataCellConverterFactory(org.knime.core.data.convert.datacell.JavaToDataCellConverterFactory) ExecutionContext(org.knime.core.node.ExecutionContext) JarEntry(java.util.jar.JarEntry) BundleFile(org.eclipse.osgi.storage.bundlefile.BundleFile) CellFactory(org.knime.core.data.container.CellFactory) NodeLogger(org.knime.core.node.NodeLogger) OutputStreamWriter(java.io.OutputStreamWriter) JarOutputStream(java.util.jar.JarOutputStream) BundleWiring(org.osgi.framework.wiring.BundleWiring) MalformedURLException(java.net.MalformedURLException) InVar(org.knime.base.node.jsnippet.util.field.InVar) FileLocator(org.eclipse.core.runtime.FileLocator) JSnippetParser(org.knime.base.node.jsnippet.ui.JSnippetParser) Closeable(java.io.Closeable) ColumnRearranger(org.knime.core.data.container.ColumnRearranger) BundleWire(org.osgi.framework.wiring.BundleWire) Collections(java.util.Collections) InputStream(java.io.InputStream) MalformedURLException(java.net.MalformedURLException) ModuleClassLoader(org.eclipse.osgi.internal.loader.ModuleClassLoader) IOException(java.io.IOException) URL(java.net.URL) URLClassLoader(java.net.URLClassLoader) BundleFile(org.eclipse.osgi.storage.bundlefile.BundleFile) File(java.io.File) BundleFile(org.eclipse.osgi.storage.bundlefile.BundleFile)

Example 5 with ModuleClassLoader

use of org.eclipse.osgi.internal.loader.ModuleClassLoader in project rt.equinox.framework by eclipse.

the class Handler method findBundleEntry.

protected BundleEntry findBundleEntry(URL url, Module module) throws IOException {
    ModuleRevision current = module.getCurrentRevision();
    ModuleWiring wiring = current == null ? null : current.getWiring();
    ModuleClassLoader classloader = (ModuleClassLoader) (current == null ? null : wiring.getClassLoader());
    if (classloader == null)
        throw new FileNotFoundException(url.getPath());
    BundleEntry entry = classloader.getClasspathManager().findLocalEntry(url.getPath(), url.getPort());
    if (entry == null) {
        // this isn't strictly needed but is kept to maintain compatibility
        entry = classloader.getClasspathManager().findLocalEntry(url.getPath());
    }
    if (entry == null) {
        throw new FileNotFoundException(url.getPath());
    }
    return entry;
}
Also used : ModuleClassLoader(org.eclipse.osgi.internal.loader.ModuleClassLoader) ModuleWiring(org.eclipse.osgi.container.ModuleWiring) FileNotFoundException(java.io.FileNotFoundException) ModuleRevision(org.eclipse.osgi.container.ModuleRevision) BundleEntry(org.eclipse.osgi.storage.bundlefile.BundleEntry)

Aggregations

ModuleClassLoader (org.eclipse.osgi.internal.loader.ModuleClassLoader)9 URL (java.net.URL)4 File (java.io.File)3 ClasspathManager (org.eclipse.osgi.internal.loader.classpath.ClasspathManager)3 URLClassLoader (java.net.URLClassLoader)2 ArrayList (java.util.ArrayList)2 ModuleWiring (org.eclipse.osgi.container.ModuleWiring)2 BundleLoader (org.eclipse.osgi.internal.loader.BundleLoader)2 BundleFile (org.eclipse.osgi.storage.bundlefile.BundleFile)2 Bundle (org.osgi.framework.Bundle)2 BundleWiring (org.osgi.framework.wiring.BundleWiring)2 BufferedWriter (java.io.BufferedWriter)1 Closeable (java.io.Closeable)1 FileInputStream (java.io.FileInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 OutputStreamWriter (java.io.OutputStreamWriter)1 StringWriter (java.io.StringWriter)1