Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
package org.openas2.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Header;
import javax.mail.MessagingException;
import javax.mail.internet.ContentType;
import javax.mail.internet.InternetHeaders;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openas2.DispositionException;
import org.openas2.OpenAS2Exception;
import org.openas2.Session;
import org.openas2.cert.CertificateFactory;
import org.openas2.lib.helper.BCCryptoHelper;
import org.openas2.lib.helper.ICryptoHelper;
import org.openas2.lib.message.AS2Standards;
import org.openas2.lib.util.MimeUtil;
import org.openas2.message.AS2Message;
import org.openas2.message.AS2MessageMDN;
import org.openas2.message.FileAttribute;
import org.openas2.message.Message;
import org.openas2.message.MessageMDN;
import org.openas2.params.CompositeParameters;
import org.openas2.params.DateParameters;
import org.openas2.params.InvalidParameterException;
import org.openas2.params.MessageMDNParameters;
import org.openas2.params.MessageParameters;
import org.openas2.params.ParameterParser;
import org.openas2.params.RandomParameters;
import org.openas2.partner.Partnership;
import org.openas2.processor.Processor;
import org.openas2.processor.msgtracking.BaseMsgTrackingModule;
import org.openas2.processor.resender.ResenderModule;
import org.openas2.processor.sender.SenderModule;
import org.openas2.processor.storage.StorageModule;
public class AS2Util {
private static ICryptoHelper ch;
public static ICryptoHelper getCryptoHelper() throws Exception {
if (ch == null) {
ch = new BCCryptoHelper();
ch.initialize();
}
return ch;
}
public static String generateMessageID(Message msg, boolean isMDN) throws InvalidParameterException
{
String idFormat = null;
CompositeParameters params =
new CompositeParameters(false).
add("date", new DateParameters()).
add("msg", new MessageParameters(msg)).
add("rand", new RandomParameters());
if (isMDN) {
params.add("mdn", new MessageMDNParameters(msg.getMDN()));
idFormat = msg.getPartnership().getAttributeOrProperty(Properties.AS2_MDN_MESSAGE_ID_FORMAT,null);
}
if (idFormat == null)
idFormat = msg.getPartnership().getAttributeOrProperty(Properties.AS2_MESSAGE_ID_FORMAT
, "");
String id = ParameterParser.parse(idFormat, params);
// RFC822 requires enclosing message in <> but AS2 spec provides for this to be overridden
String isEncap = msg.getPartnership().getAttributeOrProperty(Properties.AS2_MESSAGE_ID_ENCLOSE_IN_BRACKETS, "true");
if ("true".equalsIgnoreCase(isEncap)) {
// Add the angle brackets if not already added
if (!id.startsWith("<")) {
id = "<" + id;
}
if (!id.endsWith(">")) {
id = id + ">";
}
}
return id;
}
public static void parseMDN(Message msg, X509Certificate receiver) throws OpenAS2Exception
{
Log logger = LogFactory.getLog(AS2Util.class.getSimpleName());
MessageMDN mdn = msg.getMDN();
MimeBodyPart mainPart = mdn.getData();
if (logger.isTraceEnabled() && "true".equalsIgnoreCase(System.getProperty("logRxdMdnMimeBodyParts", "false")))
{
try {
logger.trace("Received MimeBodyPart for inbound MDN: " + msg.getLogMsgID()
+ "\n" + MimeUtil.toString(mainPart, true));
} catch (Exception e) {
logger.trace("Failed to log the MimeBodyPart as part of trace logging: " + e.getMessage());
}
}
try
{
ICryptoHelper ch = getCryptoHelper();
if (ch.isSigned(mainPart)) {
mainPart = getCryptoHelper().verifySignature(mainPart, receiver);
}
} catch (Exception e1)
{
logger.error("Error parsing MDN: " + org.openas2.logging.Log.getExceptionMsg(e1), e1);
throw new OpenAS2Exception("Failed to verify signature of received MDN.");
}
try
{
MimeMultipart reportParts = new MimeMultipart(mainPart.getDataHandler().getDataSource());
if (reportParts != null) {
ContentType reportType = new ContentType(reportParts.getContentType());
if (reportType.getBaseType().equalsIgnoreCase("multipart/report")) {
int reportCount = reportParts.getCount();
MimeBodyPart reportPart;
for (int j = 0; j < reportCount; j++) {
reportPart = (MimeBodyPart) reportParts.getBodyPart(j);
if (logger.isTraceEnabled() && "true".equalsIgnoreCase(System.getProperty("logRxdMdnMimeBodyParts", "false")))
{
logger.trace("Report MimeBodyPart from Multipart for inbound MDN: " + msg.getLogMsgID()
+ "\n" + MimeUtil.toString(reportPart, true));
}
if (reportPart.isMimeType("text/plain")) {
mdn.setText(reportPart.getContent().toString());
} else if (reportPart.isMimeType(AS2Standards.DISPOSITION_TYPE)) {
InternetHeaders disposition = new InternetHeaders(reportPart
.getInputStream());
mdn.setAttribute(AS2MessageMDN.MDNA_REPORTING_UA, disposition.getHeader(
"Reporting-UA", ", "));
mdn.setAttribute(AS2MessageMDN.MDNA_ORIG_RECIPIENT, disposition.getHeader(
"Original-Recipient", ", "));
mdn.setAttribute(AS2MessageMDN.MDNA_FINAL_RECIPIENT, disposition.getHeader(
"Final-Recipient", ", "));
mdn.setAttribute(AS2MessageMDN.MDNA_ORIG_MESSAGEID, disposition.getHeader(
"Original-Message-ID", ", "));
mdn.setAttribute(AS2MessageMDN.MDNA_DISPOSITION, disposition.getHeader(
"Disposition", ", "));
mdn.setAttribute(AS2MessageMDN.MDNA_MIC, disposition.getHeader(
"Received-Content-MIC", ", "));
}
}
}
}
} catch (Exception e)
{
throw new OpenAS2Exception("Filed to parse MDN: " + org.openas2.logging.Log.getExceptionMsg(e), e);
}
}
/**
* Verify disposition status is "processed" then check MIC is matched
* @param msg - the original message sent to the partner that the MDN relates to
* @throws DispositionException - something wrong t=with the Disposition structure
* @throws OpenAS2Exception - an internally handled error has occurred
* @return true if mdn processed
*/
public static boolean checkMDN(AS2Message msg) throws DispositionException, OpenAS2Exception {
Log logger = LogFactory.getLog(AS2Util.class.getSimpleName());
/*
* The sender may return an error in the disposition and not set the MIC
* so check disposition first
*/
String disposition = msg.getMDN().getAttribute(AS2MessageMDN.MDNA_DISPOSITION);
if (disposition != null && logger.isInfoEnabled())
logger.info("received MDN [" + disposition + "]" + msg.getLogMsgID());
boolean dispositionHasWarning = false;
try {
new DispositionType(disposition).validate();
} catch (DispositionException de) {
if (logger.isWarnEnabled()) logger.warn("Disposition exception on MDN. Disposition: " + disposition + msg.getLogMsgID(), de);
// Something wrong detected so flag it for later use
dispositionHasWarning = true;
de.setText(msg.getMDN().getText());
if ((de.getDisposition() != null) && de.getDisposition().isWarning()) {
// Do not throw error in this case ... just log it
de.addSource(OpenAS2Exception.SOURCE_MESSAGE, msg);
de.terminate();
} else {
throw de;
}
} catch (OpenAS2Exception e) {
msg.setLogMsg("Processing error occurred: " + org.openas2.logging.Log.getExceptionMsg(e));
logger.error(msg, e);
throw new OpenAS2Exception(e);
}
if ("none".equalsIgnoreCase(msg.getPartnership().getAttribute(Partnership.PA_AS2_MDN_OPTIONS))) {
// signed MDN not requested so...
return true;
}
if (logger.isTraceEnabled())
logger.trace("MIC processing start... ");
// get the returned mic from mdn object
String returnMIC = msg.getMDN().getAttribute(AS2MessageMDN.MDNA_MIC);
if (returnMIC == null || returnMIC.length() < 1) {
if (dispositionHasWarning)
{
// TODO: Think this should pribably throw error if MIC should have been returned but for now...
msg.setLogMsg("Returned MIC not found but disposition has warning so might be normal.");
logger.warn(msg);
}
else
{
msg.setLogMsg("Returned MIC not found so cannot validate returned message.");
logger.error(msg);
}
return false;
}
String calcMIC = msg.getCalculatedMIC();
if (calcMIC == null)
{
throw new OpenAS2Exception("The claculated MIC was not retrieved from the message object.");
}
if (logger.isTraceEnabled())
logger.trace("MIC check on calculated MIC: " + calcMIC + msg.getLogMsgID());
/* Returned-Content-MIC header and rfc822 headers can contain spaces all over the place.
* (not to mention comments!). Simple fix - delete all spaces.
* Since the partner could return the algorithm in different case to
* what was sent, remove the algorithm before compare
* The Algorithm is appended as a part of the MIC by adding a comma then
* optionally a space followed by the algorithm
*/
String regex = "^\\s*(\\S+)\\s*,\\s*(\\S+)\\s*$";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(returnMIC);
if (!m.find())
{
msg.setLogMsg("Invalid MIC format in returned MIC: " + returnMIC);
logger.error(msg);
throw new OpenAS2Exception("Invalid MIC string received. Forcing Resend");
}
String rMic = m.group(1);
String rMicAlg = m.group(2);
m = p.matcher(calcMIC);
if (!m.find())
{
msg.setLogMsg("Invalid MIC format in calculated MIC: " + calcMIC);
logger.error(msg);
throw new OpenAS2Exception("Invalid MIC string retrieved from calculated MIC. Forcing Resend");
}
String cMic = m.group(1);
String cMicAlg = m.group(2);
if (!cMicAlg.equalsIgnoreCase(rMicAlg)) {
// Appears not to match.... make sure dash is not the issue as in SHA-1 compared to SHA1
if (!cMicAlg.replaceAll("-", "").equalsIgnoreCase(rMicAlg.replaceAll("-", "")))
{
/*
* RFC 6362 specifies that the sent attachments should be
* considered invalid and retransmitted
*/
String errmsg = "MIC algorithm returned by partner is not the same as the algorithm requested but must be the same per RFC4130 section 7.4.3. Original MIC alg: "
+ cMicAlg
+ " ::: returned MIC alg: "
+ rMicAlg
+ "\n\t\tEnsure that Partner supports the requested algorithm and the \""
+ Partnership.PA_AS2_MDN_OPTIONS
+ "\" attribute for the outbound partnership uses the same algorithm as the \" +"
+ Partnership.PA_SIGNATURE_ALGORITHM
+ "\" attribute.";
throw new OpenAS2Exception(errmsg + " Forcing Resend");
}
}
if (!cMic.equals(rMic)) {
/* RFC 6362 specifies that the sent attachments should be considered invalid and retransmitted
*/
msg.setLogMsg("MIC not matched, original MIC: " + calcMIC + " return MIC: " + returnMIC);
logger.error(msg);
throw new OpenAS2Exception("MIC not matched. Forcing Resend");
}
if (logger.isTraceEnabled())
logger.trace("MIC is matched, received MIC: " + returnMIC + msg.getLogMsgID());
return true;
}
// How many times should this message be sent?
public static String retries(Map