Example usage for java.net URLClassLoader URLClassLoader

List of usage examples for java.net URLClassLoader URLClassLoader

Introduction

In this page you can find the example usage for java.net URLClassLoader URLClassLoader.

Prototype

URLClassLoader(URL[] urls, AccessControlContext acc) 

Source Link

Usage

From source file:boa.evaluator.BoaEvaluator.java

public void evaluate() {
    final String[] actualArgs = createHadoopProgramArguments();
    final File srcDir = new File(this.COMPILATION_DIR);

    try {//from   w  w  w .  java2 s.  com
        final URL srcDirUrl = srcDir.toURI().toURL();

        final ClassLoader cl = new URLClassLoader(new URL[] { srcDirUrl }, ClassLoader.getSystemClassLoader());
        final Class<?> cls = cl.loadClass("boa." + jarToClassname(this.PROG_PATH));
        final Method method = cls.getMethod("main", String[].class);

        method.invoke(null, (Object) actualArgs);
    } catch (final Throwable e) {
        System.err.print(e);
    }
}

From source file:com.github.jknack.handlebars.maven.I18nJsPlugin.java

@Override
protected void doExecute() throws Exception {
    notNull(bundle, "The bundle's name parameter is required.");
    notNull(output, "The output parameter is required.");

    Handlebars handlebars = new Handlebars();
    Context context = Context.newContext(null);
    URL[] classpath = projectClasspath();

    new File(output).mkdirs();

    getLog().info("Converting bundles...");
    getLog().debug("Options:");
    getLog().debug("  output: " + output);
    getLog().debug("  merge: " + merge);
    getLog().debug("  amd: " + amd);
    getLog().debug("  classpath: " + join(classpath, File.pathSeparator));

    StringBuilder buffer = new StringBuilder();

    // 1. find all the bundles
    List<File> bundles = bundles(this.bundle, classpath);

    // 2. hash for i18njs helper
    Map<String, Object> hash = new HashMap<String, Object>();
    hash.put("wrap", false);
    if (classpath.length > 0) {
        hash.put("classLoader", new URLClassLoader(classpath, getClass().getClassLoader()));
    }//from w ww .ja v a  2  s .c  o  m
    // 3. get the base name from the bundle
    String basename = FileUtils.removePath(this.bundle.replace(".", FileUtils.FS));

    Collections.sort(bundles);
    for (File bundle : bundles) {
        // bundle name
        String bundleName = FileUtils.removeExtension(bundle.getName());
        getLog().debug("converting: " + bundle.getName());
        // extract locale from bundle name
        String locale = bundleName.substring(basename.length());
        if (locale.startsWith("_")) {
            locale = locale.substring(1);
        }
        // set bundle name
        hash.put("bundle", this.bundle);

        Options options = new Options.Builder(handlebars, I18nHelper.i18nJs.name(), TagType.VAR, context,
                Template.EMPTY).setHash(hash).build();
        // convert to JS
        buffer.append(I18nHelper.i18nJs.apply(locale, options));

        if (!merge) {
            FileUtils.fileWrite(new File(output, bundleName + ".js"), encoding, wrap(bundleName, buffer, amd));
            buffer.setLength(0);
            getLog().debug("  => " + bundleName + ".js");
        } else {
            buffer.append("\n");
        }
    }
    if (merge && buffer.length() > 0) {
        FileUtils.fileWrite(new File(output, basename + ".js"), wrap(basename, buffer, amd));
        getLog().debug("  =>" + basename + ".js");
    }
}

From source file:com.enioka.jqm.tools.JndiContext.java

/**
 * Create a new Context//from w  ww  .j a  v  a  2s.c  o  m
 * 
 * @throws NamingException
 */
private JndiContext() throws NamingException {
    super();

    // List all jars inside ext directory
    File extDir = new File("ext/");
    List<URL> urls = new ArrayList<URL>();
    if (extDir.isDirectory()) {
        for (File f : extDir.listFiles()) {
            if (!f.canRead()) {
                throw new NamingException("can't access file " + f.getAbsolutePath());
            }
            try {
                urls.add(f.toURI().toURL());
            } catch (MalformedURLException e) {
                jqmlogger.error("Error when parsing the content of ext directory. File will be ignored", e);
            }
        }

        // Create classloader
        final URL[] aUrls = urls.toArray(new URL[0]);
        for (URL u : aUrls) {
            jqmlogger.trace(u.toString());
        }
        extResources = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
            @Override
            public URLClassLoader run() {
                return new URLClassLoader(aUrls, null);
            }
        });
    } else {
        throw new NamingException("JQM_ROOT/ext directory does not exist or cannot be read");
    }
}

From source file:org.zenoss.zep.impl.PluginServiceImpl.java

private URLClassLoader createPluginClassLoader() throws ZenossException {
    final List<URL> urls = new ArrayList<URL>();
    List<ZenPack> zenPacks;
    try {/*from  ww w  . j  av a  2 s. c o  m*/
        zenPacks = ZenPacks.getAllZenPacks();
    } catch (ZenossException e) {
        logger.warn("Unable to find ZenPacks", e);
        return null;
    }

    for (ZenPack zenPack : zenPacks) {
        final File pluginDir = new File(zenPack.packPath("zep", "plugins"));
        if (!pluginDir.isDirectory()) {
            continue;
        }
        final File[] pluginJars = pluginDir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.isFile() && pathname.getName().endsWith(".jar");
            }
        });
        if (pluginJars != null) {
            for (File pluginJar : pluginJars) {
                try {
                    urls.add(pluginJar.toURI().toURL());
                    logger.info("Loading plugin: {}", pluginJar.getAbsolutePath());
                } catch (MalformedURLException e) {
                    logger.warn("Failed to get URL from file: {}", pluginJar.getAbsolutePath());
                }
            }
        }
    }

    URLClassLoader classLoader = null;
    if (!urls.isEmpty()) {
        logger.info("Discovered plug-ins: {}", urls);
        classLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), getClass().getClassLoader());
    } else {
        logger.info("No external plug-ins found.");
    }
    return classLoader;
}

From source file:io.siddhi.doc.gen.core.utils.DocumentationUtils.java

/**
 * Returns the extension extension meta data
 * Gets the meta data from the siddhi manager
 *
 * @param targetDirectoryPath The path of the target directory of the maven module containing extensions
 * @param logger              The maven plugin logger
 * @return NamespaceMetaData namespace meta data list
 * @throws MojoFailureException   If this fails to access project dependencies
 * @throws MojoExecutionException If the classes directory from which classes are loaded is invalid
 *///from ww w .  ja va2  s  .c o m
public static List<NamespaceMetaData> getExtensionMetaData(String targetDirectoryPath,
        List<String> runtimeClasspathElements, Log logger) throws MojoFailureException, MojoExecutionException {
    List<NamespaceMetaData> namespaceMetaDataList = new ArrayList<NamespaceMetaData>();
    int urlCount = runtimeClasspathElements.size() + 1; // +1 to include the module's target/classes folder

    // Creating a list of URLs with all project dependencies
    URL[] urls = new URL[urlCount];
    for (int i = 0; i < runtimeClasspathElements.size(); i++) {
        try {
            urls[i] = new File(runtimeClasspathElements.get(i)).toURI().toURL();
        } catch (MalformedURLException e) {
            throw new MojoFailureException(
                    "Unable to access project dependency: " + runtimeClasspathElements.get(i), e);
        }
    }

    File classesDirectory = new File(targetDirectoryPath + File.separator + Constants.CLASSES_DIRECTORY);
    try {
        // Adding the generated classes to the class loader
        urls[urlCount - 1] = classesDirectory.toURI().toURL();
        ClassLoader urlClassLoader = AccessController
                .doPrivileged((PrivilegedAction<ClassLoader>) () -> new URLClassLoader(urls,
                        Thread.currentThread().getContextClassLoader()));
        // Getting extensions from all the class files in the classes directory
        addExtensionInDirectory(classesDirectory, classesDirectory.getAbsolutePath(), urlClassLoader,
                namespaceMetaDataList, logger);
    } catch (MalformedURLException e) {
        throw new MojoExecutionException("Invalid classes directory: " + classesDirectory.getAbsolutePath(), e);
    }
    for (NamespaceMetaData aNamespaceMetaData : namespaceMetaDataList) {
        for (List<ExtensionMetaData> extensionMetaData : aNamespaceMetaData.getExtensionMap().values()) {
            Collections.sort(extensionMetaData);
        }
    }
    Collections.sort(namespaceMetaDataList);
    return namespaceMetaDataList;
}

From source file:org.apache.airavata.gfac.hadoop.provider.impl.HadoopProvider.java

public void execute(JobExecutionContext jobExecutionContext) throws GFacProviderException {
    HadoopApplicationDeploymentDescriptionType hadoopAppDesc = (HadoopApplicationDeploymentDescriptionType) jobExecutionContext
            .getApplicationContext().getApplicationDeploymentDescription().getType();
    MessageContext inMessageContext = jobExecutionContext.getInMessageContext();
    HadoopApplicationDeploymentDescriptionType.HadoopJobConfiguration jobConf = hadoopAppDesc
            .getHadoopJobConfiguration();

    try {/*ww  w.j  a v a 2  s.  co  m*/
        // Preparing Hadoop configuration
        Configuration hadoopConf = HadoopUtils.createHadoopConfiguration(jobExecutionContext,
                isWhirrBasedDeployment, hadoopConfigDir);

        // Load jar containing map-reduce job implementation
        ArrayList<URL> mapRedJars = new ArrayList<URL>();
        mapRedJars.add(new File(jobConf.getJarLocation()).toURL());
        URLClassLoader childClassLoader = new URLClassLoader(mapRedJars.toArray(new URL[mapRedJars.size()]),
                this.getClass().getClassLoader());

        Job job = new Job(hadoopConf);

        job.setJobName(jobConf.getJobName());

        job.setOutputKeyClass(Class.forName(jobConf.getOutputKeyClass(), true, childClassLoader));
        job.setOutputValueClass(Class.forName(jobConf.getOutputValueClass(), true, childClassLoader));

        job.setMapperClass(
                (Class<? extends Mapper>) Class.forName(jobConf.getMapperClass(), true, childClassLoader));
        job.setCombinerClass(
                (Class<? extends Reducer>) Class.forName(jobConf.getCombinerClass(), true, childClassLoader));
        job.setReducerClass(
                (Class<? extends Reducer>) Class.forName(jobConf.getCombinerClass(), true, childClassLoader));

        job.setInputFormatClass((Class<? extends InputFormat>) Class.forName(jobConf.getInputFormatClass(),
                true, childClassLoader));
        job.setOutputFormatClass((Class<? extends OutputFormat>) Class.forName(jobConf.getOutputFormatClass(),
                true, childClassLoader));

        FileInputFormat.setInputPaths(job, new Path(hadoopAppDesc.getInputDataDirectory()));
        FileOutputFormat.setOutputPath(job, new Path(hadoopAppDesc.getOutputDataDirectory()));

        job.waitForCompletion(true);
        System.out.println(job.getTrackingURL());
        if (jobExecutionContext.getOutMessageContext() == null) {
            jobExecutionContext.setOutMessageContext(new MessageContext());
        }

        OutputParameterType[] outputParametersArray = jobExecutionContext.getApplicationContext()
                .getServiceDescription().getType().getOutputParametersArray();
        for (OutputParameterType outparamType : outputParametersArray) {
            String paramName = outparamType.getParameterName();
            if (paramName.equals("test-hadoop")) {
                ActualParameter outParam = new ActualParameter();
                outParam.getType().changeType(StringParameterType.type);
                ((StringParameterType) outParam.getType()).setValue(job.getTrackingURL());
                jobExecutionContext.getOutMessageContext().addParameter("test-hadoop", outParam);
            }
        }
    } catch (Exception e) {
        String errMessage = "Error occurred during Map-Reduce job execution.";
        logger.error(errMessage, e);
        throw new GFacProviderException(errMessage, e);
    }
}

From source file:org.deegree.commons.modules.ModuleInfo.java

/**
 * Returns the {@link ModuleInfo} for the deegree module on the given classpath.
 * /*from  w  ww. j a v a  2  s  .  co  m*/
 * @param classpathURL
 *            classpath url, must not be <code>null</code>
 * @return module info or <code>null</code> (if the module does not have file META-INF/deegree/buildinfo.properties)
 * @throws IOException
 *             if accessing <code>META-INF/deegree/buildinfo.properties</code> or
 *             <code>META-INF/maven/[..]/pom.properties</code> fails
 */
public static ModuleInfo extractModuleInfo(URL classpathURL) throws IOException {

    ModuleInfo moduleInfo = null;

    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder = builder.setUrls(classpathURL);
    builder = builder.setScanners(new ResourcesScanner());
    Reflections r = new Reflections(builder);

    Set<String> resources = r.getResources(Pattern.compile("buildinfo\\.properties"));
    if (!resources.isEmpty()) {
        URLClassLoader classLoader = new URLClassLoader(new URL[] { classpathURL }, null);
        String resourcePath = resources.iterator().next();
        InputStream buildInfoStream = null;
        try {
            Properties props = new Properties();
            buildInfoStream = classLoader.getResourceAsStream(resourcePath);
            props.load(buildInfoStream);
            String buildBy = props.getProperty("build.by");
            String buildArtifactId = props.getProperty("build.artifactId");
            String buildDate = props.getProperty("build.date");
            String buildRev = props.getProperty("build.svnrev");
            String pomVersion = null;

            resources = r.getResources(Pattern.compile("pom\\.properties"));
            InputStream pomInputStream = null;
            if (!resources.isEmpty()) {
                resourcePath = resources.iterator().next();
                try {
                    props = new Properties();
                    pomInputStream = classLoader.findResource(resourcePath).openStream();
                    props.load(pomInputStream);
                    String pomArtifactId = props.getProperty("artifactId");
                    if (!pomArtifactId.equals(buildArtifactId)) {
                        LOG.warn("ArtifactId mismatch for module on path: " + classpathURL
                                + " (buildinfo.properties vs. pom.properties).");
                    }
                    pomVersion = props.getProperty("version");
                } finally {
                    closeQuietly(pomInputStream);
                }
            }
            moduleInfo = new ModuleInfo(buildArtifactId, pomVersion, buildRev, buildDate, buildBy);
        } finally {
            closeQuietly(buildInfoStream);
        }
    }
    return moduleInfo;
}

From source file:com.web.server.EJBDeployer.java

@Override
public void run() {
    EJBJarFileListener jarFileListener = new EJBJarFileListener(registry, this.servicesRegistryPort, jarEJBMap,
            jarMDBMap, jms, connectionFactory);
    DefaultFileMonitor fm = new DefaultFileMonitor(jarFileListener);
    FileObject listendir = null;//  ww  w .j a v  a 2 s  .c om
    StandardFileSystemManager fsManager = new StandardFileSystemManager();
    String[] dirsToScan = scanDirectory.split(";");
    EJBContext ejbContext;
    try {
        File scanDirFile = new File(dirsToScan[0]);
        File[] scanJarFiles = scanDirFile.listFiles();
        System.out.println("SCANDIRECTORY=" + scanDirectory);
        if (scanJarFiles != null) {
            for (File scanJarFile : scanJarFiles) {
                if (scanJarFile.isFile() && scanJarFile.getAbsolutePath().endsWith(".jar")) {
                    URLClassLoader classLoader = new URLClassLoader(
                            new URL[] { new URL("file:///" + scanJarFile.getAbsolutePath()) },
                            Thread.currentThread().getContextClassLoader());
                    ConfigurationBuilder config = new ConfigurationBuilder();
                    config.addUrls(ClasspathHelper.forClassLoader(classLoader));
                    config.addClassLoader(classLoader);
                    org.reflections.Reflections reflections = new org.reflections.Reflections(config);
                    EJBContainer container = EJBContainer
                            .getInstance("file:///" + scanJarFile.getAbsolutePath(), config);
                    container.inject();
                    Set<Class<?>> cls = reflections.getTypesAnnotatedWith(Stateless.class);
                    Set<Class<?>> clsMessageDriven = reflections.getTypesAnnotatedWith(MessageDriven.class);
                    Object obj;
                    System.gc();
                    if (cls.size() > 0) {
                        ejbContext = new EJBContext();
                        ejbContext.setJarPath(scanJarFile.getAbsolutePath());
                        ejbContext.setJarDeployed(scanJarFile.getName());
                        for (Class<?> ejbInterface : cls) {
                            //BeanPool.getInstance().create(ejbInterface);
                            obj = BeanPool.getInstance().get(ejbInterface);
                            System.out.println(obj);
                            ProxyFactory factory = new ProxyFactory();
                            obj = UnicastRemoteObject.exportObject((Remote) factory.createWithBean(obj),
                                    servicesRegistryPort);
                            String remoteBinding = container.getRemoteBinding(ejbInterface);
                            System.out.println(remoteBinding + " for EJB" + obj);
                            if (remoteBinding != null) {
                                //registry.unbind(remoteBinding);
                                registry.rebind(remoteBinding, (Remote) obj);
                                ejbContext.put(remoteBinding, obj.getClass());
                            }
                            //registry.rebind("name", (Remote) obj);
                        }
                        jarEJBMap.put("file:///" + scanJarFile.getAbsolutePath().replace("\\", "/"),
                                ejbContext);
                    }
                    System.out.println("Class Message Driven" + clsMessageDriven);
                    if (clsMessageDriven.size() > 0) {
                        System.out.println("Class Message Driven");
                        MDBContext mdbContext;
                        ConcurrentHashMap<String, MDBContext> mdbContexts;
                        if (jarMDBMap.get(scanJarFile.getAbsolutePath()) != null) {
                            mdbContexts = jarMDBMap.get(scanJarFile.getAbsolutePath());
                        } else {
                            mdbContexts = new ConcurrentHashMap<String, MDBContext>();
                        }
                        jarMDBMap.put("file:///" + scanJarFile.getAbsolutePath().replace("\\", "/"),
                                mdbContexts);
                        MDBContext mdbContextOld;
                        for (Class<?> mdbBean : clsMessageDriven) {
                            String classwithpackage = mdbBean.getName();
                            System.out.println("class package" + classwithpackage);
                            classwithpackage = classwithpackage.replace("/", ".");
                            System.out.println("classList:" + classwithpackage.replace("/", "."));
                            try {
                                if (!classwithpackage.contains("$")) {
                                    //System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass);
                                    //System.out.println();
                                    if (!mdbBean.isInterface()) {
                                        Annotation[] classServicesAnnot = mdbBean.getDeclaredAnnotations();
                                        if (classServicesAnnot != null) {
                                            for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) {
                                                if (classServicesAnnot[annotcount] instanceof MessageDriven) {
                                                    MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount];
                                                    ActivationConfigProperty[] activationConfigProperties = messageDrivenAnnot
                                                            .activationConfig();
                                                    mdbContext = new MDBContext();
                                                    mdbContext.setMdbName(messageDrivenAnnot.name());
                                                    for (ActivationConfigProperty activationConfigProperty : activationConfigProperties) {
                                                        if (activationConfigProperty.propertyName()
                                                                .equals(MDBContext.DESTINATIONTYPE)) {
                                                            mdbContext.setDestinationType(
                                                                    activationConfigProperty.propertyValue());
                                                        } else if (activationConfigProperty.propertyName()
                                                                .equals(MDBContext.DESTINATION)) {
                                                            mdbContext.setDestination(
                                                                    activationConfigProperty.propertyValue());
                                                        } else if (activationConfigProperty.propertyName()
                                                                .equals(MDBContext.ACKNOWLEDGEMODE)) {
                                                            mdbContext.setAcknowledgeMode(
                                                                    activationConfigProperty.propertyValue());
                                                        }
                                                    }
                                                    if (mdbContext.getDestinationType()
                                                            .equals(Queue.class.getName())) {
                                                        mdbContextOld = null;
                                                        if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                            mdbContextOld = mdbContexts
                                                                    .get(mdbContext.getMdbName());
                                                            if (mdbContextOld != null
                                                                    && mdbContext.getDestination().equals(
                                                                            mdbContextOld.getDestination())) {
                                                                throw new Exception(
                                                                        "Only one MDB can listen to destination:"
                                                                                + mdbContextOld
                                                                                        .getDestination());
                                                            }
                                                        }
                                                        mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                        Queue queue = (Queue) jms
                                                                .lookup(mdbContext.getDestination());
                                                        Connection connection = connectionFactory
                                                                .createConnection("guest", "guest");
                                                        connection.start();
                                                        Session session;
                                                        if (mdbContext.getAcknowledgeMode() != null
                                                                && mdbContext.getAcknowledgeMode()
                                                                        .equals("Auto-Acknowledge")) {
                                                            session = connection.createSession(false,
                                                                    Session.AUTO_ACKNOWLEDGE);
                                                        } else {
                                                            session = connection.createSession(false,
                                                                    Session.AUTO_ACKNOWLEDGE);
                                                        }
                                                        MessageConsumer consumer = session
                                                                .createConsumer(queue);
                                                        consumer.setMessageListener(
                                                                (MessageListener) mdbBean.newInstance());
                                                        mdbContext.setConnection(connection);
                                                        mdbContext.setSession(session);
                                                        mdbContext.setConsumer(consumer);
                                                        System.out.println("Queue=" + queue);
                                                    } else if (mdbContext.getDestinationType()
                                                            .equals(Topic.class.getName())) {
                                                        if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                            mdbContextOld = mdbContexts
                                                                    .get(mdbContext.getMdbName());
                                                            if (mdbContextOld.getConsumer() != null)
                                                                mdbContextOld.getConsumer()
                                                                        .setMessageListener(null);
                                                            if (mdbContextOld.getSession() != null)
                                                                mdbContextOld.getSession().close();
                                                            if (mdbContextOld.getConnection() != null)
                                                                mdbContextOld.getConnection().close();
                                                        }
                                                        mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                        Topic topic = (Topic) jms
                                                                .lookup(mdbContext.getDestination());
                                                        Connection connection = connectionFactory
                                                                .createConnection("guest", "guest");
                                                        connection.start();
                                                        Session session;
                                                        if (mdbContext.getAcknowledgeMode() != null
                                                                && mdbContext.getAcknowledgeMode()
                                                                        .equals("Auto-Acknowledge")) {
                                                            session = connection.createSession(false,
                                                                    Session.AUTO_ACKNOWLEDGE);
                                                        } else {
                                                            session = connection.createSession(false,
                                                                    Session.AUTO_ACKNOWLEDGE);
                                                        }
                                                        MessageConsumer consumer = session
                                                                .createConsumer(topic);
                                                        consumer.setMessageListener(
                                                                (MessageListener) mdbBean.newInstance());
                                                        mdbContext.setConnection(connection);
                                                        mdbContext.setSession(session);
                                                        mdbContext.setConsumer(consumer);
                                                        System.out.println("Topic=" + topic);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }
                    classLoader.close();
                    System.out.println(scanJarFile.getAbsolutePath() + " Deployed");
                }
            }
        }
        FileSystemOptions opts = new FileSystemOptions();
        FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
        fsManager.init();
        for (String dir : dirsToScan) {
            if (dir.startsWith("ftp://")) {
                listendir = fsManager.resolveFile(dir, opts);
            } else {
                listendir = fsManager.resolveFile(dir);
            }
            fm.addFile(listendir);
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    fm.setRecursive(true);
    fm.setDelay(1000);
    fm.start();
}

From source file:org.deegree.workspace.standard.ModuleInfo.java

/**
 * Returns the {@link ModuleInfo} for the deegree module on the given classpath.
 * /*from  ww  w.j  ava2 s  .co  m*/
 * @param classpathURL
 *            classpath url, must not be <code>null</code>
 * @return module info or <code>null</code> (if the module does not have file META-INF/deegree/buildinfo.properties)
 * @throws IOException
 *             if accessing <code>META-INF/deegree/buildinfo.properties</code> or
 *             <code>META-INF/maven/[..]/pom.properties</code> fails
 */
public static ModuleInfo extractModuleInfo(URL classpathURL) throws IOException {

    ModuleInfo moduleInfo = null;

    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder = builder.setUrls(classpathURL);
    builder = builder.setScanners(new ResourcesScanner());
    Reflections r = new Reflections(builder);

    Set<String> resources = r.getResources(Pattern.compile("(MANIFEST\\.MF|buildinfo\\.properties)"));
    if (!resources.isEmpty()) {
        URLClassLoader classLoader = new URLClassLoader(new URL[] { classpathURL }, null);
        String resourcePath = resources.iterator().next();
        InputStream buildInfoStream = null;
        try {
            Properties props = new Properties();
            buildInfoStream = classLoader.getResourceAsStream(resourcePath);
            props.load(buildInfoStream);
            String buildBy = props.getProperty("deegree-build-by", props.getProperty("build.by"));
            String buildArtifactId = props.getProperty("deegree-build-artifactId",
                    props.getProperty("build.artifactId"));
            String buildDate = props.getProperty("deegree-build-date", props.getProperty("build.date"));
            String buildRev = props.getProperty("deegree-build-rev", props.getProperty("build.svnrev"));
            String pomVersion = null;

            if (buildArtifactId == null) {
                // skipping because this jar is not from deegree
                return null;
            }

            resources = r.getResources(Pattern.compile("pom\\.properties"));
            InputStream pomInputStream = null;
            if (!resources.isEmpty()) {
                resourcePath = resources.iterator().next();
                try {
                    props = new Properties();
                    pomInputStream = classLoader.findResource(resourcePath).openStream();
                    props.load(pomInputStream);
                    String pomArtifactId = props.getProperty("artifactId");
                    if (!pomArtifactId.equals(buildArtifactId)) {
                        LOG.warn(
                                "ArtifactId mismatch for module on path: {} (MANIFEST.MF/buildinfo.properties vs. pom.properties).",
                                classpathURL);
                    }
                    pomVersion = props.getProperty("version");
                } finally {
                    closeQuietly(pomInputStream);
                }
            }
            moduleInfo = new ModuleInfo(buildArtifactId, pomVersion, buildRev, buildDate, buildBy);
        } finally {
            closeQuietly(buildInfoStream);
            // * closeQuietly( classLoader ); */ // TODO enable for JDK 1.7
        }
    }
    return moduleInfo;
}

From source file:com.fujitsu.dc.engine.extension.support.ExtensionJarLoader.java

/**
 * .//from w w  w .  ja  va  2 s.c  o  m
 * PCS????????????????? getInstance()???
 * @param extJarDir Extensionjar??
 * @param searchDescend true: ?, false: ????
 * @param parentCl 
 * @param filter Extension
 * @throws IOException Extension????
 * @throws DcEngineException 
 */
private ExtensionJarLoader(Path extJarDir, boolean searchDescend, ClassLoader parentCl,
        ExtensionClassFilter filter) throws IOException, DcEngineException {
    extensionJarDirectory = extJarDir;
    searchDescendant = searchDescend;
    List<URL> jarPaths = getJarPaths(extensionJarDirectory, searchDescendant);
    classloader = new URLClassLoader(jarPaths.toArray(new URL[] {}), parentCl);

    scriptableClassSet = loadPrototypeClassSet(jarPaths, filter);
}