use of com.helger.mail.cte.EContentTransferEncoding in project as2-lib by phax.
the class AsynchMDNSenderModule method _sendViaHTTP.
private void _sendViaHTTP(@Nonnull final AS2Message aMsg, @Nonnull final DispositionType aDisposition, @Nullable final IHTTPOutgoingDumper aOutgoingDumper, @Nonnull final AS2ResourceHelper aResHelper) throws AS2Exception, IOException, MessagingException {
final IMessageMDN aMdn = aMsg.getMDN();
// Create a HTTP connection
final String sUrl = aMsg.getAsyncMDNurl();
final EHttpMethod eRequestMethod = EHttpMethod.POST;
// MDN is a small message. We will always use CHttp
final AS2HttpClient aConn = getHttpClient(sUrl, eRequestMethod, getSession().getHttpProxy());
try {
if (aOutgoingDumper != null)
aOutgoingDumper.start(sUrl, aMsg);
if (LOGGER.isInfoEnabled())
LOGGER.info("Connecting to " + sUrl + aMsg.getLoggingText());
// Set all custom headers first (so that they are overridden with the
// mandatory ones in here)
// Use HttpHeaderMap and not String to ensure name casing is identical!
final HttpHeaderMap aHeaderMap = aMdn.headers().getClone();
aHeaderMap.setHeader(CHttpHeader.CONNECTION, CAS2Header.DEFAULT_CONNECTION);
aHeaderMap.setHeader(CHttpHeader.USER_AGENT, CAS2Header.DEFAULT_USER_AGENT);
final boolean bQuoteHeaderValues = isQuoteHeaderValues();
final AS2HttpHeaderSetter aHeaderSetter = new AS2HttpHeaderSetter(aConn, aOutgoingDumper, bQuoteHeaderValues);
// Copy all the header from mdn to the RequestProperties of conn
// Unification needed, because original MDN headers may contain newlines
aHeaderMap.forEachSingleHeader(aHeaderSetter::setHttpHeader, true, false);
if (aOutgoingDumper != null)
aOutgoingDumper.finishedHeaders();
aMsg.attrs().putIn(CNetAttribute.MA_DESTINATION_IP, aConn.getURL().getHost());
aMsg.attrs().putIn(CNetAttribute.MA_DESTINATION_PORT, aConn.getURL().getPort());
final InputStream aMsgIS = aMdn.getData().getInputStream();
// Transfer the data
final StopWatch aSW = StopWatch.createdStarted();
final long nBytes = aConn.send(aMsgIS, (EContentTransferEncoding) null, aOutgoingDumper, aResHelper);
aSW.stop();
if (LOGGER.isInfoEnabled())
LOGGER.info("AS2 MDN transferred " + AS2IOHelper.getTransferRate(nBytes, aSW) + aMsg.getLoggingText());
if (aOutgoingDumper != null)
aOutgoingDumper.finishedPayload();
final int nHttpResponseCode = aConn.getResponseCode();
if (getOutgoingHttpCallback() != null)
getOutgoingHttpCallback().onOutgoingHttpMessage(false, aMsg.getAS2From(), aMsg.getAS2To(), aMsg.getMessageID(), (MIC) null, (EContentTransferEncoding) null, sUrl, nHttpResponseCode);
// Check the HTTP Response code
if (AS2HttpClient.isErrorResponseCode(nHttpResponseCode)) {
if (LOGGER.isErrorEnabled())
LOGGER.error("sent AsyncMDN [" + aDisposition.getAsString() + "] Fail(" + nHttpResponseCode + ") " + aMsg.getLoggingText());
throw new AS2HttpResponseException(sUrl, nHttpResponseCode, aConn.getResponseMessage());
}
if (LOGGER.isInfoEnabled())
LOGGER.info("sent AsyncMDN [" + aDisposition.getAsString() + "] OK(" + nHttpResponseCode + ") " + aMsg.getLoggingText());
// log & store mdn into backup folder.
try {
getSession().getMessageProcessor().handle(IProcessorStorageModule.DO_STOREMDN, aMsg, null);
} catch (final AS2ComponentNotFoundException | AS2NoModuleException ex) {
// No message processor found
// Or no module found in message processor
}
} finally {
aConn.disconnect();
}
}
use of com.helger.mail.cte.EContentTransferEncoding in project as2-lib by phax.
the class BCCryptoHelperTest method testEncryptWithAllCTEs.
@Test
public void testEncryptWithAllCTEs() throws Exception {
final MimeBodyPart aPart = new MimeBodyPart();
aPart.setText("Hello world");
for (final EContentTransferEncoding eCTE : EContentTransferEncoding.values()) {
final MimeBodyPart aEncrypted = AS2Helper.getCryptoHelper().encrypt(aPart, CERT_ENCRYPT, ECryptoAlgorithmCrypt.CRYPT_AES256_GCM, eCTE);
assertNotNull(aEncrypted);
assertArrayEquals(new String[] { "application/pkcs7-mime; name=\"smime.p7m\"; smime-type=enveloped-data" }, aEncrypted.getHeader(CHttpHeader.CONTENT_TYPE));
assertArrayEquals(new String[] { "attachment; filename=\"smime.p7m\"" }, aEncrypted.getHeader(CHttpHeader.CONTENT_DISPOSITION));
}
}
use of com.helger.mail.cte.EContentTransferEncoding in project phase4 by phax.
the class MimeMessageCreator method generateMimeMessage.
@Nonnull
public static AS4MimeMessage generateMimeMessage(@Nonnull final ESoapVersion eSoapVersion, @Nonnull final Document aSoapEnvelope, @Nullable final ICommonsList<WSS4JAttachment> aEncryptedAttachments) throws MessagingException {
ValueEnforcer.notNull(eSoapVersion, "SoapVersion");
ValueEnforcer.notNull(aSoapEnvelope, "SoapEnvelope");
final Charset aCharset = AS4XMLHelper.XWS.getCharset();
final SoapMimeMultipart aMimeMultipart = new SoapMimeMultipart(eSoapVersion, aCharset);
final EContentTransferEncoding eCTE = EContentTransferEncoding.BINARY;
final String sContentType = eSoapVersion.getMimeType(aCharset).getAsString();
{
// Message Itself (repeatable)
final MimeBodyPart aMessagePart = new MimeBodyPart();
aMessagePart.setDataHandler(new DataHandler(new DOMSource(aSoapEnvelope), sContentType));
aMessagePart.setHeader(CHttpHeader.CONTENT_TRANSFER_ENCODING, eCTE.getID());
aMimeMultipart.addBodyPart(aMessagePart);
}
boolean bIsRepeatable = true;
if (aEncryptedAttachments != null)
for (final WSS4JAttachment aEncryptedAttachment : aEncryptedAttachments) {
aEncryptedAttachment.addToMimeMultipart(aMimeMultipart);
if (!aEncryptedAttachment.isRepeatable())
bIsRepeatable = false;
}
// Build main message
final AS4MimeMessage aMsg = new AS4MimeMessage((Session) null, bIsRepeatable);
aMsg.setContent(aMimeMultipart);
aMsg.saveChanges();
return aMsg;
}
use of com.helger.mail.cte.EContentTransferEncoding in project as2-lib by phax.
the class AS2SenderModule method handle.
public void handle(@Nonnull final String sAction, @Nonnull final IMessage aBaseMsg, @Nullable final Map<String, Object> aOptions) throws AS2Exception {
final AS2Message aMsg = (AS2Message) aBaseMsg;
if (LOGGER.isInfoEnabled())
LOGGER.info("Submitting message" + aMsg.getLoggingText());
// verify all required information is present for sending
checkRequired(aMsg);
final int nRetries = getRetryCount(aMsg.partnership(), aOptions);
try (final AS2ResourceHelper aResHelper = new AS2ResourceHelper()) {
// Get Content-Transfer-Encoding to use
final String sContentTransferEncoding = aMsg.partnership().getContentTransferEncodingSend(EContentTransferEncoding.AS2_DEFAULT.getID());
final EContentTransferEncoding eCTE = EContentTransferEncoding.getFromIDCaseInsensitiveOrDefault(sContentTransferEncoding, EContentTransferEncoding.AS2_DEFAULT);
// compress and/or sign and/or encrypt the message if needed
final MimeBodyPart aSecuredData = secure(aMsg, eCTE);
// Calculate MIC after compress/sign/crypt was handled, because the
// message data might change if compression before signing is active.
final MIC aMIC;
if (aMsg.isRequestingMDN())
aMIC = calculateAndStoreMIC(aMsg);
else
aMIC = null;
if (LOGGER.isDebugEnabled())
LOGGER.debug("Setting message content type to '" + aSecuredData.getContentType() + "'");
aMsg.setContentType(aSecuredData.getContentType());
try (final IHTTPOutgoingDumper aOutgoingDumper = getHttpOutgoingDumper(aMsg)) {
final IHTTPIncomingDumper aIncomingDumper = getEffectiveHttpIncomingDumper();
// Use no CTE, because it was set on all MIME parts
_sendViaHTTP(aMsg, aSecuredData, aMIC, true ? null : eCTE, aOutgoingDumper, aIncomingDumper, aResHelper);
}
} catch (final AS2HttpResponseException ex) {
if (LOGGER.isErrorEnabled())
LOGGER.error("Http Response Error " + ex.getMessage());
ex.terminate(aMsg);
if (!doResend(IProcessorSenderModule.DO_SEND, aMsg, ex, nRetries))
throw ex;
} catch (final IOException ex) {
// Re-send if a network error occurs during transmission
final AS2Exception wioe = WrappedAS2Exception.wrap(ex).setSourceMsg(aMsg).terminate();
if (!doResend(IProcessorSenderModule.DO_SEND, aMsg, wioe, nRetries))
throw wioe;
} catch (final Exception ex) {
// Propagate error if it can't be handled by a re-send
throw WrappedAS2Exception.wrap(ex);
}
}
use of com.helger.mail.cte.EContentTransferEncoding in project as2-lib by phax.
the class MainSendToMendelsonTestServerPlayground method main.
public static void main(final String[] args) throws Exception {
// Enable or disable debug mode
if (false)
GlobalDebug.setDebugModeDirect(false);
Proxy aHttpProxy = null;
if (false)
aHttpProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("172.30.9.6", 8080));
IHTTPOutgoingDumperFactory aOutgoingDumperFactory = null;
if (false)
aOutgoingDumperFactory = x -> new HTTPOutgoingDumperStreamBased(System.out);
if (false)
HTTPHelper.setHTTPIncomingDumperFactory(() -> new HTTPIncomingDumperStreamBased(new NonClosingOutputStream(System.out)));
// Start client configuration
final AS2ClientSettings aSettings = new AS2ClientSettings();
aSettings.setKeyStore(EKeyStoreType.PKCS12, new File("src/test/resources/mendelson/key3.pfx"), "test");
// Fixed sender
aSettings.setSenderData("mycompanyAS2", "phax.as2-lib@github.com", "key3");
// Fixed receiver - key alias must be "mendelsontestAS2"
aSettings.setReceiverData("mendelsontestAS2", "mendelsontestAS2", "http://testas2.mendelson-e-c.com:8080/as2/HttpReceiver");
final X509Certificate aReceiverCertificate = AS2KeyStoreHelper.readX509Certificate("src/test/resources/mendelson/key4.cer");
aSettings.setReceiverCertificate(aReceiverCertificate);
// AS2 stuff
aSettings.setPartnershipName(aSettings.getSenderAS2ID() + "_" + aSettings.getReceiverAS2ID());
// When a signed message is used, the algorithm for MIC and message must be
// identical
final ECryptoAlgorithmSign eSignAlgo = ECryptoAlgorithmSign.DIGEST_SHA1;
// Encryption is required for Mendelson
// CRYPT_AES256_GCM is not supported
// CRYPT_AES256_CBC is supported
// CRYPT_AES192_GCM is not supported
// CRYPT_AES192_CBC is supported
// CRYPT_AES128_GCM is not supported
// CRYPT_AES128_CBC is supported
// CRYPT_3DES is supported
final ECryptoAlgorithmCrypt eCryptAlgo = ECryptoAlgorithmCrypt.CRYPT_3DES;
final ECompressionType eCompress = ECompressionType.ZLIB;
final boolean bCompressBeforeSigning = true;
if (eSignAlgo != null)
aSettings.setMDNOptions(new DispositionOptions().setMICAlg(eSignAlgo).setMICAlgImportance(DispositionOptions.IMPORTANCE_REQUIRED).setProtocol(DispositionOptions.PROTOCOL_PKCS7_SIGNATURE).setProtocolImportance(DispositionOptions.IMPORTANCE_REQUIRED));
if (false)
aSettings.setMDNOptions("");
aSettings.setEncryptAndSign(eCryptAlgo, eSignAlgo);
aSettings.setCompress(eCompress, bCompressBeforeSigning);
aSettings.setMessageIDFormat("github-phax-as2-lib-$date.uuuuMMdd-HHmmssZ$-$rand.1234$@$msg.sender.as2_id$_$msg.receiver.as2_id$");
aSettings.setRetryCount(1);
aSettings.setConnectTimeoutMS(10_000);
aSettings.setReadTimeoutMS(10_000);
aSettings.setHttpOutgoingDumperFactory(aOutgoingDumperFactory);
// Build client request
final AS2ClientRequest aRequest = new AS2ClientRequest("AS2 test message from as2-lib");
if (false)
aRequest.setData(new File("src/test/resources/mendelson/testcontent.attachment"), StandardCharsets.ISO_8859_1);
else
aRequest.setData(new DataHandler(new FileDataSource(new File("src/test/resources/mendelson/testcontent.attachment"))));
aRequest.setContentType(CMimeType.TEXT_PLAIN.getAsString());
// "CTE" and "compress before sign" have impact on MIC matching
// EContentTransferEncoding._7BIT MIC is matched
// EContentTransferEncoding._8BIT MIC is matched
// EContentTransferEncoding.BINARY MIC is matched
// EContentTransferEncoding.QUOTED_PRINTABLE - not supported by Mendelson
// EContentTransferEncoding.BASE64 MIC is matched
aRequest.setContentTransferEncoding(EContentTransferEncoding.BASE64);
// Send message
final AS2ClientResponse aResponse = new AS2Client().setHttpProxy(aHttpProxy).sendSynchronous(aSettings, aRequest);
if (aResponse.hasException())
LOGGER.info(aResponse.getAsString());
LOGGER.info("Done");
}
Aggregations