Example usage for java.util NoSuchElementException initCause

List of usage examples for java.util NoSuchElementException initCause

Introduction

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

Prototype

public synchronized Throwable initCause(Throwable cause) 

Source Link

Document

Initializes the cause of this throwable to the specified value.

Usage

From source file:com.martinkampjensen.thesis.util.gromacs.EnergyExtractor.java

/**
 * Reads and returns the next energy value.
 * /*from  www .  j  ava  2 s  .co  m*/
 * @return the energy value.
 * @throws IllegalStateException if {@link #close()} has been called.
 * @throws NoSuchElementException if there are no more energy values. This
 *         means that {@link #hasNext()} would have returned
 *         <code>false</code> immediately before this method was called or
 *         that an {@link IOException} occurred.
 */
@Override
public double next() {
    checkState();

    if (!_hasNext) {
        throw new NoSuchElementException();
    }

    _nValues++;
    final double toReturn = _next;

    try {
        _next = readReal(_input, _useDoublePrecision);
        skipBytes(_input, _bytesBetweenValues);
    } catch (EOFException e) {
        _hasNext = false;
    } catch (IOException e) {
        final NoSuchElementException nsee = new NoSuchElementException();
        nsee.initCause(e);

        try {
            _input.close();
        } catch (IOException e2) {
            // Ignore second IOException.
        }

        throw nsee;
    }

    return toReturn;
}

From source file:com.manh.pool.impl.GenericObjectPool.java

/**
 * Borrow an object from the pool using the specific waiting time which only
 * applies if {@link #getBlockWhenExhausted()} is true.
 * <p>/*w w  w .j av a 2s.c  o m*/
 * If there is one or more idle instance available in the pool, then an
 * idle instance will be selected based on the value of {@link #getLifo()},
 * activated and returned. If activation fails, or {@link #getTestOnBorrow()
 * testOnBorrow} is set to <code>true</code> and validation fails, the
 * instance is destroyed and the next available instance is examined. This
 * continues until either a valid instance is returned or there are no more
 * idle instances available.
 * <p>
 * If there are no idle instances available in the pool, behavior depends on
 * the {@link #getMaxTotal() maxTotal}, (if applicable)
 * {@link #getBlockWhenExhausted()} and the value passed in to the
 * <code>borrowMaxWaitMillis</code> parameter. If the number of instances
 * checked out from the pool is less than <code>maxTotal,</code> a new
 * instance is created, activated and (if applicable) validated and returned
 * to the caller. If validation fails, a <code>NoSuchElementException</code>
 * is thrown.
 * <p>
 * If the pool is exhausted (no available idle instances and no capacity to
 * create new ones), this method will either block (if
 * {@link #getBlockWhenExhausted()} is true) or throw a
 * <code>NoSuchElementException</code> (if
 * {@link #getBlockWhenExhausted()} is false). The length of time that this
 * method will block when {@link #getBlockWhenExhausted()} is true is
 * determined by the value passed in to the <code>borrowMaxWaitMillis</code>
 * parameter.
 * <p>
 * When the pool is exhausted, multiple calling threads may be
 * simultaneously blocked waiting for instances to become available. A
 * "fairness" algorithm has been implemented to ensure that threads receive
 * available instances in request arrival order.
 *
 * @param borrowMaxWaitMillis The time to wait in milliseconds for an object
 *                            to become available
 *
 * @return object instance from the pool
 *
 * @throws NoSuchElementException if an instance cannot be returned
 *
 * @throws Exception if an object instance cannot be returned due to an
 *                   error
 */
public T borrowObject(long borrowMaxWaitMillis) throws Exception {
    assertOpen();

    AbandonedConfig ac = this.abandonedConfig;
    if (ac != null && ac.getRemoveAbandonedOnBorrow() && (getNumIdle() < 2)
            && (getNumActive() > getMaxTotal() - 3)) {
        removeAbandoned(ac);
    }

    PooledObject<T> p = null;

    // Get local copy of current config so it is consistent for entire
    // method execution
    boolean blockWhenExhausted = getBlockWhenExhausted();

    boolean create;
    long waitTime = System.currentTimeMillis();

    while (p == null) {
        create = false;
        if (blockWhenExhausted) {
            p = idleObjects.pollFirst();
            if (p == null) {
                p = create();
                if (p != null) {
                    create = true;
                }
            }
            if (p == null) {
                if (borrowMaxWaitMillis < 0) {
                    p = idleObjects.takeFirst();
                } else {
                    p = idleObjects.pollFirst(borrowMaxWaitMillis, TimeUnit.MILLISECONDS);
                }
            }
            if (p == null) {
                throw new NoSuchElementException("Timeout waiting for idle object");
            }
            if (!p.allocate()) {
                p = null;
            }
        } else {
            p = idleObjects.pollFirst();
            if (p == null) {
                p = create();
                if (p != null) {
                    create = true;
                }
            }
            if (p == null) {
                throw new NoSuchElementException("Pool exhausted");
            }
            if (!p.allocate()) {
                p = null;
            }
        }

        if (p != null) {
            try {
                factory.activateObject(p);
            } catch (Exception e) {
                try {
                    destroy(p);
                } catch (Exception e1) {
                    // Ignore - activation failure is more important
                }
                p = null;
                if (create) {
                    NoSuchElementException nsee = new NoSuchElementException("Unable to activate object");
                    nsee.initCause(e);
                    throw nsee;
                }
            }
            if (p != null && (getTestOnBorrow() || create && getTestOnCreate())) {
                boolean validate = false;
                Throwable validationThrowable = null;
                try {
                    validate = factory.validateObject(p);
                } catch (Throwable t) {
                    PoolUtils.checkRethrow(t);
                    validationThrowable = t;
                }
                if (!validate) {
                    try {
                        destroy(p);
                        destroyedByBorrowValidationCount.incrementAndGet();
                    } catch (Exception e) {
                        // Ignore - validation failure is more important
                    }
                    p = null;
                    if (create) {
                        NoSuchElementException nsee = new NoSuchElementException("Unable to validate object");
                        nsee.initCause(validationThrowable);
                        throw nsee;
                    }
                }
            }
        }
    }

    updateStatsBorrow(p, System.currentTimeMillis() - waitTime);

    return p.getObject();
}

From source file:nl.nn.adapterframework.util.CredentialFactory.java

protected void getCredentialsFromAlias() {
    if (!gotCredentials && StringUtils.isNotEmpty(getAlias())) {
        try {//  ww w .ja  v  a  2  s  .co m
            Set principals = new HashSet();
            Set publicCredentials = new HashSet();
            Set privateCredentials = new HashSet();
            Principal p = new IbisPrincipal();
            principals.add(p);
            Subject initialSubject = new Subject(false, principals, publicCredentials, privateCredentials);
            String loginConfiguration = AppConstants.getInstance().getProperty("PrincipalMapping",
                    "DefaultPrincipalMapping");
            LoginContext lc = new LoginContext(loginConfiguration, initialSubject, this);
            lc.login();
            Subject s = lc.getSubject();
            //showSet(s.getPrincipals(),"principals");
            //showSet(s.getPublicCredentials(),"PublicCredentials");
            //showSet(s.getPrivateCredentials(),"PrivateCredentials");
            //Object pwcred=Subject.doAsPrivileged(s,new PasswordGetter(s),AccessController.getContext());
            //Object pwcred=AccessController.doPrivileged(new PasswordGetter(s));

            Object pwcred = s.getPrivateCredentials().toArray()[0];

            setUsername(ClassUtils.invokeStringGetter(pwcred, "getUserName"));
            setPassword(invokeCharArrayGetter(pwcred, "getPassword"));
            gotCredentials = true;
        } catch (Exception e) {
            if (!useFallback) {
                NoSuchElementException nsee = new NoSuchElementException(
                        "cannot obtain credentials from authentication alias [" + getAlias() + "]");
                nsee.initCause(e);
                throw nsee;
            }
            log.error("exception obtaining credentials for alias [" + getAlias() + "]", e);

            String usernameProp = "alias." + getAlias() + ".username";
            String passwordProp = "alias." + getAlias() + ".password";
            log.info("trying to solve Authentication Alias from application properties [" + usernameProp
                    + "] and [" + passwordProp + "]");
            setUsername(AppConstants.getInstance().getProperty(usernameProp, username));
            setPassword(AppConstants.getInstance().getProperty(passwordProp, password));
        }
    }
}

From source file:org.zbus.common.pool.impl.GenericKeyedObjectPool.java

/**
 * Borrows an object from the sub-pool associated with the given key using
 * the specified waiting time which only applies if
 * {@link #getBlockWhenExhausted()} is true.
 * <p>/*  w w  w  .  j  av a  2s  .c o m*/
 * If there is one or more idle instances available in the sub-pool
 * associated with the given key, then an idle instance will be selected
 * based on the value of {@link #getLifo()}, activated and returned.  If
 * activation fails, or {@link #getTestOnBorrow() testOnBorrow} is set to
 * <code>true</code> and validation fails, the instance is destroyed and the
 * next available instance is examined.  This continues until either a valid
 * instance is returned or there are no more idle instances available.
 * <p>
 * If there are no idle instances available in the sub-pool associated with
 * the given key, behavior depends on the {@link #getMaxTotalPerKey()
 * maxTotalPerKey}, {@link #getMaxTotal() maxTotal}, and (if applicable)
 * {@link #getBlockWhenExhausted()} and the value passed in to the
 * <code>borrowMaxWaitMillis</code> parameter. If the number of instances checked
 * out from the sub-pool under the given key is less than
 * <code>maxTotalPerKey</code> and the total number of instances in
 * circulation (under all keys) is less than <code>maxTotal</code>, a new
 * instance is created, activated and (if applicable) validated and returned
 * to the caller. If validation fails, a <code>NoSuchElementException</code>
 * will be thrown.
 * <p>
 * If the associated sub-pool is exhausted (no available idle instances and
 * no capacity to create new ones), this method will either block
 * ({@link #getBlockWhenExhausted()} is true) or throw a
 * <code>NoSuchElementException</code>
 * ({@link #getBlockWhenExhausted()} is false).
 * The length of time that this method will block when
 * {@link #getBlockWhenExhausted()} is true is determined by the value
 * passed in to the <code>borrowMaxWait</code> parameter.
 * <p>
 * When <code>maxTotal</code> is set to a positive value and this method is
 * invoked when at the limit with no idle instances available under the requested
 * key, an attempt is made to create room by clearing the oldest 15% of the
 * elements from the keyed sub-pools.
 * <p>
 * When the pool is exhausted, multiple calling threads may be
 * simultaneously blocked waiting for instances to become available. A
 * "fairness" algorithm has been implemented to ensure that threads receive
 * available instances in request arrival order.
 *
 * @param key pool key
 * @param borrowMaxWaitMillis The time to wait in milliseconds for an object
 *                            to become available
 *
 * @return object instance from the keyed pool
 *
 * @throws NoSuchElementException if a keyed object instance cannot be
 *                                returned because the pool is exhausted.
 *
 * @throws Exception if a keyed object instance cannot be returned due to an
 *                   error
 */
public T borrowObject(K key, long borrowMaxWaitMillis) throws Exception {
    assertOpen();

    PooledObject<T> p = null;

    // Get local copy of current config so it is consistent for entire
    // method execution
    boolean blockWhenExhausted = getBlockWhenExhausted();

    boolean create;
    long waitTime = 0;
    ObjectDeque<T> objectDeque = register(key);

    try {
        while (p == null) {
            create = false;
            if (blockWhenExhausted) {
                p = objectDeque.getIdleObjects().pollFirst();
                if (p == null) {
                    create = true;
                    p = create(key);
                }
                if (p == null) {
                    if (borrowMaxWaitMillis < 0) {
                        p = objectDeque.getIdleObjects().takeFirst();
                    } else {
                        waitTime = System.currentTimeMillis();
                        p = objectDeque.getIdleObjects().pollFirst(borrowMaxWaitMillis, TimeUnit.MILLISECONDS);
                        waitTime = System.currentTimeMillis() - waitTime;
                    }
                }
                if (p == null) {
                    throw new NoSuchElementException("Timeout waiting for idle object");
                }
                if (!p.allocate()) {
                    p = null;
                }
            } else {
                p = objectDeque.getIdleObjects().pollFirst();
                if (p == null) {
                    create = true;
                    p = create(key);
                }
                if (p == null) {
                    throw new NoSuchElementException("Pool exhausted");
                }
                if (!p.allocate()) {
                    p = null;
                }
            }

            if (p != null) {
                try {
                    factory.activateObject(key, p);
                } catch (Exception e) {
                    try {
                        destroy(key, p, true);
                    } catch (Exception e1) {
                        // Ignore - activation failure is more important
                    }
                    p = null;
                    if (create) {
                        NoSuchElementException nsee = new NoSuchElementException("Unable to activate object");
                        nsee.initCause(e);
                        throw nsee;
                    }
                }
                if (p != null && (getTestOnBorrow() || create && getTestOnCreate())) {
                    boolean validate = false;
                    Throwable validationThrowable = null;
                    try {
                        validate = factory.validateObject(key, p);
                    } catch (Throwable t) {
                        PoolUtils.checkRethrow(t);
                        validationThrowable = t;
                    }
                    if (!validate) {
                        try {
                            destroy(key, p, true);
                            destroyedByBorrowValidationCount.incrementAndGet();
                        } catch (Exception e) {
                            // Ignore - validation failure is more important
                        }
                        p = null;
                        if (create) {
                            NoSuchElementException nsee = new NoSuchElementException(
                                    "Unable to validate object");
                            nsee.initCause(validationThrowable);
                            throw nsee;
                        }
                    }
                }
            }
        }
    } finally {
        deregister(key);
    }

    updateStatsBorrow(p, waitTime);

    return p.getObject();
}

From source file:org.zbus.common.pool.impl.GenericObjectPool.java

/**
 * Borrow an object from the pool using the specific waiting time which only
 * applies if {@link #getBlockWhenExhausted()} is true.
 * <p>//from  w ww . j a va  2 s . c  o  m
 * If there is one or more idle instance available in the pool, then an
 * idle instance will be selected based on the value of {@link #getLifo()},
 * activated and returned. If activation fails, or {@link #getTestOnBorrow()
 * testOnBorrow} is set to <code>true</code> and validation fails, the
 * instance is destroyed and the next available instance is examined. This
 * continues until either a valid instance is returned or there are no more
 * idle instances available.
 * <p>
 * If there are no idle instances available in the pool, behavior depends on
 * the {@link #getMaxTotal() maxTotal}, (if applicable)
 * {@link #getBlockWhenExhausted()} and the value passed in to the
 * <code>borrowMaxWaitMillis</code> parameter. If the number of instances
 * checked out from the pool is less than <code>maxTotal,</code> a new
 * instance is created, activated and (if applicable) validated and returned
 * to the caller. If validation fails, a <code>NoSuchElementException</code>
 * is thrown.
 * <p>
 * If the pool is exhausted (no available idle instances and no capacity to
 * create new ones), this method will either block (if
 * {@link #getBlockWhenExhausted()} is true) or throw a
 * <code>NoSuchElementException</code> (if
 * {@link #getBlockWhenExhausted()} is false). The length of time that this
 * method will block when {@link #getBlockWhenExhausted()} is true is
 * determined by the value passed in to the <code>borrowMaxWaitMillis</code>
 * parameter.
 * <p>
 * When the pool is exhausted, multiple calling threads may be
 * simultaneously blocked waiting for instances to become available. A
 * "fairness" algorithm has been implemented to ensure that threads receive
 * available instances in request arrival order.
 *
 * @param borrowMaxWaitMillis The time to wait in milliseconds for an object
 *                            to become available
 *
 * @return object instance from the pool
 *
 * @throws NoSuchElementException if an instance cannot be returned
 *
 * @throws Exception if an object instance cannot be returned due to an
 *                   error
 */
public T borrowObject(long borrowMaxWaitMillis) throws Exception {
    assertOpen();

    AbandonedConfig ac = this.abandonedConfig;
    if (ac != null && ac.getRemoveAbandonedOnBorrow() && (getNumIdle() < 2)
            && (getNumActive() > getMaxTotal() - 3)) {
        removeAbandoned(ac);
    }

    PooledObject<T> p = null;

    // Get local copy of current config so it is consistent for entire
    // method execution
    boolean blockWhenExhausted = getBlockWhenExhausted();

    boolean create;
    long waitTime = 0;

    while (p == null) {
        create = false;
        if (blockWhenExhausted) {
            p = idleObjects.pollFirst();
            if (p == null) {
                create = true;
                p = create();
            }
            if (p == null) {
                if (borrowMaxWaitMillis < 0) {
                    p = idleObjects.takeFirst();
                } else {
                    waitTime = System.currentTimeMillis();
                    p = idleObjects.pollFirst(borrowMaxWaitMillis, TimeUnit.MILLISECONDS);
                    waitTime = System.currentTimeMillis() - waitTime;
                }
            }
            if (p == null) {
                throw new NoSuchElementException("Timeout waiting for idle object");
            }
            if (!p.allocate()) {
                p = null;
            }
        } else {
            p = idleObjects.pollFirst();
            if (p == null) {
                create = true;
                p = create();
            }
            if (p == null) {
                throw new NoSuchElementException("Pool exhausted");
            }
            if (!p.allocate()) {
                p = null;
            }
        }

        if (p != null) {
            try {
                factory.activateObject(p);
            } catch (Exception e) {
                try {
                    destroy(p);
                } catch (Exception e1) {
                    // Ignore - activation failure is more important
                }
                p = null;
                if (create) {
                    NoSuchElementException nsee = new NoSuchElementException("Unable to activate object");
                    nsee.initCause(e);
                    throw nsee;
                }
            }
            if (p != null && (getTestOnBorrow() || create && getTestOnCreate())) {
                boolean validate = false;
                Throwable validationThrowable = null;
                try {
                    validate = factory.validateObject(p);
                } catch (Throwable t) {
                    PoolUtils.checkRethrow(t);
                    validationThrowable = t;
                }
                if (!validate) {
                    try {
                        destroy(p);
                        destroyedByBorrowValidationCount.incrementAndGet();
                    } catch (Exception e) {
                        // Ignore - validation failure is more important
                    }
                    p = null;
                    if (create) {
                        NoSuchElementException nsee = new NoSuchElementException("Unable to validate object");
                        nsee.initCause(validationThrowable);
                        throw nsee;
                    }
                }
            }
        }
    }

    updateStatsBorrow(p, waitTime);

    return p.getObject();
}