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.ebayopensource.turmeric.eclipse.utils.classloader.SOAPluginClassLoader.java

/**
 * Instantiates a new sOA plugin class loader.
 *
 * @param name the name/*from ww  w. java  2 s  .c  o  m*/
 * @param urls the urls
 */
public SOAPluginClassLoader(String name, URL[] urls) {
    super(EMPTY_URLS);

    for (int i = 0; i < urls.length; i++) {
        File file = FileUtils.toFile(urls[i]);
        if (file.isDirectory()) {
            m_dirURLs.add(urls[i]);
        } else if (file.isFile()) {
            m_jarURLs.add(urls[i]);
        }
    }
    for (URL dirURL : m_dirURLs) {
        addURL(dirURL);
    }
    m_classPathURLs.addAll(m_jarURLs);
    m_classPathURLs.addAll(m_dirURLs);
    if (logger.isLoggable(Level.FINE)) {
        logger.fine("Inside soa plugin loader setM_classPathURLs: " + m_classPathURLs);
    }
}

From source file:org.ebayopensource.turmeric.eclipse.utils.classloader.SOAPluginClassLoader.java

/**
 * {@inheritDoc}//w  w w.  jav a2s. c  o  m
 */
@Override
public URL findResource(String resourceName) {
    //logger.info("resource name in findresource is " + resourceName);
    try {
        URL retUrl = null;
        for (Bundle pluginBundle : pluginBundles) {
            retUrl = pluginBundle.getResource(resourceName);
            if (retUrl != null) {
                if (logger.isLoggable(Level.FINE)) {
                    logger.fine("found resource using bundle " + resourceName);
                }
                return retUrl;
            }
        }

    } catch (Exception exception) {
    }

    for (URL url : m_jarURLs) {

        try {
            File file = FileUtils.toFile(url);
            JarFile jarFile;
            jarFile = new JarFile(file);
            JarEntry jarEntry = jarFile.getJarEntry(resourceName);
            if (jarEntry != null) {
                SOAToolFileUrlHandler handler = new SOAToolFileUrlHandler(jarFile, jarEntry);
                URL retUrl = new URL("jar", "", -1,
                        new File(jarFile.getName()).toURI().toURL() + "!/" + jarEntry.getName(), handler);
                handler.setExpectedUrl(retUrl);
                return retUrl;

            }
        } catch (IOException e) {
            e.printStackTrace(); // KEEPME
        }

    }

    return super.findResource(resourceName);
}

From source file:org.ebayopensource.turmeric.eclipse.utils.io.IOUtil.java

/**
 * In the normal jar URLs usage in Windows Java puts a lock on it. And the
 * SOA Tool Handler will create a non locking URL by setting the caching
 * off. There is obviously a performance compromise made here by disabling
 * the cache.// w  w w. j  a v a  2 s  . co  m
 *
 * @param jarFileUrl the jar file url
 * @param jarEntryPath the jar entry path
 * @return the non locking url
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static URL getNonLockingURL(URL jarFileUrl, String jarEntryPath) throws IOException {
    File file = FileUtils.toFile(jarFileUrl);
    JarFile jarFile;
    jarFile = new JarFile(file);
    JarEntry jarEntry = jarFile.getJarEntry(jarEntryPath);
    if (jarEntry != null) {
        SOAToolFileUrlHandler handler = new SOAToolFileUrlHandler(jarFile, jarEntry);
        URL retUrl = new URL("jar", "", -1,
                new File(jarFile.getName()).toURI().toURL() + "!/" + jarEntry.getName(), handler);
        handler.setExpectedUrl(retUrl);
        return retUrl;

    }
    return null;
}

From source file:org.eclipse.jdt.ls.core.internal.handlers.DocumentLifeCycleHandlerTest.java

@Test
public void testDidOpenNotOnClasspath() throws Exception {
    importProjects("eclipse/hello");
    IProject project = WorkspaceHelper.getProject("hello");
    URI uri = project.getFile("nopackage/Test2.java").getRawLocationURI();
    ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri);
    String source = FileUtils.readFileToString(FileUtils.toFile(uri.toURL()));
    openDocument(cu, source, 1);/* w w w. j a va  2s. com*/
    Job.getJobManager().join(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor);
    assertEquals(project, cu.getJavaProject().getProject());
    assertEquals(source, cu.getSource());
    List<PublishDiagnosticsParams> diagnosticReports = getClientRequests("publishDiagnostics");
    assertEquals(1, diagnosticReports.size());
    PublishDiagnosticsParams diagParam = diagnosticReports.get(0);
    assertEquals(1, diagParam.getDiagnostics().size());
    closeDocument(cu);
    Job.getJobManager().join(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor);
    diagnosticReports = getClientRequests("publishDiagnostics");
    assertEquals(2, diagnosticReports.size());
    diagParam = diagnosticReports.get(1);
    assertEquals(0, diagParam.getDiagnostics().size());
}

From source file:org.eclipse.koneki.ldt.ui.internal.LuaDocumentationHelper.java

protected static String initStyleSheet() {
    Bundle bundle = Activator.getDefault().getBundle();
    URL styleSheetURL = bundle.getEntry(CSS_FILE_PATH);
    if (styleSheetURL == null) {
        String errorMessage = MessageFormat.format("No css found on the path: {1}", CSS_FILE_PATH); //$NON-NLS-1$
        Activator.logError(errorMessage, new NullPointerException());
    }/* www  .j  a v a2 s .c  o  m*/
    try {
        styleSheetURL = FileLocator.toFileURL(styleSheetURL);
        File cssFile = FileUtils.toFile(styleSheetURL);
        return FileUtils.readFileToString(cssFile);

    } catch (IOException ex) {
        Activator.logError("Unable to open CSS file for luadoc view", ex); //$NON-NLS-1$
    }
    return null;
}

From source file:org.esipfed.eskg.nlp.OpenIE.java

public static void main(String[] args) throws IOException {

    SentenceDetector sentenceDetector = null;
    try {/*from   w ww .  j a  va2 s.co  m*/
        // need to change this to the resource folder
        InputStream modelIn = OpenIE.class.getClassLoader().getResourceAsStream("en-sent.bin");
        final SentenceModel sentenceModel = new SentenceModel(modelIn);
        modelIn.close();
        sentenceDetector = new SentenceDetectorME(sentenceModel);
    } catch (IOException ioe) {
        LOG.error("Error either reading 'en-sent.bin' file or creating SentanceModel: ", ioe);
        throw new IOException(ioe);
    }
    edu.knowitall.openie.OpenIE openIE = new edu.knowitall.openie.OpenIE(
            new ClearParser(new ClearPostagger(new ClearTokenizer())), new ClearSrl(), false, false);

    // any text file that contains English sentences would work
    File file = FileUtils.toFile(OpenIE.class.getClassLoader().getResource("test.txt"));
    String text = readFile(file.getAbsolutePath(), StandardCharsets.UTF_8);

    if (sentenceDetector != null) {
        String[] sentences = sentenceDetector.sentDetect(text);
        for (int i = 0; i < sentences.length; i++) {

            Seq<Instance> extractions = openIE.extract(sentences[i]);

            List<Instance> listExtractions = JavaConversions.seqAsJavaList(extractions);

            for (Instance instance : listExtractions) {
                StringBuilder sb = new StringBuilder();

                sb.append(instance.confidence()).append('\t').append(instance.extr().context()).append('\t')
                        .append(instance.extr().arg1().text()).append('\t').append(instance.extr().rel().text())
                        .append('\t');

                List<Argument> listArg2s = JavaConversions.seqAsJavaList(instance.extr().arg2s());
                for (Argument argument : listArg2s) {
                    sb.append(argument.text()).append("; ");
                }

                LOG.info(sb.toString());
            }
        }
    }

}

From source file:org.grycap.gpf4med.DocumentFetcher.java

public void fecth(final ImmutableList<URL> urls) {
    checkArgument(urls != null, "Uninitialized URLs");
    final ImmutableMap.Builder<URI, File> pendingBuilder = new ImmutableMap.Builder<URI, File>();
    try {//from w w w.  jav a2s.  c  o m
        final File cacheDir = new File(ConfigurationManager.INSTANCE.getLocalCacheDir(), "reports");
        final ImmutableMap.Builder<URI, File> requestBuilder = new ImmutableMap.Builder<URI, File>();
        for (final URL url : urls) {
            try {
                if (URLUtils.isRemoteProtocol(url)) {
                    final URI source = url.toURI().normalize();
                    final File destination = new File(cacheDir,
                            NamingUtils.genSafeFilename(new String[] { source.toString() }, null, ".xml"));
                    requestBuilder.put(source, destination);
                } else if (URLUtils.isFileProtocol(url)) {
                    FileQueue.INSTANCE.add(FileUtils.toFile(url));
                } else {
                    FileQueue.INSTANCE.failed(1);
                    LOGGER.warn("Ignoring unsupported URL: " + url.toString());
                }
            } catch (Exception e2) {
                FileQueue.INSTANCE.failed();
            }
        }
        final DownloadConfiguration downloadConfig = new DownloadConfiguration(CONNECTION_TIMEOUT_MILLIS,
                READ_TIMEOUT_MILLIS, RETRIES, TIMEOUT_INCREMENT_PERCENTAGE);
        final ImmutableMap<URI, File> pending = new DownloadService().download(requestBuilder.build(), null,
                downloadConfig, ConfigurationManager.INSTANCE.getFileEncryptionProvider(),
                new PostProcessTask<File>() {
                    @Override
                    public void apply(final File object) {
                        FileQueue.INSTANCE.add(object);
                    }
                });
        if (pending != null) {
            pendingBuilder.putAll(pending);
        }
    } catch (Exception e) {
        final ImmutableMap<URI, File> pending = pendingBuilder.build();
        if (pending != null && pending.size() > 0) {
            FileQueue.INSTANCE.failed(pending.size());
        }
    }
}

From source file:org.grycap.gpf4med.URLUtilsTest.java

@Test
public void test() {
    System.out.println("URLUtilsTest.test()");
    try {/*  ww  w. ja  v  a  2 s  .co  m*/
        // load index
        final String[] validLines = new String[] { "file:///path/to/local-file-system",
                "http://www.google.com/index.html", "https://github.com/index.html # GitHub" };
        final String[] invalidLines = new String[] { "/path/to/local-file-system",
                "invalid_protocol://www.google.com/index.html" };
        final String[] commentLines = new String[] { "#file:///path/to/local-file-system",
                " #  http://www.google.com/index.html", "#file:///path/to/local-file-system",
                " #  http://www.google.com/index.html", "   #file:///path/to/local-file-system" };
        final List<String> linesList = new ArrayList<String>();
        linesList.addAll(Arrays.asList(validLines));
        linesList.addAll(Arrays.asList(invalidLines));
        linesList.addAll(Arrays.asList(commentLines));
        final String indexFilename = FilenameUtils.concat(TEST_OUTPUT_DIR, "index.txt");
        FileUtils.writeLines(new File(indexFilename), linesList);
        final URL[] urls = URLUtils.readIndex(new File(indexFilename).toURI().toURL());
        assertThat("URLs is not null", urls, notNullValue());
        assertThat("number of readed URLs coincides", urls.length, equalTo(validLines.length));
        for (final String line : validLines) {
            boolean found = false;
            final String target = new StringTokenizer(line).nextToken();
            for (int i = 0; i < urls.length && !found; i++) {
                final String query = (!URLUtils.isFileProtocol(urls[i]) ? urls[i].toString()
                        : URLUtils.FILE + "://" + urls[i].getPath());
                if (query.equals(target)) {
                    found = true;
                }
            }
            assertThat("a valid URL was found in the index: " + line, found);
        }
        // parse URL
        final String[][] paths = { { "file:///foo", "/foo" }, { "/foo//", "/foo/" }, { "/foo/./", "/foo/" },
                { "/foo/../bar", "/bar" }, { "/foo/../bar/", "/bar/" }, { "/foo/../bar/../baz", "/baz" },
                { "//foo//./bar", "/foo/bar" }, { "/../", null },
                { "../foo", FilenameUtils.concat(System.getProperty("user.dir"), "../foo") },
                { "foo/bar/..", FilenameUtils.concat(System.getProperty("user.dir"), "foo/bar/..") },
                { "foo/../../bar", FilenameUtils.concat(System.getProperty("user.dir"), "foo/../../bar") },
                { "foo/../bar", FilenameUtils.concat(System.getProperty("user.dir"), "foo/../bar") },
                { "//server/foo/../bar", "/server/bar" }, { "//server/../bar", null },
                { "C:\\foo\\..\\bar", "/bar" }, { "C:\\..\\bar", null },
                { "~/foo/../bar/", FilenameUtils.concat(System.getProperty("user.home"), "foo/../bar/") },
                { "~/../bar", FilenameUtils.concat(System.getProperty("user.home"), "../bar") },
                { "http://localhost", null } };
        for (int i = 0; i < paths.length; i++) {
            URL url = null;
            try {
                url = URLUtils.parseURL(paths[i][0]);
                System.out.println("PATH='" + paths[i][0] + "', URL='" + (url != null ? url.toString() : "NULL")
                        + "', EXPECTED='" + paths[i][1] + "'");
                assertThat("URL is not null", url, notNullValue());
                if (URLUtils.isFileProtocol(url)) {
                    final File file = FileUtils.toFile(url);
                    assertThat("file is not null", file, notNullValue());
                    assertThat("file name coincides",
                            FilenameUtils.normalizeNoEndSeparator(file.getCanonicalPath(), true)
                                    .equals(FilenameUtils.normalizeNoEndSeparator(paths[i][1], true)));
                }
            } catch (IOException ioe) {
                if (paths[i][1] != null) {
                    throw ioe;
                } else {
                    System.out.println("PATH='" + paths[i][0] + "' thrown the expected exception");
                }
            }
        }
        // validate URL
        assertThat("valid URL", URLUtils.isValid("http://www.google.com", true));
        assertThat("valid URL", !URLUtils.isValid("http://invalidURL^$&%$&^", true));
        assertThat("valid URL", URLUtils.isValid("http://example.com/file[/].html", false));
        assertThat("valid URL", !URLUtils.isValid("http://example.com/file[/].html", true));
    } catch (Exception e) {
        e.printStackTrace(System.err);
        fail("URLUtilsTest.test() failed: " + e.getMessage());
    } finally {
        System.out.println("URLUtilsTest.test() has finished");
    }
}

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

/**
 * Reads a text object from a URL and writes it to a Java {@code String}.
 * @param source Source URL.//from w  ww.j a  va 2  s  .  c  o  m
 * @return The content of the text object.
 * @throws IOException If an input/output error occurs.
 */
public static String readURLToString(final URL source) throws IOException {
    checkArgument(source != null, "Uninitialized source");
    String content = null;
    File srcFile = null;
    boolean deleteFileOnExit = false;
    try {
        if (isFileProtocol(source)) {
            srcFile = FileUtils.toFile(source);
        } else {
            srcFile = File.createTempFile("URLUtils_readURLToString", null);
            deleteFileOnExit = true;
            download(source, srcFile);
        }
        content = FileUtils.readFileToString(srcFile);
    } finally {
        if (deleteFileOnExit) {
            FileUtils.deleteQuietly(srcFile);
        }
    }
    return content;
}

From source file:org.hibernate.search.test.util.impl.ClasspathResourceAsFile.java

private void createFileIfNecessary() throws IOException {
    this.file = FileUtils.toFile(url);
    if (file == null) {
        this.file = File.createTempFile("classPathResourceAsFile", getOriginalExtension(), parentDirectory);
        this.hasCreatedTempFile = true;
        try (InputStream input = url.openStream(); OutputStream output = new FileOutputStream(file)) {
            IOUtils.copy(input, output);
        }/*  w w  w  .j av a2  s  . c  o  m*/
    }
}