Example usage for java.io File toURI

List of usage examples for java.io File toURI

Introduction

In this page you can find the example usage for java.io File toURI.

Prototype

public URI toURI() 

Source Link

Document

Constructs a file: URI that represents this abstract pathname.

Usage

From source file:com.maomao.server.AppManager.java

/**
 * parse app.xml/*from  w ww  .j  a v a  2 s.  com*/
 * 
 * @param file
 * @throws Exception
 */
public static void parseAppModeXml(App app, File file) throws Exception {
    logger.info("reading app.xml in app docbase:" + file.getPath());

    URL url = null;
    if (file.isFile() && file.getName().endsWith(".jar")) {
        String appConfig = "jar:file:" + file.getCanonicalPath() + "!/" + appXml;
        url = new URL(appConfig);
    } else if (file.isDirectory()) {
        File confFile = new File(file, "app.xml");
        if (!confFile.exists()) {
            throw new Exception("Cannot find app.xml in : " + file.getCanonicalPath());
        }
        url = confFile.toURI().toURL();
    }

    if (url != null) {
        XStream xs = new XStream();
        xs.alias("mm-app", App.class);
        App appDesc = (App) xs.fromXML(url.openStream());

        // merge 
        app.setPk(appDesc.getPk());
        app.setAppid(appDesc.getAppid());
        app.setName(appDesc.getName());
        app.setDescription(appDesc.getDescription());
        app.setEmail(appDesc.getEmail());
        app.setDeveloper(appDesc.getDeveloper());
        app.setVersion(appDesc.getVersion());
        app.setVersionLabel(appDesc.getVersionLabel());
    }
}

From source file:fll.xml.XMLUtils.java

/**
 * Get all challenge descriptors build into the software.
 *//*from   ww w .jav a 2s  .  co m*/
public static Collection<URL> getAllKnownChallengeDescriptorURLs() {
    final String baseDir = "fll/resources/challenge-descriptors/";

    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    final URL directory = classLoader.getResource(baseDir);
    if (null == directory) {
        LOGGER.warn("base dir for challenge descriptors not found");
        return Collections.emptyList();
    }

    final Collection<URL> urls = new LinkedList<URL>();
    if ("file".equals(directory.getProtocol())) {
        try {
            final URI uri = directory.toURI();
            final File fileDir = new File(uri);
            final File[] files = fileDir.listFiles();
            if (null != files) {
                for (final File file : files) {
                    if (file.getName().endsWith(".xml")) {
                        try {
                            final URL fileUrl = file.toURI().toURL();
                            urls.add(fileUrl);
                        } catch (final MalformedURLException e) {
                            LOGGER.error("Unable to convert file to URL: " + file.getAbsolutePath(), e);
                        }
                    }
                }
            }
        } catch (final URISyntaxException e) {
            LOGGER.error("Unable to convert URL to URI: " + e.getMessage(), e);
        }
    } else if (directory.getProtocol().equals("jar")) {
        final CodeSource src = XMLUtils.class.getProtectionDomain().getCodeSource();
        if (null != src) {
            final URL jar = src.getLocation();

            JarInputStream zip = null;
            try {
                zip = new JarInputStream(jar.openStream());

                JarEntry ze = null;
                while ((ze = zip.getNextJarEntry()) != null) {
                    final String entryName = ze.getName();
                    if (entryName.startsWith(baseDir) && entryName.endsWith(".xml")) {
                        // add 1 to baseDir to skip past the path separator
                        final String challengeName = entryName.substring(baseDir.length());

                        // check that the file really exists and turn it into a URL
                        final URL challengeUrl = classLoader.getResource(baseDir + challengeName);
                        if (null != challengeUrl) {
                            urls.add(challengeUrl);
                        } else {
                            // TODO could write the resource out to a temporary file if
                            // needed
                            // then mark the file as delete on exit
                            LOGGER.warn("URL doesn't exist for " + baseDir + challengeName + " entry: "
                                    + entryName);
                        }
                    }
                }

                zip.close();
            } catch (final IOException e) {
                LOGGER.error("Error reading jar file at: " + jar.toString(), e);
            } finally {
                IOUtils.closeQuietly(zip);
            }

        } else {
            LOGGER.warn("Null code source in protection domain, cannot get challenge descriptors");
        }
    } else {
        throw new UnsupportedOperationException("Cannot list files for URL " + directory);

    }

    return urls;

}

From source file:gate.Main.java

/** Process arguments and set up member fields appropriately.
  * Will shut down the process (via System.exit) if there are
  * incorrect arguments, or if the arguments ask for something
  * simple like printing the help message.
  *//*from  www  . ja v a2  s .com*/
public static void processArgs(String[] args) {

    Getopt g = new Getopt("GATE main", args, "hd:ei:");
    int c;
    while ((c = g.getopt()) != -1)
        switch (c) {
        // -h
        case 'h':
            help();
            usage();
            System.exit(STATUS_NORMAL);
            break;
        // -d creole-dir
        case 'd':
            String urlString = g.getOptarg();
            URL u = null;
            try {
                u = new URL(urlString);
            } catch (MalformedURLException e) {
                Err.prln("Bad URL: " + urlString);
                Err.prln(e);
                System.exit(STATUS_ERROR);
            }
            pendingCreoleUrls.add(u);
            Out.prln("CREOLE Directory " + urlString + " queued for registration");
            break;
        // -i gate.xml site-wide init file
        case 'i':
            String optionString = g.getOptarg();
            @SuppressWarnings("unused")
            URL u2 = null;
            File f = new File(optionString);
            try {
                u2 = f.toURI().toURL();
            } catch (MalformedURLException e) {
                Err.prln("Bad initialisation file: " + optionString);
                Err.prln(e);
                System.exit(STATUS_ERROR);
            }
            Gate.setSiteConfigFile(f);
            if (DEBUG)
                Out.prln("Initialisation file " + optionString + " recorded for initialisation");
            break;
        case '?':
            // leave the warning to getopt
            System.exit(STATUS_ERROR);
            break;

        default:
            // shouldn't happen!
            Err.prln("getopt() returned " + c + "\n");
            System.exit(STATUS_ERROR);
            break;
        } // getopt switch

}

From source file:difflib.DiffUtils.java

/**
 * Diff between two files//from   w w  w. j a v a 2 s .c  om
 *
 * @param <T>
 *            the generic type
 * @param _str
 *            the first file
 * @param _revised
 *            the revised file
 * @return the patch
 * @throws IOException 
 */
public static Patch<String> diff(File _str, File _revised) throws IOException {

    return DiffUtils.diff(IOUtils.toString(_str.toURI()), IOUtils.toString(_revised.toURI()));
}

From source file:de.xirp.ate.ATEManager.java

/**
 * Executes the a the <code>algorithm( )</code> method from a
 * given class, which is indicated by is name.
 * // w w  w .  j  a  va 2 s  .  co m
 * @param className
 *            The class to execute the method from.
 */
public static void execute(String className) {
    File clazz = new File(Constants.MAZE_CODE_DIR);
    try {
        URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { clazz.toURI().toURL() });
        Class<?> forName = Class.forName(className, true, classLoader);
        Method declaredMethod = forName.getDeclaredMethod("algorithm", new Class[0]); //$NON-NLS-1$
        declaredMethod.invoke(forName.newInstance(), new Object[0]);
    } catch (Exception e) {
        logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
    }
}

From source file:android.databinding.tool.MakeCopy.java

private static void addFromFile(File resDir, File resTarget) {
    for (File layoutDir : resDir.listFiles(LAYOUT_DIR_FILTER)) {
        if (layoutDir.isDirectory()) {
            File targetDir = new File(resTarget, layoutDir.getName());
            for (File layoutFile : layoutDir.listFiles(XML_FILENAME_FILTER)) {
                File targetFile = new File(targetDir, layoutFile.getName());
                FileWriter appender = null;
                try {
                    appender = new FileWriter(targetFile, true);
                    appender.write("<!-- From: " + layoutFile.toURI().toString() + " -->\n");
                } catch (IOException e) {
                    System.err.println("Could not update " + layoutFile + ": " + e.getLocalizedMessage());
                } finally {
                    IOUtils.closeQuietly(appender);
                }/*from   www  .  j a v  a2s  .  c  o m*/
            }
        }
    }
}

From source file:com.moviejukebox.tools.DOMHelper.java

/**
 * Get a DOM document from the supplied file
 *
 * @param xmlFile//w w  w . j ava  2 s .  co m
 * @return
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 */
public static Document getDocFromFile(File xmlFile)
        throws ParserConfigurationException, SAXException, IOException {
    URL url = xmlFile.toURI().toURL();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc;

    // Custom error handler
    db.setErrorHandler(new SaxErrorHandler());

    try (InputStream in = url.openStream()) {
        doc = db.parse(in);
    } catch (SAXParseException ex) {
        if (FilenameUtils.isExtension(xmlFile.getName().toLowerCase(), "xml")) {
            throw new SAXParseException("Failed to process file as XML", null, ex);
        }
        // Try processing the file a different way
        doc = null;
    }

    if (doc == null) {
        try (
                // try wrapping the file in a root
                StringReader sr = new StringReader(wrapInXml(FileTools.readFileToString(xmlFile)))) {
            doc = db.parse(new InputSource(sr));
        }
    }

    if (doc != null) {
        doc.getDocumentElement().normalize();
    }

    return doc;
}

From source file:com.amalto.core.jobox.util.JoboxUtil.java

public static URL[] getClasspathURLs(String paths, JobInfo info) {
    List<URL> urls = new ArrayList<URL>();
    if (paths == null || paths.length() <= 0) {
        return new URL[0];
    }// w  ww . ja v  a  2  s .co  m
    String separator = System.getProperty("path.separator"); //$NON-NLS-1$
    String[] pathToAdds = paths.split(separator);
    for (String pathToAdd : pathToAdds) {
        if (pathToAdd != null && pathToAdd.length() > 0) {
            try {
                File fileToAdd = new File(pathToAdd).getCanonicalFile();
                if (ignoreLibrary(fileToAdd.getName())) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Ignoring " + fileToAdd.toURI().toURL() + " from job '" + info.getName() //$NON-NLS-1$//$NON-NLS-2$
                                + "'. "); //$NON-NLS-1$
                    }
                } else {
                    urls.add(fileToAdd.toURI().toURL());
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(
                                "Added " + fileToAdd.toURI().toURL() + " to job '" + info.getName() + "'. "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                    }
                }
            } catch (IOException e) {
                throw new JoboxException(e);
            }
        }
    }
    return urls.toArray(new URL[urls.size()]);
}

From source file:com.liferay.blade.samples.integration.test.utils.BladeCLIUtil.java

public static String installBundle(File file) throws Exception {
    String bundleID;//  w w w. j a  v a 2  s .  c om
    String output;
    String printFileName;

    if (file.getName().endsWith(".war")) {
        printFileName = file.getName();

        printFileName = printFileName.substring(0, printFileName.lastIndexOf('.'));

        String fileURI = "webbundle:" + file.toURI().toASCIIString() + "?Web-ContextPath=/" + printFileName;

        output = execute("sh", "install", "\'" + fileURI + "\'");

        bundleID = output.substring(output.indexOf("ID:") + 4, output.lastIndexOf("\n"));
    } else {
        output = execute("sh", "install", "\'" + file.toURI().toASCIIString() + "\'");

        bundleID = output.substring(output.indexOf("ID:") + 4, output.lastIndexOf("\n"));
    }

    if (output.toLowerCase().contains("failed") || output.toLowerCase().contains("exception")) {

        throw new Exception(output);
    }

    return bundleID;
}

From source file:com.sonicle.webtop.core.app.util.LogbackHelper.java

public static URL findURLOfCustomConfigurationFile(String webappsConfigDir, String webappFullName) {
    File file = null;
    if (!StringUtils.isBlank(webappsConfigDir)) {
        // Try to get file under: "/path/to/webappsConfig/myAppName/logback.xml"
        file = new File(PathUtils.concatPathParts(webappsConfigDir, webappFullName,
                ContextInitializer.AUTOCONFIG_FILE));
        if (file.exists() && file.isFile()) {
            try {
                return file.toURI().toURL();
            } catch (MalformedURLException e1) {
            }//from   w w  w.java 2 s  .  co  m
        }

        // Try to get file under: "/path/to/webappsConfig/logback.xml"
        file = new File(PathUtils.concatPathParts(webappsConfigDir, ContextInitializer.AUTOCONFIG_FILE));
        if (file.exists() && file.isFile()) {
            try {
                return file.toURI().toURL();
            } catch (MalformedURLException e1) {
            }
        }
    }
    return null;
}