Example usage for java.util NoSuchElementException getMessage

List of usage examples for java.util NoSuchElementException getMessage

Introduction

In this page you can find the example usage for java.util NoSuchElementException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.continuent.tungsten.common.security.KeystoreManagerCtrl.java

/**
 * Password Manager entry point//from w  ww.  j  a v a 2 s.co  m
 * 
 * @param argv
 * @throws Exception
 */
public static void main(String argv[]) throws Exception {
    keystoreManager = new KeystoreManagerCtrl();

    // --- Options ---
    CommandLine line = null;

    try {
        CommandLineParser parser = new GnuParser();
        // --- Parse the command line arguments ---

        // --- Help
        line = parser.parse(keystoreManager.helpOptions, argv, true);
        if (line.hasOption(_HELP)) {
            DisplayHelpAndExit(EXIT_CODE.EXIT_OK);
        }

        // --- Program command line options
        line = parser.parse(keystoreManager.options, argv);

        // --- Compulsory arguments : Get options ---
        if (line.hasOption(_KEYSTORE_LOCATION))
            keystoreManager.keystoreLocation = line.getOptionValue(_KEYSTORE_LOCATION);

        if (line.hasOption(_KEY_ALIAS))
            keystoreManager.keyAlias = line.getOptionValue(_KEY_ALIAS);

        if (line.hasOption(_KEY_TYPE)) {
            String keyType = line.getOptionValue(_KEY_TYPE);
            // This will throw an exception if the type is not recognised
            KEYSTORE_TYPE certificateTYpe = KEYSTORE_TYPE.fromString(keyType);
            keystoreManager.keyType = certificateTYpe;
        }

        if (line.hasOption(_KEYSTORE_PASSWORD))
            keystoreManager.keystorePassword = line.getOptionValue(_KEYSTORE_PASSWORD);
        if (line.hasOption(_KEY_PASSWORD))
            keystoreManager.keyPassword = line.getOptionValue(_KEY_PASSWORD);

    } catch (ParseException exp) {
        logger.error(exp.getMessage());
        DisplayHelpAndExit(EXIT_CODE.EXIT_ERROR);
    } catch (Exception e) {
        // Workaround for Junit test
        if (e.toString().contains("CheckExitCalled")) {
            throw e;
        } else
        // Normal behaviour
        {
            logger.error(e.getMessage());
            Exit(EXIT_CODE.EXIT_ERROR);
        }

    }

    // --- Perform commands ---

    // ######### Check password ##########
    if (line.hasOption(_CHECK)) {
        try {
            if (keystoreManager.keystorePassword == null || keystoreManager.keyPassword == null) {
                // --- Get passwords from stdin if not given on command line
                List<String> listPrompts = Arrays.asList("Keystore password:",
                        MessageFormat.format("Password for key {0}:", keystoreManager.keyAlias));
                List<String> listUserInput = keystoreManager.getUserInputFromStdin(listPrompts);

                if (listUserInput.size() == listPrompts.size()) {
                    keystoreManager.keystorePassword = listUserInput.get(0);
                    keystoreManager.keyPassword = listUserInput.get(1);
                } else {
                    throw new NoSuchElementException();
                }
            }
            try {
                // --- Check that all keys in keystore use the keystore
                // password
                logger.info(MessageFormat.format("Using keystore:{0}", keystoreManager.keystoreLocation));

                SecurityHelper.checkKeyStorePasswords(keystoreManager.keystoreLocation, keystoreManager.keyType,
                        keystoreManager.keystorePassword, keystoreManager.keyAlias,
                        keystoreManager.keyPassword);
                logger.info(MessageFormat.format("OK : Identical password for Keystore and key={0}",
                        keystoreManager.keyAlias));
            } catch (UnrecoverableKeyException uke) {
                logger.error(MessageFormat.format("At least 1 key has a wrong password.{0}", uke.getMessage()));
                Exit(EXIT_CODE.EXIT_ERROR);
            } catch (Exception e) {
                logger.error(MessageFormat.format("{0}", e.getMessage()));
                Exit(EXIT_CODE.EXIT_ERROR);
            }

        } catch (NoSuchElementException nse) {
            logger.error(nse.getMessage());
            Exit(EXIT_CODE.EXIT_ERROR);
        } catch (Exception e) {
            logger.error(MessageFormat.format("Error while running the program: {0}", e.getMessage()));
            Exit(EXIT_CODE.EXIT_ERROR);
        }
    }

    Exit(EXIT_CODE.EXIT_OK);
}

From source file:com.act.lcms.v2.MZCollisionCounter.java

public static void main(String[] args) throws Exception {
    CLIUtil cliUtil = new CLIUtil(MassChargeCalculator.class, HELP_MESSAGE, OPTION_BUILDERS);
    CommandLine cl = cliUtil.parseCommandLine(args);

    File inputFile = new File(cl.getOptionValue(OPTION_INPUT_INCHI_LIST));
    if (!inputFile.exists()) {
        cliUtil.failWithMessage("Input file at does not exist at %s", inputFile.getAbsolutePath());
    }/* w  w w  .  jav  a2s.  c om*/

    List<MassChargeCalculator.MZSource> sources = new ArrayList<>();
    try (BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            sources.add(new MassChargeCalculator.MZSource(line));
            if (sources.size() % 1000 == 0) {
                LOGGER.info("Loaded %d sources from input file", sources.size());
            }
        }
    }

    Set<String> considerIons = Collections.emptySet();
    if (cl.hasOption(OPTION_ONLY_CONSIDER_IONS)) {
        List<String> ions = Arrays.asList(cl.getOptionValues(OPTION_ONLY_CONSIDER_IONS));
        LOGGER.info("Only considering ions for m/z calculation: %s", StringUtils.join(ions, ", "));
        considerIons = new HashSet<>(ions);
    }

    TSVWriter<String, Long> tsvWriter = new TSVWriter<>(Arrays.asList("collisions", "count"));
    tsvWriter.open(new File(cl.getOptionValue(OPTION_OUTPUT_FILE)));

    try {
        LOGGER.info("Loaded %d sources in total from input file", sources.size());

        MassChargeCalculator.MassChargeMap mzMap = MassChargeCalculator.makeMassChargeMap(sources,
                considerIons);

        if (!cl.hasOption(OPTION_COUNT_WINDOW_INTERSECTIONS)) {
            // Do an exact analysis of the m/z collisions if windowing is not specified.

            LOGGER.info("Computing precise collision histogram.");
            Iterable<Double> mzs = mzMap.ionMZIter();
            Map<Integer, Long> collisionHistogram = histogram(
                    StreamSupport.stream(mzs.spliterator(), false).map(mz -> { // See comment about Iterable below.
                        try {
                            return mzMap.ionMZToMZSources(mz).size();
                        } catch (NoSuchElementException e) {
                            LOGGER.error("Caught no such element exception for mz %f: %s", mz, e.getMessage());
                            throw e;
                        }
                    }));
            List<Integer> sortedCollisions = new ArrayList<>(collisionHistogram.keySet());
            Collections.sort(sortedCollisions);
            for (Integer collision : sortedCollisions) {
                tsvWriter.append(new HashMap<String, Long>() {
                    {
                        put("collisions", collision.longValue());
                        put("count", collisionHistogram.get(collision));
                    }
                });
            }
        } else {
            /* After some deliberation (thanks Gil!), the windowed variant of this calculation counts the number of
             * structures whose 0.01 Da m/z windows (for some set of ions) overlap with each other.
             *
             * For example, let's assume we have five total input structures, and are only searching for one ion.  Let's
             * also assume that three of those structures have m/z A and the remaining two have m/z B.  The windows might
             * look like this in the m/z domain:
             * |----A----|
             *        |----B----|
             * Because A represents three structures and overlaps with B, which represents two, we assign A a count of 5--
             * this is the number of structures we believe could fall into the range of A given our current peak calling
             * approach.  Similarly, B is assigned a count of 5, as the possibility for collision/confusion is symmetric.
             *
             * Note that this is an over-approximation of collisions, as we could more precisely only consider intersections
             * when the exact m/z of B falls within the window around A and vice versa.  However, because we have observed
             * cases where the MS sensor doesn't report structures at exactly the m/z we predict, we employ this weaker
             * definition of intersection to give a slightly pessimistic view of what confusions might be possible. */
            // Compute windows for every m/z.  We don't care about the original mz values since we just want the count.
            List<Double> mzs = mzMap.ionMZsSorted();

            final Double windowHalfWidth;
            if (cl.hasOption(OPTION_WINDOW_HALFWIDTH)) {
                // Don't use get with default for this option, as we want the exact FP value of the default tolerance.
                windowHalfWidth = Double.valueOf(cl.getOptionValue(OPTION_WINDOW_HALFWIDTH));
            } else {
                windowHalfWidth = DEFAULT_WINDOW_TOLERANCE;
            }

            /* Window = (lower bound, upper bound), counter of represented m/z's that collide with this window, and number
             * of representative structures (which will be used in counting collisions). */
            LinkedList<CollisionWindow> allWindows = new LinkedList<CollisionWindow>() {
                {
                    for (Double mz : mzs) {
                        // CPU for memory trade-off: don't re-compute the window bounds over and over and over and over and over.
                        try {
                            add(new CollisionWindow(mz, windowHalfWidth, mzMap.ionMZToMZSources(mz).size()));
                        } catch (NoSuchElementException e) {
                            LOGGER.error("Caught no such element exception for mz %f: %s", mz, e.getMessage());
                            throw e;
                        }
                    }
                }
            };

            // Sweep line time!  The window ranges are the interesting points.  We just accumulate overlap counts as we go.
            LinkedList<CollisionWindow> workingSet = new LinkedList<>();
            List<CollisionWindow> finished = new LinkedList<>();

            while (allWindows.size() > 0) {
                CollisionWindow thisWindow = allWindows.pop();
                // Remove any windows from the working set that don't overlap with the next window.
                while (workingSet.size() > 0 && workingSet.peekFirst().getMaxMZ() < thisWindow.getMinMZ()) {
                    finished.add(workingSet.pop());
                }

                for (CollisionWindow w : workingSet) {
                    /* Add the size of the new overlapping window's structure count to each of the windows in the working set,
                     * which represents the number of possible confused structures that fall within the overlapping region.
                     * We exclude the window itself as it should already have counted the colliding structures it represents. */
                    w.getAccumulator().add(thisWindow.getStructureCount());

                    /* Reciprocally, add the structure counts of all windows with which the current window overlaps to it. */
                    thisWindow.getAccumulator().add(w.getStructureCount());
                }

                // Now that accumulation is complete, we can safely add the current window.
                workingSet.add(thisWindow);
            }

            // All the interesting events are done, so drop the remaining windows into the finished set.
            finished.addAll(workingSet);

            Map<Long, Long> collisionHistogram = histogram(
                    finished.stream().map(w -> w.getAccumulator().longValue()));
            List<Long> sortedCollisions = new ArrayList<>(collisionHistogram.keySet());
            Collections.sort(sortedCollisions);
            for (Long collision : sortedCollisions) {
                tsvWriter.append(new HashMap<String, Long>() {
                    {
                        put("collisions", collision);
                        put("count", collisionHistogram.get(collision));
                    }
                });
            }
        }
    } finally {
        if (tsvWriter != null) {
            tsvWriter.close();
        }
    }
}

From source file:fr.cls.atoll.motu.library.misc.utils.PropertiesUtilities.java

/**
 * Replace in the properties values the name of the system variable that follows the scheme
 * <tt>${var}<tt> with their corresponding values.
 * // w  w  w.  java2s.c om
 * @param props properties to substitute.
 */
static public void replaceSystemVariable(Properties props) {
    Iterator it;
    Map.Entry entry;
    String value;
    for (it = props.entrySet().iterator(); it.hasNext();) {
        entry = (Map.Entry) it.next();
        try {
            value = replaceSystemVariable((String) entry.getValue());
        } catch (NoSuchElementException ex) {
            throw new NoSuchElementException(
                    ex.getMessage() + " subsitution for property " + (String) entry.getKey());
        }
        entry.setValue(value);
    }
}

From source file:com.act.lcms.v2.MZCollisionCounter.java

public static <T> Map<T, Long> histogram(Stream<T> stream) {
    Map<T, Long> hist = new HashMap<>();
    // This could be done with reduce (fold) or collector cleverness, but this invocation makes the intention clear.
    //stream.forEach(x -> hist.merge(x, 1l, (acc, one) -> one + acc));
    stream.forEach(x -> {/*ww w  . j av a  2s  .  c o m*/
        try {
            hist.put(x, hist.getOrDefault(x, 0l) + 1);
        } catch (NoSuchElementException e) {
            LOGGER.error("Caught no such element exception for %s: %s", x.toString(), e.getMessage());
            throw e;
        }
    });

    return hist;
}

From source file:nl.minvenj.pef.stream.LiveCapture.java

private static boolean checkConfiguration(final XMLConfiguration config) {
    final long MAX_FILE_SIZE = 1000;
    //Test if all fields are available. For now it exits per field.
    try {/*from w w w.  j ava  2s . c om*/
        //First all normal fields. The library field is optional, default to metal.
        final boolean live = config.getBoolean("live");
        final String inputFile = config.getString("input");
        if (!live) {
            if (inputFile == null) {
                throw new NoSuchElementException(
                        "For offline use, the parameter 'input' file needs to be specified");
            }
            File testInput = new File(inputFile);
            if (!testInput.exists()) {
                logger.severe("The specified input file " + testInput.toPath().toAbsolutePath().toString()
                        + " does not exist.");
                return false;
            }
            if (!testInput.canRead()) {
                logger.severe("The user is not allowed to read the file");
            }
        }
        // Will throw an error if conversion fails.
        config.getBoolean("remove_failing_packets");
        config.getBoolean("remove_unknown_protocols");
        config.getBoolean("checksum_reset");
        config.getBoolean("timer", false);
        final String outputDir = config.getString("output_directory");
        // The file size does not need to be specified. Therefore a default is provided.
        final long fileSize = config.getLong("file_size", 120);
        if (fileSize > MAX_FILE_SIZE) {
            logger.severe(" A file size over 1000 MB is not supported.");
            return false;
        }
        if (outputDir == null) {
            throw new NoSuchElementException("The output_directory parameter is not set");
        }
        final Path path = Paths.get(outputDir);
        if (!Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) {
            logger.severe("The output directory configured is not a path.");
            return false;
        }
        if (!Files.isWritable(path)) {
            logger.severe("The selected output directory is not writable.");
            return false;
        }
        final String parseLibrary = config.getString("parse_library");
        if (!parseLibrary.equals("metal")) {
            logger.severe("Only the metal library is currently implemented as parse library.");
            return false;
        }
        String[] packetInputLibraryOptions = { "metal", "jnetpcap" };
        final String packetInputLibrary = config.getString("packets_input_library");
        if (!Arrays.asList(packetInputLibraryOptions).contains(packetInputLibrary)) {
            logger.severe("Packet Input Library: " + packetInputLibrary + " is not implemented.");
        }
        // Test all algorithms and their parameters.
        testPseudonymizationSettings(config);
    } catch (NoSuchElementException e) {
        logger.severe("Input element is missing: " + e.getMessage());
        return false;
    } catch (InvalidPathException e) {
        logger.severe("The path specified in the config file is invalid: " + e.getMessage());
        return false;
    } catch (ConversionException e) {
        logger.severe("Conversion failed: " + e.getMessage());
        return false;
    } catch (ClassNotFoundException e) {
        logger.severe("Error in creating a parameter: the class could not be found: " + e.getMessage());
        return false;
    } catch (ConfigurationException e) {
        logger.severe(e.getMessage());
        return false;
    }
    return true;
}

From source file:com.tesora.dve.worker.DirectConnectionCache.java

public static CachedConnection checkoutDatasource(EventLoopGroup preferredEventLoop, UserAuthentication auth,
        AdditionalConnectionInfo additionalConnInfo, StorageSite site) throws PESQLException {
    try {//from w  w  w  . j a  v a  2 s. c  o  m
        if (preferredEventLoop == null)
            preferredEventLoop = SharedEventLoopHolder.getLoop();

        DSCacheKey datasourceKey = new DirectConnectionCache.DSCacheKey(preferredEventLoop, auth,
                additionalConnInfo, site);

        CachedConnection cacheEntry;
        if (DirectConnectionCache.suppressConnectionCaching) {
            cacheEntry = DirectConnectionCache.connect(datasourceKey);
        } else {
            cacheEntry = DirectConnectionCache.connectionCache.borrowObject(datasourceKey);
        }

        return cacheEntry;
    } catch (NoSuchElementException e) {
        if (e.getMessage().matches(".*java.net.ConnectException.*"))
            throw new PECommunicationsException(
                    "Cannot connect to '" + site.getMasterUrl() + "' as user '" + auth.userid + "'", e);

        throw new PESQLException(
                "Unable to connect to site '" + site.getName() + "' as user '" + auth.userid + "'", e);
    } catch (Exception e) {
        throw new PESQLException(
                "Unable to connect to site '" + site.getName() + "' as user '" + auth.userid + "'", e);
    }
}

From source file:com.spokentech.speechdown.server.util.pool.AbstractPoolableObjectFactory.java

/**
 * Initializes an {@link org.apache.commons.pool.ObjectPool} by borrowing each object from the
 * pool (thereby triggering activation) and then returning all the objects back to the pool. 
 * @param pool the object pool to be initialized.
 * @throws InstantiationException if borrowing (or returning) an object from the pool triggers an exception.
 *///from  w  w  w  . j a v  a2s . c o m
public static void initPool(ObjectPool pool) throws InstantiationException {
    try {
        List<Object> objects = new ArrayList<Object>();
        while (true)
            try {
                objects.add(pool.borrowObject());
            } catch (NoSuchElementException e) {
                // ignore, max active reached
                break;
            }
        for (Object obj : objects) {
            pool.returnObject(obj);
        }
    } catch (Exception e) {
        try {
            pool.close();
        } catch (Exception e1) {
            _logger.warn("Encounter expception while attempting to close object pool!", e1);
        }
        throw (InstantiationException) new InstantiationException(e.getMessage()).initCause(e);
    }

}

From source file:com.telefonica.euro_iaas.sdc.puppetwrapper.controllers.GenericController.java

@ExceptionHandler(NoSuchElementException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)/*ww  w . j a  v  a2 s.  c  om*/
@ResponseBody
public PuppetWrapperError handleNoSuchElementException(NoSuchElementException ex) {
    logger.error(ex.getMessage());
    return new PuppetWrapperError(HttpStatus.NOT_FOUND.value(), ex.getMessage());
}

From source file:com.dream.messaging.sender.socket.LongConnSocketMessageSender.java

@Override
protected Message send(Message req) throws ConnectionException {
    IoSession iosession = null;//  w w  w  . j ava 2 s  .com
    Message response = null;
    try {
        iosession = getObjectPool().borrowObject();
        IoBuffer buffer = IoBuffer.allocate(4);
        WriteFuture future = iosession.write(buffer);
        future.await();
    } catch (NoSuchElementException e) {
        logger.error(e.getMessage(), e);
    } catch (IllegalStateException e) {
        logger.error(e.getMessage(), e);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        try {
            getObjectPool().returnObject(iosession);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
    return response;
}