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.cloudera.sqoop.orm.CompilationManager.java

/**
 * Compile the .java files into .class files via embedded javac call.
 * On success, move .java files to the code output dir.
 *//*from  www.j  a v a2 s. c  o m*/
public void compile() throws IOException {
    List<String> args = new ArrayList<String>();

    // ensure that the jar output dir exists.
    String jarOutDir = options.getJarOutputDir();
    File jarOutDirObj = new File(jarOutDir);
    if (!jarOutDirObj.exists()) {
        boolean mkdirSuccess = jarOutDirObj.mkdirs();
        if (!mkdirSuccess) {
            LOG.debug("Warning: Could not make directories for " + jarOutDir);
        }
    } else if (LOG.isDebugEnabled()) {
        LOG.debug("Found existing " + jarOutDir);
    }

    // Make sure jarOutDir ends with a '/'.
    if (!jarOutDir.endsWith(File.separator)) {
        jarOutDir = jarOutDir + File.separator;
    }

    // find hadoop-*-core.jar for classpath.
    String coreJar = findHadoopCoreJar();
    if (null == coreJar) {
        // Couldn't find a core jar to insert into the CP for compilation.  If,
        // however, we're running this from a unit test, then the path to the
        // .class files might be set via the hadoop.alt.classpath property
        // instead. Check there first.
        String coreClassesPath = System.getProperty("hadoop.alt.classpath");
        if (null == coreClassesPath) {
            // no -- we're out of options. Fail.
            throw new IOException("Could not find hadoop core jar!");
        } else {
            coreJar = coreClassesPath;
        }
    }

    // find sqoop jar for compilation classpath
    String sqoopJar = Jars.getSqoopJarPath();
    if (null != sqoopJar) {
        sqoopJar = File.pathSeparator + sqoopJar;
    } else {
        LOG.warn("Could not find sqoop jar; child compilation may fail");
        sqoopJar = "";
    }

    String curClasspath = System.getProperty("java.class.path");

    args.add("-sourcepath");
    args.add(jarOutDir);

    args.add("-d");
    args.add(jarOutDir);

    args.add("-classpath");
    args.add(curClasspath + File.pathSeparator + coreJar + sqoopJar);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (null == compiler) {
        LOG.error("It seems as though you are running sqoop with a JRE.");
        LOG.error("Sqoop requires a JDK that can compile Java code.");
        LOG.error("Please install a JDK and set $JAVA_HOME to use it.");
        throw new IOException("Could not start Java compiler.");
    }
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    ArrayList<String> srcFileNames = new ArrayList<String>();
    for (String srcfile : sources) {
        srcFileNames.add(jarOutDir + srcfile);
        LOG.debug("Adding source file: " + jarOutDir + srcfile);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Invoking javac with args:");
        for (String arg : args) {
            LOG.debug("  " + arg);
        }
    }

    Iterable<? extends JavaFileObject> srcFileObjs = fileManager.getJavaFileObjectsFromStrings(srcFileNames);
    JavaCompiler.CompilationTask task = compiler.getTask(null, // Write to stderr
            fileManager, null, // No special diagnostic handling
            args, null, // Compile all classes in the source compilation units
            srcFileObjs);

    boolean result = task.call();
    if (!result) {
        throw new IOException("Error returned by javac");
    }

    // Where we should move source files after compilation.
    String srcOutDir = new File(options.getCodeOutputDir()).getAbsolutePath();
    if (!srcOutDir.endsWith(File.separator)) {
        srcOutDir = srcOutDir + File.separator;
    }

    // Move these files to the srcOutDir.
    for (String srcFileName : sources) {
        String orig = jarOutDir + srcFileName;
        String dest = srcOutDir + srcFileName;
        File fOrig = new File(orig);
        File fDest = new File(dest);
        File fDestParent = fDest.getParentFile();
        if (null != fDestParent && !fDestParent.exists()) {
            if (!fDestParent.mkdirs()) {
                LOG.error("Could not make directory: " + fDestParent);
            }
        }

        if (!fOrig.renameTo(fDest)) {
            LOG.error("Could not rename " + orig + " to " + dest);
        }
    }
}

From source file:org.apache.sqoop.orm.CompilationManager.java

/**
 * Compile the .java files into .class files via embedded javac call.
 * On success, move .java files to the code output dir.
 *///from  ww  w  .  jav a  2s.co m
public void compile() throws IOException {
    List<String> args = new ArrayList<String>();

    // ensure that the jar output dir exists.
    String jarOutDir = options.getJarOutputDir();
    File jarOutDirObj = new File(jarOutDir);
    if (!jarOutDirObj.exists()) {
        boolean mkdirSuccess = jarOutDirObj.mkdirs();
        if (!mkdirSuccess) {
            LOG.debug("Warning: Could not make directories for " + jarOutDir);
        }
    } else if (LOG.isDebugEnabled()) {
        LOG.debug("Found existing " + jarOutDir);
    }

    // Make sure jarOutDir ends with a '/'.
    if (!jarOutDir.endsWith(File.separator)) {
        jarOutDir = jarOutDir + File.separator;
    }

    // find hadoop-*-core.jar for classpath.
    String coreJar = findHadoopCoreJar();
    if (null == coreJar) {
        // Couldn't find a core jar to insert into the CP for compilation.  If,
        // however, we're running this from a unit test, then the path to the
        // .class files might be set via the hadoop.alt.classpath property
        // instead. Check there first.
        String coreClassesPath = System.getProperty("hadoop.alt.classpath");
        if (null == coreClassesPath) {
            // no -- we're out of options. Fail.
            throw new IOException("Could not find hadoop core jar!");
        } else {
            coreJar = coreClassesPath;
        }
    }

    // find sqoop jar for compilation classpath
    String sqoopJar = Jars.getSqoopJarPath();
    if (null != sqoopJar) {
        sqoopJar = File.pathSeparator + sqoopJar;
    } else {
        LOG.warn("Could not find sqoop jar; child compilation may fail");
        sqoopJar = "";
    }

    String curClasspath = System.getProperty("java.class.path");

    args.add("-sourcepath");
    args.add(jarOutDir);

    args.add("-d");
    args.add(jarOutDir);

    args.add("-classpath");
    args.add(curClasspath + File.pathSeparator + coreJar + sqoopJar);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (null == compiler) {
        LOG.error("It seems as though you are running sqoop with a JRE.");
        LOG.error("Sqoop requires a JDK that can compile Java code.");
        LOG.error("Please install a JDK and set $JAVA_HOME to use it.");
        throw new IOException("Could not start Java compiler.");
    }
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    ArrayList<String> srcFileNames = new ArrayList<String>();
    for (String srcfile : sources) {
        srcFileNames.add(jarOutDir + srcfile);
        LOG.debug("Adding source file: " + jarOutDir + srcfile);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Invoking javac with args:");
        for (String arg : args) {
            LOG.debug("  " + arg);
        }
    }

    Iterable<? extends JavaFileObject> srcFileObjs = fileManager.getJavaFileObjectsFromStrings(srcFileNames);
    JavaCompiler.CompilationTask task = compiler.getTask(null, // Write to stderr
            fileManager, null, // No special diagnostic handling
            args, null, // Compile all classes in the source compilation units
            srcFileObjs);

    boolean result = task.call();
    if (!result) {
        throw new IOException("Error returned by javac");
    }

    // Where we should move source files after compilation.
    String srcOutDir = new File(options.getCodeOutputDir()).getAbsolutePath();
    if (!srcOutDir.endsWith(File.separator)) {
        srcOutDir = srcOutDir + File.separator;
    }

    // Move these files to the srcOutDir.
    for (String srcFileName : sources) {
        String orig = jarOutDir + srcFileName;
        String dest = srcOutDir + srcFileName;
        File fOrig = new File(orig);
        File fDest = new File(dest);
        File fDestParent = fDest.getParentFile();
        if (null != fDestParent && !fDestParent.exists()) {
            if (!fDestParent.mkdirs()) {
                LOG.error("Could not make directory: " + fDestParent);
            }
        }
        try {
            FileUtils.moveFile(fOrig, fDest);
        } catch (IOException e) {
            LOG.debug("Could not rename " + orig + " to " + dest, e);
        }
    }
}

From source file:at.ac.tuwien.dsg.cloud.salsa.engine.utils.SystemFunctions.java

/**
 * Run a command and wait// w  w  w .java  2s.  c  o  m
 *
 * @param cmd The command to run
 * @param workingDir The folder where the command is run
 * @param executeFrom For logging message to the center of where to execute the command.
 * @return
 */
public static String executeCommandGetOutput(String cmd, String workingDir, String executeFrom) {
    logger.debug("Execute command: " + cmd);
    if (workingDir == null) {
        workingDir = "/tmp";
    }
    try {
        String[] splitStr = cmd.split("\\s+");
        ProcessBuilder pb = new ProcessBuilder(splitStr);
        pb.directory(new File(workingDir));
        pb = pb.redirectErrorStream(true); // this is important to redirect the error stream to output stream, prevent blocking with long output
        Map<String, String> env = pb.environment();
        String path = env.get("PATH");
        path = path + File.pathSeparator + "/usr/bin:/usr/sbin";
        logger.debug("PATH to execute command: " + pb.environment().get("PATH"));
        env.put("PATH", path);

        Process p = pb.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        StringBuffer output = new StringBuffer();
        int lineCount = 0;
        while ((line = reader.readLine()) != null) {
            if (lineCount < 10) { // only get 10 lines to prevent the overflow
                output.append(line);
            }
            lineCount += 1;
            logger.debug(line);
        }
        if (lineCount >= 10) {
            logger.debug("... there are alot of more output here which is not shown ! ...");
        }
        p.waitFor();
        System.out.println("Execute Commang output: " + output.toString().trim());

        if (p.exitValue() == 0) {
            logger.debug("Command exit 0, result: " + output.toString().trim());
            return output.toString().trim();
        } else {
            logger.debug("Command return non zero code: " + p.exitValue());
            return null;
        }
    } catch (InterruptedException | IOException e1) {
        logger.error("Error when execute command. Error: " + e1);
    }
    return null;
}

From source file:org.apache.cocoon.components.language.programming.java.JavaLanguage.java

public void initialize() throws Exception {

    // Initialize the classpath
    String systemBootClasspath = System.getProperty("sun.boot.class.path");
    String systemClasspath = SystemUtils.JAVA_CLASS_PATH;
    String systemExtDirs = SystemUtils.JAVA_EXT_DIRS;
    String systemExtClasspath = null;

    try {//from www .j  a v a 2 s . c om
        systemExtClasspath = expandDirs(systemExtDirs);
    } catch (Exception e) {
        getLogger().warn("Could not expand Directory:" + systemExtDirs, e);
    }

    this.classpath = ((super.classpath != null) ? File.pathSeparator + super.classpath : "")
            + ((systemBootClasspath != null) ? File.pathSeparator + systemBootClasspath : "")
            + ((systemClasspath != null) ? File.pathSeparator + systemClasspath : "")
            + ((systemExtClasspath != null) ? File.pathSeparator + systemExtClasspath : "");
}

From source file:org.jiemamy.eclipse.core.ui.composer.DbImporterWizardPage.java

public void createControl(final Composite parent) { // CHECKSTYLE IGNORE THIS LINE
    Label label;/*  w w  w.  j  av a 2  s .  co  m*/
    GridData gd;

    Composite composite = new Composite(parent, SWT.NULL);
    composite.setLayout(new GridLayout(3, false));
    composite.setLayoutData(new GridData(GridData.FILL_BOTH));

    label = new Label(composite, SWT.NONE);
    label.setText(Messages.DbImportWizardPage_label_dbType);

    cmbDialect = new Combo(composite, SWT.READ_ONLY);
    gd = new GridData(GridData.FILL_HORIZONTAL);
    gd.horizontalSpan = 2;
    cmbDialect.setLayoutData(gd);
    for (Dialect dialect : dialectResolver.getAllInstance()) {
        cmbDialect.add(dialect.getClass().getName());
    }
    cmbDialect.select(0);
    cmbDialect.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            String connectionUriTemplate = getDialect().getConnectionUriTemplate();
            txtUri.setText(StringUtils.defaultIfEmpty(connectionUriTemplate, txtUri.getText()));
        }
    });
    // THINK JiemamyContext???Dialect??
    //      cmbDialect.setText(context.getMetadata().getDialectClassName());
    cmbDialect.setText(StringUtils.defaultIfEmpty(settings.get("cmbDialect"), ""));

    label = new Label(composite, SWT.NONE);
    label.setText("JDBC?jar(&J)"); // RESOURCE

    lstDriverJars = new org.eclipse.swt.widgets.List(composite, SWT.BORDER | SWT.MULTI);
    lstDriverJars.setLayoutData(new GridData(GridData.FILL_BOTH));
    String pathsString = StringUtils.defaultIfEmpty(settings.get("lstDriverJars"), "");
    for (String path : pathsString.split(File.pathSeparator)) {
        if (new File(path).exists()) {
            lstDriverJars.add(path);
        }
    }

    Composite cmpButtons = new Composite(composite, SWT.NULL);
    cmpButtons.setLayout(new RowLayout(SWT.VERTICAL));
    createButtons(cmpButtons);

    label = new Label(composite, SWT.NONE);
    label.setText("JDBC?(&C)"); // RESOURCE

    cmbDriverClass = new Combo(composite, SWT.BORDER | SWT.READ_ONLY);
    gd = new GridData(GridData.FILL_HORIZONTAL);
    gd.horizontalSpan = 2;
    cmbDriverClass.setLayoutData(gd);
    if (lstDriverJars.getItemCount() > 0) {
        driverListChanged();
    }
    cmbDriverClass.setText(StringUtils.defaultIfEmpty(settings.get("cmbDriverClass"), ""));

    label = new Label(composite, SWT.NONE);
    label.setText("URI(&I)"); // RESOURCE

    txtUri = new Text(composite, SWT.BORDER);
    txtUri.addFocusListener(new TextSelectionAdapter(txtUri));
    gd = new GridData(GridData.FILL_HORIZONTAL);
    gd.horizontalSpan = 2;
    txtUri.setLayoutData(gd);
    txtUri.setText(StringUtils.defaultIfEmpty(settings.get("txtUri"), ""));

    label = new Label(composite, SWT.NONE);
    label.setText("??(&U)"); // RESOURCE

    txtUsername = new Text(composite, SWT.BORDER);
    txtUsername.addFocusListener(new TextSelectionAdapter(txtUsername));
    txtUsername.setText("sa");
    gd = new GridData(GridData.FILL_HORIZONTAL);
    gd.horizontalSpan = 2;
    txtUsername.setLayoutData(gd);
    txtUsername.setText(StringUtils.defaultIfEmpty(settings.get("txtUsername"), ""));

    label = new Label(composite, SWT.NONE);
    label.setText("(&P)"); // RESOURCE

    txtPassword = new Text(composite, SWT.BORDER | SWT.PASSWORD);
    txtPassword.addFocusListener(new TextSelectionAdapter(txtPassword));
    gd = new GridData(GridData.FILL_HORIZONTAL);
    gd.horizontalSpan = 2;
    txtPassword.setLayoutData(gd);
    txtPassword.setText(StringUtils.defaultIfEmpty(settings.get("txtPassword"), ""));

    label = new Label(composite, SWT.NONE);
    label.setText("??(&S)"); // RESOURCE

    txtSchema = new Text(composite, SWT.BORDER);
    txtSchema.addFocusListener(new TextSelectionAdapter(txtSchema));
    gd = new GridData(GridData.FILL_HORIZONTAL);
    gd.horizontalSpan = 2;
    txtSchema.setLayoutData(gd);
    txtSchema.setText(StringUtils.defaultIfEmpty(settings.get("txtSchema"), ""));

    @SuppressWarnings("unused")
    Object unused = new Label(composite, SWT.NONE);

    btnImportDataSet = new Button(composite, SWT.CHECK);
    btnImportDataSet.setText("DataSet??"); // RESOURCE
    gd = new GridData(GridData.FILL_HORIZONTAL);
    gd.horizontalSpan = 2;
    btnImportDataSet.setLayoutData(gd);
    btnImportDataSet.setSelection(settings.getBoolean("btnImportDataSet"));

    createTestButton(composite);
    setControl(composite);
}

From source file:com.twosigma.beaker.groovy.evaluator.GroovyEvaluator.java

public void resetEnvironment() {
    executor.killAllThreads();/*from   ww  w .ja  v  a 2 s .  c  o m*/

    String cpp = "";
    for (String pt : classPath) {
        cpp += pt;
        cpp += File.pathSeparator;
    }
    cpp += File.pathSeparator;
    cpp += System.getProperty("java.class.path");
    cps = new GroovyClasspathScanner(cpp);
    gac = createGroovyAutocomplete(cps);

    for (String st : imports)
        gac.addImport(st);

    updateLoader = true;
    syncObject.release();
}

From source file:org.bimserver.tools.generators.ProtocolBuffersGenerator.java

private void generateProtocolBuffersObjects(File protoFile, File protoDestFile, boolean javaOut) {
    File destDir = new File("../GeneratedProtocolBuffersClient/generated");
    File protoDir = new File("../Builds/build/pb");

    File execFile = null;//from  w  w w.  j a v a2s.c o m
    String execFileName = "protoc";
    String path = System.getenv("PATH");
    String[] folders = path.split(File.pathSeparator);
    for (String folder : folders) {
        File file = new File(folder, execFileName);
        if (file.isFile()) {
            execFile = file;
            break;
        }
    }
    if (execFile == null) {
        execFile = new File("../Builds/build/pb/protoc.exe");
    }

    try {
        ProcessBuilder processBuilder = null;
        if (javaOut) {
            processBuilder = new ProcessBuilder(execFile.getAbsolutePath(), "-I=" + protoDir.getAbsolutePath(),
                    "--java_out=" + destDir.getAbsolutePath(),
                    "--descriptor_set_out=" + protoDestFile.getAbsolutePath(), protoFile.getAbsolutePath());
        } else {
            processBuilder = new ProcessBuilder(execFile.getAbsolutePath(), "-I=" + protoDir.getAbsolutePath(),
                    "--descriptor_set_out=" + protoDestFile.getAbsolutePath(), protoFile.getAbsolutePath());
        }
        final Process exec = processBuilder.start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                InputStream inputStream = exec.getInputStream();
                byte[] buffer = new byte[1024];
                int red;
                try {
                    red = inputStream.read(buffer);
                    while (red != -1) {
                        System.out.print(new String(buffer, 0, red));
                        red = inputStream.read(buffer);
                    }
                } catch (IOException e) {
                    LOGGER.error("", e);
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                InputStream inputStream = exec.getErrorStream();
                byte[] buffer = new byte[1024];
                int red;
                try {
                    red = inputStream.read(buffer);
                    while (red != -1) {
                        System.err.print(new String(buffer, 0, red));
                        red = inputStream.read(buffer);
                    }
                } catch (IOException e) {
                    LOGGER.error("", e);
                }
            }
        }).start();
        exec.waitFor();
    } catch (IOException e) {
        LOGGER.error("", e);
    } catch (InterruptedException e) {
        LOGGER.error("", e);
    }
}

From source file:org.apache.catalina.util.ExtensionValidator.java

/**
 *  Access to this class can only be made through the factory method
 *  getInstance()/*from   ww  w .j  av  a2 s .c  om*/
 *
 *  This private constructor loads the container level extensions that are
 *  available to all web applications. This method scans all extension 
 *  directories available via the "java.ext.dirs" System property. 
 *
 *  The System Class-Path is also scanned for jar files that may contain 
 *  available extensions. The system extensions are loaded only the 
 *  first time an instance of the ExtensionValidator is created.
 */
private ExtensionValidator() throws IOException {

    // check for container level optional packages
    String systemClasspath = System.getProperty("java.class.path");

    StringTokenizer strTok = new StringTokenizer(systemClasspath, File.pathSeparator);

    // build a list of jar files in the classpath
    while (strTok.hasMoreTokens()) {
        String classpathItem = strTok.nextToken();
        if (classpathItem.toLowerCase().endsWith(".jar")) {
            File item = new File(classpathItem);
            if (item.exists()) {
                addSystemResource(item);
            }
        }
    }

    // get the files in the extensions directory
    String extensionsDir = System.getProperty("java.ext.dirs");
    if (extensionsDir != null) {
        StringTokenizer extensionsTok = new StringTokenizer(extensionsDir, File.pathSeparator);
        while (extensionsTok.hasMoreTokens()) {
            File targetDir = new File(extensionsTok.nextToken());
            if (!targetDir.exists() || !targetDir.isDirectory()) {
                continue;
            }
            File[] files = targetDir.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].getName().toLowerCase().endsWith(".jar")) {
                    addSystemResource(files[i]);
                }
            }
        }
    }
}

From source file:com.axelor.studio.service.ModuleRecorderService.java

private void setServerEnv() throws AxelorException {

    String path = ENV.get("PATH");
    if (path == null) {
        path = "";
    }/*from   www.  j a va 2s  .co  m*/

    if (SystemUtils.IS_OS_WINDOWS) {
        String winPath = ENV.get("Path");
        if (!path.contains(winPath)) {
            path += File.pathSeparator + winPath;
        }
    }

    for (String var : ENV_VARS) {
        path = setPath(path, var);
    }

    ENV.put("PATH", path);

}

From source file:org.bimserver.webservices.impl.AdminServiceImpl.java

@Override
public SJavaInfo getJavaInfo() {
    SJavaInfo javaInfo = new SJavaInfo();
    javaInfo.setHeapTotal(Runtime.getRuntime().totalMemory());
    javaInfo.setHeapUsed(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
    javaInfo.setHeapFree(Runtime.getRuntime().freeMemory());
    javaInfo.setHeapMax(Runtime.getRuntime().maxMemory());
    javaInfo.setThreads(Thread.activeCount());
    javaInfo.setJavaHome(System.getProperty("java.home"));
    javaInfo.setJavaVersion(System.getProperty("java.version"));
    javaInfo.setJavaVendor(System.getProperty("java.vendor"));
    javaInfo.setJavaVendorurl(System.getProperty("java.vendor.url"));
    javaInfo.setJavavmVersion(System.getProperty("java.vm.version"));
    javaInfo.setJavavmVendor(System.getProperty("java.vm.vendor"));
    javaInfo.setJavavmName(System.getProperty("java.vm.name"));
    javaInfo.setJavaspecVersion(System.getProperty("java.specification.version"));
    javaInfo.setJavaspecVendor(System.getProperty("java.specification.vendor"));
    javaInfo.setJavaspecName(System.getProperty("java.specification.name"));
    javaInfo.setJavaClassVersion(System.getProperty("java.class.version"));

    for (String classp : System.getProperty("java.class.path").split(File.pathSeparator)) {
        javaInfo.getJavaClasspath().add(classp);
    }//from   w ww  .j a  v a  2  s .  c  om
    for (String classp : System.getProperty("java.library.path").split(File.pathSeparator)) {
        javaInfo.getJavaLibrarypath().add(classp);
    }
    javaInfo.setJavaIoTmp(System.getProperty("java.io.tmpdir"));
    javaInfo.setJavaExtdir(System.getProperty("java.ext.dirs"));
    javaInfo.setJavaFileSeparator(System.getProperty("file.separator"));
    javaInfo.setJavaPathSeparator(System.getProperty("path.separator"));
    javaInfo.setJavaLineSeparator(System.getProperty("line.separator"));

    return javaInfo;
}