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.tactfactory.harmony.utils.TactFileUtils.java

/**
 * Converts an absolute path to a path relative to working dir.
 * @param absolute The absolute path/*w ww  .j a  v  a2s .  com*/
 * @param relative The relative path to use
 * @return The relative path
 */
public static String absoluteToRelativePath(final String absolute, final String relative) {
    String result = ".";

    final File abs = new File(absolute);
    final File workingDir = new File(relative);

    final URI resultString = workingDir.toURI().relativize(abs.toURI());

    if (!resultString.toString().equals("")) {
        result = resultString.toString();
    }

    if (result.startsWith("file:")) {
        result = result.substring("file:".length());

    }

    return result;
}

From source file:com.googlecode.jsonschema2pojo.integration.util.CodeGenerationHelper.java

public static ClassLoader compile(File sourceDirectory, List<String> classpath) {

    List<String> fullClasspath = new ArrayList<String>();
    fullClasspath.addAll(classpath);/*from   ww  w  .  j  av a2 s  . com*/
    fullClasspath.add(System.getProperty("java.class.path"));

    new Compiler().compile(sourceDirectory, join(fullClasspath, File.pathSeparatorChar));

    try {
        return URLClassLoader.newInstance(new URL[] { sourceDirectory.toURI().toURL() },
                Thread.currentThread().getContextClassLoader());
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }

}

From source file:co.cask.cdap.internal.app.runtime.LocalizationUtils.java

/**
 * Localizes the specified {@link LocalizeResource} in the specified {@link File targetDir} with the specified
 * file name and returns the {@link File} pointing to the localized file.
 *
 * @param fileName the name to localize the file with
 * @param resource the {@link LocalizeResource} to localize
 * @param targetDir the directory to localize the resource in
 * @return the {@link File} pointing to the localized file.
 *//*from  w w  w  .j a v a  2 s.c  o  m*/
public static File localizeResource(String fileName, LocalizeResource resource, File targetDir)
        throws IOException {
    File localizedResource = new File(targetDir, fileName);
    File input = getFileToLocalize(resource, targetDir);
    if (resource.isArchive()) {
        LOG.debug("Decompress file {} to {}", input, localizedResource);
        unpack(input, localizedResource);
    } else {
        try {
            LOG.debug("Hard link file from {} to {}", input, localizedResource);
            java.nio.file.Files.createLink(Paths.get(localizedResource.toURI()), Paths.get(input.toURI()));
        } catch (Exception e) {
            LOG.debug("Copy file from {} to {}", input, localizedResource);
            Files.copy(input, localizedResource);
        }
    }
    return localizedResource;
}

From source file:io.werval.cli.DamnSmallDevShell.java

private static URL[] prepareApplicationClasspath(boolean debug, File classesDir) throws MalformedURLException {
    URL[] applicationClasspath = new URL[] { classesDir.toURI().toURL() };
    if (debug) {//from  w w w  .java 2  s . c  o m
        System.out.println("Application Classpath is: " + Arrays.toString(applicationClasspath));
    }
    return applicationClasspath;
}

From source file:com.semagia.cassa.client.GraphClient.java

private static MediaType guessMediaType(final File file) {
    return guessMediaType(file.toURI());
}

From source file:com.qwazr.compiler.JavaCompiler.java

static JavaCompiler newInstance(ExecutorService executorService, File javaSourceDirectory,
        File javaClassesDirectory, File... classPathDirectories) throws IOException, URISyntaxException {
    Objects.requireNonNull(javaSourceDirectory, "No source directory given (null)");
    Objects.requireNonNull(javaClassesDirectory, "No class directory given (null)");
    final FileSystem fs = FileSystems.getDefault();
    final List<URL> urlList = new ArrayList<URL>();
    urlList.add(javaClassesDirectory.toURI().toURL());
    final String classPath = buildClassPath(classPathDirectories, urlList);
    return new JavaCompiler(executorService, javaSourceDirectory, javaClassesDirectory, classPath, urlList);
}

From source file:eu.planets_project.services.utils.DigitalObjectUtils.java

/**
 * Convenience method that creates a URL from a file in a proper (i.e. not deprecated) way, using the toURI().toURL() way. 
 * Hiding the Exception, so you don't have to put it in a try-catch block.
 * @param file/*ww  w  . jav a2 s .  c o  m*/
 * @return The URL for the given file
 */
private static URL getUrlFromFile(File file) {
    try {
        return file.toURI().toURL();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:edu.harvard.hul.ois.drs.pdfaconvert.PdfaConvert.java

private static void loadApplicationPropertiesFile() {
    // Set the projects properties.
    // First look for a system property pointing to a project properties file.
    // This value can be either a file path, file protocol (e.g. - file:/path/to/file),
    // or a URL (http://some/server/file).
    // If this value either does not exist or is not valid, the default
    // file that comes with this application will be used for initialization.
    String environmentProjectPropsFile = System.getProperty(ApplicationConstants.ENV_PROJECT_PROPS);
    logger.info("Have {} from environment: {}", ApplicationConstants.PROJECT_PROPS,
            environmentProjectPropsFile);
    URI projectPropsUri = null;/*from w w w  .  j a  va2s . c  o  m*/
    if (environmentProjectPropsFile != null) {
        try {
            projectPropsUri = new URI(environmentProjectPropsFile);
            // properties file needs a scheme in the URI so convert to file if necessary.
            if (null == projectPropsUri.getScheme()) {
                File projectProperties = new File(environmentProjectPropsFile);
                if (projectProperties.exists() && projectProperties.isFile()) {
                    projectPropsUri = projectProperties.toURI();
                } else {
                    // No scheme and not a file - yikes!!! Let's bail and
                    // use fall-back file.
                    projectPropsUri = null;
                    throw new URISyntaxException(environmentProjectPropsFile, "Not a valid file");
                }
            }
        } catch (URISyntaxException e) {
            // fall back to default file
            logger.error("Unable to load properties file: {} -- reason: {}", environmentProjectPropsFile,
                    e.getReason());
            logger.error("Falling back to default {} file: {}", ApplicationConstants.PROJECT_PROPS,
                    ApplicationConstants.PROJECT_PROPS);
        }
    }

    applicationProps = new Properties();
    // load properties if environment value set
    if (projectPropsUri != null) {
        File envPropFile = new File(projectPropsUri);
        if (envPropFile.exists() && envPropFile.isFile() && envPropFile.canRead()) {
            Reader reader;
            try {
                reader = new FileReader(envPropFile);
                logger.info("About to load {} from environment: {}", ApplicationConstants.PROJECT_PROPS,
                        envPropFile.getAbsolutePath());
                applicationProps.load(reader);
                logger.info("Success -- loaded properties file.");
            } catch (IOException e) {
                logger.error("Could not load environment properties file: {}", projectPropsUri, e);
                // set URI back to null so default prop file loaded
                projectPropsUri = null;
            }
        }
    }

    if (projectPropsUri == null) {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        try {
            InputStream resourceStream = loader.getResourceAsStream(ApplicationConstants.PROJECT_PROPS);
            applicationProps.load(resourceStream);
            logger.info("loaded default applicationProps: ");
        } catch (IOException e) {
            logger.error("Could not load properties file: {}", ApplicationConstants.PROJECT_PROPS, e);
            // couldn't load default properties so bail...
            throw new RuntimeException("Couldn't load an applications properties file.", e);
        }
    }
}

From source file:ee.ioc.cs.vsle.ccl.PackageClassLoader.java

/**
 * Creates a URL array with paths required for package class loading.
 * The returned array contains the URLs of the package directory,
 * all the jar and zip archives found in the package top level directory
 * (the directory is NOT searched recursively) and the compilation
 * classpath set by the user./*from ww  w .java2 s  .c o m*/
 * @return the package classpath
 */
private static URL[] createPackageClassPath(File packagePath) {
    ArrayList<URL> urls = new ArrayList<URL>();

    // (1) CoCoVila standard libraries
    // CoCoViLa standard libraries should be accessible using the parent
    // classloader, therefore we omit them here.

    // (2) The package directory
    try {
        urls.add(packagePath.toURI().toURL());
    } catch (MalformedURLException e) {
        logger.error(null, e);
    }

    // (3) jar and zip archives from the package top level directory
    File[] pkgLibs = getLibraryFiles(packagePath);
    if (pkgLibs != null) {
        for (File f : pkgLibs) {
            try {
                urls.add(f.toURI().toURL());
            } catch (MalformedURLException e) {
                logger.error(null, e);
            }
        }
    }

    // (4) user set classpath
    String[] paths = RuntimeProperties.getCompilationClasspaths();

    for (String path : paths) {
        File file = new File(path);
        if (file.exists()) {
            try {
                urls.add(file.toURI().toURL());
            } catch (MalformedURLException e) {
                logger.error(null, e);
            }
        }
    }

    if (RuntimeProperties.isFromWebstart()) {
        urls.addAll(getWebStartClasspath());
    }

    return urls.toArray(new URL[urls.size()]);
}

From source file:edu.kit.dama.util.DataManagerSettings.java

/**
 * Get KIT Data Manager configuration URL from one of the following sources
 * in the following order://from  www  . j av  a  2 s  .  c  om
 * <ul>
 * <li>Environment variable DATAMANAGER_CONFIG</li>
 * <li>System.getProperty('datamanager.config')</li>
 * <li>File or resource 'datamanager.xml' in current folder/classpath</li>
 * </ul>
 *
 * Environment variable and system property may contain resource paths or
 * absolute/relative paths to a file on disk. If no configuration was found,
 * a ConfigurationException is thrown.
 *
 * @return The configuration URL.
 *
 * @throws ConfigurationException If no configuration was found at any
 * supported location.
 */
public static URL getConfigurationURL() throws ConfigurationException {
    LOGGER.debug("Checking for configuration in environment variable DATAMANAGER_CONFIG");
    String configResource = System.getenv("DATAMANAGER_CONFIG");

    if (configResource == null) {
        LOGGER.debug("Environment variable is empty. Checking system property 'datamanager.config'");
        configResource = System.getProperty("datamanager.config");
        LOGGER.debug("System property datamanager.config is set to: {}", configResource);
    }

    URL resource = null;
    if (configResource != null) {
        LOGGER.debug("Try to read resource from {}", configResource);

        //just try if configResource is not null
        resource = Thread.currentThread().getContextClassLoader().getResource(configResource);
    }

    if (resource != null) {
        //system property/environment variable is a resource
        return resource;
    } else if (configResource != null && new File(configResource).exists()) {
        //system property is a file
        LOGGER.debug("Trying to return URL for provided configuration {}", configResource);
        try {
            //return URL to file
            return new File(configResource).toURI().toURL();
        } catch (MalformedURLException mue) {
            throw new ConfigurationException(
                    "Provided configuration file '" + configResource + "' could not be mapped to a file", mue);
        }
    } else {
        LOGGER.debug("System property is invalid. Checking file {}", SETTINGS_FILENAME);
        configResource = SETTINGS_FILENAME;
    }

    File fileToResource = new File(configResource);
    if (fileToResource.exists()) {//file exists...use it
        LOGGER.debug("Trying to return URL for provided configuration {}", configResource);
        try {
            return fileToResource.toURI().toURL();
        } catch (MalformedURLException mue) {
            throw new ConfigurationException(
                    "Provided configuration file '" + configResource + "' could not be mapped to a file", mue);
        }
    } else {//try to get from resource
        configResource = SETTINGS_FILENAME;
        LOGGER.debug("Try getting default configuration from resource '{}'", configResource);
        URL resourceURL = DataManagerSettings.class.getResource(configResource);
        if (resourceURL != null) {
            return resourceURL;
        } else {
            LOGGER.debug("Try getting default configuration from context classloader");
            resourceURL = Thread.currentThread().getContextClassLoader().getResource(SETTINGS_FILENAME);
            if (resourceURL != null) {
                return resourceURL;
            }
        }
    }

    throw new ConfigurationException(
            "Neither environment variable nor configuration file are pointing to a valid settings file.");
}