/**
   * Gets the amount of transaction in ProtocolStatus as Pending Notified from the specified table
   *
   * @param transactionType
   * @return
   * @throws CantExecuteDatabaseOperationException
   */
  public int getPendingNotifiedTransactions(TransactionTypes transactionType)
      throws CantExecuteDatabaseOperationException {
    DatabaseTable databaseTable;
    if (transactionType == TransactionTypes.OUTGOING) {
      databaseTable =
          database.getTable(BitcoinCryptoNetworkDatabaseConstants.OUTGOING_TRANSACTIONS_TABLE_NAME);
      databaseTable.setStringFilter(
          BitcoinCryptoNetworkDatabaseConstants.OUTGOING_TRANSACTIONS_PROTOCOL_STATUS_COLUMN_NAME,
          ProtocolStatus.TO_BE_NOTIFIED.getCode(),
          DatabaseFilterType.EQUAL);
    } else {
      databaseTable =
          database.getTable(BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_TABLE_NAME);
      databaseTable.setStringFilter(
          BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_PROTOCOL_STATUS_COLUMN_NAME,
          ProtocolStatus.TO_BE_NOTIFIED.getCode(),
          DatabaseFilterType.EQUAL);
    }

    try {
      databaseTable.loadToMemory();
    } catch (CantLoadTableToMemoryException e) {
      throwLoadToMemoryException(e, databaseTable.getTableName());
    }

    /** I return the amount of records. */
    return databaseTable.getRecords().size();
  }
  private void setUpMockitoRules() throws Exception {

    when(mockDatabase.getDatabaseFactory()).thenReturn(mockDatabaseFactory);
    when(mockDatabaseTable.getEmptyRecord()).thenReturn(mockDatabaseTableRecord);
    when(mockDatabase.getTable(AssetIssuingDatabaseConstants.ASSET_ISSUING_TABLE_NAME))
        .thenReturn(mockDatabaseTable);
    when(pluginDatabaseSystem.openDatabase(
            pluginId, AssetIssuingDatabaseConstants.ASSET_ISSUING_DATABASE))
        .thenReturn(mockDatabase);

    //        when(mockExtraUserActorDatabaseFactory.createDatabase(pluginId,
    // pluginId.toString())).thenReturn(mockDatabase);
    when(deviceUser.getPublicKey()).thenReturn("myPublicKey");
    when(deviceUserManager.getLoggedInDeviceUser()).thenReturn(deviceUser);
    when(eventManager.getNewListener(
            EventType.INCOMING_ASSET_ON_CRYPTO_NETWORK_WAITING_TRANSFERENCE_ASSET_ISSUER))
        .thenReturn(fermatEventListener1);
    when(eventManager.getNewListener(
            EventType.INCOMING_ASSET_ON_BLOCKCHAIN_WAITING_TRANSFERENCE_ASSET_ISSUER))
        .thenReturn(fermatEventListener2);
    when(eventManager.getNewListener(
            EventType.INCOMING_ASSET_REVERSED_ON_BLOCKCHAIN_WAITING_TRANSFERENCE_ASSET_ISSUER))
        .thenReturn(fermatEventListener3);
    when(eventManager.getNewListener(
            EventType.INCOMING_ASSET_REVERSED_ON_CRYPTO_NETWORK_WAITING_TRANSFERENCE_ASSET_ISSUER))
        .thenReturn(fermatEventListener4);
    when(eventManager.getNewListener(EventType.RECEIVED_NEW_DIGITAL_ASSET_METADATA_NOTIFICATION))
        .thenReturn(fermatEventListener5);

    when(actorAssetIssuerManager.getActorAssetIssuer()).thenReturn(actorAssetIssuer);
  }
Пример #3
0
  @Before
  public void setUp() throws Exception {

    bitcoinCryptoVault = new BitcoinCryptoVault(userPublicKey);
    bitcoinCryptoVault.setPluginFileSystem(pluginFileSystem);
    bitcoinCryptoVault.setPluginDatabaseSystem(pluginDatabaseSystem);
    bitcoinCryptoVault.setPluginFileSystem(pluginFileSystem);
    bitcoinCryptoVault.setUserPublicKey(userPublicKey);
    bitcoinCryptoVault.setDatabase(mockDatabase);

    bitcoinCryptoVault.setPluginId(pluginId);
    bitcoinCryptoVault.setLogManager(mockLogManager);
    when(pluginFileSystem.createTextFile(
            pluginId,
            userPublicKey,
            userPublicKey.toString() + ".vault",
            FilePrivacy.PRIVATE,
            FileLifeSpan.PERMANENT))
        .thenReturn(mockPluginTextFile);

    bitcoinCryptoVault.loadOrCreateVault();

    when(pluginDatabaseSystem.openDatabase(pluginId, userPublicKey)).thenReturn(mockDatabase);
    when(mockDatabase.getTable(anyString())).thenReturn(mockTable);
    when(mockDatabase.newTransaction()).thenReturn(mockDatabaseTransaction);
    when(mockTable.getRecords()).thenReturn(mockRecords);
    Mockito.doReturn(mockRecord).when(mockRecords).get(0);
  }
  /**
   * Gets both incoming and outgoing transactions hash stored in the database
   *
   * @return
   * @throws CantExecuteDatabaseOperationException
   */
  public Set<String> getStoredStransactionsHash() throws CantExecuteDatabaseOperationException {
    Set<String> transactionsSet = new HashSet<>();

    /** Loads and puts in the transactionsSet the list of stored Hashes */
    DatabaseTable databaseTable =
        database.getTable(BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_TABLE_NAME);
    try {
      databaseTable.loadToMemory();
    } catch (CantLoadTableToMemoryException e) {
      throwLoadToMemoryException(e, databaseTable.getTableName());
    }

    for (DatabaseTableRecord record : databaseTable.getRecords()) {
      transactionsSet.add(
          record.getStringValue(
              BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_HASH_COLUMN_NAME));
    }

    /** Loads and puts in the transactionsSet the list of stored Hashes */
    databaseTable =
        database.getTable(BitcoinCryptoNetworkDatabaseConstants.OUTGOING_TRANSACTIONS_TABLE_NAME);
    try {
      databaseTable.loadToMemory();
    } catch (CantLoadTableToMemoryException e) {
      throwLoadToMemoryException(e, databaseTable.getTableName());
    }

    for (DatabaseTableRecord record : databaseTable.getRecords()) {
      transactionsSet.add(
          record.getStringValue(
              BitcoinCryptoNetworkDatabaseConstants.OUTGOING_TRANSACTIONS_HASH_COLUMN_NAME));
    }

    return transactionsSet;
  }
  public List<CryptoMoneyTransaction> getCryptoMoneyTransactionList(DatabaseTableFilter filter)
      throws DatabaseOperationException, InvalidParameterException {
    Database database = null;
    try {
      database = openDatabase();
      List<CryptoMoneyTransaction> cryptoMoneyTransactions = new ArrayList<>();
      // I will add the Asset Factory information from the database
      for (DatabaseTableRecord cryptoMoneyRestockRecord : getCryptoMoneyRestockData(filter)) {
        final CryptoMoneyTransaction cryptoMoneyTransaction =
            getCryptoMoneyRestockTransaction(cryptoMoneyRestockRecord);

        cryptoMoneyTransactions.add(cryptoMoneyTransaction);
      }

      database.closeDatabase();

      return cryptoMoneyTransactions;
    } catch (Exception e) {
      if (database != null) database.closeDatabase();
      throw new DatabaseOperationException(
          DatabaseOperationException.DEFAULT_MESSAGE,
          e,
          "error trying to get Bank Money Restock Transaction from the database with filter: "
              + filter.toString(),
          null);
    }
  }
Пример #6
0
  public void setUpDataBase() throws Exception {

    when(mockPluginDatabaseSystem.openDatabase(any(UUID.class), anyString()))
        .thenReturn(mockDatabase);
    when(mockDatabaseFactory.newTableFactory(any(UUID.class), anyString()))
        .thenReturn(mockFactoryTable);
    when(mockDatabase.getTable(anyString())).thenReturn(mockDatabaseTable);
    when(mockDatabaseTable.getEmptyRecord()).thenReturn(mockDatabaseTableRecord);
    when(mockDatabase.newTransaction()).thenReturn(mockTransaction);
    subAppResourcesDAO = new SubAppResourcesInstallationNetworkServiceDAO(mockPluginDatabaseSystem);
    subAppResourcesDAO = new SubAppResourcesInstallationNetworkServiceDAO(mockPluginDatabaseSystem);

    String path = "path1";
    String skinName = "skinName1";
    String navigationStructureVersion = "version1";
    repository = new Repository(skinName, navigationStructureVersion, path);

    subAppResourcesDAO.initializeDatabase(
        UUID.randomUUID(), SubAppResourcesNetworkServiceDatabaseConstants.DATABASE_NAME);
    skinId = UUID.randomUUID();
    subAppResourcesDAO.createRepository(repository, skinId);
    when(mockDatabase.getTable(anyString())).thenReturn(mockDatabaseTable);
    mockDatabaseTable.setUUIDFilter(
        SubAppResourcesNetworkServiceDatabaseConstants.REPOSITORIES_SKIN_ID_COLUMN_NAME,
        skinId,
        DatabaseFilterType.EQUAL);
    mockDatabaseTable.loadToMemory();
    when(mockDatabaseTable.getRecords()).thenReturn(databaseTableRecordList);
    when(databaseTableRecordList.get(anyInt())).thenReturn(mockDatabaseTableRecord);
    when(mockDatabaseTableRecord.getStringValue(anyString())).thenReturn(anyString());
  }
 public List<DeveloperDatabaseTableRecord> getDatabaseTableContent(
     DeveloperObjectFactory developerObjectFactory,
     DeveloperDatabaseTable developerDatabaseTable) {
   /** Will get the records for the given table */
   List<DeveloperDatabaseTableRecord> returnedRecords =
       new ArrayList<DeveloperDatabaseTableRecord>();
   /** I load the passed table name from the SQLite database. */
   DatabaseTable selectedTable = database.getTable(developerDatabaseTable.getName());
   try {
     selectedTable.loadToMemory();
     List<DatabaseTableRecord> records = selectedTable.getRecords();
     for (DatabaseTableRecord row : records) {
       List<String> developerRow = new ArrayList<String>();
       /** for each row in the table list */
       for (DatabaseRecord field : row.getValues()) {
         /** I get each row and save them into a List<String> */
         developerRow.add(field.getValue());
       }
       /** I create the Developer Database record */
       returnedRecords.add(
           developerObjectFactory.getNewDeveloperDatabaseTableRecord(developerRow));
     }
     /** return the list of DeveloperRecords for the passed table. */
   } catch (CantLoadTableToMemoryException cantLoadTableToMemory) {
     /** if there was an error, I will returned an empty list. */
     database.closeDatabase();
     return returnedRecords;
   } catch (Exception e) {
     database.closeDatabase();
     return returnedRecords;
   }
   database.closeDatabase();
   return returnedRecords;
 }
  public void update(NegotiationTransmission entity) throws CantUpdateRecordDataBaseException {

    if (entity == null) {
      throw new IllegalArgumentException("The entity is required, can not be null");
    }

    try {

      DatabaseTable outgoingNotificationtable = getDatabaseTable();

      DatabaseTableRecord emptyRecord = getDatabaseTable().getEmptyRecord();
      /*
       * 1- Create the record to the entity
       */
      DatabaseTableRecord entityRecord =
          loadRecordAsSendNegotiationTransmission(emptyRecord, entity);

      /** 2.- Create a new transaction and execute */
      DatabaseTransaction transaction = database.newTransaction();

      // Set filter
      outgoingNotificationtable.addUUIDFilter(
          NegotiationTransmissionNetworkServiceDatabaseConstants
              .OUTGOING_NOTIFICATION_TRANSMISSION_ID_COLUMN_NAME,
          entity.getTransmissionId(),
          DatabaseFilterType.EQUAL);
      //
      // outgoingNotificationtable.addUUIDFilter(NegotiationTransmissionNetworkServiceDatabaseConstants.INCOMING_NOTIFICATION_TRANSACTION_ID_COLUMN_NAME, entity.getTransactionId(), DatabaseFilterType.EQUAL);
      //
      // outgoingNotificationtable.addUUIDFilter(NegotiationTransmissionNetworkServiceDatabaseConstants.INCOMING_NOTIFICATION_NEGOTIATION_ID_COLUMN_NAME, entity.getNegotiationId(), DatabaseFilterType.EQUAL);

      transaction.addRecordToUpdate(outgoingNotificationtable, entityRecord);
      database.executeTransaction(transaction);

    } catch (DatabaseTransactionFailedException databaseTransactionFailedException) {
      // Register the failure.
      StringBuilder contextBuilder = new StringBuilder();
      contextBuilder
          .append("Database Name: ")
          .append(NegotiationTransmissionNetworkServiceDatabaseConstants.DATA_BASE_NAME);

      String context = contextBuilder.toString();
      String possibleCause = "The record do not exist";
      CantUpdateRecordDataBaseException cantUpdateRecordDataBaseException =
          new CantUpdateRecordDataBaseException(
              CantUpdateRecordDataBaseException.DEFAULT_MESSAGE,
              databaseTransactionFailedException,
              context,
              possibleCause);
      throw cantUpdateRecordDataBaseException;
      //        } catch (CantBuildDataBaseRecordException e) {
      //            CantUpdateRecordDataBaseException cantUpdateRecordDataBaseException = new
      // CantUpdateRecordDataBaseException(CantUpdateRecordDataBaseException.DEFAULT_MESSAGE, e, "",
      // "");
      //            throw cantUpdateRecordDataBaseException;
    }
  }
Пример #9
0
 @Test
 public void test() {
   List<DatabaseTableRecord> records = mock(ArrayList.class);
   when(database.getTable(anyString())).thenReturn(table);
   when(database.newTransaction()).thenReturn(transaction);
   when(table.getRecords()).thenReturn(records);
   when(table.getEmptyRecord()).thenReturn(record);
   when(records.isEmpty()).thenReturn(true);
   VaultEventListeners eventListeners =
       new VaultEventListeners(database, errorManager, eventManager, logManager);
   eventListeners.onCoinsReceived(wallet, tx, Coin.CENT, Coin.CENT);
 }
 private void setUpMockitoGeneralRules() throws Exception {
   when(mockPluginDatabaseSystem.createDatabase(
           pluginId, IntraWalletUserActorDatabaseConstants.INTRA_WALLET_USER_DATABASE_NAME))
       .thenReturn(mockDatabase);
   when(mockDatabase.getDatabaseFactory()).thenReturn(mockDatabaseFactory);
   when(mockDatabaseFactory.newTableFactory(
           pluginId, IntraWalletUserActorDatabaseConstants.INTRA_WALLET_USER_TABLE_NAME))
       .thenReturn(mockIntraUserTableFactory);
   when(mockDatabase.getTable(IntraWalletUserActorDatabaseConstants.INTRA_WALLET_USER_TABLE_NAME))
       .thenReturn(mockTable);
   when(mockTable.getEmptyRecord()).thenReturn(mockTableRecord);
 }
 public void setUpMockitoRules() throws Exception {
   when(mockDatabase.getDatabaseFactory()).thenReturn(mockDatabaseFactory);
   when(mockDatabaseTable.getEmptyRecord()).thenReturn(mockDatabaseTableRecord);
   when(mockDatabase.getTable(CryptoIndexDatabaseConstants.CRYPTO_INDEX_TABLE_NAME))
       .thenReturn(mockDatabaseTable);
   when(mockPluginDatabaseSystem.openDatabase(
           pluginId, CryptoIndexDatabaseConstants.CRYPTO_INDEX_DATABASE_NAME))
       .thenReturn(mockDatabase);
   when(mockCryptoIndexDatabaseFactory.createDatabase(
           pluginId, CryptoIndexDatabaseConstants.CRYPTO_INDEX_DATABASE_NAME))
       .thenReturn(mockDatabase);
   cryptoIndexDao = new CryptoIndexDao(mockPluginDatabaseSystem, pluginId);
 }
Пример #12
0
  //    @Override
  public void update(ActorAssetNetworkServiceRecord entity)
      throws CantUpdateRecordDataBaseException {

    if (entity == null) {
      throw new IllegalArgumentException("The entity is required, can not be null");
    }

    try {

      DatabaseTable incomingNotificationtable = getDatabaseTable();

      DatabaseTableRecord emptyRecord = getDatabaseTable().getEmptyRecord();
      /*
       * 1- Create the record to the entity
       */
      DatabaseTableRecord entityRecord = buildDatabaseRecord(emptyRecord, entity);

      /** 2.- Create a new transaction and execute */
      DatabaseTransaction transaction = database.newTransaction();

      // Set filter
      incomingNotificationtable.addUUIDFilter(
          AssetUserNetworkServiceDatabaseConstants.INCOMING_NOTIFICATION_ID_COLUMN_NAME,
          entity.getId(),
          DatabaseFilterType.EQUAL);

      transaction.addRecordToUpdate(incomingNotificationtable, entityRecord);
      database.executeTransaction(transaction);

    } catch (DatabaseTransactionFailedException databaseTransactionFailedException) {
      // Register the failure.
      StringBuffer contextBuffer = new StringBuffer();
      contextBuffer.append(
          "Database Name: " + AssetUserNetworkServiceDatabaseConstants.DATA_BASE_NAME);

      String context = contextBuffer.toString();
      String possibleCause = "The record do not exist";
      CantUpdateRecordDataBaseException cantUpdateRecordDataBaseException =
          new CantUpdateRecordDataBaseException(
              CantUpdateRecordDataBaseException.DEFAULT_MESSAGE,
              databaseTransactionFailedException,
              context,
              possibleCause);
      throw cantUpdateRecordDataBaseException;
    } catch (CantBuildDataBaseRecordException e) {
      CantUpdateRecordDataBaseException cantUpdateRecordDataBaseException =
          new CantUpdateRecordDataBaseException(
              CantUpdateRecordDataBaseException.DEFAULT_MESSAGE, e, "", "");
      throw cantUpdateRecordDataBaseException;
    }
  }
  /**
   * Gets the pending transaction data from the specified table
   *
   * @param transactionType
   * @return
   */
  private List<TransactionProtocolData> getPendingTransactionProtocolData(
      TransactionTypes transactionType) throws CantExecuteDatabaseOperationException {
    DatabaseTable databaseTable;
    String transactionIdColumnName;

    List<TransactionProtocolData> transactionProtocolDataList = new ArrayList<>();

    if (transactionType == TransactionTypes.INCOMING) {
      databaseTable =
          database.getTable(BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_TABLE_NAME);
      databaseTable.setStringFilter(
          BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_PROTOCOL_STATUS_COLUMN_NAME,
          ProtocolStatus.TO_BE_NOTIFIED.getCode(),
          DatabaseFilterType.EQUAL);
      transactionIdColumnName =
          BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_TRX_ID_COLUMN_NAME;
    } else {
      databaseTable =
          database.getTable(BitcoinCryptoNetworkDatabaseConstants.OUTGOING_TRANSACTIONS_TABLE_NAME);
      databaseTable.setStringFilter(
          BitcoinCryptoNetworkDatabaseConstants.OUTGOING_TRANSACTIONS_PROTOCOL_STATUS_COLUMN_NAME,
          ProtocolStatus.TO_BE_NOTIFIED.getCode(),
          DatabaseFilterType.EQUAL);
      transactionIdColumnName =
          BitcoinCryptoNetworkDatabaseConstants.OUTGOING_TRANSACTIONS_TRX_ID_COLUMN_NAME;
    }

    try {
      databaseTable.loadToMemory();
    } catch (CantLoadTableToMemoryException e) {
      throwLoadToMemoryException(e, databaseTable.getTableName());
    }

    /** Will form the TransactionProtocolData object from the records */
    for (DatabaseTableRecord record : databaseTable.getRecords()) {
      TransactionProtocolData transactionProtocolData = new TransactionProtocolData();
      transactionProtocolData.setTransactionId(
          UUID.fromString(record.getStringValue(transactionIdColumnName)));
      transactionProtocolData.setCryptoTransaction(
          getCryptoTransactionFromRecord(transactionType, record));
      transactionProtocolData.setAction(Action.APPLY);
      transactionProtocolData.setTimestamp(
          System.currentTimeMillis()
              / 1000L); // todo I need to convert the stored saved date to long

      transactionProtocolDataList.add(transactionProtocolData);
    }

    return transactionProtocolDataList;
  }
  private void setUpMockitoRules() throws Exception {

    when(mockDatabase.getDatabaseFactory()).thenReturn(mockDatabaseFactory);
    when(mockDatabaseTable.getEmptyRecord()).thenReturn(mockDatabaseTableRecord);
    when(mockDatabase.getTable(
            AssetIssuingTransactionDatabaseConstants.DIGITAL_ASSET_TRANSACTION_TABLE_NAME))
        .thenReturn(mockDatabaseTable);
    when(mockDatabase.getTable(
            AssetIssuingTransactionDatabaseConstants
                .DIGITAL_ASSET_TRANSACTION_ASSET_ISSUING_TABLE_NAME))
        .thenReturn(mockDatabaseTable2);
    when(mockDatabaseTable2.getEmptyRecord()).thenReturn(mockDatabaseTableRecord);
    when(mockDatabaseTable2.getRecords()).thenReturn(records);
    when(pluginDatabaseSystem.openDatabase(
            pluginId, AssetIssuingTransactionDatabaseConstants.DIGITAL_ASSET_TRANSACTION_DATABASE))
        .thenReturn(mockDatabase);

    when(deviceUser.getPublicKey()).thenReturn("myPublicKey");
    when(deviceUserManager.getLoggedInDeviceUser()).thenReturn(deviceUser);

    when(actorAssetIssuerManager.getActorAssetIssuer()).thenReturn(actorAssetIssuer);

    when(eventManager.getNewListener(
            EventType.INCOMING_ASSET_ON_CRYPTO_NETWORK_WAITING_TRANSFERENCE_ASSET_ISSUER))
        .thenReturn(fermatEventListener1);
    when(eventManager.getNewListener(
            EventType.INCOMING_ASSET_ON_BLOCKCHAIN_WAITING_TRANSFERENCE_ASSET_ISSUER))
        .thenReturn(fermatEventListener2);
    when(eventManager.getNewListener(
            EventType.INCOMING_ASSET_REVERSED_ON_BLOCKCHAIN_WAITING_TRANSFERENCE_ASSET_ISSUER))
        .thenReturn(fermatEventListener3);
    when(eventManager.getNewListener(
            EventType.INCOMING_ASSET_REVERSED_ON_CRYPTO_NETWORK_WAITING_TRANSFERENCE_ASSET_ISSUER))
        .thenReturn(fermatEventListener4);

    when(pluginFileSystem.createTextFile(
            this.pluginId,
            "digital-asset-issuing/publicKey",
            "name.xml",
            FilePrivacy.PUBLIC,
            FileLifeSpan.PERMANENT))
        .thenReturn(pluginTextFile);
    when(bitcoinWalletManager.loadWallet(this.walletPublicKey)).thenReturn(bitcoinWalletWallet);
    when(bitcoinWalletWallet.getBalance(BalanceType.AVAILABLE)).thenReturn(bitcoinWalletBalance);
    when(bitcoinWalletBalance.getBalance()).thenReturn(bitcoinWalletAvailableBalance);
    when(assetVaultManager.getNewAssetVaultCryptoAddress(this.blockchainNetworkType))
        .thenReturn(cryptoAddress);
    //        doNothing().when(assetIssuingPluginRoot).issueAssets(digitalAsset, 1, walletPublicKey,
    // blockchainNetworkType);
  }
  public void initializeDatabase() throws CantInitializeCashMoneyDestockDatabaseException {
    try {

      /*
       * Open new database connection
       */
      database =
          this.pluginDatabaseSystem.openDatabase(
              pluginId,
              StockTransactionsCashMoneyDestockDatabaseConstants.CASH_MONEY_DESTOCK_DATABASE_NAME);
      database.closeDatabase();

    } catch (CantOpenDatabaseException cantOpenDatabaseException) {

      /*
       * The database exists but cannot be open. I can not handle this situation.
       */
      throw new CantInitializeCashMoneyDestockDatabaseException(
          cantOpenDatabaseException.getMessage());

    } catch (DatabaseNotFoundException e) {

      /*
       * The database no exist may be the first time the plugin is running on this device,
       * We need to create the new database
       */
      StockTransactionsCashMoneyDestockDatabaseFactory
          stockTransactionsCashMoneyDestockDatabaseFactory =
              new StockTransactionsCashMoneyDestockDatabaseFactory(this.pluginDatabaseSystem);

      try {
        /*
         * We create the new database
         */
        database =
            stockTransactionsCashMoneyDestockDatabaseFactory.createDatabase(
                pluginId,
                StockTransactionsCashMoneyDestockDatabaseConstants
                    .CASH_MONEY_DESTOCK_DATABASE_NAME);
        database.closeDatabase();
      } catch (CantCreateDatabaseException cantCreateDatabaseException) {
        /*
         * The database cannot be created. I can not handle this situation.
         */
        throw new CantInitializeCashMoneyDestockDatabaseException(
            cantCreateDatabaseException.getMessage());
      }
    }
  }
  public final List<DeveloperDatabaseTableRecord> getDatabaseTableContent(
      final DeveloperObjectFactory developerObjectFactory,
      final DeveloperDatabaseTable developerDatabaseTable) {

    final List<DeveloperDatabaseTableRecord> returnedRecords = new ArrayList<>();

    final DatabaseTable selectedTable = database.getTable(developerDatabaseTable.getName());

    try {

      selectedTable.loadToMemory();
      final List<DatabaseTableRecord> records = selectedTable.getRecords();

      for (final DatabaseTableRecord row : records) {

        final List<String> developerRow = new ArrayList<>();

        for (DatabaseRecord field : row.getValues()) developerRow.add(field.getValue());

        returnedRecords.add(
            developerObjectFactory.getNewDeveloperDatabaseTableRecord(developerRow));
      }

    } catch (CantLoadTableToMemoryException cantLoadTableToMemory) {

      return returnedRecords;
    } catch (Exception e) {
      return returnedRecords;
    }
    return returnedRecords;
  }
  @Override
  public int getPublicKeyPosition(String address) throws CantExecuteDatabaseOperationException {
    DatabaseTable databaseTable =
        database.getTable(
            AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_DETAIL_TABLE_NAME);
    databaseTable.addStringFilter(
        AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_DETAIL_ADDRESS_COLUMN_NAME,
        address,
        DatabaseFilterType.EQUAL);

    try {
      databaseTable.loadToMemory();
    } catch (CantLoadTableToMemoryException e) {
      throwLoadToMemoryException(e, databaseTable.getTableName());
    }

    List<DatabaseTableRecord> databaseTableRecords = databaseTable.getRecords();
    if (databaseTableRecords.size() != 0) {
      return databaseTableRecords
          .get(0)
          .getIntegerValue(
              AssetsOverBitcoinCryptoVaultDatabaseConstants
                  .KEY_MAINTENANCE_DETAIL_KEY_DEPTH_COLUMN_NAME);
    } else return 0;
  }
Пример #18
0
  private boolean isAssetsByReceptionStatus(ReceptionStatus receptionStatus)
      throws CantExecuteQueryException {
    try {
      this.database = openDatabase();
      DatabaseTable databaseTable;
      databaseTable = database.getTable(AssetReceptionDatabaseConstants.ASSET_RECEPTION_TABLE_NAME);
      databaseTable.addStringFilter(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_RECEPTION_STATUS_COLUMN_NAME,
          receptionStatus.getCode(),
          DatabaseFilterType.EQUAL);
      databaseTable.addStringFilter(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_CRYPTO_STATUS_COLUMN_NAME,
          CryptoStatus.PENDING_SUBMIT.getCode(),
          DatabaseFilterType.EQUAL);
      databaseTable.loadToMemory();

      return !databaseTable.getRecords().isEmpty();
    } catch (CantLoadTableToMemoryException exception) {

      throw new CantExecuteQueryException(
          "Error executing query in DB.",
          exception,
          "Getting assets by reception status.",
          "Cannot load table to memory.");
    } catch (Exception exception) {

      throw new CantExecuteQueryException(
          CantExecuteQueryException.DEFAULT_MESSAGE,
          FermatException.wrapException(exception),
          "Getting assets by reception status.",
          "Unexpected exception");
    }
  }
Пример #19
0
  private List<String> getValueListFromTableByColumn(
      String referenceValue, String table, String referenceColumn, String returningColumn)
      throws CantCheckAssetReceptionProgressException {

    try {
      this.database = openDatabase();
      DatabaseTable databaseTable;
      List<String> returningList = new ArrayList<>();
      databaseTable = database.getTable(table);
      databaseTable.addStringFilter(referenceColumn, referenceValue, DatabaseFilterType.EQUAL);
      databaseTable.loadToMemory();
      for (DatabaseTableRecord record : databaseTable.getRecords()) {
        returningList.add(record.getStringValue(returningColumn));
      }

      return returningList;
    } catch (CantLoadTableToMemoryException exception) {

      throw new CantCheckAssetReceptionProgressException(
          exception, "Getting " + referenceColumn + " list", "Cannot load table to memory");
    } catch (CantExecuteDatabaseOperationException exception) {

      throw new CantCheckAssetReceptionProgressException(
          exception,
          "Getting " + referenceColumn + " list",
          "Cannot open or find the Asset Reception database");
    } catch (Exception exception) {

      throw new CantCheckAssetReceptionProgressException(
          FermatException.wrapException(exception),
          "Getting " + referenceColumn + " list",
          "Unexpected exception");
    }
  }
Пример #20
0
  private boolean isPendingEventsBySource(EventSource eventSource)
      throws CantExecuteQueryException {
    try {
      this.database = openDatabase();
      DatabaseTable databaseTable;
      databaseTable =
          database.getTable(
              AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_TABLE_NAME);
      databaseTable.addStringFilter(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_STATUS_COLUMN_NAME,
          EventStatus.PENDING.getCode(),
          DatabaseFilterType.EQUAL);
      databaseTable.addStringFilter(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_SOURCE_COLUMN_NAME,
          eventSource.getCode(),
          DatabaseFilterType.EQUAL);
      databaseTable.loadToMemory();

      return !databaseTable.getRecords().isEmpty();
    } catch (CantLoadTableToMemoryException exception) {

      throw new CantExecuteQueryException(
          "Error executing query in DB.",
          exception,
          "Getting pending events.",
          "Cannot load table to memory.");
    } catch (Exception exception) {

      throw new CantExecuteQueryException(
          CantExecuteQueryException.DEFAULT_MESSAGE,
          FermatException.wrapException(exception),
          "Getting pending events.",
          "Unexpected exception");
    }
  }
Пример #21
0
  public boolean isPendingTransactions(CryptoStatus cryptoStatus) throws CantExecuteQueryException {
    try {
      this.database = openDatabase();
      DatabaseTable databaseTable;
      databaseTable = database.getTable(AssetReceptionDatabaseConstants.ASSET_RECEPTION_TABLE_NAME);
      databaseTable.addStringFilter(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_PROTOCOL_STATUS_COLUMN_NAME,
          ProtocolStatus.TO_BE_NOTIFIED.getCode(),
          DatabaseFilterType.EQUAL);
      databaseTable.addStringFilter(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_CRYPTO_STATUS_COLUMN_NAME,
          cryptoStatus.getCode(),
          DatabaseFilterType.EQUAL);
      databaseTable.loadToMemory();

      return !databaseTable.getRecords().isEmpty();
    } catch (CantLoadTableToMemoryException exception) {

      throw new CantExecuteQueryException(
          "Error executing query in DB.",
          exception,
          "Getting pending transactions.",
          "Cannot load table to memory.");
    } catch (Exception exception) {

      throw new CantExecuteQueryException(
          CantExecuteQueryException.DEFAULT_MESSAGE,
          FermatException.wrapException(exception),
          "Getting pending transactions.",
          "Unexpected exception");
    }
  }
  /**
   * Gets the next It to be used to create a new HierarchyAccountId
   *
   * @return
   */
  public int getNextAvailableHierarchyAccountId() throws CantExecuteDatabaseOperationException {
    DatabaseTable databaseTable =
        database.getTable(AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_ACCOUNTS_TABLE_NAME);
    try {
      databaseTable.loadToMemory();
    } catch (CantLoadTableToMemoryException e) {
      throwLoadToMemoryException(e, databaseTable.getTableName());
    }

    /** returns the next available Id to be used. */
    List<DatabaseTableRecord> databaseTableRecords = databaseTable.getRecords();
    if (databaseTableRecords.isEmpty()) return 0;
    else {
      int hierarchyAccountId = 0;
      for (DatabaseTableRecord record : databaseTableRecords) {
        if (record.getIntegerValue(
                AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_ACCOUNTS_ID_COLUMN_NAME)
            > hierarchyAccountId)
          hierarchyAccountId =
              record.getIntegerValue(
                  AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_ACCOUNTS_ID_COLUMN_NAME);
      }

      return hierarchyAccountId + 1;
    }
  }
  public void setUpMockitoRules() throws Exception {

    when(mockPluginDatabaseSystem.openDatabase(pluginId, pluginId.toString()))
        .thenReturn(mockDatabase);

    when(mockExtraUserActorDatabaseFactory.createDatabase(pluginId, pluginId.toString()))
        .thenReturn(mockDatabase);

    when(mockDatabase.getTable(ExtraUserActorDatabaseConstants.EXTRA_USER_TABLE_NAME))
        .thenReturn(mockTable);
    when(mockTable.getRecords()).thenReturn(mockRecords);
    when(mockRecords.get(anyInt())).thenReturn(mockTableRecord);
    when(mockPluginFileSystem.getBinaryFile(
            any(UUID.class),
            anyString(),
            anyString(),
            any(FilePrivacy.class),
            any(FileLifeSpan.class)))
        .thenReturn(mockBinaryFile);

    when(mockPluginFileSystem.getTextFile(
            any(UUID.class),
            anyString(),
            anyString(),
            any(FilePrivacy.class),
            any(FileLifeSpan.class)))
        .thenReturn(mockFile);

    when(mockBinaryFile.getContent()).thenReturn(new byte[100]);
  }
  /**
   * Saves and outgoing transaction into the database
   *
   * @param hash
   * @param cryptoStatus
   * @param blockDepth
   * @param addressTo
   * @param addressFrom
   * @param value
   * @param op_Return
   * @param protocolStatus
   * @throws CantExecuteDatabaseOperationException
   */
  public void saveNewOutgoingTransaction(
      String hash,
      CryptoStatus cryptoStatus,
      int blockDepth,
      CryptoAddress addressTo,
      CryptoAddress addressFrom,
      long value,
      String op_Return,
      ProtocolStatus protocolStatus)
      throws CantExecuteDatabaseOperationException {
    DatabaseTable databaseTable =
        database.getTable(BitcoinCryptoNetworkDatabaseConstants.OUTGOING_TRANSACTIONS_TABLE_NAME);
    DatabaseTableRecord record = databaseTable.getEmptyRecord();

    /** generates the trx_id */
    UUID trxId = UUID.randomUUID();

    record.setUUIDValue(
        BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_TRX_ID_COLUMN_NAME, trxId);
    record.setStringValue(
        BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_HASH_COLUMN_NAME, hash);
    record.setStringValue(
        BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_CRYPTO_STATUS_COLUMN_NAME,
        cryptoStatus.getCode());
    record.setIntegerValue(
        BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_BLOCK_DEPTH_COLUMN_NAME,
        blockDepth);
    record.setStringValue(
        BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_ADDRESS_TO_COLUMN_NAME,
        addressTo.getAddress());
    record.setStringValue(
        BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_ADDRESS_FROM_COLUMN_NAME,
        addressFrom.getAddress());
    record.setDoubleValue(
        BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_VALUE_COLUMN_NAME, value);
    record.setStringValue(
        BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_OP_RETURN_COLUMN_NAME,
        op_Return);
    record.setStringValue(
        BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_PROTOCOL_STATUS_COLUMN_NAME,
        protocolStatus.getCode());
    record.setStringValue(
        BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_LAST_UPDATE_COLUMN_NAME,
        getCurrentDateTime());
    try {
      databaseTable.insertRecord(record);
    } catch (CantInsertRecordException e) {
      StringBuilder outputMessage =
          new StringBuilder(
              "There was an error inserting a new transaction in the Outgoing Transactions Table. Transaction record is:");
      outputMessage.append(System.lineSeparator());
      outputMessage.append(XMLParser.parseObject(record));

      throw new CantExecuteDatabaseOperationException(
          CantExecuteDatabaseOperationException.DEFAULT_MESSAGE,
          e,
          outputMessage.toString(),
          "database issue.");
    }
  }
Пример #25
0
  public boolean isGenesisTransactionRegistered(String genesisTransaction)
      throws CantExecuteQueryException {
    try {
      this.database = openDatabase();
      DatabaseTable databaseTable;
      databaseTable = database.getTable(AssetReceptionDatabaseConstants.ASSET_RECEPTION_TABLE_NAME);
      databaseTable.addStringFilter(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_GENESIS_TRANSACTION_COLUMN_NAME,
          genesisTransaction,
          DatabaseFilterType.EQUAL);
      databaseTable.loadToMemory();

      return !databaseTable.getRecords().isEmpty();
    } catch (CantLoadTableToMemoryException exception) {

      throw new CantExecuteQueryException(
          "Error executing query in DB.",
          exception,
          "Checking if genesis transaction exists in database.",
          "Cannot load table to memory.");
    } catch (Exception exception) {

      throw new CantExecuteQueryException(
          CantExecuteQueryException.DEFAULT_MESSAGE,
          FermatException.wrapException(exception),
          "Checking if genesis transaction exits in database.",
          "Unexpected exception");
    }
  }
  @Test
  public void GetBalance_GeneralException_ReturnsAvailableBalance() throws Exception {
    when(mockDatabase.getTable(BitcoinWalletDatabaseConstants.BITCOIN_WALLET_BALANCE_TABLE_NAME))
        .thenReturn(null);

    catchException(testBalance).getBalance();
    assertThat(caughtException()).isNotNull().isInstanceOf(CantCalculateBalanceException.class);
  }
 private void mockitoRules() throws Exception {
   when(database.getTable(AssetIssuingDatabaseConstants.ASSET_ISSUING_TABLE_NAME))
       .thenReturn(databaseTable);
   when(databaseTable.getRecords()).thenReturn(records);
   when(databaseTableRecord.getIntegerValue(
           AssetIssuingDatabaseConstants.ASSET_ISSUING_ASSETS_COMPLETED_COLUMN_NAME))
       .thenReturn(issuedAssetsExpected);
 }
  /**
   * This method open or creates the database i'll be working with
   *
   * @throws CantInitializeArtistIdentityDatabaseException
   */
  public void initializeDatabase() throws CantInitializeArtistIdentityDatabaseException {
    try {

      /*
       * Open new database connection
       */
      database =
          this.pluginDatabaseSystem.openDatabase(
              pluginId, ArtistIdentityDatabaseConstants.ARTIST_IDENTITY_DB_NAME);
      database.closeDatabase();

    } catch (CantOpenDatabaseException cantOpenDatabaseException) {

      /*
       * The database exists but cannot be open. I can not handle this situation.
       */
      throw new CantInitializeArtistIdentityDatabaseException(
          cantOpenDatabaseException.getMessage());

    } catch (DatabaseNotFoundException e) {

      /*
       * The database no exist may be the first time the plugin is running on this device,
       * We need to create the new database
       */
      ArtistIdentityDatabaseFactory assetIssuerIdentityDatabaseFactory =
          new ArtistIdentityDatabaseFactory(pluginDatabaseSystem);

      try {
        /*
         * We create the new database
         */
        database = assetIssuerIdentityDatabaseFactory.createDatabase(pluginId);
        database.closeDatabase();
      } catch (CantCreateDatabaseException cantCreateDatabaseException) {
        /*
         * The database cannot be created. I can not handle this situation.
         */
        throw new CantInitializeArtistIdentityDatabaseException(
            cantCreateDatabaseException.getMessage());
      }
    } catch (Exception e) {

      throw new CantInitializeArtistIdentityDatabaseException(e.getMessage());
    }
  }
  /**
   * Gets the crypto Status list that are in pending status from the specified table.
   *
   * @param transactionType
   * @return
   */
  public Set<CryptoStatus> getPendingCryptoStatus(TransactionTypes transactionType)
      throws CantExecuteDatabaseOperationException {
    DatabaseTable databaseTable;
    String cryptoStatusColumnName;
    Set<CryptoStatus> cryptoStatuses = new HashSet<>();

    /** Will set up filters and column names depending on the transaction type. */
    if (transactionType == TransactionTypes.OUTGOING) {
      databaseTable =
          database.getTable(BitcoinCryptoNetworkDatabaseConstants.OUTGOING_TRANSACTIONS_TABLE_NAME);
      databaseTable.setStringFilter(
          BitcoinCryptoNetworkDatabaseConstants.OUTGOING_TRANSACTIONS_PROTOCOL_STATUS_COLUMN_NAME,
          ProtocolStatus.TO_BE_NOTIFIED.getCode(),
          DatabaseFilterType.EQUAL);
      cryptoStatusColumnName =
          BitcoinCryptoNetworkDatabaseConstants.OUTGOING_TRANSACTIONS_CRYPTO_STATUS_COLUMN_NAME;
    } else {
      databaseTable =
          database.getTable(BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_TABLE_NAME);
      databaseTable.setStringFilter(
          BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_PROTOCOL_STATUS_COLUMN_NAME,
          ProtocolStatus.TO_BE_NOTIFIED.getCode(),
          DatabaseFilterType.EQUAL);
      cryptoStatusColumnName =
          BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_CRYPTO_STATUS_COLUMN_NAME;
    }

    try {
      databaseTable.loadToMemory();
    } catch (CantLoadTableToMemoryException e) {
      throwLoadToMemoryException(e, databaseTable.getTableName());
    }

    /** get all the CryptoStatus and remove duplicates as Im storing them in a set. */
    for (DatabaseTableRecord record : databaseTable.getRecords()) {
      try {
        CryptoStatus cryptoStatus =
            CryptoStatus.getByCode(record.getStringValue(cryptoStatusColumnName));
        cryptoStatuses.add(cryptoStatus);
      } catch (InvalidParameterException e) {
        e.printStackTrace();
      }
    }

    return cryptoStatuses;
  }
  /**
   * Insert new public keys into the detailed monitor table
   *
   * @param accountId
   * @param keys
   * @throws CantExecuteDatabaseOperationException
   */
  public void updateDetailMaintainerStats(int accountId, List<ECKey> keys, int currentGeneratedKeys)
      throws CantExecuteDatabaseOperationException {
    /** If we are not allowed to save detailed information then we will exit. */
    if (!VaultKeyMaintenanceParameters.STORE_DETAILED_KEY_INFORMATION) return;

    DatabaseTable databaseTable =
        database.getTable(
            AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_DETAIL_TABLE_NAME);
    DatabaseTransaction transaction = database.newTransaction();

    /**
     * I will insert each key. Since I don't want to repeat inserting keys, I will only insert the
     * keys which position is after currentGeneratedKeys value
     */
    int i = 1;
    for (ECKey key : keys) {
      if (i >= currentGeneratedKeys) {
        DatabaseTableRecord record = databaseTable.getEmptyRecord();
        record.setIntegerValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants
                .KEY_MAINTENANCE_DETAIL_ACCOUNT_ID_COLUMN_NAME,
            accountId);
        record.setIntegerValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants
                .KEY_MAINTENANCE_DETAIL_KEY_DEPTH_COLUMN_NAME,
            i);
        record.setStringValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants
                .KEY_MAINTENANCE_DETAIL_PUBLIC_KEY_COLUMN_NAME,
            key.getPublicKeyAsHex());
        transaction.addRecordToInsert(databaseTable, record);
      }
      i++;
    }

    /** once I collected all records, I will insert them in a single transaction */
    try {
      database.executeTransaction(transaction);
    } catch (DatabaseTransactionFailedException e) {
      throw new CantExecuteDatabaseOperationException(
          CantExecuteDatabaseOperationException.DEFAULT_MESSAGE,
          e,
          "error inserting records in transaction.",
          null);
    }
  }