public async Task OutMessageIsCreatedForToBeForwardedMessage() { // Arrange const string messageId = "message-id"; var as4Message = AS4Message.Create(CreateForwardPushUserMessage(messageId)); // Act InsertToBeForwardedInMessage( pmodeId: "Forward_Push", mep: MessageExchangePattern.Push, tobeForwarded: as4Message); // Assert: if an OutMessage is created with the correct status and operation. InMessage inMessage = await PollUntilPresent( () => _databaseSpy.GetInMessageFor( m => m.EbmsMessageId == messageId && m.Operation == Operation.Forwarded), TimeSpan.FromSeconds(15)); Assert.NotNull(AS4XmlSerializer.FromString <ReceivingProcessingMode>(inMessage.PMode)); OutMessage outMessage = await PollUntilPresent( () => _databaseSpy.GetOutMessageFor(m => m.EbmsMessageId == messageId), timeout : TimeSpan.FromSeconds(5)); Assert.True(outMessage.Intermediary); Assert.Equal(Operation.ToBeProcessed, outMessage.Operation); Assert.NotNull(AS4XmlSerializer.FromString <SendingProcessingMode>(outMessage.PMode)); }
/// <summary> /// Complete the <paramref name="pmode" /> with the SMP metadata that is present in the <paramref name="smpMetaData" /> /// <see cref="XmlDocument" /> /// </summary> /// <param name="pmode">The <see cref="SendingProcessingMode" /> that must be decorated with the SMP metadata</param> /// <param name="smpMetaData">An XmlDocument that contains the SMP MetaData that has been received from an SMP server.</param> /// <returns>The completed <see cref="SendingProcessingMode" /></returns> public DynamicDiscoveryResult DecoratePModeWithSmpMetaData(SendingProcessingMode pmode, XmlDocument smpMetaData) { if (pmode == null) { throw new ArgumentNullException(nameof(pmode)); } if (smpMetaData == null) { throw new ArgumentNullException(nameof(smpMetaData)); } var smpResponse = AS4XmlSerializer.FromString <SmpConfiguration>(smpMetaData.OuterXml); if (smpResponse == null) { throw new ArgumentNullException( nameof(smpResponse), $@"SMP Response cannot be deserialized correctly to a SmpConfiguration model: {smpMetaData.OuterXml}"); } OverridePushProtocolUrlWithTlsEnabling(pmode, smpResponse); OverrideEntireEncryption(pmode, smpResponse); OverrideToParty(pmode, smpResponse); OverrideCollaborationServiceAction(pmode, smpResponse); AddFinalRecipientToMessageProperties(pmode, smpResponse); return(DynamicDiscoveryResult.Create(pmode)); }
/// <summary> /// Execute the step for a given <paramref name="messagingContext" />. /// </summary> /// <param name="messagingContext">Message used during the step execution.</param> /// <returns></returns> public async Task <StepResult> ExecuteAsync(MessagingContext messagingContext) { var pullRequest = messagingContext?.AS4Message?.FirstSignalMessage as PullRequest; if (pullRequest == null) { throw new InvalidMessageException( "The received message is not a PullRequest message, " + "therefore no UserMessage can be selected to return to the sender"); } (bool hasMatch, OutMessage match) = RetrieveUserMessageForPullRequest(pullRequest); if (hasMatch) { // Retrieve the existing MessageBody and put that stream in the MessagingContext. // The HttpReceiver processor will make sure that it gets serialized to the http response stream. Stream messageBody = await match.RetrieveMessageBody(_messageBodyStore).ConfigureAwait(false); messagingContext.ModifyContext( new ReceivedMessage(messageBody, match.ContentType), MessagingContextMode.Send); messagingContext.SendingPMode = AS4XmlSerializer.FromString <SendingProcessingMode>(match.PMode); return(StepResult.Success(messagingContext)); } AS4Message pullRequestWarning = AS4Message.Create(Error.CreatePullRequestWarning(IdentifierFactory.Instance.Create())); messagingContext.ModifyContext(pullRequestWarning); return(StepResult.Success(messagingContext).AndStopExecution()); }
public async Task ThenSignalMessageIsTransformedToNotifyEnvelopeWithCorrectContents() { // Arrange ReceivedEntityMessage receivedSignal = await CreateReceivedReceiptMessage(); // Act MessagingContext result = await ExerciseTransform(receivedSignal); // Assert Assert.NotNull(result.NotifyMessage); var notifyMessage = AS4XmlSerializer.FromString <NotifyMessage>(Encoding.UTF8.GetString(result.NotifyMessage.NotifyMessage)); Assert.NotNull(notifyMessage); // Assert: check if the original Receipt is a part of the NotifyMessage. var document = new XmlDocument { PreserveWhitespace = true }; document.LoadXml(Encoding.UTF8.GetString(((MemoryStream)receivedSignal.UnderlyingStream).ToArray())); Assert.Equal( Canonicalize(document.SelectSingleNode("//*[local-name()='SignalMessage']")), Canonicalize(notifyMessage.StatusInfo.Any.First())); }
public async Task ThenAgentStoresOutMessageFoReceivedSubmitMessage() { // Arrange string fixture = SubmitMessageFixture; var submitMessage = AS4XmlSerializer.FromString <SubmitMessage>(fixture); Assert.True(submitMessage?.MessageInfo?.MessageId != null, "Send SubmitMessage hasn't got a MessageInfo.MessageId element"); Assert.True(submitMessage?.Collaboration?.AgreementRef != null, "Send SubmitMessage hasn't got a Collaboration.AgreementRef element"); // Act using (HttpResponseMessage response = await StubSender.SendRequest(HttpSubmitAgentUrl, Encoding.UTF8.GetBytes(fixture), "application/xml")) { Assert.Equal(HttpStatusCode.Accepted, response.StatusCode); Assert.True(String.IsNullOrWhiteSpace(response.Content.Headers.ContentType?.ToString())); } // Assert IConfig config = _as4Msh.GetConfiguration(); string pmodeId = submitMessage.Collaboration.AgreementRef.PModeId; SendingProcessingMode usedSendingPMode = config.GetSendingPMode(pmodeId); Assert.True(usedSendingPMode.PushConfiguration?.Protocol != null, "SendingPMode for SubmitMessage hasn't got PushConfiguration.Protocol element"); var databaseSpy = new DatabaseSpy(config); OutMessage outMessage = databaseSpy.GetOutMessageFor( m => m.EbmsMessageId == submitMessage.MessageInfo.MessageId); Assert.True(outMessage != null, "No OutMessage was stored for send SubmitMessage"); Assert.Equal(usedSendingPMode.PushConfiguration.Protocol.Url, outMessage.Url); }
public async Task ForwardingWithPushOnPull() { // Arrange const string messageId = "user-message-id"; var tobeForwarded = AS4Message.Create(CreateForwardPushUserMessage(messageId)); // Act InsertToBeForwardedInMessage( pmodeId: "Forward_Push", mep: MessageExchangePattern.Pull, tobeForwarded: tobeForwarded); // Assert: if an OutMessage is created with the correct status and operation await PollUntilPresent( () => _databaseSpy.GetInMessageFor(m => m.EbmsMessageId == messageId && m.Operation == Operation.Forwarded), TimeSpan.FromSeconds(20)); OutMessage outMessage = await PollUntilPresent( () => _databaseSpy.GetOutMessageFor(m => m.EbmsMessageId == messageId), TimeSpan.FromSeconds(5)); var sendingPMode = AS4XmlSerializer.FromString <SendingProcessingMode>(outMessage.PMode); Assert.NotNull(sendingPMode); Assert.Equal(Operation.ToBeProcessed, outMessage.Operation); Assert.Equal(MessageExchangePattern.Push, outMessage.MEP); Assert.Equal(sendingPMode.MessagePackaging.Mpc, outMessage.Mpc); }
private static SubmitMessage DeserializeSubmitMessage(ReceivedMessage message) { try { var doc = new XmlDocument(); doc.Load(message.UnderlyingStream); var schemas = new XmlSchemaSet(); schemas.Add(XsdSchemaDefinitions.SubmitMessage); doc.Schemas = schemas; doc.Validate((sender, args) => { Logger.Fatal("Incoming Submit Message doesn't match the XSD: " + args.Message); throw args.Exception; }); return(AS4XmlSerializer.FromString <SubmitMessage>(doc.OuterXml)); } catch (Exception ex) { throw new InvalidMessageException( $"Received stream from {message.Origin} is not a SubmitMessage", ex); } }
/// <summary> /// Gets the sending processing mode based on a child representation of a message entity. /// </summary> public override SendingProcessingMode GetSendingPMode() { if (Intermediary || EbmsMessageType == MessageType.UserMessage) { return(AS4XmlSerializer.FromString <SendingProcessingMode>(PMode)); } return(null); }
/// <summary> /// Gets the receiving processing mode based on a child representation of a message entity. /// </summary> public override ReceivingProcessingMode GetReceivingPMode() { if (EbmsMessageType == MessageType.UserMessage) { return(AS4XmlSerializer.FromString <ReceivingProcessingMode>(PMode)); } return(null); }
/// <summary> /// Gets the sending processing mode based on a child representation of a message entity. /// </summary> public override SendingProcessingMode GetSendingPMode() { if (EbmsMessageType == MessageType.Receipt || EbmsMessageType == MessageType.Error) { return(AS4XmlSerializer.FromString <SendingProcessingMode>(PMode)); } return(null); }
public void Create_UserMessage_From_SubmitMessage() { // Arrange const string submitXml = @"<?xml version=""1.0""?> <SubmitMessage xmlns=""urn:cef:edelivery:eu:as4:messages""> <MessageInfo> <MessageId>F4840B69-8057-40C9-8530-EC91F946C3BF</MessageId> </MessageInfo> <Collaboration> <AgreementRef> <Value>eu.europe.agreements</Value> <PModeId>sample-pmode</PModeId> </AgreementRef> </Collaboration> <MessageProperties> <MessageProperty> <Name>Payloads</Name> <Type>Metadata</Type> <Value>2</Value> </MessageProperty> </MessageProperties> <Payloads> <Payload> <Id>earth</Id> <MimeType>image/jpeg</MimeType> <Location>file:///messages\attachments\earth.jpg</Location> <PayloadProperties/> </Payload> <Payload> <Id>xml-sample</Id> <MimeType>application/xml</MimeType> <Location>file:///messages\attachments\sample.xml</Location> <PayloadProperties> <PayloadProperty> <Name>Important</Name> <Value>Yes</Value> </PayloadProperty> </PayloadProperties> </Payload> </Payloads> </SubmitMessage>"; var submit = AS4XmlSerializer.FromString <SubmitMessage>(submitXml); var sendingPMode = new SendingProcessingMode(); // Act UserMessage result = SubmitMessageMap.CreateUserMessage(submit, sendingPMode); // Assert Assert.NotNull(result); Assert.NotEqual(Maybe.Nothing <AgreementReference>(), result.CollaborationInfo.AgreementReference); Assert.Single(result.MessageProperties); Assert.True(result.PayloadInfo.Count() == 2, "expected 2 part infos"); }
private void OverrideTransformerReceivingPModeSetting(string settingsFileName, string pmodeId) { string settingsFilePath = Path.Combine(ComponentTestSettingsPath, settingsFileName); var settings = AS4XmlSerializer.FromString <Settings>(File.ReadAllText(settingsFilePath)); settings.Agents .ReceiveAgents.First() .Transformer .Setting.First(s => s.Key == "ReceivingPMode") .Value = pmodeId; File.WriteAllText(settingsFilePath, AS4XmlSerializer.ToString(settings)); }
public void DynamicDiscovery_Invalid_With_Empty_SmpProfile(string xml, bool expected) { // Arrange var pmode = AS4XmlSerializer.FromString <SendingProcessingMode>(xml); // Act ValidationResult result = ExerciseValidation(pmode); // Assert Assert.True( expected == result.IsValid, result.AppendValidationErrorsToErrorMessage("Invalid SendingPMode: ")); }
protected Settings OverrideSettings(string settingsFile) { Console.WriteLine($@"Overwrite 'settings.xml' with '{settingsFile}'"); File.Copy(@".\config\settings.xml", @".\config\settings_original.xml", true); string specificSettings = $@".\config\componenttest-settings\{settingsFile}"; File.Copy(specificSettings, @".\config\settings.xml", true); _restoreSettings = true; return(AS4XmlSerializer.FromString <Settings>(File.ReadAllText(specificSettings))); }
/// <summary> /// Gets the receiving processing mode based on a child representation of a message entity. /// </summary> public override ReceivingProcessingMode GetReceivingPMode() { if (Intermediary) { return(null); } if (EbmsMessageType == MessageType.Receipt || EbmsMessageType == MessageType.Error) { return(AS4XmlSerializer.FromString <ReceivingProcessingMode>(PMode)); } return(null); }
public async Task OutMessageIsCreatedForPrimaryMessageUnitOfToBeForwardedAS4Message() { // Arrange const string primaryMessageId = "primary-message-id"; const string secondMessageId = "secondary-message-id"; var primaryUserMessage = CreateForwardPushUserMessage(primaryMessageId); var secondaryUserMessage = new UserMessage(secondMessageId); var as4Message = AS4Message.Create(primaryUserMessage); as4Message.AddMessageUnit(secondaryUserMessage); // Act InsertToBeForwardedInMessage( pmodeId: "Forward_Push", mep: MessageExchangePattern.Push, tobeForwarded: as4Message); // Assert: if an OutMessage is created with the correct status and operation. InMessage primaryInMessage = await PollUntilPresent( () => _databaseSpy.GetInMessageFor( m => m.EbmsMessageId == primaryMessageId && m.Operation == Operation.Forwarded), TimeSpan.FromSeconds(20)); Assert.NotNull(AS4XmlSerializer.FromString <ReceivingProcessingMode>(primaryInMessage.PMode)); await PollUntilPresent( () => _databaseSpy.GetInMessageFor(m => m.EbmsMessageId == secondMessageId), timeout : TimeSpan.FromSeconds(20)); Assert.Equal(Operation.Forwarded, primaryInMessage.Operation); Assert.NotNull(AS4XmlSerializer.FromString <ReceivingProcessingMode>(primaryInMessage.PMode)); OutMessage primaryOutMessage = await PollUntilPresent( () => _databaseSpy.GetOutMessageFor(m => m.EbmsMessageId == primaryMessageId), timeout : TimeSpan.FromSeconds(5)); Assert.Equal(Operation.ToBeProcessed, primaryOutMessage.Operation); Assert.NotNull(AS4XmlSerializer.FromString <SendingProcessingMode>(primaryOutMessage.PMode)); OutMessage secondaryOutMessage = _databaseSpy.GetOutMessageFor(m => m.EbmsMessageId == secondMessageId); Assert.Null(secondaryOutMessage); }
private static void AssertIfSenderAndReceiverAreReversed(AS4Message expectedAS4Message, XmlNode doc) { XmlNode routingInputNode = doc.UnsafeSelectEbmsNode("/s12:Envelope/s12:Header/mh:RoutingInput"); Assert.NotNull(routingInputNode); var routingInput = AS4XmlSerializer.FromString <RoutingInput>(routingInputNode.OuterXml); RoutingInputUserMessage actualUserMessage = routingInput.UserMessage; UserMessage expectedUserMessage = expectedAS4Message.FirstUserMessage; Assert.Equal(expectedUserMessage.Sender.Role, actualUserMessage.PartyInfo.To.Role); Assert.Equal( expectedUserMessage.Sender.PartyIds.First().Id, actualUserMessage.PartyInfo.To.PartyId.First().Value); Assert.Equal(expectedUserMessage.Receiver.Role, actualUserMessage.PartyInfo.From.Role); Assert.Equal( expectedUserMessage.Receiver.PartyIds.First().Id, actualUserMessage.PartyInfo.From.PartyId.First().Value); }
private SendingProcessingMode RetrieveSendingPModeForMessageWithEbmsMessageId(string ebmsMessageId) { if (ebmsMessageId == null) { Logger.Debug("Can't retrieve SendingPMode because NotifyMessage.MessageInfo.RefToMessageId is not present"); return(null); } using (DatastoreContext context = _createContext()) { var repository = new DatastoreRepository(context); var outMessageData = repository.GetOutMessageData( where : m => m.EbmsMessageId == ebmsMessageId && m.Intermediary == false, selection: m => new { m.PMode, m.ModificationTime }) .OrderByDescending(m => m.ModificationTime) .FirstOrDefault(); if (outMessageData == null) { Logger.Debug( "Can't retrieve SendingPMode because no matching stored OutMessage found " + $"for EbmsMessageId = {ebmsMessageId} AND Intermediary = false"); return(null); } var pmode = AS4XmlSerializer.FromString <SendingProcessingMode>(outMessageData.PMode); if (pmode == null) { Logger.Debug( "Can't use SendingPMode from matching OutMessage for NotifyMessage.MessageInfo.RefToMessageId " + $"{ebmsMessageId} because the PMode field can't be deserialized correctly to a SendingPMode"); } return(pmode); } }
public async Task Test_8_2_8_Send_AS4Message_To_Receiving_MSH_That_Cant_Find_PMode_Result_In_Notification_Error() { // Arrange AS4Component.Start(); // Act AS4Component.PutSubmitMessage("8.2.8-pmode", AS4Component.SubmitPayloadImage); // Assert IEnumerable <FileInfo> errors = await PollingService.PollUntilPresentAsync(AS4Component.ErrorsPath); string xml = File.ReadAllText(errors.First().FullName); var notification = AS4XmlSerializer.FromString <NotifyMessage>(xml); Assert.True(notification != null, "Found Error notification cannot be deserialized to a 'NotifyMessage'"); Assert.True(notification.StatusInfo != null, "Found Error notification doesn't hava a <StatusInfo/> element"); Assert.Equal(Status.Error, notification.StatusInfo.Status); Assert.True( notification.StatusInfo.Any.First().SelectSingleNode("//*[local-name()='ErrorDetail']")?.InnerText != null, "Found Error notification doesn't have a <SignalMessage/> included"); }
public async Task RetrieveSmpResponseFromDatastore() { // Arrange var fixture = new Party("role", new PartyId(Guid.NewGuid().ToString(), "type")); var expected = new SmpConfiguration { PartyRole = fixture.Role, ToPartyId = fixture.PrimaryPartyId, PartyType = "type" }; InsertSmpResponse(expected); var sut = new LocalDynamicDiscoveryProfile(GetDataStoreContext); // Act XmlDocument actualDoc = await sut.RetrieveSmpMetaDataAsync(fixture, properties : null); // Assert var actual = AS4XmlSerializer.FromString <SmpConfiguration>(actualDoc.OuterXml); Assert.Equal(expected.ToPartyId, actual.ToPartyId); }
public async Task Test_8_1_12_AS4Message_With_Single_Payload_Result_In_Notified_Signed_Non_Repudiation_Receipt() { // Arrange AS4Component.Start(); Holodeck.CopyPModeToHolodeckB("8.1.12-pmode.xml"); // Act AS4Component.PutSubmitMessageSinglePayload("8.1.12-pmode"); IEnumerable <FileInfo> receipts = await PollingService.PollUntilPresentAsync(AS4Component.ReceiptsPath); string xml = File.ReadAllText(receipts.First().FullName); var notification = AS4XmlSerializer.FromString <NotifyMessage>(xml); Assert.True(notification != null, "Found Receipt notification cannot be deserialized to a NotifyMessage"); Assert.True(notification.StatusInfo != null, "Found Receipt notification doesn't have a <StatusInfo/> element"); Assert.Equal(Status.Delivered, notification.StatusInfo.Status); Assert.True(notification.StatusInfo.Any?.Any(), "Found Receipt notification doesn't have a <SignalMessage/> included"); Assert.True( notification.StatusInfo.Any?.First()?.SelectSingleNode("//*[local-name()='NonRepudiationInformation']") != null, "Found Receipt notification doesn't have a <NonRepudiationInformation/> element"); }
private static void TestConfigInitialization( Action <Settings> alterSettings, Action <Config> onInitialized) { string testSettingsFileName = Path.Combine( Config.ApplicationPath, "config", "test-settings.xml"); string originalSettingsFileName = Path.Combine( Config.ApplicationPath, "config", "settings.xml"); var settings = AS4XmlSerializer .FromString <Settings>(File.ReadAllText(originalSettingsFileName)); alterSettings(settings); File.WriteAllText( testSettingsFileName, AS4XmlSerializer.ToString(settings)); File.Copy( originalSettingsFileName, testSettingsFileName, overwrite: true); Directory.CreateDirectory(Path.Combine(Config.ApplicationPath, "config", "send-pmodes")); Directory.CreateDirectory(Path.Combine(Config.ApplicationPath, "config", "receive-pmodes")); // Act Config.Instance.Initialize(testSettingsFileName); // Assert onInitialized(Config.Instance); // TearDown File.Delete(testSettingsFileName); }
public void StartReceiver() { var stubConfig = new StubConfig( sendingPModes: new Dictionary <string, SendingProcessingMode> { ["01-send"] = AS4XmlSerializer.FromString <SendingProcessingMode>(Properties.Resources.send_01) }, receivingPModes: new Dictionary <string, ReceivingProcessingMode> { ["01-receive"] = AS4XmlSerializer.FromString <ReceivingProcessingMode>(Properties.Resources.receive_01) }); // Arrange var receiver = new PullRequestReceiver(stubConfig); Setting receiverSetting = CreateMockReceiverSetting(); receiver.Configure(new[] { receiverSetting }); // Act receiver.StartReceiving(OnMessageReceived, CancellationToken.None); // Assert Assert.True(_waitHandle.WaitOne(timeout: TimeSpan.FromMinutes(2))); }
protected SubmitMessage SubmitWithTwoPayloads() { return(AS4XmlSerializer.FromString <SubmitMessage>(Properties.Resources.submitmessage)); }
/// <summary> /// Gets the receiving processing mode of the child representation of an exception. /// </summary> /// <returns></returns> public override ReceivingProcessingMode GetReceivingPMode() { return(AS4XmlSerializer.FromString <ReceivingProcessingMode>(PMode)); }
public void SendingPMode_Party_Is_Not_Present_When_Non_Existing_Tag(string xml, bool specified) { var result = AS4XmlSerializer.FromString <PartyInfo>(xml); Assert.True((result.ToParty != null) == specified); }
/// <summary> /// Gets the sending processing mode of the child representation of an exception. /// </summary> public override SendingProcessingMode GetSendingPMode() { return(AS4XmlSerializer.FromString <SendingProcessingMode>(PMode)); }
protected SendingProcessingMode DefaultSendPMode() { return(AS4XmlSerializer.FromString <SendingProcessingMode>(Properties.Resources.sendingprocessingmode)); }