예제 #1
0
  /**
   * This method returns a String value from the fieldCode, filtered by value in indexColumn
   *
   * @param tableName table name
   * @param value value used as filter
   * @param fieldCode column that contains the required value
   * @param indexColumn the column filter
   * @return a String with the required value
   * @throws CantCheckAssetReceptionProgressException
   * @throws UnexpectedResultReturnedFromDatabaseException
   */
  private String getStringValueFromSelectedTableTableByFieldCode(
      String tableName, String value, String fieldCode, String indexColumn)
      throws CantCheckAssetReceptionProgressException,
          UnexpectedResultReturnedFromDatabaseException {
    try {
      this.database = openDatabase();
      DatabaseTable databaseTable = getDatabaseTable(tableName);
      databaseTable.addStringFilter(indexColumn, value, DatabaseFilterType.EQUAL);
      databaseTable.loadToMemory();
      DatabaseTableRecord databaseTableRecord;
      List<DatabaseTableRecord> databaseTableRecords = databaseTable.getRecords();
      if (databaseTableRecords.size() > 1) {

        throw new UnexpectedResultReturnedFromDatabaseException(
            "Unexpected result. More than value returned.", indexColumn + ":" + value);
      } else {
        databaseTableRecord = databaseTableRecords.get(0);
      }

      String stringToReturn = databaseTableRecord.getStringValue(fieldCode);
      return stringToReturn;
    } catch (CantExecuteDatabaseOperationException exception) {

      throw new CantCheckAssetReceptionProgressException(
          exception, "Trying to get " + fieldCode, "Cannot find or open the database");
    } catch (CantLoadTableToMemoryException exception) {

      throw new CantCheckAssetReceptionProgressException(
          exception, "Trying to get " + fieldCode, "Cannot load the database into memory");
    }
  }
 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;
 }
  /**
   * 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;
  }
예제 #4
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");
    }
  }
  /**
   * 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 updateTxHash(UUID transactionId, String newHash)
      throws OutgoingIntraActorCantInsertRecordException {
    try {
      DatabaseTable transactionTable =
          this.database.getTable(
              OutgoingDraftTransactionDatabaseConstants.OUTGOING_DRAFT_TABLE_NAME);
      transactionTable.addStringFilter(
          OutgoingDraftTransactionDatabaseConstants.OUTGOING_DRAFT_TRANSACTION_ID_COLUMN_NAME,
          transactionId.toString(),
          DatabaseFilterType.EQUAL);
      transactionTable.loadToMemory();

      if (transactionTable.getRecords().isEmpty()) throw new RecordsNotFoundException();

      DatabaseTableRecord record = transactionTable.getRecords().get(0);
      record.setStringValue(
          OutgoingDraftTransactionDatabaseConstants.OUTGOING_DRAFT_TRANSACTION_HASH_COLUMN_NAME,
          newHash);
      transactionTable.updateRecord(record);
    } catch (Exception exception) {
      throw new com.bitdubai.fermat_ccp_plugin.layer.crypto_transaction.outgoing_draft.developer
          .bitdubai.version_1.exceptions.OutgoingIntraActorCantInsertRecordException(
          com.bitdubai.fermat_ccp_plugin.layer.crypto_transaction.outgoing_draft.developer.bitdubai
              .version_1.exceptions.OutgoingIntraActorCantInsertRecordException.DEFAULT_MESSAGE,
          FermatException.wrapException(exception),
          null,
          null);
    }
  }
  // TODO: mejorar, el plugin de mierda de db es un asco
  public void markReadTransaction(UUID requestId) {
    try {
      DatabaseTable transactionTable =
          this.database.getTable(
              OutgoingDraftTransactionDatabaseConstants.OUTGOING_DRAFT_TABLE_NAME);
      transactionTable.addUUIDFilter(
          OutgoingDraftTransactionDatabaseConstants.OUTGOING_DRAFT_TRANSACTION_ID_COLUMN_NAME,
          requestId,
          DatabaseFilterType.EQUAL);
      transactionTable.loadToMemory();
      List<DatabaseTableRecord> records = transactionTable.getRecords();

      if (!records.isEmpty()) {
        DatabaseTableRecord record = records.get(0);
        // set new record values
        record.setStringValue(
            OutgoingDraftTransactionDatabaseConstants.OUTGOING_DRAFT_TRANSACTION_MARK_COLUMN_NAME,
            Boolean.TRUE.toString());

        transactionTable.updateRecord(record);
      }
    } catch (CantLoadTableToMemoryException e) {
      e.printStackTrace();
    } catch (CantUpdateRecordException e) {
      e.printStackTrace();
    }
  }
  public void setToCryptoStatus(
      OutgoingDraftTransactionWrapper transactionWrapper, CryptoStatus cryptoStatus)
      throws CantUpdateRecordException, CantLoadTableToMemoryException,
          com.bitdubai.fermat_ccp_plugin.layer.crypto_transaction.outgoing_draft.developer.bitdubai
              .version_1.exceptions.OutgoingIntraActorInconsistentTableStateException {
    try {
      DatabaseTable transactionTable =
          this.database.getTable(
              OutgoingDraftTransactionDatabaseConstants.OUTGOING_DRAFT_TABLE_NAME);
      DatabaseTableRecord recordToUpdate = getByPrimaryKey(transactionWrapper.getRequestId());

      recordToUpdate.setStringValue(
          OutgoingDraftTransactionDatabaseConstants.OUTGOING_DRAFT_CRYPTO_STATUS_COLUMN_NAME,
          cryptoStatus.getCode());
      transactionTable.addStringFilter(
          OutgoingDraftTransactionDatabaseConstants.OUTGOING_DRAFT_TRANSACTION_ID_COLUMN_NAME,
          transactionWrapper.getRequestId().toString(),
          DatabaseFilterType.EQUAL);

      transactionTable.updateRecord(recordToUpdate);

    } catch (CantUpdateRecordException
        | com.bitdubai.fermat_ccp_plugin.layer.crypto_transaction.outgoing_draft.developer.bitdubai
            .version_1.exceptions.OutgoingIntraActorInconsistentTableStateException
        | CantLoadTableToMemoryException exception) {
      throw exception;
    } catch (Exception exception) {
      throw new CantLoadTableToMemoryException(
          CantLoadTableToMemoryException.DEFAULT_MESSAGE,
          FermatException.wrapException(exception),
          null,
          null);
    }
  }
  /**
   * gets the list of Active network Types activated in the platform
   *
   * @return
   * @throws CantExecuteDatabaseOperationException
   */
  public List<BlockchainNetworkType> getActiveNetworkTypes()
      throws CantExecuteDatabaseOperationException {
    List<BlockchainNetworkType> networkTypes = new ArrayList<>();
    DatabaseTable databaseTable =
        getDatabaseTable(AssetsOverBitcoinCryptoVaultDatabaseConstants.ACTIVE_NETWORKS_TABLE_NAME);

    /** I will check to see if I already have a value for this account so i can updated it. */
    try {
      databaseTable.loadToMemory();
    } catch (CantLoadTableToMemoryException e) {
      throwLoadToMemoryException(e, databaseTable.getTableName());
    }

    /** I will add all the saved values into the list to return */
    for (DatabaseTableRecord record : databaseTable.getRecords()) {
      networkTypes.add(
          BlockchainNetworkType.getByCode(
              record.getStringValue(
                  AssetsOverBitcoinCryptoVaultDatabaseConstants
                      .ACTIVE_NETWORKS_NETWORKTYPE_COLUMN_NAME)));
    }

    /**
     * If there are no records saved yet, because no one request an address to set the network I
     * will manually save the default value
     */
    if (networkTypes.size() == 0) {
      this.setActiveNetworkType(BlockchainNetworkType.getDefaultBlockchainNetworkType());
      networkTypes.add(BlockchainNetworkType.getDefaultBlockchainNetworkType());
    }

    return networkTypes;
  }
  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;
  }
예제 #11
0
  public BigDecimal getWalletBalance(String walletPublicKey, BalanceType balanceType)
      throws CantGetCashMoneyWalletBalanceException {
    BigDecimal balance;
    try {
      DatabaseTableRecord record = this.getWalletRecordByPublicKey(walletPublicKey);
      if (balanceType == BalanceType.AVAILABLE)
        balance =
            new BigDecimal(
                record.getStringValue(
                    CashMoneyWalletDatabaseConstants.WALLETS_AVAILABLE_BALANCE_COLUMN_NAME));
      else if (balanceType == BalanceType.BOOK)
        balance =
            new BigDecimal(
                record.getStringValue(
                    CashMoneyWalletDatabaseConstants.WALLETS_BOOK_BALANCE_COLUMN_NAME));
      else throw new InvalidParameterException();
    } catch (Exception e) {
      errorManager.reportUnexpectedPluginException(
          Plugins.BITDUBAI_CSH_WALLET_CASH_MONEY,
          UnexpectedPluginExceptionSeverity.DISABLES_THIS_PLUGIN,
          e);
      throw new CantGetCashMoneyWalletBalanceException(
          CantGetCashMoneyWalletBalanceException.DEFAULT_MESSAGE,
          e,
          "Cant get wallet balance",
          null);
    }

    return balance;
  }
예제 #12
0
  public ActorAssetNetworkServiceRecord changeActorAssetNotificationDescriptor(
      final String senderPublicKey,
      final AssetNotificationDescriptor assetNotificationDescriptor,
      final ActorAssetProtocolState actorAssetProtocolState)
      throws CantUpdateRecordDataBaseException, CantUpdateRecordException,
          CantGetActorAssetNotificationException {

    if (senderPublicKey == null)
      throw new CantUpdateRecordDataBaseException("senderPublicKey null ", null);

    if (assetNotificationDescriptor == null)
      throw new CantUpdateRecordDataBaseException("protocolState null", null);

    try {

      DatabaseTable cryptoPaymentRequestTable = getDatabaseTable();

      cryptoPaymentRequestTable.addStringFilter(
          AssetUserNetworkServiceDatabaseConstants
              .INCOMING_NOTIFICATION_SENDER_PUBLIC_KEY_COLUMN_NAME,
          senderPublicKey,
          DatabaseFilterType.EQUAL);

      cryptoPaymentRequestTable.loadToMemory();

      List<DatabaseTableRecord> records = cryptoPaymentRequestTable.getRecords();

      if (!records.isEmpty()) {
        DatabaseTableRecord record = records.get(records.size() - 1); // Last pending

        record.setStringValue(
            AssetUserNetworkServiceDatabaseConstants.INCOMING_NOTIFICATION_DESCRIPTOR_COLUMN_NAME,
            assetNotificationDescriptor.getCode());
        record.setStringValue(
            AssetUserNetworkServiceDatabaseConstants
                .INCOMING_NOTIFICATION_PROTOCOL_STATE_COLUMN_NAME,
            actorAssetProtocolState.getCode());

        cryptoPaymentRequestTable.updateRecord(record);

        return buildAssetUserNetworkServiceRecord(record);
      } else {
        throw new CantGetActorAssetNotificationException(
            "senderPublicKey: " + senderPublicKey,
            "Cannot find a connection request with the given id.");
      }

    } catch (CantLoadTableToMemoryException e) {

      throw new CantUpdateRecordDataBaseException(
          "Exception not handled by the plugin, there is a problem in database and i cannot load the table.",
          e);
    } catch (CantUpdateRecordException exception) {

      throw new CantUpdateRecordDataBaseException("Cant update record exception.", exception);
    } catch (InvalidParameterException e) {
      throw new CantUpdateRecordDataBaseException("Cant get the updated record exception.", e);
    }
  }
  /**
   * Sets the new depth of the current Used keys value
   *
   * @param accountId
   * @param newValue
   * @throws CantExecuteDatabaseOperationException
   */
  public void setNewCurrentUsedKeyValue(int accountId, int newValue)
      throws CantExecuteDatabaseOperationException {
    DatabaseTable databaseTable =
        getDatabaseTable(AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_TABLE_NAME);

    /** I will check to see if I already have a value for this account so i can updated it. */
    databaseTable.addStringFilter(
        AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_ACCOUNT_ID_COLUMN_NAME,
        String.valueOf(accountId),
        DatabaseFilterType.EQUAL);
    try {
      databaseTable.loadToMemory();
    } catch (CantLoadTableToMemoryException e) {
      throwLoadToMemoryException(e, databaseTable.getTableName());
    }

    DatabaseTableRecord record = null;
    try {
      if (databaseTable.getRecords().size() == 0) {
        // I will insert the new value
        record = databaseTable.getEmptyRecord();
        record.setIntegerValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_ACCOUNT_ID_COLUMN_NAME,
            accountId);
        record.setIntegerValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants
                .KEY_MAINTENANCE_GENERATED_KEYS_COLUMN_NAME,
            0);
        record.setIntegerValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_USED_KEYS_COLUMN_NAME,
            newValue);

        databaseTable.insertRecord(record);
      } else {
        // I will update the existing value
        record = databaseTable.getRecords().get(0);
        record.setIntegerValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_USED_KEYS_COLUMN_NAME,
            newValue);
        databaseTable.updateRecord(record);
      }
    } catch (CantInsertRecordException | CantUpdateRecordException e) {
      StringBuilder outputMessage =
          new StringBuilder(
              "There was an error inserting or updating the key depth value in the database.");
      outputMessage.append(System.lineSeparator());
      outputMessage.append("The record is:");
      outputMessage.append(System.lineSeparator());
      outputMessage.append(XMLParser.parseObject(record));

      throw new CantExecuteDatabaseOperationException(
          CantExecuteDatabaseOperationException.DEFAULT_MESSAGE,
          e,
          outputMessage.toString(),
          "database issue");
    }
  }
  /**
   * Updates the Key detailed table for this account and key, with the passed addres
   *
   * @param hierarchyAccountId
   * @param ecKey
   * @param cryptoAddress
   * @param blockchainNetworkType
   */
  public void updateKeyDetailedStatsWithNewAddress(
      int hierarchyAccountId,
      ECKey ecKey,
      CryptoAddress cryptoAddress,
      BlockchainNetworkType blockchainNetworkType)
      throws CantExecuteDatabaseOperationException, UnexpectedResultReturnedFromDatabaseException {
    /** 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);
    databaseTable.addStringFilter(
        AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_DETAIL_ACCOUNT_ID_COLUMN_NAME,
        String.valueOf(hierarchyAccountId),
        DatabaseFilterType.EQUAL);
    databaseTable.addStringFilter(
        AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_DETAIL_PUBLIC_KEY_COLUMN_NAME,
        ecKey.getPublicKeyAsHex(),
        DatabaseFilterType.EQUAL);

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

    if (databaseTable.getRecords().size() == 0) {
      StringBuilder output = new StringBuilder("The key " + ecKey.toString());
      output.append(System.lineSeparator());
      output.append("which generated the address " + cryptoAddress.getAddress());
      output.append(System.lineSeparator());
      output.append("is not a key derived from the vault.");

      throw new UnexpectedResultReturnedFromDatabaseException(
          null, output.toString(), "Vault derivation miss match");
    }

    DatabaseTableRecord record = databaseTable.getRecords().get(0);
    record.setStringValue(
        AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_DETAIL_ADDRESS_COLUMN_NAME,
        cryptoAddress.getAddress());
    record.setStringValue(
        AssetsOverBitcoinCryptoVaultDatabaseConstants
            .KEY_MAINTENANCE_DETAIL_BLOCKCHAIN_NETWORK_TYPE_COLUMN_NAME,
        blockchainNetworkType.getCode());
    try {
      databaseTable.updateRecord(record);
    } catch (CantUpdateRecordException e) {
      throw new CantExecuteDatabaseOperationException(
          CantExecuteDatabaseOperationException.DEFAULT_MESSAGE,
          e,
          "error updating record",
          "database issue");
    }
  }
예제 #15
0
  /**
   * first i persist private key on a file second i insert the record in database third i save the
   * profile image file
   *
   * @param alias
   * @param publicKey
   * @param privateKey
   * @param deviceUser
   * @param profileImage
   * @throws CantCreateArtistIdentityException
   */
  public void createNewUser(
      String alias, String publicKey, String privateKey, DeviceUser deviceUser, byte[] profileImage)
      throws CantCreateArtistIdentityException {

    try {
      if (aliasExists(alias)) {
        throw new CantCreateArtistIdentityException(
            "Cant create new Redeem Point Identity, alias exists.",
            "Redeem Point Identity",
            "Cant create new Redeem Point, alias exists.");
      }

      persistNewUserPrivateKeysFile(publicKey, privateKey);

      DatabaseTable table =
          this.database.getTable(ArtistIdentityDatabaseConstants.ARTIST_IDENTITY_TABLE_NAME);
      DatabaseTableRecord record = table.getEmptyRecord();

      record.setStringValue(
          ArtistIdentityDatabaseConstants.ARTIST_IDENTITY_PUBLIC_KEY_COLUMN_NAME, publicKey);
      record.setStringValue(
          ArtistIdentityDatabaseConstants.ARTIST_IDENTITY_ALIAS_COLUMN_NAME, alias);
      record.setStringValue(
          ArtistIdentityDatabaseConstants.ARTIST_IDENTITY_DEVICE_USER_PUBLIC_KEY_COLUMN_NAME,
          deviceUser.getPublicKey());

      table.insertRecord(record);

      if (profileImage != null) persistNewUserProfileImage(publicKey, profileImage);

    } catch (CantInsertRecordException e) {
      // Cant insert record.
      throw new CantCreateArtistIdentityException(
          e.getMessage(),
          e,
          "Redeem Point Identity",
          "Cant create new Redeem Point, insert database problems.");

    } catch (CantPersistPrivateKeyException e) {
      // Cant insert record.
      throw new CantCreateArtistIdentityException(
          e.getMessage(),
          e,
          "ARedeem Point Identity",
          "Cant create new Redeem Point, persist private key error.");

    } catch (Exception e) {
      // Failure unknown.

      throw new CantCreateArtistIdentityException(
          e.getMessage(),
          FermatException.wrapException(e),
          "Redeem Point Identity",
          "Cant create new Redeem Point, unknown failure.");
    }
  }
예제 #16
0
  private void constructRecordFromCashMoneyWalletTransaction(
      DatabaseTableRecord newRecord, CashMoneyWalletTransaction cashMoneyWalletTransaction) {

    newRecord.setUUIDValue(
        CashMoneyWalletDatabaseConstants.TRANSACTIONS_TRANSACTION_ID_COLUMN_NAME,
        cashMoneyWalletTransaction.getTransactionId());
    newRecord.setStringValue(
        CashMoneyWalletDatabaseConstants.TRANSACTIONS_WALLET_PUBLIC_KEY_COLUMN_NAME,
        cashMoneyWalletTransaction.getPublicKeyWallet());
    newRecord.setStringValue(
        CashMoneyWalletDatabaseConstants.TRANSACTIONS_ACTOR_PUBLIC_KEY_COLUMN_NAME,
        cashMoneyWalletTransaction.getPublicKeyActor());
    newRecord.setStringValue(
        CashMoneyWalletDatabaseConstants.TRANSACTIONS_PLUGIN_PUBLIC_KEY_COLUMN_NAME,
        cashMoneyWalletTransaction.getPublicKeyPlugin());
    newRecord.setStringValue(
        CashMoneyWalletDatabaseConstants.TRANSACTIONS_TRANSACTION_TYPE_COLUMN_NAME,
        cashMoneyWalletTransaction.getTransactionType().getCode());
    newRecord.setStringValue(
        CashMoneyWalletDatabaseConstants.TRANSACTIONS_BALANCE_TYPE_COLUMN_NAME,
        cashMoneyWalletTransaction.getBalanceType().getCode());
    newRecord.setStringValue(
        CashMoneyWalletDatabaseConstants.TRANSACTIONS_AMOUNT_COLUMN_NAME,
        cashMoneyWalletTransaction.getAmount().toPlainString());
    newRecord.setStringValue(
        CashMoneyWalletDatabaseConstants.TRANSACTIONS_MEMO_COLUMN_NAME,
        cashMoneyWalletTransaction.getMemo());
    newRecord.setLongValue(
        CashMoneyWalletDatabaseConstants.TRANSACTIONS_TIMESTAMP_COLUMN_NAME,
        cashMoneyWalletTransaction.getTimestamp());
  }
  /**
   * Sets the new value of how many keys have been generated by the Key Maintainer
   *
   * @param accountId the account id
   * @param value the amount of keys generated. This value accumulates to the one that existed.
   * @throws CantExecuteDatabaseOperationException
   */
  public void setGeneratedKeysValue(int accountId, int value)
      throws CantExecuteDatabaseOperationException {
    DatabaseTable databaseTable =
        getDatabaseTable(AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_TABLE_NAME);

    /**
     * first I see if we already have records for this account by setting a filter and getting the
     * values
     */
    databaseTable.addStringFilter(
        AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_ACCOUNT_ID_COLUMN_NAME,
        String.valueOf(accountId),
        DatabaseFilterType.EQUAL);
    try {
      databaseTable.loadToMemory();
    } catch (CantLoadTableToMemoryException e) {
      throwLoadToMemoryException(e, databaseTable.getTableName());
    }

    /** I will insert or update the record */
    DatabaseTableRecord record = null;
    try {
      if (databaseTable.getRecords().size() == 0) {
        // insert
        record = databaseTable.getEmptyRecord();
        record.setIntegerValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_ACCOUNT_ID_COLUMN_NAME,
            accountId);
        record.setIntegerValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants
                .KEY_MAINTENANCE_GENERATED_KEYS_COLUMN_NAME,
            value);
        record.setIntegerValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_USED_KEYS_COLUMN_NAME, 0);
        databaseTable.insertRecord(record);
      } else {
        // update
        record = databaseTable.getRecords().get(0);
        record.setIntegerValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants
                .KEY_MAINTENANCE_GENERATED_KEYS_COLUMN_NAME,
            value);
        databaseTable.updateRecord(record);
      }
    } catch (CantInsertRecordException | CantUpdateRecordException e) {
      StringBuilder outputMessage =
          new StringBuilder("There was an error inserting or updating the following table: ");
      outputMessage.append(databaseTable.getTableName());
      outputMessage.append(System.lineSeparator());
      outputMessage.append("The record is:");
      outputMessage.append(System.lineSeparator());
      outputMessage.append(XMLParser.parseObject(record));
    }
  }
  /**
   * Sets the active network type that the Bitcoin Network will need to listen too. Network types
   * are MainNet, TestNet and RegTest
   *
   * @param blockchainNetworkType
   * @throws CantExecuteDatabaseOperationException
   */
  public void setActiveNetworkType(BlockchainNetworkType blockchainNetworkType)
      throws CantExecuteDatabaseOperationException {
    DatabaseTable databaseTable =
        getDatabaseTable(AssetsOverBitcoinCryptoVaultDatabaseConstants.ACTIVE_NETWORKS_TABLE_NAME);

    /** I will check to see if I already have a value for this account so i can updated it. */
    databaseTable.addStringFilter(
        AssetsOverBitcoinCryptoVaultDatabaseConstants.ACTIVE_NETWORKS_NETWORKTYPE_COLUMN_NAME,
        blockchainNetworkType.getCode(),
        DatabaseFilterType.EQUAL);
    try {
      databaseTable.loadToMemory();
    } catch (CantLoadTableToMemoryException e) {
      throwLoadToMemoryException(e, databaseTable.getTableName());
    }
    DatabaseTableRecord record = null;
    String date = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
    try {
      if (databaseTable.getRecords().size() == 0) {
        // I will insert the new value
        record = databaseTable.getEmptyRecord();
        record.setStringValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants.ACTIVE_NETWORKS_NETWORKTYPE_COLUMN_NAME,
            blockchainNetworkType.getCode());
        record.setStringValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants
                .ACTIVE_NETWORKS_ACTIVATION_DATE_COLUMN_NAME,
            date);
        databaseTable.insertRecord(record);
      } else {
        // I will update the existing value
        record = databaseTable.getRecords().get(0);
        record.setStringValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants
                .ACTIVE_NETWORKS_ACTIVATION_DATE_COLUMN_NAME,
            date);
        databaseTable.updateRecord(record);
      }
    } catch (CantInsertRecordException | CantUpdateRecordException e) {
      StringBuilder outputMessage =
          new StringBuilder(
              "There was an error inserting or updating the network type in the database.");
      outputMessage.append(System.lineSeparator());
      outputMessage.append("The record is:");
      outputMessage.append(System.lineSeparator());
      outputMessage.append(XMLParser.parseObject(record));

      throw new CantExecuteDatabaseOperationException(
          CantExecuteDatabaseOperationException.DEFAULT_MESSAGE,
          e,
          outputMessage.toString(),
          "database issue");
    }
  }
예제 #19
0
  public void updateEventStatus(String eventId)
      throws CantExecuteQueryException, UnexpectedResultReturnedFromDatabaseException {
    try {
      this.database = openDatabase();
      DatabaseTable databaseTable =
          this.database.getTable(
              AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_TABLE_NAME);
      databaseTable.addStringFilter(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_ID_COLUMN_NAME,
          eventId,
          DatabaseFilterType.EQUAL);
      databaseTable.loadToMemory();
      DatabaseTableRecord databaseTableRecord;
      List<DatabaseTableRecord> databaseTableRecords = databaseTable.getRecords();
      if (databaseTableRecords.size() > 1) {

        throw new UnexpectedResultReturnedFromDatabaseException(
            "Unexpected result. More than value returned.", "Event ID:" + eventId);
      } else {
        databaseTableRecord = databaseTableRecords.get(0);
      }
      databaseTableRecord.setStringValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_STATUS_COLUMN_NAME,
          EventStatus.NOTIFIED.getCode());
      databaseTable.updateRecord(databaseTableRecord);

    } catch (CantExecuteDatabaseOperationException exception) {

      throw new CantExecuteQueryException(
          CantExecuteDatabaseOperationException.DEFAULT_MESSAGE,
          exception,
          "Trying to update "
              + AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_TABLE_NAME,
          "Check the cause");
    } catch (CantLoadTableToMemoryException exception) {

      throw new CantExecuteQueryException(
          CantLoadTableToMemoryException.DEFAULT_MESSAGE,
          exception,
          "Trying to update "
              + AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_TABLE_NAME,
          "Check the cause");
    } catch (Exception exception) {

      throw new CantExecuteQueryException(
          CantExecuteQueryException.DEFAULT_MESSAGE,
          FermatException.wrapException(exception),
          "Trying to update "
              + AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_TABLE_NAME,
          "Unexpected exception");
    }
  }
  /**
   * 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;
  }
  /**
   * Creates a incoming or outgoing CryptoTransaction object from a database record
   *
   * @param transactionType
   * @param record
   * @return
   */
  private CryptoTransaction getCryptoTransactionFromRecord(
      TransactionTypes transactionType, DatabaseTableRecord record) {
    String addressFromColumnName,
        addressToColumnName,
        transactionHashColumnName,
        valueColumnName,
        cryptoStatusColumnName;
    if (transactionType == TransactionTypes.INCOMING) {
      transactionHashColumnName =
          BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_HASH_COLUMN_NAME;
      addressFromColumnName =
          BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_ADDRESS_FROM_COLUMN_NAME;
      addressToColumnName =
          BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_ADDRESS_TO_COLUMN_NAME;
      valueColumnName =
          BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_VALUE_COLUMN_NAME;
      cryptoStatusColumnName =
          BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_CRYPTO_STATUS_COLUMN_NAME;
    } else {
      transactionHashColumnName =
          BitcoinCryptoNetworkDatabaseConstants.OUTGOING_TRANSACTIONS_HASH_COLUMN_NAME;
      addressFromColumnName =
          BitcoinCryptoNetworkDatabaseConstants.OUTGOING_TRANSACTIONS_ADDRESS_FROM_COLUMN_NAME;
      addressToColumnName =
          BitcoinCryptoNetworkDatabaseConstants.OUTGOING_TRANSACTIONS_ADDRESS_TO_COLUMN_NAME;
      valueColumnName =
          BitcoinCryptoNetworkDatabaseConstants.OUTGOING_TRANSACTIONS_VALUE_COLUMN_NAME;
      cryptoStatusColumnName =
          BitcoinCryptoNetworkDatabaseConstants.OUTGOING_TRANSACTIONS_CRYPTO_STATUS_COLUMN_NAME;
    }

    CryptoTransaction cryptoTransaction = new CryptoTransaction();
    cryptoTransaction.setTransactionHash(record.getStringValue(transactionHashColumnName));
    cryptoTransaction.setCryptoCurrency(CryptoCurrency.BITCOIN);
    try {
      cryptoTransaction.setCryptoStatus(
          CryptoStatus.getByCode(record.getStringValue(cryptoStatusColumnName)));
    } catch (InvalidParameterException e) {
      e.printStackTrace();
    }
    cryptoTransaction.setCryptoAmount(record.getLongValue(valueColumnName));
    cryptoTransaction.setAddressFrom(
        new CryptoAddress(record.getStringValue(addressFromColumnName), CryptoCurrency.BITCOIN));
    cryptoTransaction.setAddressTo(
        new CryptoAddress(record.getStringValue(addressToColumnName), CryptoCurrency.BITCOIN));

    // todo define how to get the Op_Return value
    return cryptoTransaction;
  }
예제 #22
0
  public void persistDigitalAsset(
      String genesisTransaction,
      String localStoragePath,
      String digitalAssetHash,
      String senderId,
      PlatformComponentType platformComponentType)
      throws CantPersistDigitalAssetException {
    try {
      this.database = openDatabase();
      DatabaseTable databaseTable =
          getDatabaseTable(AssetReceptionDatabaseConstants.ASSET_RECEPTION_TABLE_NAME);
      DatabaseTableRecord record = databaseTable.getEmptyRecord();
      record.setStringValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_GENESIS_TRANSACTION_COLUMN_NAME,
          genesisTransaction);
      record.setStringValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_DIGITAL_ASSET_HASH_COLUMN_NAME,
          digitalAssetHash);
      record.setStringValue(
          AssetReceptionDatabaseConstants
              .ASSET_RECEPTION_DIGITAL_ASSET_STORAGE_LOCAL_PATH_COLUMN_NAME,
          localStoragePath);
      record.setStringValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_SENDER_ID_COLUMN_NAME, senderId);
      record.setStringValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_SENDER_TYPE_COLUMN_NAME,
          platformComponentType.getCode());
      record.setStringValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_RECEPTION_STATUS_COLUMN_NAME,
          ReceptionStatus.RECEIVING.getCode());
      record.setStringValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_PROTOCOL_STATUS_COLUMN_NAME,
          ProtocolStatus.TO_BE_NOTIFIED.getCode());
      record.setStringValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_CRYPTO_STATUS_COLUMN_NAME,
          CryptoStatus.PENDING_SUBMIT.getCode());

      databaseTable.insertRecord(record);
    } catch (CantExecuteDatabaseOperationException exception) {
      throw new CantPersistDigitalAssetException(
          exception,
          "Persisting a receiving genesis digital asset",
          "Cannot open the Asset Reception database");
    } catch (CantInsertRecordException exception) {
      throw new CantPersistDigitalAssetException(
          exception,
          "Persisting a receiving genesis digital asset",
          "Cannot insert a record in the Asset Reception database");
    } catch (Exception exception) {
      throw new CantPersistDigitalAssetException(
          exception, "Persisting a receiving genesis digital asset", "Unexpected exception");
    }
  }
예제 #23
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());
  }
예제 #24
0
  private List<String> getPendingEventsBySource(EventSource eventSource)
      throws CantCheckAssetReceptionProgressException,
          UnexpectedResultReturnedFromDatabaseException {

    try {
      this.database = openDatabase();
      List<String> eventIdList = new ArrayList<>();
      DatabaseTable databaseTable =
          getDatabaseTable(
              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.addFilterOrder(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_TIMESTAMP_COLUMN_NAME,
          DatabaseFilterOrder.ASCENDING);
      databaseTable.loadToMemory();
      List<DatabaseTableRecord> databaseTableRecords = databaseTable.getRecords();
      for (DatabaseTableRecord databaseTableRecord : databaseTableRecords) {
        String eventId =
            databaseTableRecord.getStringValue(
                AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_ID_COLUMN_NAME);
        eventIdList.add(eventId);
      }

      return eventIdList;
    } catch (CantExecuteDatabaseOperationException exception) {

      throw new CantCheckAssetReceptionProgressException(
          exception, "Trying to get pending events", "Cannot find or open the database");
    } catch (CantLoadTableToMemoryException exception) {

      throw new CantCheckAssetReceptionProgressException(
          exception, "Trying to get pending events", "Cannot load the database into memory");
    } catch (Exception exception) {

      throw new CantCheckAssetReceptionProgressException(
          FermatException.wrapException(exception),
          "Trying to get pending events.",
          "Unexpected exception");
    }
  }
 private void mockitoRules() throws Exception {
   when(database.getTable(AssetIssuingDatabaseConstants.ASSET_ISSUING_METADATA_TABLE))
       .thenReturn(databaseTable);
   when(databaseTable.getRecords()).thenReturn(records);
   when(databaseTableRecord.getStringValue(
           AssetIssuingDatabaseConstants.ASSET_ISSUING_GENESIS_TRANSACTION_COLUMN_NAME))
       .thenReturn(genesisTransactionExpected);
 }
  /**
   * 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);
    }
  }
예제 #27
0
  /**
   * @param record with values from the table
   * @return FermatMessage setters the values from table
   */
  private FermatMessage constructFrom(DatabaseTableRecord record) {

    FermatMessageCommunication incomingTemplateNetworkServiceMessage =
        new FermatMessageCommunication();

    try {

      incomingTemplateNetworkServiceMessage.setId(
          UUID.fromString(
              record.getStringValue(
                  CommunicationNetworkServiceDatabaseConstants.INCOMING_MESSAGES_ID_COLUMN_NAME)));
      incomingTemplateNetworkServiceMessage.setSender(
          record.getStringValue(
              CommunicationNetworkServiceDatabaseConstants
                  .INCOMING_MESSAGES_SENDER_ID_COLUMN_NAME));
      incomingTemplateNetworkServiceMessage.setReceiver(
          record.getStringValue(
              CommunicationNetworkServiceDatabaseConstants
                  .INCOMING_MESSAGES_RECEIVER_ID_COLUMN_NAME));

      incomingTemplateNetworkServiceMessage.setContent(
          record.getStringValue(
              CommunicationNetworkServiceDatabaseConstants
                  .INCOMING_MESSAGES_TEXT_CONTENT_COLUMN_NAME));
      incomingTemplateNetworkServiceMessage.setFermatMessageContentType(
          (FermatMessageContentType.getByCode(
              record.getStringValue(
                  CommunicationNetworkServiceDatabaseConstants
                      .INCOMING_MESSAGES_TYPE_COLUMN_NAME))));
      incomingTemplateNetworkServiceMessage.setShippingTimestamp(
          new Timestamp(
              record.getLongValue(
                  CommunicationNetworkServiceDatabaseConstants
                      .INCOMING_MESSAGES_SHIPPING_TIMESTAMP_COLUMN_NAME)));
      incomingTemplateNetworkServiceMessage.setDeliveryTimestamp(
          new Timestamp(
              record.getLongValue(
                  CommunicationNetworkServiceDatabaseConstants
                      .INCOMING_MESSAGES_DELIVERY_TIMESTAMP_COLUMN_NAME)));

      incomingTemplateNetworkServiceMessage.setFermatMessagesStatus(
          FermatMessagesStatus.getByCode(
              record.getStringValue(
                  CommunicationNetworkServiceDatabaseConstants
                      .INCOMING_MESSAGES_STATUS_COLUMN_NAME)));

    } catch (InvalidParameterException e) {
      // TODO METODO CON RETURN NULL - OJO: solo INFORMATIVO de ayuda VISUAL para DEBUG - Eliminar
      // si molesta
      // this should not happen, but if it happens return null
      e.printStackTrace();
      return null;
    }

    return incomingTemplateNetworkServiceMessage;
  }
 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);
 }
  /**
   * 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;
  }
  private void populateProviderInfo(String providerName)
      throws CantInitializeProviderInfoException {
    DatabaseTable table =
        this.database.getTable(BitcoinVenezuelaProviderDatabaseConstants.PROVIDER_INFO_TABLE_NAME);
    DatabaseTableRecord newRecord = table.getEmptyRecord();

    newRecord.setUUIDValue(
        BitcoinVenezuelaProviderDatabaseConstants.PROVIDER_INFO_ID_COLUMN_NAME, UUID.randomUUID());
    newRecord.setStringValue(
        BitcoinVenezuelaProviderDatabaseConstants.PROVIDER_INFO_NAME_COLUMN_NAME, providerName);

    try {
      table.insertRecord(newRecord);
    } catch (CantInsertRecordException e) {
      throw new CantInitializeProviderInfoException(e.getMessage());
    }
  }