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:net.sourceforge.pmd.util.fxdesigner.MainDesignerController.java

@PersistentProperty
public String getRecentFiles() {
    return recentFiles.stream().map(File::getAbsolutePath).collect(Collectors.joining(File.pathSeparator));
}

From source file:org.lib4j.xml.jaxb.XJCompiler.java

public static void compile(final Command command) throws JAXBException, MalformedURLException {
    if (command.getSchemas() == null || command.getSchemas().size() == 0)
        return;//  w w w.j a  va  2  s  . c  o m

    final List<String> args = new ArrayList<>();
    args.add("java");
    if (command.classpath.size() > 0) {
        args.add("-cp");
        final StringBuilder cp = new StringBuilder();
        for (final File classpathFile : command.classpath)
            cp.append(File.pathSeparator).append(classpathFile.getAbsolutePath());

        args.add(cp.substring(1));
    }

    args.add(XJCFacade.class.getName());
    args.add("-Xannotate");
    if (command.isAddGeneratedAnnotation())
        args.add("-mark-generated");

    if (command.getCatalog() != null) {
        args.add(1, "-Dxml.catalog.ignoreMissing");
        args.add("-catalog");
        args.add(command.getCatalog().toURI().toURL().toExternalForm());
    }

    if (command.isEnableIntrospection())
        args.add("-enableIntrospection");

    if (command.isExtension())
        args.add("-extension");

    if (command.isLaxSchemaValidation())
        args.add("-nv");

    if (command.isNoGeneratedHeaderComments())
        args.add("-no-header");

    if (command.isNoPackageLevelAnnotations())
        args.add("-npa");

    if (command.isQuiet())
        args.add("-quiet");

    if (command.getTargetVersion() != null) {
        args.add("-target");
        args.add(command.getTargetVersion().version);
    }

    if (command.isVerbose())
        args.add("-verbose");

    if (command.getSourceType() != null)
        args.add("-" + command.getSourceType().type);

    if (command.getEncoding() != null) {
        args.add("-encoding");
        args.add(command.getEncoding());
    }

    if (command.getPackageName() != null) {
        args.add("-p");
        args.add(command.getPackageName());
    }

    try {
        if (command.getDestDir() != null) {
            args.add("-d");
            args.add(command.getDestDir().getAbsolutePath());

            if (!command.getDestDir().exists() && !command.getDestDir().mkdirs()) {
                throw new JAXBException(
                        "Unable to create output directory " + command.getDestDir().getAbsolutePath());
            }
            // FIXME: This does not work because the files that are written are only known by xjc, so I cannot
            // FIXME: stop this generator from overwriting them if owerwrite=false
            //        else if (command.isOverwrite()) {
            //          for (final File file : command.getDestDir().listFiles())
            //            Files.walk(file.toPath()).map(Path::toFile).filter(a -> a.getName().endsWith(".java")).sorted((o1, o2) -> o2.compareTo(o1)).forEach(File::delete);
            //        }
        }

        for (final URL schema : command.getSchemas()) {
            if (URLs.isFile(schema)) {
                final File file = new File(schema.getFile());
                if (!file.exists())
                    throw new FileNotFoundException(file.getAbsolutePath());

                args.add(file.getAbsolutePath());
            } else {
                try (final InputStream in = schema.openStream()) {
                    final File file = File.createTempFile(URLs.getName(schema), "");
                    args.add(file.getAbsolutePath());
                    file.deleteOnExit();
                    Files.write(file.toPath(), Streams.readBytes(in));
                }
            }

            args.add(schema.getFile());
        }

        if (command.getXJBs() != null) {
            for (final URL xjb : command.getXJBs()) {
                args.add("-b");
                if (URLs.isFile(xjb)) {
                    args.add(xjb.getFile());
                } else {
                    try (final InputStream in = xjb.openStream()) {
                        final File file = File.createTempFile(URLs.getName(xjb), "");
                        args.add(file.getAbsolutePath());
                        file.deleteOnExit();
                        Files.write(file.toPath(), Streams.readBytes(in));
                    }
                }
            }
        }

        if (command.isGenerateEpisode()) {
            final File metaInfDir = new File(command.getDestDir(),
                    "META-INF" + File.separator + "sun-jaxb.episode");
            if (!metaInfDir.getParentFile().mkdirs())
                throw new JAXBException("Unable to create output directory META-INF"
                        + metaInfDir.getParentFile().getAbsolutePath());

            args.add("-episode");
            args.add(metaInfDir.getAbsolutePath());
        }

        final Process process = new ProcessBuilder(args).inheritIO().redirectErrorStream(true).start();
        try (final Scanner scanner = new Scanner(process.getInputStream())) {
            while (scanner.hasNextLine())
                log(scanner.nextLine().trim());

            final StringBuilder lastLine = new StringBuilder();
            while (scanner.hasNextByte())
                lastLine.append(scanner.nextByte());

            if (lastLine.length() > 0)
                log(lastLine.toString());
        }

        final int exitCode = process.waitFor();
        if (exitCode != 0)
            throw new JAXBException(
                    "xjc finished with code: " + exitCode + "\n" + Collections.toString(args, " "));
    } catch (final IOException | InterruptedException e) {
        throw new JAXBException(e.getMessage(), e);
    }
}

From source file:org.evosuite.junit.JUnitAnalyzer.java

private static List<File> compileTests(List<TestCase> tests, File dir) {

    TestSuiteWriter suite = new TestSuiteWriter();
    suite.insertAllTests(tests);//from w w w . java2s  .co m

    //to get name, remove all package before last '.'
    int beginIndex = Properties.TARGET_CLASS.lastIndexOf(".") + 1;
    String name = Properties.TARGET_CLASS.substring(beginIndex);
    name += "_" + (NUM++) + "_tmp_" + Properties.JUNIT_SUFFIX; //postfix

    try {
        //now generate the JUnit test case
        List<File> generated = suite.writeTestSuite(name, dir.getAbsolutePath(), Collections.EMPTY_LIST);
        for (File file : generated) {
            if (!file.exists()) {
                logger.error("Supposed to generate " + file + " but it does not exist");
                return null;
            }
        }

        //try to compile the test cases
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null) {
            logger.error("No Java compiler is available");
            return null;
        }

        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        Locale locale = Locale.getDefault();
        Charset charset = Charset.forName("UTF-8");
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, locale, charset);

        Iterable<? extends JavaFileObject> compilationUnits = fileManager
                .getJavaFileObjectsFromFiles(generated);

        List<String> optionList = new ArrayList<>();
        String evosuiteCP = ClassPathHandler.getInstance().getEvoSuiteClassPath();
        if (JarPathing.containsAPathingJar(evosuiteCP)) {
            evosuiteCP = JarPathing.expandPathingJars(evosuiteCP);
        }

        String targetProjectCP = ClassPathHandler.getInstance().getTargetProjectClasspath();
        if (JarPathing.containsAPathingJar(targetProjectCP)) {
            targetProjectCP = JarPathing.expandPathingJars(targetProjectCP);
        }

        String classpath = targetProjectCP + File.pathSeparator + evosuiteCP;

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

        CompilationTask task = compiler.getTask(null, fileManager, diagnostics, optionList, null,
                compilationUnits);
        boolean compiled = task.call();
        fileManager.close();

        if (!compiled) {
            logger.error("Compilation failed on compilation units: " + compilationUnits);
            logger.error("Classpath: " + classpath);
            //TODO remove
            logger.error("evosuiteCP: " + evosuiteCP);

            for (Diagnostic<?> diagnostic : diagnostics.getDiagnostics()) {
                if (diagnostic.getMessage(null).startsWith("error while writing")) {
                    logger.error("Error is due to file permissions, ignoring...");
                    return generated;
                }
                logger.error("Diagnostic: " + diagnostic.getMessage(null) + ": " + diagnostic.getLineNumber());
            }

            StringBuffer buffer = new StringBuffer();
            for (JavaFileObject sourceFile : compilationUnits) {
                List<String> lines = FileUtils.readLines(new File(sourceFile.toUri().getPath()));

                buffer.append(compilationUnits.iterator().next().toString() + "\n");

                for (int i = 0; i < lines.size(); i++) {
                    buffer.append((i + 1) + ": " + lines.get(i) + "\n");
                }
            }
            logger.error(buffer.toString());
            return null;
        }

        return generated;

    } catch (IOException e) {
        logger.error("" + e, e);
        return null;
    }
}

From source file:net.sourceforge.pmd.util.fxdesigner.MainDesignerController.java

public void setRecentFiles(String files) {
    Arrays.stream(files.split(File.pathSeparator)).map(File::new).forEach(recentFiles::push);
}

From source file:org.apache.pig.PigServer.java

private void addJarsFromProperties() throws ExecException {
    //add jars from properties to extraJars
    String jar_str = pigContext.getProperties().getProperty("pig.additional.jars");
    if (jar_str == null) {
        jar_str = "";
    }/*  ww w . ja  v a  2  s.com*/
    jar_str = jar_str.replaceAll(File.pathSeparator, ",");
    if (!jar_str.isEmpty()) {
        jar_str += ",";
    }

    String jar_str_comma = pigContext.getProperties().getProperty("pig.additional.jars.uris");
    if (jar_str_comma != null && !jar_str_comma.isEmpty()) {
        jar_str = jar_str + jar_str_comma;
    }

    if (jar_str != null && !jar_str.isEmpty()) {
        // Use File.pathSeparator (":" on Linux, ";" on Windows)
        // to correctly handle path aggregates as they are represented
        // on the Operating System.
        for (String jar : jar_str.split(",")) {
            try {
                registerJar(jar);
            } catch (IOException e) {
                int errCode = 4010;
                String msg = "Failed to register jar :" + jar + ". Caught exception.";
                throw new ExecException(msg, errCode, PigException.USER_ENVIRONMENT, e);
            }
        }
    }
}

From source file:com.googlecode.mycontainer.maven.plugin.ExecMojo.java

private static void addToClasspath(StringBuffer theClasspath, String toAdd) {
    if (theClasspath.length() > 0) {
        theClasspath.append(File.pathSeparator);
    }/*from w  w  w. ja  v a 2  s  .  c  om*/
    theClasspath.append(toAdd);
}

From source file:JavaFiles.AbstractWsToolClient.java

/** Read the contents of a file into a byte array.
 * /* w  ww .  j  a v a 2s  .  c o  m*/
 * @param file the file to read
 * @return the contents of the file in a byte array
 * @throws IOException if all contents not read
 */
public byte[] readFile(File file) throws IOException, FileNotFoundException {
    printDebugMessage("readFile", "Begin", 1);
    printDebugMessage("readFile", "file: " + file.getPath() + File.pathSeparator + file.getName(), 2);
    if (!file.exists()) {
        throw new FileNotFoundException(file.getName() + " does not exist");
    }
    InputStream is = new FileInputStream(file);
    byte[] bytes = readStream(is);
    is.close();
    printDebugMessage("readFile", "End", 1);
    return bytes;
}

From source file:interactivespaces.workbench.tasks.WorkbenchTaskContext.java

/**
 * Scan the project path.// w ww  .  java 2  s.co  m
 */
public void scanProjectPath() {
    if (!projectPathScanned) {
        ProjectManager projectManager = workbench.getProjectManager();
        List<String> projectPaths = workbenchConfig.getPropertyStringList(
                CONFIGURATION_INTERACTIVESPACES_WORKBENCH_PROJECT_PATH, File.pathSeparator);
        if (projectPaths != null) {
            for (String projectPath : projectPaths) {
                File projectPathBaseDir = fileSupport.newFile(projectPath);
                processProjectPathDirectory(projectPathBaseDir, projectManager);
            }
        }

        projectPathScanned = true;
    }
}

From source file:de.sitewaerts.cordova.documentviewer.DocumentViewerPlugin.java

private File getAccessibleFile(String fileArg) throws JSONException {
    if (fileArg.startsWith(ASSETS)) {
        String filePath = fileArg.substring(ASSETS.length());
        String fileName = filePath.substring(filePath.lastIndexOf(File.pathSeparator) + 1);

        //Log.d(TAG, "Handling assets file: fileArg: " + fileArg + ", filePath: " + filePath + ", fileName: " + fileName);

        try {//from   ww  w  . j  a v  a  2  s.  c  om
            File tmpFile = getSharedTempFile(fileName);
            InputStream in;
            try {
                in = this.cordova.getActivity().getAssets().open(filePath);
                if (in == null)
                    return null;
            } catch (IOException e) {
                // not found
                return null;
            }
            copyFile(in, tmpFile);
            tmpFile.deleteOnExit();
            return tmpFile;
        } catch (IOException e) {
            Log.e(TAG, "Failed to copy file: " + filePath, e);
            JSONException je = new JSONException(e.getMessage());
            je.initCause(e);
            throw je;
        }
    } else {
        File file = getFile(fileArg);
        if (!file.exists() || !file.isFile())
            return null;

        // detect private files, copy to accessible tmp dir if necessary
        // XXX does this condition cover all cases?
        if (file.getAbsolutePath().contains(cordova.getActivity().getFilesDir().getAbsolutePath())) {
            //                  XXX this is the "official" way to share private files with other apps: with a content:// URI. Unfortunately, MuPDF does not swallow the generated URI. :(
            //                  path = FileProvider.getUriForFile(cordova.getActivity(), "de.sitewaerts.cordova.fileprovider", file);
            //                  cordova.getActivity().grantUriPermission(packageId, path, Intent.FLAG_GRANT_READ_URI_PERMISSION|Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            //                  intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION|Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

            try {
                File tmpFile = getSharedTempFile(file.getName());
                copyFile(file, tmpFile);
                tmpFile.deleteOnExit();
                return tmpFile;
            } catch (IOException e) {
                Log.e(TAG, "Failed to copy file: " + file.getName(), e);
                JSONException je = new JSONException(e.getMessage());
                je.initCause(e);
                throw je;
            }
        }

        return file;
    }
}

From source file:org.apache.maven.cli.NoSyspropChangingMavenCli.java

private ClassRealm setupContainerRealm(CliRequest cliRequest) throws Exception {
    ClassRealm containerRealm = null;/* w w w .j av a 2 s  .c om*/

    String extClassPath = cliRequest.userProperties.getProperty(EXT_CLASS_PATH);
    if (extClassPath == null) {
        extClassPath = cliRequest.systemProperties.getProperty(EXT_CLASS_PATH);
    }

    if (StringUtils.isNotEmpty(extClassPath)) {
        String[] jars = StringUtils.split(extClassPath, File.pathSeparator);

        if (jars.length > 0) {
            ClassRealm coreRealm = cliRequest.classWorld.getClassRealm("plexus.core");
            if (coreRealm == null) {
                coreRealm = (ClassRealm) cliRequest.classWorld.getRealms().iterator().next();
            }

            ClassRealm extRealm = cliRequest.classWorld.newRealm("maven.ext", null);

            logger.debug("Populating class realm " + extRealm.getId());

            for (String jar : jars) {
                File file = resolveFile(new File(jar), cliRequest.workingDirectory);

                logger.debug("  Included " + file);

                extRealm.addURL(file.toURI().toURL());
            }

            extRealm.setParentRealm(coreRealm);

            containerRealm = extRealm;
        }
    }

    return containerRealm;
}