/** * 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 processMetadata() { try { listRecorMessageToSend = outgoingMessageDao.findAll( CommunicationNetworkServiceDatabaseConstants.OUTGOING_MESSAGES_STATUS_COLUMN_NAME, FermatMessagesStatus.PENDING_TO_SEND.getCode()); if (listRecorMessageToSend != null && !listRecorMessageToSend.isEmpty()) { for (FermatMessage fm : listRecorMessageToSend) { if (!poolConnectionsWaitingForResponse.containsKey(fm.getReceiver())) { /* * Create the sender basic profile */ PlatformComponentProfile sender = wsCommunicationsCloudClientManager .getCommunicationsCloudClientConnection() .constructBasicPlatformComponentProfileFactory( fm.getSender(), NetworkServiceType.UNDEFINED, PlatformComponentType.ACTOR_ASSET_REDEEM_POINT); /* * Create the receiver basic profile */ PlatformComponentProfile receiver = wsCommunicationsCloudClientManager .getCommunicationsCloudClientConnection() .constructBasicPlatformComponentProfileFactory( fm.getReceiver(), NetworkServiceType.UNDEFINED, PlatformComponentType.ACTOR_ASSET_ISSUER); try { communicationNetworkServiceConnectionManager.connectTo( sender, platformComponentProfile, receiver); } catch (Exception e) { e.printStackTrace(); } // pass the metada to a pool wainting for the response of the other peer or server // failure poolConnectionsWaitingForResponse.put(fm.getReceiver(), fm); } } } } catch (CantReadRecordDataBaseException e) { errorManager.reportUnexpectedPluginException( Plugins.BITDUBAI_DAP_ASSET_ISSUER_ACTOR_NETWORK_SERVICE, UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN, new Exception("Can not send Message PENDING_TO_SEND")); } }
/** * Check fail send message * * @param destinationPublicKey */ private void checkFailedSendMessage(String destinationPublicKey) { try { /* * Read all pending message from database */ Map<String, Object> filters = new HashMap<>(); filters.put( CommunicationNetworkServiceDatabaseConstants.OUTGOING_MESSAGES_RECEIVER_ID_COLUMN_NAME, destinationPublicKey); filters.put( CommunicationNetworkServiceDatabaseConstants.OUTGOING_MESSAGES_STATUS_COLUMN_NAME, MessagesStatus.PENDING_TO_SEND.getCode()); List<FermatMessage> messages = getCommunicationNetworkServiceConnectionManager() .getOutgoingMessageDao() .findAll(filters); for (FermatMessage fermatMessage : messages) { /* * Increment the fail count field */ FermatMessageCommunication fermatMessageCommunication = (FermatMessageCommunication) fermatMessage; fermatMessageCommunication.setFailCount(fermatMessageCommunication.getFailCount() + 1); if (fermatMessageCommunication.getFailCount() > 10) { /* * Calculate the date */ long sentDate = fermatMessageCommunication.getShippingTimestamp().getTime(); long currentTime = System.currentTimeMillis(); long dif = currentTime - sentDate; double dias = Math.floor(dif / (1000 * 60 * 60 * 24)); /* * if have mora that 3 days */ if ((int) dias > 3) { getCommunicationNetworkServiceConnectionManager() .getOutgoingMessageDao() .delete(fermatMessage.getId()); } } else { getCommunicationNetworkServiceConnectionManager() .getOutgoingMessageDao() .update(fermatMessage); } } } catch (Exception e) { e.printStackTrace(); } }
public final void handleNewMessages(final FermatMessage fermatMessage) { try { final Gson gson = new Gson(); final String jsonMessage = fermatMessage.getContent(); final NetworkServiceMessage networkServiceMessage = gson.fromJson(jsonMessage, NetworkServiceMessage.class); switch (networkServiceMessage.getMessageType()) { case INFORMATION: // update the request to processing receive state with the given action. final InformationMessage informationMessage = gson.fromJson(jsonMessage, InformationMessage.class); receiveInformationMessage(informationMessage); System.out.println( " CPR NS - Information Message Received: " + informationMessage.toString()); break; case REQUEST: // create the request in processing receive state. final RequestMessage requestMessage = gson.fromJson(jsonMessage, RequestMessage.class); receiveCryptoPaymentRequest(requestMessage); System.out.println(" CPR NS - Request Message Received: " + requestMessage.toString()); break; } } catch (Exception e) { reportUnexpectedException(e); } }
/** * (non-Javadoc) * * @see FermatEventHandler#handleEvent(FermatEvent) * @param platformEvent * @throws Exception */ @Override public void handleEvent(FermatEvent platformEvent) throws FermatException { if (platformEvent.getSource() == NetworkServiceChatNetworkServicePluginRoot.EVENT_SOURCE) { // System.out.println("CompleteComponentConnectionRequestNotificationEventHandler - // handleEvent platformEvent =" + platformEvent.toString()); // System.out.println("NetworkServiceChatNetworkServicePluginRoot - NOTIFICACION EVENTO // MENSAJE RECIBIDO!!!!"); /* * 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 */ ChatMessageTransactionType chatMessageTransactionType = gson.fromJson( jsonMsjContent.get(ChatTransmissionJsonAttNames.MSJ_CONTENT_TYPE), ChatMessageTransactionType.class); /* * Process the messages for his type */ if (messagesProcessorsRegistered.containsKey(chatMessageTransactionType)) { messagesProcessorsRegistered .get(chatMessageTransactionType) .processingMessage(fermatMessageReceive, jsonMsjContent); } else { System.out.println( "NetworkServiceChatNetworkServicePluginRoot - CompleteComponentConnectionRequestNotificationEventHandler - message type no supported = " + chatMessageTransactionType); } } }
/** * Method that update an entity in the data base. * * @param entity FermatMessage to update. * @throws CantUpdateRecordDataBaseException */ public void update(FermatMessage entity) throws CantUpdateRecordDataBaseException { if (entity == null) { throw new IllegalArgumentException("The entity is required, can not be null"); } try { /* * 1- Create the record to the entity */ DatabaseTableRecord entityRecord = constructFrom(entity); /* * 2.- Create a new transaction and execute */ DatabaseTable outgoinMessageTable = getDatabaseTable(); DatabaseTransaction transaction = getDataBase().newTransaction(); // set filter outgoinMessageTable.addUUIDFilter( CommunicationNetworkServiceDatabaseConstants.OUTGOING_MESSAGES_ID_COLUMN_NAME, entity.getId(), DatabaseFilterType.EQUAL); transaction.addRecordToUpdate(outgoinMessageTable, entityRecord); getDataBase().executeTransaction(transaction); } catch (DatabaseTransactionFailedException databaseTransactionFailedException) { StringBuffer contextBuffer = new StringBuffer(); contextBuffer.append( "Database Name: " + CommunicationNetworkServiceDatabaseConstants.DATA_BASE_NAME); String context = contextBuffer.toString(); String possibleCause = "The record do not exist"; CantUpdateRecordDataBaseException cantUpdateRecordDataBaseException = new CantUpdateRecordDataBaseException( CantUpdateRecordDataBaseException.DEFAULT_MESSAGE, databaseTransactionFailedException, context, possibleCause); throw cantUpdateRecordDataBaseException; } }
/** * Method that create a new entity in the data base. * * @param entity FermatMessage to create. * @throws CantInsertRecordDataBaseException */ public void create(FermatMessage entity) throws CantInsertRecordDataBaseException { if (entity == null) { throw new IllegalArgumentException("The entity is required, can not be null"); } try { if (findById(String.valueOf(entity.getId())) == null) { /* * 1- Create the record to the entity */ DatabaseTableRecord entityRecord = constructFrom(entity); /** 2.- Create a new transaction and execute */ DatabaseTransaction transaction = getDataBase().newTransaction(); transaction.addRecordToInsert(getDatabaseTable(), entityRecord); getDataBase().executeTransaction(transaction); } } catch (DatabaseTransactionFailedException databaseTransactionFailedException) { // Register the failure. StringBuffer contextBuffer = new StringBuffer(); contextBuffer.append( "Database Name: " + CommunicationNetworkServiceDatabaseConstants.DATA_BASE_NAME); String context = contextBuffer.toString(); String possibleCause = "The Template Database triggered an unexpected problem that wasn't able to solve by itself"; CantInsertRecordDataBaseException cantInsertRecordDataBaseException = new CantInsertRecordDataBaseException( CantInsertRecordDataBaseException.DEFAULT_MESSAGE, databaseTransactionFailedException, context, possibleCause); throw cantInsertRecordDataBaseException; } catch (CantReadRecordDataBaseException e) { CantInsertRecordDataBaseException cantInsertRecordDataBaseException = new CantInsertRecordDataBaseException( CantInsertRecordDataBaseException.DEFAULT_MESSAGE, e, "", "Cant Get record"); throw cantInsertRecordDataBaseException; } }
/** * 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); }
/** * 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")); } }
/** * This method process the message received and save on the data base in the table <code> * incoming_messages</code> and notify all observers to the new messages received */ private void processMessageReceived() { try { // System.out.println("CommunicationNetworkServiceRemoteAgent - // communicationsVPNConnection.isActive() = "+communicationsVPNConnection.isActive()); /** Verified the status of the connection */ if (communicationsVPNConnection.isActive()) { // System.out.println("CommunicationNetworkServiceRemoteAgent - // communicationsVPNConnection.getUnreadMessagesCount() = // "+communicationsVPNConnection.getUnreadMessagesCount()); /** process all pending messages */ for (int i = 0; i < communicationsVPNConnection.getUnreadMessagesCount(); i++) { /* * Read the next message in the queue */ FermatMessage message = communicationsVPNConnection.readNextMessage(); /* * Validate the message signature */ AsymmetricCryptography.verifyMessageSignature( message.getSignature(), message.getContent(), communicationsVPNConnection .getRemoteParticipantNetworkService() .getIdentityPublicKey()); /* * Decrypt the message content */ ((FermatMessageCommunication) message) .setContent( AsymmetricCryptography.decryptMessagePrivateKey( message.getContent(), eccKeyPair.getPrivateKey())); /* * Change to the new status */ ((FermatMessageCommunication) message) .setFermatMessagesStatus(FermatMessagesStatus.NEW_RECEIVED); /* * Save to the data base table */ incomingMessageDao.create(message); /* * Remove the message from the queue */ communicationsVPNConnection.removeMessageRead(message); /* * Notify all observer of this agent that Received a new message */ setChanged(); notifyObservers(message); } } // Sleep for a time toReceive.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")); } catch (CantInsertRecordDataBaseException e) { errorManager.reportUnexpectedPluginException( Plugins.BITDUBAI_DAP_ASSET_ISSUER_ACTOR_NETWORK_SERVICE, UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN, new Exception("Can not process message received. Error reason: " + e.getMessage())); } }
/** * (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); } }
/** * Decode a FermatMessage * * @param fermatMessage * @return */ public static JsonObject decodeMsjContent(FermatMessage fermatMessage) { return parser.parse(fermatMessage.getContent()).getAsJsonObject(); }
@Override protected final void handleNewMessages(FermatMessage message) throws FermatException { System.out.println( "******************* Crypto Payment Request messages arrived: " + message.getContent()); ((CryptoPaymentRequestNetworkServicePluginRoot) networkService).handleNewMessages(message); }