Search in sources :

Example 16 with NoSuchElementException

use of java.util.NoSuchElementException in project tomcat by apache.

the class GenericObjectPool method borrowObject.

/**
     * Borrow an object from the pool using the specific waiting time which only
     * applies if {@link #getBlockWhenExhausted()} is true.
     * <p>
     * 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(final long borrowMaxWaitMillis) throws Exception {
    assertOpen();
    final 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
    final boolean blockWhenExhausted = getBlockWhenExhausted();
    boolean create;
    final long waitTime = System.currentTimeMillis();
    while (p == null) {
        create = false;
        p = idleObjects.pollFirst();
        if (p == null) {
            p = create();
            if (p != null) {
                create = true;
            }
        }
        if (blockWhenExhausted) {
            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");
            }
        } else {
            if (p == null) {
                throw new NoSuchElementException("Pool exhausted");
            }
        }
        if (!p.allocate()) {
            p = null;
        }
        if (p != null) {
            try {
                factory.activateObject(p);
            } catch (final Exception e) {
                try {
                    destroy(p);
                } catch (final Exception e1) {
                // Ignore - activation failure is more important
                }
                p = null;
                if (create) {
                    final 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 (final Throwable t) {
                    PoolUtils.checkRethrow(t);
                    validationThrowable = t;
                }
                if (!validate) {
                    try {
                        destroy(p);
                        destroyedByBorrowValidationCount.incrementAndGet();
                    } catch (final Exception e) {
                    // Ignore - validation failure is more important
                    }
                    p = null;
                    if (create) {
                        final NoSuchElementException nsee = new NoSuchElementException("Unable to validate object");
                        nsee.initCause(validationThrowable);
                        throw nsee;
                    }
                }
            }
        }
    }
    updateStatsBorrow(p, System.currentTimeMillis() - waitTime);
    return p.getObject();
}
Also used : NoSuchElementException(java.util.NoSuchElementException) NoSuchElementException(java.util.NoSuchElementException)

Example 17 with NoSuchElementException

use of java.util.NoSuchElementException in project tomcat by apache.

the class SoftReferenceObjectPool method borrowObject.

/**
     * Borrow an object from the pool. If there are no idle instances available
     * in the pool, the configured factory's
     * {@link PooledObjectFactory#makeObject()} method is invoked to create a
     * new instance.
     * <p>
     * All instances are {@link PooledObjectFactory#activateObject(
     * org.apache.tomcat.dbcp.pool2.PooledObject) activated}
     * and {@link PooledObjectFactory#validateObject(
     * org.apache.tomcat.dbcp.pool2.PooledObject)
     * validated} before being returned by this method. If validation fails or
     * an exception occurs activating or validating an idle instance, the
     * failing instance is {@link PooledObjectFactory#destroyObject(
     * org.apache.tomcat.dbcp.pool2.PooledObject)
     * destroyed} and another instance is retrieved from the pool, validated and
     * activated. This process continues until either the pool is empty or an
     * instance passes validation. If the pool is empty on activation or it does
     * not contain any valid instances, the factory's <code>makeObject</code>
     * method is used to create a new instance. If the created instance either
     * raises an exception on activation or fails validation,
     * <code>NoSuchElementException</code> is thrown. Exceptions thrown by
     * <code>MakeObject</code> are propagated to the caller; but other than
     * <code>ThreadDeath</code> or <code>VirtualMachineError</code>, exceptions
     * generated by activation, validation or destroy methods are swallowed
     * silently.
     *
     * @throws NoSuchElementException
     *             if a valid object cannot be provided
     * @throws IllegalStateException
     *             if invoked on a {@link #close() closed} pool
     * @throws Exception
     *             if an exception occurs creating a new instance
     * @return a valid, activated object instance
     */
// ref cannot be null
@SuppressWarnings("null")
@Override
public synchronized T borrowObject() throws Exception {
    assertOpen();
    T obj = null;
    boolean newlyCreated = false;
    PooledSoftReference<T> ref = null;
    while (null == obj) {
        if (idleReferences.isEmpty()) {
            if (null == factory) {
                throw new NoSuchElementException();
            }
            newlyCreated = true;
            obj = factory.makeObject().getObject();
            createCount++;
            // Do not register with the queue
            ref = new PooledSoftReference<>(new SoftReference<>(obj));
            allReferences.add(ref);
        } else {
            ref = idleReferences.pollFirst();
            obj = ref.getObject();
            // Clear the reference so it will not be queued, but replace with a
            // a new, non-registered reference so we can still track this object
            // in allReferences
            ref.getReference().clear();
            ref.setReference(new SoftReference<>(obj));
        }
        if (null != factory && null != obj) {
            try {
                factory.activateObject(ref);
                if (!factory.validateObject(ref)) {
                    throw new Exception("ValidateObject failed");
                }
            } catch (final Throwable t) {
                PoolUtils.checkRethrow(t);
                try {
                    destroy(ref);
                } catch (final Throwable t2) {
                    PoolUtils.checkRethrow(t2);
                // Swallowed
                } finally {
                    obj = null;
                }
                if (newlyCreated) {
                    throw new NoSuchElementException("Could not create a validated object, cause: " + t.getMessage());
                }
            }
        }
    }
    numActive++;
    ref.allocate();
    return obj;
}
Also used : SoftReference(java.lang.ref.SoftReference) NoSuchElementException(java.util.NoSuchElementException) NoSuchElementException(java.util.NoSuchElementException)

Example 18 with NoSuchElementException

use of java.util.NoSuchElementException in project tomcat by apache.

the class InstanceKeyDataSource method getConnection.

/**
     * Attempt to retrieve a database connection using {@link #getPooledConnectionAndInfo(String, String)}
     * with the provided username and password.  The password on the {@link PooledConnectionAndInfo}
     * instance returned by <code>getPooledConnectionAndInfo</code> is compared to the <code>password</code>
     * parameter.  If the comparison fails, a database connection using the supplied username and password
     * is attempted.  If the connection attempt fails, an SQLException is thrown, indicating that the given password
     * did not match the password used to create the pooled connection.  If the connection attempt succeeds, this
     * means that the database password has been changed.  In this case, the <code>PooledConnectionAndInfo</code>
     * instance retrieved with the old password is destroyed and the <code>getPooledConnectionAndInfo</code> is
     * repeatedly invoked until a <code>PooledConnectionAndInfo</code> instance with the new password is returned.
     * @param username The user name to use to connect
     * @param password The password
     * @return the connection
     * @throws SQLException Connection failed
     */
@Override
public Connection getConnection(final String username, final String password) throws SQLException {
    if (instanceKey == null) {
        throw new SQLException("Must set the ConnectionPoolDataSource " + "through setDataSourceName or setConnectionPoolDataSource" + " before calling getConnection.");
    }
    getConnectionCalled = true;
    PooledConnectionAndInfo info = null;
    try {
        info = getPooledConnectionAndInfo(username, password);
    } catch (final NoSuchElementException e) {
        closeDueToException(info);
        throw new SQLException("Cannot borrow connection from pool", e);
    } catch (final RuntimeException e) {
        closeDueToException(info);
        throw e;
    } catch (final SQLException e) {
        closeDueToException(info);
        throw e;
    } catch (final Exception e) {
        closeDueToException(info);
        throw new SQLException("Cannot borrow connection from pool", e);
    }
    if (!(null == password ? null == info.getPassword() : password.equals(info.getPassword()))) {
        // Password on PooledConnectionAndInfo does not match
        try {
            // See if password has changed by attempting connection
            testCPDS(username, password);
        } catch (final SQLException ex) {
            // Password has not changed, so refuse client, but return connection to the pool
            closeDueToException(info);
            throw new SQLException("Given password did not match password used" + " to create the PooledConnection.", ex);
        } catch (final javax.naming.NamingException ne) {
            throw new SQLException("NamingException encountered connecting to database", ne);
        }
        /*
             * Password must have changed -> destroy connection and keep retrying until we get a new, good one,
             * destroying any idle connections with the old password as we pull them from the pool.
             */
        final UserPassKey upkey = info.getUserPassKey();
        final PooledConnectionManager manager = getConnectionManager(upkey);
        // Destroy and remove from pool
        manager.invalidate(info.getPooledConnection());
        // Reset the password on the factory if using CPDSConnectionFactory
        manager.setPassword(upkey.getPassword());
        info = null;
        for (int i = 0; i < 10; i++) {
            // Bound the number of retries - only needed if bad instances return
            try {
                info = getPooledConnectionAndInfo(username, password);
            } catch (final NoSuchElementException e) {
                closeDueToException(info);
                throw new SQLException("Cannot borrow connection from pool", e);
            } catch (final RuntimeException e) {
                closeDueToException(info);
                throw e;
            } catch (final SQLException e) {
                closeDueToException(info);
                throw e;
            } catch (final Exception e) {
                closeDueToException(info);
                throw new SQLException("Cannot borrow connection from pool", e);
            }
            if (info != null && password != null && password.equals(info.getPassword())) {
                break;
            }
            if (info != null) {
                manager.invalidate(info.getPooledConnection());
            }
            info = null;
        }
        if (info == null) {
            throw new SQLException("Cannot borrow connection from pool - password change failure.");
        }
    }
    final Connection con = info.getPooledConnection().getConnection();
    try {
        setupDefaults(con, username);
        con.clearWarnings();
        return con;
    } catch (final SQLException ex) {
        try {
            con.close();
        } catch (final Exception exc) {
            getLogWriter().println("ignoring exception during close: " + exc);
        }
        throw ex;
    }
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) PooledConnection(javax.sql.PooledConnection) NoSuchElementException(java.util.NoSuchElementException) SQLFeatureNotSupportedException(java.sql.SQLFeatureNotSupportedException) SQLException(java.sql.SQLException) NoSuchElementException(java.util.NoSuchElementException)

Example 19 with NoSuchElementException

use of java.util.NoSuchElementException in project tomcat by apache.

the class PerUserPoolDataSource method getPooledConnectionAndInfo.

// ----------------------------------------------------------------------
// Inherited abstract methods
@Override
protected PooledConnectionAndInfo getPooledConnectionAndInfo(final String username, final String password) throws SQLException {
    final PoolKey key = getPoolKey(username);
    ObjectPool<PooledConnectionAndInfo> pool;
    PooledConnectionManager manager;
    synchronized (this) {
        manager = managers.get(key);
        if (manager == null) {
            try {
                registerPool(username, password);
                manager = managers.get(key);
            } catch (final NamingException e) {
                throw new SQLException("RegisterPool failed", e);
            }
        }
        pool = ((CPDSConnectionFactory) manager).getPool();
    }
    PooledConnectionAndInfo info = null;
    try {
        info = pool.borrowObject();
    } catch (final NoSuchElementException ex) {
        throw new SQLException("Could not retrieve connection info from pool", ex);
    } catch (final Exception e) {
        // See if failure is due to CPDSConnectionFactory authentication failure
        try {
            testCPDS(username, password);
        } catch (final Exception ex) {
            throw new SQLException("Could not retrieve connection info from pool", ex);
        }
        // New password works, so kill the old pool, create a new one, and borrow
        manager.closePool(username);
        synchronized (this) {
            managers.remove(key);
        }
        try {
            registerPool(username, password);
            pool = getPool(key);
        } catch (final NamingException ne) {
            throw new SQLException("RegisterPool failed", ne);
        }
        try {
            info = pool.borrowObject();
        } catch (final Exception ex) {
            throw new SQLException("Could not retrieve connection info from pool", ex);
        }
    }
    return info;
}
Also used : SQLException(java.sql.SQLException) NamingException(javax.naming.NamingException) NoSuchElementException(java.util.NoSuchElementException) IOException(java.io.IOException) NamingException(javax.naming.NamingException) SQLException(java.sql.SQLException) NoSuchElementException(java.util.NoSuchElementException)

Example 20 with NoSuchElementException

use of java.util.NoSuchElementException in project zookeeper by apache.

the class DistributedQueue method remove.

/**
     * Attempts to remove the head of the queue and return it.
     * @return The former head of the queue
     * @throws NoSuchElementException
     * @throws KeeperException
     * @throws InterruptedException
     */
public byte[] remove() throws NoSuchElementException, KeeperException, InterruptedException {
    TreeMap<Long, String> orderedChildren;
    // Same as for element.  Should refactor this.
    while (true) {
        try {
            orderedChildren = orderedChildren(null);
        } catch (KeeperException.NoNodeException e) {
            throw new NoSuchElementException();
        }
        if (orderedChildren.size() == 0)
            throw new NoSuchElementException();
        for (String headNode : orderedChildren.values()) {
            String path = dir + "/" + headNode;
            try {
                byte[] data = zookeeper.getData(path, false, null);
                zookeeper.delete(path, -1);
                return data;
            } catch (KeeperException.NoNodeException e) {
            // Another client deleted the node first.
            }
        }
    }
}
Also used : KeeperException(org.apache.zookeeper.KeeperException) NoSuchElementException(java.util.NoSuchElementException)

Aggregations

NoSuchElementException (java.util.NoSuchElementException)645 Iterator (java.util.Iterator)119 Scanner (java.util.Scanner)59 Test (org.junit.Test)53 IOException (java.io.IOException)49 ArrayList (java.util.ArrayList)47 InputMismatchException (java.util.InputMismatchException)46 StringTokenizer (java.util.StringTokenizer)43 Locale (java.util.Locale)24 HashMap (java.util.HashMap)22 NodeIterator (javax.jcr.NodeIterator)20 File (java.io.File)19 Map (java.util.Map)19 ConcurrentLinkedDeque (java.util.concurrent.ConcurrentLinkedDeque)16 Collection (java.util.Collection)15 LinkedList (java.util.LinkedList)15 List (java.util.List)15 Set (java.util.Set)15 BufferedReader (java.io.BufferedReader)13 Enumeration (java.util.Enumeration)13