Example usage for org.apache.commons.io FileUtils toURLs

List of usage examples for org.apache.commons.io FileUtils toURLs

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils toURLs.

Prototype

public static URL[] toURLs(File[] files) throws IOException 

Source Link

Document

Converts each of an array of File to a URL.

Usage

From source file:fi.jumi.actors.maven.GenerateEventStubsMojo.java

private static Class<?> loadFromClasspath(String className, File[] classpath) throws ClassNotFoundException {
    try {/*from  w  w w .  ja va  2s .  c  om*/
        URL[] urls = FileUtils.toURLs(classpath);
        URLClassLoader loader = new URLClassLoader(urls);
        return loader.loadClass(className);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.cubeia.maven.plugin.firebase.FirebaseRunPlugin.java

@SuppressWarnings("unchecked")
private ClassLoader createClassLoader(FirebaseDirectory dir) throws MojoExecutionException {
    List<File> list = new LinkedList<File>();
    list.add(dir.binDirectory);/*from ww w . j a v  a2  s.c o  m*/
    list.add(new File(dir.binDirectory, "firebase-bootstrap.jar"));
    list.addAll(FileUtils.listFiles(dir.commonLibDirectory, new String[] { "jar" }, false));
    list.add(dir.firebaseDirectory);
    list.add(dir.confDirectory);
    File[] arr = new File[list.size()];
    list.toArray(arr);
    try {
        URL[] urls = FileUtils.toURLs(arr);
        return new URLClassLoader(urls);
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to create URL for class path", e);
    }
}

From source file:org.apache.usergrid.cassandra.CassandraResource.java

/**
 * Starts up Cassandra before TestSuite or test Class execution.
 *
 * @throws Throwable if we cannot start up Cassandra
 *///from  w w w  . j av  a  2s. com
@Override
protected void before() throws Throwable {
    /*
     * Note that the lock is static so it is JVM wide which prevents other
     * instances of this class from making changes to the Cassandra system
     * properties while we are initializing Cassandra with unique settings.
     */

    synchronized (lock) {
        super.before();

        if (isReady()) {
            return;
        }

        LOG.info("Initializing Cassandra at {} ...", tempDir.toString());

        // Create temp directory, setup to create new File configuration there
        File newYamlFile = new File(tempDir, "cassandra.yaml");
        URL newYamlUrl = FileUtils.toURLs(new File[] { newYamlFile })[0];

        // Read the original yaml file, make changes, and dump to new position in tmpdir
        Yaml yaml = new Yaml();
        @SuppressWarnings("unchecked")
        Map<String, Object> map = (Map<String, Object>) yaml
                .load(ClassLoader.getSystemResourceAsStream("cassandra.yaml"));
        map.put(RPC_PORT_KEY, getRpcPort());
        map.put(STORAGE_PORT_KEY, getStoragePort());
        map.put(SSL_STORAGE_PORT_KEY, getSslStoragePort());
        map.put(NATIVE_TRANSPORT_PORT_KEY, getNativeTransportPort());
        map.put(COMMIT_FILE_DIR_KEY, new File(tempDir, "commitlog").toString());
        map.put(DATA_FILE_DIR_KEY, new String[] { new File(tempDir, "data").toString() });
        map.put(SAVED_CACHES_DIR_KEY, new File(tempDir, "saved_caches").toString());
        FileWriter writer = new FileWriter(newYamlFile);
        yaml.dump(map, writer);
        writer.flush();
        writer.close();

        // Fire up Cassandra by setting configuration to point to new yaml file
        System.setProperty("cassandra.url", "localhost:" + Integer.toString(rpcPort));
        System.setProperty("cassandra-foreground", "true");
        System.setProperty("log4j.defaultInitOverride", "true");
        System.setProperty("log4j.configuration", "log4j.properties");
        System.setProperty("cassandra.ring_delay_ms", "100");
        System.setProperty("cassandra.config", newYamlUrl.toString());

        //while ( !AvailablePortFinder.available( rpcPort ) || rpcPort == 9042 ) {
        // why previously has a or condition of rpc == 9042?
        while (!AvailablePortFinder.available(rpcPort)) {
            rpcPort++;
        }

        while (!AvailablePortFinder.available(storagePort)) {
            storagePort++;
        }

        while (!AvailablePortFinder.available(sslStoragePort)) {
            sslStoragePort++;
        }

        while (!AvailablePortFinder.available(nativeTransportPort)) {
            nativeTransportPort++;
        }

        System.setProperty("cassandra." + RPC_PORT_KEY, Integer.toString(rpcPort));
        System.setProperty("cassandra." + STORAGE_PORT_KEY, Integer.toString(storagePort));
        System.setProperty("cassandra." + SSL_STORAGE_PORT_KEY, Integer.toString(sslStoragePort));
        System.setProperty("cassandra." + NATIVE_TRANSPORT_PORT_KEY, Integer.toString(nativeTransportPort));

        LOG.info(
                "before() test, setting system properties for ports : [rpc, storage, sslStoage, native] = [{}, {}, {}, {}]",
                new Object[] { rpcPort, storagePort, sslStoragePort, nativeTransportPort });
        if (!newYamlFile.exists()) {
            throw new RuntimeException("Cannot find new Yaml file: " + newYamlFile);
        }

        cassandraDaemon = new CassandraDaemon();
        cassandraDaemon.activate();

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                after();
            }
        });

        String[] locations = { "usergrid-test-context.xml" };
        applicationContext = new ClassPathXmlApplicationContext(locations);

        loadSchemaManager(schemaManagerName);
        initialized = true;
        LOG.info("External Cassandra resource at {} is ready!", tempDir.toString());
        lock.notifyAll();
    }
}

From source file:org.grycap.gpf4med.graph.base.PipelineTest.java

@Test
public void test() {
    System.out.println("PipelineTest.test()");
    File graphvizFile = null;//from  w w  w  . j  a  v a 2s .  c  om
    try {
        // load example templates
        final Collection<File> templateFiles = TestUtils.getTemplateFiles();
        TemplateManager.INSTANCE
                .setup(Arrays.asList(FileUtils.toURLs(templateFiles.toArray(new File[templateFiles.size()]))));
        TemplateManager.INSTANCE.preload();
        // load example reports in the graph
        GraphDatabaseHandler.INSTANCE.restart();
        GraphDatabaseHandler.INSTANCE.setConnector(new BaseGraphConnector());
        final Collection<File> reportFiles = TestUtils.getReportFiles();
        final ImmutableList<URL> urls = new ImmutableList.Builder<URL>()
                .add(FileUtils.toURLs(reportFiles.toArray(new File[reportFiles.size()]))).build();
        Statistics.INSTANCE.setTotalSubmitted(reportFiles.size());
        // start asynchronously load
        DocumentFetcher.INSTANCE.fecth(urls);
        graphvizFile = GraphvizPrinter.print(GraphDatabaseHandler.INSTANCE.service(),
                RandomStringUtils.random(8, true, true) + ".dot");
        assertThat("graphviz file is not null", graphvizFile, notNullValue());
        final String graphvizStr = FileUtils.readFileToString(graphvizFile);
        System.out.println(graphvizFile.getAbsolutePath());
        assertThat("graphviz string is not null", graphvizStr, notNullValue());
        assertThat("graphviz string is not empty", StringUtils.isNotBlank(graphvizStr));
        /* uncomment for additional output
        System.out.println(" >> Graphviz\n" + graphvizStr + "\n"); */

        FileUtils.copyFile(graphvizFile, new File("/opt/trencadis/mammography_graph.dot"));

    } catch (Exception e) {
        e.printStackTrace(System.err);
        fail("PipelineTest.test() failed: " + e.getMessage());
    } finally {
        FileUtils.deleteQuietly(graphvizFile);
        System.out.println("PipelineTest.test() has finished");
    }
}

From source file:org.grycap.gpf4med.util.TestUtils.java

public static void getTemplateFiles() {
    final File dir = new File(FilenameUtils.concat(AllUnitTests.TEST_RESOURCES_PATH, TEMPLATES_FOLDER));
    Collection<File> files = FileUtils.listFiles(dir, new String[] { "xml" }, false);
    try {/*  w w w.  j  a v a  2 s.c om*/
        TemplateManager.INSTANCE.setup(Arrays.asList(FileUtils.toURLs(files.toArray(new File[files.size()]))));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.grycap.gpf4med.util.TestUtils.java

public static void getReportFiles() {
    final File dir = new File(FilenameUtils.concat(AllUnitTests.TEST_RESOURCES_PATH, REPORTS_FOLDER));
    Collection<File> files = FileUtils.listFiles(dir, new String[] { "xml" }, false);
    try {/*from ww w .  j av  a2  s  . c o  m*/
        DocumentManager.INSTANCE.setup(Arrays.asList(FileUtils.toURLs(files.toArray(new File[files.size()]))));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.jbpm.formbuilder.server.trans.gwt.Translator.java

@Override
public URL translateForm(FormRepresentation form) throws TranslatorException {
    FormRepresentationEncoder encoder = FormEncodingServerFactory.getEncoder();
    try {/*  ww w  .  j a  v a2 s .c o  m*/
        String json = encoder.encode(form);
        File file = File.createTempFile("form-gwt-", ".json");
        FileUtils.writeStringToFile(file, json);
        return FileUtils.toURLs(new File[] { file })[0];
    } catch (IOException e) {
        throw new TranslatorException("Problem writing temporal file", e);
    } catch (FormEncodingException e) {
        throw new TranslatorException("Problem encoding form", e);
    }
}

From source file:org.kalypso.util.themes.image.controls.ImageComposite.java

/**
 * This function creates the image group.
 * //w  w w  .j  a va 2 s  .  c  o m
 * @param parent
 *          The parent composite.
 * @return The image group.
 */
private Group createImageGroup(final Composite parent) {
    /* Create a group. */
    final Group imageGroup = new Group(parent, SWT.NONE);
    imageGroup.setLayout(new GridLayout(3, false));
    imageGroup.setText(Messages.getString("ImageComposite_0")); //$NON-NLS-1$

    /* Create a label. */
    final Label backgroundColorLabel = new Label(imageGroup, SWT.NONE);
    backgroundColorLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
    backgroundColorLabel.setText(Messages.getString("ImageComposite_1")); //$NON-NLS-1$
    backgroundColorLabel.setAlignment(SWT.LEFT);

    /* Create a label. */
    final Label backgroundLabel = new Label(imageGroup, SWT.BORDER);
    backgroundLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
    backgroundLabel.setText(Messages.getString("ImageComposite_2")); //$NON-NLS-1$
    backgroundLabel.setBackground(new Color(parent.getDisplay(), m_background));

    backgroundLabel.addDisposeListener(new DisposeListener() {
        @Override
        public void widgetDisposed(final DisposeEvent e) {
            backgroundLabel.getBackground().dispose();
        }
    });

    /* Create a button. */
    final Button backgroundColorButton = new Button(imageGroup, SWT.PUSH);
    backgroundColorButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
    backgroundColorButton.setText("..."); //$NON-NLS-1$
    backgroundColorButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(final SelectionEvent e) {
            final Shell shell = ImageComposite.this.getShell();

            final ColorDialog dialog = new ColorDialog(shell);
            dialog.setRGB(m_background);
            final RGB rgb = dialog.open();
            if (rgb == null)
                return;

            m_background = rgb;

            backgroundLabel.getBackground().dispose();
            backgroundLabel.setBackground(new Color(parent.getDisplay(), m_background));

            fireImagePropertyChanged(getProperties(), m_horizontal, m_vertical, m_background, m_imageUrl);
        }
    });

    /* Create a label. */
    final Label imageUrlLabel = new Label(imageGroup, SWT.NONE);
    imageUrlLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
    imageUrlLabel.setText(Messages.getString("ImageComposite_4")); //$NON-NLS-1$
    imageUrlLabel.setAlignment(SWT.LEFT);

    /* Create a text field. */
    final Text imageUrlText = new Text(imageGroup, SWT.BORDER);
    final GridData imageUrlData = new GridData(SWT.FILL, SWT.CENTER, true, false);
    imageUrlData.widthHint = 250;
    imageUrlText.setLayoutData(imageUrlData);
    if (m_imageUrl != null)
        imageUrlText.setText(m_imageUrl);

    /* Add a listener. */
    imageUrlText.addModifyListener(new ModifyListener() {
        /**
         * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent)
         */
        @Override
        public void modifyText(final ModifyEvent e) {
            /* Reset the URL of the image. */
            m_imageUrl = null;

            /* Get the source. */
            final Text source = (Text) e.getSource();

            /* Get the text. */
            final String text = source.getText();

            /* Create the URL of the image. */
            if (text != null && text.length() > 0)
                m_imageUrl = text;

            /* Fire the image property changed event. */
            fireImagePropertyChanged(getProperties(), m_horizontal, m_vertical, m_background, m_imageUrl);
        }
    });

    /* Create a button. */
    final Button imageUrlButton = new Button(imageGroup, SWT.PUSH);
    imageUrlButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
    imageUrlButton.setText(Messages.getString("ImageComposite_5")); //$NON-NLS-1$

    /* Add a listener. */
    imageUrlButton.addSelectionListener(new SelectionAdapter() {
        /**
         * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
         */
        @Override
        public void widgetSelected(final SelectionEvent e) {
            try {
                /* Create a file dialog. */
                final FileDialog dialog = new FileDialog(ImageComposite.this.getShell(), SWT.OPEN);
                dialog.setText(Messages.getString("ImageComposite_6")); //$NON-NLS-1$
                dialog.setFilterExtensions(new String[] { "*.bmp", "*.png", "*.gif", "*.jpg", "*.tif" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
                dialog.setFilterNames(new String[] { Messages.getString("ImageComposite_12"), //$NON-NLS-1$
                        Messages.getString("ImageComposite_13"), Messages.getString("ImageComposite_14"), //$NON-NLS-1$//$NON-NLS-2$
                        Messages.getString("ImageComposite_15"), Messages.getString("ImageComposite_16") }); //$NON-NLS-1$ //$NON-NLS-2$

                /* Open the dialog. */
                final String file = dialog.open();
                if (file == null)
                    return;

                /* Set the URL of the image. */
                final URL[] urls = FileUtils.toURLs(new File[] { new File(file) });
                imageUrlText.setText(urls[0].toExternalForm());
            } catch (final IOException ex) {
                /* Print the stack trace. */
                ex.printStackTrace();
            }
        }
    });

    return imageGroup;
}

From source file:org.pepstock.jem.springbatch.tasks.utilities.MainLauncherTasklet.java

/**
 * Loads java class from className and for classpath
 * @param className classname to be loaded
 * @return class object loaded from classpath
 * @throws IOException if any error occurs
 * @throws ClassNotFoundException if any error occurs
 *///from   w  ww . ja v  a  2s  .  c  om
private Class<?> loadCustomClass(String classNam) throws IOException, ClassNotFoundException {
    // CLASSPATH has been set therefore it an try to load the plugin by
    // a custom classloader
    // collection of all file of classpath
    Collection<File> files = new LinkedList<File>();

    for (String classPathFile : classPath) {
        classPathFile = FilenameUtils.normalize(classPathFile, true);
        // checks if a item contains more than 1 path
        String[] paths = null;
        if (classPathFile.contains(File.pathSeparator)) {
            // substitute variables if there are and split
            paths = StringUtils.split(JobsProperties.getInstance().replacePlaceHolders(classPathFile),
                    File.pathSeparator);
        } else if (classPathFile.contains(";")) {
            // substitute variables if there are and split
            paths = StringUtils.split(JobsProperties.getInstance().replacePlaceHolders(classPathFile), ";");
        } else {
            // substitute variables if there are and assign
            paths = new String[] { JobsProperties.getInstance().replacePlaceHolders(classPathFile) };
        }
        if (paths != null) {
            for (String path : paths) {
                // creates the file
                File file = new File(path);
                // if file ends with * could be only this folder or all folders
                // in cascade
                if (path.endsWith(ClassLoaderUtil.ALL_FOLDER)) {
                    // checks if is all folders in cascade
                    boolean cascade = path.endsWith(ClassLoaderUtil.ALL_FOLDER_IN_CASCADE);
                    // gets the parent and asks for all JAR files
                    File parent = file.getParentFile();
                    Collection<File> newFiles = FileUtils.listFiles(parent,
                            ClassLoaderUtil.EXTENSIONS.toArray(new String[0]), cascade);
                    // loads to the collection
                    files.addAll(newFiles);
                } else if (file.isDirectory() && file.exists()) {
                    // if here, we have a directory
                    // adds the directory to collection
                    files.add(file);
                } else if (file.isFile() && file.exists()) {
                    // if here, a file has been indicated
                    // adds the directory to collection
                    files.add(file);
                }
            }
        }
    }
    // checks if the collection is empty.
    // if yes, all classpath definiton is wrong and no files have been
    // loaded
    if (!files.isEmpty()) {
        // gets where the class is located
        // because it must be added to classpath
        CodeSource codeSource = JavaMainClassLauncher.class.getProtectionDomain().getCodeSource();
        if (codeSource != null) {
            // gets URL
            URL url = codeSource.getLocation();
            if (url != null) {
                // adds URL to classpath
                files.add(FileUtils.toFile(url));
            }
        }
        // exports files in URLs, for our classloader
        final URL[] urls = FileUtils.toURLs(files.toArray(new File[files.size()]));
        // loads a our classloader by access controller
        ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                return new ReverseURLClassLoader(urls, MainLauncherTasklet.class.getClassLoader(), false);
            }
        });
        // loads the plugin from classloader
        return loader.loadClass(className);
    } else {
        throw new IOException(UtilMessage.JEMB009E.toMessage().getMessage());
    }
}

From source file:org.pepstock.jem.util.ClassLoaderUtil.java

/**
 * Loads all classpath information from plugin configuration and creates a
 * custom classloader to load the plugin.
 * //from   w  ww.j  a va2  s  .  c o m
 * @param pluginDef plugin defintion
 * @param props list of properties to used to substitute if necessary
 * @param knownLoader ClassLoader already created previously
 * @return containers with object instantiated and class path based on URLs
 * @throws InstantiationException if any error occurs
 * @throws IllegalAccessException if any error occurs
 * @throws ClassNotFoundException if any error occurs
 * @throws IOException if any error occurs
 */
public static ObjectAndClassPathContainer loadAbstractPlugin(AbstractPluginDefinition pluginDef,
        Properties props, ClassLoader knownLoader)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException, IOException {
    // creates the result to return
    ObjectAndClassPathContainer result = new ObjectAndClassPathContainer();

    if (knownLoader != null) {
        // there already a classloader
        // loads the plugin from classloader
        Class<?> clazz = knownLoader.loadClass(pluginDef.getClassName());
        // sets the object
        result.setObject(clazz.newInstance());
        return result;
    } else if (pluginDef.getClasspath() == null || pluginDef.getClasspath().isEmpty()) {
        // if plugin defintion doesn't have the classpath, that means that the
        // plugin is already placed in JEM classpath
        // therefore it's enough to call it
        // load by Class.forName of factory
        result.setObject(Class.forName(pluginDef.getClassName()).newInstance());
    } else {
        // CLASSPATH has been set therefore it an try to load the plugin by
        // a custom classloader
        // collection of all file of classpath
        Collection<File> files = new LinkedList<File>();
        // scans all strings of classpath
        for (ClassPath classPath : pluginDef.getClasspath()) {
            // substitute variables if there are
            String path = VariableSubstituter.substitute(classPath.getContent(), props);
            // creates the file
            File file = new File(path);
            // if file ends with * could be only this folder or all folders
            // in cascade
            if (path.endsWith(ALL_FOLDER)) {
                // checks if is all folders in cascade
                boolean cascade = path.endsWith(ALL_FOLDER_IN_CASCADE);
                // gets the parent and asks for all JAR files
                File parent = file.getParentFile();
                Collection<File> newFiles = FileUtils.listFiles(parent, EXTENSIONS.toArray(new String[0]),
                        cascade);
                // loads to the collection
                files.addAll(newFiles);
                if (cascade) {
                    // scan all files to extract folder to add classpath
                    // with *, standard JAVA
                    for (File newFile : newFiles) {
                        String parentNormalized = newFile.getParentFile().getAbsolutePath() + File.separator
                                + ALL_FOLDER;
                        // if the path is not already in the result, load it
                        if (!result.getClassPath().contains(parentNormalized)) {
                            result.getClassPath().add(parentNormalized);
                        }
                    }
                } else {
                    // loads all files
                    if (!result.getClassPath().contains(file.getAbsolutePath())) {
                        result.getClassPath().add(file.getAbsolutePath());
                    }
                }
            } else if (file.isDirectory() && file.exists()) {
                // if here, we have a directory
                // adds the directory to collection
                files.add(file);
                if (!result.getClassPath().contains(file.getAbsolutePath())) {
                    result.getClassPath().add(file.getAbsolutePath());
                }
            } else if (file.isFile() && file.exists()) {
                // if here, a file has been indicated
                // adds the directory to collection
                files.add(file);
                if (!result.getClassPath().contains(file.getAbsolutePath())) {
                    result.getClassPath().add(file.getAbsolutePath());
                }
            }
        }
        // checks if the collection is empty.
        // if yes, all classpath definiton is wrong and no files have been
        // loaded
        if (!files.isEmpty()) {
            // exports files in URLs, for our classloader
            final URL[] urls = FileUtils.toURLs(files.toArray(new File[files.size()]));
            // loads a our classloader by access controller
            ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
                public ClassLoader run() {
                    return new ReverseURLClassLoader(urls, Main.class.getClassLoader());
                }
            });
            // loads the plugin from classloader
            Class<?> clazz = loader.loadClass(pluginDef.getClassName());
            // sets the object
            result.setObject(clazz.newInstance());
            result.setLoader(loader);
        } else {
            throw new IOException(UtilMessage.JEMB009E.toMessage().getMessage());
        }
    }
    return result;
}