Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package com.facebook.presto.server;
 
 
 
 import java.io.File;
 import java.net.URL;
 import java.util.List;
 import java.util.Map;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 
 public class PluginManager
 {
     private static final Logger log = Logger.get(PluginManager.class);
 
     private final Injector injector;
     private final ConnectorManager connectorManager;
     private final SystemTablesManager systemTablesManager;
     private final MetadataManager metadataManager;
     private final ArtifactResolver resolver;
     private final File installedPluginsDir;
     private final List<Stringplugins;
     private final Map<StringStringoptionalConfig;
     private final AtomicBoolean pluginsLoaded = new AtomicBoolean();
 
     @Inject
     public PluginManager(Injector injector,
             NodeInfo nodeInfo,
             HttpServerInfo httpServerInfo,
             PluginManagerConfig config,
             ConnectorManager connectorManager,
             ConfigurationFactory configurationFactory,
             SystemTablesManager systemTablesManager,
             MetadataManager metadataManager)
     {
         checkNotNull(injector"injector is null");
         checkNotNull(nodeInfo"nodeInfo is null");
         checkNotNull(httpServerInfo"httpServerInfo is null");
         checkNotNull(config"config is null");
         checkNotNull(configurationFactory"configurationFactory is null");
 
         this. = injector;
          = config.getInstalledPluginsDir();
         if (config.getPlugins() == null) {
             this. = ImmutableList.of();
         }
         else {
             this. = ImmutableList.copyOf(config.getPlugins());
         }
         this. = new ArtifactResolver(config.getMavenLocalRepository(), config.getMavenRemoteRepository());
 
         Map<StringStringoptionalConfig = new TreeMap<>(configurationFactory.getProperties());
         optionalConfig.put("node.id"nodeInfo.getNodeId());
         // TODO: make this work with and without HTTP and HTTPS
         optionalConfig.put("http-server.http.port", Integer.toString(httpServerInfo.getHttpUri().getPort()));
        this. = ImmutableMap.copyOf(optionalConfig);
        this. = checkNotNull(connectorManager"connectorManager is null");
        this. = checkNotNull(systemTablesManager"systemTablesManager is null");
        this. = checkNotNull(metadataManager"metadataManager is null");
    }
    public boolean arePluginsLoaded()
    {
        return .get();
    }
    public void loadPlugins()
            throws Exception
    {
        if (!.compareAndSet(falsetrue)) {
            return;
        }
        for (File file : listFiles()) {
            if (file.isDirectory()) {
                loadPlugin(file.getAbsolutePath());
            }
        }
        for (String plugin : ) {
            loadPlugin(plugin);
        }
    }
    @SuppressWarnings("UnusedDeclaration")
    private void loadPlugin(String plugin)
            throws Exception
    {
        .info("-- Loading plugin %s --"plugin);
        URLClassLoader pluginClassLoader = buildClassLoader(plugin);
        try (ThreadContextClassLoader threadContextClassLoader = new ThreadContextClassLoader(pluginClassLoader)) {
            loadPlugin(pluginClassLoader);
        }
        .info("-- Finished loading plugin %s --"plugin);
    }
    private void loadPlugin(URLClassLoader pluginClassLoader)
            throws Exception
    {
        ServiceLoader<PluginserviceLoader = ServiceLoader.load(Plugin.classpluginClassLoader);
        List<Pluginplugins = ImmutableList.copyOf(serviceLoader);
        for (Plugin plugin : plugins) {
            installPlugin(plugin);
        }
    }
    public void installPlugin(Plugin plugin)
    {
        .injectMembers(plugin);
        plugin.setOptionalConfig();
        for (ConnectorFactory connectorFactory : plugin.getServices(ConnectorFactory.class)) {
            .addConnectorFactory(connectorFactory);
        }
        for (SystemTable systemTable : plugin.getServices(SystemTable.class)) {
            .addTable(systemTable);
        }
        for (FunctionFactory functionFactory : plugin.getServices(FunctionFactory.class)) {
            .addFunctions(functionFactory.listFunctions());
        }
    }
    private URLClassLoader buildClassLoader(String plugin)
            throws Exception
    {
        File file = new File(plugin);
        if (file.isFile() && (file.getName().equals("pom.xml") || file.getName().endsWith(".pom"))) {
            return buildClassLoaderFromPom(file);
        }
        else if (file.isDirectory()) {
            return buildClassLoaderFromDirectory(file);
        }
        else {
            return buildClassLoaderFromCoordinates(plugin);
        }
    }
    private URLClassLoader buildClassLoaderFromPom(File pomFile)
            throws Exception
    {
        List<Artifactartifacts = .resolvePom(pomFile);
        .debug("Classpath for %s:"pomFile);
        List<URLurls = new ArrayList<>();
        urls.add(new File(pomFile.getParentFile(), "target/classes/").toURI().toURL());
        for (Artifact artifact : artifacts) {
            if (artifact.getFile() != null) {
                .debug("    %s"artifact.getFile());
                urls.add(artifact.getFile().toURI().toURL());
            }
            else {
                .debug("  Could not resolve artifact %s"artifact);
            }
        }
        return createClassLoader(urls);
    }
            throws Exception
    {
        .debug("Classpath for %s:"dir.getName());
        List<URLurls = new ArrayList<>();
        for (File file : listFiles(dir)) {
            .debug("    %s"file);
            urls.add(file.toURI().toURL());
        }
        return createClassLoader(urls);
    }
            throws Exception
    {
        Artifact rootArtifact = new DefaultArtifact(coordinates);
        List<Artifactartifacts = .resolveArtifacts(rootArtifact);
        .debug("Classpath for %s:"rootArtifact);
        List<URLurls = new ArrayList<>();
        for (Artifact artifact : artifacts) {
            if (artifact.getFile() != null) {
                .debug("    %s"artifact.getFile());
                urls.add(artifact.getFile().toURI().toURL());
            }
            else {
                // todo maybe exclude things like presto-spi
                .warn("  Could not resolve artifact %s"artifact);
            }
        }
        return createClassLoader(urls);
    }
    private URLClassLoader createClassLoader(List<URLurls)
    {
        return new SimpleChildFirstClassLoader(urls,
                getClass().getClassLoader(),
                ImmutableList.of("org.slf4j"),
                ImmutableList.of("com.facebook.presto""com.fasterxml.jackson"));
    }
    private List<FilelistFiles(File installedPluginsDir)
    {
        if (installedPluginsDir != null && installedPluginsDir.isDirectory()) {
            File[] files = installedPluginsDir.listFiles();
            if (files != null) {
                return ImmutableList.copyOf(files);
            }
        }
        return ImmutableList.of();
    }
    private static class SimpleChildFirstClassLoader
            extends URLClassLoader
    {
        private final List<StringhiddenClasses;
        private final List<StringparentFirstClasses;
        private final List<StringhiddenResources;
        private final List<StringparentFirstResources;
        public SimpleChildFirstClassLoader(List<URLurls,
                ClassLoader parent,
                Iterable<StringhiddenClasses,
                Iterable<StringparentFirstClasses)
        {
            this(urls,
                    parent,
                    hiddenClasses,
                    parentFirstClasses,
                    Iterables.transform(hiddenClassesclassNameToResource()),
                    Iterables.transform(parentFirstClassesclassNameToResource()));
        }
        public SimpleChildFirstClassLoader(List<URLurls,
                ClassLoader parent,
                Iterable<StringhiddenClasses,
                Iterable<StringparentFirstClasses,
                Iterable<StringhiddenResources,
                Iterable<StringparentFirstResources)
        {
            // child first requires a parent class loader
            super(urls.toArray(new URL[urls.size()]), checkNotNull(parent"parent is null"));
            this. = ImmutableList.copyOf(hiddenClasses);
            this. = ImmutableList.copyOf(parentFirstClasses);
            this. = ImmutableList.copyOf(hiddenResources);
            this. = ImmutableList.copyOf(parentFirstResources);
        }
        @Override
        protected Class<?> loadClass(String nameboolean resolve)
                throws ClassNotFoundException
        {
            // grab the magic lock
            synchronized (getClassLoadingLock(name)) {
                // Check if class is in the loaded classes cache
                Class<?> cachedClass = findLoadedClass(name);
                if (cachedClass != null) {
                    return resolveClass(cachedClassresolve);
                }
                // If this is not a parent first class, look for the class locally
                if (!isParentFirstClass(name)) {
                    try {
                        Class<?> clazz = findClass(name);
                        return resolveClass(clazzresolve);
                    }
                    catch (ClassNotFoundException ignored) {
                        // not a local class
                    }
                }
                // Check parent class loaders, unless this is a hidden class
                if (!isHiddenClass(name)) {
                    try {
                        Class<?> clazz = getParent().loadClass(name);
                        return resolveClass(clazzresolve);
                    }
                    catch (ClassNotFoundException ignored) {
                        // this parent didn't have the class
                    }
                }
                // If this is a parent first class, now look for the class locally
                if (isParentFirstClass(name)) {
                    Class<?> clazz = findClass(name);
                    return resolveClass(clazzresolve);
                }
                throw new ClassNotFoundException(name);
            }
        }
        private Class<?> resolveClass(Class<?> clazzboolean resolve)
        {
            if (resolve) {
                resolveClass(clazz);
            }
            return clazz;
        }
        private boolean isParentFirstClass(String name)
        {
            for (String nonOverridableClass : ) {
                // todo maybe make this more precise and only match base package
                if (name.startsWith(nonOverridableClass)) {
                    return true;
                }
            }
            return false;
        }
        private boolean isHiddenClass(String name)
        {
            for (String hiddenClass : ) {
                // todo maybe make this more precise and only match base package
                if (name.startsWith(hiddenClass)) {
                    return true;
                }
            }
            return false;
        }
        @Override
        public URL getResource(String name)
        {
            // If this is not a parent first resource, check local resources first
            if (!isParentFirstResource(name)) {
                URL url = findResource(name);
                if (url != null) {
                    return url;
                }
            }
            // Check parent class loaders
            if (!isHiddenResource(name)) {
                URL url = getParent().getResource(name);
                if (url != null) {
                    return url;
                }
            }
            // If this is a parent first resource, now check local resources
            if (isParentFirstResource(name)) {
                URL url = findResource(name);
                if (url != null) {
                    return url;
                }
            }
            return null;
        }
        @Override
        public Enumeration<URLgetResources(String name)
                throws IOException
        {
            List<Iterator<URL>> resources = new ArrayList<>();
            // If this is not a parent first resource, add resources from local urls first
            if (!isParentFirstResource(name)) {
                Iterator<URLmyResources = Iterators.forEnumeration(findResources(name));
                resources.add(myResources);
            }
            // Add parent resources
            if (!isHiddenResource(name)) {
                Iterator<URLparentResources = Iterators.forEnumeration(getParent().getResources(name));
                resources.add(parentResources);
            }
            // If this is a parent first resource, now add resources from local urls
            if (isParentFirstResource(name)) {
                Iterator<URLmyResources = Iterators.forEnumeration(findResources(name));
                resources.add(myResources);
            }
            return Iterators.asEnumeration(Iterators.concat(resources.iterator()));
        }
        private boolean isParentFirstResource(String name)
        {
            for (String nonOverridableResource : ) {
                if (name.startsWith(nonOverridableResource)) {
                    return true;
                }
            }
            return false;
        }
        private boolean isHiddenResource(String name)
        {
            for (String hiddenResource : ) {
                if (name.startsWith(hiddenResource)) {
                    return true;
                }
            }
            return false;
        }
        private static Function<StringStringclassNameToResource()
        {
            return new Function<StringString>()
            {
                @Override
                public String apply(String className)
                {
                    return className.replace('.''/');
                }
            };
        }
    }
New to GrepCode? Check out our FAQ X