getComponents();
/**
* Short-cut method to retrieve a partner factory.
*
* @return the currently registered PartnerFactory
component
- *
* @throws ComponentNotFound If a PartnerFactory
component has not been registered
- *
* @see PartnershipFactory
* @see Component
*/
- public PartnershipFactory getPartnershipFactory() throws ComponentNotFoundException;
+ PartnershipFactory getPartnershipFactory() throws ComponentNotFoundException;
/**
* Short-cut method to retrieve a processor.
*
* @return the currently registered Processor
component
- *
* @throws ComponentNotFound If a Processor
component has not been registered
- *
* @see Processor
* @see Component
*/
- public Processor getProcessor() throws ComponentNotFoundException;
-
- public String getBaseDirectory();
-
- public void setBaseDirectory(String dir);
-
- public String getAppVersion();
-
- public String getAppTitle();
+ Processor getProcessor() throws ComponentNotFoundException;
+
+ String getBaseDirectory();
+
+ String getAppVersion();
+
+ String getAppTitle();
}
diff --git a/Server/src/main/java/org/openas2/XMLSession.java b/Server/src/main/java/org/openas2/XMLSession.java
index 941ffccc..62b10dfa 100644
--- a/Server/src/main/java/org/openas2/XMLSession.java
+++ b/Server/src/main/java/org/openas2/XMLSession.java
@@ -5,26 +5,32 @@
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
+import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.openas2.app.OpenAS2Server;
import org.openas2.cert.CertificateFactory;
import org.openas2.cmd.CommandManager;
import org.openas2.cmd.CommandRegistry;
-import org.openas2.cmd.CommandRegistryFactory;
import org.openas2.cmd.processor.BaseCommandProcessor;
import org.openas2.logging.LogManager;
import org.openas2.logging.Logger;
import org.openas2.partner.PartnershipFactory;
import org.openas2.processor.Processor;
import org.openas2.processor.ProcessorModule;
+import org.openas2.schedule.SchedulerComponent;
import org.openas2.util.Properties;
import org.openas2.util.XMLUtil;
import org.w3c.dom.Document;
@@ -35,232 +41,292 @@
/**
* original author unknown
- *
+ *
* in this release added command registry methods
- * @author joseph mcverry
*
+ * @author joseph mcverry
*/
-public class XMLSession extends BaseSession implements CommandRegistryFactory {
- public static final String EL_PROPERTIES = "properties";
- public static final String EL_CERTIFICATES = "certificates";
- public static final String EL_CMDPROCESSOR = "commandProcessors";
- public static final String EL_PROCESSOR = "processor";
- public static final String EL_PARTNERSHIPS = "partnerships";
- public static final String EL_COMMANDS = "commands";
- public static final String EL_LOGGERS = "loggers";
- public static final String PARAM_BASE_DIRECTORY = "basedir";
- private CommandRegistry commandRegistry;
- private CommandManager cmdManager;
-
- private String VERSION;
- private String TITLE;
-
-
- public XMLSession(InputStream in) throws OpenAS2Exception,
- ParserConfigurationException, SAXException, IOException {
- super();
- load(in);
- }
-
- public XMLSession(String filename) throws OpenAS2Exception,
- ParserConfigurationException, SAXException, IOException {
- File file = new File(filename).getAbsoluteFile();
- setBaseDirectory(file.getParent());
- FileInputStream fin = new FileInputStream(file);
- try {
- load(fin);
- } finally {
- fin.close();
- }
- }
-
- public void setCommandRegistry(CommandRegistry registry) {
- commandRegistry = registry;
- }
-
- public CommandRegistry getCommandRegistry() {
- return commandRegistry;
- }
-
- protected void load(InputStream in) throws ParserConfigurationException,
- SAXException, IOException, OpenAS2Exception {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
-
- DocumentBuilder parser = factory.newDocumentBuilder();
- Document document = parser.parse(in);
- Element root = document.getDocumentElement();
-
- NodeList rootNodes = root.getChildNodes();
- Node rootNode;
- String nodeName;
-
- for (int i = 0; i < rootNodes.getLength(); i++) {
- rootNode = rootNodes.item(i);
-
- nodeName = rootNode.getNodeName();
-
- if (nodeName.equals(EL_PROPERTIES)) {
- loadProperties(rootNode);
- } else if (nodeName.equals(EL_CERTIFICATES)) {
- loadCertificates(rootNode);
- } else if (nodeName.equals(EL_PROCESSOR)) {
- loadProcessor(rootNode);
- } else if (nodeName.equals(EL_CMDPROCESSOR)) {
- loadCommandProcessors(rootNode);
- } else if (nodeName.equals(EL_PARTNERSHIPS)) {
- loadPartnerships(rootNode);
- } else if (nodeName.equals(EL_COMMANDS)) {
- loadCommands(rootNode);
- } else if (nodeName.equals(EL_LOGGERS)) {
- loadLoggers(rootNode);
- } else if (nodeName.equals("#text")) {
- // do nothing
- } else if (nodeName.equals("#comment")) {
- // do nothing
- } else {
- throw new OpenAS2Exception("Undefined tag: " + nodeName);
- }
- }
- }
-
- protected void loadProperties(Node propNode)
+public class XMLSession extends BaseSession {
+ private static final String EL_PROPERTIES = "properties";
+ private static final String EL_CERTIFICATES = "certificates";
+ private static final String EL_CMDPROCESSOR = "commandProcessors";
+ private static final String EL_PROCESSOR = "processor";
+ private static final String EL_PARTNERSHIPS = "partnerships";
+ private static final String EL_COMMANDS = "commands";
+ private static final String EL_LOGGERS = "loggers";
+ private static final String PARAM_BASE_DIRECTORY = "basedir";
+
+ private CommandRegistry commandRegistry;
+ private CommandManager cmdManager = new CommandManager();
+
+ private String VERSION;
+ private String TITLE;
+
+ private static final Log LOGGER = LogFactory.getLog(XMLSession.class.getSimpleName());
+
+ public XMLSession(String configAbsPath) throws OpenAS2Exception,
+ ParserConfigurationException, SAXException, IOException
+ {
+ File configXml = new File(configAbsPath);
+ File configDir = configXml.getParentFile();
+
+ FileInputStream configAsStream = new FileInputStream(configXml);
+ setBaseDirectory(configDir.getAbsolutePath());
+
+ load(configAsStream);
+
+ // scheduler should be initializer after all modules
+ addSchedulerComponent();
+ }
+
+ private void addSchedulerComponent() throws OpenAS2Exception
+ {
+ SchedulerComponent comp = new SchedulerComponent();
+ setComponent("scheduler", comp);
+ comp.init(this, Collections.emptyMap());
+ }
+
+
+ protected void load(InputStream in) throws ParserConfigurationException,
+ SAXException, IOException, OpenAS2Exception
+ {
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+
+ DocumentBuilder parser = factory.newDocumentBuilder();
+ Document document = parser.parse(in);
+ Element root = document.getDocumentElement();
+
+ NodeList rootNodes = root.getChildNodes();
+ Node rootNode;
+ String nodeName;
+
+ // this is used by all other objects to access global configs and functionality
+ LOGGER.info("Loading configuration...");
+ for (int i = 0; i < rootNodes.getLength(); i++)
+ {
+ rootNode = rootNodes.item(i);
+
+ nodeName = rootNode.getNodeName();
+
+ // enter the command processing loop
+ if (nodeName.equals(EL_PROPERTIES))
+ {
+ loadProperties(rootNode);
+ } else if (nodeName.equals(EL_CERTIFICATES))
+ {
+ loadCertificates(rootNode);
+ } else if (nodeName.equals(EL_PROCESSOR))
+ {
+ loadProcessor(rootNode);
+ } else if (nodeName.equals(EL_CMDPROCESSOR))
+ {
+ loadCommandProcessors(rootNode);
+ } else if (nodeName.equals(EL_PARTNERSHIPS))
+ {
+ loadPartnerships(rootNode);
+ } else if (nodeName.equals(EL_COMMANDS))
+ {
+ loadCommands(rootNode);
+ } else if (nodeName.equals(EL_LOGGERS))
+ {
+ loadLoggers(rootNode);
+ } else if (nodeName.equals("#text"))
+ {
+ // do nothing
+ } else if (nodeName.equals("#comment"))
+ {
+ // do nothing
+ } else
+ {
+ throw new OpenAS2Exception("Undefined tag: " + nodeName);
+ }
+ }
+
+ cmdManager.registerCommands(commandRegistry);
+ }
+
+ private void loadProperties(Node propNode)
+ {
+ LOGGER.info("Loading properties...");
+
+ Map properties = XMLUtil.mapAttributes(propNode, false);
+ // Make key things accessible via static object for things that do not have accesss to session object
+ properties.put(Properties.APP_TITLE_PROP, getAppTitle());
+ properties.put(Properties.APP_VERSION_PROP, getAppVersion());
+ Properties.setProperties(properties);
+ }
+
+ private void loadCertificates(Node rootNode) throws OpenAS2Exception
+ {
+ CertificateFactory certFx = (CertificateFactory) XMLUtil.getComponent(
+ rootNode, this);
+ setComponent(CertificateFactory.COMPID_CERTIFICATE_FACTORY, certFx);
+ }
+
+ private void loadCommands(Node rootNode) throws OpenAS2Exception
+ {
+ Component component = XMLUtil.getComponent(rootNode, this);
+ commandRegistry = (CommandRegistry) component;
+ }
+
+ private void loadLoggers(Node rootNode) throws OpenAS2Exception
+ {
+ LOGGER.info("Loading log manager(s)...");
+
+ LogManager manager = LogManager.getLogManager();
+ if (LogManager.isRegisteredWithApache())
+ {
+ ; // continue
+ } else
+ {
+ // if using the OpenAS2 loggers the log manager must registered with the jvm argument
+ // -Dorg.apache.commons.logging.Log=org.openas2.logging.Log
+ throw new OpenAS2Exception("the OpenAS2 loggers' log manager must registered with the jvm argument -Dorg.apache.commons.logging.Log=org.openas2.logging.Log");
+ }
+ NodeList loggers = rootNode.getChildNodes();
+ Node logger;
+
+ for (int i = 0; i < loggers.getLength(); i++)
+ {
+ logger = loggers.item(i);
+
+ if (logger.getNodeName().equals("logger"))
+ {
+ loadLogger(manager, logger);
+ }
+ }
+ }
+
+ private void loadLogger(LogManager manager, Node loggerNode)
+ throws OpenAS2Exception
+ {
+ Logger logger = (Logger) XMLUtil.getComponent(loggerNode, this);
+ manager.addLogger(logger);
+ }
+
+ private void loadCommandProcessors(Node rootNode) throws OpenAS2Exception
{
- Map properties = XMLUtil.mapAttributes(propNode);
- Properties.setProperties(properties);
+
+ // get a registry of Command objects, and add Commands for the Session
+ LOGGER.info("Loading command processor(s)...");
+
+ NodeList cmdProcessor = rootNode.getChildNodes();
+ Node processor;
+
+ for (int i = 0; i < cmdProcessor.getLength(); i++)
+ {
+ processor = cmdProcessor.item(i);
+
+ if (processor.getNodeName().equals("commandProcessor"))
+ {
+ loadCommandProcessor(cmdManager, processor);
+ }
+ }
+ }
+
+ private void loadCommandProcessor(CommandManager manager,
+ Node cmdPrcessorNode) throws OpenAS2Exception
+ {
+ BaseCommandProcessor cmdProcesor = (BaseCommandProcessor) XMLUtil
+ .getComponent(cmdPrcessorNode, this);
+ manager.addProcessor(cmdProcesor);
+
+ setComponent(cmdProcesor.getName(), cmdProcesor);
}
- protected void loadCertificates(Node rootNode) throws OpenAS2Exception {
- CertificateFactory certFx = (CertificateFactory) XMLUtil.getComponent(
- rootNode, this);
- setComponent(CertificateFactory.COMPID_CERTIFICATE_FACTORY, certFx);
- }
-
- protected void loadCommands(Node rootNode) throws OpenAS2Exception {
- CommandRegistry cmdReg = (CommandRegistry) XMLUtil.getComponent(
- rootNode, this);
- setCommandRegistry(cmdReg);
- }
-
- protected void loadLoggers(Node rootNode) throws OpenAS2Exception {
-
- LogManager manager = LogManager.getLogManager();
- if (LogManager.isRegisteredWithApache())
- ; // continue
- else {
- // if using the OpenAS2 loggers the log manager must registered with the jvm argument
- // -Dorg.apache.commons.logging.Log=org.openas2.logging.Log
- throw new OpenAS2Exception("the OpenAS2 loggers' log manager must registered with the jvm argument -Dorg.apache.commons.logging.Log=org.openas2.logging.Log");
- }
- NodeList loggers = rootNode.getChildNodes();
- Node logger;
-
- for (int i = 0; i < loggers.getLength(); i++) {
- logger = loggers.item(i);
-
- if (logger.getNodeName().equals("logger")) {
- loadLogger(manager, logger);
- }
- }
- }
-
- protected void loadLogger(LogManager manager, Node loggerNode)
- throws OpenAS2Exception {
- Logger logger = (Logger) XMLUtil.getComponent(loggerNode, this);
- manager.addLogger(logger);
- }
-
- protected void loadCommandProcessors(Node rootNode) throws OpenAS2Exception {
- cmdManager = CommandManager.getCmdManager();
-
- NodeList cmdProcessor = rootNode.getChildNodes();
- Node processor;
-
- for (int i = 0; i < cmdProcessor.getLength(); i++) {
- processor = cmdProcessor.item(i);
-
- if (processor.getNodeName().equals("commandProcessor")) {
- loadCommandProcessor(cmdManager, processor);
- }
- }
- }
-
- public CommandManager getCommandManager() {
- return cmdManager;
- }
-
- protected void loadCommandProcessor(CommandManager manager,
- Node cmdPrcessorNode) throws OpenAS2Exception {
- BaseCommandProcessor cmdProcesor = (BaseCommandProcessor) XMLUtil
- .getComponent(cmdPrcessorNode, this);
- manager.addProcessor(cmdProcesor);
- }
- protected void loadPartnerships(Node rootNode) throws OpenAS2Exception {
- PartnershipFactory partnerFx = (PartnershipFactory) XMLUtil
- .getComponent(rootNode, this);
- setComponent(PartnershipFactory.COMPID_PARTNERSHIP_FACTORY, partnerFx);
- }
-
- protected void loadProcessor(Node rootNode) throws OpenAS2Exception {
- Processor proc = (Processor) XMLUtil.getComponent(rootNode, this);
- setComponent(Processor.COMPID_PROCESSOR, proc);
-
- NodeList modules = rootNode.getChildNodes();
- Node module;
-
- for (int i = 0; i < modules.getLength(); i++) {
- module = modules.item(i);
-
- if (module.getNodeName().equals("module")) {
- loadProcessorModule(proc, module);
- }
- }
- }
-
- protected void loadProcessorModule(Processor proc, Node moduleNode)
- throws OpenAS2Exception {
- ProcessorModule procmod = (ProcessorModule) XMLUtil.getComponent(
- moduleNode, this);
- proc.getModules().add(procmod);
- }
-
- private String getManifestAttribValue(String attrib) {
- Enumeration> resEnum;
- try {
- resEnum = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
- while (resEnum.hasMoreElements()) {
- try {
- URL url = (URL)resEnum.nextElement();
- if (!url.getPath().contains("openas2")) continue;
- InputStream is = url.openStream();
- if (is != null) {
- Manifest manifest = new Manifest(is);
- Attributes mainAttribs = manifest.getMainAttributes();
- String value = mainAttribs.getValue(attrib);
- if(value != null) {
- return value;
- }
- }
- }
- catch (Exception e) {
- // Silently ignore wrong manifests on classpath?
- }
- }
- } catch (IOException e1) {
- // Silently ignore wrong manifests on classpath?
- }
- return null;
- }
-
- public String getAppVersion()
- {
- if (VERSION == null) VERSION = getManifestAttribValue("Implementation-Version");
- return VERSION;
- }
-
- public String getAppTitle()
- {
- if (TITLE == null) TITLE = getManifestAttribValue("Implementation-Title") + " v" + getAppVersion();
- return TITLE;
-
- }
+ private void loadPartnerships(Node rootNode) throws OpenAS2Exception
+ {
+ LOGGER.info("Loading partnerships...");
+
+ PartnershipFactory partnerFx = (PartnershipFactory) XMLUtil
+ .getComponent(rootNode, this);
+ setComponent(PartnershipFactory.COMPID_PARTNERSHIP_FACTORY, partnerFx);
+ }
+
+ private void loadProcessor(Node rootNode) throws OpenAS2Exception
+ {
+ Processor proc = (Processor) XMLUtil.getComponent(rootNode, this);
+ setComponent(Processor.COMPID_PROCESSOR, proc);
+
+ LOGGER.info("Loading processor modules...");
+
+ NodeList modules = rootNode.getChildNodes();
+ Node module;
+
+ for (int i = 0; i < modules.getLength(); i++)
+ {
+ module = modules.item(i);
+
+ if (module.getNodeName().equals("module"))
+ {
+ loadProcessorModule(proc, module);
+ }
+ }
+ }
+
+ private void loadProcessorModule(Processor proc, Node moduleNode)
+ throws OpenAS2Exception
+ {
+ ProcessorModule procmod = (ProcessorModule) XMLUtil.getComponent(
+ moduleNode, this);
+ proc.getModules().add(procmod);
+ }
+
+ @Nullable
+ private String getManifestAttribValue(@Nonnull String attrib)
+ {
+ Enumeration> resEnum;
+ try
+ {
+ resEnum = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
+ while (resEnum.hasMoreElements())
+ {
+ try
+ {
+ URL url = (URL) resEnum.nextElement();
+ if (!url.getPath().contains("openas2"))
+ {
+ continue;
+ }
+ InputStream is = url.openStream();
+ if (is != null)
+ {
+ Manifest manifest = new Manifest(is);
+ Attributes mainAttribs = manifest.getMainAttributes();
+ String value = mainAttribs.getValue(attrib);
+ if (value != null)
+ {
+ return value;
+ }
+ }
+ } catch (Exception e)
+ {
+ // Silently ignore wrong manifests on classpath?
+ }
+ }
+ } catch (IOException e1)
+ {
+ // Silently ignore wrong manifests on classpath?
+ }
+ return null;
+ }
+
+ public String getAppVersion()
+ {
+ if (VERSION == null)
+ {
+ VERSION = getManifestAttribValue("Implementation-Version");
+ }
+ return VERSION;
+ }
+
+ public String getAppTitle()
+ {
+ if (TITLE == null)
+ {
+ TITLE = getManifestAttribValue("Implementation-Title") + " v" + getAppVersion();
+ }
+ return TITLE;
+
+ }
}
diff --git a/Server/src/main/java/org/openas2/app/OpenAS2Server.java b/Server/src/main/java/org/openas2/app/OpenAS2Server.java
index be9c464e..5aad9c88 100644
--- a/Server/src/main/java/org/openas2/app/OpenAS2Server.java
+++ b/Server/src/main/java/org/openas2/app/OpenAS2Server.java
@@ -1,155 +1,117 @@
package org.openas2.app;
-import java.io.BufferedWriter;
import java.io.File;
-import java.io.OutputStreamWriter;
-import java.util.List;
+
+import javax.annotation.Nonnull;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openas2.OpenAS2Exception;
+import org.openas2.Session;
import org.openas2.XMLSession;
-import org.openas2.cmd.CommandManager;
-import org.openas2.cmd.CommandRegistry;
-import org.openas2.cmd.processor.BaseCommandProcessor;
-/**
+/**
* original author unknown
- *
+ *
* in this release added ability to have multiple command processors
- * @author joseph mcverry
*
*/
public class OpenAS2Server {
- protected BufferedWriter sysOut;
- BaseCommandProcessor cmd = null;
- XMLSession session = null;
+ private static final Log LOGGER = LogFactory.getLog(OpenAS2Server.class.getSimpleName());
+
+ @Nonnull
+ private final Session session;
+
+
+ public OpenAS2Server(@Nonnull Session session)
+ {
+ this.session = session;
+ }
+
+
+ public static void main(String[] args) throws Exception
+ {
+ new OpenAS2Server.Builder()
+ .registerShutdownHook()
+ .run(args);
+ }
-
- public static void main(String[] args) {
- OpenAS2Server server = new OpenAS2Server();
- server.start(args);
- }
+ private void start() throws Exception
+ {
+ LOGGER.info("Starting " + session.getAppTitle() + "...");
+ session.start();
+ LOGGER.info(session.getAppTitle() + " started.");
+ }
- public void start(String[] args) {
- int exitStatus = 0;
+ public void shutdown()
+ {
+ try
+ {
+ session.getProcessor().stopActiveModules();
+ } catch (OpenAS2Exception same)
+ {
+ same.terminate();
+ }
+
+ LOGGER.info("OpenAS2 has shut down\r\n");
+ }
- Runtime.getRuntime().addShutdownHook(new Thread()
+ public static class Builder {
+ private boolean registerShutdownHook;
+
+ @Nonnull
+ private static File findConfig(@Nonnull String[] runArgs) throws Exception
{
- @Override
- public void run()
+ LOGGER.info("Retrieving config file...");
+ // Check for passed in as parameter first then look for system property
+ String configFile = (runArgs.length > 0) ? runArgs[0] : System.getProperty("openas2.config.file");
+ if (configFile == null || configFile.length() < 1)
+ {
+ // Try the default location assuming the app was started in the bin folder
+ configFile = System.getProperty("user.dir") + "/../config/config.xml";
+ }
+ File cfg = new File(configFile);
+ if (!cfg.exists())
{
- shutdown();
- System.out.println("Shutdown due to process interruption!");
+ LOGGER.error("No config file found: " + configFile);
+ LOGGER.error("Pass as the first paramter on the command line or set the system property \"openas2.config.file\" to identify the configuration file to start OpenAS2");
+ throw new Exception("Missing configuration file");
}
- });
- try {
- Log logger = LogFactory.getLog(OpenAS2Server.class.getSimpleName());
-
- write("Retrieving config file..." + System.getProperty("line.separator"));
- // Check for passed in as parameter first then look for system property
- String configFile = (args.length > 0)?args[0]:System.getProperty("openas2.config.file");
- if (configFile == null || configFile.length() < 1) {
- // Try the default location assuming the app was started in the bin folder
- configFile = System.getProperty("user.dir") + "/../config/config.xml";
- }
- File cfg = new File(configFile);
- if (!cfg.exists()) {
- write("No config file found: " + configFile + System.getProperty("line.separator"));
- write("Pass as the first paramter on the command line or set the system property \"openas2.config.file\" to identify the configuration file to start OpenAS2" + System.getProperty("line.separator"));
- throw new Exception("Missing configuration file");
- }
- session = new XMLSession(configFile);
-
- write("Starting Server..." + System.getProperty("line.separator"));
-
- // create the OpenAS2 Session object
- // this is used by all other objects to access global configs and functionality
- write("Loading configuration..." + System.getProperty("line.separator"));
-
- write(session.getAppTitle() + ": Session instantiated." + System.getProperty("line.separator"));
- // create a command processor
-
- // get a registry of Command objects, and add Commands for the Session
- write("Registering Session to Command Processor..." + System.getProperty("line.separator"));
-
- CommandRegistry reg = session.getCommandRegistry();
-
- // start the active processor modules
- write("Starting Active Modules..." + System.getProperty("line.separator"));
- session.getProcessor().startActiveModules();
-
- // enter the command processing loop
- write(session.getAppTitle() + " Started" + System.getProperty("line.separator"));
-
-
- logger.info("- OpenAS2 Started - V" + session.getAppVersion());
-
- CommandManager cmdMgr = session.getCommandManager();
- List processors = cmdMgr.getProcessors();
- for (int i = 0; i < processors.size(); i++) {
- write("Loading Command Processor..." + processors.toString()
- + System.getProperty("line.separator"));
- cmd = (BaseCommandProcessor) processors.get(i);
- cmd.init();
- cmd.addCommands(reg);
- cmd.start();
- }
- breakOut : while (true) {
- for (int i = 0; i < processors.size(); i++) {
- cmd = (BaseCommandProcessor) processors.get(i);
- if (cmd.isTerminated())
- break breakOut;
- Thread.sleep(100);
- }
- }
- logger.info("- OpenAS2 Stopped -");
- } catch (Exception e) {
- exitStatus = -1;
- e.printStackTrace();
- } catch (Error err) {
- exitStatus = -1;
- err.printStackTrace();
- } finally {
- shutdown();
- System.exit(exitStatus);
- }
- }
-
- public void shutdown()
- {
- if (session != null) {
- try {
- session.getProcessor().stopActiveModules();
- } catch (OpenAS2Exception same) {
- same.terminate();
- }
- }
-
- if (cmd != null) {
- try {
- cmd.deInit();
- } catch (OpenAS2Exception cdie) {
- cdie.terminate();
- }
- }
-
- write("OpenAS2 has shut down\r\n");
-
-
- }
-
- public void write(String msg) {
- if (sysOut == null) {
- sysOut = new BufferedWriter(new OutputStreamWriter(System.out));
- }
-
- try {
- sysOut.write(msg);
- sysOut.flush();
- } catch (java.io.IOException e) {
- e.printStackTrace();
- }
- }
+ return cfg;
+ }
+
+ public OpenAS2Server run(String... args) throws Exception
+ {
+
+ XMLSession session = new XMLSession(findConfig(args).getAbsolutePath());
+ final OpenAS2Server server = new OpenAS2Server(session);
+
+ registerShutdownHookIfNeeded(server);
+
+ server.start();
+ return server;
+ }
+
+ private void registerShutdownHookIfNeeded(final OpenAS2Server server)
+ {
+ if (registerShutdownHook)
+ {
+ Runtime.getRuntime().addShutdownHook(new Thread() {
+ @Override
+ public void run()
+ {
+ server.shutdown();
+ }
+ });
+ LOGGER.info("Shutdown hook registered.");
+ }
+ }
+
+ public Builder registerShutdownHook()
+ {
+ this.registerShutdownHook = true;
+ return this;
+ }
+ }
}
diff --git a/Server/src/main/java/org/openas2/cert/PKCS12CertificateFactory.java b/Server/src/main/java/org/openas2/cert/PKCS12CertificateFactory.java
index 480db371..1d5e94ed 100644
--- a/Server/src/main/java/org/openas2/cert/PKCS12CertificateFactory.java
+++ b/Server/src/main/java/org/openas2/cert/PKCS12CertificateFactory.java
@@ -16,6 +16,8 @@
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -27,351 +29,398 @@
import org.openas2.params.InvalidParameterException;
import org.openas2.partner.Partnership;
import org.openas2.partner.SecurePartnership;
+import org.openas2.schedule.HasSchedule;
+import org.openas2.support.FileMonitorAdapter;
import org.openas2.util.AS2Util;
-import org.openas2.util.FileMonitor;
-import org.openas2.util.FileMonitorListener;
public class PKCS12CertificateFactory extends BaseCertificateFactory implements
AliasedCertificateFactory, KeyStoreCertificateFactory, StorableCertificateFactory,
- FileMonitorListener {
+ HasSchedule {
public static final String PARAM_FILENAME = "filename";
public static final String PARAM_PASSWORD = "password";
public static final String PARAM_INTERVAL = "interval";
- private FileMonitor fileMonitor;
private KeyStore keyStore;
- private Log logger = LogFactory.getLog(PKCS12CertificateFactory.class.getSimpleName());
-
- public String getAlias(Partnership partnership, String partnershipType) throws OpenAS2Exception {
+ private Log logger = LogFactory.getLog(PKCS12CertificateFactory.class.getSimpleName());
+
+ public String getAlias(Partnership partnership, String partnershipType) throws OpenAS2Exception
+ {
String alias = null;
- if (partnershipType == Partnership.PTYPE_RECEIVER) {
+ if (partnershipType == Partnership.PTYPE_RECEIVER)
+ {
alias = partnership.getReceiverID(SecurePartnership.PID_X509_ALIAS);
- } else if (partnershipType == Partnership.PTYPE_SENDER) {
+ } else if (partnershipType == Partnership.PTYPE_SENDER)
+ {
alias = partnership.getSenderID(SecurePartnership.PID_X509_ALIAS);
}
- if (alias == null) {
+ if (alias == null)
+ {
throw new CertificateNotFoundException(partnershipType, null);
}
return alias;
}
- public X509Certificate getCertificate(String alias) throws OpenAS2Exception {
- try {
+ public X509Certificate getCertificate(String alias) throws OpenAS2Exception
+ {
+ try
+ {
KeyStore ks = getKeyStore();
X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
- if (cert == null) {
+ if (cert == null)
+ {
throw new CertificateNotFoundException(null, alias);
}
return cert;
- } catch (KeyStoreException kse) {
+ } catch (KeyStoreException kse)
+ {
throw new WrappedException(kse);
}
}
public X509Certificate getCertificate(Message msg, String partnershipType)
- throws OpenAS2Exception {
- try {
+ throws OpenAS2Exception
+ {
+ try
+ {
return getCertificate(getAlias(msg.getPartnership(), partnershipType));
- } catch (CertificateNotFoundException cnfe) {
+ } catch (CertificateNotFoundException cnfe)
+ {
cnfe.setPartnershipType(partnershipType);
throw cnfe;
}
}
public X509Certificate getCertificate(MessageMDN mdn, String partnershipType)
- throws OpenAS2Exception {
- try {
+ throws OpenAS2Exception
+ {
+ try
+ {
return getCertificate(getAlias(mdn.getPartnership(), partnershipType));
- } catch (CertificateNotFoundException cnfe) {
+ } catch (CertificateNotFoundException cnfe)
+ {
cnfe.setPartnershipType(partnershipType);
throw cnfe;
}
}
- public Map getCertificates() throws OpenAS2Exception {
+ public Map getCertificates() throws OpenAS2Exception
+ {
KeyStore ks = getKeyStore();
- try {
- Map certs = new HashMap();
+ try
+ {
+ Map certs = new HashMap();
String certAlias;
Enumeration e = ks.aliases();
- while (e.hasMoreElements()) {
- certAlias = (String) e.nextElement();
+ while (e.hasMoreElements())
+ {
+ certAlias = e.nextElement();
certs.put(certAlias, (X509Certificate) ks.getCertificate(certAlias));
}
return certs;
- } catch (GeneralSecurityException gse) {
+ } catch (GeneralSecurityException gse)
+ {
throw new WrappedException(gse);
}
}
- public void setFileMonitor(FileMonitor fileMonitor) {
- this.fileMonitor = fileMonitor;
+ private int getRefreshInterval() throws InvalidParameterException
+ {
+ return getParameterInt(PARAM_INTERVAL, false);
}
- public FileMonitor getFileMonitor() throws InvalidParameterException {
- boolean createMonitor = ((fileMonitor == null) && (getParameter(PARAM_INTERVAL, false) != null));
-
- if (!createMonitor && fileMonitor != null) {
- String filename = fileMonitor.getFilename();
- createMonitor = ((filename != null) && !filename.equals(getFilename()));
- }
-
- if (createMonitor) {
- if (fileMonitor != null) {
- fileMonitor.stop();
- }
-
- int interval = getParameterInt(PARAM_INTERVAL, true);
- File file = new File(getFilename());
- fileMonitor = new FileMonitor(file, interval);
- fileMonitor.addListener(this);
- }
-
- return fileMonitor;
+ public String getFilename() throws InvalidParameterException
+ {
+ return getParameter(PARAM_FILENAME, true);
}
- public void setFilename(String filename) {
+ public void setFilename(String filename)
+ {
getParameters().put(PARAM_FILENAME, filename);
}
- public String getFilename() throws InvalidParameterException {
- return getParameter(PARAM_FILENAME, true);
+ public KeyStore getKeyStore()
+ {
+ return keyStore;
}
- public void setKeyStore(KeyStore keyStore) {
+ public void setKeyStore(KeyStore keyStore)
+ {
this.keyStore = keyStore;
}
- public KeyStore getKeyStore() {
- return keyStore;
+ public char[] getPassword() throws InvalidParameterException
+ {
+ return getParameter(PARAM_PASSWORD, true).toCharArray();
}
- public void setPassword(char[] password) {
+ public void setPassword(char[] password)
+ {
getParameters().put(PARAM_PASSWORD, new String(password));
}
- public char[] getPassword() throws InvalidParameterException {
- return getParameter(PARAM_PASSWORD, true).toCharArray();
- }
-
- public PrivateKey getPrivateKey(X509Certificate cert) throws OpenAS2Exception {
+ private PrivateKey getPrivateKey(X509Certificate cert) throws OpenAS2Exception
+ {
KeyStore ks = getKeyStore();
String alias = null;
- try {
+ try
+ {
alias = ks.getCertificateAlias(cert);
- if (alias == null) {
+ if (alias == null)
+ {
throw new KeyNotFoundException(cert, "-- alias null from getCertificateAlias(cert) call");
}
PrivateKey key = (PrivateKey) ks.getKey(alias, getPassword());
- if (key == null) {
+ if (key == null)
+ {
throw new KeyNotFoundException(cert, "-- key null from getKey(" + alias + ") call");
}
return key;
- } catch (GeneralSecurityException e) {
+ } catch (GeneralSecurityException e)
+ {
throw new KeyNotFoundException(cert, alias, e);
}
}
- public PrivateKey getPrivateKey(Message msg, X509Certificate cert) throws OpenAS2Exception {
+ public PrivateKey getPrivateKey(Message msg, X509Certificate cert) throws OpenAS2Exception
+ {
return getPrivateKey(cert);
}
- public PrivateKey getPrivateKey(MessageMDN mdn, X509Certificate cert) throws OpenAS2Exception {
+ public PrivateKey getPrivateKey(MessageMDN mdn, X509Certificate cert) throws OpenAS2Exception
+ {
return getPrivateKey(cert);
}
public void addCertificate(String alias, X509Certificate cert, boolean overwrite)
- throws OpenAS2Exception {
+ throws OpenAS2Exception
+ {
KeyStore ks = getKeyStore();
- try {
- if (ks.containsAlias(alias) && !overwrite) {
+ try
+ {
+ if (ks.containsAlias(alias) && !overwrite)
+ {
throw new CertificateExistsException(alias);
}
ks.setCertificateEntry(alias, cert);
save(getFilename(), getPassword());
- } catch (GeneralSecurityException gse) {
+ } catch (GeneralSecurityException gse)
+ {
throw new WrappedException(gse);
}
}
- public void addPrivateKey(String alias, Key key, String password) throws OpenAS2Exception {
+ public void addPrivateKey(String alias, Key key, String password) throws OpenAS2Exception
+ {
KeyStore ks = getKeyStore();
- try {
- if (!ks.containsAlias(alias)) {
+ try
+ {
+ if (!ks.containsAlias(alias))
+ {
throw new CertificateNotFoundException(null, alias);
}
Certificate[] certChain = ks.getCertificateChain(alias);
if (certChain == null)
{
- X509Certificate x509cert = (X509Certificate)ks.getCertificate(alias);
- if (x509cert.getSubjectDN().equals(x509cert.getIssuerDN()))
+ X509Certificate x509cert = (X509Certificate) ks.getCertificate(alias);
+ if (x509cert.getSubjectDN().equals(x509cert.getIssuerDN()))
{
- // Trust chain is to itself
- certChain = new X509Certificate[] { x509cert, x509cert };
- if (logger.isInfoEnabled()) logger.info("Detected self-signed certificate and allowed import. Alias: " + alias);
+ // Trust chain is to itself
+ certChain = new X509Certificate[]{x509cert, x509cert};
+ if (logger.isInfoEnabled())
+ {
+ logger.info("Detected self-signed certificate and allowed import. Alias: " + alias);
+ }
}
}
ks.setKeyEntry(alias, key, password.toCharArray(), certChain);
save(getFilename(), getPassword());
- } catch (GeneralSecurityException gse) {
+ } catch (GeneralSecurityException gse)
+ {
throw new WrappedException(gse);
}
}
- public void clearCertificates() throws OpenAS2Exception {
+ public void clearCertificates() throws OpenAS2Exception
+ {
KeyStore ks = getKeyStore();
- try {
+ try
+ {
Enumeration aliases = ks.aliases();
- while (aliases.hasMoreElements()) {
- ks.deleteEntry((String) aliases.nextElement());
+ while (aliases.hasMoreElements())
+ {
+ ks.deleteEntry(aliases.nextElement());
}
save(getFilename(), getPassword());
- } catch (GeneralSecurityException gse) {
+ } catch (GeneralSecurityException gse)
+ {
throw new WrappedException(gse);
}
}
- public void handle(FileMonitor monitor, File file, int eventID) {
- switch (eventID) {
- case FileMonitorListener.EVENT_MODIFIED:
-
- try {
- load();
- logger.info("- Certificates Reloaded -");
- } catch (OpenAS2Exception oae) {
- oae.terminate();
- }
-
- break;
- }
- }
-
- public void init(Session session, Map options) throws OpenAS2Exception {
+ public void init(Session session, Map options) throws OpenAS2Exception
+ {
super.init(session, options);
-
+
// Override the password if it was passed as a system property
String pwd = System.getProperty("org.openas2.cert.Password");
if (pwd != null)
{
- setPassword(pwd.toCharArray());
+ setPassword(pwd.toCharArray());
}
- try {
+ try
+ {
this.keyStore = AS2Util.getCryptoHelper().getKeyStore();
- } catch (Exception e) {
+ } catch (Exception e)
+ {
throw new WrappedException(e);
}
-
- load(getFilename(), getPassword());
+ load();
}
- public void load(String filename, char[] password) throws OpenAS2Exception {
- try {
+ public void load(String filename, char[] password) throws OpenAS2Exception
+ {
+ try
+ {
FileInputStream fIn = new FileInputStream(filename);
load(fIn, password);
fIn.close();
- } catch (IOException ioe) {
+ } catch (IOException ioe)
+ {
throw new WrappedException(ioe);
}
}
- public void load(InputStream in, char[] password) throws OpenAS2Exception {
- try {
+ public void load(InputStream in, char[] password) throws OpenAS2Exception
+ {
+ try
+ {
KeyStore ks = getKeyStore();
- synchronized (ks) {
+ synchronized (ks)
+ {
ks.load(in, password);
}
-
- getFileMonitor();
- } catch (IOException ioe) {
+ } catch (IOException ioe)
+ {
throw new WrappedException(ioe);
- } catch (GeneralSecurityException gse) {
+ } catch (GeneralSecurityException gse)
+ {
throw new WrappedException(gse);
}
}
- public void load() throws OpenAS2Exception {
+ public void load() throws OpenAS2Exception
+ {
load(getFilename(), getPassword());
}
- public void removeCertificate(X509Certificate cert) throws OpenAS2Exception {
+ public void removeCertificate(X509Certificate cert) throws OpenAS2Exception
+ {
KeyStore ks = getKeyStore();
- try {
+ try
+ {
String alias = ks.getCertificateAlias(cert);
- if (alias == null) {
+ if (alias == null)
+ {
throw new CertificateNotFoundException(cert);
}
removeCertificate(alias);
- } catch (GeneralSecurityException gse) {
+ } catch (GeneralSecurityException gse)
+ {
throw new WrappedException(gse);
}
}
- public void removeCertificate(String alias) throws OpenAS2Exception {
+ public void removeCertificate(String alias) throws OpenAS2Exception
+ {
KeyStore ks = getKeyStore();
- try {
- if (ks.getCertificate(alias) == null) {
+ try
+ {
+ if (ks.getCertificate(alias) == null)
+ {
throw new CertificateNotFoundException(null, alias);
}
ks.deleteEntry(alias);
save(getFilename(), getPassword());
- } catch (GeneralSecurityException gse) {
+ } catch (GeneralSecurityException gse)
+ {
throw new WrappedException(gse);
}
}
- public void save() throws OpenAS2Exception {
+ public void save() throws OpenAS2Exception
+ {
save(getFilename(), getPassword());
}
- public void save(String filename, char[] password) throws OpenAS2Exception {
- try {
+ public void save(String filename, char[] password) throws OpenAS2Exception
+ {
+ try
+ {
FileOutputStream fOut = new FileOutputStream(filename, false);
save(fOut, password);
fOut.close();
- } catch (IOException ioe) {
+ } catch (IOException ioe)
+ {
throw new WrappedException(ioe);
}
}
- public void save(OutputStream out, char[] password) throws OpenAS2Exception {
- try {
+ public void save(OutputStream out, char[] password) throws OpenAS2Exception
+ {
+ try
+ {
getKeyStore().store(out, password);
- } catch (IOException ioe) {
+ } catch (IOException ioe)
+ {
throw new WrappedException(ioe);
- } catch (GeneralSecurityException gse) {
+ } catch (GeneralSecurityException gse)
+ {
throw new WrappedException(gse);
}
}
+
+ @Override
+ public void schedule(ScheduledExecutorService executor) throws OpenAS2Exception
+ {
+ new FileMonitorAdapter() {
+ @Override
+ public void onConfigFileChanged() throws OpenAS2Exception
+ {
+ load();
+ logger.info("- Certificates Reloaded -");
+ }
+ }.scheduleIfNeed(executor, new File(getFilename()), getRefreshInterval(), TimeUnit.SECONDS);
+ }
}
\ No newline at end of file
diff --git a/Server/src/main/java/org/openas2/cmd/BaseCommand.java b/Server/src/main/java/org/openas2/cmd/BaseCommand.java
index c6345af1..1c97c318 100644
--- a/Server/src/main/java/org/openas2/cmd/BaseCommand.java
+++ b/Server/src/main/java/org/openas2/cmd/BaseCommand.java
@@ -11,60 +11,78 @@
public abstract class BaseCommand extends BaseComponent implements Command {
public static final String PARAM_NAME = "name";
public static final String PARAM_DESCRIPTION = "description";
- public static final String PARAM_USAGE = "usage";
-
- public void init(Session session, Map parameters) throws OpenAS2Exception {
- super.init(session, parameters);
- if (getName() == null) {
- setName(getDefaultName());
- };
- if (getDescription() == null) {
- setDescription(getDefaultDescription());
- }
- if (getUsage() == null) {
- setUsage(getDefaultUsage());
- }
- }
+ public static final String PARAM_USAGE = "usage";
- public String getDescription() {
- try {
+ public void init(Session session, Map parameters) throws OpenAS2Exception
+ {
+ super.init(session, parameters);
+ if (getName() == null)
+ {
+ setName(getDefaultName());
+ }
+ if (getDescription() == null)
+ {
+ setDescription(getDefaultDescription());
+ }
+ if (getUsage() == null)
+ {
+ setUsage(getDefaultUsage());
+ }
+ }
+
+ public String getDescription()
+ {
+ try
+ {
return getParameter(PARAM_DESCRIPTION, false);
- } catch (InvalidParameterException e) {
+ } catch (InvalidParameterException e)
+ {
return null;
}
}
- public String getName() {
- try {
- return getParameter(PARAM_NAME, false);
- } catch (InvalidParameterException e) {
- return null;
- }
+ public void setDescription(String desc)
+ {
+ setParameter(PARAM_DESCRIPTION, desc);
}
- public String getUsage() {
- try {
- return getParameter(PARAM_USAGE, false);
- } catch (InvalidParameterException e) {
- return null;
- }
+ public String getName()
+ {
+ try
+ {
+ return getParameter(PARAM_NAME, false);
+ } catch (InvalidParameterException e)
+ {
+ return null;
+ }
}
-
- public abstract String getDefaultName();
- public abstract String getDefaultDescription();
- public abstract String getDefaultUsage();
-
- public abstract CommandResult execute(Object[] params);
- public void setDescription(String desc) {
- setParameter(PARAM_DESCRIPTION, desc);
+ public void setName(String name)
+ {
+ setParameter(PARAM_NAME, name);
}
- public void setName(String name) {
- setParameter(PARAM_NAME, name);
+ public String getUsage()
+ {
+ try
+ {
+ return getParameter(PARAM_USAGE, false);
+ } catch (InvalidParameterException e)
+ {
+ return null;
+ }
}
- public void setUsage(String usage) {
+ public void setUsage(String usage)
+ {
setParameter(PARAM_USAGE, usage);
}
+
+ public abstract String getDefaultName();
+
+ public abstract String getDefaultDescription();
+
+ public abstract String getDefaultUsage();
+
+ public abstract CommandResult execute(Object[] params);
}
diff --git a/Server/src/main/java/org/openas2/cmd/BaseCommandRegistry.java b/Server/src/main/java/org/openas2/cmd/BaseCommandRegistry.java
index 6eecf6c7..70c8f557 100644
--- a/Server/src/main/java/org/openas2/cmd/BaseCommandRegistry.java
+++ b/Server/src/main/java/org/openas2/cmd/BaseCommandRegistry.java
@@ -1,22 +1,21 @@
package org.openas2.cmd;
-import java.util.ArrayList;
+import java.util.LinkedList;
import java.util.List;
import org.openas2.BaseComponent;
public class BaseCommandRegistry extends BaseComponent implements CommandRegistry {
- private List commands;
-
- public List getCommands() {
- if (commands == null) {
- commands = new ArrayList();
- }
- return commands;
- }
+ private List commands = new LinkedList();
+
+ public List getCommands()
+ {
+ return commands;
+ }
+
+ public void setCommands(List commands)
+ {
+ this.commands = commands;
+ }
- public void setCommands(List commands) {
- this.commands = commands;
- }
-
}
diff --git a/Server/src/main/java/org/openas2/cmd/CommandManager.java b/Server/src/main/java/org/openas2/cmd/CommandManager.java
index 41fa9b7e..58bca817 100644
--- a/Server/src/main/java/org/openas2/cmd/CommandManager.java
+++ b/Server/src/main/java/org/openas2/cmd/CommandManager.java
@@ -3,41 +3,28 @@
import java.util.ArrayList;
import java.util.List;
+import org.openas2.OpenAS2Exception;
import org.openas2.cmd.processor.BaseCommandProcessor;
/**
* command calls the registered command processors
- *
- * @author joseph mcverry
*
+ * @author joseph mcverry
*/
public class CommandManager {
- private static CommandManager defaultManager;
- private List processors;
-
- public static CommandManager getCmdManager() {
- if (defaultManager == null) {
- defaultManager = new CommandManager();
- }
-
- return defaultManager;
- }
-
- public void setProcessors(List listeners) {
- this.processors = listeners;
- }
-
- public List getProcessors() {
- if (processors == null) {
- processors = new ArrayList();
- }
- return processors;
- }
+ private List processors = new ArrayList();
- public void addProcessor(BaseCommandProcessor processor) {
- List processors = getProcessors();
- processors.add(processor);
- }
+ public void addProcessor(BaseCommandProcessor processor)
+ {
+ processors.add(processor);
+ }
+ public void registerCommands(CommandRegistry reg) throws OpenAS2Exception
+ {
+ for (BaseCommandProcessor processor : processors)
+ {
+ processor.addCommands(reg);
+ }
+ }
}
diff --git a/Server/src/main/java/org/openas2/cmd/CommandRegistryFactory.java b/Server/src/main/java/org/openas2/cmd/CommandRegistryFactory.java
deleted file mode 100644
index 770c437b..00000000
--- a/Server/src/main/java/org/openas2/cmd/CommandRegistryFactory.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package org.openas2.cmd;
-
-public interface CommandRegistryFactory {
- public CommandRegistry getCommandRegistry();
-}
diff --git a/Server/src/main/java/org/openas2/cmd/MultiCommand.java b/Server/src/main/java/org/openas2/cmd/MultiCommand.java
index f4f7fc5d..bbfc218e 100644
--- a/Server/src/main/java/org/openas2/cmd/MultiCommand.java
+++ b/Server/src/main/java/org/openas2/cmd/MultiCommand.java
@@ -28,7 +28,7 @@ public Command getCommand(String name) {
Command cmd;
for (int i = 0; i < commands.size(); i++) {
- cmd = (Command) commands.get(i);
+ cmd = commands.get(i);
if (cmd.getName().equals(name)) {
return cmd;
diff --git a/Server/src/main/java/org/openas2/cmd/XMLCommandRegistry.java b/Server/src/main/java/org/openas2/cmd/XMLCommandRegistry.java
index e4b4983d..fea92253 100644
--- a/Server/src/main/java/org/openas2/cmd/XMLCommandRegistry.java
+++ b/Server/src/main/java/org/openas2/cmd/XMLCommandRegistry.java
@@ -4,7 +4,6 @@
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
-
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
@@ -12,6 +11,7 @@
import org.openas2.OpenAS2Exception;
import org.openas2.Session;
import org.openas2.WrappedException;
+import org.openas2.XMLSession;
import org.openas2.util.XMLUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -23,14 +23,16 @@
public class XMLCommandRegistry extends BaseCommandRegistry {
public static final String PARAM_FILENAME = "filename";
- public void init(Session session, Map parameters) throws OpenAS2Exception {
+ public void init(Session session, Map parameters) throws OpenAS2Exception
+ {
super.init(session, parameters);
refresh();
}
public void load(InputStream in)
- throws ParserConfigurationException, SAXException, IOException, OpenAS2Exception {
+ throws ParserConfigurationException, SAXException, IOException, OpenAS2Exception
+ {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
@@ -42,46 +44,58 @@ public void load(InputStream in)
getCommands().clear();
- for (int i = 0; i < rootNodes.getLength(); i++) {
+ for (int i = 0; i < rootNodes.getLength(); i++)
+ {
rootNode = rootNodes.item(i);
nodeName = rootNode.getNodeName();
- if (nodeName.equals("command")) {
+ if (nodeName.equals("command"))
+ {
loadCommand(rootNode, null);
- } else if (nodeName.equals("multicommand")) {
+ } else if (nodeName.equals("multicommand"))
+ {
loadMultiCommand(rootNode, null);
}
}
}
- public void refresh() throws OpenAS2Exception {
- try {
+ public void refresh() throws OpenAS2Exception
+ {
+ try
+ {
load(new FileInputStream(getParameter(PARAM_FILENAME, true)));
- } catch (Exception e) {
+ } catch (Exception e)
+ {
throw new WrappedException(e);
}
}
protected void loadCommand(Node node, MultiCommand parent)
- throws OpenAS2Exception {
- Command cmd = (Command) XMLUtil.getComponent(node, getSession());
+ throws OpenAS2Exception
+ {
+ Command cmd = (Command) XMLUtil.getComponent(node, (XMLSession) getSession());
- if (parent != null) {
+ if (parent != null)
+ {
parent.getCommands().add(cmd);
- } else {
+ } else
+ {
getCommands().add(cmd);
}
}
protected void loadMultiCommand(Node node, MultiCommand parent)
- throws OpenAS2Exception {
+ throws OpenAS2Exception
+ {
MultiCommand cmd = new MultiCommand();
cmd.init(getSession(), XMLUtil.mapAttributes(node));
- if (parent != null) {
+ if (parent != null)
+ {
parent.getCommands().add(cmd);
- } else {
+ } else
+ {
getCommands().add(cmd);
}
@@ -90,14 +104,17 @@ protected void loadMultiCommand(Node node, MultiCommand parent)
Node childNode;
String childName;
- for (int i = 0; i < childCmds.getLength(); i++) {
+ for (int i = 0; i < childCmds.getLength(); i++)
+ {
childNode = childCmds.item(i);
childName = childNode.getNodeName();
- if (childName.equals("command")) {
+ if (childName.equals("command"))
+ {
loadCommand(childNode, cmd);
- } else if (childName.equals("multicommand")) {
+ } else if (childName.equals("multicommand"))
+ {
loadMultiCommand(childNode, cmd);
}
}
diff --git a/Server/src/main/java/org/openas2/cmd/processor/BaseCommandProcessor.java b/Server/src/main/java/org/openas2/cmd/processor/BaseCommandProcessor.java
index 74506b71..f448f5e3 100644
--- a/Server/src/main/java/org/openas2/cmd/processor/BaseCommandProcessor.java
+++ b/Server/src/main/java/org/openas2/cmd/processor/BaseCommandProcessor.java
@@ -1,85 +1,114 @@
package org.openas2.cmd.processor;
import java.util.ArrayList;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ScheduledExecutorService;
+import javax.annotation.Nullable;
+
+import org.apache.commons.lang3.ClassUtils;
import org.openas2.Component;
import org.openas2.OpenAS2Exception;
import org.openas2.Session;
import org.openas2.cmd.Command;
import org.openas2.cmd.CommandRegistry;
+import org.openas2.schedule.HasSchedule;
-public abstract class BaseCommandProcessor extends Thread implements CommandProcessor, Component {
-
- public Map getParameters() {
- // TODO Auto-generated method stub
- return null;
- }
+public abstract class BaseCommandProcessor implements CommandProcessor, Component, HasSchedule {
- public Session getSession() {
- // TODO Auto-generated method stub
- return null;
- }
+ private static final Void VOID = null;
+ private List commands = new ArrayList();
+ private Session session;
+ private Map parameters;
+ private boolean running = true;
- public void init(Session session, Map parameters) throws OpenAS2Exception {
- // TODO Auto-generated method stub
-
- }
- private List commands;
- private boolean terminated;
-
- public BaseCommandProcessor() {
- super();
- terminated = false;
+ public List getCommands()
+ {
+ return commands;
}
- public void setCommands(List list) {
- commands = list;
+ @Override
+ public String getName()
+ {
+ return ClassUtils.getSimpleName(getClass());
}
- public List getCommands() {
- if (commands == null) {
- commands = new ArrayList();
- }
+ @Override
+ public void init(Session session, Map parameters) throws OpenAS2Exception
+ {
+ this.session = session;
+ this.parameters = parameters;
+ }
- return commands;
+ @Override
+ public Map getParameters()
+ {
+ return parameters;
}
-
- public Command getCommand(String name) {
- Command currentCmd;
- Iterator commandIt = getCommands().iterator();
- while (commandIt.hasNext()) {
- currentCmd = commandIt.next();
- if (currentCmd.getName().equals(name)) {
- return currentCmd;
- }
- }
- return null;
- }
-
- public boolean isTerminated() {
- return terminated;
+
+ @Override
+ public Session getSession()
+ {
+ return session;
}
- public void processCommand() throws OpenAS2Exception {
- throw new OpenAS2Exception("super class method call, not initialized correctly");
+ @Nullable
+ Command getCommand(String name)
+ {
+ Command currentCmd;
+ for (Command command : getCommands())
+ {
+ currentCmd = command;
+ if (currentCmd.getName().equals(name))
+ {
+ return currentCmd;
+ }
+ }
+ return null;
}
-
- public void addCommands(CommandRegistry reg) {
- ;
+
+ public abstract void processCommand() throws Exception;
+
+ public void addCommands(CommandRegistry reg)
+ {
List regCmds = reg.getCommands();
- if (regCmds.size() > 0) {
- getCommands().addAll(regCmds);
+ if (regCmds.size() > 0)
+ {
+ commands.addAll(regCmds);
}
}
- public void terminate() {
- terminated = true;
+ public void terminate() throws Exception
+ {
+ running = false;
+ getSession().stop();
+ }
+
+ @Override
+ public void destroy() throws Exception
+ {
+ running = false;
+ }
+
+ @Override
+ public void schedule(ScheduledExecutorService executor) throws OpenAS2Exception
+ {
+ executor.submit(new Callable() {
+ @Override
+ public Void call() throws Exception
+ {
+ while (running)
+ {
+ processCommand();
+ }
+ return VOID;
+ }
+ });
}
}
diff --git a/Server/src/main/java/org/openas2/cmd/processor/CommandProcessor.java b/Server/src/main/java/org/openas2/cmd/processor/CommandProcessor.java
index eab40e89..47ddca82 100644
--- a/Server/src/main/java/org/openas2/cmd/processor/CommandProcessor.java
+++ b/Server/src/main/java/org/openas2/cmd/processor/CommandProcessor.java
@@ -3,24 +3,16 @@
import java.util.List;
-import org.openas2.OpenAS2Exception;
import org.openas2.cmd.Command;
import org.openas2.cmd.CommandRegistry;
-
public interface CommandProcessor {
- public List getCommands();
-
- public boolean isTerminated();
-
- public void addCommands(CommandRegistry reg);
+ List getCommands();
- public void deInit() throws OpenAS2Exception;
+ void addCommands(CommandRegistry reg);
- public void init() throws OpenAS2Exception;
+ void terminate() throws Exception;
- public void terminate();
-
- public void processCommand() throws OpenAS2Exception;
+ void processCommand() throws Exception;
}
\ No newline at end of file
diff --git a/Server/src/main/java/org/openas2/cmd/processor/SocketCommandProcessor.java b/Server/src/main/java/org/openas2/cmd/processor/SocketCommandProcessor.java
index 481a8889..c70162f8 100644
--- a/Server/src/main/java/org/openas2/cmd/processor/SocketCommandProcessor.java
+++ b/Server/src/main/java/org/openas2/cmd/processor/SocketCommandProcessor.java
@@ -5,6 +5,7 @@
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
+import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -13,193 +14,194 @@
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
+import org.apache.commons.io.IOUtils;
import org.openas2.OpenAS2Exception;
import org.openas2.Session;
+import org.openas2.WrappedException;
import org.openas2.cmd.Command;
import org.openas2.cmd.CommandResult;
import org.openas2.util.CommandTokenizer;
-import org.xml.sax.SAXException;
-/** actual socket command processor
- * takes commands from socket/port and passes them to the OpenAS2Server
- * message format
- * the actual command
- *
+/**
+ * actual socket command processor
+ * takes commands from socket/port and passes them to the OpenAS2Server
+ * message format
+ * the actual command
+ *
* when inited the valid userid and password is passed, then as each
* command is processed the processCommand method verifies the two fields correctness
- *
- * @author joseph mcverry
*
+ * @author joseph mcverry
*/
-public class SocketCommandProcessor extends BaseCommandProcessor
- implements
- Runnable {
-
- private BufferedReader rdr = null;
- private BufferedWriter wrtr = null;
- private SSLServerSocket sslserversocket = null;
-
- private String userid, password;
-
- public SocketCommandProcessor() {
- }
-
- public void deInit() throws OpenAS2Exception {
- }
-
- SocketCommandParser parser;
-
- public void init() throws OpenAS2Exception {
- }
-
- public void init(Session session, Map parameters) throws OpenAS2Exception {
- String p = (String) parameters.get("portid");
- try {
- int port = Integer.parseInt(p);
-
- SSLServerSocketFactory sslserversocketfactory =
- (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
- sslserversocket =
- (SSLServerSocket) sslserversocketfactory.createServerSocket(port);
- String cipherSuites = System.getProperty("CmdProcessorSocketCipher", "TLS_DH_anon_WITH_AES_256_CBC_SHA");
- final String[] enabledCipherSuites = { cipherSuites };
- try
- {
- sslserversocket.setEnabledCipherSuites(enabledCipherSuites);
- } catch (IllegalArgumentException e)
- {
- throw new OpenAS2Exception(
- "Cipher is not supported. Use command line switch -DCmdProcessorSocketCipher= to use one supported by your version of java security."
- , e);
- }
-
-
- } catch (IOException e) {
- e.printStackTrace();
- throw new OpenAS2Exception(e);
- } catch (NumberFormatException e) {
- e.printStackTrace();
- throw new OpenAS2Exception("error converting portid parameter " + e);
- }
- userid = (String) parameters.get("userid");
- if (userid == null || userid.length() < 1)
- throw new OpenAS2Exception("missing userid parameter");
-
- password = (String) parameters.get("password");
- if (password == null || password.length() < 1)
- throw new OpenAS2Exception("missing password parameter");
-
- try {
- parser = new SocketCommandParser();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- new OpenAS2Exception(e);
- }
- }
-
- public void processCommand() throws OpenAS2Exception {
-
- SSLSocket socket = null;
- try {
- socket = (SSLSocket) sslserversocket.accept();
- socket.setSoTimeout(2000);
- rdr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- wrtr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
-
- String line;
- line = rdr.readLine();
-
- parser.parse(line);
-
- if (parser.getUserid().equals(userid) == false) {
- wrtr.write("Bad userid/password");
- throw new OpenAS2Exception("Bad userid");
- }
-
- if (parser.getPassword().equals(password) == false) {
- wrtr.write("Bad userid/password");
- throw new OpenAS2Exception("Bad password");
- }
-
- String str = parser.getCommandText();
- if (str != null && str.length() > 0) {
- CommandTokenizer cmdTkn = new CommandTokenizer(str);
-
- if (cmdTkn.hasMoreTokens()) {
- String commandName = cmdTkn.nextToken().toLowerCase();
-
- if (commandName.equals(StreamCommandProcessor.EXIT_COMMAND)) {
- terminate();
- } else {
- List params = new ArrayList();
-
- while (cmdTkn.hasMoreTokens()) {
- params.add(cmdTkn.nextToken());
- }
-
- Command cmd = getCommand(commandName);
-
- if (cmd != null) {
- CommandResult result = cmd.execute(params.toArray());
-
- if (result.getType() == CommandResult.TYPE_OK) {
- wrtr.write(result.toXML());
- } else {
- wrtr.write("\r\n" +StreamCommandProcessor.COMMAND_ERROR + "\r\n");
- wrtr.write(result.getResult());
- }
- } else {
- wrtr.write(StreamCommandProcessor.COMMAND_NOT_FOUND
- + "> " + commandName + "\r\n");
- List l = getCommands();
- wrtr.write("List of commands:" + "\r\n");
- for (int i = 0; i < l.size(); i++) {
- cmd = l.get(i);
- wrtr.write(cmd.getName() + "\r\n");
- }
- }
- }
- }
-
-
- }
- wrtr.flush();
- } catch (IOException ioe) {
- ioe.printStackTrace();
- } catch (SAXException e) {
- try {
- if (socket != null)
- socket.close();
- } catch (IOException e1) {
- }
- new OpenAS2Exception(e);
- } catch (Exception e) {
- new OpenAS2Exception(e);
- }
- finally {
- if (socket != null)
- try {
- socket.close();
- } catch (IOException e) {
- ;
- }
-
- }
-
- }
-
- /* (non-Javadoc)
- * @see java.lang.Runnable#run()
- */
- public void run() {
- try {
- while (true) {
- processCommand();
- }
- } catch (OpenAS2Exception e) {
- e.printStackTrace();
- }
-
- }
-
+public class SocketCommandProcessor extends BaseCommandProcessor {
+
+ SocketCommandParser parser;
+ private BufferedReader rdr = null;
+ private BufferedWriter wrtr = null;
+ private SSLServerSocket sslserversocket = null;
+ private String userid, password;
+
+ public void init(Session session, Map parameters) throws OpenAS2Exception
+ {
+ String p = parameters.get("portid");
+ try
+ {
+ int port = Integer.parseInt(p);
+
+ SSLServerSocketFactory sslserversocketfactory =
+ (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
+ sslserversocket =
+ (SSLServerSocket) sslserversocketfactory.createServerSocket(port);
+ String cipherSuites = System.getProperty("CmdProcessorSocketCipher", "TLS_DH_anon_WITH_AES_256_CBC_SHA");
+ final String[] enabledCipherSuites = {cipherSuites};
+ try
+ {
+ sslserversocket.setEnabledCipherSuites(enabledCipherSuites);
+ } catch (IllegalArgumentException e)
+ {
+ throw new OpenAS2Exception(
+ "Cipher is not supported. Use command line switch -DCmdProcessorSocketCipher= to use one supported by your version of java security."
+ , e);
+ }
+
+
+ } catch (IOException e)
+ {
+ e.printStackTrace();
+ throw new OpenAS2Exception(e);
+ } catch (NumberFormatException e)
+ {
+ e.printStackTrace();
+ throw new OpenAS2Exception("error converting portid parameter " + e);
+ }
+ userid = (String) parameters.get("userid");
+ if (userid == null || userid.length() < 1)
+ {
+ throw new OpenAS2Exception("missing userid parameter");
+ }
+
+ password = (String) parameters.get("password");
+ if (password == null || password.length() < 1)
+ {
+ throw new OpenAS2Exception("missing password parameter");
+ }
+
+ try
+ {
+ parser = new SocketCommandParser();
+ } catch (Exception e)
+ {
+ // TODO Auto-generated catch block
+ new OpenAS2Exception(e);
+ }
+ }
+
+ public void processCommand() throws OpenAS2Exception
+ {
+
+ SSLSocket socket = null;
+ try
+ {
+ socket = (SSLSocket) sslserversocket.accept();
+ socket.setSoTimeout(2000);
+ rdr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
+ wrtr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
+
+ String line;
+ line = rdr.readLine();
+
+ parser.parse(line);
+
+ if (parser.getUserid().equals(userid) == false)
+ {
+ wrtr.write("Bad userid/password");
+ throw new OpenAS2Exception("Bad userid");
+ }
+
+ if (parser.getPassword().equals(password) == false)
+ {
+ wrtr.write("Bad userid/password");
+ throw new OpenAS2Exception("Bad password");
+ }
+
+ String str = parser.getCommandText();
+ if (str != null && str.length() > 0)
+ {
+ CommandTokenizer cmdTkn = new CommandTokenizer(str);
+
+ if (cmdTkn.hasMoreTokens())
+ {
+ String commandName = cmdTkn.nextToken().toLowerCase();
+
+ if (commandName.equals(StreamCommandProcessor.EXIT_COMMAND))
+ {
+ terminate();
+ } else
+ {
+ List params = new ArrayList();
+
+ while (cmdTkn.hasMoreTokens())
+ {
+ params.add(cmdTkn.nextToken());
+ }
+
+ Command cmd = getCommand(commandName);
+
+ if (cmd != null)
+ {
+ CommandResult result = cmd.execute(params.toArray());
+
+ if (result.getType() == CommandResult.TYPE_OK)
+ {
+ wrtr.write(result.toXML());
+ } else
+ {
+ wrtr.write("\r\n" + StreamCommandProcessor.COMMAND_ERROR + "\r\n");
+ wrtr.write(result.getResult());
+ }
+ } else
+ {
+ wrtr.write(StreamCommandProcessor.COMMAND_NOT_FOUND
+ + "> " + commandName + "\r\n");
+ List l = getCommands();
+ wrtr.write("List of commands:" + "\r\n");
+ for (int i = 0; i < l.size(); i++)
+ {
+ cmd = l.get(i);
+ wrtr.write(cmd.getName() + "\r\n");
+ }
+ }
+ }
+ }
+
+
+ }
+ wrtr.flush();
+ } catch (SocketException socketError)
+ {
+ // shutdown case
+ if (!sslserversocket.isClosed())
+ {
+ throw new WrappedException(socketError);
+ }
+ } catch (IOException e)
+ {
+ //nothing
+ } catch (Exception e)
+ {
+ //nothing
+ } finally
+ {
+ IOUtils.closeQuietly(socket);
+ }
+
+ }
+
+ @Override
+ public void destroy() throws Exception
+ {
+ IOUtils.closeQuietly(sslserversocket); // closes remote session
+ super.destroy();
+
+ }
}
diff --git a/Server/src/main/java/org/openas2/cmd/processor/StreamCommandProcessor.java b/Server/src/main/java/org/openas2/cmd/processor/StreamCommandProcessor.java
index 99f406ec..db57cc80 100644
--- a/Server/src/main/java/org/openas2/cmd/processor/StreamCommandProcessor.java
+++ b/Server/src/main/java/org/openas2/cmd/processor/StreamCommandProcessor.java
@@ -8,7 +8,7 @@
import java.util.ArrayList;
import java.util.List;
-import org.openas2.OpenAS2Exception;
+import org.apache.commons.io.IOUtils;
import org.openas2.WrappedException;
import org.openas2.cmd.Command;
import org.openas2.cmd.CommandResult;
@@ -16,131 +16,137 @@
/**
* original author unknown
- *
+ *
* in this release made the process a thread so it can be shared with other command processors like
* the SocketCommandProcessor
* created innerclass CommandTokenizer so it could handle quotes and spaces within quotes
- * @author joseph mcverry
*
+ * @author joseph mcverry
*/
-public class StreamCommandProcessor extends BaseCommandProcessor
- implements
- Runnable {
- public static final String COMMAND_NOT_FOUND = "Error: command not found";
- public static final String COMMAND_ERROR = "Error executing command";
- public static final String EXIT_COMMAND = "exit";
- public static final String PROMPT = "#>";
- private BufferedReader reader = null;
- private BufferedWriter writer = null;
-
- public StreamCommandProcessor() {
- reader = new BufferedReader(new InputStreamReader(System.in));
- writer = new BufferedWriter(new OutputStreamWriter(System.out));
- }
-
- public BufferedReader getReader() {
- return reader;
- }
-
- public BufferedWriter getWriter() {
- return writer;
- }
-
- public void deInit() throws OpenAS2Exception {
- }
-
- public void init() throws OpenAS2Exception {
- }
-
- /* (non-Javadoc)
- * @see java.lang.Runnable#run()
- */
- public void run() {
- try {
- while (true)
- processCommand();
-
- } catch (OpenAS2Exception e) {
- e.printStackTrace();
- }
-
- }
-
- public void processCommand() throws OpenAS2Exception {
- try {
-
- String str = readLine();
-
- if (str != null) {
- CommandTokenizer strTkn = new CommandTokenizer(str);
-
- if (strTkn.hasMoreTokens()) {
- String commandName = strTkn.nextToken().toLowerCase();
-
- if (commandName.equals(EXIT_COMMAND)) {
- terminate();
- } else {
- List params = new ArrayList();
-
- while (strTkn.hasMoreTokens()) {
-
- params.add(strTkn.nextToken());
- }
-
- Command cmd = getCommand(commandName);
-
- if (cmd != null) {
- CommandResult result = cmd
- .execute(params.toArray());
-
- if (result.getType() == CommandResult.TYPE_OK) {
- writeLine(result.toString());
- } else {
- writeLine(COMMAND_ERROR);
- writeLine(result.getResult());
- }
- } else {
- writeLine(COMMAND_NOT_FOUND + "> " + commandName);
- List l = getCommands();
- writeLine("List of commands:");
- writeLine(EXIT_COMMAND);
- for (int i = 0; i < l.size(); i++) {
- cmd = l.get(i);
- writeLine(cmd.getName());
- }
- }
- }
- }
-
- write(PROMPT);
- } else {
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- }
- }
-
- } catch (IOException ioe) {
- throw new WrappedException(ioe);
- }
- }
-
- public String readLine() throws java.io.IOException {
- BufferedReader rd = getReader();
-
- return rd.readLine().trim();
- }
-
- public void write(String text) throws java.io.IOException {
- BufferedWriter wr = getWriter();
- wr.write(text);
- wr.flush();
- }
-
- public void writeLine(String line) throws java.io.IOException {
- BufferedWriter wr = getWriter();
- wr.write(line + "\r\n");
- wr.flush();
- }
-
+public class StreamCommandProcessor extends BaseCommandProcessor {
+ public static final String COMMAND_NOT_FOUND = "Error: command not found";
+ public static final String COMMAND_ERROR = "Error executing command";
+ public static final String EXIT_COMMAND = "exit";
+ public static final String PROMPT = "#>";
+ private BufferedReader reader = null;
+ private BufferedWriter writer = null;
+
+ public StreamCommandProcessor()
+ {
+ reader = new BufferedReader(new InputStreamReader(System.in));
+ writer = new BufferedWriter(new OutputStreamWriter(System.out));
+ }
+
+ public BufferedReader getReader()
+ {
+ return reader;
+ }
+
+ public BufferedWriter getWriter()
+ {
+ return writer;
+ }
+
+ public void processCommand() throws Exception
+ {
+ try
+ {
+
+ String str = readLine();
+
+ if (str != null)
+ {
+ CommandTokenizer strTkn = new CommandTokenizer(str);
+
+ if (strTkn.hasMoreTokens())
+ {
+ String commandName = strTkn.nextToken().toLowerCase();
+
+ if (commandName.equals(EXIT_COMMAND))
+ {
+ terminate();
+ } else
+ {
+ List params = new ArrayList();
+
+ while (strTkn.hasMoreTokens())
+ {
+
+ params.add(strTkn.nextToken());
+ }
+
+ Command cmd = getCommand(commandName);
+
+ if (cmd != null)
+ {
+ CommandResult result = cmd
+ .execute(params.toArray());
+
+ if (result.getType() == CommandResult.TYPE_OK)
+ {
+ writeLine(result.toString());
+ } else
+ {
+ writeLine(COMMAND_ERROR);
+ writeLine(result.getResult());
+ }
+ } else
+ {
+ writeLine(COMMAND_NOT_FOUND + "> " + commandName);
+ List l = getCommands();
+ writeLine("List of commands:");
+ writeLine(EXIT_COMMAND);
+ for (int i = 0; i < l.size(); i++)
+ {
+ cmd = l.get(i);
+ writeLine(cmd.getName());
+ }
+ }
+ }
+ }
+
+ write(PROMPT);
+ } else
+ {
+ try
+ {
+ Thread.sleep(100);
+ } catch (InterruptedException e)
+ {
+ }
+ }
+
+ } catch (IOException ioe)
+ {
+ throw new WrappedException(ioe);
+ }
+ }
+
+ public String readLine() throws java.io.IOException
+ {
+ BufferedReader rd = getReader();
+
+ return rd.readLine().trim();
+ }
+
+ public void write(String text) throws java.io.IOException
+ {
+ BufferedWriter wr = getWriter();
+ wr.write(text);
+ wr.flush();
+ }
+
+ public void writeLine(String line) throws java.io.IOException
+ {
+ BufferedWriter wr = getWriter();
+ wr.write(line + "\r\n");
+ wr.flush();
+ }
+
+ @Override
+ public void destroy() throws Exception
+ {
+ IOUtils.closeQuietly(reader); // stops terminal
+ super.destroy();
+ }
}
diff --git a/Server/src/main/java/org/openas2/database/H2DBHandler.java b/Server/src/main/java/org/openas2/database/H2DBHandler.java
deleted file mode 100644
index 0864b4c8..00000000
--- a/Server/src/main/java/org/openas2/database/H2DBHandler.java
+++ /dev/null
@@ -1,112 +0,0 @@
-package org.openas2.database;
-
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.concurrent.TimeUnit;
-
-import org.h2.jdbcx.JdbcConnectionPool;
-import org.openas2.OpenAS2Exception;
-
-public class H2DBHandler implements IDBHandler
-{
- JdbcConnectionPool cp = null;
-
- private String jdbcDriver = "org.h2.Driver";
-
- private String connectString = "jdbc:h2:file:DB/openas2";
-
- public H2DBHandler()
- {
- }
-
- /**
- * @param jdbcDriver
- */
- public H2DBHandler(String jdbcDriver)
- {
- setJdbcDriver(jdbcDriver);
- }
-
- /**
- * @param jdbcDriver
- */
- public void setJdbcDriver(String jdbcDriver)
- {
- this.jdbcDriver = jdbcDriver;
- }
-
- public void createConnectionPool(String connectString, String userName, String pwd) throws OpenAS2Exception
- {
- // Check that a connection pool is not already running
- if (cp != null)
- {
- throw new OpenAS2Exception(
- "Connection pool already initialized. Cannot create a new connection pool. Stop current one first. DB connect string:"
- + connectString + " :: Active pool connect string: " + this.connectString);
- }
- this.connectString = connectString;
- // Load the Database Engine JDBC driver
- // Class.forName(jdbcDriver);
-
- cp = JdbcConnectionPool.create(connectString, userName, pwd);
- }
-
- public void destroyConnectionPool()
- {
- if (cp == null)
- return;
- cp.dispose();
- cp = null;
- }
-
- public Connection getConnection() throws SQLException, OpenAS2Exception
- {
- // Check that a connection pool is running
- if (cp == null)
- {
- throw new OpenAS2Exception("Connection pool not initialized.");
- }
- return cp.getConnection();
- }
-
- public Connection connect(String connectString, String userName, String password) throws Exception
- {
-
- // Load the Database Engine JDBC driver
- Class.forName(jdbcDriver);
- try
- {
-
- return DriverManager.getConnection(connectString, userName, password);
- } catch (SQLException e)
- {
- throw new Exception("Failed to obtain connection to database: " + connectString, e);
- }
- }
-
- public boolean shutdown(String connectString) throws SQLException, OpenAS2Exception
- {
- // Wait briefly if there are active connections
- int waitCount = 0;
- try
- {
- while (cp.getActiveConnections() > 0 && waitCount < 10)
- {
- TimeUnit.MILLISECONDS.sleep(100);
- waitCount++;
- }
- } catch (InterruptedException e)
- {
- // Do nothing
- }
- Connection c = getConnection();
- Statement st = c.createStatement();
-
- boolean result = st.execute("SHUTDOWN");
- c.close();
- return result;
- }
-
-}
diff --git a/Server/src/main/java/org/openas2/database/IDBHandler.java b/Server/src/main/java/org/openas2/database/IDBHandler.java
deleted file mode 100644
index a12d52b4..00000000
--- a/Server/src/main/java/org/openas2/database/IDBHandler.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package org.openas2.database;
-
-import java.sql.Connection;
-import java.sql.SQLException;
-
-import org.openas2.OpenAS2Exception;
-
-public interface IDBHandler
-{
- public void setJdbcDriver(String jdbcDriver);
-
- public void createConnectionPool(String connectString, String userName, String pwd) throws OpenAS2Exception;
-
- public void destroyConnectionPool();
-
- public Connection getConnection() throws SQLException, OpenAS2Exception;
-
- public Connection connect(String connectString, String userName, String password) throws Exception;
-
- public boolean shutdown(String connectString) throws SQLException, OpenAS2Exception;
-}
diff --git a/Server/src/main/java/org/openas2/lib/Info.java b/Server/src/main/java/org/openas2/lib/Info.java
deleted file mode 100644
index 02e26f1a..00000000
--- a/Server/src/main/java/org/openas2/lib/Info.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package org.openas2.lib;
-
-public class Info {
- public static final String NAME = "OpenAS2";
- public static final String VERSION = "v1.0";
- public static final String NAME_VERSION = NAME + " " + VERSION;
-}
diff --git a/Server/src/main/java/org/openas2/lib/MDNEngine.java b/Server/src/main/java/org/openas2/lib/MDNEngine.java
index af967b62..8ffe218d 100644
--- a/Server/src/main/java/org/openas2/lib/MDNEngine.java
+++ b/Server/src/main/java/org/openas2/lib/MDNEngine.java
@@ -23,6 +23,7 @@
import org.openas2.lib.partner.IPartnershipChooser;
import org.openas2.message.Message;
import org.openas2.partner.Partnership;
+import org.openas2.util.Properties;
public class MDNEngine {
private EDIINTHelper ediintHelper;
@@ -97,7 +98,7 @@ protected AS2MessageMDN createAS2MDN(AS2Message msg, EngineResults results) thro
// generate the MDN data
MDNData mdnData = mdn.getMDNData();
- mdnData.setReportingUA(Info.NAME_VERSION);
+ mdnData.setReportingUA(Properties.getProperty(Properties.APP_TITLE_PROP, "OpenAS2 Server"));
mdnData.setOriginalRecipient("rfc822; " + msg.getAS2To());
if (results.getPartnership() != null) {
mdnData.setFinalRecipient("rfc822; "
diff --git a/Server/src/main/java/org/openas2/lib/helper/BCCryptoHelper.java b/Server/src/main/java/org/openas2/lib/helper/BCCryptoHelper.java
index 6a25be94..29916509 100644
--- a/Server/src/main/java/org/openas2/lib/helper/BCCryptoHelper.java
+++ b/Server/src/main/java/org/openas2/lib/helper/BCCryptoHelper.java
@@ -31,6 +31,7 @@
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
+import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
@@ -81,7 +82,6 @@
import org.openas2.DispositionException;
import org.openas2.OpenAS2Exception;
import org.openas2.Session;
-import org.openas2.lib.util.IOUtil;
import org.openas2.message.AS2Message;
import org.openas2.message.Message;
import org.openas2.processor.receiver.AS2ReceiverModule;
@@ -89,91 +89,120 @@
import org.openas2.util.DispositionType;
public class BCCryptoHelper implements ICryptoHelper {
- private Log logger = LogFactory.getLog(BCCryptoHelper.class.getSimpleName());
+ private Log logger = LogFactory.getLog(BCCryptoHelper.class.getSimpleName());
- public boolean isEncrypted(MimeBodyPart part) throws MessagingException {
+ public boolean isEncrypted(MimeBodyPart part) throws MessagingException
+ {
ContentType contentType = new ContentType(part.getContentType());
String baseType = contentType.getBaseType().toLowerCase();
- if (baseType.equalsIgnoreCase("application/pkcs7-mime")) {
+ if (baseType.equalsIgnoreCase("application/pkcs7-mime"))
+ {
String smimeType = contentType.getParameter("smime-type");
boolean checkResult = (smimeType != null) && smimeType.equalsIgnoreCase("enveloped-data");
if (!checkResult && logger.isDebugEnabled())
- logger.debug("Check for encrypted data failed on SMIME content type: " + smimeType);
+ {
+ logger.debug("Check for encrypted data failed on SMIME content type: " + smimeType);
+ }
return (checkResult);
}
- if (logger.isDebugEnabled()) logger.debug("Check for encrypted data failed on BASE content type: " + baseType);
+ if (logger.isDebugEnabled())
+ {
+ logger.debug("Check for encrypted data failed on BASE content type: " + baseType);
+ }
return false;
}
- public boolean isSigned(MimeBodyPart part) throws MessagingException {
+ public boolean isSigned(MimeBodyPart part) throws MessagingException
+ {
ContentType contentType = new ContentType(part.getContentType());
String baseType = contentType.getBaseType().toLowerCase();
return baseType.equalsIgnoreCase("multipart/signed");
}
- public boolean isCompressed(MimeBodyPart part) throws MessagingException {
+ public boolean isCompressed(MimeBodyPart part) throws MessagingException
+ {
ContentType contentType = new ContentType(part.getContentType());
String baseType = contentType.getBaseType().toLowerCase();
- if (logger.isTraceEnabled())
- {
- try
- {
- logger.trace("Compression check. MIME Base Content-Type:" + contentType.getBaseType());
- logger.trace("Compression check. SMIME-TYPE:" + contentType.getParameter("smime-type"));
- logger.trace("Compressed MIME msg AFTER COMPRESSION Content-Disposition:" + part.getDisposition());
- } catch (MessagingException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- if (baseType.equalsIgnoreCase("application/pkcs7-mime")) {
+ if (logger.isTraceEnabled())
+ {
+ try
+ {
+ logger.trace("Compression check. MIME Base Content-Type:" + contentType.getBaseType());
+ logger.trace("Compression check. SMIME-TYPE:" + contentType.getParameter("smime-type"));
+ logger.trace("Compressed MIME msg AFTER COMPRESSION Content-Disposition:" + part.getDisposition());
+ } catch (MessagingException e)
+ {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ if (baseType.equalsIgnoreCase("application/pkcs7-mime"))
+ {
String smimeType = contentType.getParameter("smime-type");
boolean checkResult = (smimeType != null) && smimeType.equalsIgnoreCase("compressed-data");
if (!checkResult && logger.isDebugEnabled())
- logger.debug("Check for compressed data failed on SMIME content type: " + smimeType);
+ {
+ logger.debug("Check for compressed data failed on SMIME content type: " + smimeType);
+ }
return (checkResult);
}
- if (logger.isDebugEnabled()) logger.debug("Check for compressed data failed on BASE content type: " + baseType);
+ if (logger.isDebugEnabled())
+ {
+ logger.debug("Check for compressed data failed on BASE content type: " + baseType);
+ }
return false;
}
public String calculateMIC(MimeBodyPart part, String digest, boolean includeHeaders)
- throws GeneralSecurityException, MessagingException, IOException
+ throws GeneralSecurityException, MessagingException, IOException
{
- return calculateMIC(part, digest, includeHeaders, false);
+ return calculateMIC(part, digest, includeHeaders, false);
}
public String calculateMIC(MimeBodyPart part, String digest, boolean includeHeaders, boolean noCanonicalize)
- throws GeneralSecurityException, MessagingException, IOException {
+ throws GeneralSecurityException, MessagingException, IOException
+ {
String micAlg = convertAlgorithm(digest, true);
if (logger.isDebugEnabled())
- logger.debug("Calc MIC called with digest: " + digest + " ::: Incl headers? " + includeHeaders
- + " ::: Prevent canonicalization: " + noCanonicalize + " ::: Encoding: " + part.getEncoding());
+ {
+ logger.debug("Calc MIC called with digest: " + digest + " ::: Incl headers? " + includeHeaders
+ + " ::: Prevent canonicalization: " + noCanonicalize + " ::: Encoding: " + part.getEncoding());
+ }
MessageDigest md = MessageDigest.getInstance(micAlg, "BC");
- if (includeHeaders && logger.isTraceEnabled()) {
- logger.trace("Calculating MIC on MIMEPART Headers: " + AS2Util.printHeaders(part.getAllHeaders()));
+ if (includeHeaders && logger.isTraceEnabled())
+ {
+ logger.trace("Calculating MIC on MIMEPART Headers: " + AS2Util.printHeaders(part.getAllHeaders()));
}
// convert the Mime data to a byte array, then to an InputStream
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
-
+
// Canonicalize the data if not binary content transfer encoding
- OutputStream os = null;
+ OutputStream os = null;
String encoding = part.getEncoding();
// Default encoding in case the bodypart does not have a transfer encoding set
- if (encoding == null) encoding = Session.DEFAULT_CONTENT_TRANSFER_ENCODING;
- if ("binary".equals(encoding) || noCanonicalize) os = bOut;
- else os = new CRLFOutputStream(bOut);
-
- if (includeHeaders) {
+ if (encoding == null)
+ {
+ encoding = Session.DEFAULT_CONTENT_TRANSFER_ENCODING;
+ }
+ if ("binary".equals(encoding) || noCanonicalize)
+ {
+ os = bOut;
+ } else
+ {
+ os = new CRLFOutputStream(bOut);
+ }
+
+ if (includeHeaders)
+ {
part.writeTo(os);
- } else {
- IOUtil.copy(part.getInputStream(), os);
+ } else
+ {
+ IOUtils.copy(part.getInputStream(), os);
}
byte[] data = bOut.toByteArray();
@@ -185,7 +214,8 @@ public String calculateMIC(MimeBodyPart part, String digest, boolean includeHead
byte[] buf = new byte[4096];
- while (digIn.read(buf) >= 0) {
+ while (digIn.read(buf) >= 0)
+ {
}
bOut.close();
@@ -200,9 +230,11 @@ public String calculateMIC(MimeBodyPart part, String digest, boolean includeHead
public MimeBodyPart decrypt(MimeBodyPart part, Certificate cert, Key key)
throws GeneralSecurityException, MessagingException, CMSException, IOException,
- SMIMEException {
+ SMIMEException
+ {
// Make sure the data is encrypted
- if (!isEncrypted(part)) {
+ if (!isEncrypted(part))
+ {
throw new GeneralSecurityException("Content-Type indicates data isn't encrypted");
}
@@ -214,76 +246,80 @@ public MimeBodyPart decrypt(MimeBodyPart part, Certificate cert, Key key)
// Get the recipient object for decryption
if (logger.isDebugEnabled())
- logger.debug("Extracted X500 info:: PRINCIPAL : " + x509Cert.getIssuerX500Principal()
- + " :: NAME : " + x509Cert.getIssuerX500Principal().getName());
+ {
+ logger.debug("Extracted X500 info:: PRINCIPAL : " + x509Cert.getIssuerX500Principal()
+ + " :: NAME : " + x509Cert.getIssuerX500Principal().getName());
+ }
X500Name x500Name = new X500Name(x509Cert.getIssuerX500Principal().getName());
- KeyTransRecipientId certRecId = new KeyTransRecipientId(x500Name,x509Cert.getSerialNumber());
+ KeyTransRecipientId certRecId = new KeyTransRecipientId(x500Name, x509Cert.getSerialNumber());
RecipientInformationStore recipientInfoStore = envelope.getRecipientInfos();
-
+
Collection recipients = recipientInfoStore.getRecipients();
- if (recipients == null) {
+ if (recipients == null)
+ {
throw new GeneralSecurityException("Certificate recipients could not be extracted");
}
//RecipientInformation recipientInfo = recipientInfoStore.get(recId);
//Object recipient = null;
-
+
boolean foundRecipient = false;
- for (Iterator iterator = recipients.iterator(); iterator.hasNext();)
- {
- RecipientInformation recipientInfo = iterator.next();
- //recipient = iterator.next();
- if (recipientInfo instanceof KeyTransRecipientInformation) {
- // X509CertificateHolder x509CertHolder = new X509CertificateHolder(x509Cert.getEncoded());
-
- //RecipientId rid = recipientInfo.getRID();
- if (certRecId.match(recipientInfo) && !foundRecipient) {
- foundRecipient = true;
- // byte[] decryptedData = recipientInfo.getContent(new JceKeyTransEnvelopedRecipient((PrivateKey)key).setProvider("BC"));
- byte[] decryptedData = recipientInfo.getContent(
- new BcRSAKeyTransEnvelopedRecipient(PrivateKeyFactory.createKey(PrivateKeyInfo.getInstance(key.getEncoded()))));
-
- return SMIMEUtil.toMimeBodyPart(decryptedData);
- }
- else
- {
- if (logger.isDebugEnabled())
- logger.debug("Failed match on recipient ID's:\n RID from msg:"
- + recipientInfo.getRID().toString() + " \n RID from priv cert: " + certRecId.toString());
- }
- }
+ for (Iterator iterator = recipients.iterator(); iterator.hasNext(); )
+ {
+ RecipientInformation recipientInfo = iterator.next();
+ //recipient = iterator.next();
+ if (recipientInfo instanceof KeyTransRecipientInformation)
+ {
+ // X509CertificateHolder x509CertHolder = new X509CertificateHolder(x509Cert.getEncoded());
+
+ //RecipientId rid = recipientInfo.getRID();
+ if (certRecId.match(recipientInfo) && !foundRecipient)
+ {
+ foundRecipient = true;
+ // byte[] decryptedData = recipientInfo.getContent(new JceKeyTransEnvelopedRecipient((PrivateKey)key).setProvider("BC"));
+ byte[] decryptedData = recipientInfo.getContent(
+ new BcRSAKeyTransEnvelopedRecipient(PrivateKeyFactory.createKey(PrivateKeyInfo.getInstance(key.getEncoded()))));
+
+ return SMIMEUtil.toMimeBodyPart(decryptedData);
+ } else
+ {
+ if (logger.isDebugEnabled())
+ {
+ logger.debug("Failed match on recipient ID's:\n RID from msg:"
+ + recipientInfo.getRID().toString() + " \n RID from priv cert: " + certRecId.toString());
+ }
+ }
+ }
}
throw new GeneralSecurityException("Matching certificate recipient could not be found");
}
- public void deinitialize() {
+ public void deinitialize()
+ {
}
public MimeBodyPart encrypt(MimeBodyPart part, Certificate cert, String algorithm, String contentTxfrEncoding)
- throws GeneralSecurityException, SMIMEException, MessagingException {
+ throws GeneralSecurityException, SMIMEException, MessagingException
+ {
X509Certificate x509Cert = castCertificate(cert);
-
-
+
+
SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator();
- gen.setContentTransferEncoding(getEncoding(contentTxfrEncoding));
+ gen.setContentTransferEncoding(getEncoding(contentTxfrEncoding));
if (logger.isDebugEnabled())
{
- logger.debug("Encrypting on MIME part containing the following headers: " + AS2Util.printHeaders(part.getAllHeaders()));
+ logger.debug("Encrypting on MIME part containing the following headers: " + AS2Util.printHeaders(part.getAllHeaders()));
}
gen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(x509Cert).setProvider("BC"));
- MimeBodyPart encData = gen.generate(part, getOutputEncryptor(algorithm));
-
- //TODO: Check if this gc call makes sense
- System.gc();
-
- return encData;
+ return gen.generate(part, getOutputEncryptor(algorithm));
}
- public void initialize() {
+ public void initialize()
+ {
Security.addProvider(new BouncyCastleProvider());
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
@@ -296,43 +332,50 @@ public void initialize() {
}
public MimeBodyPart sign(MimeBodyPart part, Certificate cert, Key key, String digest, String contentTxfrEncoding
- , boolean adjustDigestToOldName, boolean isRemoveCmsAlgorithmProtectionAttr)
- throws GeneralSecurityException, SMIMEException, MessagingException {
+ , boolean adjustDigestToOldName, boolean isRemoveCmsAlgorithmProtectionAttr)
+ throws GeneralSecurityException, SMIMEException, MessagingException
+ {
//String signDigest = convertAlgorithm(digest, true);
X509Certificate x509Cert = castCertificate(cert);
PrivateKey privKey = castKey(key);
String encryptAlg = cert.getPublicKey().getAlgorithm();
SMIMESignedGenerator sGen = new SMIMESignedGenerator();
- sGen.setContentTransferEncoding(getEncoding(contentTxfrEncoding));
+ sGen.setContentTransferEncoding(getEncoding(contentTxfrEncoding));
SignerInfoGenerator sig;
- try {
+ try
+ {
if (logger.isDebugEnabled())
{
- logger.debug("Params for creating SMIME signed generator:: SIGN DIGEST: " + digest
- + " PUB ENCRYPT ALG: " + encryptAlg
- + " X509 CERT: " + x509Cert);
- logger.debug("Signing on MIME part containing the following headers: " + AS2Util.printHeaders(part.getAllHeaders()));
+ logger.debug("Params for creating SMIME signed generator:: SIGN DIGEST: " + digest
+ + " PUB ENCRYPT ALG: " + encryptAlg
+ + " X509 CERT: " + x509Cert);
+ logger.debug("Signing on MIME part containing the following headers: " + AS2Util.printHeaders(part.getAllHeaders()));
}
// Remove the dash for SHA based digest for signing call
- if (digest.toUpperCase().startsWith("SHA-")) digest = digest.replaceAll("-", "");
+ if (digest.toUpperCase().startsWith("SHA-"))
+ {
+ digest = digest.replaceAll("-", "");
+ }
JcaSimpleSignerInfoGeneratorBuilder jSig = new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC");
- sig = jSig.build(digest+"with"+encryptAlg, privKey, x509Cert);
+ sig = jSig.build(digest + "with" + encryptAlg, privKey, x509Cert);
// Some AS2 systems cannot handle certain OID's ...
- if (isRemoveCmsAlgorithmProtectionAttr)
- {
- final CMSAttributeTableGenerator sAttrGen = sig.getSignedAttributeTableGenerator();
- sig = new SignerInfoGenerator(sig, new DefaultSignedAttributeTableGenerator(){
- @Override
- public AttributeTable getAttributes(@SuppressWarnings("rawtypes") Map parameters) {
- AttributeTable ret = sAttrGen.getAttributes(parameters);
- return ret.remove(CMSAttributes.cmsAlgorithmProtect);
- }
- }, sig.getUnsignedAttributeTableGenerator());
- }
- } catch (OperatorCreationException e) {
- throw new GeneralSecurityException(e);
- }
+ if (isRemoveCmsAlgorithmProtectionAttr)
+ {
+ final CMSAttributeTableGenerator sAttrGen = sig.getSignedAttributeTableGenerator();
+ sig = new SignerInfoGenerator(sig, new DefaultSignedAttributeTableGenerator() {
+ @Override
+ public AttributeTable getAttributes(@SuppressWarnings("rawtypes") Map parameters)
+ {
+ AttributeTable ret = sAttrGen.getAttributes(parameters);
+ return ret.remove(CMSAttributes.cmsAlgorithmProtect);
+ }
+ }, sig.getUnsignedAttributeTableGenerator());
+ }
+ } catch (OperatorCreationException e)
+ {
+ throw new GeneralSecurityException(e);
+ }
sGen.addSignerInfoGenerator(sig);
MimeMultipart signedData;
@@ -343,7 +386,10 @@ public AttributeTable getAttributes(@SuppressWarnings("rawtypes") Map parameters
tmpBody.setContent(signedData);
String ct = signedData.getContentType();
// FIX for latest BC version setting the micalg value to sha-1 when passed sha1 as digest
- if (adjustDigestToOldName && digest.equalsIgnoreCase("SHA1")) ct = ct.replaceAll("-1", "1");
+ if (adjustDigestToOldName && digest.equalsIgnoreCase("SHA1"))
+ {
+ ct = ct.replaceAll("-1", "1");
+ }
tmpBody.setHeader("Content-Type", ct);
//tmpBody.setHeader("Content-Transfer-Encoding", contentTxfrEncoding);
@@ -351,9 +397,11 @@ public AttributeTable getAttributes(@SuppressWarnings("rawtypes") Map parameters
}
public MimeBodyPart verifySignature(MimeBodyPart part, Certificate cert)
- throws GeneralSecurityException, IOException, MessagingException, CMSException, OperatorCreationException {
+ throws GeneralSecurityException, IOException, MessagingException, CMSException, OperatorCreationException
+ {
// Make sure the data is signed
- if (!isSigned(part)) {
+ if (!isSigned(part))
+ {
throw new GeneralSecurityException("Content-Type indicates data isn't signed");
}
@@ -362,123 +410,130 @@ public MimeBodyPart verifySignature(MimeBodyPart part, Certificate cert)
MimeMultipart mainParts = (MimeMultipart) part.getContent();
SMIMESigned signedPart = new SMIMESigned(mainParts);
- //SignerInformationStore signers = signedPart.getSignerInfos();
-
+ //SignerInformationStore signers = signedPart.getSignerInfos();
+
DigestCalculatorProvider dcp = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
String contentTxfrEnc = signedPart.getContent().getEncoding();
if (contentTxfrEnc == null || contentTxfrEnc.length() < 1)
{
- contentTxfrEnc = Session.DEFAULT_CONTENT_TRANSFER_ENCODING;
+ contentTxfrEnc = Session.DEFAULT_CONTENT_TRANSFER_ENCODING;
}
SMIMESignedParser ssp = new SMIMESignedParser(dcp, mainParts, contentTxfrEnc);
- SignerInformationStore sis = ssp.getSignerInfos();
+ SignerInformationStore sis = ssp.getSignerInfos();
if (logger.isTraceEnabled())
{
- String headers = null;
+ String headers = null;
try
- {
- headers = AS2Util.printHeaders(part.getAllHeaders());
- logger.trace("Headers on MimeBodyPart passed in to signature verifier: " + headers);
- headers = AS2Util.printHeaders(ssp.getContent().getAllHeaders());
- logger.trace("Checking signature on SIGNED MIME part extracted from multipart contains headers: " + headers);
- } catch (Throwable e)
- {
- logger.trace("Error logging mime part for signer: " + org.openas2.logging.Log.getExceptionMsg(e), e);
- }
-
- }
-
- Iterator it = sis.getSigners().iterator();
- SignerInformationVerifier signerInfoVerifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(x509Cert);
- while (it.hasNext())
- {
- SignerInformation signer = it.next();
- if (logger.isTraceEnabled())
- {
- AttributeTable attrTbl = signer.getSignedAttributes();
- logger.trace("Signer Attributes: " + (attrTbl==null?"NULL":attrTbl.toHashtable()));
- }
- if (signer.verify(signerInfoVerifier))
- {
- logSignerInfo("Verified signature for signer info", signer, part, x509Cert);
- return signedPart.getContent();
- }
- logSignerInfo("Failed to verify signature for signer info", signer, part, x509Cert);
- }
- throw new SignatureException("Signature Verification failed");
+ {
+ headers = AS2Util.printHeaders(part.getAllHeaders());
+ logger.trace("Headers on MimeBodyPart passed in to signature verifier: " + headers);
+ headers = AS2Util.printHeaders(ssp.getContent().getAllHeaders());
+ logger.trace("Checking signature on SIGNED MIME part extracted from multipart contains headers: " + headers);
+ } catch (Throwable e)
+ {
+ logger.trace("Error logging mime part for signer: " + org.openas2.logging.Log.getExceptionMsg(e), e);
+ }
+ }
+
+ Iterator it = sis.getSigners().iterator();
+ SignerInformationVerifier signerInfoVerifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(x509Cert);
+ while (it.hasNext())
+ {
+ SignerInformation signer = it.next();
+ if (logger.isTraceEnabled())
+ {
+ AttributeTable attrTbl = signer.getSignedAttributes();
+ logger.trace("Signer Attributes: " + (attrTbl == null ? "NULL" : attrTbl.toHashtable()));
+ }
+ if (signer.verify(signerInfoVerifier))
+ {
+ logSignerInfo("Verified signature for signer info", signer, part, x509Cert);
+ return signedPart.getContent();
+ }
+ logSignerInfo("Failed to verify signature for signer info", signer, part, x509Cert);
+ }
+ throw new SignatureException("Signature Verification failed");
+ }
+
+ public MimeBodyPart compress(Message msg, MimeBodyPart mbp, String compressionType, String contentTxfrEncoding)
+ throws SMIMEException, OpenAS2Exception
+ {
+ OutputCompressor compressor = null;
+ if (compressionType != null)
+ {
+ if (compressionType.equalsIgnoreCase(ICryptoHelper.COMPRESSION_ZLIB))
+ {
+ compressor = new ZlibCompressor();
+ } else
+ {
+ throw new OpenAS2Exception("Unsupported compression type: " + compressionType);
+ }
+ }
+ SMIMECompressedGenerator sCompGen = new SMIMECompressedGenerator();
+ sCompGen.setContentTransferEncoding(getEncoding(contentTxfrEncoding));
+ MimeBodyPart smime = sCompGen.generate(mbp, compressor);
+ if (logger.isTraceEnabled())
+ {
+ try
+ {
+ logger.trace("Compressed MIME msg AFTER COMPRESSION Content-Type:" + smime.getContentType());
+ logger.trace("Compressed MIME msg AFTER COMPRESSION Content-Disposition:" + smime.getDisposition());
+ } catch (MessagingException e)
+ {
+ }
+ }
+ return smime;
+ }
+
+ public void decompress(AS2Message msg) throws DispositionException
+ {
+ try
+ {
+ if (logger.isDebugEnabled())
+ {
+ logger.debug("Decompressing a compressed message");
+ }
+ SMIMECompressed compressed = new SMIMECompressed(msg.getData());
+ // decompression step MimeBodyPart
+ MimeBodyPart recoveredPart = SMIMEUtil.toMimeBodyPart(compressed.getContent(new ZlibExpanderProvider()));
+ // Update the message object
+ msg.setData(recoveredPart);
+ } catch (Exception ex)
+ {
+
+ msg.setLogMsg("Error decompressing received message: " + ex.getCause());
+ logger.error(msg, ex);
+ throw new DispositionException(new DispositionType("automatic-action", "MDN-sent-automatically",
+ "processed", "Error", "unexpected-processing-error"), AS2ReceiverModule.DISP_DECOMPRESSION_ERROR,
+ ex);
+ }
}
- public MimeBodyPart compress(Message msg, MimeBodyPart mbp, String compressionType, String contentTxfrEncoding)
- throws SMIMEException, OpenAS2Exception
- {
- OutputCompressor compressor = null;
- if (compressionType != null)
- {
- if (compressionType.equalsIgnoreCase(ICryptoHelper.COMPRESSION_ZLIB))
- {
- compressor = new ZlibCompressor();
- } else
- throw new OpenAS2Exception("Unsupported compression type: " + compressionType);
- }
- SMIMECompressedGenerator sCompGen = new SMIMECompressedGenerator();
- sCompGen.setContentTransferEncoding(getEncoding(contentTxfrEncoding));
- MimeBodyPart smime = sCompGen.generate(mbp, compressor);
- if (logger.isTraceEnabled())
- {
- try
- {
- logger.trace("Compressed MIME msg AFTER COMPRESSION Content-Type:" + smime.getContentType());
- logger.trace("Compressed MIME msg AFTER COMPRESSION Content-Disposition:" + smime.getDisposition());
- } catch (MessagingException e)
- {
- }
- }
- return smime;
- }
-
- public void decompress(AS2Message msg) throws DispositionException
- {
- try
- {
- if (logger.isDebugEnabled()) logger.debug("Decompressing a compressed message");
- SMIMECompressed compressed = new SMIMECompressed(msg.getData());
- // decompression step MimeBodyPart
- MimeBodyPart recoveredPart = SMIMEUtil.toMimeBodyPart(compressed.getContent(new ZlibExpanderProvider()));
- // Update the message object
- msg.setData(recoveredPart);
- }
-
- catch (Exception ex)
- {
-
- msg.setLogMsg("Error decompressing received message: " + ex.getCause());
- logger.error(msg, ex);
- throw new DispositionException(new DispositionType("automatic-action", "MDN-sent-automatically",
- "processed", "Error", "unexpected-processing-error"), AS2ReceiverModule.DISP_DECOMPRESSION_ERROR,
- ex);
- }
- }
-
- protected String getEncoding(String contentTxfrEncoding)
- {
+ protected String getEncoding(String contentTxfrEncoding)
+ {
// Bouncy castle only deals with binary or base64 so pass base64 for 7bit, 8bit etc
- return "binary".equalsIgnoreCase(contentTxfrEncoding)?"binary":"base64";
- }
+ return "binary".equalsIgnoreCase(contentTxfrEncoding) ? "binary" : "base64";
+ }
- protected X509Certificate castCertificate(Certificate cert) throws GeneralSecurityException {
- if (cert == null) {
+ protected X509Certificate castCertificate(Certificate cert) throws GeneralSecurityException
+ {
+ if (cert == null)
+ {
throw new GeneralSecurityException("Certificate is null");
}
- if (!(cert instanceof X509Certificate)) {
+ if (!(cert instanceof X509Certificate))
+ {
throw new GeneralSecurityException("Certificate must be an instance of X509Certificate");
}
return (X509Certificate) cert;
}
- protected PrivateKey castKey(Key key) throws GeneralSecurityException {
- if (!(key instanceof PrivateKey)) {
+ protected PrivateKey castKey(Key key) throws GeneralSecurityException
+ {
+ if (!(key instanceof PrivateKey))
+ {
throw new GeneralSecurityException("Key must implement PrivateKey interface");
}
@@ -486,75 +541,112 @@ protected PrivateKey castKey(Key key) throws GeneralSecurityException {
}
protected String convertAlgorithm(String algorithm, boolean toBC)
- throws NoSuchAlgorithmException {
- if (algorithm == null) {
+ throws NoSuchAlgorithmException
+ {
+ if (algorithm == null)
+ {
throw new NoSuchAlgorithmException("Algorithm is null");
}
- if (toBC) {
- if (algorithm.toUpperCase().startsWith("SHA-")) algorithm = algorithm.replaceAll("-", "");
- if (algorithm.equalsIgnoreCase(DIGEST_MD5)) {
+ if (toBC)
+ {
+ if (algorithm.toUpperCase().startsWith("SHA-"))
+ {
+ algorithm = algorithm.replaceAll("-", "");
+ }
+ if (algorithm.equalsIgnoreCase(DIGEST_MD5))
+ {
return SMIMESignedGenerator.DIGEST_MD5;
- } else if (algorithm.equalsIgnoreCase(DIGEST_SHA1)) {
+ } else if (algorithm.equalsIgnoreCase(DIGEST_SHA1))
+ {
return SMIMESignedGenerator.DIGEST_SHA1;
- } else if (algorithm.equalsIgnoreCase(DIGEST_SHA224)) {
+ } else if (algorithm.equalsIgnoreCase(DIGEST_SHA224))
+ {
return SMIMESignedGenerator.DIGEST_SHA224;
- } else if (algorithm.equalsIgnoreCase(DIGEST_SHA256)) {
+ } else if (algorithm.equalsIgnoreCase(DIGEST_SHA256))
+ {
return SMIMESignedGenerator.DIGEST_SHA256;
- } else if (algorithm.equalsIgnoreCase(DIGEST_SHA384)) {
+ } else if (algorithm.equalsIgnoreCase(DIGEST_SHA384))
+ {
return SMIMESignedGenerator.DIGEST_SHA384;
- } else if (algorithm.equalsIgnoreCase(DIGEST_SHA512)) {
+ } else if (algorithm.equalsIgnoreCase(DIGEST_SHA512))
+ {
return SMIMESignedGenerator.DIGEST_SHA512;
- } else if (algorithm.equalsIgnoreCase(CRYPT_3DES)) {
+ } else if (algorithm.equalsIgnoreCase(CRYPT_3DES))
+ {
return SMIMEEnvelopedGenerator.DES_EDE3_CBC;
- } else if (algorithm.equalsIgnoreCase(CRYPT_CAST5)) {
+ } else if (algorithm.equalsIgnoreCase(CRYPT_CAST5))
+ {
return SMIMEEnvelopedGenerator.CAST5_CBC;
- } else if (algorithm.equalsIgnoreCase(CRYPT_IDEA)) {
+ } else if (algorithm.equalsIgnoreCase(CRYPT_IDEA))
+ {
return SMIMEEnvelopedGenerator.IDEA_CBC;
- } else if (algorithm.equalsIgnoreCase(CRYPT_RC2)) {
+ } else if (algorithm.equalsIgnoreCase(CRYPT_RC2))
+ {
return SMIMEEnvelopedGenerator.RC2_CBC;
- } else if (algorithm.equalsIgnoreCase(CRYPT_RC2_CBC)) {
+ } else if (algorithm.equalsIgnoreCase(CRYPT_RC2_CBC))
+ {
return SMIMEEnvelopedGenerator.RC2_CBC;
- } else if (algorithm.equalsIgnoreCase(AES256_CBC)) {
+ } else if (algorithm.equalsIgnoreCase(AES256_CBC))
+ {
return SMIMEEnvelopedGenerator.AES256_CBC;
- } else if (algorithm.equalsIgnoreCase(AES192_CBC)) {
+ } else if (algorithm.equalsIgnoreCase(AES192_CBC))
+ {
return SMIMEEnvelopedGenerator.AES192_CBC;
- } else if (algorithm.equalsIgnoreCase(AES128_CBC)) {
+ } else if (algorithm.equalsIgnoreCase(AES128_CBC))
+ {
return SMIMEEnvelopedGenerator.AES128_CBC;
- } else if (algorithm.equalsIgnoreCase(AES256_WRAP)) {
+ } else if (algorithm.equalsIgnoreCase(AES256_WRAP))
+ {
return SMIMEEnvelopedGenerator.AES256_WRAP;
- } else {
+ } else
+ {
throw new NoSuchAlgorithmException("Unsupported or invalid algorithm: " + algorithm);
}
}
- if (algorithm.equalsIgnoreCase(SMIMESignedGenerator.DIGEST_MD5)) {
+ if (algorithm.equalsIgnoreCase(SMIMESignedGenerator.DIGEST_MD5))
+ {
return DIGEST_MD5;
- } else if (algorithm.equalsIgnoreCase(SMIMESignedGenerator.DIGEST_SHA1)) {
+ } else if (algorithm.equalsIgnoreCase(SMIMESignedGenerator.DIGEST_SHA1))
+ {
return DIGEST_SHA1;
- } else if (algorithm.equalsIgnoreCase(SMIMESignedGenerator.DIGEST_SHA224)) {
+ } else if (algorithm.equalsIgnoreCase(SMIMESignedGenerator.DIGEST_SHA224))
+ {
return DIGEST_SHA224;
- } else if (algorithm.equalsIgnoreCase(SMIMESignedGenerator.DIGEST_SHA256)) {
+ } else if (algorithm.equalsIgnoreCase(SMIMESignedGenerator.DIGEST_SHA256))
+ {
return DIGEST_SHA256;
- } else if (algorithm.equalsIgnoreCase(SMIMESignedGenerator.DIGEST_SHA384)) {
+ } else if (algorithm.equalsIgnoreCase(SMIMESignedGenerator.DIGEST_SHA384))
+ {
return DIGEST_SHA384;
- } else if (algorithm.equalsIgnoreCase(SMIMESignedGenerator.DIGEST_SHA512)) {
+ } else if (algorithm.equalsIgnoreCase(SMIMESignedGenerator.DIGEST_SHA512))
+ {
return DIGEST_SHA512;
- } else if (algorithm.equalsIgnoreCase(SMIMEEnvelopedGenerator.CAST5_CBC)) {
+ } else if (algorithm.equalsIgnoreCase(SMIMEEnvelopedGenerator.CAST5_CBC))
+ {
return CRYPT_CAST5;
- } else if (algorithm.equalsIgnoreCase(SMIMEEnvelopedGenerator.AES128_CBC)) {
+ } else if (algorithm.equalsIgnoreCase(SMIMEEnvelopedGenerator.AES128_CBC))
+ {
return AES128_CBC;
- } else if (algorithm.equalsIgnoreCase(SMIMEEnvelopedGenerator.AES192_CBC)) {
+ } else if (algorithm.equalsIgnoreCase(SMIMEEnvelopedGenerator.AES192_CBC))
+ {
return AES192_CBC;
- } else if (algorithm.equalsIgnoreCase(SMIMEEnvelopedGenerator.AES256_CBC)) {
+ } else if (algorithm.equalsIgnoreCase(SMIMEEnvelopedGenerator.AES256_CBC))
+ {
return AES256_CBC;
- } else if (algorithm.equalsIgnoreCase(SMIMEEnvelopedGenerator.AES256_WRAP)) {
+ } else if (algorithm.equalsIgnoreCase(SMIMEEnvelopedGenerator.AES256_WRAP))
+ {
return AES256_WRAP;
- } else if (algorithm.equalsIgnoreCase(SMIMEEnvelopedGenerator.DES_EDE3_CBC)) {
+ } else if (algorithm.equalsIgnoreCase(SMIMEEnvelopedGenerator.DES_EDE3_CBC))
+ {
return CRYPT_3DES;
- } else if (algorithm.equalsIgnoreCase(SMIMEEnvelopedGenerator.IDEA_CBC)) {
+ } else if (algorithm.equalsIgnoreCase(SMIMEEnvelopedGenerator.IDEA_CBC))
+ {
return CRYPT_IDEA;
- } else if (algorithm.equalsIgnoreCase(SMIMEEnvelopedGenerator.RC2_CBC)) {
+ } else if (algorithm.equalsIgnoreCase(SMIMEEnvelopedGenerator.RC2_CBC))
+ {
return CRYPT_RC2;
- } else {
+ } else
+ {
throw new NoSuchAlgorithmException("Unknown algorithm: " + algorithm);
}
@@ -566,10 +658,10 @@ protected String convertAlgorithm(String algorithm, boolean toBC)
* @return the OutputEncryptor of the given hash algorithm
* @throws NoSuchAlgorithmException
* @description Looks up the correct ASN1 OID of the passed in algorithm string and returns the encryptor.
- * The encryption key length is set where necessary
- *
+ * The encryption key length is set where necessary
+ *
* TODO: Possibly just use new ASN1ObjectIdentifier(algorithm) instead of explicit lookup to support random configured algorithms
- * but will require determining if this has any side effects from a security point of view.
+ * but will require determining if this has any side effects from a security point of view.
*/
protected OutputEncryptor getOutputEncryptor(String algorithm)
throws NoSuchAlgorithmException
@@ -583,94 +675,86 @@ protected OutputEncryptor getOutputEncryptor(String algorithm)
if (algorithm.equalsIgnoreCase(DIGEST_MD2))
{
asn1ObjId = new ASN1ObjectIdentifier(PKCSObjectIdentifiers.md2.getId());
- }
- else if (algorithm.equalsIgnoreCase(DIGEST_MD5))
+ } else if (algorithm.equalsIgnoreCase(DIGEST_MD5))
{
asn1ObjId = new ASN1ObjectIdentifier(PKCSObjectIdentifiers.md5.getId());
- }
- else if (algorithm.equalsIgnoreCase(DIGEST_SHA1))
+ } else if (algorithm.equalsIgnoreCase(DIGEST_SHA1))
{
asn1ObjId = new ASN1ObjectIdentifier(OIWObjectIdentifiers.idSHA1.getId());
- }
- else if (algorithm.equalsIgnoreCase(DIGEST_SHA224))
+ } else if (algorithm.equalsIgnoreCase(DIGEST_SHA224))
{
asn1ObjId = new ASN1ObjectIdentifier(NISTObjectIdentifiers.id_sha224.getId());
- }
- else if (algorithm.equalsIgnoreCase(DIGEST_SHA256))
+ } else if (algorithm.equalsIgnoreCase(DIGEST_SHA256))
{
asn1ObjId = new ASN1ObjectIdentifier(NISTObjectIdentifiers.id_sha256.getId());
- }
- else if (algorithm.equalsIgnoreCase(DIGEST_SHA384))
+ } else if (algorithm.equalsIgnoreCase(DIGEST_SHA384))
{
asn1ObjId = new ASN1ObjectIdentifier(NISTObjectIdentifiers.id_sha384.getId());
- }
- else if (algorithm.equalsIgnoreCase(DIGEST_SHA512))
+ } else if (algorithm.equalsIgnoreCase(DIGEST_SHA512))
{
asn1ObjId = new ASN1ObjectIdentifier(NISTObjectIdentifiers.id_sha512.getId());
- }
- else if (algorithm.equalsIgnoreCase(CRYPT_3DES))
+ } else if (algorithm.equalsIgnoreCase(CRYPT_3DES))
{
asn1ObjId = new ASN1ObjectIdentifier(PKCSObjectIdentifiers.des_EDE3_CBC.getId());
- }
- else if (algorithm.equalsIgnoreCase(CRYPT_RC2_CBC) || algorithm.equalsIgnoreCase(CRYPT_RC2_CBC))
+ } else if (algorithm.equalsIgnoreCase(CRYPT_RC2_CBC) || algorithm.equalsIgnoreCase(CRYPT_RC2_CBC))
{
asn1ObjId = new ASN1ObjectIdentifier(PKCSObjectIdentifiers.RC2_CBC.getId());
keyLen = 40;
- }
-
- else if (algorithm.equalsIgnoreCase(AES128_CBC))
+ } else if (algorithm.equalsIgnoreCase(AES128_CBC))
{
- asn1ObjId = CMSAlgorithm.AES128_CBC;
- }
- else if (algorithm.equalsIgnoreCase(AES192_CBC))
+ asn1ObjId = CMSAlgorithm.AES128_CBC;
+ } else if (algorithm.equalsIgnoreCase(AES192_CBC))
{
- asn1ObjId = CMSAlgorithm.AES192_CBC;
- }
- else if (algorithm.equalsIgnoreCase(AES256_CBC))
+ asn1ObjId = CMSAlgorithm.AES192_CBC;
+ } else if (algorithm.equalsIgnoreCase(AES256_CBC))
{
- asn1ObjId = CMSAlgorithm.AES256_CBC;
- }
- else if (algorithm.equalsIgnoreCase(AES256_WRAP))
+ asn1ObjId = CMSAlgorithm.AES256_CBC;
+ } else if (algorithm.equalsIgnoreCase(AES256_WRAP))
{
- asn1ObjId = CMSAlgorithm.AES256_WRAP;
- }
-
- else if (algorithm.equalsIgnoreCase(CRYPT_CAST5))
+ asn1ObjId = CMSAlgorithm.AES256_WRAP;
+ } else if (algorithm.equalsIgnoreCase(CRYPT_CAST5))
{
- asn1ObjId = CMSAlgorithm.CAST5_CBC;
- }
- else if (algorithm.equalsIgnoreCase(CRYPT_IDEA))
+ asn1ObjId = CMSAlgorithm.CAST5_CBC;
+ } else if (algorithm.equalsIgnoreCase(CRYPT_IDEA))
{
- asn1ObjId = CMSAlgorithm.IDEA_CBC;
- }
- else
+ asn1ObjId = CMSAlgorithm.IDEA_CBC;
+ } else
{
- throw new NoSuchAlgorithmException("Unsupported or invalid algorithm: " + algorithm);
+ throw new NoSuchAlgorithmException("Unsupported or invalid algorithm: " + algorithm);
}
OutputEncryptor oe = null;
- try {
- if (keyLen < 0)
- oe = new JceCMSContentEncryptorBuilder(asn1ObjId).setProvider("BC").build();
- else
- oe = new JceCMSContentEncryptorBuilder(asn1ObjId, keyLen).setProvider("BC").build();
- } catch (CMSException e1) {
- throw new NoSuchAlgorithmException("Error creating encryptor builder using algorithm: " + algorithm + " Cause:" + e1.getCause());
- }
- return oe;
+ try
+ {
+ if (keyLen < 0)
+ {
+ oe = new JceCMSContentEncryptorBuilder(asn1ObjId).setProvider("BC").build();
+ } else
+ {
+ oe = new JceCMSContentEncryptorBuilder(asn1ObjId, keyLen).setProvider("BC").build();
+ }
+ } catch (CMSException e1)
+ {
+ throw new NoSuchAlgorithmException("Error creating encryptor builder using algorithm: " + algorithm + " Cause:" + e1.getCause());
+ }
+ return oe;
}
- protected InputStream trimCRLFPrefix(byte[] data) {
+ protected InputStream trimCRLFPrefix(byte[] data)
+ {
ByteArrayInputStream bIn = new ByteArrayInputStream(data);
int scanPos = 0;
int len = data.length;
- while (scanPos < (len - 1)) {
- if (new String(data, scanPos, 2).equals("\r\n")) {
+ while (scanPos < (len - 1))
+ {
+ if (new String(data, scanPos, 2).equals("\r\n"))
+ {
bIn.read();
bIn.read();
scanPos += 2;
- } else {
+ } else
+ {
return bIn;
}
}
@@ -678,60 +762,68 @@ protected InputStream trimCRLFPrefix(byte[] data) {
return bIn;
}
- public KeyStore getKeyStore() throws KeyStoreException, NoSuchProviderException {
+ public KeyStore getKeyStore() throws KeyStoreException, NoSuchProviderException
+ {
return KeyStore.getInstance("PKCS12", "BC");
}
- public KeyStore loadKeyStore(InputStream in, char[] password) throws Exception {
+ public KeyStore loadKeyStore(InputStream in, char[] password) throws Exception
+ {
KeyStore ks = getKeyStore();
ks.load(in, password);
return ks;
}
- public KeyStore loadKeyStore(String filename, char[] password) throws Exception {
+ public KeyStore loadKeyStore(String filename, char[] password) throws Exception
+ {
FileInputStream fIn = new FileInputStream(filename);
- try {
+ try
+ {
return loadKeyStore(fIn, password);
- } finally {
+ } finally
+ {
fIn.close();
}
}
-
+
public String getHeaderValue(MimeBodyPart part, String headerName)
{
- try
- {
- String[] values = part.getHeader(headerName);
- if (values == null) return null;
- return values[0];
- } catch (MessagingException e)
- {
- return null;
- }
+ try
+ {
+ String[] values = part.getHeader(headerName);
+ if (values == null)
+ {
+ return null;
+ }
+ return values[0];
+ } catch (MessagingException e)
+ {
+ return null;
+ }
}
-
+
public void logSignerInfo(String msgPrefix, SignerInformation signer, MimeBodyPart part, X509Certificate cert)
{
if (logger.isDebugEnabled())
{
- try
- {
- logger.debug(msgPrefix + ": \n Digest Alg OID: " + signer.getDigestAlgOID()
- + "\n Encrypt Alg OID: " + signer.getEncryptionAlgOID()
- + "\n Signer Version: " + signer.getVersion()
- + "\n Content Digest: " + Arrays.toString(signer.getContentDigest())
- + "\n Content Type: " + signer.getContentType()
- + "\n SID: " + signer.getSID().getIssuer()
- + "\n Signature: " + signer.getSignature()
- + "\n Unsigned attribs: " + signer.getUnsignedAttributes()
- + "\n Content-transfer-encoding: " + part.getEncoding()
- + "\n Certificate: " + cert
- );
- } catch (Throwable e)
- {
- logger.debug("Error logging signer info: " + org.openas2.logging.Log.getExceptionMsg(e), e);
- }
+ try
+ {
+ logger.debug(msgPrefix + ": \n Digest Alg OID: " + signer.getDigestAlgOID()
+ + "\n Encrypt Alg OID: " + signer.getEncryptionAlgOID()
+ + "\n Signer Version: " + signer.getVersion()
+ + "\n Content Digest: " + Arrays.toString(signer.getContentDigest())
+ + "\n Content Type: " + signer.getContentType()
+ + "\n SID: " + signer.getSID().getIssuer()
+ + "\n Signature: " + Arrays.toString(signer.getSignature())
+ + "\n Unsigned attribs: " + signer.getUnsignedAttributes()
+ + "\n Content-transfer-encoding: " + part.getEncoding()
+ + "\n Certificate: " + cert
+ );
+ } catch (Throwable e)
+ {
+ logger.debug("Error logging signer info: " + org.openas2.logging.Log.getExceptionMsg(e), e);
+ }
}
}
}
diff --git a/Server/src/main/java/org/openas2/lib/helper/ICryptoHelper.java b/Server/src/main/java/org/openas2/lib/helper/ICryptoHelper.java
index 591e35d3..9eeedbe9 100644
--- a/Server/src/main/java/org/openas2/lib/helper/ICryptoHelper.java
+++ b/Server/src/main/java/org/openas2/lib/helper/ICryptoHelper.java
@@ -4,7 +4,6 @@
import java.security.Key;
import java.security.KeyStore;
import java.security.cert.Certificate;
-
import javax.mail.internet.MimeBodyPart;
import org.bouncycastle.mail.smime.SMIMEException;
@@ -53,8 +52,6 @@ public interface ICryptoHelper {
MimeBodyPart decrypt(MimeBodyPart part, Certificate cert, Key key) throws Exception;
- void deinitialize() throws Exception;
-
MimeBodyPart encrypt(MimeBodyPart part, Certificate cert, String algorithm, String contentTxfrEncoding) throws Exception;
void initialize() throws Exception;
diff --git a/Server/src/main/java/org/openas2/lib/message/AS2Message.java b/Server/src/main/java/org/openas2/lib/message/AS2Message.java
index 7d658591..7d4d6a7c 100644
--- a/Server/src/main/java/org/openas2/lib/message/AS2Message.java
+++ b/Server/src/main/java/org/openas2/lib/message/AS2Message.java
@@ -6,8 +6,7 @@
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
-import org.openas2.lib.Info;
-
+import org.openas2.util.Properties;
public class AS2Message extends EDIINTMessage {
public AS2Message() {
@@ -57,9 +56,9 @@ public String getAS2Version() {
public void setDefaults() {
super.setDefaults();
- setAS2Version("1.1");
- setUserAgent("OpenAS2");
- setServer(Info.NAME_VERSION);
+ setAS2Version(Properties.getProperty(Properties.APP_VERSION_PROP, ""));
+ setUserAgent(Properties.getProperty(Properties.APP_TITLE_PROP, "OpenAS2 Server"));
+ setServer(Properties.getProperty(Properties.APP_TITLE_PROP, "OpenAS2 Server"));
}
public void setDispositionNotificationOptions(String options) {
diff --git a/Server/src/main/java/org/openas2/lib/message/AS2MessageMDN.java b/Server/src/main/java/org/openas2/lib/message/AS2MessageMDN.java
index 7aa4e651..e3d42b0f 100644
--- a/Server/src/main/java/org/openas2/lib/message/AS2MessageMDN.java
+++ b/Server/src/main/java/org/openas2/lib/message/AS2MessageMDN.java
@@ -6,7 +6,7 @@
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
-import org.openas2.lib.Info;
+import org.openas2.util.Properties;
public class AS2MessageMDN extends EDIINTMessageMDN {
private AS2MDNData mdnData;
@@ -65,8 +65,8 @@ public String getAS2Version() {
public void setDefaults() {
super.setDefaults();
- setAS2Version("1.1");
- setServer(Info.NAME_VERSION);
+ setAS2Version(Properties.getProperty(Properties.APP_VERSION_PROP, ""));
+ setServer(Properties.getProperty(Properties.APP_TITLE_PROP, "OpenAS2 Server"));
}
public void setServer(String server) {
diff --git a/Server/src/main/java/org/openas2/lib/util/GeneralUtil.java b/Server/src/main/java/org/openas2/lib/util/GeneralUtil.java
index b4f83d81..cd0d45c5 100644
--- a/Server/src/main/java/org/openas2/lib/util/GeneralUtil.java
+++ b/Server/src/main/java/org/openas2/lib/util/GeneralUtil.java
@@ -1,7 +1,5 @@
package org.openas2.lib.util;
-import java.io.PrintWriter;
-import java.io.StringWriter;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
@@ -11,48 +9,21 @@
public class GeneralUtil {
- public static String convert(Object[] array, String delimiter) {
- StringBuffer buffer = new StringBuffer();
- for (int i = 0; i < array.length; i++) {
- if (buffer.length() > 0) {
- buffer.append(delimiter);
- }
- buffer.append(array[i].toString());
- }
-
- return buffer.toString();
- }
-
- public static boolean contains(String[] array, String value) {
- for (int i = 0; i < array.length; i++) {
- if (array[i] == null) {
- if (value == null) {
- return true;
- }
- } else if (value != null && array[i].equals(value)) {
- return true;
- }
- }
- return false;
- }
public static String[] convert(Enumeration en) {
List list = Collections.list(en);
return convert(list);
}
-
- public static String[] convert(List list) {
- String[] values = new String[0];
- return (String[]) list.toArray(values);
- }
-
- public static String convert(List