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:de.xirp.plugin.PluginManager.java

/**
 * Gets the library path used on startup of this application.
 * //from  ww  w  . j a  va2 s  . co  m
 * @return the first entry of the library path.
 */
private static String getLibraryPath() {
    String path = ManagementFactory.getRuntimeMXBean().getLibraryPath();
    // String path = System.getProperty("java.library.path");
    // //$NON-NLS-1$
    return path.split(File.pathSeparator)[0];
}

From source file:org.apache.catalina.loader.WebappLoader.java

/**
 * Set the appropriate context attribute for our class path.  This
 * is required only because Jasper depends on it.
 *///from w  w w.j a v a  2  s.  c o  m
private void setClassPath() {

    // Validate our current state information
    if (!(container instanceof Context))
        return;
    ServletContext servletContext = ((Context) container).getServletContext();
    if (servletContext == null)
        return;

    if (container instanceof StandardContext) {
        String baseClasspath = ((StandardContext) container).getCompilerClasspath();
        if (baseClasspath != null) {
            servletContext.setAttribute(Globals.CLASS_PATH_ATTR, baseClasspath);
            return;
        }
    }

    StringBuffer classpath = new StringBuffer();

    // Assemble the class path information from our class loader chain
    ClassLoader loader = getClassLoader();
    int layers = 0;
    int n = 0;
    while (loader != null) {
        if (!(loader instanceof URLClassLoader)) {
            String cp = getClasspath(loader);
            if (cp == null) {
                log.info("Unknown loader " + loader + " " + loader.getClass());
                break;
            } else {
                if (n > 0)
                    classpath.append(File.pathSeparator);
                classpath.append(cp);
                n++;
            }
            break;
            //continue;
        }
        URL repositories[] = ((URLClassLoader) loader).getURLs();
        for (int i = 0; i < repositories.length; i++) {
            String repository = repositories[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 (n > 0)
                classpath.append(File.pathSeparator);
            classpath.append(repository);
            n++;
        }
        loader = loader.getParent();
        layers++;
    }

    this.classpath = classpath.toString();

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

}

From source file:io.druid.segment.realtime.plumber.RealtimePlumber.java

protected File computeCorruptedFileDumpDir(File persistDir, DataSchema schema) {
    return new File(persistDir.getAbsolutePath().replace(schema.getDataSource(),
            "corrupted" + File.pathSeparator + schema.getDataSource()));
}

From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.java

public void sanitizeEnv(Map<String, String> environment, Path pwd, List<Path> appDirs,
        List<String> containerLogDirs, Map<Path, List<String>> resources, Path nmPrivateClasspathJarDir)
        throws IOException {
    /**//from w  w w . j  a  va 2s. c  om
     * Non-modifiable environment variables
     */

    environment.put(Environment.CONTAINER_ID.name(), container.getContainerId().toString());

    environment.put(Environment.NM_PORT.name(), String.valueOf(this.context.getNodeId().getPort()));

    environment.put(Environment.NM_HOST.name(), this.context.getNodeId().getHost());

    environment.put(Environment.NM_HTTP_PORT.name(), String.valueOf(this.context.getHttpPort()));

    environment.put(Environment.LOCAL_DIRS.name(), StringUtils.join(",", appDirs));

    environment.put(Environment.LOG_DIRS.name(), StringUtils.join(",", containerLogDirs));

    environment.put(Environment.USER.name(), container.getUser());

    environment.put(Environment.LOGNAME.name(), container.getUser());

    environment.put(Environment.HOME.name(),
            conf.get(YarnConfiguration.NM_USER_HOME_DIR, YarnConfiguration.DEFAULT_NM_USER_HOME_DIR));

    environment.put(Environment.PWD.name(), pwd.toString());

    putEnvIfNotNull(environment, Environment.HADOOP_CONF_DIR.name(),
            System.getenv(Environment.HADOOP_CONF_DIR.name()));

    if (!Shell.WINDOWS) {
        environment.put("JVM_PID", "$$");
    }

    /**
     * Modifiable environment variables
     */

    // allow containers to override these variables
    String[] whitelist = conf
            .get(YarnConfiguration.NM_ENV_WHITELIST, YarnConfiguration.DEFAULT_NM_ENV_WHITELIST).split(",");

    for (String whitelistEnvVariable : whitelist) {
        putEnvIfAbsent(environment, whitelistEnvVariable.trim());
    }

    // variables here will be forced in, even if the container has specified them.
    Apps.setEnvFromInputString(environment,
            conf.get(YarnConfiguration.NM_ADMIN_USER_ENV, YarnConfiguration.DEFAULT_NM_ADMIN_USER_ENV),
            File.pathSeparator);

    // TODO: Remove Windows check and use this approach on all platforms after
    // additional testing.  See YARN-358.
    if (Shell.WINDOWS) {

        String inputClassPath = environment.get(Environment.CLASSPATH.name());

        if (inputClassPath != null && !inputClassPath.isEmpty()) {

            //On non-windows, localized resources
            //from distcache are available via the classpath as they were placed
            //there but on windows they are not available when the classpath
            //jar is created and so they "are lost" and have to be explicitly
            //added to the classpath instead.  This also means that their position
            //is lost relative to other non-distcache classpath entries which will
            //break things like mapreduce.job.user.classpath.first.  An environment
            //variable can be set to indicate that distcache entries should come
            //first

            boolean preferLocalizedJars = Boolean
                    .parseBoolean(environment.get(Environment.CLASSPATH_PREPEND_DISTCACHE.name()));

            boolean needsSeparator = false;
            StringBuilder newClassPath = new StringBuilder();
            if (!preferLocalizedJars) {
                newClassPath.append(inputClassPath);
                needsSeparator = true;
            }

            // Localized resources do not exist at the desired paths yet, because the
            // container launch script has not run to create symlinks yet.  This
            // means that FileUtil.createJarWithClassPath can't automatically expand
            // wildcards to separate classpath entries for each file in the manifest.
            // To resolve this, append classpath entries explicitly for each
            // resource.
            for (Map.Entry<Path, List<String>> entry : resources.entrySet()) {
                boolean targetIsDirectory = new File(entry.getKey().toUri().getPath()).isDirectory();

                for (String linkName : entry.getValue()) {
                    // Append resource.
                    if (needsSeparator) {
                        newClassPath.append(File.pathSeparator);
                    } else {
                        needsSeparator = true;
                    }
                    newClassPath.append(pwd.toString()).append(Path.SEPARATOR).append(linkName);

                    // FileUtil.createJarWithClassPath must use File.toURI to convert
                    // each file to a URI to write into the manifest's classpath.  For
                    // directories, the classpath must have a trailing '/', but
                    // File.toURI only appends the trailing '/' if it is a directory that
                    // already exists.  To resolve this, add the classpath entries with
                    // explicit trailing '/' here for any localized resource that targets
                    // a directory.  Then, FileUtil.createJarWithClassPath will guarantee
                    // that the resulting entry in the manifest's classpath will have a
                    // trailing '/', and thus refer to a directory instead of a file.
                    if (targetIsDirectory) {
                        newClassPath.append(Path.SEPARATOR);
                    }
                }
            }
            if (preferLocalizedJars) {
                if (needsSeparator) {
                    newClassPath.append(File.pathSeparator);
                }
                newClassPath.append(inputClassPath);
            }

            // When the container launches, it takes the parent process's environment
            // and then adds/overwrites with the entries from the container launch
            // context.  Do the same thing here for correct substitution of
            // environment variables in the classpath jar manifest.
            Map<String, String> mergedEnv = new HashMap<String, String>(System.getenv());
            mergedEnv.putAll(environment);

            // this is hacky and temporary - it's to preserve the windows secure
            // behavior but enable non-secure windows to properly build the class
            // path for access to job.jar/lib/xyz and friends (see YARN-2803)
            Path jarDir;
            if (exec instanceof WindowsSecureContainerExecutor) {
                jarDir = nmPrivateClasspathJarDir;
            } else {
                jarDir = pwd;
            }
            String[] jarCp = FileUtil.createJarWithClassPath(newClassPath.toString(), jarDir, pwd, mergedEnv);
            // In a secure cluster the classpath jar must be localized to grant access
            Path localizedClassPathJar = exec.localizeClasspathJar(new Path(jarCp[0]), pwd,
                    container.getUser());
            String replacementClassPath = localizedClassPathJar.toString() + jarCp[1];
            environment.put(Environment.CLASSPATH.name(), replacementClassPath);
        }
    }
    // put AuxiliaryService data to environment
    for (Map.Entry<String, ByteBuffer> meta : containerManager.getAuxServiceMetaData().entrySet()) {
        AuxiliaryServiceHelper.setServiceDataIntoEnv(meta.getKey(), meta.getValue(), environment);
    }
}

From source file:ca.weblite.xmlvm.XMLVM.java

/**
 * Perform a clean build./* w w  w  .j  a v  a2 s . c  o m*/
 * @throws IOException 
 */
public void doCleanBuild() throws IOException {

    // Step 1:  Clear out the XMLVM cache dirs (used for dependency analysis)

    File xmlvmDir = this.getXmlvmCacheDir("xmlvm");
    System.out.print("Deleting old xmlvm cache directory...");
    FileUtils.deleteDirectory(xmlvmDir);
    System.out.println("Finished.");
    xmlvmDir.mkdirs();

    // Step 2:  Compile java source files with javac.
    Javac javac = (Javac) getProject().createTask("javac");
    setJavac(javac);
    javac.setDestdir(getJavaBuildDir());
    javac.setSrcdir(getSrc());
    javac.setClasspath(getClassPath());
    javac.execute();

    // Step 3: Generate Dependency graph
    createDependencyGraph(getJavaBuildDir(), xmlvmDir, javac.getClasspath());

    // Step 4: Do a full XMLVM to C compilation

    // Delete the destination directory via rename
    System.out.print("Deleting destination directory...");
    FileUtils.deleteDirectory(getDest());
    System.out.println("Finished");

    this.runXmlvm(new String[] { "--in=" + getJavaBuildDir().getAbsolutePath(),
            "--out=" + getDest().getAbsolutePath(), "--target=c",
            "--libraries=" + getJavac().getClasspath().toString().replaceAll(File.pathSeparator, ","),
            "--c-source-extension=m", // "--debug=all",
            "--load-dependencies", "--disable-vtable-optimizations" });

}

From source file:ca.weblite.xmlvm.XMLVM.java

/**
 * /*from   www .  j  a va 2s. com*/
 * @param src Directory containing class files.
 * @param dest Directory where xmlvm files will be written, as well as .deps files
 */
public void createDependencyGraph(File src, File dest, Path libPath) {
    try {
        this.runXmlvm(new String[] { "--in=" + src.getAbsolutePath(), "--out=" + dest.getAbsolutePath(),
                "--target=vtable", "--libraries=" + libPath.toString().replaceAll(File.pathSeparator, ","),
                "--load-dependencies", "--disable-vtable-optimizations" });

        for (File f : dest.listFiles()) {
            if (!f.getName().endsWith(".xmlvm")) {
                continue;
            }
            addFileToDependencyGraph(f, dest);
        }

    } catch (Exception ex) {
        Logger.getLogger(XMLVM.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.apache.maven.plugin.javadoc.JavadocUtil.java

/**
 * Unify the given path with the current System path separator, to be platform independent.
 * Examples://w w  w  .j  a  va 2  s .  c  o  m
 * <pre>
 * unifyPathSeparator( "/home:/tmp" ) = "/home:/tmp" (Solaris box)
 * unifyPathSeparator( "/home:/tmp" ) = "/home;/tmp" (Windows box)
 * </pre>
 *
 * @param path which can contain multiple paths by separating them with a colon (<code>:</code>) or a
 * semi-colon (<code>;</code>), platform independent. Could be null.
 * @return the same path but separated with the current System path separator or <code>null</code> if path was
 * <code>null</code>.
 * @since 2.6.1
 * @see #splitPath(String)
 * @see File#pathSeparator
 */
protected static String unifyPathSeparator(final String path) {
    if (path == null) {
        return null;
    }

    return StringUtils.join(splitPath(path), File.pathSeparator);
}

From source file:org.apache.hadoop.hdfs.server.datanode.DWRRBlockReceiver.java

void finalizeReceiveBlock() throws IOException {
    try {//from w w  w  . j a v  a  2  s. c  om
        while (toBeWritten.size() > 0) {
            finalizeReceivePacket(toBeWritten.poll());
        }
        toBeWritten = null;
        // wait for all outstanding packet responses. And then
        // indicate responder to gracefully shutdown.
        // Mark that responder has been closed for future processing
        if (responder != null) {
            ((PacketResponder) responder.getRunnable()).close();
            responderClosed = true;
        }

        // If this write is for a replication or transfer-RBW/Finalized,
        // then finalize block or convert temporary to RBW.
        // For client-writes, the block is finalized in the PacketResponder.
        if (isDatanode || isTransfer) {
            // close the block/crc files
            close();
            block.setNumBytes(replicaInfo.getNumBytes());

            if (stage == BlockConstructionStage.TRANSFER_RBW) {
                // for TRANSFER_RBW, convert temporary to RBW
                datanode.data.convertTemporaryToRbw(block);
            } else {
                // for isDatnode or TRANSFER_FINALIZED
                // Finalize the block.
                datanode.data.finalizeBlock(block);
            }
            datanode.metrics.incrBlocksWritten();
        }
        if (isClient) {
            close();
            final long endTime = ClientTraceLog.isInfoEnabled() ? System.nanoTime() : 0;
            block.setNumBytes(replicaInfo.getNumBytes());
            datanode.data.finalizeBlock(block);
            datanode.closeBlock(block, DataNode.EMPTY_DEL_HINT, replicaInfo.getStorageUuid());
            if (ClientTraceLog.isInfoEnabled() && isClient) {
                long offset = 0;
                DatanodeRegistration dnR = datanode.getDNRegistrationForBP(block.getBlockPoolId());
                ClientTraceLog.info(String.format(DN_CLIENTTRACE_FORMAT, inAddr, myAddr, block.getNumBytes(),
                        "HDFS_WRITE", clientname, offset, dnR.getDatanodeUuid(), block, endTime));
            } else {
                LOG.info("Received " + block + " size " + block.getNumBytes() + " from " + inAddr);
            }

        }

    } catch (IOException ioe) {
        LOG.error("CAMAMILLA " + this + " ioexception finalizeReceiveBlock " + ioe); // TODO TODO log
        if (datanode.isRestarting()) {
            // Do not throw if shutting down for restart. Otherwise, it will cause
            // premature termination of responder.
            LOG.info("Shutting down for restart (" + block + ").");
        } else {
            LOG.info("Exception for " + block, ioe);
            throw ioe;
        }
    } catch (Exception e) { // TODO TODO no hi era en l'ogriginal
        LOG.error("CAMAMILLA " + this + " exception finalizeReceiveBlock " + e); // TODO TODO log
    } finally {
        // Clear the previous interrupt state of this thread.
        Thread.interrupted();
        // If a shutdown for restart was initiated, upstream needs to be notified.
        // There is no need to do anything special if the responder was closed
        // normally.
        if (!responderClosed) { // Data transfer was not complete.
            LOG.info("CAMAMILLA " + this + " finally finalizeReceiveBlock responderClosed " + responderClosed); // TODO TODO log
            if (responder != null) {
                // In case this datanode is shutting down for quick restart,
                // send a special ack upstream.
                if (datanode.isRestarting() && isClient && !isTransfer) {
                    File blockFile = ((ReplicaInPipeline) replicaInfo).getBlockFile();
                    File restartMeta = new File(blockFile.getParent() + File.pathSeparator + "."
                            + blockFile.getName() + ".restart");
                    if (restartMeta.exists() && !restartMeta.delete()) {
                        LOG.warn("Failed to delete restart meta file: " + restartMeta.getPath());
                    }
                    try {
                        FileWriter out = new FileWriter(restartMeta);
                        // write out the current time.
                        out.write(Long.toString(Time.now() + restartBudget));
                        out.flush();
                        out.close();
                    } catch (IOException ioe) {
                        // The worst case is not recovering this RBW replica.
                        // Client will fall back to regular pipeline recovery.
                    }
                    LOG.info("CAMAMILLA " + this + " finally finalizeReceiveBlock send OOB Ack"); // TODO TODO log
                    try {
                        ((PacketResponder) responder.getRunnable())
                                .sendOOBResponse(PipelineAck.getRestartOOBStatus());
                        // Even if the connection is closed after the ack packet is
                        // flushed, the client can react to the connection closure
                        // first. Insert a delay to lower the chance of client
                        // missing the OOB ack.
                        Thread.sleep(1000);
                    } catch (InterruptedException ie) {
                        // It is already going down. Ignore this.
                    } catch (IOException ioe) {
                        LOG.info("Error sending OOB Ack.", ioe);
                    }
                }
                responder.interrupt();
            }
            IOUtils.closeStream(this);
            cleanupBlock();
        }
        if (responder != null) {
            try {
                responder.interrupt();
                // join() on the responder should timeout a bit earlier than the
                // configured deadline. Otherwise, the join() on this thread will
                // likely timeout as well.
                long joinTimeout = datanode.getDnConf().getXceiverStopTimeout();
                joinTimeout = joinTimeout > 1 ? joinTimeout * 8 / 10 : joinTimeout;
                responder.join(joinTimeout);
                if (responder.isAlive()) {
                    String msg = "Join on responder thread " + responder + " timed out";
                    LOG.warn(msg + "\n" + StringUtils.getStackTrace(responder));
                    throw new IOException(msg);
                }
            } catch (InterruptedException e) {
                responder.interrupt();
                // do not throw if shutting down for restart.
                if (!datanode.isRestarting()) {
                    throw new IOException("Interrupted receiveBlock");
                }
            }
            responder = null;
        }
    }
}

From source file:ca.weblite.xmlvm.XMLVM.java

/**
 * Almost the same as creating a dependency graph except that we assume that
 * the src directory only contains a subset of the files to convert.  It involves
 * Comparing the previous references of the files in the src dir to see if anything
 * has changed.// ww w .  j  av a2  s  . c  om
 * @param src Directory containing class files that have changed.
 * @param dest Directory containing xmlvm files and .deps files.
 */
private void updateDependencyGraph(File src, File dest) throws IOException {

    File tmpDir = File.createTempFile("dep", "dir");
    try {
        tmpDir.delete();
        tmpDir.mkdir();
        this.runXmlvm(new String[] { "--in=" + src.getAbsolutePath(), "--out=" + tmpDir.getAbsolutePath(),
                "--target=vtable", "--disable-vtable-optimizations",
                "--libraries=" + getJavac().getClasspath().toString().replaceAll(File.pathSeparator, ","),
                //"--load-dependencies"
        });

        for (File f : tmpDir.listFiles()) {
            if (f.getName().endsWith(".xmlvm")) {
                File oldXmlvmFile = new File(dest, f.getName());
                Map<String, String> newRefs = loadReferences(f);
                Map<String, String> oldRefs = null;
                if (oldXmlvmFile.exists()) {
                    oldRefs = loadReferences(oldXmlvmFile);

                } else {
                    oldRefs = new HashMap<>();
                }
                boolean changed = false;
                if (!oldRefs.entrySet().containsAll(newRefs.entrySet())) {
                    changed = true;
                }
                if (!changed && !newRefs.entrySet().containsAll(oldRefs.entrySet())) {
                    changed = true;
                }

                if (changed) {
                    updateDependencyGraphForFile(f, oldRefs, dest);

                }
                System.out.println("Copying " + f + " to " + oldXmlvmFile);
                FileUtils.copyFile(f, oldXmlvmFile);

            }

        }
    } finally {

        FileUtils.deleteDirectory(tmpDir);
    }
}

From source file:org.schemaspy.Config.java

/**
 * Returns the jar that we were loaded from
 *
 * @return//ww w  .ja  va2s .com
 */
public static String getLoadedFromJar() {
    String classpath = System.getProperty("java.class.path");
    return new StringTokenizer(classpath, File.pathSeparator).nextToken();
}