/**
   * 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 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;
  }
  /**
   * @param record with values from the table
   * @return WalletStoreNetworkServiceMessage setters the values from table
   */
  private WalletStoreNetworkServiceMessage constructFrom(DatabaseTableRecord record) {

    WalletStoreNetworkServiceMessage walletStoreNetworkServiceMessage =
        new WalletStoreNetworkServiceMessage();

    try {

      walletStoreNetworkServiceMessage.setId(
          record.getLongValue(
              WalletStoreNetworkServiceDatabaseConstants.INCOMING_MESSAGES_TABLE_ID_COLUMN_NAME));
      walletStoreNetworkServiceMessage.setSender(
          UUID.fromString(
              record.getStringValue(
                  WalletStoreNetworkServiceDatabaseConstants
                      .INCOMING_MESSAGES_TABLE_SENDER_ID_COLUMN_NAME)));
      walletStoreNetworkServiceMessage.setReceiver(
          UUID.fromString(
              record.getStringValue(
                  WalletStoreNetworkServiceDatabaseConstants
                      .INCOMING_MESSAGES_TABLE_RECEIVER_ID_COLUMN_NAME)));
      walletStoreNetworkServiceMessage.setTextContent(
          record.getStringValue(
              WalletStoreNetworkServiceDatabaseConstants
                  .INCOMING_MESSAGES_TABLE_TEXT_CONTENT_COLUMN_NAME));
      walletStoreNetworkServiceMessage.setMessageType(
          MessagesTypes.getByCode(
              record.getStringValue(
                  WalletStoreNetworkServiceDatabaseConstants
                      .INCOMING_MESSAGES_TABLE_TYPE_COLUMN_NAME)));
      walletStoreNetworkServiceMessage.setShippingTimestamp(
          new Timestamp(
              record.getLongValue(
                  WalletStoreNetworkServiceDatabaseConstants
                      .INCOMING_MESSAGES_TABLE_SHIPPING_TIMESTAMP_COLUMN_NAME)));
      walletStoreNetworkServiceMessage.setDeliveryTimestamp(
          new Timestamp(
              record.getLongValue(
                  WalletStoreNetworkServiceDatabaseConstants
                      .INCOMING_MESSAGES_TABLE_DELIVERY_TIMESTAMP_COLUMN_NAME)));
      walletStoreNetworkServiceMessage.setStatus(
          MessagesStatus.getByCode(
              record.getStringValue(
                  WalletStoreNetworkServiceDatabaseConstants
                      .INCOMING_MESSAGES_TABLE_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
      return null;
    }

    return walletStoreNetworkServiceMessage;
  }
  /**
   * 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;
  }
  private CustomerBrokerClose getCustomerBrokerCloseFromRecord(DatabaseTableRecord record)
      throws InvalidParameterException {

    UUID transactionId =
        record.getUUIDValue(
            CustomerBrokerCloseNegotiationTransactionDatabaseConstants
                .CUSTOMER_BROKER_CLOSE_TRANSACTION_ID_COLUMN_NAME);
    UUID negotiationId =
        record.getUUIDValue(
            CustomerBrokerCloseNegotiationTransactionDatabaseConstants
                .CUSTOMER_BROKER_CLOSE_NEGOTIATION_ID_COLUMN_NAME);
    String publicKeyBroker =
        record.getStringValue(
            CustomerBrokerCloseNegotiationTransactionDatabaseConstants
                .CUSTOMER_BROKER_CLOSE_PUBLIC_KEY_BROKER_COLUMN_NAME);
    String publicKeyCustomer =
        record.getStringValue(
            CustomerBrokerCloseNegotiationTransactionDatabaseConstants
                .CUSTOMER_BROKER_CLOSE_PUBLIC_KEY_CUSTOMER_COLUMN_NAME);
    NegotiationTransactionStatus status =
        NegotiationTransactionStatus.getByCode(
            record.getStringValue(
                CustomerBrokerCloseNegotiationTransactionDatabaseConstants
                    .CUSTOMER_BROKER_CLOSE_STATUS_COLUMN_NAME));
    NegotiationType negotiationType =
        NegotiationType.getByCode(
            record.getStringValue(
                CustomerBrokerCloseNegotiationTransactionDatabaseConstants
                    .CUSTOMER_BROKER_CLOSE_NEGOTIATION_TYPE_COLUMN_NAME));
    String negotiationXML =
        record.getStringValue(
            CustomerBrokerCloseNegotiationTransactionDatabaseConstants
                .CUSTOMER_BROKER_CLOSE_NEGOTIATION_XML_COLUMN_NAME);
    long timestamp =
        record.getLongValue(
            CustomerBrokerCloseNegotiationTransactionDatabaseConstants
                .CUSTOMER_BROKER_CLOSE_TIMESTAMP_COLUMN_NAME);

    return new CustomerBrokerCloseImpl(
        transactionId,
        negotiationId,
        publicKeyBroker,
        publicKeyCustomer,
        status,
        negotiationType,
        negotiationXML,
        timestamp);
  }
  /**
   * 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 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());
  }
  /**
   * 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;
  }
  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");
    }
  }
 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);
 }
  // GET LIST PENDING EVENT
  public List<String> getAllEvents()
      throws UnexpectedResultReturnedFromDatabaseException,
          CantGetNegotiationTransactionListException {

    try {

      DatabaseTable table =
          this.database.getTable(
              CustomerBrokerNewNegotiationTransactionDatabaseConstants
                  .CUSTOMER_BROKER_NEW_EVENT_TABLE_NAME);
      List<String> eventTypeList = new ArrayList<>();
      String eventString;
      table.loadToMemory();
      List<DatabaseTableRecord> records = table.getRecords();
      if (records.isEmpty()) return eventTypeList;

      for (DatabaseTableRecord databaseTableRecord : records) {
        eventString =
            "\n - ID = "
                + databaseTableRecord.getUUIDValue(
                    CustomerBrokerNewNegotiationTransactionDatabaseConstants
                        .CUSTOMER_BROKER_NEW_EVENT_ID_COLUMN_NAME)
                + "\n - STATUS = "
                + databaseTableRecord.getStringValue(
                    CustomerBrokerNewNegotiationTransactionDatabaseConstants
                        .CUSTOMER_BROKER_NEW_EVENT_STATUS_COLUMN_NAME)
                + ", "
                + "\n - TYPE = "
                + databaseTableRecord.getStringValue(
                    CustomerBrokerNewNegotiationTransactionDatabaseConstants
                        .CUSTOMER_BROKER_NEW_EVENT_TYPE_COLUMN_NAME);

        eventTypeList.add(eventString);
      }

      return eventTypeList;

    } catch (CantLoadTableToMemoryException e) {
      throw new CantGetNegotiationTransactionListException(
          CantGetNegotiationTransactionListException.DEFAULT_MESSAGE,
          e,
          "Getting events in EventStatus.PENDING",
          "Cannot load the table into memory");
    }
  }
  /**
   * Gets all the HierarchyAccounts records stored in the database
   *
   * @return the list of HierarchyAccounts objects
   * @throws CantExecuteDatabaseOperationException
   */
  @Override
  public List<HierarchyAccount> getHierarchyAccounts()
      throws CantExecuteDatabaseOperationException {
    List<HierarchyAccount> hierarchyAccounts = new ArrayList<>();
    DatabaseTable databaseTable =
        getDatabaseTable(AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_ACCOUNTS_TABLE_NAME);
    try {
      databaseTable.loadToMemory();
    } catch (CantLoadTableToMemoryException e) {
      throwLoadToMemoryException(e, databaseTable.getTableName());
    }

    /** Iterate each record and form the HierarchyAccount object. */
    for (DatabaseTableRecord record : databaseTable.getRecords()) {
      HierarchyAccount hierarchyAccount = null;
      try {
        hierarchyAccount =
            new HierarchyAccount(
                record.getIntegerValue(
                    AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_ACCOUNTS_ID_COLUMN_NAME),
                record.getStringValue(
                    AssetsOverBitcoinCryptoVaultDatabaseConstants
                        .KEY_ACCOUNTS_DESCRIPTION_COLUMN_NAME),
                HierarchyAccountType.getByCode(
                    record.getStringValue(
                        AssetsOverBitcoinCryptoVaultDatabaseConstants
                            .KEY_ACCOUNTS_TYPE_COLUMN_NAME)));
      } catch (InvalidParameterException e) {
        throw new CantExecuteDatabaseOperationException(
            CantExecuteDatabaseOperationException.DEFAULT_MESSAGE,
            e,
            "Invalid Account Type: "
                + record.getStringValue(
                    AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_ACCOUNTS_TYPE_COLUMN_NAME),
            null);
      }

      /** Adds the created HierarchyAccount into the list to be returned. */
      hierarchyAccounts.add(hierarchyAccount);
    }

    return hierarchyAccounts;
  }
  /**
   * (non-javadoc)
   *
   * @see AbstractBaseDao#getEntityFromDatabaseTableRecord(DatabaseTableRecord)
   */
  @Override
  protected NodeConnectionHistory getEntityFromDatabaseTableRecord(DatabaseTableRecord record)
      throws InvalidParameterException {

    NodeConnectionHistory entity = new NodeConnectionHistory();

    entity.setUuid(
        record.getUUIDValue(
            CommunicationsNetworkNodeP2PDatabaseConstants
                .NODES_CONNECTIONS_HISTORY_UUID_COLUMN_NAME));
    entity.setConnectionTimestamp(
        new Timestamp(
            record.getLongValue(
                CommunicationsNetworkNodeP2PDatabaseConstants
                    .NODES_CONNECTIONS_HISTORY_CONNECTION_TIMESTAMP_COLUMN_NAME)));
    entity.setDefaultPort(
        record.getIntegerValue(
            CommunicationsNetworkNodeP2PDatabaseConstants
                .NODES_CONNECTIONS_HISTORY_DEFAULT_PORT_COLUMN_NAME));
    entity.setIdentityPublicKey(
        record.getStringValue(
            CommunicationsNetworkNodeP2PDatabaseConstants
                .NODES_CONNECTIONS_HISTORY_IDENTITY_PUBLIC_KEY_COLUMN_NAME));
    entity.setIp(
        record.getStringValue(
            CommunicationsNetworkNodeP2PDatabaseConstants
                .NODES_CONNECTIONS_HISTORY_IP_COLUMN_NAME));
    entity.setLastLatitude(
        record.getDoubleValue(
            CommunicationsNetworkNodeP2PDatabaseConstants
                .NODES_CONNECTIONS_HISTORY_LAST_LATITUDE_COLUMN_NAME));
    entity.setLastLongitude(
        record.getDoubleValue(
            CommunicationsNetworkNodeP2PDatabaseConstants
                .NODES_CONNECTIONS_HISTORY_LAST_LONGITUDE_COLUMN_NAME));
    entity.setStatus(
        record.getStringValue(
            CommunicationsNetworkNodeP2PDatabaseConstants
                .NODES_CONNECTIONS_HISTORY_STATUS_COLUMN_NAME));

    return entity;
  }
  /**
   * Construct a ImageMiddlewareImpl whit the values of the table record pass by parameter
   *
   * @param record with values from the table
   * @return ImageMiddlewareImpl setters the values from table
   */
  private ImageMiddlewareImpl constructFrom(DatabaseTableRecord record)
      throws FileNotFoundException, CantCreateFileException {

    /*
     * Construct object
     */
    ImageMiddlewareImpl imageMiddleware = new ImageMiddlewareImpl();
    imageMiddleware.setFileId(
        UUID.fromString(
            record.getStringValue(
                WalletPublisherMiddlewareDatabaseConstants
                    .SCREENS_SHOTS_COMPONENTS_FILE_ID_COLUMN_NAME)));
    imageMiddleware.setComponentId(
        UUID.fromString(
            record.getStringValue(
                WalletPublisherMiddlewareDatabaseConstants
                    .SCREENS_SHOTS_COMPONENTS_COMPONENT_ID_COLUMN_NAME)));
    imageMiddleware.setData(imageManager.loadImageFile(imageMiddleware.getFileId().toString()));

    return imageMiddleware;
  }
  /**
   * 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;
  }
  /**
   * @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;
  }
Exemple #17
0
  public void saveNewEvent(String eventType, String eventSource) throws CantSaveEventException {
    try {
      this.database = openDatabase();
      DatabaseTable databaseTable =
          this.database.getTable(
              AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_TABLE_NAME);
      DatabaseTableRecord eventRecord = databaseTable.getEmptyRecord();
      UUID eventRecordID = UUID.randomUUID();
      long unixTime = System.currentTimeMillis();
      Logger LOG = Logger.getGlobal();
      LOG.info("ASSET DAO:\nUUID:" + eventRecordID + "\n" + unixTime);
      eventRecord.setUUIDValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_ID_COLUMN_NAME,
          eventRecordID);
      eventRecord.setStringValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_EVENT_COLUMN_NAME,
          eventType);
      eventRecord.setStringValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_SOURCE_COLUMN_NAME,
          eventSource);
      eventRecord.setStringValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_STATUS_COLUMN_NAME,
          EventStatus.PENDING.getCode());
      eventRecord.setLongValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_TIMESTAMP_COLUMN_NAME,
          unixTime);
      databaseTable.insertRecord(eventRecord);
      LOG.info(
          "record:"
              + eventRecord.getStringValue(
                  AssetReceptionDatabaseConstants
                      .ASSET_RECEPTION_EVENTS_RECORDED_TABLE_FIRST_KEY_COLUMN));

    } catch (CantExecuteDatabaseOperationException exception) {

      throw new CantSaveEventException(
          exception, "Saving new event.", "Cannot open or find the Asset Reception database");
    } catch (CantInsertRecordException exception) {

      throw new CantSaveEventException(
          exception, "Saving new event.", "Cannot insert a record in Asset Reception database");
    } catch (Exception exception) {

      throw new CantSaveEventException(
          FermatException.wrapException(exception), "Saving new event.", "Unexpected exception");
    }
  }
Exemple #18
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");
    }
  }
  /**
   * 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 List<String> getStringList(String key, String keyColumn, String valueColumn)
      throws CantGetNegotiationTransactionListException {
    try {

      DatabaseTable table =
          this.database.getTable(
              CustomerBrokerCloseNegotiationTransactionDatabaseConstants
                  .CUSTOMER_BROKER_CLOSE_TABLE_NAME);
      if (table == null) {
        throw new CantGetUserDeveloperIdentitiesException(
            "CANT GET NEGOTIATION TRANSACTION LISt. TABLE NO FOUNT.",
            "NEGOTIATION TRANSACTION customer broker close",
            "CANT GET NEGOTIATION TRANSACTION LIST, TABLE NO FOUNT.");
      }
      List<String> negotiationList = new ArrayList<>();
      String negotiation;
      table.addStringFilter(keyColumn, key, DatabaseFilterType.EQUAL);
      table.loadToMemory();
      List<DatabaseTableRecord> records = table.getRecords();
      if (records.isEmpty()) {
        // There is no records in database, I'll return an empty list.
        return negotiationList;
      }

      for (DatabaseTableRecord databaseTableRecord : records) {
        negotiation = databaseTableRecord.getStringValue(valueColumn);
        negotiationList.add(negotiation);
      }

      return negotiationList;

    } catch (CantLoadTableToMemoryException e) {
      throw new CantGetNegotiationTransactionListException(
          CantGetNegotiationTransactionListException.DEFAULT_MESSAGE,
          e,
          "Getting " + valueColumn + " based on " + key,
          "Cannot load the table into memory");
    } catch (Exception e) {
      throw new CantGetNegotiationTransactionListException(
          e.getMessage(),
          FermatException.wrapException(e),
          "Getting " + valueColumn + " based on " + key,
          "Cannot load the table into memory");
    }
  }
  public boolean walletExists(String walletPublicKey) {
    DatabaseTableRecord record = null;
    try {
      record = this.getWalletRecordByPublicKey(walletPublicKey);
    } catch (CashMoneyWalletDoesNotExistException e) {
      return false;
    } catch (Exception e) {
      errorManager.reportUnexpectedPluginException(
          Plugins.BITDUBAI_CSH_WALLET_CASH_MONEY,
          UnexpectedPluginExceptionSeverity.DISABLES_THIS_PLUGIN,
          e);
      return false;
    }

    if (record
        .getStringValue(CashMoneyWalletDatabaseConstants.WALLETS_WALLET_PUBLIC_KEY_COLUMN_NAME)
        .equals(walletPublicKey)) return true;
    else return false;
  }
  public void updateDailyExchangeRateTable(
      CurrencyPair currencyPair, List<ExchangeRate> exchangeRates)
      throws CantSaveExchangeRateException {
    List<String> exchangeRateTimestampsInDatabase = new ArrayList<>();

    DatabaseTable table =
        this.database.getTable(
            BitcoinVenezuelaProviderDatabaseConstants.DAILY_EXCHANGE_RATES_TABLE_NAME);
    table.addStringFilter(
        BitcoinVenezuelaProviderDatabaseConstants.DAILY_EXCHANGE_RATES_FROM_CURRENCY_COLUMN_NAME,
        currencyPair.getFrom().getCode(),
        DatabaseFilterType.EQUAL);
    table.addStringFilter(
        BitcoinVenezuelaProviderDatabaseConstants.DAILY_EXCHANGE_RATES_TO_CURRENCY_COLUMN_NAME,
        currencyPair.getTo().getCode(),
        DatabaseFilterType.EQUAL);

    try {
      table.loadToMemory();

      for (DatabaseTableRecord record : table.getRecords()) {
        String timestamp =
            record.getStringValue(
                BitcoinVenezuelaProviderDatabaseConstants
                    .DAILY_EXCHANGE_RATES_TIMESTAMP_COLUMN_NAME);
        exchangeRateTimestampsInDatabase.add(timestamp);
      }
    } catch (CantLoadTableToMemoryException e) {
      throw new CantSaveExchangeRateException(
          CantSaveExchangeRateException.DEFAULT_MESSAGE,
          e,
          "Failed to get ExchangeRates in database for CurrencyPair: " + currencyPair.toString(),
          "Couldn't load table to memory");
    }

    for (ExchangeRate e : exchangeRates) {
      String currentTimestamp = String.valueOf(e.getTimestamp());
      if (!exchangeRateTimestampsInDatabase.contains(currentTimestamp)) {
        this.saveDailyExchangeRate(e); // TODO: improve this.. saving one by one..
      }
    }
  }
Exemple #23
0
  public String getEventTypeById(String eventId)
      throws CantCheckAssetReceptionProgressException,
          UnexpectedResultReturnedFromDatabaseException {

    try {
      this.database = openDatabase();
      DatabaseTable databaseTable =
          getDatabaseTable(
              AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_TABLE_NAME);
      databaseTable.addStringFilter(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_ID_COLUMN_NAME,
          eventId,
          DatabaseFilterType.EQUAL);
      databaseTable.loadToMemory();
      List<DatabaseTableRecord> databaseTableRecords = databaseTable.getRecords();
      DatabaseTableRecord databaseTableRecord;
      if (databaseTableRecords.size() > 1) {

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

      return databaseTableRecord.getStringValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_EVENT_COLUMN_NAME);
    } 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");
    }
  }
  /**
   * Will load an existing Hierarchy Account
   *
   * @param publicKey
   * @return
   */
  public HierarchyAccount getHierarchyAccount(String publicKey)
      throws CantExecuteDatabaseOperationException {
    DatabaseTable databaseTable =
        database.getTable(AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_ACCOUNTS_TABLE_NAME);
    databaseTable.addStringFilter(
        AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_ACCOUNTS_DESCRIPTION_COLUMN_NAME,
        publicKey,
        DatabaseFilterType.EQUAL);

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

    if (databaseTable.getRecords().size() != 1)
      throw new CantExecuteDatabaseOperationException(
          CantExecuteDatabaseOperationException.DEFAULT_MESSAGE,
          null,
          "inconsistent data found in Key_Accounts table.",
          "more than one Hierarchy Account stored.");

    DatabaseTableRecord record = databaseTable.getRecords().get(0);

    /** Gets the records and forms the HierarchyAccount class. */
    int id =
        record.getIntegerValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_ACCOUNTS_ID_COLUMN_NAME);
    HierarchyAccountType hierarchyAccountType = null;
    try {
      hierarchyAccountType =
          HierarchyAccountType.getByCode(
              record.getStringValue(
                  AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_ACCOUNTS_TYPE_COLUMN_NAME));
    } catch (InvalidParameterException e) {
      hierarchyAccountType = HierarchyAccountType.REDEEMPOINT_ACCOUNT;
    }

    HierarchyAccount hierarchyAccount = new HierarchyAccount(id, publicKey, hierarchyAccountType);
    return hierarchyAccount;
  }
  public FiatCurrency getWalletCurrency(String walletPublicKey)
      throws CantGetCashMoneyWalletCurrencyException {
    FiatCurrency currency;
    try {
      DatabaseTableRecord record = this.getWalletRecordByPublicKey(walletPublicKey);
      currency =
          FiatCurrency.getByCode(
              record.getStringValue(CashMoneyWalletDatabaseConstants.WALLETS_CURRENCY_COLUMN_NAME));
    } catch (Exception e) {
      errorManager.reportUnexpectedPluginException(
          Plugins.BITDUBAI_CSH_WALLET_CASH_MONEY,
          UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN,
          e);
      throw new CantGetCashMoneyWalletCurrencyException(
          CantGetCashMoneyWalletCurrencyException.DEFAULT_MESSAGE,
          e,
          "Cant get wallet currency",
          null);
    }

    return currency;
  }
  public List<RedeemPointIdentity> getIdentityAssetRedeemPointsFromCurrentDeviceUser(
      DeviceUser deviceUser) throws CantListAssetRedeemPointIdentitiesException {

    // Setup method.
    List<RedeemPointIdentity> list = new ArrayList<>(); // Intra User list.
    DatabaseTable table; // Intra User table.

    // Get Redeem Point identities list.
    try {

      /** 1) Get the table. */
      table =
          this.database.getTable(
              AssetRedeemPointIdentityDatabaseConstants.ASSET_REDEEM_POINT_IDENTITY_TABLE_NAME);

      if (table == null) {
        /** Table not found. */
        throw new CantGetUserDeveloperIdentitiesException(
            "Cant get Asset Issuer identity list, table not found.",
            "Asset IssuerIdentity",
            "Cant get Intra User identity list, table not found.");
      }

      // 2) Find the Redeem Point.
      table.setStringFilter(
          AssetRedeemPointIdentityDatabaseConstants
              .ASSET_REDEEM_POINT_IDENTITY_DEVICE_USER_PUBLIC_KEY_COLUMN_NAME,
          deviceUser.getPublicKey(),
          DatabaseFilterType.EQUAL);
      table.loadToMemory();

      // 3) Get Redeem Point.
      for (DatabaseTableRecord record : table.getRecords()) {

        // Add records to list.
        list.add(
            new IdentityAssetRedeemPointImpl(
                record.getStringValue(
                    AssetRedeemPointIdentityDatabaseConstants
                        .ASSET_REDEEM_POINT_IDENTITY_ALIAS_COLUMN_NAME),
                record.getStringValue(
                    AssetRedeemPointIdentityDatabaseConstants
                        .ASSET_REDEEM_POINT_IDENTITY_PUBLIC_KEY_COLUMN_NAME),
                getAssetIssuerIdentityPrivateKey(
                    record.getStringValue(
                        AssetRedeemPointIdentityDatabaseConstants
                            .ASSET_REDEEM_POINT_IDENTITY_PUBLIC_KEY_COLUMN_NAME)),
                getAssetIssuerProfileImagePrivateKey(
                    record.getStringValue(
                        AssetRedeemPointIdentityDatabaseConstants
                            .ASSET_REDEEM_POINT_IDENTITY_DEVICE_USER_PUBLIC_KEY_COLUMN_NAME)),
                pluginFileSystem,
                pluginId));
      }
    } catch (CantLoadTableToMemoryException e) {
      throw new CantListAssetRedeemPointIdentitiesException(
          e.getMessage(),
          e,
          "Asset Redeem Point Identity",
          "Cant load "
              + AssetRedeemPointIdentityDatabaseConstants.ASSET_REDEEM_POINT_IDENTITY_TABLE_NAME
              + " table in memory.");
    } catch (CantGetAssetRedeemPointIdentityPrivateKeyException e) {
      // Failure unknown.
      throw new CantListAssetRedeemPointIdentitiesException(
          e.getMessage(), e, "Asset Redeem Point Identity", "Can't get private key.");

    } catch (Exception e) {
      throw new CantListAssetRedeemPointIdentitiesException(
          e.getMessage(),
          FermatException.wrapException(e),
          "Asset Redeem Point Identity",
          "Cant get Asset Issuer identity list, unknown failure.");
    }

    // Return the list values.
    return list;
  }
  private NegotiationTransmission buildNegotiationTransmission(DatabaseTableRecord record)
      throws InvalidParameterException {
    try {

      UUID transmissionId =
          record.getUUIDValue(
              com.bitdubai
                  .fermat_cbp_plugin
                  .layer
                  .network_service
                  .negotiation_transmission
                  .developer
                  .bitdubai
                  .version_1
                  .newDatabase
                  .NegotiationTransmissionNetworkServiceDatabaseConstants
                  .OUTGOING_NOTIFICATION_TRANSMISSION_ID_COLUMN_NAME);
      UUID transactionId =
          record.getUUIDValue(
              com.bitdubai
                  .fermat_cbp_plugin
                  .layer
                  .network_service
                  .negotiation_transmission
                  .developer
                  .bitdubai
                  .version_1
                  .newDatabase
                  .NegotiationTransmissionNetworkServiceDatabaseConstants
                  .OUTGOING_NOTIFICATION_TRANSACTION_ID_COLUMN_NAME);
      UUID negotiationId =
          record.getUUIDValue(
              com.bitdubai
                  .fermat_cbp_plugin
                  .layer
                  .network_service
                  .negotiation_transmission
                  .developer
                  .bitdubai
                  .version_1
                  .newDatabase
                  .NegotiationTransmissionNetworkServiceDatabaseConstants
                  .OUTGOING_NOTIFICATION_NEGOTIATION_ID_COLUMN_NAME);
      String negotiationTransactionType =
          record.getStringValue(
              com.bitdubai
                  .fermat_cbp_plugin
                  .layer
                  .network_service
                  .negotiation_transmission
                  .developer
                  .bitdubai
                  .version_1
                  .newDatabase
                  .NegotiationTransmissionNetworkServiceDatabaseConstants
                  .OUTGOING_NOTIFICATION_NEGOTIATION_TRANSACTION_TYPE_COLUMN_NAME);
      String publicKeyActorSend =
          record.getStringValue(
              com.bitdubai
                  .fermat_cbp_plugin
                  .layer
                  .network_service
                  .negotiation_transmission
                  .developer
                  .bitdubai
                  .version_1
                  .newDatabase
                  .NegotiationTransmissionNetworkServiceDatabaseConstants
                  .OUTGOING_NOTIFICATION_PUBLIC_KEY_ACTOR_SEND_COLUMN_NAME);
      String actorSendType =
          record.getStringValue(
              com.bitdubai
                  .fermat_cbp_plugin
                  .layer
                  .network_service
                  .negotiation_transmission
                  .developer
                  .bitdubai
                  .version_1
                  .newDatabase
                  .NegotiationTransmissionNetworkServiceDatabaseConstants
                  .OUTGOING_NOTIFICATION_ACTOR_SEND_TYPE_COLUMN_NAME);
      String publicKeyActorReceive =
          record.getStringValue(
              com.bitdubai
                  .fermat_cbp_plugin
                  .layer
                  .network_service
                  .negotiation_transmission
                  .developer
                  .bitdubai
                  .version_1
                  .newDatabase
                  .NegotiationTransmissionNetworkServiceDatabaseConstants
                  .OUTGOING_NOTIFICATION_PUBLIC_KEY_ACTOR_RECEIVE_COLUMN_NAME);
      String actorReceiveType =
          record.getStringValue(
              com.bitdubai
                  .fermat_cbp_plugin
                  .layer
                  .network_service
                  .negotiation_transmission
                  .developer
                  .bitdubai
                  .version_1
                  .newDatabase
                  .NegotiationTransmissionNetworkServiceDatabaseConstants
                  .OUTGOING_NOTIFICATION_ACTOR_RECEIVE_TYPE_COLUMN_NAME);
      String transmissionType =
          record.getStringValue(
              com.bitdubai
                  .fermat_cbp_plugin
                  .layer
                  .network_service
                  .negotiation_transmission
                  .developer
                  .bitdubai
                  .version_1
                  .newDatabase
                  .NegotiationTransmissionNetworkServiceDatabaseConstants
                  .OUTGOING_NOTIFICATION_TRANSMISSION_TYPE_COLUMN_NAME);
      String transmissionState =
          record.getStringValue(
              com.bitdubai
                  .fermat_cbp_plugin
                  .layer
                  .network_service
                  .negotiation_transmission
                  .developer
                  .bitdubai
                  .version_1
                  .newDatabase
                  .NegotiationTransmissionNetworkServiceDatabaseConstants
                  .OUTGOING_NOTIFICATION_TRANSMISSION_STATE_COLUMN_NAME);
      String negotiationType =
          record.getStringValue(
              com.bitdubai
                  .fermat_cbp_plugin
                  .layer
                  .network_service
                  .negotiation_transmission
                  .developer
                  .bitdubai
                  .version_1
                  .newDatabase
                  .NegotiationTransmissionNetworkServiceDatabaseConstants
                  .OUTGOING_NOTIFICATION_NEGOTIATION_TYPE_COLUMN_NAME);
      String negotiationXML =
          record.getStringValue(
              com.bitdubai
                  .fermat_cbp_plugin
                  .layer
                  .network_service
                  .negotiation_transmission
                  .developer
                  .bitdubai
                  .version_1
                  .newDatabase
                  .NegotiationTransmissionNetworkServiceDatabaseConstants
                  .OUTGOING_NOTIFICATION_NEGOTIATION_XML_COLUMN_NAME);
      long timestamp =
          record.getLongValue(
              com.bitdubai
                  .fermat_cbp_plugin
                  .layer
                  .network_service
                  .negotiation_transmission
                  .developer
                  .bitdubai
                  .version_1
                  .newDatabase
                  .NegotiationTransmissionNetworkServiceDatabaseConstants
                  .OUTGOING_NOTIFICATION_TIMESTAMP_COLUMN_NAME);
      String pendingFlag =
          record.getStringValue(
              com.bitdubai
                  .fermat_cbp_plugin
                  .layer
                  .network_service
                  .negotiation_transmission
                  .developer
                  .bitdubai
                  .version_1
                  .newDatabase
                  .NegotiationTransmissionNetworkServiceDatabaseConstants
                  .OUTGOING_NOTIFICATION_NETWORK_SERVICE_PENDING_FLAG_COLUMN_NAME);
      String flagRead =
          record.getStringValue(
              com.bitdubai
                  .fermat_cbp_plugin
                  .layer
                  .network_service
                  .negotiation_transmission
                  .developer
                  .bitdubai
                  .version_1
                  .newDatabase
                  .NegotiationTransmissionNetworkServiceDatabaseConstants
                  .OUTGOING_NOTIFICATION_READ_MARK_COLUMN_NAME);
      String protocolState =
          record.getStringValue(
              com.bitdubai
                  .fermat_cbp_plugin
                  .layer
                  .network_service
                  .negotiation_transmission
                  .developer
                  .bitdubai
                  .version_1
                  .newDatabase
                  .NegotiationTransmissionNetworkServiceDatabaseConstants
                  .OUTGOING_NOTIFICATION_PROTOCOL_STATE_COLUMN_NAME);
      int sentCount = 0;
      UUID responseToNotificationId =
          record.getUUIDValue(
              com.bitdubai
                  .fermat_cbp_plugin
                  .layer
                  .network_service
                  .negotiation_transmission
                  .developer
                  .bitdubai
                  .version_1
                  .newDatabase
                  .NegotiationTransmissionNetworkServiceDatabaseConstants
                  .OUTGOING_NOTIFICATION_RESPONSE_TO_NOTIFICATION_ID_COLUMN_NAME);

      ActorProtocolState actorProtocolState = null;
      if (protocolState != null) {
        actorProtocolState = ActorProtocolState.getByCode(protocolState);
      }

      return new NegotiationTransmissionImpl(
          transmissionId,
          transactionId,
          negotiationId,
          NegotiationTransactionType.getByCode(negotiationTransactionType),
          publicKeyActorSend,
          PlatformComponentType.getByCode(actorSendType),
          publicKeyActorReceive,
          PlatformComponentType.getByCode(actorReceiveType),
          NegotiationTransmissionType.getByCode(transmissionType),
          NegotiationTransmissionState.getByCode(transmissionState),
          NegotiationType.getByCode(negotiationType),
          negotiationXML,
          timestamp,
          Boolean.valueOf(pendingFlag),
          Boolean.valueOf(flagRead),
          actorProtocolState,
          sentCount,
          responseToNotificationId);
    } catch (Exception e) {
      throw new InvalidParameterException();
    }
  }
  public Artist getIdentityArtist(String publicKey) throws CantGetArtistIdentityException {

    // Setup method.
    Artist artist = null;
    DatabaseTable table; // Intra User table.

    // Get Asset Issuers identities list.
    try {

      /** 1) Get the table. */
      table = this.database.getTable(ArtistIdentityDatabaseConstants.ARTIST_IDENTITY_TABLE_NAME);

      if (table == null) {
        /** Table not found. */
        throw new CantUpdateArtistIdentityException(
            "Cant get Asset Issuer identity list, table not found.",
            "Asset IssuerIdentity",
            "Cant get Intra User identity list, table not found.");
      }

      // 2) Find the Identity Issuers.

      table.addStringFilter(
          ArtistIdentityDatabaseConstants.ARTIST_IDENTITY_PUBLIC_KEY_COLUMN_NAME,
          publicKey,
          DatabaseFilterType.EQUAL);
      table.loadToMemory();

      // 3) Get Identity Issuers.

      for (DatabaseTableRecord record : table.getRecords()) {

        // Add records to list.
        /*artist = new IdentityAssetRedeemPointImpl(
        record.getStringValue(ArtistIdentityDatabaseConstants.ARTIST_IDENTITY_ALIAS_COLUMN_NAME),
        record.getStringValue(ArtistIdentityDatabaseConstants.ARTIST_IDENTITY_PUBLIC_KEY_COLUMN_NAME),
        getArtistProfileImagePrivateKey(record.getStringValue(ArtistIdentityDatabaseConstants.ARTIST_IDENTITY_PUBLIC_KEY_COLUMN_NAME)));*/
        artist =
            new ArtistIdentityImp(
                record.getStringValue(
                    ArtistIdentityDatabaseConstants.ARTIST_IDENTITY_ALIAS_COLUMN_NAME),
                record.getStringValue(
                    ArtistIdentityDatabaseConstants.ARTIST_IDENTITY_PUBLIC_KEY_COLUMN_NAME),
                getArtistProfileImagePrivateKey(
                    record.getStringValue(
                        ArtistIdentityDatabaseConstants.ARTIST_IDENTITY_PUBLIC_KEY_COLUMN_NAME)),
                record.getStringValue(
                    ArtistIdentityDatabaseConstants.ARTIST_IDENTITY_EXTERNAL_USER_NAME_COLUMN_NAME),
                record.getStringValue(
                    ArtistIdentityDatabaseConstants
                        .ARTIST_IDENTITY_EXTERNAL_ACCESS_TOKEN_COLUMN_NAME),
                ExternalPlatform.getByCode(
                    record.getStringValue(
                        ArtistIdentityDatabaseConstants
                            .ARTIST_IDENTITY_EXTERNAL_PLATFORM_COLUMN_NAME)),
                ExposureLevel.getByCode(
                    record.getStringValue(
                        ArtistIdentityDatabaseConstants
                            .ARTIST_IDENTITY_EXPOSURE_LEVEL_COLUMN_NAME)),
                ArtistAcceptConnectionsType.getByCode(
                    record.getStringValue(
                        ArtistIdentityDatabaseConstants
                            .ARTIST_IDENTITY_ACEEPTS_CONNECTIONS_TYPE_COLUMN_NAME)),
                pluginFileSystem,
                pluginId);
      }
    } catch (CantLoadTableToMemoryException e) {
      throw new CantGetArtistIdentityException(
          e.getMessage(),
          e,
          "Asset Redeem Point Identity",
          "Cant load "
              + ArtistIdentityDatabaseConstants.ARTIST_IDENTITY_TABLE_NAME
              + " table in memory.");
    } catch (Exception e) {
      throw new CantGetArtistIdentityException(
          e.getMessage(),
          FermatException.wrapException(e),
          "Asset Redeem Point Identity",
          "Cant get Asset Redeem Point identity list, unknown failure.");
    }

    // Return the list values.
    return artist;
  }
  private OutgoingDraftTransactionWrapper convertToBT(DatabaseTableRecord record)
      throws InvalidParameterException {
    //        boolean sameDevice =
    // Boolean.valueOf(record.getStringValue(OutgoingDraftTransactionDatabaseConstants.OUTGOING_DRAFT_SAME_DEVICE_COLUMN_NAME));
    String walletPublicKey =
        record.getStringValue(
            OutgoingDraftTransactionDatabaseConstants
                .OUTGOING_DRAFT_WALLET_ID_TO_DEBIT_FROM_COLUMN_NAME);
    UUID transactionId =
        record.getUUIDValue(
            OutgoingDraftTransactionDatabaseConstants.OUTGOING_DRAFT_TRANSACTION_ID_COLUMN_NAME);
    String transactionHash =
        record.getStringValue(
            OutgoingDraftTransactionDatabaseConstants.OUTGOING_DRAFT_TRANSACTION_HASH_COLUMN_NAME);
    long amount =
        record.getLongValue(
            OutgoingDraftTransactionDatabaseConstants.OUTGOING_DRAFT_CRYPTO_AMOUNT_COLUMN_NAME);
    //        String op_Return =
    // record.getStringValue(OutgoingDraftTransactionDatabaseConstants.OUTGOING_DRAFT_OP_RETURN_COLUMN_NAME);
    com.bitdubai.fermat_ccp_plugin.layer.crypto_transaction.outgoing_draft.developer.bitdubai
            .version_1.enums.TransactionState
        state =
            com.bitdubai.fermat_ccp_plugin.layer.crypto_transaction.outgoing_draft.developer
                .bitdubai.version_1.enums.TransactionState.getByCode(
                record.getStringValue(
                    OutgoingDraftTransactionDatabaseConstants
                        .OUTGOING_DRAFT_TRANSACTION_STATUS_COLUMN_NAME));
    long timestamp =
        record.getLongValue(
            OutgoingDraftTransactionDatabaseConstants.OUTGOING_DRAFT_TIMESTAMP_COLUMN_NAME);
    String memo =
        record.getStringValue(
            OutgoingDraftTransactionDatabaseConstants.OUTGOING_DRAFT_DESCRIPTION_COLUMN_NAME);
    //        CryptoStatus cryptoStatus =
    // CryptoStatus.getByCode(record.getStringValue(OutgoingDraftTransactionDatabaseConstants.OUTGOING_DRAFT_CRYPTO_STATUS_COLUMN_NAME));
    Actors actorFromType =
        Actors.getByCode(
            record.getStringValue(
                OutgoingDraftTransactionDatabaseConstants
                    .OUTGOING_DRAFT_ACTOR_FROM_TYPE_COLUMN_NAME));
    Actors actorToType =
        Actors.getByCode(
            record.getStringValue(
                OutgoingDraftTransactionDatabaseConstants
                    .OUTGOING_DRAFT_ACTOR_TO_TYPE_COLUMN_NAME));
    String actorFromPublicKey =
        record.getStringValue(
            OutgoingDraftTransactionDatabaseConstants
                .OUTGOING_DRAFT_ACTOR_FROM_PUBLIC_KEY_COLUMN_NAME);
    String actorToPublicKey =
        record.getStringValue(
            OutgoingDraftTransactionDatabaseConstants
                .OUTGOING_DRAFT_ACTOR_TO_PUBLIC_KEY_COLUMN_NAME);
    ReferenceWallet referenceWallet =
        ReferenceWallet.getByCode(
            record.getStringValue(
                OutgoingDraftTransactionDatabaseConstants
                    .OUTGOING_DRAFT_WALLET_REFERENCE_TYPE_COLUMN_NAME));
    String addressFrom =
        record.getStringValue(
            OutgoingDraftTransactionDatabaseConstants.OUTGOING_DRAFT_ADDRESS_FROM_COLUMN_NAME);
    String addressTo =
        record.getStringValue(
            OutgoingDraftTransactionDatabaseConstants.OUTGOING_DRAFT_ADDRESS_TO_COLUMN_NAME);
    //        CryptoAddress cryptoAddressFrom = null;
    //        if (addressFrom != null) {
    //            cryptoAddressFrom = new CryptoAddress(
    //                    addressFrom,
    //
    // CryptoCurrency.getByCode(OutgoingDraftTransactionDatabaseConstants.OUTGOING_DRAFT_CRYPTO_CURRENCY_COLUMN_NAME));
    //        }
    CryptoAddress cryptoAddressTo = null;
    if (addressFrom != null) {
      cryptoAddressTo =
          new CryptoAddress(
              addressTo,
              CryptoCurrency.getByCode(
                  record.getStringValue(
                      OutgoingDraftTransactionDatabaseConstants
                          .OUTGOING_DRAFT_CRYPTO_CURRENCY_COLUMN_NAME)));
    }
    BlockchainNetworkType blockchainNetworkType =
        BlockchainNetworkType.getByCode(
            record.getStringValue(
                OutgoingDraftTransactionDatabaseConstants.OUTGOING_DRAFT_RUNNING_NETWORK_TYPE));

    return new OutgoingDraftTransactionWrapper(
        transactionId,
        walletPublicKey,
        amount,
        cryptoAddressTo,
        referenceWallet,
        blockchainNetworkType,
        actorFromPublicKey,
        actorToPublicKey,
        actorFromType,
        actorToType,
        memo,
        timestamp,
        transactionHash);
  }
  /**
   * Gets the incoming transaction data and forms the CryptoTransaction object
   *
   * @param txHash
   * @return
   * @throws CantExecuteDatabaseOperationException
   */
  public List<CryptoTransaction> getIncomingCryptoTransaction(String txHash)
      throws CantExecuteDatabaseOperationException {
    DatabaseTable databaseTable =
        database.getTable(BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_TABLE_NAME);
    databaseTable.setStringFilter(
        BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_HASH_COLUMN_NAME,
        txHash,
        DatabaseFilterType.EQUAL);

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

    List<CryptoTransaction> cryptoTransactions = new ArrayList<>();
    for (DatabaseTableRecord record : databaseTable.getRecords()) {

      /** Gets all the values */
      CryptoAddress addressFrom = new CryptoAddress();
      addressFrom.setAddress(
          record.getStringValue(
              BitcoinCryptoNetworkDatabaseConstants
                  .INCOMING_TRANSACTIONS_ADDRESS_FROM_COLUMN_NAME));
      addressFrom.setCryptoCurrency(CryptoCurrency.BITCOIN);

      CryptoAddress addressTo = new CryptoAddress();
      addressFrom.setAddress(
          record.getStringValue(
              BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_ADDRESS_TO_COLUMN_NAME));
      addressFrom.setCryptoCurrency(CryptoCurrency.BITCOIN);

      long amount =
          record.getLongValue(
              BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_VALUE_COLUMN_NAME);

      CryptoStatus cryptoStatus = null;
      try {
        cryptoStatus =
            CryptoStatus.getByCode(
                record.getStringValue(
                    BitcoinCryptoNetworkDatabaseConstants
                        .INCOMING_TRANSACTIONS_CRYPTO_STATUS_COLUMN_NAME));
      } catch (InvalidParameterException e) {
        e.printStackTrace();
      }

      String op_Return =
          record.getStringValue(
              BitcoinCryptoNetworkDatabaseConstants.INCOMING_TRANSACTIONS_OP_RETURN_COLUMN_NAME);

      /** Forms the CryptoTransaction object */
      CryptoTransaction cryptoTransaction = new CryptoTransaction();
      cryptoTransaction.setTransactionHash(txHash);
      cryptoTransaction.setAddressTo(addressTo);
      cryptoTransaction.setAddressFrom(addressFrom);
      cryptoTransaction.setCryptoAmount(amount);
      cryptoTransaction.setCryptoCurrency(CryptoCurrency.BITCOIN);
      cryptoTransaction.setCryptoStatus(cryptoStatus);
      cryptoTransaction.setOp_Return(op_Return);

      /** adds it to the list */
      cryptoTransactions.add(cryptoTransaction);
    }

    return cryptoTransactions;
  }