/**
  * This will be called if the Connection returned by the getConnection method came from a
  * PooledConnection, and the user calls the close() method of this connection object. What we need
  * to do here is to release this PooledConnection from our pool...
  */
 public void connectionClosed(ConnectionEvent event) {
   PooledConnection pc = (PooledConnection) event.getSource();
   // if this event occurred because we were validating, or if this
   // connection has been marked for removal, ignore it
   // otherwise return the connection to the pool.
   if (!muteMap.containsKey(pc)) {
     PooledConnectionAndInfo info = (PooledConnectionAndInfo) pcMap.get(pc);
     if (info == null) {
       throw new IllegalStateException(NO_KEY_MESSAGE);
     }
     try {
       _pool.returnObject(info.getUserPassKey(), info);
     } catch (Exception e) {
       System.err.println("CLOSING DOWN CONNECTION AS IT COULD " + "NOT BE RETURNED TO THE POOL");
       cleanupMap.put(pc, null); // mark for cleanup
       muteMap.put(pc, null); // ignore events until listener is removed
       try {
         _pool.invalidateObject(info.getUserPassKey(), info);
       } catch (Exception e3) {
         System.err.println("EXCEPTION WHILE DESTROYING OBJECT " + info);
         e3.printStackTrace();
       }
     }
   }
 }
 public void testBorrowFromEmptyPoolWithNullFactory() throws Exception {
   KeyedObjectPool pool = new StackKeyedObjectPool();
   try {
     pool.borrowObject("x");
     fail("Expected NoSuchElementException");
   } catch (NoSuchElementException e) {
     // expected
   }
 }
  public void testCantResetFactoryWithActiveObjects() throws Exception {
    KeyedObjectPool pool = new StackKeyedObjectPool();
    pool.setFactory(new SimpleFactory());
    Object obj = pool.borrowObject("x");
    assertNotNull(obj);

    try {
      pool.setFactory(new SimpleFactory());
      fail("Expected IllegalStateException");
    } catch (IllegalStateException e) {
      // expected
    }
  }
 public void testSetFactory() throws Exception {
   KeyedObjectPool pool = new StackKeyedObjectPool();
   try {
     pool.borrowObject("x");
     fail("Expected NoSuchElementException");
   } catch (NoSuchElementException e) {
     // expected
   }
   pool.setFactory(new SimpleFactory());
   Object obj = pool.borrowObject("x");
   assertNotNull(obj);
   pool.returnObject("x", obj);
 }
 /**
  * Close and free all {@link PreparedStatement}s from my pool, and close my underlying connection.
  */
 public synchronized void close() throws SQLException {
   if (null != _pstmtPool) {
     KeyedObjectPool oldpool = _pstmtPool;
     _pstmtPool = null;
     try {
       oldpool.close();
     } catch (RuntimeException e) {
       throw e;
     } catch (SQLException e) {
       throw e;
     } catch (Exception e) {
       throw new SQLNestedException("Cannot close connection", e);
     }
   }
   getInnermostDelegate().close();
 }
 /**
  * Create a new <tt>KeyedPoolableConnectionFactory</tt>.
  *
  * @param cpds the ConnectionPoolDataSource from which to obtain PooledConnection's
  * @param pool the {*link ObjectPool} in which to pool those {*link Connection}s
  * @param validationQuery a query to use to {*link #validateObject validate} {*link Connection}s.
  *     Should return at least one row. May be <tt>null</tt>
  */
 public KeyedCPDSConnectionFactory(
     ConnectionPoolDataSource cpds, KeyedObjectPool pool, String validationQuery) {
   _cpds = cpds;
   _pool = pool;
   _pool.setFactory(this);
   _validationQuery = validationQuery;
 }
  /**
   * If a fatal error occurs, close the underlying physical connection so as not to be returned in
   * the future
   */
  public void connectionErrorOccurred(ConnectionEvent event) {
    PooledConnection pc = (PooledConnection) event.getSource();
    if (cleanupMap.containsKey(pc)) {
      return; // waiting for listener cleanup - ignore event
    }
    try {
      if (null != event.getSQLException()) {
        System.err.println(
            "CLOSING DOWN CONNECTION DUE TO INTERNAL ERROR (" + event.getSQLException() + ")");
      }
      cleanupMap.put(pc, null); // mark for cleanup
      muteMap.put(pc, null); // ignore events until listener is removed
    } catch (Exception ignore) {
      // ignore
    }

    PooledConnectionAndInfo info = (PooledConnectionAndInfo) pcMap.get(pc);
    if (info == null) {
      throw new IllegalStateException(NO_KEY_MESSAGE);
    }
    try {
      _pool.invalidateObject(info.getUserPassKey(), info);
    } catch (Exception e) {
      System.err.println("EXCEPTION WHILE DESTROYING OBJECT " + info);
      e.printStackTrace();
    }
  }
 /**
  * Create or obtain a {@link PreparedStatement} from my pool.
  *
  * @return a {@link PoolablePreparedStatement}
  */
 public synchronized PreparedStatement prepareStatement(String sql) throws SQLException {
   try {
     return (PreparedStatement) (_pstmtPool.borrowObject(createKey(sql)));
   } catch (NoSuchElementException e) {
     throw new SQLNestedException("MaxOpenPreparedStatements limit reached", e);
   } catch (RuntimeException e) {
     throw e;
   } catch (Exception e) {
     throw new SQLNestedException("Borrow prepareStatement from pool failed", e);
   }
 }
 /**
  * Sets the {*link ObjectPool} in which to pool {*link Connection}s.
  *
  * @param pool the {*link ObjectPool} in which to pool those {*link Connection}s
  */
 public synchronized void setPool(KeyedObjectPool pool) throws SQLException {
   if (null != _pool && pool != _pool) {
     try {
       _pool.close();
     } catch (RuntimeException e) {
       throw e;
     } catch (Exception e) {
       throw new SQLNestedException("Cannot set the pool on this factory", e);
     }
   }
   _pool = pool;
 }
Esempio n. 10
0
  public Object getValue(String serviceURL, String object, String attribute, String key)
      throws Exception {
    JMXConnector jmxc = null;
    try {
      // pega conector do pool
      jmxc = (JMXConnector) connectionPool.borrowObject(serviceURL);
      MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

      ObjectName name = new ObjectName(object);
      Object value = mbsc.getAttribute(name, attribute);
      if (value instanceof CompositeData) {
        if (key == null) {
          logger.warn(
              "Attribute {}:{} is CompositeData but resource did not define a 'compositeDataKey'",
              object,
              attribute);
          value = null;
        } else {
          CompositeData data = (CompositeData) value;
          value = data.get(key);
        }
      }
      return value;

    } catch (Exception e) {
      if (null != jmxc) {
        connectionPool.invalidateObject(serviceURL, jmxc);
        jmxc = null;
      }
      throw e;

    } finally {
      if (null != jmxc) {
        connectionPool.returnObject(serviceURL, jmxc);
      }
    }
  }
  /** Close all pools in the given Map. */
  private static void close(Map poolMap) {
    // Get iterator to loop over all pools.
    Iterator poolIter = poolMap.entrySet().iterator();

    while (poolIter.hasNext()) {
      Map.Entry nextPoolEntry = (Map.Entry) poolIter.next();

      if (nextPoolEntry.getValue() instanceof ObjectPool) {
        ObjectPool nextPool = (ObjectPool) nextPoolEntry.getValue();
        try {
          nextPool.close();
        } catch (Exception closePoolException) {
          // ignore and try to close others.
        }
      } else {
        KeyedObjectPool nextPool = (KeyedObjectPool) nextPoolEntry.getValue();
        try {
          nextPool.close();
        } catch (Exception closePoolException) {
          // ignore and try to close others.
        }
      }
    }
  }
 public void testCanResetFactoryWithoutActiveObjects() throws Exception {
   KeyedObjectPool pool = new StackKeyedObjectPool();
   {
     pool.setFactory(new SimpleFactory());
     Object obj = pool.borrowObject("x");
     assertNotNull(obj);
     pool.returnObject("x", obj);
   }
   {
     pool.setFactory(new SimpleFactory());
     Object obj = pool.borrowObject("x");
     assertNotNull(obj);
     pool.returnObject("x", obj);
   }
 }
 public void testPoolWithNullFactory() throws Exception {
   KeyedObjectPool pool = new StackKeyedObjectPool(10);
   for (int i = 0; i < 10; i++) {
     pool.returnObject("X", new Integer(i));
   }
   for (int j = 0; j < 3; j++) {
     Integer[] borrowed = new Integer[10];
     BitSet found = new BitSet();
     for (int i = 0; i < 10; i++) {
       borrowed[i] = (Integer) (pool.borrowObject("X"));
       assertNotNull(borrowed);
       assertTrue(!found.get(borrowed[i].intValue()));
       found.set(borrowed[i].intValue());
     }
     for (int i = 0; i < 10; i++) {
       pool.returnObject("X", borrowed[i]);
     }
   }
   pool.invalidateObject("X", pool.borrowObject("X"));
   pool.invalidateObject("X", pool.borrowObject("X"));
   pool.clear("X");
   pool.clear();
 }
 public String toString() {
   return "PoolingConnection: " + _pstmtPool.toString();
 }
  public void testHelperMethods() throws Exception {
    keyedObjectPoolMock.returnObject(DirContextType.READ_ONLY, contextMock);
    keyedObjectPoolControl.setVoidCallable(1);

    replay();

    // Wrap the Context once
    final DelegatingContext delegatingContext =
        new DelegatingContext(keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY);

    final Context delegateContext = delegatingContext.getDelegateContext();
    assertEquals(contextMock, delegateContext);

    final Context innerDelegateContext = delegatingContext.getInnermostDelegateContext();
    assertEquals(contextMock, innerDelegateContext);

    delegatingContext.assertOpen();

    // Wrap the wrapper
    MockControl secondKeyedObjectPoolControl = MockControl.createControl(KeyedObjectPool.class);
    KeyedObjectPool secondKeyedObjectPoolMock =
        (KeyedObjectPool) secondKeyedObjectPoolControl.getMock();
    secondKeyedObjectPoolMock.returnObject(DirContextType.READ_ONLY, delegatingContext);
    secondKeyedObjectPoolControl.setVoidCallable(1);
    secondKeyedObjectPoolControl.replay();

    final DelegatingContext delegatingContext2 =
        new DelegatingContext(
            secondKeyedObjectPoolMock, delegatingContext, DirContextType.READ_ONLY);

    final Context delegateContext2 = delegatingContext2.getDelegateContext();
    assertEquals(delegatingContext, delegateContext2);

    final Context innerDelegateContext2 = delegatingContext2.getInnermostDelegateContext();
    assertEquals(contextMock, innerDelegateContext2);

    delegatingContext2.assertOpen();

    // Close the outer wrapper
    delegatingContext2.close();

    final Context delegateContext2closed = delegatingContext2.getDelegateContext();
    assertNull(delegateContext2closed);

    final Context innerDelegateContext2closed = delegatingContext2.getInnermostDelegateContext();
    assertNull(innerDelegateContext2closed);

    try {
      delegatingContext2.assertOpen();
      fail("delegatingContext2.assertOpen() should have thrown a NamingException");
    } catch (NamingException ne) {
      // Expected
    }

    // Close the outer wrapper
    delegatingContext.close();

    final Context delegateContextclosed = delegatingContext.getDelegateContext();
    assertNull(delegateContextclosed);

    final Context innerDelegateContextclosed = delegatingContext.getInnermostDelegateContext();
    assertNull(innerDelegateContextclosed);

    try {
      delegatingContext.assertOpen();
      fail("delegatingContext.assertOpen() should have thrown a NamingException");
    } catch (NamingException ne) {
      // Expected
    }

    verify();
    secondKeyedObjectPoolControl.verify();
  }
  public void testBorrowReturnWithSometimesInvalidObjects() throws Exception {
    KeyedObjectPool pool =
        new StackKeyedObjectPool(
            new KeyedPoolableObjectFactory() {
              int counter = 0;

              public Object makeObject(Object key) {
                return new Integer(counter++);
              }

              public void destroyObject(Object key, Object obj) {}

              public boolean validateObject(Object key, Object obj) {
                if (obj instanceof Integer) {
                  return ((((Integer) obj).intValue() % 2) == 1);
                } else {
                  return false;
                }
              }

              public void activateObject(Object key, Object obj) {}

              public void passivateObject(Object key, Object obj) {
                if (obj instanceof Integer) {
                  if ((((Integer) obj).intValue() % 3) == 0) {
                    throw new RuntimeException("Couldn't passivate");
                  }
                } else {
                  throw new RuntimeException("Couldn't passivate");
                }
              }
            });

    Object[] obj = new Object[10];
    for (int i = 0; i < 10; i++) {
      Object object = null;
      int k = 0;
      while (object == null && k < 100) { // bound not really needed
        try {
          k++;
          object = pool.borrowObject("key");
          obj[i] = object;
        } catch (NoSuchElementException ex) {
          // Expected for evens, which fail validation
        }
      }
      assertEquals("Each time we borrow, get one more active.", i + 1, pool.getNumActive());
    }
    // 1,3,5,...,19 pass validation, get checked out
    for (int i = 0; i < 10; i++) {
      pool.returnObject("key", obj[i]);
      assertEquals("Each time we borrow, get one less active.", 9 - i, pool.getNumActive());
    }
    // 3, 9, 15 fail passivation.
    assertEquals(7, pool.getNumIdle());
    assertEquals(new Integer(19), pool.borrowObject("key"));
    assertEquals(new Integer(17), pool.borrowObject("key"));
    assertEquals(new Integer(13), pool.borrowObject("key"));
    assertEquals(new Integer(11), pool.borrowObject("key"));
    assertEquals(new Integer(7), pool.borrowObject("key"));
    assertEquals(new Integer(5), pool.borrowObject("key"));
    assertEquals(new Integer(1), pool.borrowObject("key"));
  }