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:com.obergner.hzserver.ServerInfo.java

private void logBootClassPath() {
    logStringEntries("BootClassPath", getBootClassPath(), File.pathSeparator);
}

From source file:org.apache.sqoop.accumulo.AccumuloTestCase.java

private static void append(StringBuilder classpathBuilder, URL url) throws URISyntaxException {
    File file = new File(url.toURI());
    // do not include dirs containing hadoop or accumulo site files, nor the hive-exec jar (which has thrift inside)
    if (!containsSiteFile(file) && !isHiveExec(file))
        classpathBuilder.append(File.pathSeparator).append(file.getAbsolutePath());
}

From source file: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 {//from  ww w  . j a  v a 2  s . co  m
        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.newContainerId(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()];
    Process amProc = Runtime.getRuntime().exec(amCmd, envAMList.toArray(envAM));

    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.geoserver.importer.transform.AbstractCommandLinePreTransform.java

/**
 * Locates and executable in the system path. On windows it will automatically append .exe to
 * the searched file name/*from  w w  w  .  ja v a2s .  c o  m*/
 * 
 * @param name
 *
 * @throws IOException
 */
protected File getExecutableFromPath(String name) throws IOException {
    if (SystemUtils.IS_OS_WINDOWS) {
        name = name + ".exe";
    }
    String systemPath = System.getenv("PATH");
    if (systemPath == null) {
        systemPath = System.getenv("path");
    }
    if (systemPath == null) {
        throw new IOException("Path is not set, cannot locate " + name);
    }
    String[] paths = systemPath.split(File.pathSeparator);

    for (String pathDir : paths) {
        File file = new File(pathDir, name);
        if (file.exists() && file.isFile() && file.canExecute()) {
            return file;
        }
    }
    throw new IOException(
            "Could not locate executable (or could locate, but does not have execution rights): " + name);
}

From source file:com.waitwha.nessus.server.Server.java

/**
 * @param args//  w w w  .j  a va2 s  .c  o m
 */
public static void main(String[] args) {
    String username = System.getProperty("user.name");
    String password = "";
    String url = "https://localhost:8834";
    String uuid = "";
    String output = "";

    for (int i = 0; i < args.length; i++) {
        if (args[i].equals("-h")) {
            url = args[(i + 1)];
            i++;
        } else if (args[i].equals("-p")) {
            password = args[(i + 1)];
            i++;
        } else if (args[i].equals("-u")) {
            username = args[(i + 1)];
            i++;
        } else if (args[i].equals("-d")) {
            uuid = args[(i + 1)];
            i++;
        } else if (args[i].equals("-o")) {
            output = args[(i + 1)];
            i++;
        }
    }

    if (uuid.length() > 0 && output.length() == 0)
        output = System.getProperty("user.dir") + File.pathSeparator + uuid + ".nessus";

    Server server = new Server(url);
    if (server.login(username, password)) {
        System.out.println(String.format("Successfully logged in as '%s'.", username));

        if (uuid.length() == 0) {
            System.out.println("Reports: ");
            ArrayList<Report> reports = server.getReports();
            for (Report report : reports)
                System.out.println(String.format(">> %s (%s)", report.getName(), report.getUuid()));

            if (reports.size() > 0) {
                System.out.println();
                System.out.println("Note: Use -d <uuid> to download a report.");
            }

        } else {
            System.out.print("Downloading report " + uuid + " -> " + output + " ...");
            try {
                server.downloadReport(uuid, output);
                System.out.println("done.");

            } catch (ParserConfigurationException | SAXException e) {
            }
        }

        server.logout();
    }
}

From source file:com.github.blindpirate.gogradle.crossplatform.DefaultGoBinaryManager.java

@SuppressWarnings({ "checkstyle:localvariablename" })
private Optional<Pair<Path, String>> findGoBinAndVersionHost() {
    String PATH = System.getenv("PATH");
    String[] paths = StringUtils.splitAndTrim(PATH, File.pathSeparator);

    for (String path : paths) {
        Path goExecutablePath = Paths.get(path).resolve("go" + Os.getHostOs().exeExtension());
        Optional<Pair<Path, String>> pathAndVersion = tryInvokeGoVersion(goExecutablePath);
        if (pathAndVersion.isPresent()) {
            return pathAndVersion;
        }//  www  .  ja v  a  2s. c om
    }
    return Optional.empty();
}

From source file:org.jitsi.jirecon.StreamForwarder.java

/**
 * Stop the converting.//from  w ww  .j a  v  a 2  s . c om
 */
public void stopForwarding() {
    //stopConvertingStreams();
    stopReceivingStreams();
    closeDataChannel();

    // Create an empty ".recording_finished" file in the output directory in
    // order to mark the directory as containing a finished recording.
    File recordingFinished = new File(outputDir + File.pathSeparator + ".recording_finished");
    try {
        if (!recordingFinished.createNewFile())
            logger.warn(".recording_finished already exists");
    } catch (IOException ioe) {
        logger.warn("Failed to create .recording_finished: " + ioe);
    }

    /*
    /*
     * NOTE: We don't need to stop translators because those media streams
     * will do it.
     */
    // stopTranslators();
}

From source file:io.druid.indexing.overlord.ForkingTaskRunner.java

@Override
public ListenableFuture<TaskStatus> run(final Task task) {
    synchronized (tasks) {
        if (!tasks.containsKey(task.getId())) {
            tasks.put(task.getId(),/*from   ww  w  .  j  a v a 2 s.  c o  m*/
                    new ForkingTaskRunnerWorkItem(task.getId(), exec.submit(new Callable<TaskStatus>() {
                        @Override
                        public TaskStatus call() {
                            final String attemptUUID = UUID.randomUUID().toString();
                            final File taskDir = new File(taskConfig.getBaseTaskDir(), task.getId());
                            final File attemptDir = new File(taskDir, attemptUUID);

                            final ProcessHolder processHolder;
                            final int childPort = portFinder.findUnusedPort();
                            try {
                                final Closer closer = Closer.create();
                                try {
                                    if (!attemptDir.mkdirs()) {
                                        throw new IOException(
                                                String.format("Could not create directories: %s", attemptDir));
                                    }

                                    final File taskFile = new File(attemptDir, "task.json");
                                    final File statusFile = new File(attemptDir, "status.json");
                                    final File logFile = new File(attemptDir, "log");

                                    // time to adjust process holders
                                    synchronized (tasks) {
                                        final ForkingTaskRunnerWorkItem taskWorkItem = tasks.get(task.getId());

                                        if (taskWorkItem.shutdown) {
                                            throw new IllegalStateException("Task has been shut down!");
                                        }

                                        if (taskWorkItem == null) {
                                            log.makeAlert("WTF?! TaskInfo disappeared!")
                                                    .addData("task", task.getId()).emit();
                                            throw new ISE("TaskInfo disappeared for task[%s]!", task.getId());
                                        }

                                        if (taskWorkItem.processHolder != null) {
                                            log.makeAlert("WTF?! TaskInfo already has a processHolder")
                                                    .addData("task", task.getId()).emit();
                                            throw new ISE("TaskInfo already has processHolder for task[%s]!",
                                                    task.getId());
                                        }

                                        final List<String> command = Lists.newArrayList();
                                        final String childHost = node.getHost();
                                        final String taskClasspath;
                                        if (task.getClasspathPrefix() != null
                                                && !task.getClasspathPrefix().isEmpty()) {
                                            taskClasspath = Joiner.on(File.pathSeparator)
                                                    .join(task.getClasspathPrefix(), config.getClasspath());
                                        } else {
                                            taskClasspath = config.getClasspath();
                                        }

                                        command.add(config.getJavaCommand());
                                        command.add("-cp");
                                        command.add(taskClasspath);

                                        Iterables.addAll(command,
                                                new QuotableWhiteSpaceSplitter(config.getJavaOpts()));

                                        // Override task specific javaOpts
                                        Object taskJavaOpts = task
                                                .getContextValue("druid.indexer.runner.javaOpts");
                                        if (taskJavaOpts != null) {
                                            Iterables.addAll(command,
                                                    new QuotableWhiteSpaceSplitter((String) taskJavaOpts));
                                        }

                                        for (String propName : props.stringPropertyNames()) {
                                            for (String allowedPrefix : config.getAllowedPrefixes()) {
                                                if (propName.startsWith(allowedPrefix)) {
                                                    command.add(String.format("-D%s=%s", propName,
                                                            props.getProperty(propName)));
                                                }
                                            }
                                        }

                                        // Override child JVM specific properties
                                        for (String propName : props.stringPropertyNames()) {
                                            if (propName.startsWith(CHILD_PROPERTY_PREFIX)) {
                                                command.add(String.format("-D%s=%s",
                                                        propName.substring(CHILD_PROPERTY_PREFIX.length()),
                                                        props.getProperty(propName)));
                                            }
                                        }

                                        // Override task specific properties
                                        final Map<String, Object> context = task.getContext();
                                        if (context != null) {
                                            for (String propName : context.keySet()) {
                                                if (propName.startsWith(CHILD_PROPERTY_PREFIX)) {
                                                    command.add(String.format("-D%s=%s",
                                                            propName.substring(CHILD_PROPERTY_PREFIX.length()),
                                                            task.getContextValue(propName)));
                                                }
                                            }
                                        }

                                        command.add(String.format("-Ddruid.host=%s", childHost));
                                        command.add(String.format("-Ddruid.port=%d", childPort));

                                        command.add("io.druid.cli.Main");
                                        command.add("internal");
                                        command.add("peon");
                                        command.add(taskFile.toString());
                                        command.add(statusFile.toString());
                                        String nodeType = task.getNodeType();
                                        if (nodeType != null) {
                                            command.add("--nodeType");
                                            command.add(nodeType);
                                        }

                                        jsonMapper.writeValue(taskFile, task);

                                        log.info("Running command: %s", Joiner.on(" ").join(command));
                                        taskWorkItem.processHolder = new ProcessHolder(
                                                new ProcessBuilder(ImmutableList.copyOf(command))
                                                        .redirectErrorStream(true).start(),
                                                logFile, childPort);

                                        processHolder = taskWorkItem.processHolder;
                                        processHolder.registerWithCloser(closer);
                                    }

                                    log.info("Logging task %s output to: %s", task.getId(), logFile);
                                    boolean runFailed = true;

                                    try (final OutputStream toLogfile = Files.asByteSink(logFile)
                                            .openBufferedStream()) {
                                        ByteStreams.copy(processHolder.process.getInputStream(), toLogfile);
                                        final int statusCode = processHolder.process.waitFor();
                                        log.info("Process exited with status[%d] for task: %s", statusCode,
                                                task.getId());
                                        if (statusCode == 0) {
                                            runFailed = false;
                                        }
                                    } finally {
                                        // Upload task logs
                                        taskLogPusher.pushTaskLog(task.getId(), logFile);
                                    }

                                    if (!runFailed) {
                                        // Process exited successfully
                                        return jsonMapper.readValue(statusFile, TaskStatus.class);
                                    } else {
                                        // Process exited unsuccessfully
                                        return TaskStatus.failure(task.getId());
                                    }
                                } catch (Throwable t) {
                                    throw closer.rethrow(t);
                                } finally {
                                    closer.close();
                                }
                            } catch (Throwable t) {
                                log.info(t, "Exception caught during execution");
                                throw Throwables.propagate(t);
                            } finally {
                                try {
                                    synchronized (tasks) {
                                        final ForkingTaskRunnerWorkItem taskWorkItem = tasks
                                                .remove(task.getId());
                                        if (taskWorkItem != null && taskWorkItem.processHolder != null) {
                                            taskWorkItem.processHolder.process.destroy();
                                        }
                                    }
                                    portFinder.markPortUnused(childPort);
                                    log.info("Removing temporary directory: %s", attemptDir);
                                    FileUtils.deleteDirectory(attemptDir);
                                } catch (Exception e) {
                                    log.error(e, "Suppressing exception caught while cleaning up task");
                                }
                            }
                        }
                    })));
        }

        return tasks.get(task.getId()).getResult();
    }
}

From source file:com.netspective.sparx.template.freemarker.FreeMarkerConfigurationAdapters.java

public void applyWebAppConfiguration(Configuration fmConfig, ServletContext servletContext) {
    String templatePathsText = servletContext
            .getInitParameter("com.netspective.sparx.template.freemarker.template-paths");
    String templatePathsDelim = servletContext
            .getInitParameter("com.netspective.sparx.template.freemarker.template-path-delim");

    List templateLoaders = new ArrayList();
    templateLoaders.add(stringTemplateLoader);
    templateLoaders.add(new WebappTemplateLoader(servletContext));

    try {//  w  w w  . ja  v  a  2  s  .com
        if (templatePathsText != null) {
            String[] templatePaths = TextUtils.getInstance().split(templatePathsText,
                    templatePathsDelim == null ? File.pathSeparator : templatePathsDelim, true);
            for (int i = 0; i < templatePaths.length; i++)
                templateLoaders
                        .add(new FileTemplateLoader(new File(servletContext.getRealPath(templatePaths[i]))));
        }
    } catch (Exception e) {
        log.error("Unable to setup file templates loader.", e);
        throw new NestableRuntimeException(e);
    }

    // allow stuff to be loaded from CLASSPATH too (like Console, etc)
    templateLoaders.add(new ClassTemplateLoader(com.netspective.sparx.ProductRelease.class));
    templateLoaders.add(new ClassTemplateLoader(com.netspective.axiom.ProductRelease.class));
    templateLoaders.add(new ClassTemplateLoader(com.netspective.commons.ProductRelease.class));

    fmConfig.setTemplateLoader(new MultiTemplateLoader(
            (TemplateLoader[]) templateLoaders.toArray(new TemplateLoader[templateLoaders.size()])));

    configureSharedVariables(fmConfig);
}

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

public synchronized List<String> getLibraryPaths() throws SQLException {
    String pathsValue = DatabaseUtils.stringForQuery(getConnection(), VALUE_QUERY,
            new String[] { Keys.LIBRARY_PATH });

    ArrayList<String> paths = new ArrayList<String>();

    if (pathsValue != null) {
        for (String path : pathsValue.split(File.pathSeparator))
            paths.add(path);//  w  w  w .  ja v a  2 s  .  c o m
    }

    return paths;
}