Example usage for java.lang NumberFormatException NumberFormatException

List of usage examples for java.lang NumberFormatException NumberFormatException

Introduction

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

Prototype

public NumberFormatException(String s) 

Source Link

Document

Constructs a NumberFormatException with the specified detail message.

Usage

From source file:com.google.android.gms.internal.zzbti.java

public int nextInt() throws IOException {
    int i = this.zzcpK;
    if (i == 0) {
        i = zzacd();//w  ww  . j a v a 2s  .c o  m
    }
    int[] iArr;
    int i2;
    if (i == 15) {
        i = (int) this.zzcpL;
        if (this.zzcpL != ((long) i)) {
            long j = this.zzcpL;
            int lineNumber = getLineNumber();
            int columnNumber = getColumnNumber();
            String path = getPath();
            throw new NumberFormatException(new StringBuilder(String.valueOf(path).length() + 89)
                    .append("Expected an int but was ").append(j).append(" at line ").append(lineNumber)
                    .append(" column ").append(columnNumber).append(" path ").append(path).toString());
        }
        this.zzcpK = 0;
        iArr = this.zzcpR;
        i2 = this.zzcpP - 1;
        iArr[i2] = iArr[i2] + 1;
    } else {
        String valueOf;
        int columnNumber2;
        String path2;
        if (i == 16) {
            this.zzcpN = new String(this.zzcpH, this.pos, this.zzcpM);
            this.pos += this.zzcpM;
        } else if (i == 8 || i == 9) {
            this.zzcpN = zzd(i == 8 ? '\'' : '\"');
            try {
                i = Integer.parseInt(this.zzcpN);
                this.zzcpK = 0;
                iArr = this.zzcpR;
                i2 = this.zzcpP - 1;
                iArr[i2] = iArr[i2] + 1;
            } catch (NumberFormatException e) {
            }
        } else {
            valueOf = String.valueOf(zzabQ());
            i2 = getLineNumber();
            columnNumber2 = getColumnNumber();
            path2 = getPath();
            throw new IllegalStateException(
                    new StringBuilder((String.valueOf(valueOf).length() + 69) + String.valueOf(path2).length())
                            .append("Expected an int but was ").append(valueOf).append(" at line ").append(i2)
                            .append(" column ").append(columnNumber2).append(" path ").append(path2)
                            .toString());
        }
        this.zzcpK = 11;
        double parseDouble = Double.parseDouble(this.zzcpN);
        i = (int) parseDouble;
        if (((double) i) != parseDouble) {
            valueOf = this.zzcpN;
            i2 = getLineNumber();
            columnNumber2 = getColumnNumber();
            path2 = getPath();
            throw new NumberFormatException(
                    new StringBuilder((String.valueOf(valueOf).length() + 69) + String.valueOf(path2).length())
                            .append("Expected an int but was ").append(valueOf).append(" at line ").append(i2)
                            .append(" column ").append(columnNumber2).append(" path ").append(path2)
                            .toString());
        }
        this.zzcpN = null;
        this.zzcpK = 0;
        iArr = this.zzcpR;
        i2 = this.zzcpP - 1;
        iArr[i2] = iArr[i2] + 1;
    }
    return i;
}

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.ja va 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 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.lockss.util.NumberUtil.java

/**
 * Returns an integer from a String array representing a number in
 * the Roman number system. The number must be in the range 0 - 2^31-1.
 * Elements of the array represent individual roman digits, of the 
 * kind returned by {@link #toRomanDigits()}.
 * /*from  w  ww  . j a va  2 s . c om*/
 * @param tokens the array of roman tokens
 * @return the integer value
 */
public static int parseRomanDigits(String[] tokens) {
    if ((tokens == null) || (tokens.length == 0)) {
        throw new IllegalArgumentException();
    }
    // special-case "N" (nulla) as 0
    if ((tokens.length == 1) && "N".equals(tokens[0])) {
        return 0;
    }
    int romanValue = 0;
    for (String s : tokens) {
        int parenCount = s.lastIndexOf('(') + 1;
        String token = s.substring(parenCount, s.length() - parenCount);
        Integer val = romanToNum.get(token);
        if (val == null) {
            throw new NumberFormatException("Not a roman digit: " + s);
        }
        // scale value by paren count
        int n = val;
        for (int i = 0; i < parenCount; i++)
            n *= 1000;
        romanValue += n;
        if (romanValue <= 0) {
            throw new NumberFormatException("Number out of range.");
        }
    }

    return romanValue;
}

From source file:org.rdkit.knime.wizards.RDKitNodesWizardsPage.java

/**
 * Returns the entered percentage value as double (devided by 100) for
 * pre processing actions.//from  ww  w.j a  va2 s .co  m
 *
 * @return Value between 0 and 1.
 *
 * @throws NumberFormatException Thrown, if the user entered an invalid value in the
 *       text field for the pre-processing percentage.
 */
public double getPreProcessingPercentage() throws NumberFormatException {
    double dPerc = 0.0d;

    if (m_textPreProcPerc != null && m_textPreProcPerc.getEnabled()) {
        dPerc = Double.parseDouble(m_textPreProcPerc.getText().trim()) / 100.0d;
        if (dPerc < 0) {
            throw new NumberFormatException(
                    "Percentage of pre-processing activities must be greater than or equal to 0%.");
        }
        if (dPerc > 1) {
            throw new NumberFormatException(
                    "Percentage of pre-processing activities must be lower than or equal to 100%.");
        }
    }

    return dPerc;
}

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

private int getGracefulShutdownSeconds(Map<String, String> props, File bootstrapConfigAbsoluteFile) {
    String gracefulShutdown = props.get(GRACEFUL_SHUTDOWN_PROP);
    if (gracefulShutdown == null) {
        gracefulShutdown = DEFAULT_GRACEFUL_SHUTDOWN_VALUE;
    }/*from  w w w  .  j a  v a  2  s  . c o m*/

    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");
    }
    return gracefulShutdownSeconds;
}

From source file:com.google.android.gms.internal.zzbti.java

public long nextLong() throws IOException {
    int i = this.zzcpK;
    if (i == 0) {
        i = zzacd();/*  w ww  . j  a va 2  s . co m*/
    }
    if (i == 15) {
        this.zzcpK = 0;
        int[] iArr = this.zzcpR;
        int i2 = this.zzcpP - 1;
        iArr[i2] = iArr[i2] + 1;
        return this.zzcpL;
    }
    long parseLong;
    int i3;
    if (i == 16) {
        this.zzcpN = new String(this.zzcpH, this.pos, this.zzcpM);
        this.pos += this.zzcpM;
    } else if (i == 8 || i == 9) {
        this.zzcpN = zzd(i == 8 ? '\'' : '\"');
        try {
            parseLong = Long.parseLong(this.zzcpN);
            this.zzcpK = 0;
            int[] iArr2 = this.zzcpR;
            i3 = this.zzcpP - 1;
            iArr2[i3] = iArr2[i3] + 1;
            return parseLong;
        } catch (NumberFormatException e) {
        }
    } else {
        String valueOf = String.valueOf(zzabQ());
        int lineNumber = getLineNumber();
        i3 = getColumnNumber();
        String path = getPath();
        throw new IllegalStateException(
                new StringBuilder((String.valueOf(valueOf).length() + 69) + String.valueOf(path).length())
                        .append("Expected a long but was ").append(valueOf).append(" at line ")
                        .append(lineNumber).append(" column ").append(i3).append(" path ").append(path)
                        .toString());
    }
    this.zzcpK = 11;
    double parseDouble = Double.parseDouble(this.zzcpN);
    parseLong = (long) parseDouble;
    if (((double) parseLong) != parseDouble) {
        valueOf = this.zzcpN;
        lineNumber = getLineNumber();
        i3 = getColumnNumber();
        path = getPath();
        throw new NumberFormatException(
                new StringBuilder((String.valueOf(valueOf).length() + 69) + String.valueOf(path).length())
                        .append("Expected a long but was ").append(valueOf).append(" at line ")
                        .append(lineNumber).append(" column ").append(i3).append(" path ").append(path)
                        .toString());
    }
    this.zzcpN = null;
    this.zzcpK = 0;
    iArr2 = this.zzcpR;
    i3 = this.zzcpP - 1;
    iArr2[i3] = iArr2[i3] + 1;
    return parseLong;
}

From source file:org.rdkit.knime.wizards.RDKitNodesWizardsPage.java

/**
 * Returns the entered percentage value as double (devided by 100) for
 * pre processing actions.//from  w  w  w.j a  v  a  2 s.co m
 *
 * @return Value between 0 and 1.
 *
 * @throws NumberFormatException Thrown, if the user entered an invalid value in the
 *       text field for the post-processing percentage.
 */
public double getPostProcessingPercentage() throws NumberFormatException {
    double dPerc = 0.0d;

    if (m_textPostProcPerc != null && m_textPostProcPerc.getEnabled()) {
        dPerc = Double.parseDouble(m_textPostProcPerc.getText().trim()) / 100.0d;
        if (dPerc < 0) {
            throw new NumberFormatException(
                    "Percentage of post-processing activities must be greater than or equal to 0%.");
        }
        if (dPerc > 1) {
            throw new NumberFormatException(
                    "Percentage of post-processing activities must be lower than or equal to 100%.");
        }
    }

    return dPerc;
}

From source file:org.lockss.util.NumberUtil.java

/**
 * Returns an integer from a String representing a number in the
 * Roman number system. The number must be within the range 0 - 2^31-1.
 * The string may not contain any other characters than allowed by the 
 * Roman numeral alphabet: 'I', 'V', 'X', 'L', 'C', 'D' and 'M'. The
 * letter 'N' is also allowed. The Bede first used 'N' (nulla) for 0 
 * around 725AD in a table of lunar epacts. Parentheses can be used for 
 * large Roman numbers. If the string does not represent a Roman number, 
 * the exception is thrown. /*from w w w .j  ava2  s .c  om*/
 * <p>
 * The input String is validated by comparing it to the String representation
 * of the parsed value, which is in normalized form. There are many examples
 * of non-normal Roman number representations on monuments and books. See the
 * Wikipedia article on "Roman_numerals" for further discussion and examples.
 * 
 * @param roman the String
 * @param validate <code>true</code> if String representation is required
 *     to be in normalized form
 * @return the integer
 * @throws NumberFormatException if the String does not represent a valid
 *    number in the Roman number system
 */
public static int parseRomanNumber(String roman, boolean validate) throws NumberFormatException {
    int romanValue = NumberUtil.parseRomanNumber(roman, (List<String>) null);

    // the algorithm above not only creates a number that is correct for any 
    // well formed Roman string but also some non well formed Roman string 
    // (e.g. IIX), so the trick is to compare the normal string for 8 (VIII) 
    // with the one given (IIX)
    if (validate && !toRomanNumber(romanValue).equals(roman)) {
        throw new NumberFormatException("Not normalized: " + roman);
    }

    return romanValue;
}

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.  jav  a  2  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;
            }
        }
    }
}

From source file:org.lockss.util.NumberUtil.java

/**
 * Returns an integer from a String representing a number in the
 * Roman number system. The number must be in the range 0 - 2^31-1.
 * The Bede first used 'N' (nulla) for 0 around 725AD in a table
 * of epacts. /*  w  w w  .j  ava2 s .  c  o m*/
 * <p>
 * If a list is provided, it will contain Roman number tokens 
 * corresponding to the input string. The roman string "MCMDLLLIX" 
 * returns ["M" "CM" "D" "L" "L" "L" "IX"], while the string 
 * "(MCM)DLLLIX" returns ["(M)" "(CM)", "D" "L" "L" "IX"]. If the
 * input roman number is not normalized, the tokens will not be either.
 * 
 * @param s the input Roman string
 * @return roman array of numbers corresponding to the input number
 * @throws NumberFormatException if the input is not a valid Roman number
 */
private static int parseRomanNumber(String roman, List<String> tokens) throws NumberFormatException {
    String notRomanNumber = "Not a roman number: " + roman;
    if (StringUtil.isNullString(roman)) {
        throw new NumberFormatException(notRomanNumber);
    }
    roman = roman.trim().toUpperCase();
    // special-case "N" (nulla) for 0
    if ("N".equals(roman)) {
        if (tokens != null) {
            tokens.add("N");
        }
        return 0;
    }
    int romanLength = roman.length();

    // determine paren count and corresponding scale of number
    int parenCount = 0;
    int scale = 1;
    int i = 0;
    for (; i < romanLength && (roman.charAt(i) == '('); i++) {
        if (++parenCount > 2) {
            throw new NumberFormatException(notRomanNumber);
        }
        scale *= 1000; // scale by thousands
    }

    int romanNumber = 0;
    int lastTokenVal = Integer.MAX_VALUE;
    List<String> list = (tokens != null) ? new ArrayList<String>() : null;

    for (; i < romanLength; i++) {
        if (roman.charAt(i) == ')') {
            if (--parenCount < 0) {
                throw new NumberFormatException(notRomanNumber);
            }
            scale /= 1000;
            lastTokenVal = Integer.MAX_VALUE;
        } else {
            String token = roman.substring(i, i + 1);
            Integer tokenVal = romanToNum.get(token);
            if (tokenVal == null) {
                throw new NumberFormatException(notRomanNumber);
            }
            // add scaled value and validate number
            tokenVal *= scale;
            romanNumber += tokenVal;
            if (tokenVal > lastTokenVal) {
                // back down number if previous token modified current one (e.g. IV)
                romanNumber -= 2 * lastTokenVal;
                if (list != null) {
                    // use previous and current character as token 
                    token = roman.substring(i - 1, i + 1);
                    list.set(list.size() - 1, String.format(romanFmt[parenCount], token));
                }
            } else if (list != null) {
                // add roman token to return list 
                list.add(String.format(romanFmt[parenCount], token));
            }
            lastTokenVal = tokenVal;
            if (romanNumber <= 0) {
                throw new NumberFormatException(notRomanNumber);
            }
        }
    }

    if (parenCount != 0) {
        throw new NumberFormatException(notRomanNumber);
    }

    // return tokens and roman number
    if (list != null) {
        tokens.addAll(list);
    }

    return (int) romanNumber;
}