Example usage for java.lang ProcessBuilder environment

List of usage examples for java.lang ProcessBuilder environment

Introduction

In this page you can find the example usage for java.lang ProcessBuilder environment.

Prototype

Map environment

To view the source code for java.lang ProcessBuilder environment.

Click Source Link

Usage

From source file:com.codesourcery.internal.installer.InstallManager.java

@Override
public void launch(LaunchItem item) throws CoreException {
    IPath installLocation = getInstallDescription().getRootLocation();

    try {//from   w  w w.j  a  v  a  2  s. com
        String program;
        // Executable item
        if (item.getType() == LaunchItemType.EXECUTABLE) {
            IPath toRun = installLocation.append(item.getPath());
            if (!toRun.toFile().exists())
                Installer.fail(InstallMessages.Error_FileNotFound + toRun.toOSString());

            // Add paths to environment and launch.
            ProcessBuilder pb = new ProcessBuilder();
            String[] paths = installDescription.getEnvironmentPaths();

            if (paths != null) {
                Map<String, String> env = pb.environment();
                String pathKey = "PATH";
                String pathVar = env.get(pathKey);

                if (pathVar == null) {
                    pathVar = "";
                }

                for (String path : paths) {
                    IPath resolvedPath = installDescription.getRootLocation().append(path);
                    pathVar = resolvedPath.toString() + File.pathSeparatorChar + pathVar;
                }
                env.put(pathKey, pathVar);
            }

            program = toRun.toOSString();
            pb.command(program);
            pb.start();
        }
        // File item
        else if (item.getType() == LaunchItemType.FILE) {
            IPath toRun = installLocation.append(item.getPath());
            if (!toRun.toFile().exists())
                Installer.fail(InstallMessages.Error_FileNotFound + toRun.toOSString());

            program = "file://" + toRun.toOSString();
            Program.launch(program);
        }
        // HTML item
        else if (item.getType() == LaunchItemType.HTML) {
            program = item.getPath();
            Program.launch(program);
        } else {
            throw new NullPointerException(InstallMessages.Error_NoLaunchItemType);
        }
    } catch (Exception e) {
        Installer.fail(NLS.bind(InstallMessages.Error_LaunchFailed0, item.getPath()), e);
    }
    // SWT Program.launch() can throw an UnsatisfiedLinkError if it is
    // unable to launch the file.
    catch (UnsatisfiedLinkError e) {
        Installer.fail(NLS.bind(InstallMessages.Error_LaunchFailed0, item.getPath()), e);
    }
}

From source file:org.springframework.yarn.test.Shell.java

/** Run a command */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;//from   w ww . j  av  a  2  s.c  o  m
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }
    if (dir != null) {
        builder.directory(this.dir);
    }

    if (Shell.WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();
        }
    } else {
        process = builder.start();
    }

    if (timeOutInterval > 0) {
        timeOutTimer = new Timer("Shell command timeout");
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        // One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    final StringBuffer errMsg = new StringBuffer();

    // 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()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        try {
            // make sure that the error thread exits
            errThread.join();
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while reading the error stream", ie);
        }
        completed.set(true);
        // the timeout thread handling
        // taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if (timeOutTimer != null) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            inReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed.get()) {
            errThread.interrupt();
        }
        try {
            errReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = Time.now();
    }
}

From source file:org.apache.hadoop.util.Shell.java

/** Run a command */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;/*from   ww  w .j a  v  a 2 s. c  o  m*/
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }
    if (dir != null) {
        builder.directory(this.dir);
    }

    builder.redirectErrorStream(redirectErrorStream);

    if (Shell.WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();
        }
    } else {
        process = builder.start();
    }

    if (timeOutInterval > 0) {
        timeOutTimer = new Timer("Shell command timeout");
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        //One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    final StringBuffer errMsg = new StringBuffer();

    // 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()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        try {
            // make sure that the error thread exits
            errThread.join();
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while reading the error stream", ie);
        }
        completed.set(true);
        //the timeout thread handling
        //taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if (timeOutTimer != null) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            // JDK 7 tries to automatically drain the input streams for us
            // when the process exits, but since close is not synchronized,
            // it creates a race if we close the stream first and the same
            // fd is recycled.  the stream draining thread will attempt to
            // drain that fd!!  it may block, OOM, or cause bizarre behavior
            // see: https://bugs.openjdk.java.net/browse/JDK-8024521
            //      issue is fixed in build 7u60
            InputStream stdout = process.getInputStream();
            synchronized (stdout) {
                inReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        try {
            if (!completed.get()) {
                errThread.interrupt();
                errThread.join();
            }
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while joining errThread");
        }
        try {
            InputStream stderr = process.getErrorStream();
            synchronized (stderr) {
                errReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = Time.now();
    }
}

From source file:org.ow2.proactive.scheduler.ext.matlab.worker.MatlabConnectionRImpl.java

protected Process createMatlabProcess(String runArg) throws Exception {
    // Attempt to run MATLAB
    final ArrayList<String> commandList = new ArrayList<String>();
    commandList.add(this.matlabLocation);
    commandList.addAll(Arrays.asList(this.startUpOptions));
    commandList.add("-logfile");
    commandList.add(this.taskOutputFile.toString());
    commandList.add("-r");
    commandList.add(runArg);//from ww w . j a  v  a2s.  com

    String[] command = (String[]) commandList.toArray(new String[commandList.size()]);

    ProcessBuilder b = new ProcessBuilder();
    // invalid on windows, it affects the starter only
    b.directory(this.workingDirectory);
    b.command(command);

    // Fix for SCHEDULING-1309: If MATLAB client uses RunAsMe option the MATLAB
    // worker jvm can crash if the client user has never started any MATLAB
    // session on the worker host

    // Since the user profile can be missing on Windows with RunAsMe, by setting
    // the MATLAB_PREFDIR variable to a writable dir (can be non-writable on Windows with RunAsMe)
    // the MATLAB doesn't crash no more

    Map<String, String> env = b.environment();

    // Transmit the prefdir as env variable
    String matlabPrefdir = System.getProperty(MATLAB_PREFDIR);
    if (matlabPrefdir != null) {
        env.put("MATLAB_PREFDIR", matlabPrefdir);
    }
    // Transmit the tmpdir as env variable
    String matlabTmpvar = System.getProperty(MATLAB_TASK_TMPDIR);
    if (matlabTmpvar != null) {
        env.put("TEMP", matlabTmpvar);
        env.put("TMP", matlabTmpvar);
    }

    return b.start();
}

From source file:org.artofsolving.jodconverter.office.OfficeProcess.java

private void addBasisAndUrePaths(ProcessBuilder processBuilder) throws IOException {
    // see http://wiki.services.openoffice.org/wiki/ODF_Toolkit/Efforts/Three-Layer_OOo
    File basisLink = new File(officeHome, "basis-link");
    if (!basisLink.isFile()) {
        logger.fine(/*  www.j  av  a2  s . c o m*/
                "no %OFFICE_HOME%/basis-link found; assuming it's OOo 2.x and we don't need to append URE and Basic paths");
        return;
    }
    String basisLinkText = FileUtils.readFileToString(basisLink).trim();
    File basisHome = new File(officeHome, basisLinkText);
    File basisProgram = new File(basisHome, "program");
    File ureLink = new File(basisHome, "ure-link");
    String ureLinkText = FileUtils.readFileToString(ureLink).trim();
    File ureHome = new File(basisHome, ureLinkText);
    File ureBin = new File(ureHome, "bin");
    Map<String, String> environment = processBuilder.environment();
    // Windows environment variables are case insensitive but Java maps are not :-/
    // so let's make sure we modify the existing key
    String pathKey = "PATH";
    for (String key : environment.keySet()) {
        if ("PATH".equalsIgnoreCase(key)) {
            pathKey = key;
        }
    }
    String path = environment.get(pathKey) + ";" + ureBin.getAbsolutePath() + ";"
            + basisProgram.getAbsolutePath();
    logger.fine(String.format("setting %s to \"%s\"", pathKey, path));
    environment.put(pathKey, path);
}

From source file:org.openbi.kettle.plugins.refreshtableauextract.RefreshTableauExtract.java

public Result execute(Result previousResult, int nr) throws KettleException {
    Result result = previousResult;
    result.setResult(validate());//from  w  ww . ja v  a 2 s  . c o m
    if (!result.getResult()) {
        return result;
    }
    String[] commands;
    String tableauCommand = getRealValue(getTableauClient()).trim();
    if (tableauCommand.toLowerCase().endsWith(".exe")) {
        tableauCommand = tableauCommand.substring(0, tableauCommand.length() - 4);
    }
    tableauCommand = "\"" + tableauCommand + "\"";
    if (getRefreshType() == 0 || getRefreshType() == 1) {
        tableauCommand += " refreshextract";
    } else if (getRefreshType() == 2) {
        tableauCommand += " addfiletoextract";
    } else {
        logError(BaseMessages.getString(PKG, "RefreshTableauExtract.Error.InvalidRefreshType"));
        result.setResult(false);
        return result;
    }

    tableauCommand += " --server " + protocolList[getProtocol()] + "://" + getRealValue(getServer());
    if (getRealValue(getServerPort()) != null && !getRealValue(getServerPort()).isEmpty()) {
        tableauCommand += ":" + getRealValue(getServerPort());
    }

    tableauCommand += " --username " + getRealValue(getServerUser());
    tableauCommand += " --password " + getRealValue(getServerPassword());
    tableauCommand += " --datasource \"" + getRealValue(getDataSource()) + "\"";

    if (getRealValue(getSiteName()) != null && !getRealValue(getSiteName()).isEmpty()) {
        tableauCommand += " --site \"" + getRealValue(getSiteName()) + "\"";
    }
    if (getRealValue(getProject()) != null && !getRealValue(getProject()).isEmpty()) {
        tableauCommand += " --project \"" + getRealValue(getProject()) + "\"";
    }
    if (getRealValue(getProxyUser()) != null && !getRealValue(getProxyUser()).isEmpty()) {
        tableauCommand += " --proxy-username " + getRealValue(getProxyUser());
    }
    if (getRealValue(getProxyPassword()) != null && !getRealValue(getProxyPassword()).isEmpty()) {
        tableauCommand += " --proxy-password " + getRealValue(getProxyPassword());
    }

    if (getRefreshType() == 0) {
        commands = new String[1];
        tableauCommand += " --original-file \"" + getRealValue(getExtractFile()) + "\"";
        commands[0] = new String(tableauCommand);
    } else if (getRefreshType() == 1) {
        commands = new String[1];
        if (getFullRefresh()) {
            tableauCommand += " --force-full-refresh";
        }
        if (getRealValue(getSourceUser()) != null && !getRealValue(getSourceUser()).isEmpty()) {
            tableauCommand += " --source-username " + getRealValue(getSourceUser());
        }
        if (getRealValue(getSourcePassword()) != null & !getRealValue(getSourcePassword()).isEmpty()) {
            tableauCommand += " --source-password " + getRealValue(getSourcePassword());
        }
        commands[0] = new String(tableauCommand);
    } else {
        String[] fileStrings = null;
        if (processResultFiles) {
            if (result != null && previousResult.getResultFiles().size() > 0) {

                int size = previousResult.getResultFiles().size();
                if (log.isBasic()) {
                    logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.FilesFound", "" + size));
                }
                try {
                    List<ResultFile> resultFiles = previousResult.getResultFilesList();
                    List<String> files = new ArrayList<String>();
                    Iterator<ResultFile> it = resultFiles.iterator();
                    while (it.hasNext()) {
                        ResultFile f = it.next();
                        FileObject o = f.getFile();
                        if (o.getType().equals(FileType.FILE)) {
                            if (o.exists()) {
                                files.add(o.getName().toString().startsWith("file:///")
                                        ? o.getName().toString().substring(8)
                                        : o.getName().toString());
                            } else {
                                logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.FileNotExist",
                                        "" + o.getName()));
                            }
                        } else {
                            logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.ResultNotFile",
                                    "" + o.getName()));
                        }
                    }
                    if (files.size() > 0) {
                        Iterator<String> ite = files.iterator();
                        fileStrings = new String[files.size()];
                        int i = 0;
                        while (ite.hasNext()) {
                            fileStrings[i] = ite.next();
                            i++;
                        }

                    } else {
                        logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.NoFilesOnResult"));
                        result.setResult(true);
                        return result;
                    }
                } catch (Exception ex) {
                    logError(ex.toString());
                    result.setResult(false);
                    return result;
                }
            } else {
                logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.NoFilesOnResult"));
                result.setResult(true);
                return result;
            }
        } else {
            // Get source and destination files, also wildcard
            String[] vFilePaths = filePaths;
            String[] vWildcards = wildcards;
            boolean[] includeSubfolders = new boolean[vFilePaths.length];
            String[] fileRequired = new String[vFilePaths.length];

            for (int i = 0; i < includeSubfolders.length; i++) {
                includeSubfolders[i] = false;
            }
            FileInputList files = FileInputList.createFileList(this, vFilePaths, vWildcards, fileRequired,
                    includeSubfolders);
            fileStrings = new String[files.getFileStrings().length];
            fileStrings = files.getFileStrings();
        }
        commands = new String[fileStrings.length];
        for (int i = 0; i < fileStrings.length; i++) {
            commands[i] = new String(tableauCommand + " --file \"" + fileStrings[i] + "\"");
        }
    }

    FileObject fileObject = null;
    String realScript = "";
    FileObject tempFile = null;

    for (int i = 0; i < commands.length; i++) {
        //    realScript+="echo Running: "+commands[i]+"\n";
        realScript += commands[i] + "\n";
        if (log.isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "RefreshTableauExtract.Commands", commands[i]));
        }
    }
    try {
        // What's the exact command?
        String[] command;

        if (log.isBasic()) {
            logBasic(BaseMessages.getString(PKG, "RefreshTableuaExtract.RunningOn", Const.getOS()));
        }

        if (Const.getOS().equals("Windows 95")) {
            //base = new String[] { "command.com", "/C" };
            tempFile = KettleVFS.createTempFile("kettle", "shell.bat", null, this);
            fileObject = createTemporaryShellFile(tempFile, realScript);
            command = new String[] { "command.com", "/C",
                    "\"" + Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject)) + "\"" };
        } else if (Const.getOS().startsWith("Windows")) {
            //base = new String[] { "cmd.exe", "/C" };
            tempFile = KettleVFS.createTempFile("kettle", "shell.bat", null, this);
            fileObject = createTemporaryShellFile(tempFile, realScript);
            command = new String[] { "cmd.exe", "/C",
                    "\"" + Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject)) + "\"" };
        } else {
            tempFile = KettleVFS.createTempFile("kettle", "shell", null, this);
            fileObject = createTemporaryShellFile(tempFile, realScript);
            command = new String[] { Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject)) };
        }

        ProcessBuilder pb = new ProcessBuilder(command);

        Map<String, String> env = pb.environment();
        String[] variables = listVariables();
        for (int i = 0; i < variables.length; i++) {
            env.put(variables[i], getVariable(variables[i]));
        }

        if (getWorkingDirectory() != null && !Const.isEmpty(Const.rtrim(getRealValue(getWorkingDirectory())))) {
            String vfsFilename = environmentSubstitute(getRealValue(getWorkingDirectory()));
            File file = new File(KettleVFS.getFilename(KettleVFS.getFileObject(vfsFilename, this)));
            pb.directory(file);
        }

        if (log.isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "RefreshTableauExtract.CommandStarted"));
        }
        Process proc = pb.start();
        // any error message?
        StreamLogger errorLogger = new StreamLogger(log, proc.getErrorStream(), "(stderr)");

        // any output?
        StreamLogger outputLogger = new StreamLogger(log, proc.getInputStream(), "(stdout)");

        // kick them off
        new Thread(errorLogger).start();
        new Thread(outputLogger).start();

        proc.waitFor();

        if (log.isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "RefreshTableauExtract.CommandFinished"));
        }
        // What's the exit status?
        result.setExitStatus(proc.exitValue());
        if (result.getExitStatus() != 0) {
            logError(BaseMessages.getString(PKG, "RefreshTableauExtract.ExitStatus",
                    "" + result.getExitStatus()));
            result.setResult(false);
        }

        // close the streams
        // otherwise you get "Too many open files, java.io.IOException" after a lot of iterations
        proc.getErrorStream().close();
        proc.getOutputStream().close();

    } catch (Exception ex) {
        logError(ex.toString());
        result.setResult(false);
    } finally {
        // If we created a temporary file, remove it...
        //
        if (tempFile != null) {
            try {
                tempFile.delete();
            } catch (Exception e) {
                BaseMessages.getString(PKG, "RefreshTableauExtract.UnexpectedError", tempFile.toString(),
                        e.toString());
            }
        }
    }

    return result;

}

From source file:org.kepler.ddp.director.DDPEngine.java

/** Check if the DDP engine server is running. If not, try to start it.
 *  @param socketAddress Host and port of the server to check.
 *  @param startScriptStr The script to start the server if not running.
 *  @return True if a server was started, false if could connect to already running server. 
 *///from w ww  . j  a  v a 2s.co  m
protected boolean _checkServer(InetSocketAddress socketAddress, String startScriptStr)
        throws IllegalActionException {

    boolean startedServer = false;

    synchronized (_serverStartStopLock) {
        Socket socket = null;
        try {
            socket = new Socket();
            boolean connected = false;
            try {
                socket.connect(socketAddress, _CONNECT_TIMEOUT);
                connected = true;
            } catch (IOException e) {

                System.out.println(_engineName + " server " + socketAddress
                        + " does not appear to be running. Starting...");

                // start the server

                if (!_checkFilesBeforeStartingServer()) {
                    throw new IllegalActionException(_director,
                            "One or more files required to start the server were not found.");
                }

                // see if the script is executable. kepler modules are zipped,
                // which does not preserve the permissions.
                File startScriptFile = new File(startScriptStr);
                if (!startScriptFile.canExecute()) {
                    throw new IllegalActionException(_director,
                            "The script " + startScriptFile + " is not executable.\n"
                                    + "You must change the permissions so that " + startScriptFile.getName()
                                    + " and all the other scripts in \n" + startScriptFile.getParent()
                                    + " are executable.");
                }

                ProcessBuilder builder = new ProcessBuilder(startScriptStr);

                // make sure JAVA_HOME is set
                java.util.Map<String, String> env = builder.environment();
                if (env.get("JAVA_HOME") == null) {
                    env.put("JAVA_HOME", System.getProperty("java.home"));
                }

                builder.redirectErrorStream(true);

                try {
                    Process process = builder.start();
                    InetSocketAddress newAddress = _parseOutputFromStartingServer(process.getInputStream());
                    if (newAddress != null) {
                        socketAddress = newAddress;
                    }
                    process.waitFor();
                    startedServer = true;
                } catch (Exception e1) {
                    throw new IllegalActionException(_director, e1,
                            "Unable to start " + _engineName + " server.");
                }

                int tries = 0;
                while (tries < 5) {
                    // wait for the server to start
                    try {
                        Thread.sleep(5000);
                        tries++;
                        System.out.print("Connecting to " + _engineName + " server port try #" + tries + ": ");
                        try {
                            socket.close();
                            socket = new Socket();
                            socket.connect(socketAddress, _CONNECT_TIMEOUT);
                            connected = true;
                            System.out.println("connected.");
                            break;
                        } catch (IOException e1) {
                            // do nothing
                            System.out.println(e1);
                        }
                    } catch (InterruptedException e2) {
                        throw new IllegalActionException(_director, e2, "Error while sleeping.");
                    }
                }

                // if we get here, we were able to connect to the master/job manager port.
                // however, the server may not be completely initialized, so wait a few more seconds
                System.out.println("Waiting 15 seconds for " + _engineName + " server to initialize.");
                try {
                    Thread.sleep(15000);
                } catch (InterruptedException e2) {
                    throw new IllegalActionException(_director, e2,
                            "Error while waiting " + " for " + _engineName + " server to initialize.");
                }

            }

            if (connected) {
                try {
                    socket.close();
                    socket = null;
                } catch (IOException e) {
                    throw new IllegalActionException(_director, e, "Error closing socket.");
                }
            } else {
                throw new IllegalActionException(_director,
                        "Could not connect to " + _engineName + " server: " + socketAddress);
            }
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new IllegalActionException(_director, e, "Error closing socket.");
                }
            }
        }
    }

    return startedServer;
}

From source file:bboss.org.artofsolving.jodconverter.office.OfficeProcess.java

private void addBasisAndUrePaths(ProcessBuilder processBuilder) throws IOException {
    // see http://wiki.services.openoffice.org/wiki/ODF_Toolkit/Efforts/Three-Layer_OOo
    File basisLink = new File(officeHome, "basis-link");
    if (!basisLink.isFile()) {
        logger.info(/*from   w  ww . java2 s.com*/
                "no %OFFICE_HOME%/basis-link found; assuming it's OOo 2.x and we don't need to append URE and Basic paths");
        return;
    }
    String basisLinkText = FileUtils.readFileToString(basisLink).trim();
    File basisHome = new File(officeHome, basisLinkText);
    File basisProgram = new File(basisHome, "program");
    File ureLink = new File(basisHome, "ure-link");
    String ureLinkText = FileUtils.readFileToString(ureLink).trim();
    File ureHome = new File(basisHome, ureLinkText);
    File ureBin = new File(ureHome, "bin");
    Map<String, String> environment = processBuilder.environment();
    // Windows environment variables are case insensitive but Java maps are not :-/
    // so let's make sure we modify the existing key
    String pathKey = "PATH";
    for (String key : environment.keySet()) {
        if ("PATH".equalsIgnoreCase(key)) {
            pathKey = key;
        }
    }
    String path = environment.get(pathKey) + ";" + ureBin.getAbsolutePath() + ";"
            + basisProgram.getAbsolutePath();
    logger.info(String.format("setting %s to \"%s\"", pathKey, path));
    environment.put(pathKey, path);
}

From source file:com.turn.ttorrent.client.Client.java

private void mergeFiles() {
    for (Torrent.TorrentFile file : this.torrent.files) {
        String filesPath = "";
        for (int i = 0; i < (file.size / this.torrent.pieceLength); i++) {
            filesPath += new File(this.torrent.parentPath, file.getPath() + "." + i).getAbsolutePath() + " ";
            //FilenameUtils.concat(this.torrent.parentPath, file.getPath()+"."+i+" ");
            System.out.println(filesPath);
        }/*from   w w w  .ja  va2 s  .c  o m*/
        try {
            System.out.println("Complete command " + this.torrent.getCompleteCommand());
            ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c",
                    this.torrent.getCompleteCommand()/*"cat $PART_LIST > $FILE"*/);
            Map<String, String> env = pb.environment();
            env.put("PART_LIST", filesPath);
            env.put("FILE", new File(this.torrent.parentPath, file.getPath()).getAbsolutePath());
            //FilenameUtils.concat(this.torrent.parentPath, file.getPath()));
            Process pr = pb.start();

            BufferedReader bre = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
            String line;
            while ((line = bre.readLine()) != null) {
                System.err.println(line);
            }
            bre.close();

            int exitVal;
            if ((exitVal = pr.waitFor()) != 0)
                ;
            else
                logger.info("Files merged...");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:bboss.org.artofsolving.jodconverter.office.OfficeProcess.java

private void addLiberofficeBasisAndUrePaths(ProcessBuilder processBuilder) throws IOException {
    // see http://wiki.services.openoffice.org/wiki/ODF_Toolkit/Efforts/Three-Layer_OOo
    //        File basisLink = new File(officeHome, "basis-link");
    //        if (!basisLink.isFile()) {
    //            logger.fine("no %OFFICE_HOME%/basis-link found; assuming it's OOo 2.x and we don't need to append URE and Basic paths");
    //            return;
    //        }// w w  w  .j  ava 2 s.com
    //        String basisLinkText = FileUtils.readFileToString(basisLink).trim();
    File basisHome = officeHome;
    File basisProgram = new File(basisHome, "program");
    File ureLink = new File(basisHome, "URE");
    //        String ureLinkText = FileUtils.readFileToString(ureLink).trim();
    //        File ureHome = new File(basisHome, ureLinkText);
    File ureBin = new File(ureLink, "bin");
    Map<String, String> environment = processBuilder.environment();
    // Windows environment variables are case insensitive but Java maps are not :-/
    // so let's make sure we modify the existing key
    String pathKey = "PATH";
    for (String key : environment.keySet()) {
        if ("PATH".equalsIgnoreCase(key)) {
            pathKey = key;
        }
    }
    String path = environment.get(pathKey) + ";" + ureBin.getAbsolutePath() + ";"
            + basisProgram.getAbsolutePath();
    logger.info(String.format("setting %s to \"%s\"", pathKey, path));
    environment.put(pathKey, path);
}