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:io.fabric8.agent.mvn.MavenSettingsImpl.java

private static URL safeGetFile(final String filePath) {
    if (filePath != null) {
        File file = new File(filePath);
        if (file.exists() && file.canRead() && file.isFile()) {
            try {
                return file.toURI().toURL();
            } catch (MalformedURLException e) {
                // do nothing
            }//from   w  w w  .ja va  2 s . c  o  m
        }
    }
    return null;
}

From source file:com.google.dart.tools.core.utilities.io.FileUtilities.java

/**
 * Returns whether the given file is a symlinked file.
 * //  www . ja  v a2s  . co  m
 * @param file
 * @return
 * @throws CoreException
 * @throws IOException
 */
public static boolean isLinkedFile(File file) throws CoreException {
    IFileStore fileStore = EFS.getStore(file.toURI());

    IFileInfo info = fileStore.fetchInfo();

    return info.getAttribute(EFS.ATTRIBUTE_SYMLINK);
}

From source file:de.cosmocode.palava.core.Palava.java

/**
 * Creates a new {@link Framework} using a properties file.
 * <p>/*from  w  ww. j  a  va 2s  .c o m*/
 *   The loaded properties will be bound using the {@link Settings} annotation.
 * </p>
 * 
 * @since 2.4
 * @param file the file pointing to the properties file
 * @return a new configured {@link Framework} instance
 * @throws NullPointerException if file is null
 * @throws IllegalArgumentException if the file does not exist
 * @throws ConfigurationException if guice configuration failed
 * @throws ProvisionException if providing an instance during creation failed
 */
public static Framework newFramework(File file) {
    Preconditions.checkNotNull(file, "File");
    Preconditions.checkArgument(file.exists(), "%s does not exist", file);
    try {
        return newFramework(file.toURI().toURL());
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:android.databinding.tool.reflection.java.JavaAnalyzer.java

public static void initForTests() {
    String androidHome = loadAndroidHome();
    if (Strings.isNullOrEmpty(androidHome) || !new File(androidHome).exists()) {
        throw new IllegalStateException(
                "you need to have ANDROID_HOME set in your environment" + " to run compiler tests");
    }/*from   w w  w .ja v a 2s  . c o  m*/
    File androidJar = new File(androidHome + "/platforms/android-21/android.jar");
    if (!androidJar.exists() || !androidJar.canRead()) {
        throw new IllegalStateException("cannot find android jar at " + androidJar.getAbsolutePath());
    }
    // now load android data binding library as well

    try {
        ClassLoader classLoader = new URLClassLoader(new URL[] { androidJar.toURI().toURL() },
                ModelAnalyzer.class.getClassLoader());
        new JavaAnalyzer(classLoader);
    } catch (MalformedURLException e) {
        throw new RuntimeException("cannot create class loader", e);
    }

    SdkUtil.initialize(8, new File(androidHome));
}

From source file:com.asakusafw.directio.hive.tools.cli.GenerateCreateTable.java

/**
 * Creates a class loader for loading plug-ins.
 * @param parent parent class loader, or {@code null} to use the system class loader
 * @param files plug-in class paths (*.jar file or class path directory)
 * @return the created class loader/*from ww w  .  jav  a2 s .c o m*/
 * @throws IllegalArgumentException if some parameters were {@code null}
 */
private static URLClassLoader buildPluginLoader(ClassLoader parent, List<File> files) {
    if (files == null) {
        throw new IllegalArgumentException("files must not be null"); //$NON-NLS-1$
    }
    List<URL> locations = new ArrayList<>();
    for (File file : files) {
        try {
            if (file.exists() == false) {
                throw new FileNotFoundException(
                        MessageFormat.format(Messages.getString("GenerateCreateTable.errorMissingPluginFile"), //$NON-NLS-1$
                                file.getAbsolutePath()));
            }
            URL url = file.toURI().toURL();
            locations.add(url);
        } catch (IOException e) {
            LOG.warn(MessageFormat.format(Messages.getString("GenerateCreateTable.warnInvalidPluginFile"), //$NON-NLS-1$
                    file.getAbsolutePath()), e);
        }
    }
    return AccessController.doPrivileged((PrivilegedAction<URLClassLoader>) () -> new URLClassLoader(
            locations.toArray(new URL[locations.size()]), parent));
}

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

private static URL[] prepareRuntimeClasspath(boolean debug, Set<File> sourcesRoots, CommandLine cmd)
        throws MalformedURLException {
    List<URL> classpathList = new ArrayList<>();
    // First, current classpath
    classpathList.addAll(ClassLoaders.urlsOf(DamnSmallDevShell.class.getClassLoader()));
    // Then add command line provided
    if (cmd.hasOption('c')) {
        for (String url : cmd.getOptionValues('c')) {
            classpathList.add(new URL(url));
        }//from w  w  w .  j  av  a  2 s .c  om
    }
    // Append Application sources
    for (File sourceRoot : sourcesRoots) {
        classpathList.add(sourceRoot.toURI().toURL());
    }
    URL[] runtimeClasspath = classpathList.toArray(new URL[classpathList.size()]);
    if (debug) {
        System.out.println("Runtime Classpath is: " + classpathList);
    }
    return runtimeClasspath;
}

From source file:com.mirth.connect.server.launcher.MirthLauncher.java

private static void addExtensionsToClasspath(List<URL> urls, String currentVersion) throws Exception {
    FileFilter extensionFileFilter = new NameFileFilter(
            new String[] { "plugin.xml", "source.xml", "destination.xml" }, IOCase.INSENSITIVE);
    FileFilter directoryFilter = FileFilterUtils.directoryFileFilter();
    File extensionPath = new File(EXTENSIONS_DIR);

    Properties extensionProperties = new Properties();
    File extensionPropertiesFile = new File(appDataDir, EXTENSION_PROPERTIES);

    /*/*  www .  j  a  v a 2 s .c  o m*/
     * If the file does not exist yet, an empty Properties object will be used, returning the
     * default of true for all extensions.
     */
    if (extensionPropertiesFile.exists()) {
        extensionProperties.load(new FileInputStream(extensionPropertiesFile));
    }

    if (extensionPath.exists() && extensionPath.isDirectory()) {
        File[] directories = extensionPath.listFiles(directoryFilter);

        for (File directory : directories) {
            File[] extensionFiles = directory.listFiles(extensionFileFilter);

            for (File extensionFile : extensionFiles) {
                try {
                    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                            .parse(extensionFile);
                    Element rootElement = document.getDocumentElement();

                    boolean enabled = extensionProperties
                            .getProperty(rootElement.getElementsByTagName("name").item(0).getTextContent(),
                                    "true")
                            .equalsIgnoreCase("true");
                    boolean compatible = isExtensionCompatible(
                            rootElement.getElementsByTagName("mirthVersion").item(0).getTextContent(),
                            currentVersion);

                    // Only add libraries from extensions that are not disabled and are compatible with the current version
                    if (enabled && compatible) {
                        NodeList libraries = rootElement.getElementsByTagName("library");

                        for (int i = 0; i < libraries.getLength(); i++) {
                            Element libraryElement = (Element) libraries.item(i);
                            String type = libraryElement.getAttribute("type");

                            if (type.equalsIgnoreCase("server") || type.equalsIgnoreCase("shared")) {
                                File pathFile = new File(directory, libraryElement.getAttribute("path"));

                                if (pathFile.exists()) {
                                    logger.trace("adding library to classpath: " + pathFile.getAbsolutePath());
                                    urls.add(pathFile.toURI().toURL());
                                } else {
                                    logger.error("could not locate library: " + pathFile.getAbsolutePath());
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error("failed to parse extension metadata: " + extensionFile.getAbsolutePath(), e);
                }
            }
        }
    } else {
        logger.warn("no extensions found");
    }
}

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

private static void devshellCommand(boolean debug, File tmpDir, CommandLine cmd) throws IOException {
    final File classesDir = createClassesDirectory(debug, tmpDir);
    Set<File> sourceRoots = prepareSourcesRoots(debug, cmd);
    Set<URL> applicationSourcesSet = new LinkedHashSet<>(sourceRoots.size());
    for (File sourceRoot : sourceRoots) {
        applicationSourcesSet.add(sourceRoot.toURI().toURL());
    }// w  w  w .  ja  v  a 2s  . co m
    URL[] applicationSources = applicationSourcesSet.toArray(new URL[applicationSourcesSet.size()]);
    URL[] applicationClasspath = prepareApplicationClasspath(debug, classesDir);
    URL[] runtimeClasspath = prepareRuntimeClasspath(debug, sourceRoots, cmd);
    applySystemProperties(debug, cmd);
    System.out.println("Loading...");

    // Watch Sources
    SourceWatcher watcher = new JavaWatcher();

    // First build
    rebuild(applicationClasspath, runtimeClasspath, sourceRoots, classesDir);

    // Run DevShell
    Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownHook(tmpDir), "werval-cli-cleanup"));
    new DevShellCommand(new SPI(applicationSources, applicationClasspath, runtimeClasspath, sourceRoots,
            watcher, classesDir)).run();
}

From source file:de.betterform.agent.web.WebUtil.java

/**
 * this method is responsible for passing all context information needed by the Adapter and Processor from
 * ServletRequest to Context. Will be called only once when the form-session is inited (GET).
 * <p/>/*ww  w.  j  a va 2 s.  co m*/
 * <p/>
 * todo: better logging of context params
 *
 * @param request     the Servlet request to fetch params from
 * @param httpSession the Http Session context
 * @param processor   the XFormsProcessor which receives the context params
 * @param sessionkey  the key to identify the XFormsSession
 */
public static void setContextParams(HttpServletRequest request, HttpSession httpSession,
        XFormsProcessor processor, String sessionkey) throws XFormsConfigException {
    Map servletMap = new HashMap();
    servletMap.put(WebProcessor.SESSION_ID, sessionkey);
    processor.setContextParam(XFormsProcessor.SUBMISSION_RESPONSE, servletMap);

    //adding requestURI to context
    processor.setContextParam(WebProcessor.REQUEST_URI, WebUtil.getRequestURI(request));

    //adding request URL to context
    String requestURL = request.getRequestURL().toString();
    processor.setContextParam(WebProcessor.REQUEST_URL, requestURL);

    // the web app name with an '/' prepended e.g. '/betterform' by default
    String contextRoot = WebUtil.getContextRoot(request);
    processor.setContextParam(WebProcessor.CONTEXTROOT, contextRoot);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("context root of webapp: " + processor.getContextParam(WebProcessor.CONTEXTROOT));
    }

    String requestPath = "";
    URL url = null;
    String plainPath = "";
    try {
        url = new URL(requestURL);
        requestPath = url.getPath();
    } catch (MalformedURLException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    if (requestPath.length() != 0) {
        //adding request path e.g. '/betterform/forms/demo/registration.xhtml'
        processor.setContextParam(WebProcessor.REQUEST_PATH, requestPath);

        //adding filename of requested doc to context
        String fileName = requestPath.substring(requestPath.lastIndexOf('/') + 1, requestPath.length());//FILENAME xforms
        processor.setContextParam(FILENAME, fileName);

        if (requestURL.contains(contextRoot)) { //case1: contextRoot is a part of the URL
            //adding plainPath which is the part between contextroot and filename e.g. '/forms' for a requestPath of '/betterform/forms/Status.xhtml'
            plainPath = requestPath.substring(contextRoot.length() + 1,
                    requestPath.length() - fileName.length());
            processor.setContextParam(PLAIN_PATH, plainPath);
        } else {//case2: contextRoot is not a part of the URL take the part previous the filename.
            String[] urlParts = requestURL.split("/");
            plainPath = urlParts[urlParts.length - 2];
        }

        //adding contextPath - requestPath without the filename
        processor.setContextParam(CONTEXT_PATH, contextRoot + "/" + plainPath);
    }

    //adding session id to context
    processor.setContextParam(HTTP_SESSION_ID, httpSession.getId());
    //adding context absolute path to context

    //EXIST-WORKAROUND: TODO triple check ...
    //TODO: triple check where this is used.
    if (request.isRequestedSessionIdValid()) {
        processor.setContextParam(EXISTDB_USER, httpSession.getAttribute(EXISTDB_USER));
    }

    //adding pathInfo to context - attention: this is only available when a servlet is requested
    String s1 = request.getPathInfo();
    if (s1 != null) {
        processor.setContextParam(WebProcessor.PATH_INFO, s1);
    }
    processor.setContextParam(WebProcessor.QUERY_STRING,
            (request.getQueryString() != null ? request.getQueryString() : ""));

    //storing the realpath for webapp

    String realPath = WebFactory.getRealPath(".", httpSession.getServletContext());
    File f = new File(realPath);
    URI fileURI = f.toURI();

    processor.setContextParam(WebProcessor.REALPATH, fileURI.toString());
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("real path of webapp: " + realPath);
    }

    //storing the TransformerService
    processor.setContextParam(TransformerService.TRANSFORMER_SERVICE,
            httpSession.getServletContext().getAttribute(TransformerService.TRANSFORMER_SERVICE));
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("TransformerService: "
                + httpSession.getServletContext().getAttribute(TransformerService.TRANSFORMER_SERVICE));
    }

    //[2] read any request params that are *not* betterForm params and pass them into the context map
    Enumeration params = request.getParameterNames();
    String s;
    while (params.hasMoreElements()) {
        s = (String) params.nextElement();
        //store all request-params we don't use in the context map of XFormsProcessorImpl
        String value = request.getParameter(s);
        processor.setContextParam(s, value);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("added request param '" + s + "' added to context");
            LOGGER.debug("param value'" + value);
        }
    }

}

From source file:net.ageto.gyrex.impex.console.internal.ImpexConsoleCommands.java

/**
 * Reads properties from file/*from w  w  w.j av a  2s  .co m*/
 *
 * @param configSourcePath
 * @param context 
 * @return
 */
public static boolean initPropertiesFile(String configSourcePath, IRuntimeContext context) {

    String propertiesFilename = FilenameUtils.concat(configSourcePath, DEFAULT_PROPERY_FILENAME);

    File propertiesFile = new File(propertiesFilename);

    if (!propertiesFile.exists()) {
        System.err.println(propertiesFilename + " file does not exist. Aborting");
        return false;
    }

    URI propertiesUri = propertiesFile.toURI();
    URL propertiesUrl;

    try {
        propertiesUrl = propertiesUri.toURL();
    } catch (MalformedURLException e) {
        System.err.println("File could not be read." + e);
        return false;
    }

    ConfigureRepositoryPreferences.readRepositoryPreferences(propertiesUrl, CASSANDRA_REPOSITORY_ID, context);

    System.out.println(propertiesFilename + " file processed successfully.");

    return true;
}