use of com.helger.phase4.attachment.AS4DecompressException in project phase4 by phax.
the class AS4RequestHandler method _invokeSPIsForIncoming.
/**
* Invoke custom SPI message processors
*
* @param aHttpHeaders
* The received HTTP headers. Never <code>null</code>.
* @param aEbmsUserMessage
* Current user message. Either this OR signal message must be
* non-<code>null</code>.
* @param aEbmsSignalMessage
* The signal message to use. Either this OR user message must be
* non-<code>null</code>.
* @param aPayloadNode
* Optional SOAP body payload (only if direct SOAP msg, not for MIME).
* May be <code>null</code>.
* @param aDecryptedAttachments
* Original attachments from source message. May be <code>null</code>.
* @param aPMode
* PMode to be used - may be <code>null</code> for Receipt messages.
* @param aState
* The current state. Never <code>null</<code></code>.
* @param aErrorMessagesTarget
* The list of error messages to be filled if something goes wrong.
* Never <code>null</code>.
* @param aResponseAttachmentsTarget
* The list of attachments to be added to the response. Never
* <code>null</code>.
* @param aSPIResult
* The result object to be filled. May not be <code>null</code>.
*/
private void _invokeSPIsForIncoming(@Nonnull final HttpHeaderMap aHttpHeaders, @Nullable final Ebms3UserMessage aEbmsUserMessage, @Nullable final Ebms3SignalMessage aEbmsSignalMessage, @Nullable final Node aPayloadNode, @Nullable final ICommonsList<WSS4JAttachment> aDecryptedAttachments, @Nullable final IPMode aPMode, @Nonnull final IAS4MessageState aState, @Nonnull final ICommonsList<Ebms3Error> aErrorMessagesTarget, @Nonnull final ICommonsList<WSS4JAttachment> aResponseAttachmentsTarget, @Nonnull final SPIInvocationResult aSPIResult) {
ValueEnforcer.isTrue(aEbmsUserMessage != null || aEbmsSignalMessage != null, "User OR Signal Message must be present");
ValueEnforcer.isFalse(aEbmsUserMessage != null && aEbmsSignalMessage != null, "Only one of User OR Signal Message may be present");
final boolean bIsUserMessage = aEbmsUserMessage != null;
final String sMessageID = bIsUserMessage ? aEbmsUserMessage.getMessageInfo().getMessageId() : aEbmsSignalMessage.getMessageInfo().getMessageId();
// Get all processors
final ICommonsList<IAS4ServletMessageProcessorSPI> aAllProcessors = m_aProcessorSupplier.get();
if (LOGGER.isDebugEnabled())
LOGGER.debug("Trying to invoke the following " + aAllProcessors.size() + " SPIs on message ID '" + sMessageID + "': " + aAllProcessors);
if (aAllProcessors.isEmpty())
LOGGER.error("No IAS4ServletMessageProcessorSPI is available to process an incoming message");
// Invoke ALL non-null SPIs
for (final IAS4ServletMessageProcessorSPI aProcessor : aAllProcessors) if (aProcessor != null)
try {
if (LOGGER.isDebugEnabled())
LOGGER.debug("Invoking AS4 message processor " + aProcessor + " for incoming message");
// Main processing
final AS4MessageProcessorResult aResult;
final ICommonsList<Ebms3Error> aProcessingErrorMessages = new CommonsArrayList<>();
if (bIsUserMessage) {
aResult = aProcessor.processAS4UserMessage(m_aMessageMetadata, aHttpHeaders, aEbmsUserMessage, aPMode, aPayloadNode, aDecryptedAttachments, aState, aProcessingErrorMessages);
} else {
aResult = aProcessor.processAS4SignalMessage(m_aMessageMetadata, aHttpHeaders, aEbmsSignalMessage, aPMode, aState, aProcessingErrorMessages);
}
// Result returned?
if (aResult == null)
throw new IllegalStateException("No result object present from AS4 message processor " + aProcessor + " - this is a programming error");
if (aProcessingErrorMessages.isNotEmpty() || aResult.isFailure()) {
if (aProcessingErrorMessages.isNotEmpty()) {
if (LOGGER.isDebugEnabled())
LOGGER.debug("AS4 message processor " + aProcessor + " had processing errors - breaking. Details: " + aProcessingErrorMessages);
if (aResult.isSuccess())
LOGGER.warn("Processing errors are present but success was returned by a previous AS4 message processor " + aProcessor + " - considering the whole processing to be failed instead");
aErrorMessagesTarget.addAll(aProcessingErrorMessages);
}
if (aResult.isFailure() && aResult.hasErrorMessage()) {
aErrorMessagesTarget.add(EEbmsError.EBMS_OTHER.getAsEbms3Error(m_aLocale, sMessageID, "Invoked AS4 message processor SPI " + aProcessor + " on '" + sMessageID + "' returned a failure: " + aResult.getErrorMessage()));
}
// Stop processing
return;
}
// SPI invocation returned success and no errors
{
final String sAsyncResultURL = aResult.getAsyncResponseURL();
if (StringHelper.hasText(sAsyncResultURL)) {
// URL present
if (aSPIResult.hasAsyncResponseURL()) {
// A second processor returned a response URL - not allowed
final String sErrorMsg = "Invoked AS4 message processor SPI " + aProcessor + " on '" + sMessageID + "' failed: the previous processor already returned an async response URL; it is not possible to handle two URLs. Please check your SPI implementations.";
LOGGER.error(sErrorMsg);
aErrorMessagesTarget.add(EEbmsError.EBMS_VALUE_INCONSISTENT.getAsEbms3Error(m_aLocale, sMessageID, sErrorMsg));
// Stop processing
return;
}
aSPIResult.setAsyncResponseURL(sAsyncResultURL);
LOGGER.info("Using asynchronous response URL '" + sAsyncResultURL + "' for message ID '" + sMessageID + "'");
}
}
if (bIsUserMessage) {
// User message specific processing result handling
// empty
} else {
// Signal message specific processing result handling
assert aResult instanceof AS4SignalMessageProcessorResult;
if (aEbmsSignalMessage.getReceipt() == null) {
final Ebms3UserMessage aPullReturnUserMsg = ((AS4SignalMessageProcessorResult) aResult).getPullReturnUserMessage();
if (aSPIResult.hasPullReturnUserMsg()) {
// to the pullrequest initiator
if (aPullReturnUserMsg != null) {
final String sErrorMsg = "Invoked AS4 message processor SPI " + aProcessor + " on '" + sMessageID + "' failed: the previous processor already returned a usermessage; it is not possible to return two usermessage. Please check your SPI implementations.";
LOGGER.warn(sErrorMsg);
aErrorMessagesTarget.add(EEbmsError.EBMS_VALUE_INCONSISTENT.getAsEbms3Error(m_aLocale, sMessageID, sErrorMsg));
// Stop processing
return;
}
} else {
// Initial return user msg
if (aPullReturnUserMsg == null) {
// No message contained in the MPC
final String sErrorMsg = "Invoked AS4 message processor SPI " + aProcessor + " on '" + sMessageID + "' returned a failure: no UserMessage contained in the MPC";
LOGGER.warn(sErrorMsg);
aErrorMessagesTarget.add(EEbmsError.EBMS_EMPTY_MESSAGE_PARTITION_CHANNEL.getAsEbms3Error(m_aLocale, sMessageID, sErrorMsg));
// Stop processing
return;
}
// We have something :)
aSPIResult.setPullReturnUserMsg(aPullReturnUserMsg);
}
} else {
if (LOGGER.isDebugEnabled())
LOGGER.debug("The AS4 EbmsSignalMessage already has a Receipt");
}
}
// Add response attachments, payloads
aResult.addAllAttachmentsTo(aResponseAttachmentsTarget);
if (LOGGER.isDebugEnabled())
LOGGER.debug("Successfully invoked AS4 message processor " + aProcessor);
} catch (final AS4DecompressException ex) {
LOGGER.error("Failed to decompress AS4 payload", ex);
// Hack for invalid GZip content from WSS4JAttachment.getSourceStream
aErrorMessagesTarget.add(EEbmsError.EBMS_DECOMPRESSION_FAILURE.getAsEbms3Error(m_aLocale, sMessageID));
return;
} catch (final RuntimeException ex) {
// Re-throw
throw ex;
} catch (final Exception ex) {
throw new IllegalStateException("Error processing incoming AS4 message with processor " + aProcessor, ex);
}
// Remember success
aSPIResult.setSuccess(true);
}
use of com.helger.phase4.attachment.AS4DecompressException in project phase4 by phax.
the class AS4IncomingHandler method _decompressAttachments.
private static void _decompressAttachments(@Nonnull final ICommonsList<WSS4JAttachment> aIncomingDecryptedAttachments, @Nonnull final Ebms3UserMessage aUserMessage, @Nonnull final IAS4MessageState aState) {
// For all incoming attachments
for (final WSS4JAttachment aIncomingAttachment : aIncomingDecryptedAttachments.getClone()) {
final EAS4CompressionMode eCompressionMode = aState.getAttachmentCompressionMode(aIncomingAttachment.getId());
if (eCompressionMode != null) {
final IHasInputStream aOldISP = aIncomingAttachment.getInputStreamProvider();
aIncomingAttachment.setSourceStreamProvider(new HasInputStream(() -> {
try {
final InputStream aSrcIS = aOldISP.getInputStream();
if (aSrcIS == null)
throw new IllegalStateException("Failed to create InputStream from " + aOldISP);
if (LOGGER.isDebugEnabled())
LOGGER.debug("Decompressing attachment with ID '" + aIncomingAttachment.getId() + "' using " + eCompressionMode);
return eCompressionMode.getDecompressStream(aSrcIS);
} catch (final IOException ex) {
// invalid payload
throw new AS4DecompressException(ex);
}
}, aOldISP.isReadMultiple()));
// Remember the compression mode
aIncomingAttachment.setCompressionMode(eCompressionMode);
final String sAttachmentContentID = StringHelper.trimStart(aIncomingAttachment.getId(), "attachment=");
// x.getHref() != null needed since, if a message contains a payload and
// an attachment, it would throw a NullPointerException since a payload
// does not have anything written in its partinfo therefore also now
// href
final Ebms3PartInfo aPartInfo = CollectionHelper.findFirst(aUserMessage.getPayloadInfo().getPartInfo(), x -> x.getHref() != null && x.getHref().contains(sAttachmentContentID));
if (aPartInfo != null && aPartInfo.getPartProperties() != null) {
// Find MimeType property
final Ebms3Property aProperty = CollectionHelper.findFirst(aPartInfo.getPartProperties().getProperty(), x -> x.getName().equalsIgnoreCase(MessageHelperMethods.PART_PROPERTY_MIME_TYPE));
if (aProperty != null) {
final String sMimeType = aProperty.getValue();
if (MimeTypeParser.safeParseMimeType(sMimeType) == null)
LOGGER.warn("Value '" + sMimeType + "' of property '" + MessageHelperMethods.PART_PROPERTY_MIME_TYPE + "' is not a valid MIME type");
aIncomingAttachment.overwriteMimeType(sMimeType);
}
}
}
}
}
use of com.helger.phase4.attachment.AS4DecompressException in project phase4 by phax.
the class Phase4PeppolServletMessageProcessorSPI method processAS4UserMessage.
@Nonnull
public AS4MessageProcessorResult processAS4UserMessage(@Nonnull final IAS4IncomingMessageMetadata aMessageMetadata, @Nonnull final HttpHeaderMap aHttpHeaders, @Nonnull final Ebms3UserMessage aUserMessage, @Nonnull final IPMode aSrcPMode, @Nullable final Node aPayload, @Nullable final ICommonsList<WSS4JAttachment> aIncomingAttachments, @Nonnull final IAS4MessageState aState, @Nonnull final ICommonsList<Ebms3Error> aProcessingErrorMessages) {
if (LOGGER.isDebugEnabled())
LOGGER.debug("Invoking processAS4UserMessage");
final String sMessageID = aUserMessage.getMessageInfo().getMessageId();
final String sService = aUserMessage.getCollaborationInfo().getServiceValue();
final String sAction = aUserMessage.getCollaborationInfo().getAction();
final String sConversationID = aUserMessage.getCollaborationInfo().getConversationId();
final String sLogPrefix = "[" + sMessageID + "] ";
final Locale aDisplayLocale = aState.getLocale();
// Debug log
if (LOGGER.isDebugEnabled()) {
if (aSrcPMode == null)
LOGGER.debug(sLogPrefix + " No Source PMode present");
else
LOGGER.debug(sLogPrefix + " Source PMode = " + aSrcPMode.getID());
LOGGER.debug(sLogPrefix + " AS4 Message ID = '" + sMessageID + "'");
LOGGER.debug(sLogPrefix + " AS4 Service = '" + sService + "'");
LOGGER.debug(sLogPrefix + " AS4 Action = '" + sAction + "'");
LOGGER.debug(sLogPrefix + " AS4 ConversationId = '" + sConversationID + "'");
// Log source properties
if (aUserMessage.getMessageProperties() != null && aUserMessage.getMessageProperties().hasPropertyEntries()) {
LOGGER.debug(sLogPrefix + " AS4 MessageProperties:");
for (final Ebms3Property p : aUserMessage.getMessageProperties().getProperty()) LOGGER.debug(sLogPrefix + " [" + p.getName() + "] = [" + p.getValue() + "]");
} else
LOGGER.debug(sLogPrefix + " No AS4 Mesage Properties present");
if (aPayload == null)
LOGGER.debug(sLogPrefix + " No SOAP Body Payload present");
else
LOGGER.debug(sLogPrefix + " SOAP Body Payload = " + XMLWriter.getNodeAsString(aPayload));
}
// Read all attachments
final ICommonsList<ReadAttachment> aReadAttachments = new CommonsArrayList<>();
if (aIncomingAttachments != null) {
int nAttachmentIndex = 0;
for (final IAS4Attachment aIncomingAttachment : aIncomingAttachments) {
final ReadAttachment a = new ReadAttachment();
a.m_sID = aIncomingAttachment.getId();
a.m_sMimeType = aIncomingAttachment.getMimeType();
a.m_sUncompressedMimeType = aIncomingAttachment.getUncompressedMimeType();
a.m_aCharset = aIncomingAttachment.getCharset();
a.m_eCompressionMode = aIncomingAttachment.getCompressionMode();
try (final InputStream aSIS = aIncomingAttachment.getSourceStream()) {
final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream();
if (StreamHelper.copyInputStreamToOutputStreamAndCloseOS(aSIS, aBAOS).isSuccess()) {
a.m_aPayloadBytes = aBAOS.getBufferOrCopy();
}
} catch (final IOException | AS4DecompressException ex) {
// Fall through
}
if (a.m_aPayloadBytes == null) {
LOGGER.error(sLogPrefix + "Failed to decompress the payload");
aProcessingErrorMessages.add(EEbmsError.EBMS_DECOMPRESSION_FAILURE.getAsEbms3Error(aDisplayLocale, aState.getMessageID()));
return AS4MessageProcessorResult.createFailure(null);
}
// Read data as SBDH
// Hint for production systems: this may take a huge amount of memory,
// if the payload is large
final ErrorList aSBDHErrors = new ErrorList();
a.m_aSBDH = SBDHReader.standardBusinessDocument().setValidationEventHandler(new WrappedCollectingValidationEventHandler(aSBDHErrors)).read(a.m_aPayloadBytes);
if (a.m_aSBDH == null) {
if (aSBDHErrors.isEmpty()) {
final String sMsg = "Failed to read the provided SBDH document";
LOGGER.error(sLogPrefix + sMsg);
aProcessingErrorMessages.add(EEbmsError.EBMS_OTHER.getAsEbms3Error(aDisplayLocale, aState.getMessageID(), sMsg));
} else {
for (final IError aError : aSBDHErrors) {
final String sMsg = "Peppol SBDH Issue: " + aError.getAsString(aDisplayLocale);
LOGGER.error(sLogPrefix + sMsg);
aProcessingErrorMessages.add(EEbmsError.EBMS_OTHER.getAsEbms3Error(aDisplayLocale, aState.getMessageID(), sMsg));
}
}
return AS4MessageProcessorResult.createFailure(null);
}
aReadAttachments.add(a);
if (LOGGER.isDebugEnabled())
LOGGER.debug(sLogPrefix + "AS4 Attachment " + nAttachmentIndex + " with ID [" + a.m_sID + "] uses [" + a.m_sMimeType + (a.m_sUncompressedMimeType == null ? null : " - uncompressed " + a.m_sUncompressedMimeType) + "] and [" + StringHelper.getToString(a.m_aCharset, "no charset") + "] and length is " + (a.m_aPayloadBytes == null ? "<error>" : Integer.toString(a.m_aPayloadBytes.length)) + " bytes" + (a.m_eCompressionMode == null ? "" : " of compressed payload"));
nAttachmentIndex++;
}
}
if (aReadAttachments.size() != 1) {
// In Peppol there must be exactly one payload
final String sMsg = "In Peppol exactly one payload attachment is expected. This request has " + aReadAttachments.size() + " attachments";
LOGGER.error(sLogPrefix + sMsg);
return AS4MessageProcessorResult.createFailure(sMsg);
}
// The one and only
final ReadAttachment aReadAttachment = aReadAttachments.getFirst();
// Extract Peppol values from SBD
final PeppolSBDHDocument aPeppolSBD;
try {
if (LOGGER.isDebugEnabled())
LOGGER.debug(sLogPrefix + "Now evaluating the SBDH against Peppol rules");
final boolean bPerformValueChecks = Phase4PeppolServletConfiguration.isPerformSBDHValueChecks();
aPeppolSBD = new PeppolSBDHDocumentReader(SimpleIdentifierFactory.INSTANCE).setPerformValueChecks(bPerformValueChecks).extractData(aReadAttachment.standardBusinessDocument());
if (LOGGER.isDebugEnabled())
LOGGER.debug(sLogPrefix + "The provided SBDH is valid according to Peppol rules, with value checks being " + (bPerformValueChecks ? "enabled" : "disabled"));
} catch (final PeppolSBDHDocumentReadException ex) {
final String sMsg = "Failed to extract the Peppol data from SBDH. Technical details: " + ex.getClass().getName() + " - " + ex.getMessage();
LOGGER.error(sLogPrefix + sMsg);
return AS4MessageProcessorResult.createFailure(sMsg);
}
if (m_aHandlers.isEmpty()) {
LOGGER.error(sLogPrefix + "No SPI handler is present - the message is unhandled and discarded");
} else {
// Start consistency checks?
final Phase4PeppolReceiverCheckData aReceiverCheckData = m_aReceiverCheckData != null ? m_aReceiverCheckData : Phase4PeppolServletConfiguration.getAsReceiverCheckData();
if (aReceiverCheckData != null) {
if (LOGGER.isDebugEnabled())
LOGGER.debug("Performing check if the provided data is registered in our SMP");
try {
// Get the endpoint information required from the recipient
// Check if an endpoint is registered
final IParticipantIdentifier aReceiverID = aPeppolSBD.getReceiverAsIdentifier();
final IDocumentTypeIdentifier aDocTypeID = aPeppolSBD.getDocumentTypeAsIdentifier();
final IProcessIdentifier aProcessID = aPeppolSBD.getProcessAsIdentifier();
final EndpointType aReceiverEndpoint = _getReceiverEndpoint(sLogPrefix, aReceiverCheckData.getSMPClient(), aReceiverID, aDocTypeID, aProcessID);
if (aReceiverEndpoint == null) {
final String sMsg = "Failed to resolve SMP endpoint for provided receiver ID (" + (aReceiverID == null ? "null" : aReceiverID.getURIEncoded()) + ")/documentType ID (" + (aDocTypeID == null ? "null" : aDocTypeID.getURIEncoded()) + ")/process ID (" + (aProcessID == null ? "null" : aProcessID.getURIEncoded()) + ")/transport profile (" + m_aTransportProfile.getID() + ") - not handling incoming AS4 document";
LOGGER.error(sLogPrefix + sMsg);
return AS4MessageProcessorResult.createFailure(sMsg);
}
// Check if the message is for us
_checkIfReceiverEndpointURLMatches(sLogPrefix, aReceiverCheckData.getAS4EndpointURL(), aReceiverEndpoint);
// Get the recipient certificate from the SMP
_checkIfEndpointCertificateMatches(sLogPrefix, aReceiverCheckData.getAPCertificate(), aReceiverEndpoint);
} catch (final Phase4Exception ex) {
final String sMsg = "The addressing data contained in the SBDH could not be verified. Technical details: " + ex.getClass().getName() + " - " + ex.getMessage();
LOGGER.error(sLogPrefix + sMsg);
return AS4MessageProcessorResult.createFailure(sMsg);
}
} else {
LOGGER.info(sLogPrefix + "Endpoint checks for incoming AS4 messages are disabled");
}
for (final IPhase4PeppolIncomingSBDHandlerSPI aHandler : m_aHandlers) {
try {
if (LOGGER.isDebugEnabled())
LOGGER.debug(sLogPrefix + "Invoking Peppol handler " + aHandler);
aHandler.handleIncomingSBD(aMessageMetadata, aHttpHeaders.getClone(), aUserMessage.clone(), aReadAttachment.payloadBytes(), aReadAttachment.standardBusinessDocument(), aPeppolSBD, aState);
} catch (final Exception ex) {
LOGGER.error(sLogPrefix + "Error invoking Peppol handler " + aHandler, ex);
if (aHandler.exceptionTranslatesToAS4Error()) {
final String sMsg = "The incoming Peppol message could not be processed. Technical details: " + ex.getClass().getName() + " - " + ex.getMessage();
LOGGER.error(sLogPrefix + sMsg);
return AS4MessageProcessorResult.createFailure(sMsg);
}
}
}
}
return AS4MessageProcessorResult.createSuccess();
}
Aggregations