예제 #1
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);
    }
  }
예제 #2
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.");
    }
  }
  /**
   * 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");
    }
  }
  /**
   * 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");
    }
  }
  /*SAVE NEW EVENT*/
  public void saveNewEventTransaction(String eventType, String eventSource)
      throws CantSaveEventException {

    try {

      UUID eventId = UUID.randomUUID();
      Date time = new Date();
      long timestamp = time.getTime();

      DatabaseTable table =
          this.database.getTable(
              CustomerBrokerNewNegotiationTransactionDatabaseConstants
                  .CUSTOMER_BROKER_NEW_EVENT_TABLE_NAME);
      DatabaseTableRecord eventRecord = table.getEmptyRecord();

      eventRecord.setUUIDValue(
          CustomerBrokerNewNegotiationTransactionDatabaseConstants
              .CUSTOMER_BROKER_NEW_EVENT_ID_COLUMN_NAME,
          eventId);
      eventRecord.setStringValue(
          CustomerBrokerNewNegotiationTransactionDatabaseConstants
              .CUSTOMER_BROKER_NEW_EVENT_TYPE_COLUMN_NAME,
          eventType);
      eventRecord.setStringValue(
          CustomerBrokerNewNegotiationTransactionDatabaseConstants
              .CUSTOMER_BROKER_NEW_EVENT_SOURCE_COLUMN_NAME,
          eventSource);
      eventRecord.setStringValue(
          CustomerBrokerNewNegotiationTransactionDatabaseConstants
              .CUSTOMER_BROKER_NEW_EVENT_STATUS_COLUMN_NAME,
          EventStatus.PENDING.getCode());
      eventRecord.setLongValue(
          CustomerBrokerNewNegotiationTransactionDatabaseConstants
              .CUSTOMER_BROKER_NEW_EVENT_TIMESTAMP_COLUMN_NAME,
          timestamp);

      table.insertRecord(eventRecord);

      //            System.out.print("\n\n**** 17) MOCK NEGOTIATION TRANSACTION - NEGOTIATION
      // TRANSMISSION - DAO - REGISTER NEW EVENT ****\n");

    } catch (CantInsertRecordException exception) {
      throw new CantSaveEventException(
          exception, "Saving new event.", "Cannot insert a record in Asset Distribution database");
    } catch (Exception exception) {
      throw new CantSaveEventException(
          FermatException.wrapException(exception), "Saving new event.", "Unexpected exception");
    }
  }
  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);
    }
  }
  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);
    }
  }
  // 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();
    }
  }
예제 #9
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");
    }
  }
예제 #10
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());
  }
  /**
   * Saves and outgoing transaction into the database
   *
   * @param hash
   * @param cryptoStatus
   * @param blockDepth
   * @param addressTo
   * @param addressFrom
   * @param value
   * @param op_Return
   * @param protocolStatus
   * @throws CantExecuteDatabaseOperationException
   */
  public void saveNewOutgoingTransaction(
      String hash,
      CryptoStatus cryptoStatus,
      int blockDepth,
      CryptoAddress addressTo,
      CryptoAddress addressFrom,
      long value,
      String op_Return,
      ProtocolStatus protocolStatus)
      throws CantExecuteDatabaseOperationException {
    DatabaseTable databaseTable =
        database.getTable(BitcoinCryptoNetworkDatabaseConstants.OUTGOING_TRANSACTIONS_TABLE_NAME);
    DatabaseTableRecord record = databaseTable.getEmptyRecord();

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

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

      throw new CantExecuteDatabaseOperationException(
          CantExecuteDatabaseOperationException.DEFAULT_MESSAGE,
          e,
          outputMessage.toString(),
          "database issue.");
    }
  }
예제 #12
0
  /**
   * Construct a DatabaseTableRecord whit the values of the a WalletStoreNetworkServiceMessage pass
   * by parameter
   *
   * @param incomingIntraUserNetworkServiceMessage the contains the values
   * @return DatabaseTableRecord whit the values
   */
  private DatabaseTableRecord constructFrom(
      WalletStoreNetworkServiceMessage incomingIntraUserNetworkServiceMessage) {

    /*
     * Create the record to the entity
     */
    DatabaseTableRecord entityRecord = getDatabaseTable().getEmptyRecord();

    /*
     * Set the entity values
     */
    entityRecord.setLongValue(
        WalletStoreNetworkServiceDatabaseConstants.INCOMING_MESSAGES_TABLE_ID_COLUMN_NAME,
        incomingIntraUserNetworkServiceMessage.getId());
    entityRecord.setStringValue(
        WalletStoreNetworkServiceDatabaseConstants.INCOMING_MESSAGES_TABLE_SENDER_ID_COLUMN_NAME,
        incomingIntraUserNetworkServiceMessage.getSender().toString());
    entityRecord.setStringValue(
        WalletStoreNetworkServiceDatabaseConstants.INCOMING_MESSAGES_TABLE_RECEIVER_ID_COLUMN_NAME,
        incomingIntraUserNetworkServiceMessage.getReceiver().toString());
    entityRecord.setStringValue(
        WalletStoreNetworkServiceDatabaseConstants.INCOMING_MESSAGES_TABLE_TEXT_CONTENT_COLUMN_NAME,
        incomingIntraUserNetworkServiceMessage.getTextContent());
    entityRecord.setStringValue(
        WalletStoreNetworkServiceDatabaseConstants.INCOMING_MESSAGES_TABLE_TYPE_COLUMN_NAME,
        incomingIntraUserNetworkServiceMessage.getMessageType().getCode());
    entityRecord.setLongValue(
        WalletStoreNetworkServiceDatabaseConstants
            .INCOMING_MESSAGES_TABLE_SHIPPING_TIMESTAMP_COLUMN_NAME,
        incomingIntraUserNetworkServiceMessage.getShippingTimestamp().getTime());
    entityRecord.setLongValue(
        WalletStoreNetworkServiceDatabaseConstants
            .INCOMING_MESSAGES_TABLE_DELIVERY_TIMESTAMP_COLUMN_NAME,
        incomingIntraUserNetworkServiceMessage.getDeliveryTimestamp().getTime());
    entityRecord.setStringValue(
        WalletStoreNetworkServiceDatabaseConstants.INCOMING_MESSAGES_TABLE_STATUS_COLUMN_NAME,
        incomingIntraUserNetworkServiceMessage.getStatus().getCode());

    /*
     * return the new table record
     */
    return entityRecord;
  }
  // SAVE NEW EVENT
  public void saveNewEventTansaction(String eventType, String eventSource)
      throws CantSaveEventException {
    try {

      DatabaseTable table =
          this.database.getTable(
              CustomerBrokerCloseNegotiationTransactionDatabaseConstants
                  .CUSTOMER_BROKER_CLOSE_EVENT_TABLE_NAME);
      DatabaseTableRecord eventRecord = table.getEmptyRecord();
      UUID eventRecordID = UUID.randomUUID();
      long unixTime = System.currentTimeMillis();
      // Logger LOG = Logger.getGlobal();
      // LOG.info("Distribution DAO:\nUUID:" + eventRecordID + "\n" + unixTime);
      eventRecord.setUUIDValue(
          CustomerBrokerCloseNegotiationTransactionDatabaseConstants
              .CUSTOMER_BROKER_CLOSE_EVENT_ID_COLUMN_NAME,
          eventRecordID);
      eventRecord.setStringValue(
          CustomerBrokerCloseNegotiationTransactionDatabaseConstants
              .CUSTOMER_BROKER_CLOSE_EVENT_TYPE_COLUMN_NAME,
          eventType);
      eventRecord.setStringValue(
          CustomerBrokerCloseNegotiationTransactionDatabaseConstants
              .CUSTOMER_BROKER_CLOSE_EVENT_SOURCE_COLUMN_NAME,
          eventSource);
      eventRecord.setStringValue(
          CustomerBrokerCloseNegotiationTransactionDatabaseConstants
              .CUSTOMER_BROKER_CLOSE_EVENT_STATUS_COLUMN_NAME,
          EventStatus.PENDING.getCode());
      eventRecord.setLongValue(
          CustomerBrokerCloseNegotiationTransactionDatabaseConstants
              .CUSTOMER_BROKER_CLOSE_EVENT_TIMESTAMP_COLUMN_NAME,
          unixTime);
      table.insertRecord(eventRecord);

    } catch (CantInsertRecordException exception) {
      throw new CantSaveEventException(
          exception, "Saving new event.", "Cannot insert a record in Asset Distribution database");
    } catch (Exception exception) {
      throw new CantSaveEventException(
          FermatException.wrapException(exception), "Saving new event.", "Unexpected exception");
    }
  }
예제 #14
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");
    }
  }
  /**
   * Inserts into the database new statistics from the key maintainer
   *
   * @param hierarchyAccountId
   * @param date
   * @param currentGeneratedKeys
   * @param currentUsedKeys
   * @param currentThreshold
   * @throws CantExecuteDatabaseOperationException
   */
  private void insertNewMaintainerStatistics(
      int hierarchyAccountId,
      String date,
      int currentGeneratedKeys,
      int currentUsedKeys,
      int currentThreshold)
      throws CantExecuteDatabaseOperationException {
    DatabaseTable databaseTable =
        getDatabaseTable(
            AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_MONITOR_TABLE_NAME);

    DatabaseTableRecord databaseTableRecord = databaseTable.getEmptyRecord();
    databaseTableRecord.setIntegerValue(
        AssetsOverBitcoinCryptoVaultDatabaseConstants
            .KEY_MAINTENANCE_MONITOR_EXECUTION_NUMBER_COLUMN_NAME,
        1);
    databaseTableRecord.setIntegerValue(
        AssetsOverBitcoinCryptoVaultDatabaseConstants
            .KEY_MAINTENANCE_MONITOR_ACCOUNT_ID_COLUMN_NAME,
        hierarchyAccountId);
    databaseTableRecord.setStringValue(
        AssetsOverBitcoinCryptoVaultDatabaseConstants
            .KEY_MAINTENANCE_MONITOR_EXECUTION_DATE_COLUMN_NAME,
        date);
    databaseTableRecord.setIntegerValue(
        AssetsOverBitcoinCryptoVaultDatabaseConstants
            .KEY_MAINTENANCE_MONITOR_GENERATED_KEYS_COLUMN_NAME,
        currentGeneratedKeys);
    databaseTableRecord.setIntegerValue(
        AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_MONITOR_USED_KEYS_COLUMN_NAME,
        currentUsedKeys);
    databaseTableRecord.setIntegerValue(
        AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_MONITOR_THRESHOLD_COLUMN_NAME,
        currentThreshold);

    try {
      databaseTable.insertRecord(databaseTableRecord);
    } catch (CantInsertRecordException e) {
      /** I will create the output meessage */
      StringBuilder outputMessage =
          new StringBuilder("there was an error inserting a new record into ");
      outputMessage.append(
          AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_MONITOR_TABLE_NAME);
      outputMessage.append(System.lineSeparator());
      outputMessage.append("The record to insert is: ");
      outputMessage.append(XMLParser.parseObject(databaseTableRecord));

      throw new CantExecuteDatabaseOperationException(
          CantExecuteDatabaseOperationException.DEFAULT_MESSAGE,
          e,
          outputMessage.toString(),
          "Database issue");
    }
  }
예제 #16
0
  public void persistReceptionId(String genesisTransaction, UUID distributionId)
      throws CantPersistsTransactionUUIDException {
    try {
      this.database = openDatabase();
      DatabaseTable databaseTable =
          getDatabaseTable(AssetReceptionDatabaseConstants.ASSET_RECEPTION_TABLE_NAME);
      databaseTable.addStringFilter(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_GENESIS_TRANSACTION_COLUMN_NAME,
          genesisTransaction,
          DatabaseFilterType.EQUAL);
      databaseTable.loadToMemory();
      DatabaseTableRecord databaseTableRecord;
      List<DatabaseTableRecord> databaseTableRecords = databaseTable.getRecords();
      if (databaseTableRecords.size() > 1) {

        throw new UnexpectedResultReturnedFromDatabaseException(
            "Unexpected result. More than value returned.",
            "GenesisTransaction:" + genesisTransaction + " OutgoingId:" + distributionId);
      } else {
        databaseTableRecord = databaseTableRecords.get(0);
      }
      databaseTableRecord.setStringValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_RECEPTION_ID_COLUMN_NAME,
          distributionId.toString());
      databaseTableRecord.setStringValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_RECEPTION_STATUS_COLUMN_NAME,
          ReceptionStatus.RECEIVING.getCode());
      databaseTable.updateRecord(databaseTableRecord);

    } catch (CantExecuteDatabaseOperationException exception) {

      throw new CantPersistsTransactionUUIDException(
          exception, "Persisting distributionId in database", "Cannot open or find the database");
    } catch (Exception exception) {

      throw new CantPersistsTransactionUUIDException(
          FermatException.wrapException(exception),
          "Persisting distributionId in database",
          "Unexpected exception");
    }
  }
  /**
   * Marks to RECEPTION_NOTIFIED the protocol status of this Outgoing transaction if found.
   *
   * @param transactionID
   */
  private void confirmOutgoingTransactionReception(UUID transactionID)
      throws CantExecuteDatabaseOperationException {
    DatabaseTable databaseTable =
        database.getTable(BitcoinCryptoNetworkDatabaseConstants.OUTGOING_TRANSACTIONS_TABLE_NAME);
    databaseTable.setStringFilter(
        BitcoinCryptoNetworkDatabaseConstants.OUTGOING_TRANSACTIONS_TRX_ID_COLUMN_NAME,
        transactionID.toString(),
        DatabaseFilterType.EQUAL);

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

    /** set the value to RECEPTION_NOTIFIED and the Last_update_time to now */
    if (databaseTable.getRecords().size() > 0) {
      DatabaseTableRecord record = databaseTable.getRecords().get(0);
      record.setStringValue(
          BitcoinCryptoNetworkDatabaseConstants.OUTGOING_TRANSACTIONS_PROTOCOL_STATUS_COLUMN_NAME,
          ProtocolStatus.RECEPTION_NOTIFIED.getCode());
      record.setStringValue(
          BitcoinCryptoNetworkDatabaseConstants.OUTGOING_TRANSACTIONS_LAST_UPDATE_COLUMN_NAME,
          getCurrentDateTime());

      try {
        databaseTable.updateRecord(record);
      } catch (CantUpdateRecordException e) {
        StringBuilder errorOutput =
            new StringBuilder(
                "There was a problem setting to RECEPTION_NOTIFIED the following transaction:");
        errorOutput.append(System.lineSeparator());
        errorOutput.append(XMLParser.parseObject(record));
        throw new CantExecuteDatabaseOperationException(
            CantExecuteDatabaseOperationException.DEFAULT_MESSAGE,
            e,
            errorOutput.toString(),
            "database issue");
      }
    }
  }
예제 #18
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");
    }
  }
예제 #19
0
  public void createCashMoneyWallet(String walletPublicKey, FiatCurrency fiatCurrency)
      throws CantCreateCashMoneyWalletException {

    if (walletExists(walletPublicKey))
      throw new CantCreateCashMoneyWalletException(
          CantCreateCashMoneyWalletException.DEFAULT_MESSAGE,
          null,
          "Cant create Cash Money Wallet",
          "Cash Wallet already exists! publicKey:" + walletPublicKey);

    try {
      DatabaseTable table =
          this.database.getTable(CashMoneyWalletDatabaseConstants.WALLETS_TABLE_NAME);
      DatabaseTableRecord record = table.getEmptyRecord();

      record.setStringValue(
          CashMoneyWalletDatabaseConstants.WALLETS_WALLET_PUBLIC_KEY_COLUMN_NAME, walletPublicKey);
      record.setStringValue(
          CashMoneyWalletDatabaseConstants.WALLETS_AVAILABLE_BALANCE_COLUMN_NAME, "0");
      record.setStringValue(CashMoneyWalletDatabaseConstants.WALLETS_BOOK_BALANCE_COLUMN_NAME, "0");
      record.setStringValue(
          CashMoneyWalletDatabaseConstants.WALLETS_CURRENCY_COLUMN_NAME, fiatCurrency.getCode());
      record.setLongValue(
          CashMoneyWalletDatabaseConstants.WALLETS_TIMESTAMP_WALLET_CREATION_COLUMN_NAME,
          (new Date().getTime() / 1000));

      table.insertRecord(record);
    } catch (CantInsertRecordException e) {
      errorManager.reportUnexpectedPluginException(
          Plugins.BITDUBAI_CSH_WALLET_CASH_MONEY,
          UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN,
          e);
      throw new CantCreateCashMoneyWalletException(
          CantCreateCashMoneyWalletException.DEFAULT_MESSAGE,
          e,
          "Cant create Cash Money Wallet",
          "Cant insert record into database");
    }
  }
예제 #20
0
  /**
   * Construct a DatabaseTableRecord whit the values of the a FermatMessage pass by parameter
   *
   * @param incomingTemplateNetworkServiceMessage the contains the values
   * @return DatabaseTableRecord whit the values
   */
  private DatabaseTableRecord constructFrom(FermatMessage incomingTemplateNetworkServiceMessage) {

    /*
     * Create the record to the entity
     */
    DatabaseTableRecord entityRecord = getDatabaseTable().getEmptyRecord();

    /*
     * Set the entity values
     */
    entityRecord.setStringValue(
        CommunicationNetworkServiceDatabaseConstants.INCOMING_MESSAGES_ID_COLUMN_NAME,
        incomingTemplateNetworkServiceMessage.getId().toString());
    entityRecord.setStringValue(
        CommunicationNetworkServiceDatabaseConstants.INCOMING_MESSAGES_SENDER_ID_COLUMN_NAME,
        incomingTemplateNetworkServiceMessage.getSender().toString());
    entityRecord.setStringValue(
        CommunicationNetworkServiceDatabaseConstants.INCOMING_MESSAGES_RECEIVER_ID_COLUMN_NAME,
        incomingTemplateNetworkServiceMessage.getReceiver().toString());
    entityRecord.setStringValue(
        CommunicationNetworkServiceDatabaseConstants.INCOMING_MESSAGES_TEXT_CONTENT_COLUMN_NAME,
        incomingTemplateNetworkServiceMessage.getContent());
    entityRecord.setStringValue(
        CommunicationNetworkServiceDatabaseConstants.INCOMING_MESSAGES_TYPE_COLUMN_NAME,
        incomingTemplateNetworkServiceMessage.getFermatMessageContentType().getCode());

    if (incomingTemplateNetworkServiceMessage.getShippingTimestamp() != null) {
      entityRecord.setLongValue(
          CommunicationNetworkServiceDatabaseConstants
              .OUTGOING_MESSAGES_SHIPPING_TIMESTAMP_COLUMN_NAME,
          incomingTemplateNetworkServiceMessage.getShippingTimestamp().getTime());
    } else {
      entityRecord.setLongValue(
          CommunicationNetworkServiceDatabaseConstants
              .OUTGOING_MESSAGES_SHIPPING_TIMESTAMP_COLUMN_NAME,
          new Long(0));
    }

    if (incomingTemplateNetworkServiceMessage.getDeliveryTimestamp() != null) {
      entityRecord.setLongValue(
          CommunicationNetworkServiceDatabaseConstants
              .INCOMING_MESSAGES_SHIPPING_TIMESTAMP_COLUMN_NAME,
          incomingTemplateNetworkServiceMessage.getDeliveryTimestamp().getTime());
    } else {
      entityRecord.setLongValue(
          CommunicationNetworkServiceDatabaseConstants
              .INCOMING_MESSAGES_DELIVERY_TIMESTAMP_COLUMN_NAME,
          new Long(0));
    }

    entityRecord.setStringValue(
        CommunicationNetworkServiceDatabaseConstants.INCOMING_MESSAGES_STATUS_COLUMN_NAME,
        incomingTemplateNetworkServiceMessage.getFermatMessagesStatus().getCode());

    /*
     * return the new table record
     */
    return entityRecord;
  }
  private void constructRecordFromExchangeRate(
      DatabaseTableRecord newRecord, ExchangeRate exchangeRate) {

    newRecord.setUUIDValue(
        BitcoinVenezuelaProviderDatabaseConstants.DAILY_EXCHANGE_RATES_ID_COLUMN_NAME,
        UUID.randomUUID());
    newRecord.setStringValue(
        BitcoinVenezuelaProviderDatabaseConstants.DAILY_EXCHANGE_RATES_FROM_CURRENCY_COLUMN_NAME,
        exchangeRate.getFromCurrency().getCode());
    newRecord.setStringValue(
        BitcoinVenezuelaProviderDatabaseConstants.DAILY_EXCHANGE_RATES_TO_CURRENCY_COLUMN_NAME,
        exchangeRate.getToCurrency().getCode());
    newRecord.setStringValue(
        BitcoinVenezuelaProviderDatabaseConstants.DAILY_EXCHANGE_RATES_SALE_PRICE_COLUMN_NAME,
        String.valueOf(exchangeRate.getSalePrice()));
    newRecord.setStringValue(
        BitcoinVenezuelaProviderDatabaseConstants.DAILY_EXCHANGE_RATES_PURCHASE_PRICE_COLUMN_NAME,
        String.valueOf(exchangeRate.getPurchasePrice()));
    newRecord.setLongValue(
        BitcoinVenezuelaProviderDatabaseConstants.DAILY_EXCHANGE_RATES_TIMESTAMP_COLUMN_NAME,
        exchangeRate.getTimestamp());
  }
  /**
   * Updates existing key maintainer statistics.
   *
   * @param date
   * @param currentGeneratedKeys
   * @param currentUsedKeys
   * @param currentThreshold
   * @throws CantExecuteDatabaseOperationException
   */
  private void updateExistingMaintainerStatistics(
      DatabaseTableRecord recordToUpdate,
      String date,
      int currentGeneratedKeys,
      int currentUsedKeys,
      int currentThreshold)
      throws CantExecuteDatabaseOperationException {
    int previousExecNumber =
        recordToUpdate.getIntegerValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants
                .KEY_MAINTENANCE_MONITOR_EXECUTION_NUMBER_COLUMN_NAME);
    recordToUpdate.setIntegerValue(
        AssetsOverBitcoinCryptoVaultDatabaseConstants
            .KEY_MAINTENANCE_MONITOR_EXECUTION_NUMBER_COLUMN_NAME,
        previousExecNumber + 1);
    recordToUpdate.setStringValue(
        AssetsOverBitcoinCryptoVaultDatabaseConstants
            .KEY_MAINTENANCE_MONITOR_EXECUTION_DATE_COLUMN_NAME,
        date);
    recordToUpdate.setIntegerValue(
        AssetsOverBitcoinCryptoVaultDatabaseConstants
            .KEY_MAINTENANCE_MONITOR_GENERATED_KEYS_COLUMN_NAME,
        currentGeneratedKeys);
    recordToUpdate.setIntegerValue(
        AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_MONITOR_USED_KEYS_COLUMN_NAME,
        currentUsedKeys);
    recordToUpdate.setIntegerValue(
        AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_MONITOR_THRESHOLD_COLUMN_NAME,
        currentThreshold);

    try {
      getDatabaseTable(
              AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_MONITOR_TABLE_NAME)
          .updateRecord(recordToUpdate);
    } catch (CantUpdateRecordException e) {
      /** I will create the output meessage */
      StringBuilder outputMessage =
          new StringBuilder("there was an error updating an existing record from ");
      outputMessage.append(
          AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_MONITOR_TABLE_NAME);
      outputMessage.append(System.lineSeparator());
      outputMessage.append("The record to insert is: ");
      outputMessage.append(XMLParser.parseObject(recordToUpdate));

      throw new CantExecuteDatabaseOperationException(
          CantExecuteDatabaseOperationException.DEFAULT_MESSAGE,
          e,
          outputMessage.toString(),
          "Database issue");
    }
  }
  /**
   * Construct a DatabaseTableRecord whit the values of the a imageImpl pass by parameter
   *
   * @param imageImpl the contains the values
   * @return DatabaseTableRecord whit the values
   */
  private DatabaseTableRecord constructFrom(ImageMiddlewareImpl imageImpl) {

    /*
     * Create the record to the entity
     */
    DatabaseTableRecord entityRecord = getDatabaseTable().getEmptyRecord();

    /*
     * Set the entity values
     */
    entityRecord.setStringValue(
        WalletPublisherMiddlewareDatabaseConstants.SCREENS_SHOTS_COMPONENTS_FILE_ID_COLUMN_NAME,
        imageImpl.getFileId().toString());
    entityRecord.setStringValue(
        WalletPublisherMiddlewareDatabaseConstants
            .SCREENS_SHOTS_COMPONENTS_COMPONENT_ID_COLUMN_NAME,
        imageImpl.getComponentId().toString());

    /*
     * return the new table record
     */
    return entityRecord;
  }
예제 #24
0
  /**
   * (non-javadoc)
   *
   * @see AbstractBaseDao#getDatabaseTableRecordFromEntity
   */
  @Override
  protected DatabaseTableRecord getDatabaseTableRecordFromEntity(NodeConnectionHistory entity) {

    DatabaseTableRecord databaseTableRecord = getDatabaseTable().getEmptyRecord();

    databaseTableRecord.setUUIDValue(
        CommunicationsNetworkNodeP2PDatabaseConstants.NODES_CONNECTIONS_HISTORY_UUID_COLUMN_NAME,
        entity.getUuid());
    databaseTableRecord.setLongValue(
        CommunicationsNetworkNodeP2PDatabaseConstants
            .NODES_CONNECTIONS_HISTORY_CONNECTION_TIMESTAMP_COLUMN_NAME,
        entity.getConnectionTimestamp().getTime());
    databaseTableRecord.setIntegerValue(
        CommunicationsNetworkNodeP2PDatabaseConstants
            .NODES_CONNECTIONS_HISTORY_DEFAULT_PORT_COLUMN_NAME,
        entity.getDefaultPort());
    databaseTableRecord.setStringValue(
        CommunicationsNetworkNodeP2PDatabaseConstants
            .NODES_CONNECTIONS_HISTORY_IDENTITY_PUBLIC_KEY_COLUMN_NAME,
        entity.getIdentityPublicKey());
    databaseTableRecord.setStringValue(
        CommunicationsNetworkNodeP2PDatabaseConstants.NODES_CONNECTIONS_HISTORY_IP_COLUMN_NAME,
        entity.getIp());
    databaseTableRecord.setDoubleValue(
        CommunicationsNetworkNodeP2PDatabaseConstants
            .NODES_CONNECTIONS_HISTORY_LAST_LATITUDE_COLUMN_NAME,
        entity.getLastLatitude());
    databaseTableRecord.setDoubleValue(
        CommunicationsNetworkNodeP2PDatabaseConstants
            .NODES_CONNECTIONS_HISTORY_LAST_LONGITUDE_COLUMN_NAME,
        entity.getLastLongitude());
    databaseTableRecord.setStringValue(
        CommunicationsNetworkNodeP2PDatabaseConstants.NODES_CONNECTIONS_HISTORY_STATUS_COLUMN_NAME,
        entity.getStatus());

    return databaseTableRecord;
  }
  /**
   * Inserts a new HierarchyAccount into the database
   *
   * @param hierarchyAccount
   * @throws CantExecuteDatabaseOperationException
   * @throws CantInsertRecordException
   */
  public void addNewHierarchyAccount(HierarchyAccount hierarchyAccount)
      throws CantExecuteDatabaseOperationException {
    DatabaseTable databaseTable =
        getDatabaseTable(AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_ACCOUNTS_TABLE_NAME);
    DatabaseTableRecord record = databaseTable.getEmptyRecord();

    record.setIntegerValue(
        AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_ACCOUNTS_ID_COLUMN_NAME,
        hierarchyAccount.getId());
    record.setStringValue(
        AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_ACCOUNTS_DESCRIPTION_COLUMN_NAME,
        hierarchyAccount.getDescription());
    record.setStringValue(
        AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_ACCOUNTS_TYPE_COLUMN_NAME,
        hierarchyAccount.getHierarchyAccountType().getCode());

    try {
      databaseTable.insertRecord(record);
    } catch (CantInsertRecordException e) {
      /**
       * if there was an error inserting the object, I will prepare the error message and throw it.
       */
      StringBuilder outputMessage =
          new StringBuilder("There was an error inserting a new HierarchyAccount value.");
      outputMessage.append(System.lineSeparator());
      outputMessage.append("HierarchyAccount value:");
      outputMessage.append(System.lineSeparator());
      outputMessage.append(XMLParser.parseObject(hierarchyAccount));

      throw new CantExecuteDatabaseOperationException(
          CantExecuteDatabaseOperationException.DEFAULT_MESSAGE,
          e,
          outputMessage.toString(),
          "A database error.");
    }
  }
  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());
    }
  }
  /**
   * 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);
    }
  }
예제 #28
0
  public void changeProtocolState(
      final UUID requestId, final ActorAssetProtocolState actorAssetProtocolState)
      throws CantUpdateRecordDataBaseException, CantUpdateRecordException,
          CantGetActorAssetNotificationException {

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

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

    try {

      DatabaseTable cryptoPaymentRequestTable = getDatabaseTable();

      cryptoPaymentRequestTable.addUUIDFilter(
          AssetUserNetworkServiceDatabaseConstants.INCOMING_NOTIFICATION_ID_COLUMN_NAME,
          requestId,
          DatabaseFilterType.EQUAL);

      cryptoPaymentRequestTable.loadToMemory();

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

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

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

        cryptoPaymentRequestTable.updateRecord(record);
      } else {
        throw new CantGetActorAssetNotificationException(
            "RequestId: " + requestId, "Cannot find a CryptoPaymentRequest 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);
    }
  }
  // UPDATE STATUS NEW NEGOTIATION TRANSACTION
  public void updateStatusRegisterCustomerBrokerCloseNegotiationTranasction(
      UUID transactionId, NegotiationTransactionStatus statusTransaction)
      throws CantRegisterCustomerBrokerCloseNegotiationTransactionException {
    try {
      if (!transactionExists(transactionId))
        throw new CantRegisterCustomerBrokerCloseNegotiationTransactionException(
            "Cant Update Status customer broker close Negotiation Transaction, not exists.",
            "customer broker close Negotiation Transaction, Update State",
            "Cant Update State customer broker close Negotiation Transaction, not exists");

      DatabaseTable table =
          this.database.getTable(
              CustomerBrokerCloseNegotiationTransactionDatabaseConstants
                  .CUSTOMER_BROKER_CLOSE_TABLE_NAME);
      table.addUUIDFilter(
          CustomerBrokerCloseNegotiationTransactionDatabaseConstants
              .CUSTOMER_BROKER_CLOSE_TRANSACTION_ID_COLUMN_NAME,
          transactionId,
          DatabaseFilterType.EQUAL);
      DatabaseTableRecord record = table.getEmptyRecord();
      record.setStringValue(
          CustomerBrokerCloseNegotiationTransactionDatabaseConstants
              .CUSTOMER_BROKER_CLOSE_STATUS_COLUMN_NAME,
          statusTransaction.getCode());
      table.updateRecord(record);

      System.out.print(
          "\n\n**** 8) MOCK NEGOTIATION TRANSACTION - CUSTOMER BROKER CLOSE - DAO - UPDATE STATUS NEGOTIATION STATUS : "
              + NegotiationTransactionStatus.SENDING_NEGOTIATION.getCode()
              + " ****\n");
    } catch (CantUpdateRecordException e) {
      throw new CantRegisterCustomerBrokerCloseNegotiationTransactionException(
          e.getMessage(),
          e,
          "customer broker close Negotiation Transaction, Update State",
          "Cant Update State customer broker close Negotiation Transaction, update database problems.");
    } catch (Exception e) {
      throw new CantRegisterCustomerBrokerCloseNegotiationTransactionException(
          e.getMessage(),
          FermatException.wrapException(e),
          "customer broker close Negotiation Transaction, Update State",
          "Cant Update State customer broker close Negotiation Transaction, unknown failure.");
    }
  }
예제 #30
0
  public void updateDigitalAssetCryptoStatusByGenesisTransaction(
      String genesisTransaction, CryptoStatus cryptoStatus)
      throws CantCheckAssetReceptionProgressException,
          UnexpectedResultReturnedFromDatabaseException {
    try {
      this.database = openDatabase();
      DatabaseTable databaseTable;
      databaseTable = database.getTable(AssetReceptionDatabaseConstants.ASSET_RECEPTION_TABLE_NAME);
      databaseTable.addStringFilter(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_GENESIS_TRANSACTION_COLUMN_NAME,
          genesisTransaction,
          DatabaseFilterType.EQUAL);
      databaseTable.loadToMemory();
      List<DatabaseTableRecord> databaseTableRecords = databaseTable.getRecords();
      DatabaseTableRecord databaseTableRecord;
      if (databaseTableRecords.size() > 1) {

        throw new UnexpectedResultReturnedFromDatabaseException(
            "Unexpected result. More than value returned.",
            "Genesis Transaction:" + genesisTransaction);
      } else {
        databaseTableRecord = databaseTableRecords.get(0);
      }
      databaseTableRecord.setStringValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_CRYPTO_STATUS_COLUMN_NAME,
          cryptoStatus.getCode());
      databaseTable.updateRecord(databaseTableRecord);

    } catch (CantExecuteDatabaseOperationException exception) {

      throw new CantCheckAssetReceptionProgressException(
          exception, "Updating Crypto Status.", "Cannot open or find the Asset Issuing database");
    } catch (CantLoadTableToMemoryException exception) {

      throw new CantCheckAssetReceptionProgressException(
          exception, "Updating Crypto Status ", "Cannot load the table into memory");
    } catch (Exception exception) {

      throw new CantCheckAssetReceptionProgressException(
          FermatException.wrapException(exception),
          "Updating Crypto Status.",
          "Unexpected exception - Transaction hash:" + genesisTransaction);
    }
  }