Example usage for java.io File pathSeparator

List of usage examples for java.io File pathSeparator

Introduction

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

Prototype

String pathSeparator

To view the source code for java.io File pathSeparator.

Click Source Link

Document

The system-dependent path-separator character, represented as a string for convenience.

Usage

From source file:org.apache.geode.management.internal.cli.commands.StartMemberUtils.java

static String toClasspath(final boolean includeSystemClasspath, String[] jarFilePathnames,
        String... userClasspaths) {
    // gemfire jar must absolutely be the first JAR file on the CLASSPATH!!!
    StringBuilder classpath = new StringBuilder(getGemFireJarPath());

    userClasspaths = (userClasspaths != null ? userClasspaths : ArrayUtils.EMPTY_STRING_ARRAY);

    // Then, include user-specified classes on CLASSPATH to enable the user to override GemFire JAR
    // dependencies
    // with application-specific versions; this logic/block corresponds to classes/jar-files
    // specified with the
    // --classpath option to the 'start locator' and 'start server commands'; also this will
    // override any
    // System CLASSPATH environment variable setting, which is consistent with the Java platform
    // behavior...
    for (String userClasspath : userClasspaths) {
        if (StringUtils.isNotBlank(userClasspath)) {
            classpath.append((classpath.length() == 0) ? StringUtils.EMPTY : File.pathSeparator);
            classpath.append(userClasspath);
        }// w  ww  . j  a  v a  2s .  c o m
    }

    // Now, include any System-specified CLASSPATH environment variable setting...
    if (includeSystemClasspath) {
        classpath.append(File.pathSeparator);
        classpath.append(getSystemClasspath());
    }

    jarFilePathnames = (jarFilePathnames != null ? jarFilePathnames : ArrayUtils.EMPTY_STRING_ARRAY);

    // And finally, include all GemFire dependencies on the CLASSPATH...
    for (String jarFilePathname : jarFilePathnames) {
        if (StringUtils.isNotBlank(jarFilePathname)) {
            classpath.append((classpath.length() == 0) ? StringUtils.EMPTY : File.pathSeparator);
            classpath.append(jarFilePathname);
        }
    }
    return classpath.toString();
}

From source file:org.devtcg.five.persistence.Configuration.java

public synchronized void setLibraryPaths(List<String> paths) throws SQLException {
    if (paths == null || paths.size() == 0)
        throw new IllegalArgumentException("paths must not be null or empty");

    StringBuilder string = new StringBuilder();
    for (String path : paths)
        string.append(path).append(File.pathSeparator);

    string.setLength(string.length() - File.pathSeparator.length());

    setValue(getConnection(), Keys.LIBRARY_PATH, string.toString());
}

From source file:org.jboss.web.tomcat.tc5.WebCtxLoader.java

/**
 * Set the appropriate context attribute for our class path.  This
 * is required only because Jasper depends on it.
 *///from   w w w.  ja  v  a2 s. c  om
private void setClassPath() {
    // Validate our current state information
    if (!(webContainer instanceof Context))
        return;
    ServletContext servletContext = ((Context) webContainer).getServletContext();
    if (servletContext == null)
        return;

    try {
        Method method = webContainer.getClass().getMethod("getCompilerClasspath", null);
        Object baseClasspath = method.invoke(webContainer, null);
        if (baseClasspath != null) {
            servletContext.setAttribute(Globals.CLASS_PATH_ATTR, baseClasspath.toString());
            return;
        }
    } catch (Exception e) {
        // Ignore
        e.printStackTrace();
    }

    StringBuffer classpath = new StringBuffer();

    // Assemble the class path information from our repositories
    for (int i = 0; i < repositories.size(); i++) {
        String repository = repositories.get(i).toString();
        if (repository.startsWith("file://"))
            repository = repository.substring(7);
        else if (repository.startsWith("file:"))
            repository = repository.substring(5);
        else if (repository.startsWith("jndi:"))
            repository = servletContext.getRealPath(repository.substring(5));
        else
            continue;
        if (repository == null)
            continue;
        if (i > 0)
            classpath.append(File.pathSeparator);
        classpath.append(repository);
    }

    // Store the assembled class path as a servlet context attribute
    servletContext.setAttribute(Globals.CLASS_PATH_ATTR, classpath.toString());

}

From source file:org.evosuite.CommandLineParameters.java

public static void handleClassPath(CommandLine line) {

    String DCP = null;/*from ww  w.  ja  v a 2 s.  c  o m*/
    java.util.Properties properties = line.getOptionProperties("D");
    for (String propertyName : properties.stringPropertyNames()) {
        if (propertyName.equals("CP")) {
            DCP = properties.getProperty(propertyName);
        }
    }

    if (line.hasOption("projectCP") && DCP != null) {
        throw new IllegalArgumentException("Ambiguous classpath: both -projectCP and -DCP are defined");
    }

    String[] cpEntries = null;

    if (line.hasOption("projectCP")) {
        cpEntries = line.getOptionValue("projectCP").split(File.pathSeparator);
    } else if (DCP != null) {
        cpEntries = DCP.split(File.pathSeparator);
    }

    if (cpEntries != null) {
        ClassPathHandler.getInstance().changeTargetClassPath(cpEntries);
    }

    if (line.hasOption("target")) {
        String target = line.getOptionValue("target");

        /* 
         * let's just add the target automatically to the classpath.
         * This is useful for when we do not want to specify the classpath,
         * and so just typing '-target' on command line
         * 
         */
        ClassPathHandler.getInstance().addElementToTargetProjectClassPath(target);
    }

    if (line.hasOption("evosuiteCP")) {
        String entry = line.getOptionValue("evosuiteCP");
        String[] entries = entry.split(File.pathSeparator);
        ClassPathHandler.getInstance().setEvoSuiteClassPath(entries);
    }
}

From source file:org.apache.struts2.JSPLoader.java

/**
 * Compiles the given source code into java bytecode
 *///from  ww  w.j av a2  s  . c o  m
private void compileJava(String className, final String source, Set<String> extraClassPath) throws IOException {
    if (LOG.isTraceEnabled())
        LOG.trace("Compiling [#0], source: [#1]", className, source);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

    //the generated bytecode is fed to the class loader
    JavaFileManager jfm = new ForwardingJavaFileManager<StandardJavaFileManager>(
            compiler.getStandardFileManager(diagnostics, null, null)) {

        @Override
        public JavaFileObject getJavaFileForOutput(Location location, String name, JavaFileObject.Kind kind,
                FileObject sibling) throws IOException {
            MemoryJavaFileObject fileObject = new MemoryJavaFileObject(name, kind);
            classLoader.addMemoryJavaFileObject(name, fileObject);
            return fileObject;
        }
    };

    //read java source code from memory
    String fileName = className.replace('.', '/') + ".java";
    SimpleJavaFileObject sourceCodeObject = new SimpleJavaFileObject(toURI(fileName),
            JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors)
                throws IOException, IllegalStateException, UnsupportedOperationException {
            return source;
        }

    };

    //build classpath
    //some entries will be added multiple times, hence the set
    List<String> optionList = new ArrayList<String>();
    Set<String> classPath = new HashSet<String>();

    FileManager fileManager = ServletActionContext.getContext().getInstance(FileManagerFactory.class)
            .getFileManager();

    //find available jars
    ClassLoaderInterface classLoaderInterface = getClassLoaderInterface();
    UrlSet urlSet = new UrlSet(classLoaderInterface);

    //find jars
    List<URL> urls = urlSet.getUrls();

    for (URL url : urls) {
        URL normalizedUrl = fileManager.normalizeToFileProtocol(url);
        File file = FileUtils.toFile(ObjectUtils.defaultIfNull(normalizedUrl, url));
        if (file.exists())
            classPath.add(file.getAbsolutePath());
    }

    //these should be in the list already, but I am feeling paranoid
    //this jar
    classPath.add(getJarUrl(EmbeddedJSPResult.class));
    //servlet api
    classPath.add(getJarUrl(Servlet.class));
    //jsp api
    classPath.add(getJarUrl(JspPage.class));

    try {
        Class annotationsProcessor = Class.forName("org.apache.AnnotationProcessor");
        classPath.add(getJarUrl(annotationsProcessor));
    } catch (ClassNotFoundException e) {
        //ok ignore
    }

    //add extra classpath entries (jars where tlds were found will be here)
    for (Iterator<String> iterator = extraClassPath.iterator(); iterator.hasNext();) {
        String entry = iterator.next();
        classPath.add(entry);
    }

    String classPathString = StringUtils.join(classPath, File.pathSeparator);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Compiling [#0] with classpath [#1]", className, classPathString);
    }

    optionList.addAll(Arrays.asList("-classpath", classPathString));

    //compile
    JavaCompiler.CompilationTask task = compiler.getTask(null, jfm, diagnostics, optionList, null,
            Arrays.asList(sourceCodeObject));

    if (!task.call()) {
        throw new StrutsException("Compilation failed:" + diagnostics.getDiagnostics().get(0).toString());
    }
}

From source file:org.apache.hadoop.distributedloadsimulator.sls.appmaster.UnmanagedAMLauncher.java

public void launchAM(ApplicationAttemptId attemptId) throws IOException, YarnException {
    Credentials credentials = new Credentials();
    Token<AMRMTokenIdentifier> token = rmClient.getAMRMToken(attemptId.getApplicationId());
    // Service will be empty but that's okay, we are just passing down only
    // AMRMToken down to the real AM which eventually sets the correct
    // service-address.
    credentials.addToken(token.getService(), token);
    File tokenFile = File.createTempFile("unmanagedAMRMToken", "", new File(System.getProperty("user.dir")));
    try {// w  w  w .j  a  v  a  2 s .  com
        FileUtil.chmod(tokenFile.getAbsolutePath(), "600");
    } catch (InterruptedException ex) {
        throw new RuntimeException(ex);
    }
    tokenFile.deleteOnExit();
    DataOutputStream os = new DataOutputStream(new FileOutputStream(tokenFile, true));
    credentials.writeTokenStorageToStream(os);
    os.close();

    Map<String, String> env = System.getenv();
    ArrayList<String> envAMList = new ArrayList<String>();
    boolean setClasspath = false;
    for (Map.Entry<String, String> entry : env.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        if (key.equals("CLASSPATH")) {
            setClasspath = true;
            if (classpath != null) {
                value = value + File.pathSeparator + classpath;
            }
        }
        envAMList.add(key + "=" + value);
    }

    if (!setClasspath && classpath != null) {
        envAMList.add("CLASSPATH=" + classpath);
    }
    ContainerId containerId = ContainerId.newInstance(attemptId, 0);

    String hostname = InetAddress.getLocalHost().getHostName();
    envAMList.add(Environment.CONTAINER_ID.name() + "=" + containerId);
    envAMList.add(Environment.NM_HOST.name() + "=" + hostname);
    envAMList.add(Environment.NM_HTTP_PORT.name() + "=0");
    envAMList.add(Environment.NM_PORT.name() + "=0");
    envAMList.add(Environment.LOCAL_DIRS.name() + "= /tmp");
    envAMList.add(ApplicationConstants.APP_SUBMIT_TIME_ENV + "=" + System.currentTimeMillis());

    envAMList.add(ApplicationConstants.CONTAINER_TOKEN_FILE_ENV_NAME + "=" + tokenFile.getAbsolutePath());

    String[] envAM = new String[envAMList.size()];

    //lets add application id cluster timestamp and attempt id to each application master process
    amCmd += " " + appId.getClusterTimestamp() + " " + appId.getId() + " " + attemptId.getAttemptId();
    LOG.info("HOP :: Applicatoin master  Container id : "
            + (Environment.CONTAINER_ID.name() + "=" + containerId));
    LOG.info("HOP :: Applicaton master process cmd: " + amCmd + "|Env variable: "
            + Arrays.toString(envAMList.toArray(envAM)));

    Process amProc = Runtime.getRuntime().exec(amCmd, envAMList.toArray(envAM));

    LOG.info("HOP :: Application master process is started ");

    final BufferedReader errReader = new BufferedReader(new InputStreamReader(amProc.getErrorStream()));
    final BufferedReader inReader = new BufferedReader(new InputStreamReader(amProc.getInputStream()));

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    System.err.println(line);
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    Thread outThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = inReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    System.out.println(line);
                    line = inReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the out stream", ioe);
            }
        }
    };
    try {
        errThread.start();
        outThread.start();
    } catch (IllegalStateException ise) {
    }

    // wait for the process to finish and check the exit code
    try {
        int exitCode = amProc.waitFor();
        LOG.info("AM process exited with value: " + exitCode);
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        amCompleted = true;
    }

    try {
        // make sure that the error thread exits
        // on Windows these threads sometimes get stuck and hang the execution
        // timeout and join later after destroying the process.
        errThread.join();
        outThread.join();
        errReader.close();
        inReader.close();
    } catch (InterruptedException ie) {
        LOG.info("ShellExecutor: Interrupted while reading the error/out stream", ie);
    } catch (IOException ioe) {
        LOG.warn("Error while closing the error/out stream", ioe);
    }
    //    amProc.destroy();
}

From source file:org.apache.accumulo.minicluster.MiniAccumuloCluster.java

private String getClasspath() throws IOException {

    try {//from w ww .  j  ava 2  s.c  o  m
        ArrayList<ClassLoader> classloaders = new ArrayList<ClassLoader>();

        ClassLoader cl = this.getClass().getClassLoader();

        while (cl != null) {
            classloaders.add(cl);
            cl = cl.getParent();
        }

        Collections.reverse(classloaders);

        StringBuilder classpathBuilder = new StringBuilder();
        classpathBuilder.append(config.getConfDir().getAbsolutePath());

        if (config.getClasspathItems() == null) {

            // assume 0 is the system classloader and skip it
            for (int i = 1; i < classloaders.size(); i++) {
                ClassLoader classLoader = classloaders.get(i);

                if (classLoader instanceof URLClassLoader) {

                    URLClassLoader ucl = (URLClassLoader) classLoader;

                    for (URL u : ucl.getURLs()) {
                        append(classpathBuilder, u);
                    }

                } else if (classLoader instanceof VFSClassLoader) {

                    VFSClassLoader vcl = (VFSClassLoader) classLoader;
                    for (FileObject f : vcl.getFileObjects()) {
                        append(classpathBuilder, f.getURL());
                    }
                } else {
                    throw new IllegalArgumentException(
                            "Unknown classloader type : " + classLoader.getClass().getName());
                }
            }
        } else {
            for (String s : config.getClasspathItems())
                classpathBuilder.append(File.pathSeparator).append(s);
        }

        return classpathBuilder.toString();

    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
}

From source file:org.apache.hama.bsp.BSPTaskLauncher.java

private GetContainerStatusesRequest setupContainer(Container allocatedContainer, ContainerManagementProtocol cm,
        String user, int id) throws IOException, YarnException {
    LOG.info("Setting up a container for user " + user + " with id of " + id + " and containerID of "
            + allocatedContainer.getId() + " as " + user);
    // Now we setup a ContainerLaunchContext
    ContainerLaunchContext ctx = Records.newRecord(ContainerLaunchContext.class);

    // Set the local resources
    Map<String, LocalResource> localResources = new HashMap<String, LocalResource>();
    LocalResource packageResource = Records.newRecord(LocalResource.class);
    FileSystem fs = FileSystem.get(conf);
    Path packageFile = new Path(System.getenv(YARNBSPConstants.HAMA_YARN_LOCATION));
    URL packageUrl = ConverterUtils
            .getYarnUrlFromPath(packageFile.makeQualified(fs.getUri(), fs.getWorkingDirectory()));
    LOG.info("PackageURL has been composed to " + packageUrl.toString());
    try {/*from   w  ww.  jav  a 2s  . c o  m*/
        LOG.info("Reverting packageURL to path: " + ConverterUtils.getPathFromYarnURL(packageUrl));
    } catch (URISyntaxException e) {
        LOG.fatal("If you see this error the workarround does not work", e);
    }

    packageResource.setResource(packageUrl);
    packageResource.setSize(Long.parseLong(System.getenv(YARNBSPConstants.HAMA_YARN_SIZE)));
    packageResource.setTimestamp(Long.parseLong(System.getenv(YARNBSPConstants.HAMA_YARN_TIMESTAMP)));
    packageResource.setType(LocalResourceType.FILE);
    packageResource.setVisibility(LocalResourceVisibility.APPLICATION);

    localResources.put(YARNBSPConstants.APP_MASTER_JAR_PATH, packageResource);

    Path hamaReleaseFile = new Path(System.getenv(YARNBSPConstants.HAMA_RELEASE_LOCATION));
    URL hamaReleaseUrl = ConverterUtils
            .getYarnUrlFromPath(hamaReleaseFile.makeQualified(fs.getUri(), fs.getWorkingDirectory()));
    LOG.info("Hama release URL has been composed to " + hamaReleaseUrl.toString());

    LocalResource hamaReleaseRsrc = Records.newRecord(LocalResource.class);
    hamaReleaseRsrc.setResource(hamaReleaseUrl);
    hamaReleaseRsrc.setSize(Long.parseLong(System.getenv(YARNBSPConstants.HAMA_RELEASE_SIZE)));
    hamaReleaseRsrc.setTimestamp(Long.parseLong(System.getenv(YARNBSPConstants.HAMA_RELEASE_TIMESTAMP)));
    hamaReleaseRsrc.setType(LocalResourceType.ARCHIVE);
    hamaReleaseRsrc.setVisibility(LocalResourceVisibility.APPLICATION);

    localResources.put(YARNBSPConstants.HAMA_SYMLINK, hamaReleaseRsrc);

    ctx.setLocalResources(localResources);

    /*
     * TODO Package classpath seems not to work if you're in pseudo distributed
     * mode, because the resource must not be moved, it will never be unpacked.
     * So we will check if our jar file has the file:// prefix and put it into
     * the CP directly
     */

    StringBuilder classPathEnv = new StringBuilder(ApplicationConstants.Environment.CLASSPATH.$())
            .append(File.pathSeparatorChar).append("./*");
    for (String c : conf.getStrings(YarnConfiguration.YARN_APPLICATION_CLASSPATH,
            YarnConfiguration.DEFAULT_YARN_APPLICATION_CLASSPATH)) {
        classPathEnv.append(File.pathSeparatorChar);
        classPathEnv.append(c.trim());
    }

    classPathEnv.append(File.pathSeparator);
    classPathEnv
            .append("./" + YARNBSPConstants.HAMA_SYMLINK + "/" + YARNBSPConstants.HAMA_RELEASE_VERSION + "/*");
    classPathEnv.append(File.pathSeparator);
    classPathEnv.append(
            "./" + YARNBSPConstants.HAMA_SYMLINK + "/" + YARNBSPConstants.HAMA_RELEASE_VERSION + "/lib/*");

    Vector<CharSequence> vargs = new Vector<CharSequence>();
    vargs.add("${JAVA_HOME}/bin/java");
    vargs.add("-cp " + classPathEnv + "");
    vargs.add(BSPRunner.class.getCanonicalName());

    vargs.add(jobId.getJtIdentifier());
    vargs.add(Integer.toString(id));
    vargs.add(this.jobFile.makeQualified(fs.getUri(), fs.getWorkingDirectory()).toString());

    vargs.add("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/bsp.stdout");
    vargs.add("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/bsp.stderr");

    // Get final commmand
    StringBuilder command = new StringBuilder();
    for (CharSequence str : vargs) {
        command.append(str).append(" ");
    }

    List<String> commands = new ArrayList<String>();
    commands.add(command.toString());

    ctx.setCommands(commands);
    LOG.info("Starting command: " + commands);

    StartContainerRequest startReq = Records.newRecord(StartContainerRequest.class);
    startReq.setContainerLaunchContext(ctx);
    startReq.setContainerToken(allocatedContainer.getContainerToken());

    List<StartContainerRequest> list = new ArrayList<StartContainerRequest>();
    list.add(startReq);
    StartContainersRequest requestList = StartContainersRequest.newInstance(list);
    cm.startContainers(requestList);

    GetContainerStatusesRequest statusReq = Records.newRecord(GetContainerStatusesRequest.class);
    List<ContainerId> containerIds = new ArrayList<ContainerId>();
    containerIds.add(allocatedContainer.getId());
    statusReq.setContainerIds(containerIds);
    return statusReq;
}

From source file:esg.node.core.Resource.java

private boolean tryClasspath(String filename) {
    String classpath = System.getProperty("java.class.path");
    String[] paths = split(classpath, File.pathSeparator);
    file = searchDirectories(paths, filename);
    return (file != null);
}

From source file:net.grinder.util.AbstractGrinderClassPathProcessor.java

/**
 * Construct classPath from current classLoader.
 *
 * @param logger logger//w w w.j  a  v a  2s .c o  m
 * @return classpath optimized for grinder.
 */
public String buildClasspathBasedOnCurrentClassLoader(Logger logger) {
    URL[] urls = ((URLClassLoader) AbstractGrinderClassPathProcessor.class.getClassLoader()).getURLs();

    StringBuilder builder = new StringBuilder();
    for (URL each : urls) {
        builder.append(each.getFile()).append(File.pathSeparator);
    }
    if (builder.length() < 300) {
        // In case of the URLClassLoader is not activated, Try with system class path
        final String property = System.getProperty("java.class.path", "");
        for (String each : property.split(File.pathSeparator)) {
            builder.append(each).append(File.pathSeparator);
        }
    }
    return filterClassPath(builder.toString(), logger);
}