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

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

Introduction

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

Prototype

public static File toFile(URL url) 

Source Link

Document

Convert from a URL to a File.

Usage

From source file:org.onehippo.repository.bootstrap.InitializationProcessorTest.java

@Test
public void testMissingWebFileBundleInitializationLogsError() throws Exception {
    final URL testBundleUrl = getClass().getResource("/hippoecm-extension.xml");

    item.setProperty(HIPPO_WEB_FILE_BUNDLE, "noSuchDirectory");
    item.setProperty(HIPPO_EXTENSIONSOURCE, testBundleUrl.toString());
    session.save();/*from   w  w  w  .  j av  a 2 s .c o m*/

    final List<PostStartupTask> tasks = process();
    assertEquals("There should be one post-startup task", 1, tasks.size());

    // test the post-startup task
    final PostStartupTask importWebFiles = tasks.get(0);

    final File testBundleDir = new File(FileUtils.toFile(testBundleUrl).getParent(), "noSuchDirectory");
    webFilesService.importJcrWebFileBundle(anyObject(Session.class), eq(testBundleDir), anyBoolean());
    expectLastCall().andThrow(new WebFileException("simulate a web file exception during import"));

    replay(webFilesService);
    importWebFiles.execute();
    verify(webFilesService);

    assertEquals("expected an error message to be logged", 1, loggingRecorder.getErrorMessages().size());
}

From source file:org.onehippo.repository.bootstrap.instructions.WebFileBundleInstruction.java

private PostStartupTask createImportWebFileTask(final String extensionSource, final String bundlePath,
        final Session session) throws IOException, URISyntaxException {
    if (extensionSource == null) {
        return null;
    } else if (extensionSource.contains("jar!")) {
        final PartialZipFile bundleZipFile = new PartialZipFile(getBaseZipFileFromURL(new URL(extensionSource)),
                bundlePath);/*from   w w w .j a  v a2s  .c  o  m*/
        return new ImportWebFileBundleFromZipTask(session, bundleZipFile);
    } else if (extensionSource.startsWith("file:")) {
        final File extensionFile = FileUtils.toFile(new URL(extensionSource));
        final File bundleDir = new File(extensionFile.getParent(), bundlePath);
        return new ImportWebFileBundleFromDirectoryTask(session, bundleDir);
    }
    return null;
}

From source file:org.onehippo.repository.bootstrap.util.PartialZipFileTest.java

@Before
public void setUp() throws Exception {
    testZipFile = FileUtils.toFile(getClass().getResource("/bootstrap/path with spaces/SubZipFileTest.zip"));
}

From source file:org.openvpms.component.business.service.archetype.descriptor.cache.ArchetypeDescriptorCacheFS.java

/**
 * Load and parse all the archetypes that are defined in the files of the
 * speciied directory. Only process files with the nominated extensions. If
 * the directory is invalid or if any of the files in the directory are
 * invalid throw an exception.//from  w w w  .  j ava  2  s .c o m
 * <p/>
 * The archetypes will be cached in memory.
 *
 * @param adir       the directory to search
 * @param extensions the file extensions to check
 * @throws ArchetypeDescriptorCacheException
 *
 */
private void loadArchetypeDescriptorsInDir(String adir, String[] extensions) {

    // check that a non-null directory was specified
    if (StringUtils.isEmpty(adir)) {
        throw new ArchetypeDescriptorCacheException(ArchetypeDescriptorCacheException.ErrorCode.NoDirSpecified);
    }

    // check that a valid directory was specified
    File dir = FileUtils.toFile(Thread.currentThread().getContextClassLoader().getResource(adir));
    if (dir == null) {
        throw new ArchetypeDescriptorCacheException(ArchetypeDescriptorCacheException.ErrorCode.InvalidDir,
                new Object[] { adir });
    }

    if (!dir.isDirectory()) {
        throw new ArchetypeDescriptorCacheException(ArchetypeDescriptorCacheException.ErrorCode.InvalidDir,
                new Object[] { adir });
    }

    // process all the files in the directory, that match the filter
    Collection collection = FileUtils.listFiles(dir, extensions, true);
    for (Object f : collection) {
        File file = (File) f;
        try {
            if (logger.isDebugEnabled()) {
                logger.debug("Attempting to process records in " + file.getName());
            }

            processArchetypeDescriptors(loadArchetypeDescriptors(new FileReader(file)));
        } catch (Exception exception) {
            // do not throw an exception but log a warning
            logger.warn("Failed to load archetype",
                    new ArchetypeDescriptorCacheException(
                            ArchetypeDescriptorCacheException.ErrorCode.InvalidFile,
                            new Object[] { file.getName() }, exception));
        }

    }

}

From source file:org.openvpms.component.business.service.ruleengine.DirectoryRuleSource.java

protected void registerRuleExecutionSets() throws RuleEngineException {
    // check that a non-null directory was specified
    if (StringUtils.isEmpty(directory)) {
        throw new RuleEngineException(RuleEngineException.ErrorCode.NoDirSpecified);
    }//from  ww w.j  av  a  2  s .c  om

    // check that a valid directory was specified
    File dir = FileUtils.toFile(Thread.currentThread().getContextClassLoader().getResource(directory));
    if (dir == null) {
        throw new RuleEngineException(RuleEngineException.ErrorCode.InvalidDir, directory);
    }

    if (log.isDebugEnabled()) {
        log.debug("The base rules directory is " + dir.getAbsolutePath());
    }

    if (!dir.isDirectory()) {
        throw new RuleEngineException(RuleEngineException.ErrorCode.InvalidDir, directory);
    }

    // process all the files in the directory, that match the filter
    Collection collection = FileUtils.listFiles(dir, new String[] { "drl" }, true);
    for (Object object : collection) {
        File file = (File) object;
        if (log.isDebugEnabled()) {
            log.debug("Registering the rule set in " + file.getAbsolutePath());
        }
        registerRuleExecutionSet(file);
    }
}

From source file:org.pentaho.di.trans.steps.accessoutput.AccessOutput.java

private boolean OpenFile() throws Exception {
    data.oneFileOpened = true;/*from  w  w w . j a va  2  s .  c o m*/
    String realFilename = environmentSubstitute(meta.getFilename());
    if (log.isBasic()) {
        logBasic(BaseMessages.getString(PKG, "AccessOutput.log.WritingToFile", realFilename));
    }
    FileObject fileObject = KettleVFS.getFileObject(realFilename, getTransMeta());
    File file = FileUtils.toFile(fileObject.getURL());

    // First open or create the access file
    if (!file.exists()) {
        if (meta.isFileCreated()) {
            data.db = Database.create(file);
        } else {
            logError(BaseMessages.getString(PKG, "AccessOutput.InitError.FileDoesNotExist", realFilename));
            return false;
        }
    } else {
        data.db = Database.open(file);
    }

    // Add the filename to the result object...
    //
    if (meta.isAddToResultFiles()) {
        ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, fileObject,
                getTransMeta().getName(), toString());
        resultFile.setComment("This file was created with an access output step");
        addResultFile(resultFile);
    }

    return true;
}

From source file:org.pentaho.di.trans.steps.fixedinput.FixedInput.java

private FileInputStream getFileInputStream(URL url) throws FileNotFoundException {
    return new FileInputStream(FileUtils.toFile(url));
}

From source file:org.pentaho.di.ui.trans.steps.accessoutput.AccessOutputDialog.java

private void getTableName() {
    AccessOutputMeta meta = new AccessOutputMeta();
    getInfo(meta);//from  ww  w  .j av a  2 s.  c o m

    Database database = null;
    // New class: SelectTableDialog
    try {
        String realFilename = transMeta.environmentSubstitute(meta.getFilename());
        FileObject fileObject = KettleVFS.getFileObject(realFilename, transMeta);
        File file = FileUtils.toFile(fileObject.getURL());

        if (!file.exists() || !file.isFile()) {
            throw new KettleException(
                    BaseMessages.getString(PKG, "AccessOutputMeta.Exception.FileDoesNotExist", realFilename));
        }

        database = Database.open(file);
        Set<String> set = database.getTableNames();
        String[] tablenames = set.toArray(new String[set.size()]);
        EnterSelectionDialog dialog = new EnterSelectionDialog(shell, tablenames,
                BaseMessages.getString(PKG, "AccessOutputDialog.Dialog.SelectATable.Title"),
                BaseMessages.getString(PKG, "AccessOutputDialog.Dialog.SelectATable.Message"));
        String tablename = dialog.open();
        if (tablename != null) {
            wTablename.setText(tablename);
        }
    } catch (Throwable e) {
        new ErrorDialog(shell, BaseMessages.getString(PKG, "AccessOutputDialog.UnableToGetListOfTables.Title"),
                BaseMessages.getString(PKG, "AccessOutputDialog.UnableToGetListOfTables.Message"), e);
    } finally {
        // Don't forget to close the bugger.
        try {
            if (database != null) {
                database.close();
            }
        } catch (Exception e) {
            // Ignore close errors
        }
    }
}

From source file:org.pepstock.jem.ant.tasks.StepJava.java

/**
 * Change the main class of the stepjava becuase this is necessary if it wants to apply
 * the JEm annotation to the main java class developed with business logic.
 * /*from  w w w.  j a  v  a  2 s.  c o m*/
 * @throws NamingException if is not ableto get the right info from JNDI
 */
private void setCustomMainClass() throws NamingException {
    // sets here the annotations
    try {
        // if has got a classpath, change the main class with a JEM one
        if (super.getCommandLine().haveClasspath()) {
            Class<?> clazz = JavaMainClassLauncher.class;
            // gets where the class is located
            // becuase it must be added to classpath
            CodeSource codeSource = clazz.getProtectionDomain().getCodeSource();
            if (codeSource != null) {
                // gets URL
                URL url = codeSource.getLocation();
                if (url != null) {
                    // add at the ends of parameters the classname
                    super.createArg().setValue(getClassname());
                    // changes class name
                    super.setClassname(JavaMainClassLauncher.class.getName());
                    // adds URL to classpath
                    super.createClasspath()
                            .add(new Path(getProject(), FileUtils.toFile(url).getAbsolutePath()));
                }
            }
        } else {
            // if no classpath, can substitute here
            Class<?> clazz = Class.forName(getClassname());
            SetFields.applyByAnnotation(clazz);
        }
    } catch (ClassNotFoundException e) {
        LogAppl.getInstance().ignore(e.getMessage(), e);
    } catch (IllegalAccessException e) {
        LogAppl.getInstance().ignore(e.getMessage(), e);
    }
}

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  ww  w  . ja  v a  2  s .  c  o m*/
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());
    }
}