private int updateRecords() throws Throwable {
   ODatabaseDocumentTx database = null;
   try {
     database = ODatabaseDocumentPool.global().acquire(getDatabaseURL(), "admin", "admin");
     int numRetries = 0;
     int numUpdated = 0;
     while (numRetries < NUM_RETRIES) {
       database.begin();
       try {
         OCommandSQL cmd =
             new OCommandSQL("UPDATE ExceptionRecord set jobId='2' where username='******'");
         numUpdated = database.command(cmd).execute((Object[]) null);
         database.commit();
         break;
       } catch (Throwable e) {
         database.rollback();
         logger.log(Level.SEVERE, "********************************");
         logger.log(Level.SEVERE, "Update Iteration=" + numRetries + ", " + e.toString(), e);
         logger.log(Level.SEVERE, "********************************");
         if (numRetries++ == NUM_RETRIES) {
           throw e;
         }
       }
     }
     return numUpdated;
   } finally {
     if (database != null && !database.isClosed()) {
       database.close();
     }
   }
 }
  public static ODatabaseDocumentTx acquire(
      final String iName, final String iUserName, final String iUserPassword)
      throws InterruptedException {
    final String path = OServerMain.server().getStoragePath(iName);

    return ODatabaseDocumentPool.global().acquire(path, iUserName, iUserPassword);
  }
  @Test
  public void testGetNewConnection() {
    ODatabaseDocumentPool poolMock = mock(ODatabaseDocumentPool.class);

    when(poolMock.acquire(expectedDatabaseUrl, expectedUserName, expectedPassword))
        .thenReturn(expectedConnection);

    connectionManager =
        new ConnectionManager(expectedDatabaseUrl, expectedUserName, expectedPassword, poolMock);

    ODatabaseDocument newConnection = connectionManager.getNewConnection();

    assertEquals("Created connection not same as expected.", expectedConnection, newConnection);

    verify(poolMock).acquire(expectedDatabaseUrl, expectedUserName, expectedPassword);
    verifyZeroInteractions(expectedConnection);
  }
  /**
   * @return A connection from the pool. Call close on the connection when done to return to the
   *     pool.
   * @throws InternalServerErrorException
   */
  ODatabaseDocumentTx getConnection() throws InternalServerErrorException {
    ODatabaseDocumentTx db = null;
    int maxRetry = 100; // give it up to approx 10 seconds to recover
    int retryCount = 0;

    synchronized (dbLock) {
      while (db == null && retryCount < maxRetry) {
        retryCount++;
        try {
          db = pool.acquire(dbURL, user, password);
          if (retryCount > 1) {
            logger.info(
                "Succeeded in acquiring connection from pool in retry attempt {}", retryCount);
          }
          retryCount = maxRetry;
        } catch (com.orientechnologies.common.concur.lock.OLockException ex) {
          // TODO: remove work-around once OrientDB resolves this condition
          if (retryCount == maxRetry) {
            logger.warn(
                "Failure reported acquiring connection from pool, retried {} times before giving up.",
                retryCount,
                ex);
            throw new InternalServerErrorException(
                "Failure reported acquiring connection from pool, retried "
                    + retryCount
                    + " times before giving up: "
                    + ex.getMessage(),
                ex);
          } else {
            logger.info("Pool acquire reported failure, retrying - attempt {}", retryCount);
            logger.trace("Pool acquire failure detail ", ex);
            try {
              Thread.sleep(100); // Give the DB time to complete what it's doing before retrying
            } catch (InterruptedException iex) {
              // ignore that sleep was interrupted
            }
          }
        }
      }
    }
    return db;
  }
  private void createExceptionRecords(int count, boolean batch) throws Exception {
    ODatabaseDocumentTx database = null;
    try {
      database = ODatabaseDocumentPool.global().acquire(getDatabaseURL(), "admin", "admin");
      database.begin();
      for (int x = 0; x < count; x++) {
        String ID = UUID.randomUUID().toString();
        ODocument document = database.newInstance("ExceptionRecord");
        document.field("id", ID);
        document.field("data", DATA);
        document.field("status", "original");
        document.field("approved", false);
        document.field("groupNonException", false);
        document.field("comment", "");
        document.field("jobId", "1");
        document.field("dataflowName", "Error_Handling_V5");
        document.field("username", "admin");
        document.field("timestamp", new Date().getTime());
        document.field("stageLabel", "Exception Monitor");
        document.field("groupColumn", "");
        document.field("lastModifiedBy", "admin");
        document.field("lastModified", new Date());
        database.save(document);

        createExceptionRecordVersion(database, ID, "1");
        if (batch && (x % BATCH_SIZE) == 0) {
          System.out.println("Committing batch of " + BATCH_SIZE);
          database.commit();
          database.begin();
        }
      }
      database.commit();
    } catch (Throwable e) {
      database.rollback();
      throw e;
    } finally {
      if (database != null) {
        database.close();
      }
    }
  }
 private int deleteRecordsWithLimit() throws Throwable {
   ODatabaseDocumentTx database = null;
   try {
     database = ODatabaseDocumentPool.global().acquire(getDatabaseURL(), "admin", "admin");
     int numRetries = 0;
     int numDeleted = 0;
     while (numRetries < NUM_RETRIES) {
       try {
         int deletedBatch = 0;
         do {
           database.begin();
           OCommandSQL cmd =
               new OCommandSQL(
                   "DELETE from ExceptionRecord where username='******' LIMIT " + BATCH_SIZE);
           deletedBatch = database.command(cmd).execute((Object[]) null);
           numDeleted += deletedBatch;
           database.commit();
         } while (deletedBatch > 0);
         break;
       } catch (Throwable e) {
         database.rollback();
         logger.log(Level.SEVERE, "********************************");
         logger.log(Level.SEVERE, "Delete Iteration=" + numRetries + ", " + e.toString(), e);
         logger.log(Level.SEVERE, "********************************");
         if (numRetries++ == NUM_RETRIES) {
           throw e;
         }
       }
     }
     return numDeleted;
   } finally {
     if (database != null && !database.isClosed()) {
       database.close();
     }
   }
 }
 public static void remove(String iName, String iUser) {
   ODatabaseDocumentPool.global().remove(iName, iUser);
 }
 public static Map<String, OResourcePool<String, ODatabaseDocumentTx>> getDatabasePools() {
   return ODatabaseDocumentPool.global().getPools();
 }
 protected ODatabaseDocumentTx getDatabase(final String dbUrl) {
   return ODatabaseDocumentPool.global(threads, threads * 2)
       .acquire(dbUrl, userName, userPassword);
 }