Example usage for java.lang Runtime removeShutdownHook

List of usage examples for java.lang Runtime removeShutdownHook

Introduction

In this page you can find the example usage for java.lang Runtime removeShutdownHook.

Prototype

public boolean removeShutdownHook(Thread hook) 

Source Link

Document

De-registers a previously-registered virtual-machine shutdown hook.

Usage

From source file:Message.java

public static void main(String[] args) {
    try {/*from   w  w w  . j  a v a 2s.co  m*/
        Message p = new Message();
        // register Message as shutdown hook
        Runtime runTime = Runtime.getRuntime();
        runTime.addShutdownHook(p);

        // remove the hook
        runTime.removeShutdownHook(p);

        System.out.println("Program is closing...");

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:it.sauronsoftware.jave.FFMPEGExecutor.java

/**
 * If there's a ffmpeg execution in progress, it kills it.
 *///from  w w w  .ja v  a2  s  .co m
public void destroy() {
    if (inputStream != null) {
        try {
            inputStream.close();
        } catch (Throwable t) {
            _log.warn("Error closing input stream", t);
        }
        inputStream = null;
    }
    if (outputStream != null) {
        try {
            outputStream.close();
        } catch (Throwable t) {
            _log.warn("Error closing output stream", t);
        }
        outputStream = null;
    }
    if (errorStream != null) {
        try {
            errorStream.close();
        } catch (Throwable t) {
            _log.warn("Error closing error stream", t);
        }
        errorStream = null;
    }
    if (ffmpeg != null) {
        ffmpeg.destroy();
        ffmpeg = null;
    }
    if (ffmpegKiller != null) {
        Runtime runtime = Runtime.getRuntime();
        runtime.removeShutdownHook(ffmpegKiller);
        ffmpegKiller = null;
    }
}

From source file:com.appcel.core.encoder.executor.FfmpegEncoderExecutor.java

/**
 * If there's a ffmpeg execution in progress, it kills it.
 *///from   ww  w.  ja v  a  2s.  c  om
public void destroy() {
    if (inputStream != null) {
        try {
            inputStream.close();
        } catch (Throwable t) {
            ;
        }
        inputStream = null;
    }
    if (outputStream != null) {
        try {
            outputStream.close();
        } catch (Throwable t) {
            ;
        }
        outputStream = null;
    }
    if (errorStream != null) {
        try {
            errorStream.close();
        } catch (Throwable t) {
            ;
        }
        errorStream = null;
    }
    if (ffmpeg != null) {
        ffmpeg.destroy();
        ffmpeg = null;
    }
    if (ffmpegKiller != null) {
        Runtime runtime = Runtime.getRuntime();
        runtime.removeShutdownHook(ffmpegKiller);
        ffmpegKiller = null;
    }
    if (null != args) {
        args = null;
    }
}

From source file:org.acmsl.queryj.api.AbstractTemplate.java

/**
 * Prints a log message displaying ClassLoader issues related
 * to ANTLR.jar and StringTemplate.jar.//ww  w.  j  a  v  a  2 s  . co  m
 */
@SuppressWarnings("unused")
protected synchronized void traceClassLoaders() {
    @NotNull
    final FinalizingThread t_FinalizingThread = FinalizingThreadSingletonContainer.getInstance();

    if (t_FinalizingThread.isNew()) {
        @Nullable
        final Runtime t_Runtime = Runtime.getRuntime();

        if (t_Runtime != null) {
            t_Runtime.removeShutdownHook(t_FinalizingThread);
            t_Runtime.addShutdownHook(t_FinalizingThread);
        }
    }
}

From source file:org.acmsl.queryj.api.AbstractTemplate.java

/**
 * Cleans up the thread to trace class loaders on shutdown.
 *//*from  www . j a va  2s  .co  m*/
@SuppressWarnings("unused")
protected void cleanUpClassLoaderTracing() {
    @NotNull
    final FinalizingThread t_FinalizingThread = FinalizingThreadSingletonContainer.getInstance();

    @Nullable
    final Runtime t_Runtime = Runtime.getRuntime();

    if (t_Runtime != null) {
        t_Runtime.removeShutdownHook(t_FinalizingThread);
    }
}

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;/*from   www .  j a  v a 2s  .  c  om*/
    }

    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;
            }
        }
    }
}

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

@SuppressWarnings({ "rawtypes", "unchecked" })
public void start() throws IOException, InterruptedException {

    final String confDir = getBootstrapProperties().getProperty(CONF_DIR_KEY);
    final File configFile = new File(getBootstrapProperties().getProperty(MINIFI_CONFIG_FILE_KEY));
    try (InputStream inputStream = new FileInputStream(configFile)) {
        ByteBuffer tempConfigFile = performTransformation(inputStream, confDir);
        currentConfigFileReference.set(tempConfigFile.asReadOnlyBuffer());
    } catch (ConfigurationChangeException e) {
        defaultLogger.error("The config file is malformed, unable to start.", e);
        return;/*from   w  w  w. j a  va 2s .c om*/
    }

    // Instantiate configuration listener and configured ingestors
    this.changeListener = new MiNiFiConfigurationChangeListener(this, defaultLogger);
    this.periodicStatusReporters = initializePeriodicNotifiers();
    startPeriodicNotifiers();
    try {
        this.changeCoordinator = initializeNotifier(this.changeListener);
    } catch (Exception e) {
        final String errorMsg = "Unable to start as {} is not properly configured due to: {}";
        cmdLogger.error(errorMsg, this.changeListener.getDescriptor(), e.getMessage());
        defaultLogger.error("Unable to initialize notifier.", e);
        // if we fail to initialize, exit without attempting to start
        System.exit(1);
    }

    Tuple<ProcessBuilder, Process> tuple = startMiNiFi();
    if (tuple == null) {
        cmdLogger.info("Start method returned null, ending start command.");
        return;
    }

    ProcessBuilder builder = tuple.getKey();
    Process process = tuple.getValue();

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

            if (alive) {
                try {
                    Thread.sleep(1000L);

                    if (reloading.get() && getNifiStarted()) {
                        final File swapConfigFile = getSwapFile(defaultLogger);
                        if (swapConfigFile.exists()) {
                            defaultLogger.info(
                                    "MiNiFi has finished reloading successfully and swap file exists. Deleting old configuration.");

                            if (swapConfigFile.delete()) {
                                defaultLogger.info("Swap file was successfully deleted.");
                            } else {
                                defaultLogger
                                        .error("Swap file was not deleted. It should be deleted manually.");
                            }
                        }

                        reloading.set(false);
                    }

                } catch (final InterruptedException ie) {
                }
            } else {
                final Runtime runtime = Runtime.getRuntime();
                try {
                    runtime.removeShutdownHook(shutdownHook);
                } catch (final IllegalStateException ise) {
                    // happens when already shutting down
                }

                if (autoRestartNiFi) {
                    final File statusFile = getStatusFile(defaultLogger);
                    if (!statusFile.exists()) {
                        defaultLogger.info("Status File no longer exists. Will not restart MiNiFi");
                        return;
                    }

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

                    final File reloadFile = getReloadFile(defaultLogger);
                    if (reloadFile.exists()) {
                        defaultLogger.info("Currently reloading configuration. Will wait to restart MiNiFi.");
                        Thread.sleep(5000L);
                        continue;
                    }

                    final boolean previouslyStarted = getNifiStarted();
                    if (!previouslyStarted) {
                        final File swapConfigFile = getSwapFile(defaultLogger);
                        if (swapConfigFile.exists()) {
                            defaultLogger.info(
                                    "Swap file exists, MiNiFi failed trying to change configuration. Reverting to old configuration.");

                            try {
                                ByteBuffer tempConfigFile = performTransformation(
                                        new FileInputStream(swapConfigFile), confDir);
                                currentConfigFileReference.set(tempConfigFile.asReadOnlyBuffer());
                            } catch (ConfigurationChangeException e) {
                                defaultLogger.error(
                                        "The swap file is malformed, unable to restart from prior state. Will not attempt to restart MiNiFi. Swap File should be cleaned up manually.");
                                return;
                            }

                            Files.copy(swapConfigFile.toPath(),
                                    Paths.get(getBootstrapProperties().getProperty(MINIFI_CONFIG_FILE_KEY)),
                                    REPLACE_EXISTING);

                            defaultLogger.info("Replacing config file with swap file and deleting swap file");
                            if (!swapConfigFile.delete()) {
                                defaultLogger.warn(
                                        "The swap file failed to delete after replacing using it to revert to the old configuration. It should be cleaned up manually.");
                            }
                            reloading.set(false);
                        } else {
                            defaultLogger.info(
                                    "MiNiFi either never started or failed to restart. Will not attempt to restart MiNiFi");
                            return;
                        }
                    } else {
                        setNiFiStarted(false);
                    }

                    process = builder.start();
                    handleLogging(process);

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

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

                    final boolean started = waitForStart();

                    if (started) {
                        defaultLogger.info("Successfully spawned the thread to start Apache MiNiFi{}",
                                (pid == null ? "" : " with PID " + pid));
                    } else {
                        defaultLogger.error("Apache MiNiFi does not appear to have started");
                    }
                } else {
                    return;
                }
            }
        }
    } finally {
        shutdownChangeNotifier();
        shutdownPeriodicStatusReporters();
    }
}

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;/* ww w  .ja v a 2  s .com*/
    }

    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.formic.util.CommandExecutor.java

/**
 * Run the thread.//www  . j a  v  a2 s  .  c o  m
 */
public void run() {
    logger.info(this.toString());
    Runtime runtime = Runtime.getRuntime();
    try {
        process = runtime.exec(cmd);

        shutdownHook = new ShutdownHook();
        try {
            runtime.addShutdownHook(shutdownHook);
        } catch (IllegalStateException ignore) {
            // happens if this is called during shutdown
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Thread outThread = createOutThread(out);
        outThread.start();

        ByteArrayOutputStream err = new ByteArrayOutputStream();
        Thread errThread = createErrThread(err);
        errThread.start();

        returnCode = process.waitFor();
        outThread.join(1000);
        errThread.join(1000);

        if (result == null) {
            result = out.toString();
        }
        if (error == null) {
            error = err.toString();
        }
    } catch (Exception e) {
        returnCode = 12;
        error = e.getMessage();
        e.printStackTrace();
    } finally {
        if (shutdownHook != null) {
            try {
                runtime.removeShutdownHook(shutdownHook);
            } catch (IllegalStateException ignore) {
                // happens if this is called during shutdown
            }
        }
    }
}