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.springsource.ide.eclipse.commons.internal.configurator.Configurator.java

public void executePendingRequests() {
    String configureTargets = Activator.getDefault().getPreferenceStore()
            .getString(Activator.PROPERTY_CONFIGURE_TARGETS);
    List<String> newConfigureTargets = new ArrayList<String>();
    if (StringUtils.hasLength(configureTargets)) {
        StringTokenizer targets = new StringTokenizer(configureTargets, File.pathSeparator);
        while (targets.hasMoreTokens()) {
            String target = targets.nextToken();
            Map<String, String> parameters = new HashMap<String, String>();
            if (target.startsWith("extension=")) {
                parameters.put(PARAM_EXTENSION, target.substring("extension=".length()));
            } else {
                parameters.put(PARAM_TARGET, target);
            }/*w  ww .  ja va 2  s . co m*/
            IStatus status = execute(parameters, true);
            if (!status.isOK()) {
                newConfigureTargets.add(target);
            }
        }
    }
    Activator.getDefault().getPreferenceStore().setValue(Activator.PROPERTY_CONFIGURE_TARGETS,
            StringUtils.collectionToDelimitedString(newConfigureTargets, File.pathSeparator));
}

From source file:net.sourceforge.ganttproject.gui.options.InterfaceOptionPageProvider.java

private static File getExtDir() {
    File fallback = new File(System.getProperty("java.home"), Joiner.on(File.separatorChar).join("lib", "ext"));
    String extDirsProperty = System.getProperty("java.ext.dirs");
    if (Strings.isNullOrEmpty(extDirsProperty)) {
        return fallback;
    }/*from   ww  w  . ja  v  a 2 s .c  o m*/
    for (String s : extDirsProperty.split(File.pathSeparator)) {
        File file = new File(s);
        if (!file.exists()) {
            continue;
        }
        if (!file.isDirectory()) {
            continue;
        }
        if (file.canWrite()) {
            return file;
        }
        fallback = file;
    }
    return fallback;
}

From source file:com.thoughtworks.gauge.maven.GaugeExecutionMojo.java

private String createCustomClasspath() {
    if (classpath == null || classpath.isEmpty()) {
        return "";
    }/*from   www  .ja  v  a2  s .  c om*/
    return StringUtils.join(classpath, File.pathSeparator);
}

From source file:org.apache.carbondata.processing.loading.TableProcessingOperations.java

/**
 *
 * This method will delete the local data load folder location after data load is complete
 *
 * @param tempLocationKey temporary location set in carbon properties
 * @param tableName//from  ww w .  j  a  v  a2  s . c o  m
 */
public static void deleteLocalDataLoadFolderLocation(String tempLocationKey, String tableName) {

    // form local store location
    final String localStoreLocations = CarbonProperties.getInstance().getProperty(tempLocationKey);
    if (localStoreLocations == null) {
        throw new RuntimeException("Store location not set for the key " + tempLocationKey);
    }
    // submit local folder clean up in another thread so that main thread execution is not blocked
    ExecutorService localFolderDeletionService = Executors.newFixedThreadPool(1,
            new CarbonThreadFactory("LocalFolderDeletionPool:" + tableName, true));
    try {
        localFolderDeletionService.submit(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                long startTime = System.currentTimeMillis();
                String[] locArray = StringUtils.split(localStoreLocations, File.pathSeparator);
                for (String loc : locArray) {
                    try {
                        CarbonUtil.deleteFoldersAndFiles(new File(loc));
                    } catch (IOException | InterruptedException e) {
                        LOGGER.error("Failed to delete local data load folder location: " + loc, e);
                    }
                }
                LOGGER.info("Deleted the local store location: " + localStoreLocations + " : Time taken: "
                        + (System.currentTimeMillis() - startTime));
                return null;
            }
        });
    } finally {
        CarbonProperties.getInstance().removeProperty(tempLocationKey);
        if (null != localFolderDeletionService) {
            localFolderDeletionService.shutdown();
        }
    }

}

From source file:com.taobao.adfs.util.Utilities.java

public static String getNormalPath(String path) throws IOException {
    if (!path.startsWith("/"))
        path = getCurrentPath() + "/" + path;
    path = new File(path).getAbsolutePath();
    path = path.replaceAll("\\.\\.", "**");
    path = path.replaceAll("\\." + File.pathSeparator + "+", "");
    while (true) {
        int posOfParentPath = path.indexOf("**");
        if (posOfParentPath < 0)
            break;
        int posOfSeparator = path.lastIndexOf(File.separator, posOfParentPath - 2);
        if (posOfSeparator < 0)
            posOfSeparator = 0;/*from ww  w.jav  a 2s. c o  m*/
        path = path.substring(0, posOfSeparator) + path.substring(posOfParentPath + 2);
        if (path.isEmpty())
            path = File.separator;
    }

    return path;
}

From source file:org.apache.hive.hcatalog.templeton.tool.LaunchMapper.java

private static void handleHadoopClasspathExtras(Configuration conf, Map<String, String> env)
        throws IOException {
    if (!TempletonUtils.isset(conf.get(JobSubmissionConstants.HADOOP_CLASSPATH_EXTRAS))) {
        return;/*from   w  w w. j a va 2s.c  om*/
    }
    LOG.debug(HADOOP_CLASSPATH_EXTRAS + "=" + conf.get(HADOOP_CLASSPATH_EXTRAS));
    String[] files = conf.getStrings(HADOOP_CLASSPATH_EXTRAS);
    StringBuilder paths = new StringBuilder();
    FileSystem fs = FileSystem.getLocal(conf);//these have been localized already
    for (String f : files) {
        Path p = new Path(f);
        FileStatus fileStatus = fs.getFileStatus(p);
        paths.append(f);
        if (fileStatus.isDir()) {
            paths.append(File.separator).append("*");
        }
        paths.append(File.pathSeparator);
    }
    paths.setLength(paths.length() - 1);
    prependPathToVariable(HADOOP_CLASSPATH, env, paths.toString());
}

From source file:dk.netarkivet.harvester.harvesting.controller.AbstractJMXHeritrixController.java

/**
 * Create a BnfHeritrixController object.
 *
 * @param files//from  w  w w  .  j a  v a  2 s.c  o m
 *            Files that are used to set up Heritrix.
 */
public AbstractJMXHeritrixController(HeritrixFiles files) {
    ArgumentNotValid.checkNotNull(files, "HeritrixFile files");
    this.files = files;

    SystemUtils.checkPortNotUsed(guiPort);
    SystemUtils.checkPortNotUsed(jmxPort);

    hostName = SystemUtils.getLocalHostName();

    try {
        log.info("Starting Heritrix for " + this);
        /*
         * To start Heritrix, we need to do the following (taken from the
         * Heritrix startup shell script): - set heritrix.home to base dir
         * of Heritrix stuff - set com.sun.management.jmxremote.port to JMX
         * port - set com.sun.management.jmxremote.ssl to false - set
         * com.sun.management.jmxremote.password.file to JMX password file -
         * set heritrix.out to heritrix_out.log - set
         * java.protocol.handler.pkgs=org.archive.net - send processOutput &
         * stderr into heritrix.out - let the Heritrix GUI-webserver listen
         * on all available network interfaces: This is done with argument
         * "--bind /" (default is 127.0.0.1) - listen on a specific port
         * using the port argument: --port <GUI port>
         *
         * We also need to output something like the following to
         * heritrix.out: `date Starting heritrix uname -a java -version
         * JAVA_OPTS ulimit -a
         */
        File heritrixOutputFile = files.getHeritrixOutput();
        StringBuilder settingProperty = new StringBuilder();
        for (File file : Settings.getSettingsFiles()) {
            settingProperty.append(File.pathSeparator);

            String absolutePath = file.getAbsolutePath();
            // check that the settings files not only exist but
            // are readable
            boolean readable = new File(absolutePath).canRead();
            if (!readable) {
                final String errMsg = "The file '" + absolutePath + "' is missing. ";
                log.warn(errMsg);
                throw new IOFailure("Failed to read file '" + absolutePath + "'");
            }
            settingProperty.append(absolutePath);
        }
        if (settingProperty.length() > 0) {
            // delete last path-separator
            settingProperty.deleteCharAt(0);
        }

        List<String> allOpts = new LinkedList<String>();
        allOpts.add(new File(new File(System.getProperty("java.home"), "bin"), "java").getAbsolutePath());
        allOpts.add("-Xmx" + Settings.get(HarvesterSettings.HERITRIX_HEAP_SIZE));
        allOpts.add("-Dheritrix.home=" + files.getCrawlDir().getAbsolutePath());

        String jvmOptsStr = Settings.get(HarvesterSettings.HERITRIX_JVM_OPTS);
        if ((jvmOptsStr != null) && (!jvmOptsStr.isEmpty())) {
            String[] add = jvmOptsStr.split(" ");
            allOpts.addAll(Arrays.asList(add));
        }

        allOpts.add("-Dcom.sun.management.jmxremote.port=" + jmxPort);
        allOpts.add("-Dcom.sun.management.jmxremote.ssl=false");
        // check that JMX password and access files are readable.
        // TODO This should probably be extracted to a method?
        File passwordFile = files.getJmxPasswordFile();
        String pwAbsolutePath = passwordFile.getAbsolutePath();
        if (!passwordFile.canRead()) {
            final String errMsg = "Failed to read the password file '" + pwAbsolutePath
                    + "'. It is possibly missing.";
            log.warn(errMsg);
            throw new IOFailure(errMsg);
        }
        File accessFile = files.getJmxAccessFile();
        String acAbsolutePath = accessFile.getAbsolutePath();
        if (!accessFile.canRead()) {
            final String errMsg = "Failed to read the access file '" + acAbsolutePath
                    + "'. It is possibly missing.";
            log.warn(errMsg);
            throw new IOFailure(errMsg);
        }
        allOpts.add("-Dcom.sun.management.jmxremote.password.file=" + new File(pwAbsolutePath));
        allOpts.add("-Dcom.sun.management.jmxremote.access.file=" + new File(acAbsolutePath));
        allOpts.add("-Dheritrix.out=" + heritrixOutputFile.getAbsolutePath());
        allOpts.add("-Djava.protocol.handler.pkgs=org.archive.net");
        allOpts.add("-Ddk.netarkivet.settings.file=" + settingProperty);
        allOpts.add(Heritrix.class.getName());
        allOpts.add("--bind");
        allOpts.add("/");
        allOpts.add("--port=" + guiPort);
        allOpts.add("--admin=" + getHeritrixAdminName() + ":" + getHeritrixAdminPassword());

        String[] args = allOpts.toArray(new String[allOpts.size()]);
        log.info("Starting Heritrix process with args" + Arrays.toString(args));
        log.debug("The JMX timeout is set to " + TimeUtils.readableTimeInterval(JMXUtils.getJmxTimeout()));

        ProcessBuilder builder = new ProcessBuilder(args);

        updateEnvironment(builder.environment());
        FileUtils.copyDirectory(new File("lib/heritrix"), files.getCrawlDir());
        builder.directory(files.getCrawlDir());
        builder.redirectErrorStream(true);
        writeSystemInfo(heritrixOutputFile, builder);
        FileUtils.appendToFile(heritrixOutputFile, "Working directory: " + files.getCrawlDir());
        addProcessKillerHook();
        heritrixProcess = builder.start();
        ProcessUtils.writeProcessOutput(heritrixProcess.getInputStream(), heritrixOutputFile,
                collectionThreads);
    } catch (IOException e) {
        throw new IOFailure("Error starting Heritrix process", e);
    }
}

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

/**
 * Construct the foremost classPath from current classLoader.
 * //from w w  w .  j  av a2 s  .  c o m
 * @param logger
 *            logger
 * @return classpath optimized for grinder.
 */
public static String buildForemostClasspathBasedOnCurrentClassLoader(Logger logger) {
    URL[] urLs = ((URLClassLoader) GrinderClassPathUtils.class.getClassLoader()).getURLs();
    StringBuilder builder = new StringBuilder();
    for (URL each : urLs) {
        builder.append(each.getFile()).append(File.pathSeparator);
    }
    return GrinderClassPathUtils.filterForeMostClassPath(builder.toString(), logger);
}

From source file:com.devesion.maven.jsr308.CheckersPlugin.java

/**
 * Plugin Entry point./*from   ww w.ja va  2  s.  c  o m*/
 * 
 * @throws MojoExecutionException exception
 * @throws MojoFailureException exception
 */
@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    getLog().info("Executing JSR-308 Checkers");

    if (checkers.size() <= 0) {
        getLog().info("No checkers found, omitting checkers execution");
        return;
    }

    final SourceContext sourceCtx = new SourceContext(compileSourceDirs, includes, excludes);
    final List<String> sources = SourceUtils.getProjectSources(sourceCtx);
    if (sources.isEmpty()) {
        getLog().info("The project does not contains any sources, omitting checkers execution");
        return;
    }

    final CommandLine cl = new CommandLine("java");
    if (checkerJar == null || checkerJar.isEmpty()) {
        checkerJar = ArtifactUtils.getArtifactPath(JSR308_ALL_GROUP_ID, JSR308_ALL_ARTIFACT_ID, dependencies);
        if (checkerJar == null) {
            throw new MojoExecutionException("Cannot find " + JSR308_ALL_GROUP_ID + ":" + JSR308_ALL_ARTIFACT_ID
                    + " artifact jar in the local repository.");
        }
    }

    cl.addArgument("-Xbootclasspath/p:" + checkerJar);
    cl.addArgument("-ea:com.sun.tools");
    if (userJavaParams != null) {
        cl.addArgument(userJavaParams);
    }
    cl.addArgument("-jar");
    cl.addArgument(checkerJar);
    cl.addArgument("-proc:only");

    // adding checkers
    for (String checker : checkers) {
        cl.addArgument("-processor");
        cl.addArgument(checker);
    }

    // adding project sources
    cl.addArguments(sources.toArray(new String[sources.size()]));

    // adding classpath
    final StringBuilder sb = new StringBuilder();
    for (String element : compileClasspathElements) {
        sb.append(element);
        sb.append(File.pathSeparator);
    }

    cl.addArgument("-classpath");
    cl.addArgument(sb.toString());
    if (userJavacParams != null) {
        cl.addArgument(userJavacParams);
    }

    // executing compiler
    final DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(EXIT_CODE_OK);

    try {
        executor.execute(cl);
    } catch (ExecuteException ex) {

        if (failOnError) {
            throw new MojoExecutionException(
                    "Unable to continue because of some errors reported by checkers - " + ex.getMessage());
        } else {
            getLog().error("Some errors has been reported by checkers - " + ex.getMessage());
        }
    } catch (IOException ex) {
        throw new MojoExecutionException("cannot execute checkers", ex);
    }
}

From source file:org.apache.hadoop.hdfs.server.namenode.NNStorageDirectoryRetentionManager.java

/**
 * Delete backups according to the retention policy.
 * /*from   w w  w.  ja  v  a2  s.  c  o  m*/
 * @param root root directory
 * @param backups backups SORTED on the timestamp from oldest to newest
 * @param daysToKeep
 * @param copiesToKeep
 */
static void deleteOldBackups(File root, String[] backups, int daysToKeep, int copiesToKeep) {
    Date now = new Date(System.currentTimeMillis());

    // leave the copiesToKeep-1 at least (+1 will be the current backup)
    int maxIndex = Math.max(0, backups.length - copiesToKeep + 1);

    for (int i = 0; i < maxIndex; i++) {
        String backup = backups[i];
        Date backupDate = null;
        try {
            backupDate = dateForm.get().parse(backup.substring(backup.indexOf(File.pathSeparator) + 1));
        } catch (ParseException pex) {
            // This should not happen because of the 
            // way we construct the list
        }
        long backupAge = now.getTime() - backupDate.getTime();

        // if daysToKeep is set delete everything older providing that
        // we retain at least copiesToKeep copies
        boolean deleteOldBackup = (daysToKeep > 0 && backupAge > daysToKeep * 24 * 60 * 60 * 1000);

        // if daysToKeep is set to zero retain most recent copies
        boolean deleteExtraBackup = (daysToKeep == 0);

        if (deleteOldBackup || deleteExtraBackup) {
            // This backup is older than daysToKeep, delete it
            try {
                FLOG.info("Deleting backup " + new File(root, backup));
                FileUtil.fullyDelete(new File(root, backup));
                FLOG.info("Deleted backup " + new File(root, backup));
            } catch (IOException iex) {
                FLOG.error("Error deleting backup " + new File(root, backup), iex);
            }
        } else {
            // done with deleting old backups
            break;
        }
    }
}