Example usage for java.io File canExecute

List of usage examples for java.io File canExecute

Introduction

In this page you can find the example usage for java.io File canExecute.

Prototype

public boolean canExecute() 

Source Link

Document

Tests whether the application can execute the file denoted by this abstract pathname.

Usage

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;//from  w ww  . j av  a 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.rhq.modules.plugins.wildfly10.BaseServerComponent.java

private List<String> validateStartScriptPluginConfigProps() {
    List<String> errors = new ArrayList<String>();

    File startScriptFile = getStartScriptFile();

    if (!startScriptFile.exists()) {
        errors.add("Start script '" + startScriptFile + "' does not exist.");
    } else {//from ww w  .  j  av  a2 s  .  com
        if (!startScriptFile.isFile()) {
            errors.add("Start script '" + startScriptFile + "' is not a regular file.");
        } else {
            if (!startScriptFile.canRead()) {
                errors.add("Start script '" + startScriptFile + "' is not readable.");
            }
            if (!startScriptFile.canExecute()) {
                errors.add("Start script '" + startScriptFile + "' is not executable.");
            }
        }
    }

    return errors;
}

From source file:org.jini.commands.files.FindFiles.java

/**
 * Search for files with specific extensions
 *
 * @param dirName//from  ww w  .j a  va2s.  c  o m
 * @param extensions
 * @param recursive
 */
void findFileWithExtension(String dirName, String[] extensions, boolean recursive) {
    PrintChar printChar = new PrintChar();
    printChar.setOutPutChar(">");

    if ((this.getJcError() == false) && (this.isDir(dirName) == false)) {
        this.setJcError(true);
        this.addErrorMessages("Error : Directory [" + dirName + "] does not exsist.");
    }

    if (this.getJcError() == false) {
        printChar.start();
        File root = new File(dirName);

        try {
            Collection files = FileUtils.listFiles(root, extensions, recursive);

            TablePrinter tableF = new TablePrinter("Name", "Type", "Readable", "Writable", "Executable",
                    "Size KB", "Size MB", "Last Modified");

            for (Iterator iterator = files.iterator(); iterator.hasNext();) {
                File file = (File) iterator.next();

                if (this.withDetails == false) {
                    System.out.println(file.getAbsolutePath());
                } else {

                    java.util.Date lastModified = new java.util.Date(file.lastModified());
                    long filesizeInKB = file.length() / 1024;
                    double bytes = file.length();
                    double kilobytes = (bytes / 1024);
                    double megabytes = (kilobytes / 1024);

                    String type = "";

                    DecimalFormat df = new DecimalFormat("####.####");

                    if (file.isDirectory()) {
                        type = "Dir";
                    }
                    if (file.isFile()) {
                        type = "File";
                    }

                    if (file.isFile() && file.isHidden()) {
                        type = "File (Hidden)";
                    }
                    if (file.isDirectory() && (file.isHidden())) {
                        type = "Dir (Hidden)";
                    }

                    String canExec = "" + file.canExecute();
                    String canRead = "" + file.canRead();
                    String canWrite = "" + file.canWrite();
                    String filesizeInKBStr = Long.toString(filesizeInKB);
                    String filesizeInMBStr = df.format(megabytes);

                    tableF.addRow(file.getAbsolutePath(), type, canRead, canWrite, canExec, filesizeInKBStr,
                            filesizeInMBStr, lastModified.toString());
                }
            }

            if (this.withDetails == true) {
                if (files.isEmpty() == false) {
                    tableF.print();
                }
            }

            printChar.setStopPrinting(true);
        } catch (Exception e) {
            this.setJcError(true);
            this.addErrorMessages("Error : " + e.toString());
        }
    }

    this.done = true;
}

From source file:org.rhq.enterprise.server.core.StartupBean.java

private void checkTempDir() {
    File tmpDir = new File(System.getProperty("java.io.tmpdir"));
    if (!tmpDir.exists()) {
        log.warn("Invalid java.io.tmpdir: [" + tmpDir.getAbsolutePath() + "] does not exist.");
        try {//from w  ww .ja  va 2 s. c  o m
            log.info("Creating java.io.tmpdir: [" + tmpDir.getAbsolutePath() + "]");
            tmpDir.mkdir();
        } catch (Throwable t) {
            throw new RuntimeException("Startup failed: Could not create missing java.io.tmpdir ["
                    + tmpDir.getAbsolutePath() + "]", t);
        }
    }
    if (!tmpDir.isDirectory()) {
        throw new RuntimeException(
                "Startup failed: java.io.tmpdir [" + tmpDir.getAbsolutePath() + "] is not a directory");
    }
    if (!tmpDir.canRead() || !tmpDir.canExecute()) {
        throw new RuntimeException(
                "Startup failed: java.io.tmpdir [" + tmpDir.getAbsolutePath() + "] is not readable");
    }
    if (!tmpDir.canWrite()) {
        throw new RuntimeException(
                "Startup failed: java.io.tmpdir [" + tmpDir.getAbsolutePath() + "] is not writable");
    }
}

From source file:com.linkedin.harisekhon.Utils.java

public static final String validateProgramPath(String path, String name, String regex) {
    String name2 = requireName(name).trim();
    if (path == null) {
        throw new IllegalArgumentException(name2 + " path not defined (null)");
    }//w ww  .  ja  v  a2s. c  om
    String path2 = path.trim();
    if (path2.isEmpty()) {
        throw new IllegalArgumentException(name2 + " path not defined (blank)");
    }
    if (!path2.matches("^[./]")) {
        try {
            path2 = which(path2);
        } catch (IOException e) {
            //                throw new IllegalArgumentException(name + " program not found in $PATH (" + System.getenv("PATH") + ")");
            throw new IllegalArgumentException(e.getMessage());
        }
    }
    String regex2;
    if (regex == null || regex.trim().isEmpty()) {
        regex2 = name2;
    } else {
        regex2 = regex.trim();
    }
    if (validateRegex(regex2, "program path regex", true) == null) {
        throw new IllegalArgumentException("invalid regex given to validateProgramPath()");
    }
    validateFilename(path2, null, true);
    //        if(validateFilename(path, null, true) == null){
    //            throw new IllegalArgumentException("invalid path given for " + name + ", failed filename regex");
    //        }
    if (!path2.matches("(?:^|.*/)" + regex2 + "$")) {
        throw new IllegalArgumentException(
                "invalid path given for " + name2 + ", is not a path to the " + name2 + " command");
    }
    File f = new File(path2);
    if (!(f.exists() && f.isFile())) {
        throw new IllegalArgumentException(path2 + " not found");
    }
    if (!f.canExecute()) {
        throw new IllegalArgumentException(path2 + " not executable");
    }
    vlogOption(name2 + " program path", path2);
    return path2;
}

From source file:name.martingeisse.ecobuild.moduletool.output.OutputTool.java

protected void handleFile(IModuleToolContext context, State state, String[] segments,
        boolean takeFromSourceTree, String autoSuffix) throws IOException {

    // basic command syntax check
    if (segments.length != 2 && segments.length != 3) {
        context.getLogger().logError("Found 'file' command with " + segments.length + " arguments");
        return;//from www  .ja v a 2  s . c  o m
    }

    // parse the copy-source module path
    final ModulePath copySourceModulePath;
    try {
        copySourceModulePath = new ModulePath(segments[1] + autoSuffix);
    } catch (UserMessageBuildException e) {
        context.getLogger().logError("Found 'file' command with malformed copy-source path. " + e.getMessage());
        return;
    }

    // build the module from which the file shall be copied
    if (!takeFromSourceTree) {
        context.buildDependency(copySourceModulePath.getParent());
    }

    // parse the copy-destination module path
    final ModulePath copyDestinationModulePath;
    if (segments.length == 2) {
        copyDestinationModulePath = null;
    } else {
        try {
            copyDestinationModulePath = new ModulePath(segments[2] + autoSuffix);
        } catch (UserMessageBuildException e) {
            context.getLogger()
                    .logError("Found 'file' command with malformed copy-destination path. " + e.getMessage());
            return;
        }
    }

    // resolve the copy-source path
    File copySourceFilePath;
    try {
        if (takeFromSourceTree) {
            copySourceFilePath = copySourceModulePath.resolve(context.getRootSourceFolder(),
                    context.getModuleSourceFolder());
        } else {
            copySourceFilePath = copySourceModulePath.resolve(context.getRootBuildFolder(),
                    context.getModuleBuildFolder());
        }
    } catch (UserMessageBuildException e) {
        context.getLogger()
                .logError("Found 'file' command with unresolvable copy-source path. " + e.getMessage());
        return;
    }

    // resolve the copy-destination path
    File copyDestinationFilePath;
    if (copyDestinationModulePath != null) {
        try {
            copyDestinationFilePath = copyDestinationModulePath.resolve(context.getMainBuildFolder(),
                    state.currentFolder);
        } catch (UserMessageBuildException e) {
            context.getLogger().logError(
                    "Found 'file' command with unresolvable copy-destination path. " + e.getMessage());
            return;
        }
    } else {
        copyDestinationFilePath = new File(state.currentFolder, copySourceFilePath.getName());
    }

    // copy the file
    try {
        FileUtils.copyFile(copySourceFilePath, copyDestinationFilePath);
        if (copySourceFilePath.canExecute()) {
            copyDestinationFilePath.setExecutable(true);
        }
    } catch (FileNotFoundException e) {
        context.getLogger().logError("Copy failed for 'file' command: " + e.getMessage());
        return;
    } catch (IOException e) {
        context.getLogger().logError("Copy failed for 'file' command. ", e);
        return;
    }

}

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  w w w.  j ava2 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 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:com.amaze.filemanager.ui.views.drawer.Drawer.java

public void refreshDrawer() {
    Menu menu = navView.getMenu();
    menu.clear();/*from www.  j  a v a  2  s.com*/
    actionViewStateManager.deselectCurrentActionView();

    int order = 0;
    ArrayList<String> storageDirectories = mainActivity.getStorageDirectories();
    phoneStorageCount = 0;
    for (String file : storageDirectories) {
        if (file.contains(OTGUtil.PREFIX_OTG)) {
            addNewItem(menu, STORAGES_GROUP, order++, "OTG", new MenuMetadata(file),
                    R.drawable.ic_usb_white_24dp, R.drawable.ic_show_chart_black_24dp);
            continue;
        }

        File f = new File(file);
        String name;
        @DrawableRes
        int icon1;
        if ("/storage/emulated/legacy".equals(file) || "/storage/emulated/0".equals(file)
                || "/mnt/sdcard".equals(file)) {
            name = resources.getString(R.string.storage);
            icon1 = R.drawable.ic_phone_android_white_24dp;
        } else if ("/storage/sdcard1".equals(file)) {
            name = resources.getString(R.string.extstorage);
            icon1 = R.drawable.ic_sd_storage_white_24dp;
        } else if ("/".equals(file)) {
            name = resources.getString(R.string.rootdirectory);
            icon1 = R.drawable.ic_drawer_root_white;
        } else {
            name = f.getName();
            icon1 = R.drawable.ic_sd_storage_white_24dp;
        }

        if (f.isDirectory() || f.canExecute()) {
            addNewItem(menu, STORAGES_GROUP, order++, name, new MenuMetadata(file), icon1,
                    R.drawable.ic_show_chart_black_24dp);
            if (phoneStorageCount == 0)
                firstPath = file;
            else if (phoneStorageCount == 1)
                secondPath = file;

            phoneStorageCount++;
        }
    }
    dataUtils.setStorages(storageDirectories);

    if (dataUtils.getServers().size() > 0) {
        Collections.sort(dataUtils.getServers(), new BookSorter());
        synchronized (dataUtils.getServers()) {
            for (String[] file : dataUtils.getServers()) {
                addNewItem(menu, SERVERS_GROUP, order++, file[0], new MenuMetadata(file[1]),
                        R.drawable.ic_settings_remote_white_24dp, R.drawable.ic_edit_24dp);
            }
        }
    }

    ArrayList<String[]> accountAuthenticationList = new ArrayList<>();

    if (CloudSheetFragment.isCloudProviderAvailable(mainActivity)) {
        for (CloudStorage cloudStorage : dataUtils.getAccounts()) {
            @DrawableRes
            int deleteIcon = R.drawable.ic_delete_grey_24dp;

            if (cloudStorage instanceof Dropbox) {
                addNewItem(menu, CLOUDS_GROUP, order++, CloudHandler.CLOUD_NAME_DROPBOX,
                        new MenuMetadata(CloudHandler.CLOUD_PREFIX_DROPBOX + "/"),
                        R.drawable.ic_dropbox_white_24dp, deleteIcon);

                accountAuthenticationList.add(new String[] { CloudHandler.CLOUD_NAME_DROPBOX,
                        CloudHandler.CLOUD_PREFIX_DROPBOX + "/", });
            } else if (cloudStorage instanceof Box) {
                addNewItem(menu, CLOUDS_GROUP, order++, CloudHandler.CLOUD_NAME_BOX,
                        new MenuMetadata(CloudHandler.CLOUD_PREFIX_BOX + "/"), R.drawable.ic_box_white_24dp,
                        deleteIcon);

                accountAuthenticationList.add(
                        new String[] { CloudHandler.CLOUD_NAME_BOX, CloudHandler.CLOUD_PREFIX_BOX + "/", });
            } else if (cloudStorage instanceof OneDrive) {
                addNewItem(menu, CLOUDS_GROUP, order++, CloudHandler.CLOUD_NAME_ONE_DRIVE,
                        new MenuMetadata(CloudHandler.CLOUD_PREFIX_ONE_DRIVE + "/"),
                        R.drawable.ic_onedrive_white_24dp, deleteIcon);

                accountAuthenticationList.add(new String[] { CloudHandler.CLOUD_NAME_ONE_DRIVE,
                        CloudHandler.CLOUD_PREFIX_ONE_DRIVE + "/", });
            } else if (cloudStorage instanceof GoogleDrive) {
                addNewItem(menu, CLOUDS_GROUP, order++, CloudHandler.CLOUD_NAME_GOOGLE_DRIVE,
                        new MenuMetadata(CloudHandler.CLOUD_PREFIX_GOOGLE_DRIVE + "/"),
                        R.drawable.ic_google_drive_white_24dp, deleteIcon);

                accountAuthenticationList.add(new String[] { CloudHandler.CLOUD_NAME_GOOGLE_DRIVE,
                        CloudHandler.CLOUD_PREFIX_GOOGLE_DRIVE + "/", });
            }
        }
        Collections.sort(accountAuthenticationList, new BookSorter());
    }

    if (mainActivity.getBoolean(PREFERENCE_SHOW_SIDEBAR_FOLDERS)) {
        if (dataUtils.getBooks().size() > 0) {

            Collections.sort(dataUtils.getBooks(), new BookSorter());

            synchronized (dataUtils.getBooks()) {
                for (String[] file : dataUtils.getBooks()) {
                    addNewItem(menu, FOLDERS_GROUP, order++, file[0], new MenuMetadata(file[1]),
                            R.drawable.ic_folder_white_24dp, R.drawable.ic_edit_24dp);
                }
            }
        }
    }

    Boolean[] quickAccessPref = TinyDB.getBooleanArray(mainActivity.getPrefs(), QuickAccessPref.KEY,
            QuickAccessPref.DEFAULT);

    if (mainActivity.getBoolean(PREFERENCE_SHOW_SIDEBAR_QUICKACCESSES)) {
        if (quickAccessPref[0]) {
            addNewItem(menu, QUICKACCESSES_GROUP, order++, R.string.quick, new MenuMetadata("5"),
                    R.drawable.ic_star_white_24dp, null);
        }
        if (quickAccessPref[1]) {
            addNewItem(menu, QUICKACCESSES_GROUP, order++, R.string.recent, new MenuMetadata("6"),
                    R.drawable.ic_history_white_24dp, null);
        }
        if (quickAccessPref[2]) {
            addNewItem(menu, QUICKACCESSES_GROUP, order++, R.string.images, new MenuMetadata("0"),
                    R.drawable.ic_photo_library_white_24dp, null);
        }
        if (quickAccessPref[3]) {
            addNewItem(menu, QUICKACCESSES_GROUP, order++, R.string.videos, new MenuMetadata("1"),
                    R.drawable.ic_video_library_white_24dp, null);
        }
        if (quickAccessPref[4]) {
            addNewItem(menu, QUICKACCESSES_GROUP, order++, R.string.audio, new MenuMetadata("2"),
                    R.drawable.ic_library_music_white_24dp, null);
        }
        if (quickAccessPref[5]) {
            addNewItem(menu, QUICKACCESSES_GROUP, order++, R.string.documents, new MenuMetadata("3"),
                    R.drawable.ic_library_books_white_24dp, null);
        }
        if (quickAccessPref[6]) {
            addNewItem(menu, QUICKACCESSES_GROUP, order++, R.string.apks, new MenuMetadata("4"),
                    R.drawable.ic_apk_library_white_24dp, null);
        }
    }

    addNewItem(menu, LASTGROUP, order++, R.string.ftp, new MenuMetadata(() -> {
        FragmentTransaction transaction2 = mainActivity.getSupportFragmentManager().beginTransaction();
        transaction2.replace(R.id.content_frame, new FtpServerFragment());
        mainActivity.getAppbar().getAppbarLayout().animate().translationY(0)
                .setInterpolator(new DecelerateInterpolator(2)).start();
        pending_fragmentTransaction = transaction2;
        if (!isDrawerLocked)
            close();
        else
            onDrawerClosed();
    }), R.drawable.ic_ftp_white_24dp, null);

    addNewItem(menu, LASTGROUP, order++, R.string.apps, new MenuMetadata(() -> {
        FragmentTransaction transaction2 = mainActivity.getSupportFragmentManager().beginTransaction();
        transaction2.replace(R.id.content_frame, new AppsListFragment());
        mainActivity.getAppbar().getAppbarLayout().animate().translationY(0)
                .setInterpolator(new DecelerateInterpolator(2)).start();
        pending_fragmentTransaction = transaction2;
        if (!isDrawerLocked)
            close();
        else
            onDrawerClosed();
    }), R.drawable.ic_android_white_24dp, null);

    addNewItem(menu, LASTGROUP, order++, R.string.setting, new MenuMetadata(() -> {
        Intent in = new Intent(mainActivity, PreferencesActivity.class);
        mainActivity.startActivity(in);
        mainActivity.finish();
    }), R.drawable.ic_settings_white_24dp, null);

    for (int i = 0; i < navView.getMenu().size(); i++) {
        navView.getMenu().getItem(i).setEnabled(true);
    }

    for (int group : GROUPS) {
        menu.setGroupCheckable(group, true, true);
    }

    MenuItem item = navView.getSelected();
    if (item != null) {
        item.setChecked(true);
        actionViewStateManager.selectActionView(item);
        isSomethingSelected = true;
    }
}

From source file:org.kepler.ssh.LocalExec.java

/**
 * Copies src file to dst file. If the dst file does not exist, it is
 * created/*from www .j  a v a 2s . c o  m*/
 */
private void copyFile(File src, File dst) throws IOException {
    // see if source and destination are the same
    if (src.equals(dst)) {
        // do not copy
        return;
    }

    //System.out.println("copying " + src + " to " + dst);

    FileChannel srcChannel = new FileInputStream(src).getChannel();
    FileChannel dstChannel = new FileOutputStream(dst).getChannel();
    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
    srcChannel.close();
    dstChannel.close();

    /* hacking for non-windows */
    // set the permission of the target file the same as the source file
    if (_commandArr[0] == "/bin/sh") {

        String osName = StringUtilities.getProperty("os.name");
        if (osName.startsWith("Mac OS X")) {

            // chmod --reference does not exist on mac, so do the best
            // we can using the java file api
            // WARNING: this relies on the umask to set the group, world
            // permissions.
            dst.setExecutable(src.canExecute());
            dst.setWritable(src.canWrite());

        } else {

            String cmd = "chmod --reference=" + src.getAbsolutePath() + " " + dst.getAbsolutePath();
            try {
                ByteArrayOutputStream streamOut = new ByteArrayOutputStream();
                ByteArrayOutputStream streamErr = new ByteArrayOutputStream();
                executeCmd(cmd, streamOut, streamErr);
            } catch (ExecException e) {
                log.warn("Tried to set the target file permissions the same as "
                        + "the source but the command failed: " + cmd + "\n" + e);
            }
        }
    }
}

From source file:net.rim.ejde.internal.packaging.PackagingManager.java

private String getRAPCPath() {
    String rapcPath = IConstants.EMPTY_STRING;
    try {/*  w  w w  .  ja  v a  2s .  c o m*/
        IVMInstall vm = null;
        if (_bbProject.getProject().hasNature(BlackBerryProjectCoreNature.NATURE_ID)) {
            vm = JavaRuntime.getVMInstall(_bbProject);
        } else {
            // for java proejct, we use the default BB jre
            vm = VMUtils.getDefaultBBVM();
        }
        if (vm != null) {
            File vmLocation = vm.getInstallLocation();
            IPath vmPath = new Path(vmLocation.getPath());
            vmPath = vmPath.append("bin");
            if (OSUtils.isWindows()) {
                vmPath = vmPath.append("rapc.exe");
            } else {
                // Make sure preverify is in executable state
                File f = null;
                if ((f = new File(vmPath + File.separator + IConstants.PREVERIFY_FILE_NAME)).exists()) {
                    if (!f.canExecute()) {
                        f.setExecutable(true);
                    }
                }
                // invoke rapc.jar instead of rapc.exe
                vmPath = vmPath.append("rapc.jar");
            }
            rapcPath = vmPath.toOSString();
        } else {
            throw ProblemFactory.create_VM_MISSING_exception(_bbProject.getElementName());
        }
    } catch (CoreException e) {
        _log.error("getRapcPath: " + e.getMessage());
    }
    return rapcPath;
}