Example usage for java.lang ProcessBuilder directory

List of usage examples for java.lang ProcessBuilder directory

Introduction

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

Prototype

File directory

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

Click Source Link

Usage

From source file:com.photon.phresco.plugins.xcode.XcodeBuild.java

/**
 * Execute the xcode command line utility.
 *//* w w w .ja va  2s.co m*/
public void execute() throws MojoExecutionException {
    if (!xcodeCommandLine.exists()) {
        throw new MojoExecutionException(
                "Invalid path, invalid xcodebuild file: " + xcodeCommandLine.getAbsolutePath());
    }
    /*
     * // Compute archive name String archiveName =
     * project.getBuild().getFinalName() + ".cust"; File finalDir = new
     * File(buildDirectory, archiveName);
     * 
     * // Configure archiver MavenArchiver archiver = new MavenArchiver();
     * archiver.setArchiver(jarArchiver); archiver.setOutputFile(finalDir);
     */

    try {
        if (!SdkVerifier.isAvailable(sdk)) {
            throw new MojoExecutionException("Selected version " + sdk + " is not available!");
        }
    } catch (IOException e2) {
        throw new MojoExecutionException("SDK verification failed!");
    } catch (InterruptedException e2) {
        throw new MojoExecutionException("SDK verification interrupted!");
    }

    try {
        init();
        configure();
        ProcessBuilder pb = new ProcessBuilder(xcodeCommandLine.getAbsolutePath());
        // Include errors in output
        pb.redirectErrorStream(true);

        List<String> commands = pb.command();
        if (xcodeProject != null) {
            commands.add("-project");
            commands.add(xcodeProject);
        }
        if (StringUtils.isNotBlank(configuration)) {
            commands.add("-configuration");
            commands.add(configuration);
        }

        if (StringUtils.isNotBlank(sdk)) {
            commands.add("-sdk");
            commands.add(sdk);
        }

        commands.add("OBJROOT=" + buildDirectory);
        commands.add("SYMROOT=" + buildDirectory);
        commands.add("DSTROOT=" + buildDirectory);

        if (StringUtils.isNotBlank(xcodeTarget)) {
            commands.add("-target");
            commands.add(xcodeTarget);
        }

        if (StringUtils.isNotBlank(gccpreprocessor)) {
            commands.add("GCC_PREPROCESSOR_DEFINITIONS=" + gccpreprocessor);
        }

        if (unittest) {
            commands.add("clean");
            commands.add("build");
        }

        getLog().info("List of commands" + pb.command());
        // pb.command().add("install");
        pb.directory(new File(basedir));
        Process child = pb.start();

        // Consume subprocess output and write to stdout for debugging
        InputStream is = new BufferedInputStream(child.getInputStream());
        int singleByte = 0;
        while ((singleByte = is.read()) != -1) {
            // output.write(buffer, 0, bytesRead);
            System.out.write(singleByte);
        }

        child.waitFor();
        int exitValue = child.exitValue();
        getLog().info("Exit Value: " + exitValue);
        if (exitValue != 0) {
            throw new MojoExecutionException("Compilation error occured. Resolve the error(s) and try again!");
        }

        if (!unittest) {
            //In case of unit testcases run, the APP files will not be generated.
            createdSYM();
            createApp();
        }
        /*
         * child.waitFor();
         * 
         * InputStream in = child.getInputStream(); InputStream err =
         * child.getErrorStream(); getLog().error(sb.toString());
         */
    } catch (IOException e) {
        getLog().error("An IOException occured.");
        throw new MojoExecutionException("An IOException occured", e);
    } catch (InterruptedException e) {
        getLog().error("The clean process was been interrupted.");
        throw new MojoExecutionException("The clean process was been interrupted", e);
    } catch (MojoFailureException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    File directory = new File(this.basedir + "/pom.xml");
    this.project.getArtifact().setFile(directory);
}

From source file:program.RunProgram.java

/**
 * This is the the actual run of the program
 * 1-Execute in the thread the commandline
 * 2-Catch both stderr and stdout/*ww w . jav  a2s  .c o m*/
 * 3-Put the program ExitValue in properties->ExitValue
 * 4-Put  both stderr and stdout in the output vector and in the "output"properties
 * @throws Exception
 */
public boolean do_run() throws Exception {

    setStatus(status_running, "\tRunning program...");
    setStatus(status_running, "<-Program Output->");
    //--Run the thread and catch stdout and stderr
    if (Docker.isProgramUseDocker(properties) && Docker.isDockerHere()) {
        Docker.executeBashFile(properties);
        setStatus(status_running, properties.get("DockerSTD"));
        String s = properties.get("DockerSTD");
        s = s.toLowerCase();
        Pattern p = Pattern.compile(".*exit is -(\\d+)-.*");
        Matcher m = p.matcher(s);
        //Util.dm(m.toString());
        int i = -1;
        if (m.find()) {
            i = Integer.parseInt(m.group(1));
        }
        Util.dm("Docker exit value is >" + Integer.toString(i) + "<");
        properties.put("ExitValue", i);
    } else {
        ProcessBuilder pb = new ProcessBuilder(commandline);
        if (properties.isSet("RunningDirectory")) {
            pb.directory(new File(properties.get("RunningDirectory")));
        }

        r = Runtime.getRuntime();
        //--Test August 2011 - For Mac OS X
        if ((config.getBoolean("MacOSX") || SystemUtils.IS_OS_MAC_OSX)) {
            if (properties.isSet("RuntimeMacOSX")) {
                String execution_type = properties.get("RuntimeMacOSX");
                //--Default
                if (execution_type.startsWith("default")) {
                    //? Not suppose to exists...
                    p = pb.start();
                }
                //--Runtime (r.exec)
                if (execution_type.startsWith("runtime")) {
                    //--IF MAC_OSX, group option if UseRuntimeMacOSX
                    String cmdm = Util.toString(commandline);
                    cmdm = Util.replaceMultiSpacesByOne(cmdm);
                    cmdm = Util.removeTrailingSpace(cmdm);
                    /*
                    for (int i=0; i<commandline.length;i++) {
                    if (!commandline[i].equals(""))
                        cmdm+=commandline[i]+" ";
                    }
                    commandline=new String[1];
                    commandline[0]=cmdm;
                    */
                    p = r.exec(cmdm);
                }
                //--Bash...
                if (execution_type.startsWith("bash (.sh)")) {
                    //--Create a new bash file
                    Util u = new Util("RunProgram.sh");
                    u.println("#!/bin/sh");
                    u.println("echo \"Executing by bash command: " + properties.getName() + "\"");
                    u.println(Util.toString(commandline));
                    //--Return the application error code
                    u.println("exit $?");
                    u.close();
                    p = r.exec("sh RunProgram.sh");
                }
            } //--End RuntimeMacOSX
              //--Run time
            else {
                //--Create a new bash file
                Util u = new Util("RunProgram.sh");
                u.println("#!/bin/sh");
                u.println("echo \"Executing by bash command: " + properties.getName() + "\"");
                u.println(Util.toString(commandline));
                //--Return the application error code
                u.println("exit $?");
                u.close();
                p = r.exec("sh RunProgram.sh");
            }
        } else if ((config.getBoolean("Linux") || SystemUtils.IS_OS_LINUX)) {
            //                Util u = new Util("RunProgram"+Util.returnTimeCode()+".sh");
            //                u.println("#!/bin/sh");
            //                u.println("echo \"Executing by bash command: "+properties.getName()+"\"");
            //                u.println(Util.toString(commandline));
            //                //--Return the application error code
            //                u.println("exit $?");
            //                u.close();
            //                p=r.exec("sh "+u.log_filename);
            //                Util.deleteFile(u.log_filename);
            String cli = Util.toString(commandline).replace("\\s+", " ");
            p = r.exec(cli); // JG 2015
        } else {
            p = pb.start();
        }

        //pb.redirectErrorStream(true)
        InputStreamThread stderr = new InputStreamThread(p.getErrorStream());
        InputStreamThread stdout = new InputStreamThread(p.getInputStream());

        int exitvalue = p.waitFor();

        //--Wait for the exitValue
        properties.put("ExitValue", exitvalue);
    }
    return true;
}

From source file:org.apache.nifi.registry.bootstrap.RunNiFiRegistry.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void start() throws IOException, InterruptedException {
    final Integer port = getCurrentPort(cmdLogger);
    if (port != null) {
        cmdLogger.info("Apache NiFi Registry is already running, listening to Bootstrap on port " + port);
        return;/* w  w w. java  2 s  . c o  m*/
    }

    final File prevLockFile = getLockFile(cmdLogger);
    if (prevLockFile.exists() && !prevLockFile.delete()) {
        cmdLogger.warn("Failed to delete previous lock file {}; this file should be cleaned up manually",
                prevLockFile);
    }

    final ProcessBuilder builder = new ProcessBuilder();

    if (!bootstrapConfigFile.exists()) {
        throw new FileNotFoundException(bootstrapConfigFile.getAbsolutePath());
    }

    final Properties properties = new Properties();
    try (final FileInputStream fis = new FileInputStream(bootstrapConfigFile)) {
        properties.load(fis);
    }

    final Map<String, String> props = new HashMap<>();
    props.putAll((Map) properties);

    final String specifiedWorkingDir = props.get("working.dir");
    if (specifiedWorkingDir != null) {
        builder.directory(new File(specifiedWorkingDir));
    }

    final File bootstrapConfigAbsoluteFile = bootstrapConfigFile.getAbsoluteFile();
    final File binDir = bootstrapConfigAbsoluteFile.getParentFile();
    final File workingDir = binDir.getParentFile();

    if (specifiedWorkingDir == null) {
        builder.directory(workingDir);
    }

    final String nifiRegistryLogDir = replaceNull(
            System.getProperty("org.apache.nifi.registry.bootstrap.config.log.dir"), DEFAULT_LOG_DIR).trim();

    final String libFilename = replaceNull(props.get("lib.dir"), "./lib").trim();
    File libDir = getFile(libFilename, workingDir);
    File libSharedDir = getFile(libFilename + "/shared", workingDir);

    final String confFilename = replaceNull(props.get("conf.dir"), "./conf").trim();
    File confDir = getFile(confFilename, workingDir);

    String nifiRegistryPropsFilename = props.get("props.file");
    if (nifiRegistryPropsFilename == null) {
        if (confDir.exists()) {
            nifiRegistryPropsFilename = new File(confDir, "nifi-registry.properties").getAbsolutePath();
        } else {
            nifiRegistryPropsFilename = DEFAULT_CONFIG_FILE;
        }
    }

    nifiRegistryPropsFilename = nifiRegistryPropsFilename.trim();

    final List<String> javaAdditionalArgs = new ArrayList<>();
    for (final Map.Entry<String, String> entry : props.entrySet()) {
        final String key = entry.getKey();
        final String value = entry.getValue();

        if (key.startsWith("java.arg")) {
            javaAdditionalArgs.add(value);
        }
    }

    final File[] libSharedFiles = libSharedDir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(final File dir, final String filename) {
            return filename.toLowerCase().endsWith(".jar");
        }
    });

    if (libSharedFiles == null || libSharedFiles.length == 0) {
        throw new RuntimeException("Could not find lib shared directory at " + libSharedDir.getAbsolutePath());
    }

    final File[] libFiles = libDir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(final File dir, final String filename) {
            return filename.toLowerCase().endsWith(".jar");
        }
    });

    if (libFiles == null || libFiles.length == 0) {
        throw new RuntimeException("Could not find lib directory at " + libDir.getAbsolutePath());
    }

    final File[] confFiles = confDir.listFiles();
    if (confFiles == null || confFiles.length == 0) {
        throw new RuntimeException("Could not find conf directory at " + confDir.getAbsolutePath());
    }

    final List<String> cpFiles = new ArrayList<>(confFiles.length + libFiles.length + libSharedFiles.length);
    cpFiles.add(confDir.getAbsolutePath());
    for (final File file : libSharedFiles) {
        cpFiles.add(file.getAbsolutePath());
    }
    for (final File file : libFiles) {
        cpFiles.add(file.getAbsolutePath());
    }

    final StringBuilder classPathBuilder = new StringBuilder();
    for (int i = 0; i < cpFiles.size(); i++) {
        final String filename = cpFiles.get(i);
        classPathBuilder.append(filename);
        if (i < cpFiles.size() - 1) {
            classPathBuilder.append(File.pathSeparatorChar);
        }
    }

    final String classPath = classPathBuilder.toString();
    String javaCmd = props.get("java");
    if (javaCmd == null) {
        javaCmd = DEFAULT_JAVA_CMD;
    }
    if (javaCmd.equals(DEFAULT_JAVA_CMD)) {
        String javaHome = System.getenv("JAVA_HOME");
        if (javaHome != null) {
            String fileExtension = isWindows() ? ".exe" : "";
            File javaFile = new File(
                    javaHome + File.separatorChar + "bin" + File.separatorChar + "java" + fileExtension);
            if (javaFile.exists() && javaFile.canExecute()) {
                javaCmd = javaFile.getAbsolutePath();
            }
        }
    }

    final NiFiRegistryListener listener = new NiFiRegistryListener();
    final int listenPort = listener.start(this);

    final List<String> cmd = new ArrayList<>();

    cmd.add(javaCmd);
    cmd.add("-classpath");
    cmd.add(classPath);
    cmd.addAll(javaAdditionalArgs);
    cmd.add("-Dnifi.registry.properties.file.path=" + nifiRegistryPropsFilename);
    cmd.add("-Dnifi.registry.bootstrap.config.file.path=" + bootstrapConfigFile.getAbsolutePath());
    cmd.add("-Dnifi.registry.bootstrap.listen.port=" + listenPort);
    cmd.add("-Dapp=NiFiRegistry");
    cmd.add("-Dorg.apache.nifi.registry.bootstrap.config.log.dir=" + nifiRegistryLogDir);
    cmd.add("org.apache.nifi.registry.NiFiRegistry");

    builder.command(cmd);

    final StringBuilder cmdBuilder = new StringBuilder();
    for (final String s : cmd) {
        cmdBuilder.append(s).append(" ");
    }

    cmdLogger.info("Starting Apache NiFi Registry...");
    cmdLogger.info("Working Directory: {}", workingDir.getAbsolutePath());
    cmdLogger.info("Command: {}", cmdBuilder.toString());

    String gracefulShutdown = props.get(GRACEFUL_SHUTDOWN_PROP);
    if (gracefulShutdown == null) {
        gracefulShutdown = DEFAULT_GRACEFUL_SHUTDOWN_VALUE;
    }

    final int gracefulShutdownSeconds;
    try {
        gracefulShutdownSeconds = Integer.parseInt(gracefulShutdown);
    } catch (final NumberFormatException nfe) {
        throw new NumberFormatException("The '" + GRACEFUL_SHUTDOWN_PROP
                + "' property in Bootstrap Config File " + bootstrapConfigAbsoluteFile.getAbsolutePath()
                + " has an invalid value. Must be a non-negative integer");
    }

    if (gracefulShutdownSeconds < 0) {
        throw new NumberFormatException("The '" + GRACEFUL_SHUTDOWN_PROP
                + "' property in Bootstrap Config File " + bootstrapConfigAbsoluteFile.getAbsolutePath()
                + " has an invalid value. Must be a non-negative integer");
    }

    Process process = builder.start();
    handleLogging(process);
    Long pid = OSUtils.getProcessId(process, cmdLogger);
    if (pid == null) {
        cmdLogger.warn("Launched Apache NiFi Registry but could not determined the Process ID");
    } else {
        nifiRegistryPid = pid;
        final Properties pidProperties = new Properties();
        pidProperties.setProperty(PID_KEY, String.valueOf(nifiRegistryPid));
        savePidProperties(pidProperties, cmdLogger);
        cmdLogger.info("Launched Apache NiFi Registry with Process ID " + pid);
    }

    shutdownHook = new ShutdownHook(process, this, secretKey, gracefulShutdownSeconds, loggingExecutor);
    final Runtime runtime = Runtime.getRuntime();
    runtime.addShutdownHook(shutdownHook);

    final String hostname = getHostname();
    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
    String now = sdf.format(System.currentTimeMillis());
    String user = System.getProperty("user.name");
    if (user == null || user.trim().isEmpty()) {
        user = "Unknown User";
    }

    while (true) {
        final boolean alive = isAlive(process);

        if (alive) {
            try {
                Thread.sleep(1000L);
            } catch (final InterruptedException ie) {
            }
        } else {
            try {
                runtime.removeShutdownHook(shutdownHook);
            } catch (final IllegalStateException ise) {
                // happens when already shutting down
            }

            now = sdf.format(System.currentTimeMillis());
            if (autoRestartNiFiRegistry) {
                final File statusFile = getStatusFile(defaultLogger);
                if (!statusFile.exists()) {
                    defaultLogger.info("Status File no longer exists. Will not restart NiFi Registry ");
                    return;
                }

                final File lockFile = getLockFile(defaultLogger);
                if (lockFile.exists()) {
                    defaultLogger.info("A shutdown was initiated. Will not restart NiFi Registry ");
                    return;
                }

                final boolean previouslyStarted = getNifiRegistryStarted();
                if (!previouslyStarted) {
                    defaultLogger.info("NiFi Registry never started. Will not restart NiFi Registry ");
                    return;
                } else {
                    setNiFiRegistryStarted(false);
                }

                defaultLogger.warn("Apache NiFi Registry appears to have died. Restarting...");
                process = builder.start();
                handleLogging(process);

                pid = OSUtils.getProcessId(process, defaultLogger);
                if (pid == null) {
                    cmdLogger.warn("Launched Apache NiFi Registry but could not obtain the Process ID");
                } else {
                    nifiRegistryPid = pid;
                    final Properties pidProperties = new Properties();
                    pidProperties.setProperty(PID_KEY, String.valueOf(nifiRegistryPid));
                    savePidProperties(pidProperties, defaultLogger);
                    cmdLogger.info("Launched Apache NiFi Registry with Process ID " + pid);
                }

                shutdownHook = new ShutdownHook(process, this, secretKey, gracefulShutdownSeconds,
                        loggingExecutor);
                runtime.addShutdownHook(shutdownHook);

                final boolean started = waitForStart();

                if (started) {
                    defaultLogger.info("Successfully started Apache NiFi Registry {}",
                            (pid == null ? "" : " with PID " + pid));
                } else {
                    defaultLogger.error("Apache NiFi Registry does not appear to have started");
                }
            } else {
                return;
            }
        }
    }
}

From source file:org.nuxeo.launcher.NuxeoLauncher.java

/**
 * Do not directly call this method without a call to
 * {@link #checkNoRunningServer()}//from  w ww .  j a v  a2 s.c o  m
 *
 * @see #doStart()
 * @throws IOException In case of issue with process.
 * @throws InterruptedException If any thread has interrupted the current
 *             thread.
 */
protected void start(boolean logProcessOutput) throws IOException, InterruptedException {
    List<String> startCommand = new ArrayList<String>();
    startCommand.add(getJavaExecutable().getPath());
    startCommand.addAll(Arrays.asList(getJavaOptsProperty().split(" ")));
    startCommand.add("-cp");
    startCommand.add(getClassPath());
    startCommand.addAll(getNuxeoProperties());
    startCommand.addAll(getServerProperties());
    setServerStartCommand(startCommand);
    for (String param : params) {
        startCommand.add(param);
    }
    ProcessBuilder pb = new ProcessBuilder(getOSCommand(startCommand));
    pb.directory(configurationGenerator.getNuxeoHome());
    // pb = pb.redirectErrorStream(true);
    log.debug("Server command: " + pb.command());
    nuxeoProcess = pb.start();
    logProcessStreams(nuxeoProcess, logProcessOutput);
    Thread.sleep(1000);
    if (getPid() != null) {
        log.warn("Server started with process ID " + pid + ".");
    } else {
        log.warn("Sent server start command but could not get process ID.");
    }
}

From source file:adalid.commons.velocity.Writer.java

private void executeFile(VelocityContext fileContext, File templatePropertiesFile) {
    Properties properties = mergeProperties(fileContext, templatePropertiesFile);
    String command = StringUtils.trimToNull(properties.getProperty(TP_EXECUTE_COMMAND));
    String directory = StringUtils.trimToNull(properties.getProperty(TP_EXECUTE_DIRECTORY));
    if (command != null) {
        StrTokenizer tokenizer = new StrTokenizer(command);
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.command(tokenizer.getTokenArray());
        if (directory != null) {
            File dir = new File(directory);
            if (dir.exists() && dir.isDirectory()) {
                if (dir.isAbsolute()) {
                    processBuilder.directory(dir);
                } else {
                    processBuilder.directory(dir.getAbsoluteFile());
                }//from w ww.  j av  a2 s .com
            }
        }
        try {
            Process process = processBuilder.start();
            int w = process.waitFor();
            int x = process.exitValue();
            logger.info(command + " = " + w + "," + x);
        } catch (IOException | InterruptedException ex) {
            error(ex);
        }
    }
}

From source file:org.apache.nifi.minifi.bootstrap.RunMiNiFi.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public Tuple<ProcessBuilder, Process> startMiNiFi() throws IOException, InterruptedException {
    final Integer port = getCurrentPort(cmdLogger);
    if (port != null) {
        cmdLogger.info("Apache MiNiFi is already running, listening to Bootstrap on port " + port);
        return null;
    }//  w ww .j  a  va  2s  . c  o  m

    final File prevLockFile = getLockFile(cmdLogger);
    if (prevLockFile.exists() && !prevLockFile.delete()) {
        cmdLogger.warn("Failed to delete previous lock file {}; this file should be cleaned up manually",
                prevLockFile);
    }

    final ProcessBuilder builder = new ProcessBuilder();

    final Map<String, String> props = readProperties();

    final String specifiedWorkingDir = props.get("working.dir");
    if (specifiedWorkingDir != null) {
        builder.directory(new File(specifiedWorkingDir));
    }

    final File bootstrapConfigAbsoluteFile = bootstrapConfigFile.getAbsoluteFile();
    final File binDir = bootstrapConfigAbsoluteFile.getParentFile();
    final File workingDir = binDir.getParentFile();

    if (specifiedWorkingDir == null) {
        builder.directory(workingDir);
    }

    final String minifiLogDir = replaceNull(
            System.getProperty("org.apache.nifi.minifi.bootstrap.config.log.dir"), DEFAULT_LOG_DIR).trim();

    final String libFilename = replaceNull(props.get("lib.dir"), "./lib").trim();
    File libDir = getFile(libFilename, workingDir);

    final String confFilename = replaceNull(props.get(CONF_DIR_KEY), "./conf").trim();
    File confDir = getFile(confFilename, workingDir);

    String minifiPropsFilename = props.get("props.file");
    if (minifiPropsFilename == null) {
        if (confDir.exists()) {
            minifiPropsFilename = new File(confDir, "nifi.properties").getAbsolutePath();
        } else {
            minifiPropsFilename = DEFAULT_CONFIG_FILE;
        }
    }

    minifiPropsFilename = minifiPropsFilename.trim();

    final List<String> javaAdditionalArgs = new ArrayList<>();
    for (final Entry<String, String> entry : props.entrySet()) {
        final String key = entry.getKey();
        final String value = entry.getValue();

        if (key.startsWith("java.arg")) {
            javaAdditionalArgs.add(value);
        }
    }

    final File[] libFiles = libDir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(final File dir, final String filename) {
            return filename.toLowerCase().endsWith(".jar");
        }
    });

    if (libFiles == null || libFiles.length == 0) {
        throw new RuntimeException("Could not find lib directory at " + libDir.getAbsolutePath());
    }

    final File[] confFiles = confDir.listFiles();
    if (confFiles == null || confFiles.length == 0) {
        throw new RuntimeException("Could not find conf directory at " + confDir.getAbsolutePath());
    }

    final List<String> cpFiles = new ArrayList<>(confFiles.length + libFiles.length);
    cpFiles.add(confDir.getAbsolutePath());
    for (final File file : libFiles) {
        cpFiles.add(file.getAbsolutePath());
    }

    final StringBuilder classPathBuilder = new StringBuilder();
    for (int i = 0; i < cpFiles.size(); i++) {
        final String filename = cpFiles.get(i);
        classPathBuilder.append(filename);
        if (i < cpFiles.size() - 1) {
            classPathBuilder.append(File.pathSeparatorChar);
        }
    }

    final String classPath = classPathBuilder.toString();
    String javaCmd = props.get("java");
    if (javaCmd == null) {
        javaCmd = DEFAULT_JAVA_CMD;
    }
    if (javaCmd.equals(DEFAULT_JAVA_CMD)) {
        String javaHome = System.getenv("JAVA_HOME");
        if (javaHome != null) {
            String fileExtension = isWindows() ? ".exe" : "";
            File javaFile = new File(
                    javaHome + File.separatorChar + "bin" + File.separatorChar + "java" + fileExtension);
            if (javaFile.exists() && javaFile.canExecute()) {
                javaCmd = javaFile.getAbsolutePath();
            }
        }
    }

    final MiNiFiListener listener = new MiNiFiListener();
    final int listenPort = listener.start(this);

    final List<String> cmd = new ArrayList<>();

    cmd.add(javaCmd);
    cmd.add("-classpath");
    cmd.add(classPath);
    cmd.addAll(javaAdditionalArgs);
    cmd.add("-Dnifi.properties.file.path=" + minifiPropsFilename);
    cmd.add("-Dnifi.bootstrap.listen.port=" + listenPort);
    cmd.add("-Dapp=MiNiFi");
    cmd.add("-Dorg.apache.nifi.minifi.bootstrap.config.log.dir=" + minifiLogDir);
    cmd.add("org.apache.nifi.minifi.MiNiFi");

    builder.command(cmd);

    final StringBuilder cmdBuilder = new StringBuilder();
    for (final String s : cmd) {
        cmdBuilder.append(s).append(" ");
    }

    cmdLogger.info("Starting Apache MiNiFi...");
    cmdLogger.info("Working Directory: {}", workingDir.getAbsolutePath());
    cmdLogger.info("Command: {}", cmdBuilder.toString());

    Process process = builder.start();
    handleLogging(process);
    Long pid = getPid(process, cmdLogger);
    if (pid != null) {
        minifiPid = pid;
        final Properties minifiProps = new Properties();
        minifiProps.setProperty(PID_KEY, String.valueOf(minifiPid));
        saveProperties(minifiProps, cmdLogger);
    }

    gracefulShutdownSeconds = getGracefulShutdownSeconds(props, bootstrapConfigAbsoluteFile);
    shutdownHook = new ShutdownHook(process, this, secretKey, gracefulShutdownSeconds, loggingExecutor);
    final Runtime runtime = Runtime.getRuntime();
    runtime.addShutdownHook(shutdownHook);

    return new Tuple<ProcessBuilder, Process>(builder, process);
}

From source file:org.nuxeo.launcher.NuxeoLauncher.java

/**
 * Since 5.5/*ww  w  . ja v  a2  s . c  om*/
 */
private boolean pack() {
    try {
        checkNoRunningServer();
        configurationGenerator.setProperty(PARAM_UPDATECENTER_DISABLED, "true");
        List<String> startCommand = new ArrayList<String>();
        startCommand.add(getJavaExecutable().getPath());
        startCommand.addAll(Arrays.asList(getJavaOptsProperty().split(" ")));
        startCommand.add("-cp");
        String classpath = getClassPath();
        classpath = addToClassPath(classpath, "bin" + File.separator + "nuxeo-launcher.jar");
        classpath = getClassPath(classpath, configurationGenerator.getServerConfigurator().getServerLibDir());
        classpath = getClassPath(classpath, configurationGenerator.getServerConfigurator().getNuxeoLibDir());
        classpath = getClassPath(classpath, new File(configurationGenerator.getRuntimeHome(), "bundles"));
        startCommand.add(classpath);
        startCommand.addAll(getNuxeoProperties());
        if (configurationGenerator.isJBoss) {
            startCommand.add(PACK_JBOSS_CLASS);
        } else if (configurationGenerator.isTomcat) {
            startCommand.add(PACK_TOMCAT_CLASS);
        } else {
            errorValue = EXIT_CODE_ERROR;
            return false;
        }
        startCommand.add(configurationGenerator.getRuntimeHome().getPath());
        for (String param : params) {
            startCommand.add(param);
        }
        ProcessBuilder pb = new ProcessBuilder(getOSCommand(startCommand));
        pb.directory(configurationGenerator.getNuxeoHome());
        log.debug("Pack command: " + pb.command());
        Process process = pb.start();
        ArrayList<ThreadedStreamGobbler> sgArray = logProcessStreams(process, true);
        Thread.sleep(100);
        process.waitFor();
        waitForProcessStreams(sgArray);
    } catch (IOException e) {
        errorValue = EXIT_CODE_ERROR;
        log.error("Could not start process", e);
    } catch (InterruptedException e) {
        errorValue = EXIT_CODE_ERROR;
        log.error("Could not start process", e);
    } catch (IllegalStateException e) {
        errorValue = EXIT_CODE_ERROR;
        log.error("The server must not be running while running pack command", e);
    } catch (ConfigurationException e) {
        errorValue = EXIT_CODE_ERROR;
        log.error(e);
    }
    return errorValue == 0;
}

From source file:org.nuxeo.launcher.NuxeoLauncher.java

/**
 * Stops the server./*  w  w w  .j  a v  a 2  s.c  o m*/
 *
 * Will try to call specific class for a clean stop, retry
 * {@link #STOP_NB_TRY}, waiting {@link #STOP_SECONDS_BEFORE_NEXT_TRY}
 * between each try, then kill the process if still running.
 */
public void stop(boolean logProcessOutput) {
    long startTime = new Date().getTime();
    long deltaTime;
    try {
        if (!isRunning()) {
            log.warn("Server is not running.");
            return;
        }
        if (!quiet) {
            System.out.print("\nStopping server...");
        }
        int nbTry = 0;
        boolean retry = false;
        int stopMaxWait = Integer.parseInt(
                configurationGenerator.getUserConfig().getProperty(STOP_MAX_WAIT_PARAM, STOP_MAX_WAIT_DEFAULT));
        do {
            List<String> stopCommand = new ArrayList<String>();
            stopCommand.add(getJavaExecutable().getPath());
            stopCommand.add("-cp");
            stopCommand.add(getShutdownClassPath());
            stopCommand.addAll(getNuxeoProperties());
            stopCommand.addAll(getServerProperties());
            setServerStopCommand(stopCommand);
            for (String param : params) {
                stopCommand.add(param);
            }
            ProcessBuilder pb = new ProcessBuilder(getOSCommand(stopCommand));
            pb.directory(configurationGenerator.getNuxeoHome());
            // pb = pb.redirectErrorStream(true);
            log.debug("Server command: " + pb.command());
            try {
                Process stopProcess = pb.start();
                ArrayList<ThreadedStreamGobbler> sgArray = logProcessStreams(stopProcess, logProcessOutput);
                stopProcess.waitFor();
                waitForProcessStreams(sgArray);
                boolean wait = true;
                while (wait) {
                    try {
                        if (stopProcess.exitValue() == 0) {
                            // Successful call for server stop
                            retry = false;
                        } else {
                            // Failed to call for server stop
                            retry = ++nbTry < STOP_NB_TRY;
                            if (!quiet) {
                                System.out.print(".");
                            }
                            Thread.sleep(STOP_SECONDS_BEFORE_NEXT_TRY * 1000);
                        }
                        wait = false;
                    } catch (IllegalThreadStateException e) {
                        // Stop call is still running
                        wait = true;
                        if (!quiet) {
                            System.out.print(".");
                        }
                        Thread.sleep(1000);
                    }
                }
                // Exit if there's no way to check for server stop
                if (processManager instanceof PureJavaProcessManager) {
                    log.warn("Can't check server status on your OS.");
                    return;
                }
                // Wait a few seconds for effective stop
                deltaTime = 0;
                do {
                    if (!quiet) {
                        System.out.print(".");
                    }
                    Thread.sleep(1000);
                    deltaTime = (new Date().getTime() - startTime) / 1000;
                } while (!retry && getPid() != null && deltaTime < stopMaxWait);
            } catch (InterruptedException e) {
                log.error(e);
            }
        } while (retry);
        if (getPid() == null) {
            log.warn("Server stopped.");
        } else {
            log.info("No answer from server, try to kill process " + pid + "...");
            processManager.kill(nuxeoProcess, pid);
            if (getPid() == null) {
                log.warn("Server forcibly stopped.");
            }
        }
    } catch (IOException e) {
        log.error("Could not manage process!", e);
    }
}

From source file:org.apache.nifi.bootstrap.RunNiFi.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void start() throws IOException, InterruptedException {
    final Integer port = getCurrentPort(cmdLogger);
    if (port != null) {
        cmdLogger.info("Apache NiFi is already running, listening to Bootstrap on port " + port);
        return;/*  www  . j  ava2  s.co  m*/
    }

    final File prevLockFile = getLockFile(cmdLogger);
    if (prevLockFile.exists() && !prevLockFile.delete()) {
        cmdLogger.warn("Failed to delete previous lock file {}; this file should be cleaned up manually",
                prevLockFile);
    }

    final ProcessBuilder builder = new ProcessBuilder();

    if (!bootstrapConfigFile.exists()) {
        throw new FileNotFoundException(bootstrapConfigFile.getAbsolutePath());
    }

    final Properties properties = new Properties();
    try (final FileInputStream fis = new FileInputStream(bootstrapConfigFile)) {
        properties.load(fis);
    }

    final Map<String, String> props = new HashMap<>();
    props.putAll((Map) properties);

    final String specifiedWorkingDir = props.get("working.dir");
    if (specifiedWorkingDir != null) {
        builder.directory(new File(specifiedWorkingDir));
    }

    final File bootstrapConfigAbsoluteFile = bootstrapConfigFile.getAbsoluteFile();
    final File binDir = bootstrapConfigAbsoluteFile.getParentFile();
    final File workingDir = binDir.getParentFile();

    if (specifiedWorkingDir == null) {
        builder.directory(workingDir);
    }

    final String nifiLogDir = replaceNull(System.getProperty("org.apache.nifi.bootstrap.config.log.dir"),
            DEFAULT_LOG_DIR).trim();

    final String libFilename = replaceNull(props.get("lib.dir"), "./lib").trim();
    File libDir = getFile(libFilename, workingDir);

    final String confFilename = replaceNull(props.get("conf.dir"), "./conf").trim();
    File confDir = getFile(confFilename, workingDir);

    String nifiPropsFilename = props.get("props.file");
    if (nifiPropsFilename == null) {
        if (confDir.exists()) {
            nifiPropsFilename = new File(confDir, "nifi.properties").getAbsolutePath();
        } else {
            nifiPropsFilename = DEFAULT_CONFIG_FILE;
        }
    }

    nifiPropsFilename = nifiPropsFilename.trim();

    final List<String> javaAdditionalArgs = new ArrayList<>();
    for (final Map.Entry<String, String> entry : props.entrySet()) {
        final String key = entry.getKey();
        final String value = entry.getValue();

        if (key.startsWith("java.arg")) {
            javaAdditionalArgs.add(value);
        }
    }

    final File[] libFiles = libDir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(final File dir, final String filename) {
            return filename.toLowerCase().endsWith(".jar");
        }
    });

    if (libFiles == null || libFiles.length == 0) {
        throw new RuntimeException("Could not find lib directory at " + libDir.getAbsolutePath());
    }

    final File[] confFiles = confDir.listFiles();
    if (confFiles == null || confFiles.length == 0) {
        throw new RuntimeException("Could not find conf directory at " + confDir.getAbsolutePath());
    }

    final List<String> cpFiles = new ArrayList<>(confFiles.length + libFiles.length);
    cpFiles.add(confDir.getAbsolutePath());
    for (final File file : libFiles) {
        cpFiles.add(file.getAbsolutePath());
    }

    final StringBuilder classPathBuilder = new StringBuilder();
    for (int i = 0; i < cpFiles.size(); i++) {
        final String filename = cpFiles.get(i);
        classPathBuilder.append(filename);
        if (i < cpFiles.size() - 1) {
            classPathBuilder.append(File.pathSeparatorChar);
        }
    }

    final String classPath = classPathBuilder.toString();
    String javaCmd = props.get("java");
    if (javaCmd == null) {
        javaCmd = DEFAULT_JAVA_CMD;
    }
    if (javaCmd.equals(DEFAULT_JAVA_CMD)) {
        String javaHome = System.getenv("JAVA_HOME");
        if (javaHome != null) {
            String fileExtension = isWindows() ? ".exe" : "";
            File javaFile = new File(
                    javaHome + File.separatorChar + "bin" + File.separatorChar + "java" + fileExtension);
            if (javaFile.exists() && javaFile.canExecute()) {
                javaCmd = javaFile.getAbsolutePath();
            }
        }
    }

    final NiFiListener listener = new NiFiListener();
    final int listenPort = listener.start(this);

    final List<String> cmd = new ArrayList<>();

    cmd.add(javaCmd);
    cmd.add("-classpath");
    cmd.add(classPath);
    cmd.addAll(javaAdditionalArgs);
    cmd.add("-Dnifi.properties.file.path=" + nifiPropsFilename);
    cmd.add("-Dnifi.bootstrap.listen.port=" + listenPort);
    cmd.add("-Dapp=NiFi");
    cmd.add("-Dorg.apache.nifi.bootstrap.config.log.dir=" + nifiLogDir);
    cmd.add("org.apache.nifi.NiFi");
    if (props.containsKey(NIFI_BOOTSTRAP_SENSITIVE_KEY)
            && !StringUtils.isBlank(props.get(NIFI_BOOTSTRAP_SENSITIVE_KEY))) {
        cmd.add("-k " + props.get(NIFI_BOOTSTRAP_SENSITIVE_KEY));
    }

    builder.command(cmd);

    final StringBuilder cmdBuilder = new StringBuilder();
    for (final String s : cmd) {
        // Mask the key
        if (s.startsWith("-k ")) {
            cmdBuilder.append("-k ****");
        } else {
            cmdBuilder.append(s).append(" ");
        }
    }

    cmdLogger.info("Starting Apache NiFi...");
    cmdLogger.info("Working Directory: {}", workingDir.getAbsolutePath());
    cmdLogger.info("Command: {}", cmdBuilder.toString());

    String gracefulShutdown = props.get(GRACEFUL_SHUTDOWN_PROP);
    if (gracefulShutdown == null) {
        gracefulShutdown = DEFAULT_GRACEFUL_SHUTDOWN_VALUE;
    }

    final int gracefulShutdownSeconds;
    try {
        gracefulShutdownSeconds = Integer.parseInt(gracefulShutdown);
    } catch (final NumberFormatException nfe) {
        throw new NumberFormatException("The '" + GRACEFUL_SHUTDOWN_PROP
                + "' property in Bootstrap Config File " + bootstrapConfigAbsoluteFile.getAbsolutePath()
                + " has an invalid value. Must be a non-negative integer");
    }

    if (gracefulShutdownSeconds < 0) {
        throw new NumberFormatException("The '" + GRACEFUL_SHUTDOWN_PROP
                + "' property in Bootstrap Config File " + bootstrapConfigAbsoluteFile.getAbsolutePath()
                + " has an invalid value. Must be a non-negative integer");
    }

    Process process = builder.start();
    handleLogging(process);
    Long pid = getPid(process, cmdLogger);
    if (pid == null) {
        cmdLogger.info("Launched Apache NiFi but could not determined the Process ID");
    } else {
        nifiPid = pid;
        final Properties pidProperties = new Properties();
        pidProperties.setProperty(PID_KEY, String.valueOf(nifiPid));
        savePidProperties(pidProperties, cmdLogger);
        cmdLogger.info("Launched Apache NiFi with Process ID " + pid);
    }

    shutdownHook = new ShutdownHook(process, this, secretKey, gracefulShutdownSeconds, loggingExecutor);
    final Runtime runtime = Runtime.getRuntime();
    runtime.addShutdownHook(shutdownHook);

    final String hostname = getHostname();
    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
    String now = sdf.format(System.currentTimeMillis());
    String user = System.getProperty("user.name");
    if (user == null || user.trim().isEmpty()) {
        user = "Unknown User";
    }
    serviceManager.notify(NotificationType.NIFI_STARTED, "NiFi Started on Host " + hostname,
            "Hello,\n\nApache NiFi has been started on host " + hostname + " at " + now + " by user " + user);

    while (true) {
        final boolean alive = isAlive(process);

        if (alive) {
            try {
                Thread.sleep(1000L);
            } catch (final InterruptedException ie) {
            }
        } else {
            try {
                runtime.removeShutdownHook(shutdownHook);
            } catch (final IllegalStateException ise) {
                // happens when already shutting down
            }

            now = sdf.format(System.currentTimeMillis());
            if (autoRestartNiFi) {
                final File statusFile = getStatusFile(defaultLogger);
                if (!statusFile.exists()) {
                    defaultLogger.info("Status File no longer exists. Will not restart NiFi");
                    return;
                }

                final File lockFile = getLockFile(defaultLogger);
                if (lockFile.exists()) {
                    defaultLogger.info("A shutdown was initiated. Will not restart NiFi");
                    return;
                }

                final boolean previouslyStarted = getNifiStarted();
                if (!previouslyStarted) {
                    defaultLogger.info("NiFi never started. Will not restart NiFi");
                    return;
                } else {
                    setNiFiStarted(false);
                }

                defaultLogger.warn("Apache NiFi appears to have died. Restarting...");
                process = builder.start();
                handleLogging(process);

                pid = getPid(process, defaultLogger);
                if (pid == null) {
                    cmdLogger.info("Launched Apache NiFi but could not obtain the Process ID");
                } else {
                    nifiPid = pid;
                    final Properties pidProperties = new Properties();
                    pidProperties.setProperty(PID_KEY, String.valueOf(nifiPid));
                    savePidProperties(pidProperties, defaultLogger);
                    cmdLogger.info("Launched Apache NiFi with Process ID " + pid);
                }

                shutdownHook = new ShutdownHook(process, this, secretKey, gracefulShutdownSeconds,
                        loggingExecutor);
                runtime.addShutdownHook(shutdownHook);

                final boolean started = waitForStart();

                if (started) {
                    defaultLogger.info("Successfully started Apache NiFi{}",
                            (pid == null ? "" : " with PID " + pid));
                    // We are expected to restart nifi, so send a notification that it died. If we are not restarting nifi,
                    // then this means that we are intentionally stopping the service.
                    serviceManager.notify(NotificationType.NIFI_DIED, "NiFi Died on Host " + hostname,
                            "Hello,\n\nIt appears that Apache NiFi has died on host " + hostname + " at " + now
                                    + "; automatically restarting NiFi");
                } else {
                    defaultLogger.error("Apache NiFi does not appear to have started");
                    // We are expected to restart nifi, so send a notification that it died. If we are not restarting nifi,
                    // then this means that we are intentionally stopping the service.
                    serviceManager.notify(NotificationType.NIFI_DIED, "NiFi Died on Host " + hostname,
                            "Hello,\n\nIt appears that Apache NiFi has died on host " + hostname + " at " + now
                                    + ". Attempted to restart NiFi but the services does not appear to have restarted!");
                }
            } else {
                return;
            }
        }
    }
}