/**
   * FermatEventHandler interface implementation
   *
   * <p>Plugin is started? The event is the expected event?
   */
  @Override
  public void handleEvent(FermatEvent fermatEvent) throws FermatException {

    if (this.cryptoBrokerActorConnectionPluginRoot.getStatus() == ServiceStatus.STARTED) {

      if (fermatEvent instanceof CryptoBrokerConnectionRequestUpdatesEvent) {

        actorConnectionEventActions.handleCryptoBrokerUpdateEvent();

      } else {
        EventType eventExpected = EventType.CRYPTO_BROKER_CONNECTION_REQUEST_UPDATES;
        String context =
            "Event received: "
                + fermatEvent.getEventType().toString()
                + " - "
                + fermatEvent.getEventType().getCode()
                + "\n"
                + "Event expected: "
                + eventExpected.toString()
                + " - "
                + eventExpected.getCode();
        throw new UnexpectedEventException(context);
      }
    } else {
      throw new CryptoBrokerActorConnectionNotStartedException("Plugin is not started.", "");
    }
  }
  @Override
  public void handleEvent(FermatEvent fermatEvent) throws FermatException {
    String context =
        "Event Type: " + fermatEvent.getEventType() + "Event Source: " + fermatEvent.getSource();

    if (assetDistributionRecorderService.getStatus() != ServiceStatus.STARTED) {
      throw new TransactionServiceNotStartedException();
    }

    if (!(fermatEvent instanceof ReceivedNewTransactionStatusNotificationEvent)) {
      // You're using the wrong handler..
      throw new CantSaveEventException(
          null,
          context,
          "The event received event is not an instance of ReceivedNewTransactionStatusNotificationEvent, use the right handler.");
    }

    ReceivedNewTransactionStatusNotificationEvent metadataNotificationEvent =
        (ReceivedNewTransactionStatusNotificationEvent) fermatEvent;

    try {
      assetDistributionRecorderService.receivedTransactionStatusNotificationrEvent(
          metadataNotificationEvent);
    } catch (Exception exception) {
      throw new CantSaveEventException(
          exception,
          "Handling the ReceivedNewTransactionStatusNotificationEvent",
          "Unexpected exception");
    }
  }
 private void testRaiseEvent() {
   printSomething("Start event test");
   FermatEvent eventToRaise =
       eventManager.getNewEvent(EventType.RECEIVED_NEW_DIGITAL_ASSET_METADATA_NOTIFICATION);
   eventToRaise.setSource(EventSource.NETWORK_SERVICE_ASSET_TRANSMISSION);
   eventManager.raiseEvent(eventToRaise);
   printSomething("End event test");
 }
 private void testRaiseEvent() {
   printSomething("Start event test");
   FermatEvent eventToRaise =
       eventManager.getNewEvent(
           EventType.INCOMING_ASSET_ON_CRYPTO_NETWORK_WAITING_TRANSFERENCE_ASSET_ISSUER);
   eventToRaise.setSource(EventSource.CRYPTO_ROUTER);
   eventManager.raiseEvent(eventToRaise);
   printSomething("End event test");
 }
  /** Notify when cloud client is disconnected */
  public void raiseClientConnectionLooseNotificationEvent() {

    System.out.println(
        "WsCommunicationsTyrusCloudClientChannel - raiseClientConnectionLooseNotificationEvent");
    FermatEvent platformEvent = eventManager.getNewEvent(P2pEventType.CLIENT_CONNECTION_LOOSE);
    platformEvent.setSource(EventSource.WS_COMMUNICATION_CLOUD_CLIENT_PLUGIN);
    eventManager.raiseEvent(platformEvent);
    System.out.println(
        "WsCommunicationsTyrusCloudClientChannel - Raised Event = P2pEventType.CLIENT_CONNECTION_LOOSE");
  }
  /**
   * (no-javadoc)
   *
   * @see FermatPacketProcessor#processingPackage(FermatPacket)
   */
  @Override
  public void processingPackage(FermatPacket receiveFermatPacket) {

    /*
     * Get the filters from the message content and decrypt
     */
    String messageContentJsonStringRepresentation =
        AsymmetricCryptography.decryptMessagePrivateKey(
            receiveFermatPacket.getMessageContent(),
            getWsCommunicationsCloudClientChannel().getClientIdentity().getPrivateKey());

    // System.out.println("FailureComponentRegistrationRequestPacketProcessor -
    // messageContentJsonStringRepresentation = "+messageContentJsonStringRepresentation);

    /*
     * Construct the json object
     */
    JsonObject packetContent =
        jsonParser.parse(messageContentJsonStringRepresentation).getAsJsonObject();
    NetworkServiceType networkServiceApplicant =
        gson.fromJson(
            packetContent.get(JsonAttNamesConstants.NETWORK_SERVICE_TYPE).getAsString(),
            NetworkServiceType.class);
    PlatformComponentProfile platformComponentProfile =
        new PlatformComponentProfileCommunication()
            .fromJson(packetContent.get(JsonAttNamesConstants.PROFILE_TO_REGISTER).getAsString());
    String errorMsj = packetContent.get(JsonAttNamesConstants.FAILURE_VPN_MSJ).getAsString();

    System.out.println("FailureComponentRegistrationRequestPacketProcessor - errorMsj " + errorMsj);

    /*
     * Create a new event whit the networkServiceType and remoteIdentity
     */
    FermatEvent event =
        P2pEventType.FAILURE_COMPONENT_REGISTRATION_REQUEST_NOTIFICATION.getNewEvent();
    event.setSource(EventSource.WS_COMMUNICATION_CLOUD_CLIENT_PLUGIN);

    /*
     * Configure the values
     */
    ((FailureComponentRegistrationNotificationEvent) event)
        .setNetworkServiceApplicant(networkServiceApplicant);
    ((FailureComponentRegistrationNotificationEvent) event)
        .setPlatformComponentProfile(platformComponentProfile);
    ((FailureComponentRegistrationNotificationEvent) event).setErrorMsj(errorMsj);

    /*
     * Raise the event
     */
    // System.out.println("FailureComponentRegistrationRequestPacketProcessor - Raised a event =
    // P2pEventType.FAILURE_COMPONENT_REGISTRATION_REQUEST_NOTIFICATION");
    getWsCommunicationsCloudClientChannel().getEventManager().raiseEvent(event);
  }
  @Override
  public void handleEvent(FermatEvent fermatEvent) throws FermatException {

    // TODO USABA LA WALLETID DE LA REQUESTED CREADA PARA CARGAR LAS BILLETERAS DEL USUARIO?
    UUID walletId = ((WalletCreatedEvent) fermatEvent).getWalletId();
    EventSource eventSource = fermatEvent.getSource();
    if (eventSource == EventSource.MIDDLEWARE_WALLET_PLUGIN) {

      if (((Service) this.walletManager).getStatus() == ServiceStatus.STARTED) {

        try {
          // TODO USABA LA WALLETID DE LA REQUESTED CREADA PARA CARGAR LAS BILLETERAS DEL USUARIO?
          this.walletManager.loadUserWallets("");
        } catch (CantLoadWalletsException cantLoadWalletsException) {
          /** The main module could not handle this exception. Me neither. Will throw it again. */
          System.err.println(
              "CantCreateCryptoWalletException: " + cantLoadWalletsException.getMessage());
          cantLoadWalletsException.printStackTrace();

          throw cantLoadWalletsException;
        }
      } else {
        throw new ModuleNotRunningException();
      }
    }
  }
  /**
   * (non-Javadoc)
   *
   * @see FermatEventHandler#handleEvent(FermatEvent)
   * @param platformEvent
   * @throws Exception
   */
  @Override
  public void handleEvent(FermatEvent platformEvent) throws FermatException {

    if (platformEvent.getSource() == AssetTransmissionNetworkServicePluginRoot.EVENT_SOURCE) {

      System.out.println(
          "CompleteComponentConnectionRequestNotificationEventHandler - handleEvent platformEvent ="
              + platformEvent.toString());
      System.out.print("NOTIFICACION EVENTO MENSAJE RECIVIDO!!!!");

      /*
       * Get the message receive
       */
      NewNetworkServiceMessageReceivedNotificationEvent
          newNetworkServiceMessageReceivedNotificationEvent =
              (NewNetworkServiceMessageReceivedNotificationEvent) platformEvent;
      FermatMessage fermatMessageReceive =
          (FermatMessage) newNetworkServiceMessageReceivedNotificationEvent.getData();

      /*
       * Get the content of the message like a JsonObject
       */
      JsonObject jsonMsjContent = parser.parse(fermatMessageReceive.getContent()).getAsJsonObject();

      /*
       * Extract the type of content of the message
       */
      DigitalAssetMetadataTransactionType digitalAssetMetadataTransactionType =
          gson.fromJson(
              jsonMsjContent.get(AssetTransmissionJsonAttNames.MSJ_CONTENT_TYPE),
              DigitalAssetMetadataTransactionType.class);

      /*
       * Process the messages for his type
       */
      if (messagesProcessorsRegistered.containsKey(digitalAssetMetadataTransactionType)) {
        messagesProcessorsRegistered
            .get(digitalAssetMetadataTransactionType)
            .processingMessage(fermatMessageReceive, jsonMsjContent);
      } else {
        System.out.println(
            "CompleteComponentConnectionRequestNotificationEventHandler - message type no supported = "
                + digitalAssetMetadataTransactionType);
      }
    }
  }
  /**
   * Notify the client when a incoming message is receive by the
   * incomingTemplateNetworkServiceMessage ant fire a new event
   *
   * @param incomingMessage received
   */
  private void onMessageReceived(FermatMessage incomingMessage) {

    System.out.println("CommunicationNetworkServiceLocal - onMessageReceived ");
    System.out.println(incomingMessage.getContent());

    /*
     * set the last message received
     */
    this.lastMessageReceived = incomingMessage;

    /** Put the message on a event and fire new event */
    FermatEvent fermatEvent =
        eventManager.getNewEvent(P2pEventType.NEW_NETWORK_SERVICE_MESSAGE_RECEIVE_NOTIFICATION);
    fermatEvent.setSource(AssetTransmissionNetworkServicePluginRoot.EVENT_SOURCE);
    ((NewNetworkServiceMessageReceivedNotificationEvent) fermatEvent).setData(incomingMessage);
    ((NewNetworkServiceMessageReceivedNotificationEvent) fermatEvent)
        .setNetworkServiceTypeApplicant(networkServiceTypePluginRoot);
    eventManager.raiseEvent(fermatEvent);
  }
  /** FermatEventHandler interface implementation */
  @Override
  public void handleEvent(FermatEvent fermatEvent) throws FermatException {
    if (!eventRecorderService.getStatus().equals(ServiceStatus.STARTED))
      throw new TransactionServiceNotStartedException(
          TransactionServiceNotStartedException.DEFAULT_MESSAGE,
          null,
          null,
          "Events can't be handled if the service is not started");

    if (fermatEvent instanceof IncomingCryptoOnCryptoNetworkWaitingTransferenceExtraUserEvent)
      eventRecorderService.saveEvent(fermatEvent);
    else
      throw new CantSaveEventException(
          CantSaveEventException.DEFAULT_MESSAGE,
          null,
          "Event: " + fermatEvent.getEventType().toString(),
          "This should have been IncomingCryptoOnCryptoNetworkWaitingTransferenceExtraUserEvent");
  }
  /**
   * (non-Javadoc)
   *
   * @see FermatEventHandler#handleEvent(FermatEvent)
   * @param platformEvent
   * @throws Exception
   */
  @Override
  public void handleEvent(FermatEvent platformEvent) throws FermatException {

    System.out.println(
        "CompleteComponentConnectionRequestNotificationEventHandler - handleEvent platformEvent ="
            + platformEvent.toString());

    // System.out.print("NOTIFICACION EVENTO LLEGADA MENSAJE!!!!");

    //        if (this.cryptoTransmissionAgent.isRunning()) {
    //
    //            NewNetworkServiceMessageReceivedNotificationEvent
    // newNetworkServiceMessageSentNotificationEvent =
    // (NewNetworkServiceMessageReceivedNotificationEvent) platformEvent;
    //
    //
    // cryptoTransmissionAgent.handleNewMessages((FermatMessage)newNetworkServiceMessageSentNotificationEvent.getData());
    //
    //
    //        }
  }
  /**
   * This method read for new messages pending to send on the data base in the table <code>
   * outbox_messages</code> and encrypt the message content, sing the message and send it
   */
  public void processMessageToSend() {

    try {

      try {

        Map<String, Object> filters = new HashMap<>();
        filters.put(
            CommunicationNetworkServiceDatabaseConstants.OUTGOING_MESSAGES_STATUS_COLUMN_NAME,
            MessagesStatus.PENDING_TO_SEND.getCode());
        filters.put(
            CommunicationNetworkServiceDatabaseConstants.OUTGOING_MESSAGES_RECEIVER_ID_COLUMN_NAME,
            communicationsVPNConnection.getRemoteParticipant().getIdentityPublicKey());

        /*
         * Read all pending message from database
         */
        List<FermatMessage> messages = outgoingMessageDao.findAll(filters);
        /*
         * For each message
         */
        for (FermatMessage message : messages) {

          if (communicationsVPNConnection.isActive()
              && (message.getFermatMessagesStatus() != FermatMessagesStatus.SENT)) {

            /*
             * Encrypt the content of the message whit the remote network service public key
             */
            ((FermatMessageCommunication) message)
                .setContent(
                    AsymmetricCryptography.encryptMessagePublicKey(
                        message.getContent(),
                        communicationsVPNConnection
                            .getRemoteParticipantNetworkService()
                            .getIdentityPublicKey()));

            /*
             * Sing the message
             */
            String signature =
                AsymmetricCryptography.createMessageSignature(
                    message.getContent(), eccKeyPair.getPrivateKey());
            ((FermatMessageCommunication) message).setSignature(signature);

            /*
             * Send the message
             */
            communicationsVPNConnection.sendMessage(message);

            /*
             * Change the message and update in the data base
             */

            ((FermatMessageCommunication) message)
                .setFermatMessagesStatus(FermatMessagesStatus.SENT);
            outgoingMessageDao.update(message);

            /*
             * Put the message on a event and fire new event
             */
            FermatEvent fermatEvent =
                eventManager.getNewEvent(
                    P2pEventType.NEW_NETWORK_SERVICE_MESSAGE_SENT_NOTIFICATION);
            fermatEvent.setSource(AssetIssuerActorNetworkServicePluginRoot.EVENT_SOURCE);
            ((NewNetworkServiceMessageSentNotificationEvent) fermatEvent).setData(message);
            eventManager.raiseEvent(fermatEvent);
          }
        }

      } catch (CantUpdateRecordDataBaseException e) {
        errorManager.reportUnexpectedPluginException(
            Plugins.BITDUBAI_DAP_ASSET_ISSUER_ACTOR_NETWORK_SERVICE,
            UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN,
            new Exception("Can not process messages to send. Error reason: " + e.getMessage()));
      } catch (CantReadRecordDataBaseException e) {
        errorManager.reportUnexpectedPluginException(
            Plugins.BITDUBAI_DAP_ASSET_ISSUER_ACTOR_NETWORK_SERVICE,
            UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN,
            new Exception("Can not process messages to send. Error reason: " + e.getMessage()));
      }

      // Sleep for a time
      toSend.sleep(CommunicationNetworkServiceRemoteAgent.SLEEP_TIME);

    } catch (InterruptedException e) {
      errorManager.reportUnexpectedPluginException(
          Plugins.BITDUBAI_DAP_ASSET_ISSUER_ACTOR_NETWORK_SERVICE,
          UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN,
          new Exception("Can not sleep"));
    }
  }
Beispiel #13
0
 private void raiseEvent(EventType eventType) {
   FermatEvent eventToRaise = eventManager.getNewEvent(eventType);
   eventToRaise.setSource(this.eventSource);
   eventManager.raiseEvent(eventToRaise);
 }
  /**
   * (non-javadoc)
   *
   * @see FermatMessageProcessor#processingMessage(FermatMessage, JsonObject)
   */
  @Override
  public void processingMessage(FermatMessage fermatMessage, JsonObject jsonMsjContent) {

    try {

      /*
       * Get the XML representation of the Digital Asset Metadata
       */
      String digitalAssetMetadataXml =
          jsonMsjContent.get(AssetTransmissionJsonAttNames.DIGITAL_ASSET_METADATA).getAsString();
      PlatformComponentType senderType =
          gson.fromJson(
              jsonMsjContent.get(AssetTransmissionJsonAttNames.SENDER_TYPE).getAsString(),
              PlatformComponentType.class);
      PlatformComponentType receiverType =
          gson.fromJson(
              jsonMsjContent.get(AssetTransmissionJsonAttNames.RECEIVER_TYPE).getAsString(),
              PlatformComponentType.class);

      /*
       * Convert the xml to object
       */
      DigitalAssetMetadata digitalAssetMetadata =
          (DigitalAssetMetadata)
              XMLParser.parseXML(digitalAssetMetadataXml, new DigitalAssetMetadata());

      /*
       * Construct a new digitalAssetMetadataTransaction
       */
      DigitalAssetMetadataTransactionImpl digitalAssetMetadataTransaction =
          new DigitalAssetMetadataTransactionImpl();
      digitalAssetMetadataTransaction.setGenesisTransaction(
          digitalAssetMetadata.getGenesisTransaction());
      digitalAssetMetadataTransaction.setSenderId(fermatMessage.getSender());
      digitalAssetMetadataTransaction.setSenderType(senderType);
      digitalAssetMetadataTransaction.setReceiverId(fermatMessage.getReceiver());
      digitalAssetMetadataTransaction.setReceiverType(receiverType);
      digitalAssetMetadataTransaction.setDigitalAssetMetadata(digitalAssetMetadata);
      digitalAssetMetadataTransaction.setDistributionStatus(DistributionStatus.ASSET_DISTRIBUTED);
      digitalAssetMetadataTransaction.setType(
          DigitalAssetMetadataTransactionType.META_DATA_TRANSMIT);
      digitalAssetMetadataTransaction.setProcessed(
          DigitalAssetMetadataTransactionImpl.NO_PROCESSED);

      /*
       * Save into data base for audit control
       */
      getAssetTransmissionNetworkServicePluginRoot()
          .getDigitalAssetMetaDataTransactionDao()
          .create(digitalAssetMetadataTransaction);

      /*
       * Mark the message as read
       */
      ((FermatMessageCommunication) fermatMessage)
          .setFermatMessagesStatus(FermatMessagesStatus.READ);
      ((CommunicationNetworkServiceConnectionManager)
              getAssetTransmissionNetworkServicePluginRoot().getNetworkServiceConnectionManager())
          .getIncomingMessageDao()
          .update(fermatMessage);

      /*
       * Notify to the interested
       */
      FermatEvent event =
          getAssetTransmissionNetworkServicePluginRoot()
              .getEventManager()
              .getNewEvent(EventType.RECEIVED_NEW_DIGITAL_ASSET_METADATA_NOTIFICATION);
      event.setSource(AssetTransmissionNetworkServicePluginRoot.EVENT_SOURCE);
      getAssetTransmissionNetworkServicePluginRoot().getEventManager().raiseEvent(event);

    } catch (Exception e) {
      getAssetTransmissionNetworkServicePluginRoot()
          .getErrorManager()
          .reportUnexpectedPluginException(
              Plugins.BITDUBAI_DAP_ASSET_TRANSMISSION_NETWORK_SERVICE,
              UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN,
              e);
    }
  }