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:jetbrains.exodus.util.ForkSupportIO.java

protected ForkSupportIO(@NotNull final String name, @NotNull String[] jvmArgs, @NotNull String[] args)
        throws IOException {
    try {/*from ww  w .j a  va2s.com*/
        serverSocket = new ServerSocket(0, 10);
        log.info("Listening on port: " + serverSocket.getLocalPort());
    } catch (IOException e) {
        log.fatal("Failed to open server socket.", e);
        throw e;
    }
    this.name = name;

    // static does not suite here since System.getProperty result can vary
    final String javaHome = System.getProperty("java.home");
    if (javaHome == null || javaHome.length() == 0) {
        throw new IllegalStateException("java.home is undefined");
    }
    final File bin = new File(javaHome, "bin");
    File javaFile = new File(bin, "java");
    if (!(javaFile.exists() && javaFile.isFile())) {
        javaFile = new File(bin, "java.exe");
        if (!(javaFile.exists() && javaFile.isFile())) {
            throw new IllegalStateException(javaFile.getPath() + " doesn't exist");
        }
    }

    final String classpath = join(getClasspath(getClass()), File.pathSeparator);
    final String[] commonJvmArgs = { javaFile.getPath(),
            // "-Xdebug", "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=7777",
            "-cp", classpath };

    final List<String> trueArgs = new ArrayList<>();
    trueArgs.addAll(Arrays.asList(commonJvmArgs));
    trueArgs.addAll(Arrays.asList(jvmArgs));
    trueArgs.add(ForkedProcessRunner.class.getName());
    trueArgs.add(Integer.toString(serverSocket.getLocalPort()));
    trueArgs.add(name);
    trueArgs.addAll(Arrays.asList(args));

    log.info("Ready to start process with arguments: " + trueArgs);
    builder = new ProcessBuilder(trueArgs);
}

From source file:com.wabacus.util.WabacusClassLoader.java

public void addClassPath(String strClassPath) {
    if (classRepository == null)
        classRepository = new ArrayList<String>();
    if ((strClassPath != null) && !(strClassPath.equals(""))) {
        StringTokenizer tokenizer = new StringTokenizer(strClassPath, File.pathSeparator);
        while (tokenizer.hasMoreTokens()) {
            classRepository.add(tokenizer.nextToken());
        }/*from  w ww .  ja v  a  2 s. co  m*/
    }
}

From source file:org.evosuite.executionmode.MeasureCoverage.java

private static void measureCoverage(String targetClass, List<String> args) {

    String classPath = ClassPathHandler.getInstance().getEvoSuiteClassPath();
    String projectCP = ClassPathHandler.getInstance().getTargetProjectClasspath();

    classPath += !classPath.isEmpty() ? File.pathSeparator + projectCP : projectCP;

    ExternalProcessHandler handler = new ExternalProcessHandler();
    int port = handler.openServer();
    List<String> cmdLine = new ArrayList<String>();
    cmdLine.add(EvoSuite.JAVA_CMD);/*from  w  ww.  j  a  v  a  2  s.  com*/
    cmdLine.add("-cp");
    cmdLine.add(classPath);
    cmdLine.add("-Dprocess_communication_port=" + port);
    if (Properties.HEADLESS_MODE) {
        cmdLine.add("-Djava.awt.headless=true");
    }
    cmdLine.add("-Dlogback.configurationFile=" + LoggingUtils.getLogbackFileName());
    cmdLine.add("-Djava.library.path=lib");
    cmdLine.add(projectCP.isEmpty() ? "-DCP=" + classPath : "-DCP=" + projectCP);

    for (String arg : args) {
        if (!arg.startsWith("-DCP=")) {
            cmdLine.add(arg);
        }
    }

    cmdLine.add("-DTARGET_CLASS=" + targetClass);
    cmdLine.add("-Djunit=" + Properties.JUNIT);
    if (Properties.PROJECT_PREFIX != null) {
        cmdLine.add("-DPROJECT_PREFIX=" + Properties.PROJECT_PREFIX);
    }

    cmdLine.add("-Dclassloader=true");
    cmdLine.add(ClientProcess.class.getName());

    /*
     * TODO: here we start the client with several properties that are set through -D. These properties are not visible to the master process (ie
     * this process), when we access the Properties file. At the moment, we only need few parameters, so we can hack them
     */
    Properties.getInstance();// should force the load, just to be sure
    Properties.TARGET_CLASS = targetClass;
    Properties.PROCESS_COMMUNICATION_PORT = port;

    LoggingUtils logUtils = new LoggingUtils();

    if (!Properties.CLIENT_ON_THREAD) {
        /*
         * We want to completely mute the SUT. So, we block all outputs from client, and use a remote logging
         */
        boolean logServerStarted = logUtils.startLogServer();
        if (!logServerStarted) {
            logger.error("Cannot start the log server");
            return;
        }
        int logPort = logUtils.getLogServerPort(); //
        cmdLine.add(1, "-Dmaster_log_port=" + logPort);
        cmdLine.add(1, "-Devosuite.log.appender=CLIENT");
    }

    String[] newArgs = cmdLine.toArray(new String[cmdLine.size()]);
    for (String entry : ClassPathHandler.getInstance().getClassPathElementsForTargetProject()) {
        try {
            ClassPathHacker.addFile(entry);
        } catch (IOException e) {
            LoggingUtils.getEvoLogger().info("* Error while adding classpath entry: " + entry);
        }
    }

    handler.setBaseDir(EvoSuite.base_dir_path);
    if (handler.startProcess(newArgs)) {
        Set<ClientNodeRemote> clients = null;
        try {
            clients = MasterServices.getInstance().getMasterNode().getClientsOnceAllConnected(10000);
        } catch (InterruptedException e) {
        }
        if (clients == null) {
            logger.error("Not possible to access to clients");
        } else {
            /*
             * The clients have started, and connected back to Master.
             * So now we just need to tell them to start a search
             */
            for (ClientNodeRemote client : clients) {
                try {
                    client.doCoverageAnalysis();
                } catch (RemoteException e) {
                    logger.error("Error in starting clients", e);
                }
            }
            int time = TimeController.getInstance().calculateForHowLongClientWillRunInSeconds();
            handler.waitForResult(time * 1000);
        }
        // timeout plus
        // 100 seconds?
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
        }
        if (Properties.NEW_STATISTICS) {
            if (MasterServices.getInstance().getMasterNode() == null) {
                logger.error("Cannot write results as RMI master node is not running");
            } else {
                LoggingUtils.getEvoLogger().info("* Writing statistics");

                SearchStatistics.getInstance().writeStatisticsForAnalysis();
            }
        }
        handler.killProcess();

    } else {
        LoggingUtils.getEvoLogger().info("* Could not connect to client process");
    }

    handler.closeServer();

    if (!Properties.CLIENT_ON_THREAD) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
        }
        logUtils.closeLogServer();
    }

}

From source file:gool.parser.java.JavaParser.java

/**
 * Parsing concrete Java into abstract GOOL is done in three steps. - We
 * call Sun's java parser to produce abstract Java; - We visit abstract Java
 * with the JavaRecognizer to produce abstract GOOL; - We annotate the
 * abstract GOOL so that it carries the Target language.
 * /*from  ww  w.j  a  v  a 2 s .  c o  m*/
 * @param defaultPlatform
 *            : specifies the Target language of the code generation that
 *            will later be applied to the abstract GOOL, once this Java
 *            parsing is performed.
 * @param compilationUnits
 *            : An Iterable of JavaFileObject, which are Sun's java parser's
 *            representation of the files to be parsed.
 * @param dependencies
 *            : specifies imported libraries
 * @param visitor
 *            : this is the class that transforms Sun's abstract java, into
 *            abstract GOOL, i.e. the JavaRecognizer.
 * @return a list of classdefs, i.e. of abstract GOOL classes.
 * @throws Exception
 */

public static Collection<ClassDef> parseGool(Platform defaultPlatform,
        Iterable<? extends JavaFileObject> compilationUnits, List<File> dependencies, JavaRecognizer visitor)
        throws Exception {
    if (visitor == null) {
        throw new IllegalArgumentException("The gool visitor is null.");
    }

    /**
     * concreteJavaToConcretePlatform We will now setup the options to Sun's
     * java compiler This requires working out the dependencies
     */
    // convert dependencies into a list of file paths to reach them
    List<String> stringDependencies = new ArrayList<String>();
    if (dependencies != null && !dependencies.isEmpty()) {
        for (File file : dependencies) {
            stringDependencies.add(file.getAbsolutePath());
        }
    }
    // further, add the GOOL library as a dependency
    // so that the program can use gool.imports.java
    stringDependencies.add(Settings.get("gool_library").toString());

    // with the dependencies all set, we can make up the options
    List<String> options = Arrays.asList("-classpath",
            StringUtils.join(stringDependencies, File.pathSeparator));

    /**
     * We now parse using Sun's java compiler
     */
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    JavacTask task = (JavacTask) compiler.getTask(null, null, null, options, null, compilationUnits);
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    visitor.setTypes(task.getTypes());
    /**
     * We now analyze using Sun's java compiler so as to get a Java abstract
     * type tree.
     */
    task.analyze();
    Trees typetrees = Trees.instance(task);

    /**
     * We now prepare the JavaRecognizer for conversion of abstract Java to
     * abstract GOOL.
     */

    // The visitor needs to know what the Target language is
    // Because it will annotate the abstract GOOL with this information.
    visitor.setDefaultPlatform(defaultPlatform);
    GoolGeneratorController.setCodeGenerator(defaultPlatform.getCodePrinter().getCodeGenerator());

    // The visitor might need Sun's analyzed Java abstract type tree.
    visitor.setTrees(typetrees);

    /**
     * We launch the JavaRecognizer against each abstract Java AST
     */
    for (CompilationUnitTree ast : asts) {
        visitor.setCurrentCompilationUnit(ast);
        visitor.scan();
    }

    /**
     * Register each abstract GOOL class, so that they can see each other
     * and therefore represent valid types
     */
    for (ClassDef classDef : visitor.getGoolClasses()) {
        classDef.getPlatform().registerCustomDependency(classDef.toString(), classDef);
    }

    return visitor.getGoolClasses();
}

From source file:edu.psu.cse.siis.coal.CommandLineParser.java

/**
 * Parses the command line options. This method parses default options that are common to all
 * analyses and it also causes analysis-specific options to be processed.
 * /*from www  .  ja  v a2  s  .  com*/
 * @param args The command line arguments.
 * @param clazz The class type of the {@link CommandLineArguments} that should be returned.
 * @return The parsed command line arguments.
 */
public A parseCommandLine(String[] args, Class<A> clazz) {
    Options options = new Options();

    parseDefaultCommandLineArguments(options);
    parseAnalysisSpecificArguments(options);

    CommandLine commandLine = null;
    try {
        org.apache.commons.cli.CommandLineParser commandLineParser = new DefaultParser();
        commandLine = commandLineParser.parse(options, args);
    } catch (ParseException e) {
        printHelp(options);
        logger.error("Could not parse command line arguments", e);
        return null;
    }

    A commandLineArguments = null;
    try {
        commandLineArguments = clazz.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        logger.error("Could not instantiate type " + clazz, e);
        return null;
    }
    commandLineArguments.setCommandLine(commandLine);
    commandLineArguments.setModel(commandLine.getOptionValue("model"));
    commandLineArguments.setCompiledModel(commandLine.getOptionValue("cmodel"));
    commandLineArguments.setInput(commandLine.getOptionValue("in"));
    commandLineArguments.setClasspath(commandLine.getOptionValue("cp") + File.pathSeparator
            + commandLineArguments.getInput() + File.pathSeparator);
    commandLineArguments.setOutput(commandLine.getOptionValue("out"));
    commandLineArguments.setTraverseModeled(commandLine.hasOption("traversemodeled"));
    AnalysisParameters.v().setInferNonModeledTypes(!commandLine.hasOption("modeledtypesonly"));

    int threadCount;
    try {
        threadCount = commandLineArguments.hasOption("threadcount")
                ? ((Number) commandLineArguments.getParsedOptionValue("threadcount")).intValue()
                : Runtime.getRuntime().availableProcessors();
    } catch (ParseException exception) {
        logger.error("Could not parse thread count: " + commandLineArguments.getOptionValue("threadcount"),
                exception);
        return null;
    }
    AnalysisParameters.v().setThreadCount(threadCount);

    return commandLineArguments;
}

From source file:org.gradle.test.fixtures.file.TestNameTestDirectoryProvider.java

private void init(String methodName, String className) {
    if (methodName == null) {
        // must be a @ClassRule; use the rule's class name instead
        methodName = getClass().getSimpleName();
    }//from  www . j a v  a2s .  co m
    if (prefix == null) {
        String safeMethodName = methodName.replaceAll("\\s", "_").replace(File.pathSeparator, "_").replace(":",
                "_");
        if (safeMethodName.length() > 64) {
            safeMethodName = safeMethodName.substring(0, 32) + "..."
                    + safeMethodName.substring(safeMethodName.length() - 32);
        }
        prefix = String.format("%s/%s", className, safeMethodName);
    }
}

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

/**
 * Construct the classpath of ngrinder which is very important and located in the head of
 * classpath./*from w  w  w .j a  v a 2 s.c o m*/
 *
 * @param classPath classpath string
 * @param logger    logger
 * @return classpath optimized for grinder.
 */
public String filterForeMostClassPath(String classPath, Logger logger) {
    List<String> classPathList = new ArrayList<String>();
    for (String eachClassPath : checkNotNull(classPath).split(File.pathSeparator)) {
        String filename = FilenameUtils.getName(eachClassPath);
        if (isForemostJar(filename) || isUsefulForForemostReferenceProject(eachClassPath)) {
            logger.trace("classpath :" + eachClassPath);
            classPathList.add(eachClassPath);
        }
    }
    return StringUtils.join(classPathList, File.pathSeparator);
}

From source file:org.gradle.util.GUtil.java

public static String asPath(Iterable<?> collection) {
    return CollectionUtils.join(File.pathSeparator, collection);
}

From source file:org.codehaus.mojo.cobertura.tasks.AbstractTask.java

/**
 * Using the <code>${project.compileClasspathElements}</code> and the <code>${plugin.artifacts}</code>, create
 * a classpath string that is suitable to be used from a forked cobertura process.
 *
 * @return the classpath string// w ww .j a va2 s. co m
 * @throws MojoExecutionException if the pluginArtifacts cannot be properly resolved to a full system path.
 */
public String createClasspath() throws MojoExecutionException {

    StringBuffer cpBuffer = new StringBuffer();

    for (Iterator it = pluginClasspathList.iterator(); it.hasNext();) {
        Artifact artifact = (Artifact) it.next();

        try {
            cpBuffer.append(File.pathSeparator).append(artifact.getFile().getCanonicalPath());
        } catch (IOException e) {
            throw new MojoExecutionException(
                    "Error while creating the canonical path for '" + artifact.getFile() + "'.", e);
        }
    }

    return cpBuffer.toString();
}

From source file:org.kantega.dogmaticmvc.java.JavaScriptCompiler.java

@Override
public Class compile(HttpServletRequest request) {

    String className = request.getServletPath().substring(1).replace('/', '.');

    List<JavaFileObject> compilationUnits = new ArrayList<JavaFileObject>();
    for (String path : (Set<String>) servletContext.getResourcePaths("/WEB-INF/dogmatic/")) {
        if (path.endsWith("java")) {
            try {
                String classNAme = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("."));
                compilationUnits.add(new JavaSourceFromURL(classNAme, servletContext.getResource(path)));
            } catch (MalformedURLException e) {
                throw new RuntimeException(e);
            }//from   ww w  .j  av a 2 s.  c  om
        }
    }
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    InMemoryJavaFileManager fileManager = new InMemoryJavaFileManager(
            compiler.getStandardFileManager(null, null, null),
            new ClassLoaderImpl(getClass().getClassLoader()));

    String cp = "";
    for (ClassLoader cl : Arrays.asList(getClass().getClassLoader(), getClass().getClassLoader().getParent())) {
        if (cl instanceof URLClassLoader) {
            URLClassLoader ucl = (URLClassLoader) cl;

            for (URL url : ucl.getURLs()) {
                if (cp.length() > 0) {
                    cp += File.pathSeparator;
                }
                cp += url.getFile();
            }
        }
    }
    List<String> options = new ArrayList(Arrays.asList("-classpath", cp));

    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null,
            compilationUnits);

    boolean success = task.call();
    StringWriter sw = new StringWriter();
    PrintWriter w = new PrintWriter(sw);

    for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
        w.println(diagnostic.getCode());
        w.println(diagnostic.getKind());
        w.println(diagnostic.getPosition());
        w.println(diagnostic.getStartPosition());
        w.println(diagnostic.getEndPosition());
        w.println(diagnostic.getSource());
        w.println(diagnostic.getMessage(null));

    }
    System.out.println("Success: " + success);

    if (success) {
        try {
            return fileManager.getClassLoader(null).loadClass(className);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    } else {
        throw new RuntimeException("Compilation failed: " + sw);
    }
}