Java API Documentation

hk.hku.cecid.corvus.http

AS2EnvelopQuerySender

public class AS2EnvelopQuerySender extends EnvelopQuerySender

The AS2EnvelopQuerySender is a client service sender using HTTP protocol for query the message envelop (i.e EDI Header + payload) from the Hermes 2 Messaging Gateway. To use it you have to provide the configuration instance called AS2AdminData. it defines the URL end-point and credential for connecting to your Hermes 2 Restricted area. An Example for adding partnership :

// Create an admin data for configuration.
AS2AdminData adminData = new AS2AdminData();
adminData.setManagePartnershipEndpoint("Your H2O location");
adminData.setUsername("Your username for logging H2O");
adminData.setPassword("Your password for logging H2O");

AS2EnvelopQuerySender sender = new AS2EnvelopQuerySender(someLogger, adminData, pData);
sender.setMessageCriteriaToDownload("The message id you want to query", "INBOX or OUTBOX");
sender.run();
InputStream ins = sender.getEnvelopStream();
// The envelop content ... process it.

Note for setting the manage partnership end-point You should add /admin/as2/partnership to your H2O host. For example, ‘http://localhost:8080/admin/as2/partnership‘. Note that the client service does not guarantee transactional behavior meaning you are always able to down-load the envelop when invoking the client. (Different from the receiver Web service).

Author:Twinsen Tsang

See also: hk.hku.cecid.corvus.ws.data.AS2AdminData

Fields

DL_RECEIPT_FORM_PARAM
protected static final String DL_RECEIPT_FORM_PARAM

Constructors

AS2EnvelopQuerySender
public AS2EnvelopQuerySender(FileLogger logger, AS2AdminData ad)

Explicit Constructor. Create an instance of AS2EnvelopQuerySender.

Parameters:
  • logger – The logger for log the sending process.
  • ad – The AS2AdminData for locating the HTTP end-point the request send to.
Throws:
  • NullPointerException – When p is null. When the manage partnership end-point from ad is null or empty.

Methods

getMessageBoxMapping
protected Map getMessageBoxMapping()
main
public static void main(String[] args)

The main method is for CLI mode.

onCreateRequest
protected HttpRequestBase onCreateRequest()

AS2EnvelopQuerySenderUnitTest

public class AS2EnvelopQuerySenderUnitTest extends EnvelopQuerySenderUnitTest

The AS2EnvelopQuerySenderUnitTest is unit test of AS2EnvelopQuerySender.

Author:Twinsen Tsang

Methods

initTestData
public void initTestData()

Initialize the test data *

initTestTarget
public void initTestTarget()

Initialize the test target which is a PartnershipSender.

testEnvelopQuery
public void testEnvelopQuery()

AS2PartnershipSender

public class AS2PartnershipSender extends PartnershipSender

The AS2PartnershipSender is a client service sender using HTTP protocol for maintaining the set of AS2 Partnership in Hermes 2 Messaging Gateway. To use it you have to provide the configuration instance called AS2AdminData. it defines the URL end-point and credential for connecting to your Hermes 2 Restricted area. An Example for adding partnership :

// Create an administrative data for configuration.
AS2AdminData adminData = new AS2AdminData();
adminData.setManagePartnershipEndpoint("Your H2O location");
adminData.setUsername("Your username for logging H2O");
adminData.setPassword("Your password for logging H2O");
// Create a partnership data for doing maintenance operation.
AS2PartnershipData pData = new AS2PartnershipData();
            .
            .
            .
AS2PartnershipSender sender = new AS2PartnershipSender(someLogger, adminData, pData);
sender.setExecuteOperation(PartnershipOp.Add);
sender.run();

Note for setting the manage partnership end-point You should add /admin/as2/partnership to your H2O host. For example, ‘http://localhost:8080/admin/as2/partnership‘. Technical Information The AS2PartnershipSender will generate a HTTP multi-part request to the manage partnership end-point. The request includes all parameter extracted from the AS2Partnership, each of them is represented as either text/plain multi-part, or application binary multi-part (for the certificates). The type of partnership operation to execute also append at the end of the HTTP request in a text multi-part form.

Author:Twinsen Tsang

See also: hk.hku.cecid.corvus.ws.data.AS2AdminData, hk.hku.cecid.corvus.ws.data.AS2PartnershipData, hk.hku.cecid.corvus.http.PartnershipOp

Fields

PARTNERSHIP_DATA_2_FROM_PARAM_NAME_MAPPING
static final Map PARTNERSHIP_DATA_2_FROM_PARAM_NAME_MAPPING
PARTNERSHIP_OP_2_WORD
static final Map PARTNERSHIP_OP_2_WORD

Constructors

AS2PartnershipSender
public AS2PartnershipSender(FileLogger logger, AS2AdminData ad, AS2PartnershipData p)

Explicit Constructor. Create an instance of AS2PartnershipSender.

Parameters:
  • logger – The logger for log the sending process.
  • ad – The AS2AdminData for locating the HTTP end-point the request send to.
  • p – The AS2PartnershipData you want to add/delete/update.
Throws:
  • NullPointerException – When p is null. When the manage partnership end-point from ad is null or empty.

Methods

getPartnershipMapping
public Map getPartnershipMapping()
getPartnershipOperationMapping
public Map getPartnershipOperationMapping()
main
public static void main(String[] args)

The main method is for CLI mode.

run
public void run()

The main method for executing the partnership operation request.

See also: hk.hku.cecid.corvus.http.HttpSender.run()

AS2PartnershipSenderUnitTest

public class AS2PartnershipSenderUnitTest extends PartnershipSenderUnitTest

The AS2PartnershipSenderUnitTest is unit test of AS2PartnershipSender.

Author:Twinsen Tsang

Methods

initTestData
public void initTestData()

Initialize the test data *

initTestTarget
public void initTestTarget()

Initialize the test target which is a HTTP Sender.

EBMSEnvelopQuerySender

public class EBMSEnvelopQuerySender extends EnvelopQuerySender

The EBMSEnvelopQuerySender is a client service sender using HTTP protocol for query the message envelop (i.e EDI Header + payload) from the Hermes 2 Messaging Gateway. To use it you have to provide the configuration instance called AS2AdminData. it defines the URL end-point and credential for connecting to your Hermes 2 Restricted area. An Example for adding partnership :

// Create an admin data for configuration.
EBMSAdminData adminData = new EBMSAdminData();
adminData.setManagePartnershipEndpoint("Your H2O location");
adminData.setUsername("Your username for logging H2O");
adminData.setPassword("Your password for logging H2O");

EBMSEnvelopQuerySender sender = new EBMSEnvelopQuerySender(someLogger, adminData, pData);
sender.setMessageCriteriaToDownload("The message id you want to query", "INBOX or OUTBOX");
sender.run();
InputStream ins = sender.getEnvelopStream();
// The envelop content ... process it.

Note for setting the manage partnership end-point You should add /admin/ebms/partnership to your H2O host. For example, ‘http://localhost:8080/admin/ebms/partnership‘. Note that the client service does not guarantee transactional behavior meaning you are always able to down-load the envelop when invoking the client. (Different from the receiver Web service).

Author:Twinsen Tsang

See also: hk.hku.cecid.corvus.ws.data.EBMSAdminData

Constructors

EBMSEnvelopQuerySender
public EBMSEnvelopQuerySender(FileLogger logger, EBMSAdminData ad)

Explicit Constructor. Create an instance of AS2EnvelopQuerySender.

Parameters:
  • logger – The logger for log the sending process.
  • ad – The EBMSAdminData for locating the HTTP end-point the request send to.
Throws:
  • NullPointerException – When p is null. When the manage partnership end-point from ad is null or empty.

Methods

getMessageBoxMapping
protected Map getMessageBoxMapping()
main
public static void main(String[] args)

The main method is for CLI mode.

EBMSEnvelopQuerySenderUnitTest

public class EBMSEnvelopQuerySenderUnitTest extends EnvelopQuerySenderUnitTest

The EBMSEnvelopQuerySenderUnitTest is unit test of EBMSEnvelopQuerySender.

Author:Twinsen Tsang

Methods

initTestData
public void initTestData()

Initialize the test data *

initTestTarget
public void initTestTarget()

Initialize the test target which is a PartnershipSender.

testEnvelopQuery
public void testEnvelopQuery()

EBMSPartnershipSender

public class EBMSPartnershipSender extends PartnershipSender

The EBMSPartnershipSender is a client service sender using HTTP protocol for maintaining the set of EBMS Partnership in Hermes 2 Messaging Gateway. To use it you have to provide the configuration instance called EBMSAdminData. it defines the URL end-point and credential for connecting to your Hermes 2 Restricted area. An Example for adding partnership :

// Create an administrative data for configuration.
EBMSAdminData adminData = new EBMSAdminData();
adminData.setManagePartnershipEndpoint("Your H2O location");
adminData.setUsername("Your username for logging H2O");
adminData.setPassword("Your password for logging H2O");
// Create a partnership data for doing maintenance operation.
EBMSPartnershipData pData = new EBMSPartnershipData();
            .
            .
            .
EBMSPartnershipData sender = new EBMSPartnershipData(someLogger, adminData, pData);
sender.setExecuteOperation(PartnershipOp.Add);
sender.run();

Note for setting the manage partnership end-point You should add /admin/ebms/partnership to your H2O host. For example, ‘http://localhost:8080/admin/ebms/partnership‘. Technical Information The EBMSPartnershipSender will generate a HTTP multi-part request to the manage partnership end-point. The request includes all parameter extracted from the EBMSPartnershipData, each of them is represented as either text/plain multi-part, or application binary multi-part (for the certificates). The type of partnership operation to execute also append at the end of the HTTP request in a text multi-part form.

Author:Twinsen Tsang

See also: hk.hku.cecid.corvus.ws.data.EBMSAdminData, hk.hku.cecid.corvus.ws.data.EBMSPartnershipData, hk.hku.cecid.corvus.http.PartnershipOp

Fields

PARTNERSHIP_DATA_2_FROM_PARAM_NAME_MAPPING
static final Map PARTNERSHIP_DATA_2_FROM_PARAM_NAME_MAPPING
PARTNERSHIP_OP_2_WORD
static final Map PARTNERSHIP_OP_2_WORD

Constructors

EBMSPartnershipSender
public EBMSPartnershipSender(FileLogger logger, EBMSAdminData ad, EBMSPartnershipData p)

Explicit Constructor. Create an instance of EBMSPartnershipSender

Parameters:
  • logger – The logger for log the sending process.
  • ad – The EBMSAdminData for locating the HTTP end-point the request send to.
  • p – The EBMSPartnershipData

Methods

getPartnershipMapping
public Map getPartnershipMapping()
getPartnershipOperationMapping
public Map getPartnershipOperationMapping()
main
public static void main(String[] args)

The main method is for CLI mode.

run
public void run()

The main method for executing the partnership operation request.

See also: hk.hku.cecid.corvus.http.HttpSender.run()

EBMSPartnershipSenderUnitTest

public class EBMSPartnershipSenderUnitTest extends PartnershipSenderUnitTest

The EBMSPartnershipSenderUnitTest is unit test of EBMSPartnershipSender.

Author:Twinsen Tsang

Methods

initTestData
public void initTestData()

Initialize the test data *

initTestTarget
public void initTestTarget()

Initialize the test target which is a HTTP Sender.

EnvelopQuerySender

public class EnvelopQuerySender extends HttpSender

The EnvelopSender is abstract base class for sending HTTP remote request to H2O for querying the message envelop through the administration page.

Author:Twinsen Tsang

Fields

MSGBOX_FORM_PARAM
protected static final String MSGBOX_FORM_PARAM

The constant field representing the HTTP request parameter name for Message box.

MSGBOX_IN
public static final String MSGBOX_IN

The constant field representing the standardized incoming message box representation

MSGBOX_OUT
public static final String MSGBOX_OUT

The constant field representing the standardized outgoing message box representation

MSGID_FORM_PARAM
protected static final String MSGID_FORM_PARAM

The constant field representing the HTTP request parameter name for Message id.

Constructors

EnvelopQuerySender
protected EnvelopQuerySender(FileLogger logger, Data d)

Explicit Constructor. Create an instance of EnvelopQuerySender

Parameters:
  • logger – The logger for log the sending process.
  • d – The data used for generate Envelop query request. It must be a kind of Admin data.
EnvelopQuerySender
protected EnvelopQuerySender(FileLogger logger, Data d, String username, String password)

Explicit Constructor. Create an instance of EnvelopQuerySender

Parameters:
  • logger – The logger for log the sending process.
  • d – The data used for generate Envelop query request. It must be a kind of Admin data.
  • username – The username for authentication
  • password – The password for authentication

Methods

getEnvelopStream
public final InputStream getEnvelopStream()

This method should be called after executed run() successfully.

Returns:The message envelop stream.
getMessageBoxMapping
protected Map getMessageBoxMapping()

Get the message box mapping from standardized representation to proprietary representation. It should return a HashMap like this:

HashMap m = new HashMap();
m.put(MSGBOX_IN , "Your Inbox representation");
m.put(MSGBOX_OUT, "Your outbox representation");
Returns:the message box mapping.

See also: EnvelopQuerySender.MSGBOX_IN, EnvelopQuerySender.MSGBOX_OUT

getMessageBoxToDownload
public final String getMessageBoxToDownload()
Returns:The message box to donw-load the message envelop. either INBOX or OUTBOX.
getMessageIdToDownload
public final String getMessageIdToDownload()
Returns:The message id to down-load the message envelop.
onCreateRequest
protected HttpRequestBase onCreateRequest()

[@EVENT] This method is invoked when the sender is required to create a HTTP Request from configuration. It generates a form-url-encoded content embedded in the HTTP POST request. It contains two parameters, message_id and message_box. The value of these parameters are extracted from getMessageIdToDownload() and getMessageBoxToDownload() respectively. NOTE: The values of message_box parameter may differ to what you see because it may transform getMessageBoxMapping().

Throws:
onResponse
protected void onResponse()

[@EVENT] This method is invoked when received the reply HTTP response from the server. It saves the response body stream and then available to get through by getEnvelopStream()

onStart
protected void onStart()

[@EVENT] The method onStart log all new configuration.

setMessageCriteriaToDownload
public final void setMessageCriteriaToDownload(String messageId, String messageBox)

Set the message criteria for down-load the message envelop (and payload).

Parameters:
  • messageId – The message id to down-load the message envelop.
  • messageBox – The message box to down-load the message envelop. either INBOX or OUTBOX.
Throws:

EnvelopQuerySenderUnitTest

public class EnvelopQuerySenderUnitTest extends TestCase

The EnvelopQuerySenderUnitTest is unit test of EnvelopQuerySender.

Author:Twinsen Tsang

Fields

PASSWORD
public static final String PASSWORD
TEST_ENDPOINT
public static final String TEST_ENDPOINT
TEST_PORT
public static final int TEST_PORT
USER_NAME
public static final String USER_NAME
kvData
protected KVPairData kvData
logger
Logger logger
target
protected EnvelopQuerySender target

The testing target which is an PartnershipSender and the associated data

testClassLogger
protected FileLogger testClassLogger

Methods

initTestData
public void initTestData()

Initialize the test data *

initTestTarget
public void initTestTarget()

Initialize the test target which is a PartnershipSender.

setUp
public void setUp()

Setup the fixture.

tearDown
public void tearDown()

Stop the HTTP monitor preventing JVM port binding *

testEnvelopQuery
public void testEnvelopQuery()

Test whether the *

testSetMessageCriteriaProperty
public void testSetMessageCriteriaProperty()

Test whether the setMessageCriteriaToDownload works well under valid data. *

testSetMessageCriteriaWithInvalid
public void testSetMessageCriteriaWithInvalid()

Test whether the setMessageCriteriaToDownload throw exception when second argument is invalid. *

testSetMessageCriteriaWithNull
public void testSetMessageCriteriaWithNull()

Test whether the setMessageCriteriaToDownload throw exception when 1 and 2 argument is null. *

testSetMessageCriteriaWithNull2
public void testSetMessageCriteriaWithNull2()

Test whether the setMessageCriteriaToDownload throw exception when second argument is null. *

HttpSender

public class HttpSender implements Runnable

The HttpSender is top base class for sending HTTP request. TODO: javadoc

Author:Twinsen Tsang

Fields

log
protected FileLogger log
properties
protected Data properties
serviceEndPoint
protected URL serviceEndPoint

Constructors

HttpSender
public HttpSender()

SPA Constructor. It is used when the HTTP Sender is a component in the SPA.

HttpSender
public HttpSender(FileLogger logger, Data d)

Explicit Constructor.

Parameters:
  • logger – The logger used for log message and exception.
  • d – The data used for sending HTTP request.
HttpSender
public HttpSender(FileLogger logger, Data d, String username, String password)

Explicit Constructor.

Parameters:
  • logger – The logger used for log message and exception.
  • d – The data used for sending HTTP request.
  • username – The username for authentication
  • password – The password for authentication
HttpSender
public HttpSender(FileLogger l, Data d, String endpoint)

Explicit Constructor.

Parameters:
  • l – The logger used for log message and exception.
  • d – The data used for sending HTTP request.
  • endpoint – The URL of service end point.
HttpSender
public HttpSender(FileLogger l, Data d, URL endpoint)

Explicit Constructor.

Parameters:
  • l – The logger used for log message and exception.
  • d – The data used for sending HTTP request.
  • endpoint – The URL of service end point.
HttpSender
public HttpSender(FileLogger l, Data d, String endpoint, String username, String password)

Explicit Constructor.

Parameters:
  • l – The logger used for log message and exception.
  • d – The data used for sending HTTP request.
  • endpoint – The URL of service end point.
  • username – The username for authentication
  • password – The password for authentication
HttpSender
public HttpSender(FileLogger l, Data d, URL endpoint, String username, String password)

Explicit Constructor.

Parameters:
  • l – The logger used for log message and exception.
  • d – The data used for sending HTTP request.
  • endpoint – The URL of service end point.
  • username – The username for authentication
  • password – The password for authentication

Methods

closeResponse
public void closeResponse(CloseableHttpResponse response)

Close http response with exception handling

Parameters:
  • response – the response to close
getCurrentLoopTimes
public int getCurrentLoopTimes()

Get what is the current loop times for looping

getExecutedMethod
public HttpRequestBase getExecutedMethod()

Get the last executed HTTP method. This method should be invoked during onResponse().

Returns:the last executed HTTP method.
getLoopTimes
public int getLoopTimes()

Get how many times should the sender to be send.

getResponse
public CloseableHttpResponse getResponse()

Get the response of the last executed HTTP method. This method should be invoked during onResponse().

Returns:the response of the last executed HTTP method
getServiceEndPoint
public URL getServiceEndPoint()

Get the service end-point.

Returns:the service end-point URL.
getUserObject
public Object getUserObject()

Get a user object.

initializeMessage
protected void initializeMessage()

Implements this method if you want to send messages without much different between other message to sent.

isAuthenticationRequired
public boolean isAuthenticationRequired()
Returns:true if HTTP authentication is required.
onBeforeRequest
protected void onBeforeRequest(HttpClient client, HttpRequestBase request)

[@EVENT] This method is invoked just before sending the request to HTTP service end-point.

Parameters:
  • client – The HTTP Connection used for sending SOAP request.
  • request – The request created by onCreateRequest().
Throws:
  • Exception – Any type of exception will be processed at onError(throwable t).
onCreateRequest
protected HttpRequestBase onCreateRequest()

[@EVENT] This method is invoked when the sender is required to create a HTTP Request from configuration. By default, this method return a PostMethod pointing to getServiceEndPoint().

Throws:
  • Exception – Sub-class implementation-specific exception
onEachLoopStart
protected void onEachLoopStart()

[@EVENT] This method is invoked when each loop iteration start.

Throws:
  • Exception – Any type of exception will be processed at onError(throw-able t).
onEnd
protected void onEnd()

[@EVENT] This method is invoked when the sending execution is ended.

onError
protected void onError(Throwable t)

[@EVENT] This method is invoked when there is any exception thrown during web service call. By default, it log the throw-able t to the instance logger.

onResponse
protected void onResponse()

[@EVENT] This method is invoked when received the reply HTTP response from the server. Developer can use getExecutedMethod() to get the HTTP method generated thru onCreateRequest()

Throws:
  • Exception – Any type of exception will be processed at onError(throwable t).
onStart
protected void onStart()

[@EVENT] This method is invoked when the sender begins to execute the run method.

run
public void run()

The thread execution method.

setLoopTimes
public void setLoopTimes(int loopTimes)

Set how many times should the sender to be send.

Parameters:
  • loopTimes – the new loopTimes.
setServiceEndPoint
public void setServiceEndPoint(URL endpoint)

Set the service end-point.

Parameters:
  • endpoint – The URL of the web service end-point.
setServiceEndPoint
public void setServiceEndPoint(String endpoint)

Set the service end-point.

Parameters:
  • endpoint – The String of the web service end-point.
setUserObject
public void setUserObject(Object obj)

Set a user object for call-back.

Parameters:
  • obj – The user object.

HttpSenderUnitTest

public class HttpSenderUnitTest extends TestCase

The HttpSenderUnitTest is unit test of HttpSender. TODO: Inadequate Test-case for testing looping.

Author:Twinsen Tsang

Fields

TEST_ENDPOINT
public static final String TEST_ENDPOINT
TEST_PORT
public static final int TEST_PORT
logger
Logger logger

Methods

initTestTarget
public void initTestTarget()

Initialize the test target which is a HTTP Sender.

setUp
public void setUp()

Setup the fixture.

tearDown
public void tearDown()

Stop the HTTP monitor preventing JVM port binding *

testLoopTimeProperty
public void testLoopTimeProperty()

Test HttpSender.getLoopTimes() and HttpSender.setLoopTimes(int) *

testSendWithBasicAuthentication
public void testSendWithBasicAuthentication()

Test wether the HTTP sender able to send the HTTP header with ‘Authorization’ header.

testSendWithMultipart
public void testSendWithMultipart()

Test whether the HTTP sender able to send the HTTP header with multi-part to our monitor successfully.

testSendWithNoContent
public void testSendWithNoContent()

Test whether the HTTP sender able to send the HTTP header to our monitor successfully.

testSendWithParameter
public void testSendWithParameter()

Test whether the HTTP sender able to send the HTTP header with POST parameter to our monitor successfully.

testServiceEndpointProperty
public void testServiceEndpointProperty()

Test HttpSender.setServiceEndPoint(URL) *

testServiceEndpointPropertyWithInvalidData
public void testServiceEndpointPropertyWithInvalidData()

Test whether HttpSender.setServiceEndPoint(String) with invalid data.

testUserObjectProperty
public void testUserObjectProperty()

Test HttpSender.getUserObject() *

PartnershipOp

public interface PartnershipOp

The PartnershipOperation is the signature interface for providing a clue that the implemented class should able to handle add/delete/update operation one or more kind of partnerships.

Author:Twinsen Tsang

Fields

ADD
int ADD

The constant field indicate the adding partnership operation *

DELETE
int DELETE

The constant field indicate the deleting partnership operation *

OP_LEN
int OP_LEN

The constant field indicate the total number of partnership operation enumeration. DO NOT USE. *

UPDATE
int UPDATE

The constant field indicate the update partnership operation *

Methods

getExecuteOperation
int getExecuteOperation()
Returns:Get the partnership operation type for execution.
setExecuteOperation
void setExecuteOperation(int op)

The interface contract indicate the partnership operation you want to execute to the realizing class. The op should be greater than zero and less than {@value #OP_LEN}.

Parameters:
  • op – The partnership operation type.

PartnershipOpVerifer

public class PartnershipOpVerifer

The PartnershipOpVerifer is an helper class for verifying whether the partnership operation has been executed successfully. Since H2O does not have any build-in SOAP-based web service for managing the partnerships under remote behavior, The PartnershipOpVerifer acts as a validator for validating the HTML content returning from the H2O administration web page. The main method of this class is validate(InputStream) and the arugment is the input stream. The input stream SHOULD contains the HTML content after you executed add/delete/update partnership in either AS2/EBMS partnership administration page.

Author:Twinsen Tsang

Fields

OP_ADD_SUCCESS
public static final String OP_ADD_SUCCESS
OP_DELETE_SUCCESS
public static final String OP_DELETE_SUCCESS
OP_NO
public static final String OP_NO
OP_UPDATE_SUCCESS
public static final String OP_UPDATE_SUCCESS
logger
final Logger logger

Constructors

PartnershipOpVerifer
public PartnershipOpVerifer()

Default constructor.

Methods

validate
public void validate(InputStream ins)

Validate the HTML content received after executed partnership operation. The content is passed as a input stream ins. This operation is quite expensive because it first transform the whole HTML content received to a well-formed XHTML before parsing by the SAX Parser.

Parameters:
  • ins – The HTML content to validate the result of partnership operation
Throws:
  • SAXException
    1. When unable to down-load the HTML DTD from the web. Check your Internet connectivity
    2. When IO related problems occur
  • ParserConfigurationException – When SAX parser mis-configures.

PartnershipOpVeriferUnitTest

public class PartnershipOpVeriferUnitTest extends TestCase

The PartnershipOpVeriferUnitTest is unit test of PartnershipOpVerifer.

Author:Twinsen Tsang

Fields

ADDOP_SUCCESS_SAMPLE
public static final String ADDOP_SUCCESS_SAMPLE
DELETEOP_SUCCESS_SAMPLE
public static final String DELETEOP_SUCCESS_SAMPLE
ERROR_SAMPLE_0
public static final String ERROR_SAMPLE_0
ERROR_SAMPLE_1
public static final String ERROR_SAMPLE_1
UPDATEOP_SUCCESS_SAMPLE
public static final String UPDATEOP_SUCCESS_SAMPLE
logger
Logger logger

Methods

initTestTarget
public void initTestTarget()

Initialize the test target which is a Partnership Operation Verifier.

setUp
public void setUp()

Setup the fixture.

tearDown
public void tearDown()

Setup the fixture.

testValidateAddSuccess
public void testValidateAddSuccess()

Test whether the validation process execute property for add operation executed properly. *

testValidateDeleteSuccess
public void testValidateDeleteSuccess()

Test whether the validation process execute property for delete operation executed properly. *

testValidateUpdateSuccess
public void testValidateUpdateSuccess()

Test whether the validation process execute property for update operation executed properly. *

testValidateWithErrorSample0
public void testValidateWithErrorSample0()

Test whether the validation process throw exception when the HTML content violate the field constraint (this case, ‘Retry Interval must be integer’);

testValidateWithErrorSample1
public void testValidateWithErrorSample1()

Test whether the validation process throw exception when the HTML content violate the field constraint (this case, ‘CPA ID cannot be empty’);

testValidateWithNullStream
public void testValidateWithNullStream()

Test whether it throws exception when null stream is passed as arugment *

PartnershipSender

public abstract class PartnershipSender extends HttpSender implements PartnershipOp

The PartnershipSender is abstract base class for sending HTTP remote request to H2O for executing partnership maintenance operation.

Author:Twinsen Tsang

Constructors

PartnershipSender
protected PartnershipSender(FileLogger logger, KVPairData d)

Explicit Constructor. Create an instance of PartnershipSender

Parameters:
  • logger – The logger for log the sending process.
  • d – The data used for generate HTTP multi-part request. It must be a kind of partnership data.
PartnershipSender
protected PartnershipSender(FileLogger logger, KVPairData d, String username, String password)

Explicit Constructor. Create an instance of PartnershipSender

Parameters:
  • logger – The logger for log the sending process.
  • d – The data used for generate HTTP multi-part request. It must be a kind of partnership data.
  • username – The username for authentication
  • password – The password for authentication

Methods

getExecuteOperation
public int getExecuteOperation()
getPartnershipMapping
public abstract Map getPartnershipMapping()

Get the mapping of the partnership data key to HTTP form parameter name. For example, if there are 3 data (with keys) in your partnership data and they are named as “dataKey0”, “dataKey1” and “dataKey2”, and you want the HTTP request going to execute containing multi-part parameters “formParam0”, “formParam1” and “formParam2” with the value equal to the data value from “dataKey0”, “dataKey1”, “dataKey2” respectively, Then you should return the Map listed below:

Map m = new HashMap(); // Or LinkedHashMap() if you want to preserve the order.
m.put("dataKey0", "fromParam0");
m.put("dataKey1", "fromParam1");
m.put("dataKey2", "fromParam2");
return m;
Returns:The mapping of the partnership data key to HTTP form parameter name.
getPartnershipOperationMapping
public abstract Map getPartnershipOperationMapping()

Get the mapping of the partnership operation from integer to words. By default, it is recommended to return a HashMap(Integer, String) with 3 mappings. HashMap.get(0) = A word representing the add partnership action. HashMap.get(1) = A word representing the delete partnership action. HashMap.get(2) = A word representing the update partnership action.

Returns:The mapping of the partnership operation from integer to words.
getStatus
public String getStatus()

Get the last status result description after executing the operation. If the sender has not been invoked by other to execute partnership operation, It returns “Not yet run”.

Returns:the last status result description after executing the operation.
onCreateRequest
protected HttpRequestBase onCreateRequest()

[@EVENT] This method is invoked when the sender is required to create a HTTP Request from configuration. It generates a multi-part content embedded in the HTTP POST request. The multi-part content contains all partnership data with the parameter name retrieved from the partnership mapping. getPartnershipMapping(). Also the type of partnership operation is appended at the end of multi-part with parameter name equal to ‘request_action’ and it’s value is extracted thru getPartnershipOperationMapping().

onResponse
protected void onResponse()

[@EVENT] This method is invoked when receivedas2 the reply HTTP response from the server. Verify the HTTP response (expected a HTML content) by PartnershipOpVerifer to check whether the partnership operation execute successfully or not.

Throws:
  • SAXException – When fail to verify by PartnershipOpVerifer.
onStart
protected void onStart()

[@EVENT] The method onStart log all new configuration.

setExecuteOperation
public void setExecuteOperation(int pOp)

PartnershipSenderUnitTest

public class PartnershipSenderUnitTest extends TestCase

The PartnershipSenderUnitTest is unit test of PartnershipSender. TODO: Inadequate Test-case for error path.

Author:Twinsen Tsang

Fields

PASSWORD
public static final String PASSWORD
TEST_ENDPOINT
public static final String TEST_ENDPOINT
TEST_PORT
public static final int TEST_PORT
USER_NAME
public static final String USER_NAME
kvData
protected KVPairData kvData
logger
Logger logger
target
protected PartnershipSender target

The testing target which is an PartnershipSender and the associated data

testClassLogger
protected FileLogger testClassLogger

Methods

initTestData
public void initTestData()

Initialize the test data *

initTestTarget
public void initTestTarget()

Initialize the test target which is a PartnershipSender.

setUp
public void setUp()

Setup the fixture.

tearDown
public void tearDown()

Stop the HTTP monitor preventing JVM port binding *

testAddPartnership
public void testAddPartnership()

Test whether the add partnership request operation perform correctly *

testDeletePartnership
public void testDeletePartnership()

Test whether the update partnership request operation perform correctly *

testUpdatePartnership
public void testUpdatePartnership()

Test whether the update partnership request operation perform correctly *

hk.hku.cecid.corvus.partnership

AS2Partnership

public class AS2Partnership

The AS2Partnership is the utilities for maintaining the partnership of AS2. In current version, it support addition or deletion of the partnership.

Author:kochiu, Twinsen Tsang (modifiers)

See also: .createAS2Partnership(String), .removeAS2Partnership(String)

Methods

createAS2Partnership
public static boolean createAS2Partnership(String xmlFile)

Create a AS2 partnership with the configuration defined in the XMLFile.

Parameters:
  • xmlFile – The partnership XML instance file. It is located at “/data/as2.xml”.
Throws:
  • DAOException – Error in persistence connectivity.
  • DocumentException – Error in reading the parameter in the xmlFile.
  • SAXException – Error in parsing the xmlFile.
  • IOException
Returns:

true if the removal operation ran successfully.

main
public static void main(String[] args)

The entry point for CLI.

Parameters:
  • args – The arguments have two parametes. The first one is the partnership maintenance which is either “-a” (add) or “-d” (delete). The second one is the xml file containing the partnership information. They are located at the “conf/as2.xml” relative to the program folders.
removeAS2Partnership
public static boolean removeAS2Partnership(String xmlFile)

Remove a particular partnership defined in the xmlFile. Only the attributes <id> in the xmlFile will be used for removing partnership.

Parameters:
  • xmlFile – The partnership XML instance file. It is located at “/data/ebms.xml”.
Throws:
  • DAOException – Error in persistence connectivity.
  • DocumentException – Error in reading the parameter in the xmlFile.
  • SAXException – Error in parsing the xmlFile.
  • IOException
Returns:

true if the removal operation ran successfully.

EbmsPartnership

public class EbmsPartnership

The EbmsPartnership is the utilities for maintaining the partnership of EbMS. In current version, it support addition or deletion of the partnership.

Author:kochiu, Twinsen Tsang (modifiers)

See also: .createEbmsPartnership(String), .removeEbmsPartnership(String)

Methods

createEbmsPartnership
public static boolean createEbmsPartnership(String xmlFile)

Create a EbMS partnership with the configuration defined in the XMLFile.

Parameters:
  • xmlFile – The partnership XML instance file. It is located at “/data/ebms.xml”.
Throws:
  • DAOException – Error in persistence connectivity.
  • DocumentException – Error in reading the parameter in the xmlFile.
  • SAXException – Error in parsing the xmlFile.
  • IOException
Returns:

true if the removal operation ran successfully.

main
public static void main(String[] args)

The entry point for CLI.

Parameters:
  • args – The arguments have two parametes. The first one is the partnership maintenance which is either “-a” (add) or “-d” (delete). The second one is the xml file containing the partnership information. They are located at the “conf/ebms.xml” relative to the program folders.
removeEbmsPartnership
public static boolean removeEbmsPartnership(String xmlFile)

Remove a particular partnership defined in the xmlFile. Only the attributes <id> in the xmlFile will be used for removing partnership.

Parameters:
  • xmlFile – The partnership XML instance file. It is located at “/data/ebms.xml”.
Throws:
  • DAOException – Error in persistence connectivity.
  • DocumentException – Error in reading the parameter in the xmlFile.
  • SAXException – Error in parsing the xmlFile.
  • IOException
Returns:

true if the removal operation ran successfully.

Utilities

public class Utilities

Comment for Utilities.java.

Author:kochiu

Methods

getBooleanValue
public static boolean getBooleanValue(Element params, String paramName)
isValidCert
public static boolean isValidCert(byte[] cert)
loadCert
public static byte[] loadCert(String filepath)

hk.hku.cecid.corvus.util

DateUtil

public class DateUtil

An utility for converting from java datetime to UTC conformed datetime and vice versa.

  1. Fixed a bug that it parses UTC datetime with ‘Z’ timezone incorrectly becasue it used wrong timezone (GMT, but not UTC). (Thank Martin Kalen for figure out this)
  2. Added datetime / calendar two UTC convertion.
Author:Twinsen Tsang, (modifier Philip Wong)

Methods

GMT2Calender
public static Calendar GMT2Calender(String dateTime)

Convert an GMT representation of string dateTime to java calendar object.

Parameters:
  • dateTime – A string representing a GMT datetime.
Throws:
Returns:

The millisecond representing the dateTime

GMT2Date
public static Date GMT2Date(String dateTime)

Convert an GMT representation of string dateTime to java Date object.

Parameters:
  • dateTime – A string representing a GMT datetime.
Throws:
Returns:

A java date object representing the dateTime

GMT2MS
public static long GMT2MS(String dateTime)

Convert an GMT representation of string dateTime to millisecond.

Parameters:
  • dateTime – A string representing a GMT datetime.
Throws:
Returns:

The millisecond representing the dateTime

GMT2Timestamp
public static Timestamp GMT2Timestamp(String dateTime)

Convert an GMT representation of string dateTime to java Timestamp object.

Parameters:
  • dateTime – A string representing a GMT datetime.
Throws:
Returns:

A java timestamp object representing the dateTime

UTC2Calendar
public static Calendar UTC2Calendar(String dateTime)

Convert an UTC representation of string dateTime to java calendar object. Followings are UTC conformed patterns:

  • 2007-07-16T13:24:56
  • 2007-07-16T13:24:56Z
  • 2007-07-16T13:24:56.789
  • 2007-07-16T13:24:56.789Z
  • 2007-07-16T13:24:56+02:00
  • 2007-07-16T13:24:56-02:00
  • 2007-07-16T13:24:56.789+02:00
  • 2007-07-16T13:24:56.789-02:00
Parameters:
  • dateTime – A string representing a UTC datetime.
Throws:
Returns:

A java clendar object representing the dateTime

UTC2Date
public static Date UTC2Date(String dateTime)

Convert an UTC representation of string dateTime to java Date object. Followings are UTC conformed patterns:

  • 2007-07-16T13:24:56
  • 2007-07-16T13:24:56Z
  • 2007-07-16T13:24:56.789
  • 2007-07-16T13:24:56.789Z
  • 2007-07-16T13:24:56+02:00
  • 2007-07-16T13:24:56-02:00
  • 2007-07-16T13:24:56.789+02:00
  • 2007-07-16T13:24:56.789-02:00
Parameters:
  • dateTime – A string representing a UTC datetime.
Throws:
Returns:

A java date object representing the dateTime.

UTC2MS
public static long UTC2MS(String dateTime)

Convert an UTC representation of string dateTime to millisecond. Followings are UTC conformed patterns:

  • 2007-07-16T13:24:56
  • 2007-07-16T13:24:56Z
  • 2007-07-16T13:24:56.789
  • 2007-07-16T13:24:56.789Z
  • 2007-07-16T13:24:56+02:00
  • 2007-07-16T13:24:56-02:00
  • 2007-07-16T13:24:56.789+02:00
  • 2007-07-16T13:24:56.789-02:00
Parameters:
  • dateTime – A string representing a UTC datetime.
Throws:
Returns:

The millisecond representing by dateTime.

UTC2Timestamp
public static Timestamp UTC2Timestamp(String dateTime)

Convert an UTC representation of string dateTime to java Timestamp object. Followings are UTC conformed patterns:

  • 2007-07-16T13:24:56
  • 2007-07-16T13:24:56Z
  • 2007-07-16T13:24:56.789
  • 2007-07-16T13:24:56.789Z
  • 2007-07-16T13:24:56+02:00
  • 2007-07-16T13:24:56-02:00
  • 2007-07-16T13:24:56.789+02:00
  • 2007-07-16T13:24:56.789-02:00
Parameters:
  • dateTime – A string representing a UTC datetime.
Throws:
Returns:

A java timestamp object representing the dateTime.

calendar2UTC
public static String calendar2UTC(Calendar dateTime)

Convert a calendar dateTime to UTC conformed representation of string.

Parameters:
  • dateTime – A java calendar representing the time you want to convert.
Throws:
Returns:

an UTC conformed representation with time specified by dateTime

date2UTC
public static String date2UTC(Date dateTime, TimeZone timeZone)

Convert a date dateTime to UTC conformed representation of string. (e.g. 2007-07-16T13:24:56.789+13:00)

Parameters:
  • dateTime – A java date representing the time you want to convert.
  • timeZone – The timezone of the dateTime. If it is null, it use the default timezone in the machine.
Throws:
Returns:

an UTC conformed representation with time specified by dateTime

getCurrentUTCDateTime
public static String getCurrentUTCDateTime()
Returns:Get the current datetime with respect to the default timezone in UTC conformed representation.

FileLogger

public class FileLogger extends Component implements Logger

The file logger is a simple logger that log everything to the desired file. Dependency : Piazza Common The sample usage is shown on the below:

 FileLogger log = new FileLogger("../logs/testlog.txt");
log.debug("Test debug statement");
log.error("Test error statement");
log.fatal("Test fatal statement");
log.info ("Test info  statement");
log.warn ("Test warn  statement");

The output in the file logger should be liked these:

[Debug] Test debug statement
[Error] Test error statement
[Fatal] Test fatal statement
[Info]  Test info statement
[Warn]  Test warn statement

SPA Component Guideline:.

Author:Twinsen Tsang

Constructors

FileLogger
public FileLogger(String filepath)

Constructor.

Parameters:
  • filepath – The filepath for logging.
Throws:
  • UtiltiesException – Throw if any IO Operations fail like can not open file or print stream.
FileLogger
public FileLogger(File f)

Constructor. The file logger open a file output stream for writing the log to the file. It use the default log file name “log.txt” for logging if the file object is a directory.

Parameters:
  • f – The file object specified.
Throws:
  • UtilitiesException – Throw if any IO Operations fail like can not open file or print stream.

Methods

debug
public void debug(Object msg)

Override debug print method.

Parameters:
  • msg – debugging object to be printed.
debug
public void debug(Object msg, Throwable t)

Override debug with exception print method.

Parameters:
  • msg – debugging object to be printed.
error
public void error(Object msg)

Override error print method.

Parameters:
  • msg – errorging object to be printed.
error
public void error(Object msg, Throwable t)

Override error with exception print method.

Parameters:
  • msg – errorging object to be printed.
fatal
public void fatal(Object msg)

Override fatal print method.

Parameters:
  • msg – fatalging object to be printed.
fatal
public void fatal(Object msg, Throwable t)

Override fatal with exception print method.

Parameters:
  • msg – fatalging object to be printed.
finalize
protected void finalize()

The method finalized the class.

info
public void info(Object msg)

Override info print method.

Parameters:
  • msg – infoging object to be printed.
info
public void info(Object msg, Throwable t)

Override info with exception print method.

Parameters:
  • msg – infoging object to be printed.
init
protected void init()

Override initialization method. It invokes when the logger is acted as Module Component.

log
public void log(String s)

Log a string to the file by the print stream.

Parameters:
  • s – The string to be logged.
logStackTrace
public void logStackTrace(Throwable e)

Log a exception / throwable to the file by the print stream. The exception element will begin with the tag [Stack Trace] other than debug, error, fatal, warn, info.

Parameters:
  • e – The throwable e to be logged.
toString
public String toString()

toString method().

warn
public void warn(Object msg)

Override warn print method.

Parameters:
  • msg – warnging object to be printed.
warn
public void warn(Object msg, Throwable t)

Override warn with exception print method.

Parameters:
  • msg – warnging object to be printed.

SOAPUtilities

public class SOAPUtilities

The SOAPUtilities acts as a SOAP Helper for some operations that frequently used. Currently supported operations:

  • create a SOAP Element with specified tag name, value, ns prefix and uri (Also an attributes set).
  • get a SOAP Element with specified tag name, ns prefix and uri and which nth tag from a SOAP Message.
  • get a list of SOAP Element with specified tag name, ns prefix and uri from a SOAP Message.
Author:Twinsen

Methods

countElement
public static int countElement(SOAPMessage message, String tagname, String nsURI)

Count how many element with tagname and nsURI is in SOAPMessage message.

Parameters:
  • message – The SOAP message
  • tagname – The name of the tag to be counted.
  • nsURI – The namespace URI of the tag.
Throws:
  • SOAPException
Returns:

The number of element in the SOAP message.

createElement
public static SOAPElement createElement(String tagName, String tagValue, String nsPrefix, String nsURI)

Create a SOAP Element with the specified parameters.

Parameters:
  • tagName – the name of XML tag.
  • tagValue – the value of XML tag.
  • nsPrefix – the namespace prefix.
  • nsURI – the namespace URL.
Returns:

the new SOAP element created.

createElement
public static SOAPElement createElement(String tagName, String tagValue, String nsPrefix, String nsURI, Hashtable attrSet)

Create a SOAP Element with the specified parameters.

Also it create the attributes set as the parameter properties.

Parameters:
  • tagName – the name of XML tag.
  • tagValue – the value of XML tag.
  • nsPrefix – the namespace prefix.
  • nsURI – the namespace URL.
  • attrSet – the attributes set in the element.
Returns:

the new SOAP element created.

getElement
public static SOAPElement getElement(SOAPMessage message, String tagname, String nsURI, int whichOne)

Get a SOAP Element from the SOAPMessage (SOAPbody inside).

Parameters:
  • message – The SOAP message to be searched with.
  • tagname – The tag name of element to be retrieved.
  • nsURI – The namespace URI.
  • whichOne – The nth child element to be returned.
Returns:

The element in the tagname specified.

getElementList
public static List getElementList(SOAPMessage message, String tagname, String nsURI)

Get a SOAP Element list from the SOAPMessage (SOAPbody inside).

Parameters:
  • message – The SOAP message to be searched with.
  • tagname – The tag name of element to be retrieved.
  • nsURI – The namespace URI.
Throws:
  • SOAPException
Returns:

list of SOAP element

linkElements
public static boolean linkElements(SOAPMessage message, String parentTagName, String parentNsURI, String childTagName, String childNsURI)

Validate the existence of child SOAP element given the parent element.

Parameters:
  • message
  • parentTagName
  • parentNsURI
  • childTagName
  • childNsURI
Throws:
  • SOAPException
Returns:

true if child element exists

hk.hku.cecid.corvus.ws

AS2ConfigSender

public class AS2ConfigSender extends SOAPSender

The AS2ConfigSender is a client sender sending SOAP web services request to B2BCollector AS2 plugin for configurating the performance factor. The web service parameters are defined in the below:

<active-module-status> true | false </active-module-status>
<inmessage-interval>15000</inmessage-interval>
<inmessage-maxthread>0</inmessage-maxthread>
<outmessage-interval>15000</outmessage-interval>
<outmessage-maxthread>0</outmessage-maxthread>
<outpayload-interval>15000</outpayload-interval>
<outpayload-maxthread>0</outpayload-maxthread>
Author:Twinsen Tsang

Constructors

AS2ConfigSender
public AS2ConfigSender(FileLogger l, AS2ConfigData data)

Explicit Constructor.

Parameters:
  • l – The logger used for log message and exception.
  • data – The AS2 Configuration parameters.

Methods

getStatus
public String getStatus()
Returns:Get the result status for the last successful web services call.
initializeMessage
public void initializeMessage()

The SOAPRequest in the creation stage should be liked this.

Throws:
  • Exceptions
main
public static void main(String[] args)

The main method is for CLI mode.

onResponse
public void onResponse()

Get the SOAP Body and analyze the result of configuration.

The result of SOAP body:

<status>success | fail</status>
onStart
public void onStart()

[@EVENT] The method onStart log all new configuration.

AS2MessageHistoryQuerySender

public class AS2MessageHistoryQuerySender extends SOAPSender

Fields

NAMESPACE
public static String NAMESPACE

Constructors

AS2MessageHistoryQuerySender
public AS2MessageHistoryQuerySender(FileLogger l, AS2MessageHistoryRequestData m)

Methods

getAvailableMessages
public List getAvailableMessages()
getResponseElementList
public List getResponseElementList(String tagname, String nsURI, int whichOne)
initializeMessage
public void initializeMessage()
main
public static void main(String[] args)

The main method is for CLI mode.

onResponse
public void onResponse()
onStart
public void onStart()

AS2MessageReceiver

public class AS2MessageReceiver extends MessageReceiver

Constructors

AS2MessageReceiver
public AS2MessageReceiver(FileLogger l, AS2MessageData m)

Methods

getMessageIdToRetreive
public String getMessageIdToRetreive()
Returns:the message id to retreive.
getOutputDirectory
public String getOutputDirectory()
Returns:the output directory of the received payload.
getResponsePayloads
public Payload[] getResponsePayloads()
initializeMessage
public void initializeMessage()

Initialize the message using the properties in the MessageProps.

main
public static void main(String[] args)

The main method is for CLI mode.

onResponse
public void onResponse()

Retrieve the payload from the message. The default receiver stores the payload as a files at the particular place specified in the configuration.

onStart
public void onStart()

Initialize the SOAP Message.

setMessageIdToRetreive
public void setMessageIdToRetreive(String messageId)
Parameters:
  • messageId – the message id to retreive the payload / message.
setOutputDirectory
public void setOutputDirectory(String path)

Set the output directory of received payload if any.

AS2MessageSender

public class AS2MessageSender extends MessageSender

The AS2MessageSender is a client sender sending SOAP web services request to B2BCollector AS2 plugin for transmission a AS2 message to other parnter. The web service parameters are defined in the below:

<part name="as2_from" type="s:string" />
<part name="as2_to" type="s:string" />
<part name="type" type="s:string" />
Author:Twinsen Tsang

Fields

NS_URI
protected static final String NS_URI

The Namespace URI

Constructors

AS2MessageSender
public AS2MessageSender(FileLogger l, AS2MessageData m, AS2PartnershipData p)

Explicit Constructor.

Parameters:
  • l – The logger used for log message and exception.
  • m – The message data for party information and send/recv configuration.
  • p – The partnership data.

Methods

addRequestPayload
public boolean addRequestPayload(Payload[] payloads)
getResponseMessageId
public String getResponseMessageId()

Get the message id of last successful web service query. This should be called only after onResponse()

Returns:the message id
initializeMessage
public void initializeMessage()

Initialize the message using the properties in the MessageProps.

main
public static void main(String[] args)

The main method is for CLI mode.

onResponse
public void onResponse()

Record the message id.

onStart
public void onStart()

Initialize the SOAP Message.

AS2PermitRedownloadSender

public class AS2PermitRedownloadSender extends PermitRedownloadServiceSender

Constructors

AS2PermitRedownloadSender
public AS2PermitRedownloadSender(FileLogger l, Data m)

Methods

getNSURI
protected String getNSURI()
main
public static void main(String[] args)

The main method is for CLI mode.

onError
public void onError(Throwable t)
onResponse
public void onResponse()

AS2ReceiverListSender

public class AS2ReceiverListSender extends MessageSender

The AS2ReceiverListSender is a client sender sending SOAP web services request to B2BCollector AS2 plugin for query whether if there is any message that are available. The web service parameters are defined in the below:

<part name="as2From" type="s:string" />
<part name="as2To" type="s:string" />
<part name="numOfMessages" type="s:int" />
Author:Twinsen Tsang

Constructors

AS2ReceiverListSender
public AS2ReceiverListSender(FileLogger l, AS2MessageData m, AS2PartnershipData p)

Explicit Constructor.

Parameters:
  • l – The logger used for log message and exception.
  • m – The message data for party information and send/recv configuration.
  • p – The partnership data.

Methods

getAvailableMessages
public List getAvailableMessages()

This method should be called after the event onResponse()

Returns:a list of message id that are ready to download.
getNumOfMessageToRetrieve
public int getNumOfMessageToRetrieve()
Returns:number of message to retrieve for one soap call.
initializeMessage
public void initializeMessage()

Initialize the message using the properties in the MessageProps.

main
public static void main(String[] args)

The main method is for CLI mode.

onResponse
public void onResponse()

[@EVENT] Record all the AS2 message that ready to download. Developer should invocate getAvailableMessages() to get a list of all ready AS2 message.

onStart
public void onStart()

Initialize the SOAP Message.

setNumOfMessageToRetrieve
public void setNumOfMessageToRetrieve(int numMsgs)

Set number of message to retrieve for one soap call.

Parameters:
  • numMsgs – number of message to retrieve for one soap call.

AS2ReceiverSender

public class AS2ReceiverSender extends AS2MessageSender

The AS2ReceiverSender is a client sender sending SOAP web services request to Hermes Messaging Gateway AS2 plugin for down-loading the AS2 message and it’s corresponding payload.

Author:Twinsen Tsang

Constructors

AS2ReceiverSender
public AS2ReceiverSender(FileLogger l, AS2MessageData m, AS2PartnershipData ps)

Explicit Constructor.

Parameters:
  • l – The logger used for log message and exception.
  • m – The message data for party information and send/recv configuration.
  • ps – The partnership data.

Methods

getMessageIdToRetreive
public String getMessageIdToRetreive()
Returns:the message id to retreive.
getOutputDirectory
public String getOutputDirectory()
Returns:the output directory of the received payload.
initializeMessage
public void initializeMessage()

Initialize the message using the properties in the MessageProps.

main
public static void main(String[] args)

The main method is for CLI mode.

onResponse
public void onResponse()

Retrieve the payload from the message. The default receiver stores the payload as a files at the particular place specified in the configuration.

onStart
public void onStart()

Initialize the SOAP Message.

setMessageIdToRetreive
public void setMessageIdToRetreive(String messageId)
Parameters:
  • messageId – the message id to retreive the payload / message.
setOutputDirectory
public void setOutputDirectory(String path)

Set the output directory of received payload if any.

AS2StatusQuerySender

public class AS2StatusQuerySender extends SOAPSender

The AS2StatusQuerySender is a client sender sending SOAP web services request to Corvus AS2 plugin for query the status of particular message. The web service parameters are defined in the below:

<messageId> 20070418-124233-75006@147.8.177.42 </messageId>

Creation Date: 02/05/2007

Author:Twinsen Tsang

Constructors

AS2StatusQuerySender
public AS2StatusQuerySender(FileLogger l, AS2StatusQueryData data)

Explicit Constructor.

Parameters:
  • l – The logger used for log message and exception.
  • data – The AS2 Status query parameter.

Methods

getLastResponseData
public AS2StatusQueryResponseData getLastResponseData()
Returns:The AS2 status response data by the last SFRM status query SOAP Call.
initializeMessage
public void initializeMessage()

The SOAPRequest in the creation stage should be liked this.

Throws:
  • Exceptions
main
public static void main(String[] args)

The main method is for CLI mode.

onResponse
public void onResponse()

Get the SOAP Body and analyze the result of configuration.

The result of SOAP body:

   <status> The current status of message </status>
<statusDescription> The current status description of message </statusDescription>
<ackMessageId> The message id of acknowledgment / receipt if any </ackMessageId>
<ackStatus> The status of acknowledgment / receipt if any </ackStatus>
<ackStatusDescription> The status description of acknowledgment / receipt if any </ackStatusDescription>
onStart
public void onStart()

[@EVENT] The method onStart log all new configuration.

EBMSConfigSender

public class EBMSConfigSender extends SOAPSender

The EBMSConfigSender is a client sender sending SOAP web services request to B2BCollector EBMS plugin for configurating the performance factor. The web service parameters are defined in the below:

<active-module-status> true | false </active-module-status>
<incollector-interval>15000</incollector-interval>
<incollector-maxthread>0</incollector-maxthread>
<outcollector-interval>15000</outcollector-interval>
<outcollector-maxthread>0</outcollector-maxthread>
<mailcollector-interval>15000</mailcollector-interval>
<mailcollector-maxthread>0</mailcollector-maxthread>
Author:Twinsen Tsang

Constructors

EBMSConfigSender
public EBMSConfigSender(FileLogger l, EBMSConfigData data)

Explicit Constructor.

Parameters:
  • l – The logger used for log message and exception.
  • data – The EBMS Configuration parameters.

Methods

getStatus
public String getStatus()
Returns:Get the result status for the last successful web services call.
initializeMessage
public void initializeMessage()

The SOAPRequest in the creation stage should be liked this.

Throws:
  • Exceptions
main
public static void main(String[] args)

The main method is for CLI mode.

onResponse
public void onResponse()

Get the SOAP Body and analyze the result of configuration.

The result of SOAP body:

<status>success | fail</status>
onStart
public void onStart()

[@EVENT] The method onStart log all new configuration.

EBMSMessageHistoryQuerySender

public class EBMSMessageHistoryQuerySender extends SOAPSender

Fields

NAMESPACE
public static String NAMESPACE

Constructors

EBMSMessageHistoryQuerySender
public EBMSMessageHistoryQuerySender(FileLogger l, EBMSMessageHistoryRequestData m)

Methods

getAvailableMessages
public List getAvailableMessages()
getResponseElementList
public List getResponseElementList(String tagname, String nsURI, int whichOne)
initializeMessage
public void initializeMessage()
main
public static void main(String[] args)

The main method is for CLI mode.

onResponse
public void onResponse()
onStart
public void onStart()

EBMSMessageHistoryQuerySenderTest

public class EBMSMessageHistoryQuerySenderTest extends TestCase

Fields

PASSWORD
public static final String PASSWORD
TEST_ENDPOINT
public static final String TEST_ENDPOINT
TEST_PORT
public static final int TEST_PORT
USER_NAME
public static final String USER_NAME
kvData
protected KVPairData kvData
logger
Logger logger
target
protected EBMSMessageHistoryQuerySender target

The testing target which is an PartnershipSender and the associated data

testClassLogger
protected FileLogger testClassLogger

Methods

initTest
public void initTest()
setUp
public void setUp()

Setup the fixture.

tearDown
public void tearDown()
testFail_NegativeQueryLimit
public void testFail_NegativeQueryLimit()
testNormalCriteriaData
public void testNormalCriteriaData()
testNullCriteriaData
public void testNullCriteriaData()
testSpecialCharacterCriteriaData
public void testSpecialCharacterCriteriaData()
testWildcardCriteriaData
public void testWildcardCriteriaData()

EBMSMessageReceiver

public class EBMSMessageReceiver extends MessageReceiver

The EBMSMessageReceiver is a client sender sending SOAP web services request to B2BCollector EbMS plugin for retrieving a ebMS message according to provided message id. The web service parameters are defined in the below:

<part name="messageId" type="s:string" /> *
Author:Jumbo Cheung

See also: hk.hku.cecid.corvus.ws.data.EBMSMessageData

Constructors

EBMSMessageReceiver
public EBMSMessageReceiver(FileLogger l, EBMSMessageData m)

Methods

getOutputDirectory
public String getOutputDirectory()
Returns:the output directory of the received payload.
initializeMessage
public void initializeMessage()

Initialize the message using the properties in the MessageProps.

main
public static void main(String[] args)
onResponse
public void onResponse()

Retrieve the payload from the message. The default receiver stores the payload as a files at the particular place specified in the configuration.

onStart
public void onStart()

Initialize the SOAP Message.

setOutputDirectory
public void setOutputDirectory(String path)

Set the output directory of received payload if any.

EBMSMessageSender

public class EBMSMessageSender extends MessageSender

The EBMSMessageSender is a client sender sending SOAP web services request to B2BCollector EbMS plugin for transmission a ebMS message to other parnter. The web service parameters are defined in the below:

<part name="cpaId" type="s:string" />
<part name="service" type="s:string" />
<part name="action" type="s:string" />
<part name="convId" type="s:string" />
<part name="fromPartyId" type="s:string" />
<part name="fromPartyType" type="s:string" />
<part name="toPartyId" type="s:string" />
<part name="toPartyType" type="s:string" />
<part name="refToMessageId" type="s:string" />
<part name="serviceType" type="s:string" />
Author:Twinsen Tsang

See also: hk.hku.cecid.corvus.ws.data.EBMSMessageData, hk.hku.cecid.corvus.ws.data.EBMSPartnershipData

Fields

NS_URI
protected static final String NS_URI

The Namespace URI

Constructors

EBMSMessageSender
public EBMSMessageSender(FileLogger l, EBMSMessageData m, EBMSPartnershipData p)

Explicit Constructor.

Parameters:
  • l – The logger used for log message and exception.
  • m – The message data for party information and send/recv configuration.
  • p – The partnership data.

Methods

getResponseMessageId
public String getResponseMessageId()

Get the message id of last successful web service query. This should be called only after onResponse()

Returns:the message id
initializeMessage
public void initializeMessage()

Initialize the message using the properties in the MessageProps.

main
public static void main(String[] args)

The main method is for CLI mode.

onResponse
public void onResponse()

[@EVENT] Retrieve the id of newly created message from the SOAP message.

onStart
public void onStart()

Initialize the SOAP Message.

EBMSPermitRedownloadSender

public class EBMSPermitRedownloadSender extends PermitRedownloadServiceSender

Constructors

EBMSPermitRedownloadSender
public EBMSPermitRedownloadSender(FileLogger l, Data m)

Methods

getNSURI
protected String getNSURI()
main
public static void main(String[] args)

The main method is for CLI mode.

onError
public void onError(Throwable t)
onResponse
public void onResponse()

EBMSReceiverListSender

public class EBMSReceiverListSender extends MessageSender

The EBMSReceiverListSender is a client sender sending SOAP web services request to H2O EbMS plugin for query whether if there is any message that are available. The web service parameters are defined in the below:

<part name="cpaId" type="s:string" />
<part name="service" type="s:string" />
<part name="action" type="s:string" />
<part name="convId" type="s:string" />
<part name="fromPartyId" type="s:string" />
<part name="fromPartyType" type="s:string" />
<part name="toPartyId" type="s:string" />
<part name="toPartyType" type="s:string" />
<part name="numOfMessages" type="s:int" />
Author:Twinsen Tsang

Constructors

EBMSReceiverListSender
public EBMSReceiverListSender(FileLogger l, EBMSMessageData m, EBMSPartnershipData p)

Explicit Constructor.

Parameters:
  • l – The logger used for log message and exception.
  • m – The message data for party information and send/recv configuration.
  • p – The partnership data.

Methods

getAvailableMessages
public List getAvailableMessages()

This method should be called after the event onResponse()

Returns:a list of message id that are ready to download.
getNumOfMessageToRetrieve
public int getNumOfMessageToRetrieve()
Returns:number of message to retrieve for one soap call.
initializeMessage
public void initializeMessage()

Initialize the message using the properties in the MessageProps.

main
public static void main(String[] args)

The main method is for CLI mode.

onResponse
public void onResponse()

[@EVENT] Record all the EbMS message that ready to download. Developer should invocate getAvailableMessages() to get a list of all ready EbMS message.

onStart
public void onStart()

Initialize the SOAP Message.

setNumOfMessageToRetrieve
public void setNumOfMessageToRetrieve(int numMsgs)

Set number of message to retrieve for one soap call.

Parameters:
  • numMsgs – number of message to retrieve for one soap call.

EBMSReceiverSender

public class EBMSReceiverSender extends EBMSMessageSender

The EBMSReceiverSender is a client sender sending SOAP web services request to B2BCollector EbMS plugin for downloading the EbMS message and it’s corresponding payload.

Author:Twinsen Tsang

Constructors

EBMSReceiverSender
public EBMSReceiverSender(FileLogger l, EBMSMessageData m, EBMSPartnershipData ps)

Explicit Constructor.

Parameters:
  • l – The logger used for log message and exception.
  • m – The message data for party information and send/recv configuration.
  • ps – The partnership data.

Methods

getMessageIdToRetreive
public String getMessageIdToRetreive()
Returns:the message id to retreive.
getOutputDirectory
public String getOutputDirectory()
Returns:the output directory of the received payload.
getResponseMessageId
public String getResponseMessageId()
Throws:
  • Operation – does not support.
initializeMessage
public void initializeMessage()

Initialize the message using the properties in the MessageProps.

main
public static void main(String[] args)

The main method is for CLI mode.

onResponse
public void onResponse()

Retrieve the payload from the message. The default receiver stores the payload as a files at the particular place specified in the configuration.

onStart
public void onStart()

Initialize the SOAP Message.

setMessageIdToRetreive
public void setMessageIdToRetreive(String messageId)
Parameters:
  • messageId – the message id to retreive the payload / message.
setOutputDirectory
public void setOutputDirectory(String path)

Set the output directory of received payload if any.

EBMSStatusQuerySender

public class EBMSStatusQuerySender extends SOAPSender

The EBMSStatusQuerySender is a client sender sending SOAP web services request to Corvus EBMS plugin for query the status of particular message. The web service parameters are defined in the below:

<messageId> 20070418-124233-75006@147.8.177.42 </messageId>

Creation Date: 02/05/2007

Author:Twinsen Tsang

Constructors

EBMSStatusQuerySender
public EBMSStatusQuerySender(FileLogger l, EBMSStatusQueryData data)

Explicit Constructor.

Parameters:
  • l – The logger used for log message and exception.
  • data – The EBMS Status query parameter.

Methods

getLastResponseData
public EBMSStatusQueryResponseData getLastResponseData()
Returns:The EBMS status response data by the last SFRM status query SOAP Call.
initializeMessage
public void initializeMessage()

The SOAPRequest in the creation stage should be liked this.

Throws:
  • Exceptions
main
public static void main(String[] args)

The main method is for CLI mode.

onResponse
public void onResponse()

Get the SOAP Body and analyze the result of configuration.

The result of SOAP body:

   <status> The current status of message </status>
<statusDescription> The current status description of message </statusDescription>
<ackMessageId> The message id of acknowledgment / receipt if any </ackMessageId>
<ackStatus> The status of acknowledgment / receipt if any </ackStatus>
<ackStatusDescription> The status description of acknowledgment / receipt if any </ackStatusDescription>
onStart
public void onStart()

[@EVENT] The method onStart log all new configuration.

MessageReceiver

public class MessageReceiver extends SOAPSender

The MessageReceiver is the abstract class which is used to send SOAP messsage request to B2B Collector series product.

Author:Jumbo Cheung

Constructors

MessageReceiver
public MessageReceiver(FileLogger l, Data m)

Explicit Constructor.

Parameters:
  • l – The logger used for log message and exception.
  • m – The message properties including how many message need to be sent and some performance parameter.

Methods

clearRequestPayload
public boolean clearRequestPayload()

Clear all payload in the request.

getContentType
public String getContentType()

Return the content type of the message.

Returns:The content type of message to bes sent.
getElapsedTime
public long getElapsedTime()

Get how long it tasks for the sender to do it’s tasks.

Returns:The times for the task from start to end in milleseconds.
getEndTime
public long getEndTime()
Returns:Return the end time of the sender process.
getResponsePayloads
public Payload[] getResponsePayloads()

Get the payload from the SOAP response. This should be called during onResponse().

Throws:
  • SOAPException – When unable to extract the payload in the SOAP Response.
  • IOException – When unable to open the input stream for the payload.
Returns:

A set of payload in SOAP message.

getStartTime
public long getStartTime()
Returns:Return the start time of the sending process.
onEnd
public void onEnd()

[@EVENT] This method is invoked when the sending execution is ended.

onError
public void onError(Throwable t)

[@EVENT] Log all known exceptions and stack trace.

Parameters:
  • t – The exception encountered.
onStart
public void onStart()

[@EVENT] This method is invoked when the sender begins to execute the run method.

setContentType
public void setContentType(String contentType)

Set the content type of the message to be sent.

Parameters:
  • contentType – The content type of message to be sent.

MessageSender

public abstract class MessageSender extends SOAPSender

The MessageSender is the abstract class which is used to send SOAP messsage request to B2B Collector series product.

Author:Joel Matsumoto, Twinsen Tsang

Fields

ps
protected Data ps

The partnership properties used for sending.

Constructors

MessageSender
public MessageSender(FileLogger l, Data m, Data p)

Explicit Constructor.

Parameters:
  • l – The logger used for log message and exception.
  • m – The message properties including how many message need to be sent and some performance parameter.
  • p – The partnership properties used for sending.

Methods

addRequestPayload
public boolean addRequestPayload(Payload[] payloads)

Add a set of payloads to the SOAP Request. The payloads are attached in the attachment part in the SOAP Message.

Parameters:
  • payloads – The array of payload.
Returns:

true if payloads is added succesfully.

clearRequestPayload
public boolean clearRequestPayload()

Clear all payload in the request.

getContentType
public String getContentType()

Return the content type of the message.

Returns:The content type of message to bes sent.
getElapsedTime
public long getElapsedTime()

Get how long it tasks for the sender to do it’s tasks.

Returns:The times for the task from start to end in milleseconds.
getEndTime
public long getEndTime()
Returns:Return the end time of the sender process.
getResponsePayloads
public Payload[] getResponsePayloads()

Get the payload from the SOAP response. This should be called during onResponse().

Throws:
  • SOAPException – When unable to extract the payload in the SOAP Response.
  • IOException – When unable to open the input stream for the payload.
Returns:

A set of payload in SOAP message.

getStartTime
public long getStartTime()
Returns:Return the start time of the sending process.
onEnd
public void onEnd()

[@EVENT] This method is invoked when the sending execution is ended.

onError
public void onError(Throwable t)

[@EVENT] Log all known exceptions and stack trace.

Parameters:
  • t – The exception encountered.
onStart
public void onStart()

[@EVENT] This method is invoked when the sender begins to execute the run method.

setContentType
public void setContentType(String contentType)

Set the content type of the message to be sent.

Parameters:
  • contentType – The content type of message to be sent.

MessageSenderException

public class MessageSenderException extends Exception

The MessageSenderException is a custom exception for the MessageSender class.

Author:Joel Matsumoto

Constructors

MessageSenderException
public MessageSenderException()

Constructor.

MessageSenderException
public MessageSenderException(String msg)

Explicit Constructor.

Parameters:
  • msg – The exception message.
MessageSenderException
public MessageSenderException(String msg, Exception e)

Explicit Constructor.

Parameters:
  • msg – The exception message.
  • e – The root cause.

MessageStatusSender

public class MessageStatusSender extends SOAPSender

The MessageStatusSender is the SOAP Message client that query the message status record through theMessage status engine (MS-E). From the description in (MS-E), a series of parameters have been defined and required to send to the MS-E.

  1. partnershipId
  2. channelType (OUTGOING | INCOMING)
  3. channelId
  4. folderName
  5. fileName
  6. fromTimestamp (in UTC format)
  7. toTimestamp (in UTC format)
  8. numOfRecords
  9. conversationId
  10. messageId
  11. messageType
  12. messageStatus
  13. protocol
  14. locale (EN)
  15. levelOfDetails (0 | 1)
  16. offset

Creation Date: 12/03/2007

Author:Twinsen Tsang

Fields

MSE_REQUEST_TYPE
public static final String MSE_REQUEST_TYPE

The complex type object for the message status request.

MSE_RESPONSE_TYPE
public static final String MSE_RESPONSE_TYPE

The complex type object for the message response request.

Constructors

MessageStatusSender
public MessageStatusSender(FileLogger l, MessageStatusRequestData m)

Explicit Constructor.

Parameters:
  • l – The logger used for log message and exception.
  • m – The message status properties including the querying parameter.

Methods

getMessageStatusList
public ArrayList getMessageStatusList()

[@GET] Get the list of message status record. It should be called only after the invocation of onResponse().

Returns:a list of message status record using the filter from the last web services call query.
initializeMessage
public void initializeMessage()

Initialize the message using the properties in the MessageStatusRequestData.

Throws:
main
public static void main(String[] args)

The main method is for CLI mode.

onResponse
public void onResponse()

[@EVENT] Retrieve the message status record from the message soap message. It parse the response and transform each MessageInfo complex type into one MessageStatusResponseData.

Throws:
onStart
public void onStart()

Initialize the SOAP Message.

PermitRedownloadServiceSender

public abstract class PermitRedownloadServiceSender extends SOAPSender

Constructors

PermitRedownloadServiceSender
public PermitRedownloadServiceSender(FileLogger l, Data m)

Explicit Constructor.

Parameters:
  • l – The logger used for log message and exception.
  • m – The message properties including how many message need to be sent and some performance parameter.

Methods

getElapsedTime
public long getElapsedTime()

Get how long it tasks for the sender to do it’s tasks.

Returns:The times for the task from start to end in milleseconds.
getEndTime
public long getEndTime()
Returns:Return the end time of the sender process.
getNSURI
protected abstract String getNSURI()
getResponseElementText
public String getResponseElementText(String tagname, String nsURI, int whichOne)

This method should only be called inside onResponse(). because the response object will be deleted upon each ws call.

Parameters:
  • tagname – The tag name of element to be retrieved.
  • nsURI – The namespace URI.
  • whichOne – The nth child element to be returned.
Returns:

The element text in the tagname specified.

getStartTime
public long getStartTime()
Returns:Return the start time of the sending process.
initializeMessage
public void initializeMessage()

Initialize Sender and Construct Message Request

onEnd
public void onEnd()

[@EVENT] This method is invoked when the sending execution is ended.

onError
public void onError(Throwable t)

[@EVENT] Log all known exceptions and stack trace.

Parameters:
  • t – The exception encountered.
onResponse
public void onResponse()

Record the message id.

onStart
public void onStart()

[@EVENT] This method is invoked when the sender begins to execute the run method.

SFRMStatusQuerySender

public class SFRMStatusQuerySender extends SOAPSender

The SFRMStatusQuerySender is a client sender sending SOAP web services request to Corvus SFRM plugin for query the status of particular message. The web service parameters are defined in the below:

<messageId> 20070418-124233-75006@147.8.177.42 </messageId>

Creation Date: 02/05/2007

Author:Twinsen Tsang

Constructors

SFRMStatusQuerySender
public SFRMStatusQuerySender(FileLogger l, SFRMStatusQueryData data)

Explicit Constructor.

Parameters:
  • l – The logger used for log message and exception.
  • data – The SFRM Status query parameter.

Methods

getLastResponseData
public SFRMStatusQueryResponseData getLastResponseData()
Returns:The SFRM status response data by the last SFRM status query SOAP Call.
initializeMessage
public void initializeMessage()

The SOAPRequest in the creation stage should be liked this.

Throws:
  • Exceptions
main
public static void main(String[] args)

The main method is for CLI mode.

onResponse
public void onResponse()

Get the SOAP Body and analyze the result of configuration.

The result of SOAP body:

<messageInfo>
        <status> The current status of message </status>
    <statusDescription> The current status description of message </statusDescription>
    <numberOfSegments> Maximum number of segments </numberOfSegments>
    <numberOfProcessedSegments> Number of processed segments </numberOfProcessedSegments>
    <lastUpdatedTime>  The last updated timestamp  </lastUpdatedTime>
</messageInfo>
onStart
public void onStart()

[@EVENT] The method onStart log all new configuration.

SOAPSender

public abstract class SOAPSender extends Component implements Runnable

The SOAPSender is a abstract class for the SOAP-Based protocol client. It reduces the complexity and version incompatible induced from the apache AXIS by using only Built-in java SOAP XML Package. The target developer is for those whose are not familiar with the complex AXIS framework. It is implemented using the event-driven model so that developer are only required to implement several event method. The package is under development and will be standardized in the future release.

Author:Twinsen Tsang

Fields

NS_PREFIX
protected static final String NS_PREFIX

The namespace prefix

log
protected FileLogger log

The logger used for log message and exception

See also: hk.hku.cecid.corvus.util.FileLogger

properties
protected Data properties

The data properties for this sender.

request
protected SOAPMessage request

The SOAP request

response
protected SOAPMessage response

The SOAP response

serviceEndPoint
protected URL serviceEndPoint

The url of service end point.

Constructors

SOAPSender
public SOAPSender()

SPA Constructor. It is used when the SOAP Sender is a component in the spa.

SOAPSender
public SOAPSender(FileLogger l, Data d)

Constructor

Parameters:
  • l – The logger used for log message and exception.
SOAPSender
public SOAPSender(FileLogger l, Data d, String endpoint)

Constructor

Parameters:
  • l – The logger used for log message and exception.
  • endpoint – The url of service end point.
SOAPSender
public SOAPSender(FileLogger l, Data d, URL endpoint)

Constructor.

Parameters:
  • l – The logger used for log message and exception.
  • endpoint – The url of service end point.

Methods

addRequestElementText
public boolean addRequestElementText(String tagName, String tagValue, String nsPrefix, String nsURI)

Add SOAP element to body with name and value.

Parameters:
  • tagName – The tag name of element to be retrieved.
  • tagValue – The value of the element to be added.
  • nsPrefix – The namespace Prefix
  • nsURI – The namespace URI.
Throws:
  • SOAPException
Returns:

true if the creation and addition is successfully.

addRequestElementText
public boolean addRequestElementText(String parentTagName, String parentNsURI, String tagName, String tagValue, String nsPrefix, String nsURI)

Add SOAP element to specify parent element

Parameters:
  • parentTagName – The tag name of parent element.
  • parentNsURI – The namespace URI of parent element.
  • tagName – The tag name of element to be retrieved.
  • tagValue – The value of the element to be added.
  • nsPrefix – The namespace Prefix
  • nsURI – The namespace URI.
Throws:
  • SOAPException
Returns:

true if the creation and linking is successfully.

countResponseElementText
public int countResponseElementText(String tagname, String nsURI)

This methods count number of specified tagname in the response. It should only be called inside onResponse().

Parameters:
  • tagname – The tag name of element to be retrieved.
  • nsURI – The namespace URI.
Throws:
  • SOAPException
Returns:

The element text in the tagname specified.

getCurrentLoopTimes
public int getCurrentLoopTimes()

Get what is the current loop times for looping

getLoopTimes
public int getLoopTimes()

Get how many times should the sender to be send.

getRequestElementText
public String getRequestElementText(String tagname, String nsURI, int whichOne)

This method should only be called inside onCreateRequest(). because the request object will be deleted upon each ws call.

Parameters:
  • tagname – The tag name of element to be retrieved.
  • nsURI – The namespace URI.
  • whichOne – The nth child element to be returned.
getResponseElementAsList
public String[] getResponseElementAsList(String tagname, String nsURI)

This method should only be called inside onResponse(). because the response object will be deleted upon each ws call. This method get the element by it’s tagname and return a list of text value inside.

Parameters:
  • tagname – The name of the XML tag to be extraceted.
  • nsURI – The namespace URI.
Throws:
  • SOAPException
Returns:

The elements’ text in the tagname specified.

getResponseElementText
public String getResponseElementText(String tagname, String nsURI, int whichOne)

This method should only be called inside onResponse(). because the response object will be deleted upon each ws call.

Parameters:
  • tagname – The tag name of element to be retrieved.
  • nsURI – The namespace URI.
  • whichOne – The nth child element to be returned.
Returns:

The element text in the tagname specified.

getSOAPRequest
protected SOAPMessage getSOAPRequest()

Get the SOAP request.

Returns:The SOAP Request Body.
getSOAPResponse
protected SOAPMessage getSOAPResponse()

Get the SOAP response. The method should only be called inside onResponse().

Returns:The SOAP Response Body.
getServiceEndPoint
public URL getServiceEndPoint()

Get the service end-point.

Returns:the service endpoint URL.
getUserObject
public Object getUserObject()

Get a user object.

initializeMessage
public void initializeMessage()

Implements this method if you want to send messages without much different between other message to sent.

isRequestDirty
public boolean isRequestDirty()
Returns:return true if the request is dirty.
isRequireXMLDeclaraction
public boolean isRequireXMLDeclaraction()

return return true if the request requires the XML declaration to sent.

onBeforeRequest
public void onBeforeRequest(SOAPConnection conn, SOAPMessage request)

[@EVENT] This method is invoked just before sending the request to Web service endpoints.

Parameters:
  • conn – The SOAP Connection used for sending SOAP request.
  • request – The request created by onCreateRequest().
Throws:
  • Exception – Any type of exception will be processed at onError(throwable t).
onCreateRequest
public SOAPMessage onCreateRequest()

[@EVENT] This method is invoked when the sender is required to sent a SOAP Request for configuration. The default return value is the request in the sender. If developer want to send a custom SOAP request other than the sender SOAP request, override the function and return your customizing SOAP Request. For example, if you want to send a SOAP request always with soap element “test”. Then you should override this function called.

public SOAPMessage onCreateRequest() throws Exception{
    SOAPMessage request = MessageFactory.newInstance().createMessage();
             ..
             ..
           add the element "test".
    return request;
}
Throws:
  • Exception – Any type of exception will be processed at onError(throwable t).
Returns:

javax.xml.SOAPMessage

onEachLoopStart
public void onEachLoopStart()

[@EVENT] This method is invoked when each loop iteration start.

Throws:
  • Exception – Any type of exception will be processed at onError(throwable t).
onEnd
public void onEnd()

[@EVENT] This method is invoked when the sending execution is ended.

onError
public void onError(Throwable t)

[@EVENT] This method is invoked when there is any exception thrown during web service call.

onResponse
public void onResponse()

[@EVENT] This method is invoked when received the reply SOAP response from the server Developer can use getSOAPResponse() to get the SOAP response for self-handling. Otherwise, developer can use getResponseElementText(String,String,int) to get the response element text from the response object.

Throws:
  • Exception – Any type of exception will be processed at onError(throwable t).
onStart
public void onStart()

[@EVENT] This method is invoked when the sender begins to execute the run method.

resetSOAPRequest
protected void resetSOAPRequest()

Reset the request to empty SOAP Body. It is commonly used when for each loop times the request

Throws:
  • SOAPException
resetSOAPResponse
protected void resetSOAPResponse()

Reset the request to empty SOAP Body. It is commonly used when for each loop times the response.

run
public void run()

The thread execution method.

setBasicAuthentication
public void setBasicAuthentication(String username, String password)

Set to use the basic authentication when calling the web service.

Parameters:
  • username – The username for basic authentication.
  • password – The password for basic authentication.
setLoopTimes
public void setLoopTimes(int loopTimes)

Set how many times should the sender to be send.

Parameters:
  • loopTimes – the new loopTimes.
setRequestDirty
public void setRequestDirty(boolean dirty)

Set if the request is dirty. We considered “dirty” as the request has been modified by someone during last sending.

setRequireXMLDeclaraction
public void setRequireXMLDeclaraction(boolean require)

Set if the request requires XML declaration at the top of the request. This is equivalent to:

SOAPRequest.setProperty(WRITE_XML_DECLARATION, "true");
Parameters:
  • require – true if requires XML declaration.

See also: javax.xml.soap.SOAPMessage.setProperty(String,Object), javax.xml.soap.SOAPMessage.WRITE_XML_DECLARATION

setServiceEndPoint
public void setServiceEndPoint(URL endpoint)

Set the service endpoint.

Parameters:
  • endpoint – The URL of the web service endpoint.
setServiceEndPoint
public void setServiceEndPoint(String endpoint)

Set the service endpoint.

Parameters:
  • endpoint – The String of the web service endpoint.
setUserObject
public void setUserObject(Object obj)

Set a user object for callback.

Parameters:
  • obj – The user object.
transformResponseContent
public PropertyTree transformResponseContent()

Transform the response into a property tree. It should only be called inside onResponse().

Returns:An XML Property tree having the same tag content in the response.

hk.hku.cecid.corvus.ws.data

AS2AdminData

public class AS2AdminData extends AdminData

The EBMSAdminData is data structure for holding the administration data for EbMS plugin.

Author:Twinsen Tsang

Fields

CONFIG_PREFIX
public static final String CONFIG_PREFIX

This is the configuration prefix for serialization / de-serialization.

PARAM_PREFIX
public static final String PARAM_PREFIX

This is the parameter prefix for serialzation / de-serialization.

Constructors

AS2AdminData
public AS2AdminData()

Create an instance of EBMSAdminData with default value.

  1. Username : corvus
  2. Password : corvus
  3. Manage Partnership End-point : http://localhost:8080/corvus/admin/as2/partnership
  4. Envelop Query End-point : http://localhost:8080/corvus/admin/as2/repository
  5. Partnership Operation : 1
  6. Message Box Criteria: INBOX
  7. Message ID Criteria: changem-messageid

AS2ConfigData

public class AS2ConfigData extends KVPairData

The AS2ConfigData is the data structure representing the parameters set for as2 runtime configuration. This is the sample WSDL request for the message status WS request.

<active-module-status> true | false </active-module-status>
<inmessage-interval>15000</inmessage-interval>
<inmessage-maxthread>0</inmessage-maxthread>
<outmessage-interval>15000</outmessage-interval>
<outmessage-maxthread>0</outmessage-maxthread>
<outpayload-interval>15000</outpayload-interval>
<outpayload-maxthread>0</outpayload-maxthread>
Author:Twinsen Tsang

Fields

CONFIG_KEY_SET
public static final String[] CONFIG_KEY_SET

This is the configuration key set for XML serialization / de-serialization.

CONFIG_PREFIX
public static final String CONFIG_PREFIX

This is the configuration prefix for serialization / de-serialization.

PARAM_KEY_SET
public static final String[] PARAM_KEY_SET

This is the key set for XML serialization / de-serialization.

PARAM_PREFIX
public static final String PARAM_PREFIX

This is the param prefix for serialzation / de-serialization.

stressMode
public boolean stressMode

This is special flag for stress test mode. In stress test mode, messages are bumped into Hermes2 before start processing. so we need to switch off the active module before bumping the message. and restart after bumping. At the result, we need a flag for switch on / off active task module.

Constructors

AS2ConfigData
public AS2ConfigData()

Default Constructor.

Methods

getActiveModuleStatus
public String getActiveModuleStatus()
Returns:Get the active module status wanted to set for this data.
getActiveModuleStatusBn
public boolean getActiveModuleStatusBn()
Returns:Get the boolean value for ths active module status wanted to set for this data.
getInMessageExecInterval
public String getInMessageExecInterval()

Get the execution interval for incoming message in this data.

Returns:the execution interval for incoming message in this data.
getInMessageMaxThread
public String getInMessageMaxThread()

Get the maximum thread for incoming message in this data.

Returns:the maximum thread for incoming message in this data.
getOutMessageExecInterval
public String getOutMessageExecInterval()

Get the execution interval for outgoing message in this data.

Returns:the execution interval for outgoing message in this data.
getOutMessageMaxThread
public String getOutMessageMaxThread()

Get the maximum thread for outgoing message in this data.

Returns:the maximum thread for outgoing message in this data.
getOutPayloadExecInterval
public String getOutPayloadExecInterval()

Get the execution interval for outgoing payload in this data.

Returns:the execution interval for outgoing payload in this data.
getOutPayloadMaxThread
public String getOutPayloadMaxThread()

Get the maximum thread for outgoing payload in this data.

Returns:the maximum thread for outgoing payload in this data.
getSendEndpoint
public String getSendEndpoint()
Returns:Get the web service endpoint for sending as2 config message to corvus.
setActiveModuleStatus
public void setActiveModuleStatus(boolean newStatus)

Set the new active module status wanted for this data.

Parameters:
  • newStatus – the new active module status wanted for this data.
setInMessageExecInterval
public void setInMessageExecInterval(long newInterval)
Parameters:
  • newInterval – the new execution interval for incoming message for this data.
setInMessageMaxThread
public void setInMessageMaxThread(long maxThread)
Parameters:
  • maxThread – the maximum thread for incoming message for this data.
setOutMessageExecInterval
public void setOutMessageExecInterval(long newInterval)
Parameters:
  • newInterval – the new execution interval for outgoing message for this data.
setOutMessageMaxThread
public void setOutMessageMaxThread(long maxThread)
Parameters:
  • maxThread – the maximum thread for outgoing message for this data.
setOutPayloadExecInterval
public void setOutPayloadExecInterval(long newInterval)
Parameters:
  • newInterval – the new execution interval for outgoing payload for this data.
setOutPayloadMaxThread
public void setOutPayloadMaxThread(long maxThread)
Parameters:
  • maxThread – the maximum thread for outgoing payload for this data.
setSendEndpoint
public void setSendEndpoint(String endpoint)

Set the web service endpoint for sending as2 config message to corvus.

Parameters:
  • endpoint – The web service endpoint for sending as2 config message to corvus.

AS2MessageData

public class AS2MessageData extends KVPairData

The AS2MessageData is the data structure representing the parameters set for sending as2 messagw with payload to Hermes2. This is the sample WSDL request for the message status WS request.

<as2_from>as2loopback</as2_from>
<as2_to>as2loopback</as2_to>
<type>xml</type>

The first three parameters are derived from AS2PartnershipData.getAS2From() and AS2PartnershipData.getAs2To().

Author:Twinsen Tsang

Fields

CONFIG_KEY_SET
public static final String[] CONFIG_KEY_SET

This is the configuration key set for XML serialization / de-serialization.

CONFIG_PREFIX
public static final String CONFIG_PREFIX

This is the configuration prefix for serialization / de-serialization.

PARAM_KEY_SET
public static final String[] PARAM_KEY_SET

This is the key set for XML serialization / de-serialization.

PARAM_PREFIX
public static final String PARAM_PREFIX

This is the param prefix for serialzation / de-serialization.

Constructors

AS2MessageData
public AS2MessageData()

Default Constructor.

Methods

getMessageIdForReceive
public String getMessageIdForReceive()

Get the Message ID that targeted to retrieve

Returns:the value of Message ID in the AS2 message.
getRecvEndpoint
public String getRecvEndpoint()
Returns:Get the web service End-point for receiving AS2 message from CORVUS.
getRecvlistEndpoint
public String getRecvlistEndpoint()
Returns:Get the web service End-point for receiving a list of AS2 message which are ready to down-load from CORVUS.
getSendEndpoint
public String getSendEndpoint()
Returns:Get the web service End-point for sending AS2 message to CORVUS.
getType
public String getType()

Get the type of the payload.

Returns:the type of payload in the AS2 message.
setMessageIdForReceive
public void setMessageIdForReceive(String value)

Set the Message ID that targeted to retrieve

Parameters:
  • value – The Message ID of the AS2 message.
setRecvEndpoint
public void setRecvEndpoint(String endpoint)

Set the web service End-point for receiving AS2 message from CORVUS.

Parameters:
  • endpoint – The web service End-point for receiving AS2 message from CORVUS.
setRecvlistEndpoint
public void setRecvlistEndpoint(String endpoint)

Set the web service End-point for receiving a list of AS2 message which are ready to down-load from CORVUS.

Parameters:
  • endpoint – the web service End-point for receiving a list of AS2 message which are ready to download from CORVUS.
setSendEndpoint
public void setSendEndpoint(String endpoint)

Set the web service End-point for sending AS2 message to CORVUS.

Parameters:
  • endpoint – The web service End-point for sending AS2 message to CORVUS.
setType
public void setType(String type)

Set the type of the payload.

Parameters:
  • type – The type of payload in the AS2 message.
toString
public String toString()

toString method.

AS2MessageHistoryRequestData

public class AS2MessageHistoryRequestData extends MessageHistoryRequestData

Fields

CONFIG_PREFIX
public static final String CONFIG_PREFIX
PARAM_AS2_KEY_SET
public static final String[] PARAM_AS2_KEY_SET
PARAM_PREFIX
public static final String PARAM_PREFIX

Constructors

AS2MessageHistoryRequestData
public AS2MessageHistoryRequestData()

Methods

getAS2FromParty
public String getAS2FromParty()
getAS2ToParty
public String getAS2ToParty()
getMessageId
public String getMessageId()
setAS2FromParty
public void setAS2FromParty(String value)
setAS2ToParty
public void setAS2ToParty(String value)
setMessageId
public void setMessageId(String value)

AS2PartnershipData

public class AS2PartnershipData extends KVPairData

The AS2PartnershipData is

Author:Twinsen Tsang

Fields

ALG_ENCRYPT_3DES
public static final String ALG_ENCRYPT_3DES

The constant field for 3DES Encryption.

ALG_ENCRYPT_RC2
public static final String ALG_ENCRYPT_RC2

The constant field for RC2 Encryption.

ALG_MIC_MD5
public static final String ALG_MIC_MD5

The constant field for MD5 Message-Integrity-Check.

ALG_MIC_SHA1
public static final String ALG_MIC_SHA1

The constant field for SHA1 Message-Integrity-Check.

ALG_SIGN_MD5
public static final String ALG_SIGN_MD5

The constant field for MD5 Signing.

ALG_SIGN_SHA1
public static final String ALG_SIGN_SHA1

The constant field for SHA1 Signing.

PARAM_CLASS_SET
static final Class[] PARAM_CLASS_SET
PARAM_KEY_SET
public static final String[] PARAM_KEY_SET

This is the key set for XML serialization / de-serialization.

PARAM_PREFIX
public static final String PARAM_PREFIX

This is the parameters prefix for serialization / de-serialization.

Constructors

AS2PartnershipData
public AS2PartnershipData()

Default Constructor.

Methods

getAS2From
public String getAS2From()
Returns:AS2 From.
getAs2To
public String getAs2To()
Returns:AS2 To.
getEncryptAlgorithm
public String getEncryptAlgorithm()
Returns:encrpytion algorithm.
getEncryptCert
public byte[] getEncryptCert()
Returns:encryption certificate in byte array.
getMicAlgorithm
public String getMicAlgorithm()
Returns:checksum algorithm.
getPartnershipId
public String getPartnershipId()
Returns:The partnership id for this partnership.
getReceiptAddress
public String getReceiptAddress()
Returns:Get receipt address.
getRecipientAddress
public String getRecipientAddress()
Returns:Get recipient address of the message.
getRetries
public int getRetries()
Returns:retries.
getRetryInterval
public int getRetryInterval()
Returns:retry interval.
getSignAlgorithm
public String getSignAlgorithm()
Returns:signing algorithm.
getSubject
public String getSubject()
Returns:Get the subject of the message.
getVerifyCert
public byte[] getVerifyCert()
Returns:verification certificate in byte array.
isDisabled
public boolean isDisabled()
Returns:the partnership is disabled ?
isHostnameVerified
public boolean isHostnameVerified()
Returns:True if hostname is verified.
isInboundEncryptRequired
public boolean isInboundEncryptRequired()
Returns:true if inbound encryption is required.
isInboundSignRequired
public boolean isInboundSignRequired()
Returns:true if inbound signing is required.
isOutboundCompressRequired
public boolean isOutboundCompressRequired()
Returns:true if outbound compression is required.
isOutboundEncryptRequired
public boolean isOutboundEncryptRequired()
Returns:true if outbound encryption is required.
isOutboundSignRequired
public boolean isOutboundSignRequired()
Returns:True if outbound signing is required.
isReceiptRequired
public boolean isReceiptRequired()
Returns:True if receipt required.
isReceiptSignRequired
public boolean isReceiptSignRequired()
Returns:true if receipt signing is required.
isSyncReply
public boolean isSyncReply()
Returns:the message required sync reply
setAs2From
public void setAs2From(String as2From)
Parameters:
  • as2From – AS2 From.
setAs2To
public void setAs2To(String as2To)
Parameters:
  • as2To – AS2 To.
setEncryptAlgorithm
public void setEncryptAlgorithm(String encryptAlgorithm)
Parameters:
  • encryptAlgorithm – encryption algorithm.
setEncryptCert
public void setEncryptCert(byte[] encryptCert)
Parameters:
  • encryptCert – encryption certificate in byte array.
setIsDisabled
public void setIsDisabled(boolean isDisabled)

Set the partnership is enabled or not.

Parameters:
  • isDisabled – the flag whether the partnership is enabled or not.
setIsHostnameVerified
public void setIsHostnameVerified(boolean isHostnameVerified)
Parameters:
  • isHostnameVerified – true if the hostname is verified.
setIsInboundEncryptRequired
public void setIsInboundEncryptRequired(boolean isInboundEncryptRequired)
Parameters:
  • isInboundEncryptRequired – true if inbound encrpytion is required.
setIsInboundSignRequired
public void setIsInboundSignRequired(boolean isInboundSignRequired)
Parameters:
  • isInboundSignRequired – true if inbound signing is required.
setIsOutboundCompressRequired
public void setIsOutboundCompressRequired(boolean isOutboundCompressRequired)
Parameters:
  • isOutboundCompressRequired – true if outbound compression is required.
setIsOutboundEncryptRequired
public void setIsOutboundEncryptRequired(boolean isOutboundEncryptRequired)
Parameters:
  • isOutboundEncryptRequired – true if outbound encryption is required.
setIsOutboundSignRequired
public void setIsOutboundSignRequired(boolean isOutboundSignRequired)
Parameters:
  • isOutboundSignRequired – true if outbound signing is required.
setIsReceiptRequired
public void setIsReceiptRequired(boolean isReceiptRequired)
Parameters:
  • isReceiptRequired – true if receipt required.
setIsReceiptSignRequired
public void setIsReceiptSignRequired(boolean isReceiptSignRequired)
Parameters:
  • isReceiptSignRequired – true if receipt signing is required.
setIsSyncReply
public void setIsSyncReply(boolean isSyncReply)

Set the message require sync reply

Parameters:
  • isSyncReply
setMicAlgorithm
public void setMicAlgorithm(String micAlgorithm)
Parameters:
  • micAlgorithm – checksum algorithm.
setPartnershipId
public void setPartnershipId(String partnershipId)
Parameters:
  • partnershipId – The partnership id for this partnership.
setReceiptAddress
public void setReceiptAddress(String receiptAddress)
Parameters:
  • receiptAddress – the receipt address
setRecipientAddress
public void setRecipientAddress(String recipientAddress)
Parameters:
  • recipientAddress – the recipient address of the message.
setRetries
public void setRetries(int retries)
Parameters:
  • retries – Retries.
setRetryInterval
public void setRetryInterval(int retryInterval)
Parameters:
  • retryInterval – retries interval.
setSignAlgorithm
public void setSignAlgorithm(String signAlgorithm)
Parameters:
  • signAlgorithm – signing algorithm.
setSubject
public void setSubject(String subject)
Parameters:
  • subject – the subject of the message.
setVerifyCert
public void setVerifyCert(byte[] verifyCert)
Parameters:
  • verifyCert – verification certificate in byte array.

AS2StatusQueryData

public class AS2StatusQueryData extends CorvusStatusQueryData

The AS2StatusQueryData is the data structure representing the request parameter set for AS2 Status Query web services. This is the sample WSDL request for the status query WS request.

<messageId> 20070418-124233-75006@147.8.177.42 </messageId>

Creation Date: 10/05/2007

Author:Twinsen Tsang

Fields

CONFIG_PREFIX
public static final String CONFIG_PREFIX

This is the configuration prefix for serialization / de-serialization.

PARAM_PREFIX
public static final String PARAM_PREFIX

This is the param prefix for serialzation / de-serialization.

Constructors

AS2StatusQueryData
public AS2StatusQueryData()

Default Constructor.

AS2StatusQueryResponseData

public class AS2StatusQueryResponseData extends CorvusStatusQueryResponseData

The AS2StatusQueryResponseData is the data structure representing the response data set for EBMS status query web services. This is the sample WSDL request for the status query WS request.

   <status> The current status of message </status>
<statusDescription> The current status description of message </statusDescription>
<mdnMessageId> The message id of acknowledgment / receipt if any </ackMessageId>
<mdnStatus> The status of acknowledgment / receipt if any </ackStatus>
<mdnStatusDescription> The status description of acknowledgment / receipt if any </ackStatusDescription>

Creation Date: 10/05/2007

Author:Twinsen Tsang

Fields

PARAM_KEY_SET
public static final String[] PARAM_KEY_SET

This is the key set for XML serialization / de-serialization.

Constructors

AS2StatusQueryResponseData
public AS2StatusQueryResponseData()

Default Constructor.

AdminData

abstract class AdminData extends KVPairData

The AdminData is

Author:Twinsen Tsang

Fields

CONFIG_KEY_SET
public static final String[] CONFIG_KEY_SET

This is the configuration key set for XML serialization / de-serialization.

PARAM_KEY_SET
public static final String[] PARAM_KEY_SET

For consistent, used for DataFactory.createEBMSAdminDataFromXML(hk.hku.cecid.piazza.commons.util.PropertyTree)

Constructors

AdminData
public AdminData(int maxCapacity)

Default constructor.

Methods

getEnvelopQueryEndpoint
public String getEnvelopQueryEndpoint()
Returns:The end-point for query the message envelop of EBMS partnership.
getManagePartnershipEndpoint
public String getManagePartnershipEndpoint()
Returns:The end-point for managing the set of EBMS partnership.
getMessageBoxCriteria
public String getMessageBoxCriteria()

[USED ONLY BY EnvelopQuerySender]

Returns:the message box acting as the criteria for search the message envelop.
getMessageIdCriteria
public String getMessageIdCriteria()

[USED ONLY BY EnvelopQuerySender]

Returns:the message id acting as the criteria for search the message envelop.
getPartnershipOperation
public int getPartnershipOperation()

[USED ONLY BY PartnershipSender]

Throws:
Returns:

The partnership operation you have set, either 0, 1, 2.

getPassword
public char[] getPassword()
Returns:The password for authenticate the administrator page.
getUsername
public String getUsername()
Returns:The user name for authenticate administrator page.
setEnvelopQueryEndpoint
public void setEnvelopQueryEndpoint(String envelopQueryEndpoint)

Set the end-point for query the message envelop of EBMS partnership.

Parameters:
  • envelopQueryEndpoint – The end-point for query the message envelop of EBMS partnership.
setManagePartnershipEndpoint
public void setManagePartnershipEndpoint(String manPartnershipEndpoint)

Set the end-point for managing the set of EBMS partnership.

Parameters:
  • manPartnershipEndpoint – The end-point for managing the set of EBMS partnership.
setMessageBoxCriteria
public void setMessageBoxCriteria(String messageBox)

[USED ONLY BY EnvelopQuerySender] Set the message box acting as the criteria for search the message envelop.

Parameters:
  • messageBox – the message box acting as the criteria for search the message envelop.
setMessageIdCriteria
public void setMessageIdCriteria(String messageId)

[USED ONLY BY EnvelopQuerySender] Set the message id acting as the criteria for search the message envelop.

Parameters:
  • messageId – the message id acting as the criteria for search the message envelop.
setPartnershipOperation
public void setPartnershipOperation(int pOp)

[USED ONLY BY PartnershipSender]

Parameters:
  • pOp – The partnership operation you want to set, either 0, 1, 2.

See also: hk.hku.cecid.corvus.http.PartnershipOp, hk.hku.cecid.corvus.http.EBMSPartnershipSender

setPassword
public void setPassword(String password)
Parameters:
  • password – the password for authenticate administrator page
setUsername
public void setUsername(String username)
Parameters:
  • username – The user name for authenticate administrator page.

CorvusStatusQueryData

public class CorvusStatusQueryData extends KVPairData

The CorvusStatusQueryData is the data structure representing the parameters set for status query web services for all protocol using Corvus level. This is the sample WSDL request for the status query WS request.

<messageId> 20070418-124233-75006@147.8.177.42 </messageId>

Creation Date: 2/5/2007

Author:Twinsen Tsang

Fields

CONFIG_KEY_SET
public static final String[] CONFIG_KEY_SET

This is the configuration key set for XML serialization / de-serialization.

PARAM_KEY_SET
public static final String[] PARAM_KEY_SET

This is the key set for XML serialization / de-serialization.

configPrefix
public String configPrefix

This is the configuration prefix for serialization / de-serialization.

paramPrefix
public String paramPrefix

This is the param prefix for serialzation / de-serialization.

Constructors

CorvusStatusQueryData
public CorvusStatusQueryData(String ConfigXPath, String ParamXPath)

Explicit Constructor.

Parameters:
  • ConfigXPath – The XPath for the configuration data in status query.
  • ParamXPath – The XPath for the paramter data in status query.

Methods

getQueryMessageId
public String getQueryMessageId()
Returns:The message id to query the status.
getSendEndpoint
public String getSendEndpoint()
Returns:Get the web service endpoint for sending status query message to corvus.
setQueryMessageId
public void setQueryMessageId(String messageId)
Parameters:
  • messageId – The message id to query the status.
setSendEndpoint
public void setSendEndpoint(String endpoint)

Set the web service endpoint for sending status query message to corvus.

Parameters:
  • endpoint – The web service endpoint for sending status query message to corvus.

CorvusStatusQueryResponseData

public class CorvusStatusQueryResponseData extends KVPairData

The CorvusStatusQueryResponseData is the data structure representing the general response data set for status query web services in corvus level. This is the sample WSDL request for the status query WS request.

   <status> The current status of message </status>
<statusDescription> The current status description of message </statusDescription>
<ackMessageId> The message id of acknowledgment / receipt if any </ackMessageId>
<ackStatus> The status of acknowledgment / receipt if any </ackStatus>
<ackStatusDescription> The status description of acknowledgment / receipt if any </ackStatusDescription>

Creation Date: 10/05/2007

Author:Twinsen Tsang

Constructors

CorvusStatusQueryResponseData
public CorvusStatusQueryResponseData(String[] paramKeySet)

Default Constructor.

Methods

getACKMessageId
public String getACKMessageId()
Returns:the message ID of the acknowledgment corresponding to the message being queried.
getACKStatus
public String getACKStatus()
Returns:the status of the acknowledgment corresponding to the message being queried.
getACKStatusDescription
public String getACKStatusDescription()
Returns:the status description of the acknowledgment corresponding to the message being queried.
getMessageId
public String getMessageId()
Returns:the message ID of the message being queried.
getStatus
public String getStatus()
Returns:the current status of Message.
getStatusDescription
public String getStatusDescription()
Returns:the current status description of Message.

Data

public interface Data

DataFactory

public class DataFactory

A DataFactory imports data from the XML property tree to create different data object used for sending web service request. Creation Date: 19/3/2007

Author:Twinsen Tsang

See also: hk.hku.cecid.piazza.commons.util.PropertyTree

Fields

XML_SEPARATOR
public static final char XML_SEPARATOR

The constants representing the XML Separator *

instance
public static final DataFactory instance

Singleton.

Methods

createAS2AdminDataFromXML
public AS2AdminData createAS2AdminDataFromXML(PropertyTree t)

Create an instance of AS2AdminData from the XML property tree.

Parameters:
  • t – The property tree to import the data.
Returns:

A new instance of AS2AdminData with data imported from the property tree.

createAS2ConfigDataFromXML
public AS2ConfigData createAS2ConfigDataFromXML(PropertyTree t)

Create an instance of AS2ConfigData From the XML property tree.

Parameters:
  • t – The property tree to import the data.
Returns:

A new instance of AS2ConfigData with data imported from the property tree.

createAS2MessageDataFromXML
public AS2MessageData createAS2MessageDataFromXML(PropertyTree t)

Create an instance of AS2MessageData from the XML property tree.

Parameters:
  • t – The property tree to import the data.
Returns:

A new instance of AS2MessageData with data imported from the property tree.

createAS2PartnershipFromXML
public AS2PartnershipData createAS2PartnershipFromXML(PropertyTree t)

Create an instance of AS2PartnershipData From the XML property tree.

Parameters:
  • t – The property tree to import the data.
Returns:

A new instance of AS2PartnershipData with data imported from the property tree.

createAS2PermitRedownloadDataFromXML
public PermitRedownloadData createAS2PermitRedownloadDataFromXML(PropertyTree t)
createAS2StatusQueryDataFromXML
public AS2StatusQueryData createAS2StatusQueryDataFromXML(PropertyTree t)

Create an instance of AS2StatusQueryData From the XML property tree.

Parameters:
  • t – The property tree to import the data.
Returns:

A new instance of AS2StatusQueryData with data imported from the property tree.

createAs2MessageHistoryQueryDataFromXML
public AS2MessageHistoryRequestData createAs2MessageHistoryQueryDataFromXML(PropertyTree t)

Create an instance of AS2MessageHistoryRequestData from the XML property tree.

Parameters:
  • t – The property tree to import the data.
Returns:

A new instance of AS2MessageHistoryRequestData with data imported from the property tree.

createEBMSAdminDataFromXML
public EBMSAdminData createEBMSAdminDataFromXML(PropertyTree t)

Create an instance of EBMSAdminData from the XML property tree.

Parameters:
  • t – The property tree to import the data.
Returns:

A new instance of EBMSAdminData with data imported from the property tree.

createEBMSConfigDataFromXML
public EBMSConfigData createEBMSConfigDataFromXML(PropertyTree t)

Create an instance of EBMSConfigData From the XML property tree.

Parameters:
  • t – The property tree to import the data.
Returns:

A new instance of EBMSConfigData with data imported from the property tree.

createEBMSMessageDataFromXML
public EBMSMessageData createEBMSMessageDataFromXML(PropertyTree t)

Create an instance of EBMSMessageData from the XML property tree.

Parameters:
  • t – The property tree to import the data.
Returns:

A new instance of EBMSMessageData with data imported from the property tree.

createEBMSPartnershipFromXML
public EBMSPartnershipData createEBMSPartnershipFromXML(PropertyTree t)

Create an instance of EBMSPartnershipData From the XML property tree.

Parameters:
  • t – The property tree to import the data.
Returns:

A new instance of EBMSPartnershipData with data imported from the property tree.

createEBMSPermitRedownloadDataFromXML
public PermitRedownloadData createEBMSPermitRedownloadDataFromXML(PropertyTree t)
createEBMSStatusQueryDataFromXML
public EBMSStatusQueryData createEBMSStatusQueryDataFromXML(PropertyTree t)

Create an instance of EBMSStatusQueryData From the XML property tree.

Parameters:
  • t – The property tree to import the data.
Returns:

A new instance of EBMSStatusQueryData with data imported from the property tree.

createEbmsMessageHistoryQueryDataFromXML
public EBMSMessageHistoryRequestData createEbmsMessageHistoryQueryDataFromXML(PropertyTree t)

Create an instance of EBMSMessageHistoryRequestData from the XML property tree.

Parameters:
  • t – The property tree to import the data.
Returns:

A new instance of EBMSMessageHistoryRequestData with data imported from the property tree.

createMessageRequestStatusDataFromXML
public static MessageStatusRequestData createMessageRequestStatusDataFromXML(PropertyTree t)

Create an instance of MessageStatusRequestData From the XML property tree.

Parameters:
  • t – The property tree to import the data.
Throws:
  • UtilitiesException – When the data factory is unable to import the data from the property tree.
Returns:

A new instance of MessageStatusRequestData with data imported from the property tree.

createMessageStatusDataFromXML
public static MessageStatusRequestData createMessageStatusDataFromXML(String filename)

Create an instance of MessageStatusRequestData From a file written in XML format.

Parameters:
  • filename – The file to load the message status request data.
Throws:
Returns:

A new instance of MessageStatusRequestData with data imported from the file with name filename

createSFRMStatusQueryDataFromXML
public SFRMStatusQueryData createSFRMStatusQueryDataFromXML(PropertyTree t)

Create an instance of SFRMStatusQueryData From the XML property tree.

Parameters:
  • t – The property tree to import the data.
Returns:

A new instance of SFRMStatusQueryData with data imported from the property tree.

getInstance
public static DataFactory getInstance()

Singleton instance.

storeAS2MessageDataToXML
public void storeAS2MessageDataToXML(AS2MessageData d, URL path)

Store an instance of AS2Message to XML.

Parameters:
  • d – The AS2MessageData to store.
  • path – The URL specified the location for storing the data.
Throws:
  • IOException – when storing the data fails.
storeAS2PartnershipFromXML
public void storeAS2PartnershipFromXML(AS2PartnershipData d, URL path)

Store the instance of AS2PartnershipData to the XML specified at path.

Parameters:
  • d – The AS2PartnershipData you want to store.
  • path – The URL specified the location for storing the data.
Throws:
  • IOException – when storing the data fails.
storeEBMSMessageDataToXML
public void storeEBMSMessageDataToXML(EBMSMessageData d, URL path)

Store an instance of EBMSMessage to XML.

Parameters:
  • d – The AS2MessageData to store.
  • path – The URL specified the location for storing the data.
Throws:
  • IOException – when storing the data fails.
storeEBMSPartnershipFromXML
public void storeEBMSPartnershipFromXML(EBMSPartnershipData d, URL path)

Store the instance of EBMSPartnershipData to the XML specified at path.

Parameters:
  • d – The EBMSPartnershipData you want to store.
  • path – The URL specified the location for storing the data.
Throws:
  • IOException – when storing the data fails.

DataFactoryUnitTest

public class DataFactoryUnitTest extends TestCase

The DataFactoryUnitTest is unit test of DataFactory.

Author:Twinsen Tsang

Fields

AS2_ADMIN_DATA_SAMPLE0
public static final String AS2_ADMIN_DATA_SAMPLE0
AS2_MESSAGE_DATA_SAMPLE0
public static final String AS2_MESSAGE_DATA_SAMPLE0
AS2_MESSAGE_DATA_STORE0
public static final String AS2_MESSAGE_DATA_STORE0
AS2_PARTNERSHIP_DATA_LOAD0
public static final String AS2_PARTNERSHIP_DATA_LOAD0

This is the fixture name for testing the reading capabilities for AS2Partnership in DataFactory.

AS2_PARTNERSHIP_DATA_STORE0
public static final String AS2_PARTNERSHIP_DATA_STORE0

This is the fixture name for testing the storing capabilities for DataFactory. This fixture does not contains any data initially.

EBMS_ADMIN_DATA_SAMPLE0
public static final String EBMS_ADMIN_DATA_SAMPLE0
EBMS_CONFIG_DATA_SAMPLE0
public static final String EBMS_CONFIG_DATA_SAMPLE0
EBMS_HISTORY_QUERY_DATA_STORE0
public static final String EBMS_HISTORY_QUERY_DATA_STORE0
EBMS_MESSAGE_DATA_SAMPLE0
public static final String EBMS_MESSAGE_DATA_SAMPLE0
EBMS_MESSAGE_DATA_STORE0
public static final String EBMS_MESSAGE_DATA_STORE0
EBMS_PARTNERSHIP_DATA_LOAD0
public static final String EBMS_PARTNERSHIP_DATA_LOAD0

This is the fixture name for testing the reading capabilities for EBMSPartnership in DataFactory.

EBMS_PARTNERSHIP_DATA_STORE0
public static final String EBMS_PARTNERSHIP_DATA_STORE0

This is the fixture name for testing the storing capabilities for DataFactory. This fixture does not contains any data initially.

logger
final Logger logger

Methods

setUp
protected void setUp()
tearDown
protected void tearDown()
testCcreateEbmsMessageHistoryQueryDataFromXML
public void testCcreateEbmsMessageHistoryQueryDataFromXML()
testCreateAS2AdminData
public void testCreateAS2AdminData()

Test whether the DataFactory able to load AS2 Administrator Data from the fixture *

testCreateAS2MessageData
public void testCreateAS2MessageData()
testCreateAS2PartnershipData
public void testCreateAS2PartnershipData()

Test whether the DataFactory able to create EBMS Partnership Data from the fixture *

testCreateEBMSAdminData
public void testCreateEBMSAdminData()

Test whether the DataFactory able to load EBMS Administrator Data from the fixture *

testCreateEBMSConfigData
public void testCreateEBMSConfigData()
testCreateEBMSPartnershipData
public void testCreateEBMSPartnershipData()

Test whether the DataFactory able to create EBMS Partnership Data from the fixture *

testStoreAS2MessageData
public void testStoreAS2MessageData()

Test whether the DataFactory able to store AS2 Message Data to the fixture *

testStoreAS2PartnershipData
public void testStoreAS2PartnershipData()

Test whether the DataFactory able to store AS2 Partnership Data to the fixture *

testStoreEBMSMessageData
public void testStoreEBMSMessageData()

Test whether the DataFactory able to store EBMS Message Data to the fixture *

testStoreEBMSPartnershipData
public void testStoreEBMSPartnershipData()

Test whether the DataFactory able to store EBMS Partnership Data to the fixture *

EBMSAdminData

public class EBMSAdminData extends AdminData

The EBMSAdminData is data structure for holding the administration data for EbMS plugin.

Author:Twinsen Tsang

Fields

CONFIG_PREFIX
public static final String CONFIG_PREFIX

This is the configuration prefix for serialization / de-serialization.

PARAM_PREFIX
public static final String PARAM_PREFIX

This is the parameter prefix for serialization / de-serialization.

Constructors

EBMSAdminData
public EBMSAdminData()

Create an instance of EBMSAdminData with default value.

  1. User-name: corvus
  2. Password : corvus
  3. Manage Partnership End-point : http://localhost:8080/corvus/admin/ebms/partnership
  4. Envelop Query End-point : http://localhost:8080/corvus/admin/ebms/repository
  5. Partnership Operation : 1
  6. Message Box Criteria: INBOX
  7. Message ID Criteria: changme-messageid

EBMSConfigData

public class EBMSConfigData extends KVPairData

The EBMSConfigData is the data structure representing the parameters set for EbMS runtime configuration. This is the WSDL schema for the message status WS request.

<active-module-status> true | false </active-module-status>
<incollector-interval>15000</incollector-interval>
<incollector-maxthread>0</incollector-maxthread>
<outcollector-interval>15000</outcollector-interval>
<outcollector-maxthread>0</outcollector-maxthread>
<mailcollector-interval>15000</mailcollector-interval>
<mailcollector-maxthread>0</mailcollector-maxthread>
Author:Twinsen

Fields

CONFIG_KEY_SET
public static final String[] CONFIG_KEY_SET

This is the configuration key set for XML serialization / de-serialization.

CONFIG_PREFIX
public static final String CONFIG_PREFIX

This is the configuration prefix for serialization / de-serialization.

PARAM_KEY_SET
public static final String[] PARAM_KEY_SET

This is the key set for XML serialization / de-serialization.

PARAM_PREFIX
public static final String PARAM_PREFIX

This is the param prefix for serialzation / de-serialization.

Constructors

EBMSConfigData
public EBMSConfigData()

Default Constructor.

Methods

getActiveModuleStatus
public String getActiveModuleStatus()
Returns:Get the active module status wanted to set for this data.
getActiveModuleStatusBn
public boolean getActiveModuleStatusBn()
Returns:Get the boolean value for ths active module status wanted to set for this data.
getInCollectorExecInterval
public String getInCollectorExecInterval()

Get the execution interval for incoming collector in this data.

Returns:the execution interval for incoming collector in this data.
getInCollectorMaxThread
public String getInCollectorMaxThread()

Get the maximum thread for incoming message in this data.

Returns:the maximum thread for incoming message in this data.
getMailCollectorExecInterval
public String getMailCollectorExecInterval()

Get the execution interval for mail collector in this data.

Returns:the execution interval for mail collector in this data.
getMailCollectorMaxThread
public String getMailCollectorMaxThread()

Get the maximum thread for mail message in this data.

Returns:the maximum thread for mail message in this data.
getOutCollectorExecInterval
public String getOutCollectorExecInterval()

Get the execution interval for outgoing collector in this data.

Returns:the execution interval for outgoing collector in this data.
getOutCollectorMaxThread
public String getOutCollectorMaxThread()

Get the maximum thread for outgoing message in this data.

Returns:the maximum thread for outgoing message in this data.
getSendEndpoint
public String getSendEndpoint()
Returns:Get the web service endpoint for sending as2 config message to corvus.
setActiveModuleStatus
public void setActiveModuleStatus(boolean newStatus)

Set the new active module status wanted for this data.

Parameters:
  • newStatus – the new active module status wanted for this data.
setInCollectorExecInterval
public void setInCollectorExecInterval(long newInterval)
Parameters:
  • newInterval – the new execution interval for incoming collector for this data.
setInCollectorMaxThread
public void setInCollectorMaxThread(long maxThread)
Parameters:
  • maxThread – the maximum thread for incoming message for this data.
setMailCollectorExecInterval
public void setMailCollectorExecInterval(long newInterval)
Parameters:
  • newInterval – the new execution interval for mail collector for this data.
setMailCollectorMaxThread
public void setMailCollectorMaxThread(long maxThread)
Parameters:
  • maxThread – the maximum thread for mail message for this data.
setOutCollectorExecInterval
public void setOutCollectorExecInterval(long newInterval)
Parameters:
  • newInterval – the new execution interval for outgoing collector for this data.
setOutCollectorMaxThread
public void setOutCollectorMaxThread(long maxThread)
Parameters:
  • maxThread – the maximum thread for outgoing message for this data.
setSendEndpoint
public void setSendEndpoint(String endpoint)

Set the web service endpoint for sending as2 config message to corvus.

Parameters:
  • endpoint – The web service endpoint for sending as2 config message to corvus.

EBMSMessageData

public class EBMSMessageData extends KVPairData

The EBMSMessageData is the data structure representing the parameters set for sending ebms message with payload to Hermes2. This is the sample WSDL request for the sending EbMS message WS request. *

<cpaId> ebmscpaid </cpaId>
<service> http://localhost:8080/corvus/httpd/ebms/inbound <service>
<action> action </action>
<convId> convId </convId>
<fromPartyId> fromPartyId </fromPartyId>
<fromPartyType> fromPartyType </fromPartyType>
<toPartyId> toPartyId </toPartyId>
<toPartyType> toPartyType </toPartyType>
<refToMessageId> </refToMessageId>
<serviceType> </serviceType>

This is the sample WSDL request for the retrieve EbMS message WS request.*

<messageId> target-messageId </messageId>

The first three parameters are derived from EBMSPartnershipData.getCpaId(), EBMSPartnershipData.getService() and EBMSPartnershipData.getAction()

Author:Twinsen Tsang

Fields

CONFIG_KEY_SET
public static final String[] CONFIG_KEY_SET

This is the configuration key set for XML serialization / de-serialization.

CONFIG_PREFIX
public static final String CONFIG_PREFIX

This is the configuration prefix for serialization / de-serialization.

PARAM_KEY_SET
public static final String[] PARAM_KEY_SET

This is the key set for XML serialization / de-serialization.

PARAM_PREFIX
public static final String PARAM_PREFIX

This is the parameters prefix for serialization / de-serialization.

isDirty
public boolean isDirty

It the data is dirty.

Constructors

EBMSMessageData
public EBMSMessageData()

Default Constructor.

Methods

getConversationId
public String getConversationId()
Returns:the conversationId
getFromPartyId
public String getFromPartyId()
Returns:the fromPartyId
getFromPartyType
public String getFromPartyType()
Returns:the fromPartyType
getMessageIdForReceive
public String getMessageIdForReceive()
Returns:the targeted Message ID for message receiver.
getRecvEndpoint
public String getRecvEndpoint()
Returns:Get the web service End-point for receiving ebMS message from CORVUS.
getRecvlistEndpoint
public String getRecvlistEndpoint()
Returns:Get the web service End-point for receiving a list of ebMS message which are ready to download from CORVUS.
getRefToMessageId
public String getRefToMessageId()
Returns:the refToMessageId
getSendEndpoint
public String getSendEndpoint()
Returns:Get the web service End-point for sending ebMS message to CORVUS.
getServiceType
public String getServiceType()
Returns:the service type.
getToPartyId
public String getToPartyId()
Returns:the toPartyId
getToPartyType
public String getToPartyType()
Returns:the toPartyType
setConversationId
public void setConversationId(String conversationId)
Parameters:
  • conversationId – the conversationId to set
setFromPartyId
public void setFromPartyId(String fromPartyId)
Parameters:
  • fromPartyId – the fromPartyId to set
setFromPartyType
public void setFromPartyType(String fromPartyType)
Parameters:
  • fromPartyType – the fromPartyType to set
setMessageIdForReceive
public void setMessageIdForReceive(String value)

Set the Message ID that targeted to retrieve

Parameters:
  • value – The MessageId of the message.
setRecvEndpoint
public void setRecvEndpoint(String endpoint)

Set the web service End-point for receiving ebMS message from CORVUS.

Parameters:
  • endpoint – The web service End-point for receiving ebMS message from CORVUS.
setRecvlistEndpoint
public void setRecvlistEndpoint(String endpoint)

Set the web service End-point for receiving a list of ebMS message which are ready to download from CORVUS.

Parameters:
  • endpoint – the web service End-point for receiving a list of ebMS message which are ready to download from CORVUS.
setRefToMessageId
public void setRefToMessageId(String refToMessageId)
Parameters:
  • refToMessageId – the refToMessageId to set
setSendEndpoint
public void setSendEndpoint(String endpoint)

Set the web service End-point for sending ebMS message to CORVUS.

Parameters:
  • endpoint – The web service End-point for sending ebMS message to CORVUS.
setServiceType
public void setServiceType(String serviceType)
Parameters:
  • serviceType – the service type to set.
setToPartyId
public void setToPartyId(String toPartyId)
Parameters:
  • toPartyId – the toPartyId to set
setToPartyType
public void setToPartyType(String toPartyType)
Parameters:
  • toPartyType – the toPartyType to set
toString
public String toString()

EBMSMessageHistoryRequestData

public class EBMSMessageHistoryRequestData extends MessageHistoryRequestData

Fields

CONFIG_PREFIX
public static final String CONFIG_PREFIX
CRITERIA_PARAM_PREFIX
public static final String CRITERIA_PARAM_PREFIX
PARAM_EBMS_KEY_SET
public static final String[] PARAM_EBMS_KEY_SET

Constructors

EBMSMessageHistoryRequestData
public EBMSMessageHistoryRequestData()

Methods

getAction
public String getAction()
getConversationId
public String getConversationId()
getCpaId
public String getCpaId()
getMessageId
public String getMessageId()
getService
public String getService()
setAction
public void setAction(String value)
setConversationId
public void setConversationId(String value)
setCpaId
public void setCpaId(String value)
setMessageId
public void setMessageId(String value)
setService
public void setService(String value)

EBMSPartnershipData

public class EBMSPartnershipData extends KVPairData

The EBMSPartnershipData is a duplicate-class data-structures for representing a EBMS partnership DVO object. It reduces the dependency from “corvus-ebms-core.jar” which changed quite frequently.

Author:Twinsen Tsang

Fields

PARAM_CLASS_SET
static final Class[] PARAM_CLASS_SET
PARAM_KEY_SET
public static final String[] PARAM_KEY_SET

This is the key set for XML serialization / de-serialization.

PARAM_PREFIX
public static final String PARAM_PREFIX

This is the parameter prefix for serialization / de-serialization.

Constructors

EBMSPartnershipData
public EBMSPartnershipData()

Default constructor.

Methods

getAckRequested
public String getAckRequested()
Returns:The acknowledgment requested.
getAckSignRequested
public String getAckSignRequested()
Returns:The acknowledgment signing requested.
getAction
public String getAction()
Returns:Returns the action.
getActor
public String getActor()
Returns:The actor.
getCpaId
public String getCpaId()
Returns:Returns the CPA ID.
getDisabled
public String getDisabled()
Returns:Returns the disabled.
getDsAlgorithm
public String getDsAlgorithm()
Returns:The digital signing algorithm.
getDupElimination
public String getDupElimination()
Returns:The duplicated elimination.
getEncryptAlgorithm
public String getEncryptAlgorithm()
Returns:The encryption algorithm.
getEncryptCert
public byte[] getEncryptCert()
Returns:The certificate for encryption in byte array.
getEncryptRequested
public String getEncryptRequested()
Returns:The checksum algorithm.
getIsHostnameVerified
public String getIsHostnameVerified()
Returns:True if the hostname is verified.
getMdAlgorithm
public String getMdAlgorithm()
Returns:The digital signing algorithm.
getMessageOrder
public String getMessageOrder()
Returns:The messageOrder.
getPartnershipId
public String getPartnershipId()
Returns:Returns the channel ID.
getPersistDuration
public String getPersistDuration()
Returns:The persistDuration.
getRetries
public int getRetries()
Returns:The retries.
getRetryInterval
public int getRetryInterval()
Returns:The retryInterval.
getService
public String getService()
Returns:Returns the service.
getSignCert
public byte[] getSignCert()
Returns:The certificate for verification in byte array.
getSignRequested
public String getSignRequested()
Returns:The signing requested.
getSyncReplyMode
public String getSyncReplyMode()
Returns:Returns the syncReplyMode.
getTransportEndpoint
public String getTransportEndpoint()
Returns:The transportEndpoint.
getTransportProtocol
public String getTransportProtocol()
Returns:The transportProtocol.
setAckRequested
public void setAckRequested(String ackRequested)
Parameters:
  • ackRequested – The acknowledgment requested to set.
setAckSignRequested
public void setAckSignRequested(String ackSignRequested)
Parameters:
  • ackSignRequested – The acknowledgment signing requested to set.
setAction
public void setAction(String action)
Parameters:
  • action – The action to set.
setActor
public void setActor(String actor)
Parameters:
  • actor – The actor to set.
setCpaId
public void setCpaId(String cpaId)
Parameters:
  • cpaId – The CPA ID to set.
setDisabled
public void setDisabled(String disabled)
Parameters:
  • disabled – The disabled to set.
setDsAlgorithm
public void setDsAlgorithm(String dsAlgorithm)
Parameters:
  • dsAlgorithm – The digital signing algorithm to set.
setDupElimination
public void setDupElimination(String dupElimination)
Parameters:
  • dupElimination – The duplicated elimination to set.
setEncryptAlgorithm
public void setEncryptAlgorithm(String encryptAlgorithm)
Parameters:
  • encryptAlgorithm – The encryption algorithm to set.
setEncryptCert
public void setEncryptCert(byte[] encryptCert)
Parameters:
  • encryptCert – The certificate for encryption in byte array.
setEncryptRequested
public void setEncryptRequested(String encryptRequested)
Parameters:
  • encryptRequested – The encryption requested to set.
setIsHostnameVerified
public void setIsHostnameVerified(String isHostnameVerified)
Parameters:
  • isHostnameVerified – True if the hostname verified to set.
setMdAlgorithm
public void setMdAlgorithm(String mdAlgorithm)
Parameters:
  • mdAlgorithm – The checksum algorithm to set.
setMessageOrder
public void setMessageOrder(String messageOrder)
Parameters:
  • messageOrder – The messageOrder to set.
setPartnershipId
public void setPartnershipId(String partnershipId)
Parameters:
  • partnershipId – The partnership ID to set.
setPersistDuration
public void setPersistDuration(String persistDuration)
Parameters:
  • persistDuration – The persistDuration to set.
setRetries
public void setRetries(int retries)
Parameters:
  • retries – The retries to set.
setRetryInterval
public void setRetryInterval(int retryInterval)
Parameters:
  • retryInterval – The retryInterval to set.
setService
public void setService(String service)
Parameters:
  • service – The service to set.
setSignCert
public void setSignCert(byte[] signCert)
Parameters:
  • signCert – The certificate for verification to set in byte array.
setSignRequested
public void setSignRequested(String signRequested)
Parameters:
  • signRequested – The signing requested to set.
setSyncReplyMode
public void setSyncReplyMode(String syncReplyMode)
Parameters:
  • syncReplyMode – The syncReplyMode to set.
setTransportEndpoint
public void setTransportEndpoint(String transportEndpoint)
Parameters:
  • transportEndpoint – The transportEndpoint to set.
setTransportProtocol
public void setTransportProtocol(String transportProtocol)
Parameters:
  • transportProtocol – The transportProtocol to set.

EBMSStatusQueryData

public class EBMSStatusQueryData extends CorvusStatusQueryData

The EBMSStatusQueryData is the data structure representing the request parameter set for EBMS Status Query web services. This is the sample WSDL request for the status query WS request.

<messageId> 20070418-124233-75006@147.8.177.42 </messageId>

Creation Date: 10/05/2007

Author:Twinsen Tsang

Fields

CONFIG_PREFIX
public static final String CONFIG_PREFIX

This is the configuration prefix for serialization / de-serialization.

PARAM_PREFIX
public static final String PARAM_PREFIX

This is the param prefix for serialzation / de-serialization.

Constructors

EBMSStatusQueryData
public EBMSStatusQueryData()

Default Constructor.

EBMSStatusQueryResponseData

public class EBMSStatusQueryResponseData extends CorvusStatusQueryResponseData

The EBMSStatusQueryResponseData is the data structure representing the response data set for EBMS status query web services. This is the sample WSDL request for the status query WS request.

   <status> The current status of message </status>
<statusDescription> The current status description of message </statusDescription>
<ackMessageId> The message id of acknowledgment / receipt if any </ackMessageId>
<ackStatus> The status of acknowledgment / receipt if any </ackStatus>
<ackStatusDescription> The status description of acknowledgment / receipt if any </ackStatusDescription>

Creation Date: 10/05/2007

Author:Twinsen Tsang

Fields

PARAM_KEY_SET
public static final String[] PARAM_KEY_SET

This is the key set for XML serialization / de-serialization.

Constructors

EBMSStatusQueryResponseData
public EBMSStatusQueryResponseData()

Default Constructor.

KVPairData

public class KVPairData implements Data

The KVPairData is a simple data structures for storing key-valued style data. It is implemented based on java.util.Map. You can define the max capacity through the constructor so that the internal data does not need to rehash when there is not enough room. Creation Date: 21/3/2007

Author:Twinsen Tsang

Fields

props
protected Map props

The KVPair interval data.

Constructors

KVPairData
public KVPairData(int maxCapacity)

Explicit Constructor.

Parameters:
  • maxCapacity – The maximum Key value pair that the data can hold.

Methods

getProperties
public Map getProperties()
Returns:the properties set for this MessageStatusRequestData.
setProperties
public void setProperties(Map hm)

Set the message status request properties and overwrite the existing one. This operation success only when the size of hm is smaller than it’s maxCapacity defined in the constructor.

Parameters:
  • hm – The new properties set.
toString
public String toString()

toString method. Simple Key-Iteration

MessageHistoryRequestData

public class MessageHistoryRequestData extends KVPairData

Fields

CONFIG_KEY_SET
public static final String[] CONFIG_KEY_SET
PARAM_KEY_SET
public static final String[] PARAM_KEY_SET

For consistent, used for DataFactory.createEBMSAdminDataFromXML(hk.hku.cecid.piazza.commons.util.PropertyTree)

Constructors

MessageHistoryRequestData
public MessageHistoryRequestData(int maxCapacity)

Methods

getEndPoint
public String getEndPoint()
getMessageBox
public String getMessageBox()
getStatus
public String getStatus()
setEndPoint
public void setEndPoint(String value)
setMessageBox
public void setMessageBox(String value)
setStatus
public void setStatus(String value)

MessageStatusRequestData

public class MessageStatusRequestData extends KVPairData

The MessageStatusRequestData is the data structures representing the parameters set for message status request query. This is the WSDL schema for the message status WS request.

<xs:sequence>
 <xs:element name="partnershipId" type="xs:string" minOccurs="0"/>
 <xs:element name="channelType" type="xs:string" minOccurs="0"/>
 <xs:element name="channelId" type="xs:string" minOccurs="0"/>
 <xs:element name="folderName" type="xs:string" minOccurs="0"/>
 <xs:element name="fileName" type="xs:string" minOccurs="0"/>
 <xs:element name="fromTimestamp" type="xs:dateTime" minOccurs="0"/>
 <xs:element name="toTimestamp" type="xs:dateTime" minOccurs="0"/>
 <xs:element name="numOfRecords" type="xs:integer" minOccurs="0"/>
 <xs:element name="conversationId" type="xs:string" minOccurs="0"/>
 <xs:element name="messageId" type="xs:string" minOccurs="0"/>
 <xs:element name="messageType" type="xs:string" minOccurs="0"/>
 <xs:element name="messageStatus" type="xs:string" minOccurs="0"/>
 <xs:element name="protocol" type="xs:string" minOccurs="0"/>
 <xs:element name="locale" type="xs:string" minOccurs="0"/>
 <xs:element name="levelOfDetails" type="xs:integer" minOccurs="0"/>
 <xs:element name="offset" type="xs:integer" minOccurs="0"/>
</xs:sequence>

Creation Date: 12/3/2007

Author:Twinsen Tsang

Fields

CONFIG_KEY_SET
public static final String[] CONFIG_KEY_SET

This is the configuration key set for XML serialization / de-serialization.

CONFIG_PREFIX
public static final String CONFIG_PREFIX

This is the prefix for serialization / de-serialization.

PARAM_KEY_SET
public static final String[] PARAM_KEY_SET

This is the key set for XML serialization / de-serialization.

PARAM_PREFIX
public static final String PARAM_PREFIX

This is the prefix for serialzation / de-serialization.

Constructors

MessageStatusRequestData
public MessageStatusRequestData()

Default Constructor.

Methods

getChannelId
public String getChannelId()

Gets the channelId value for this MessageStatusRequestData.

Returns:channelId
getChannelType
public String getChannelType()

Gets the channelType value for this MessageStatusRequestData.

Returns:channelType
getConversationId
public String getConversationId()

Gets the conversationId value for this MessageStatusRequestData.

Returns:conversationId
getFileName
public String getFileName()

Gets the fileName value for this MessageStatusRequestData.

Returns:fileName
getFolderName
public String getFolderName()

Gets the folderName value for this MessageStatusRequestData.

Returns:folderName
getFromTimestamp
public String getFromTimestamp()

Gets the fromTimestamp value for this MessageStatusRequestData.

Returns:fromTimestamp
getLevelOfDetails
public BigInteger getLevelOfDetails()

Gets the levelOfDetails value for this MessageStatusRequestData. The default value is 1.

Returns:levelOfDetails
getLocale
public String getLocale()

Gets the locale value for this MessageStatusRequestData.

Returns:locale
getMessageId
public String getMessageId()

Gets the messageId value for this MessageStatusRequestData.

Returns:messageId
getMessageStatus
public String getMessageStatus()

Gets the messageStatus value for this MessageStatusRequestData.

Returns:messageStatus
getMessageType
public String getMessageType()

Gets the messageType value for this MessageStatusRequestData.

Returns:messageType
getNumOfRecords
public BigInteger getNumOfRecords()

Gets the numOfRecords value for this MessageStatusRequestData. The default value is 1.

Returns:numOfRecords
getOffset
public BigInteger getOffset()

Gets the offset value for this MessageStatusRequestData. The default value is 1.

Returns:offset
getPartnershipId
public String getPartnershipId()

Gets the partnershipId value for this MessageStatusRequestData.

Returns:partnershipId
getPassword
public String getPassword()

Get the password for authentication.

getProtocol
public String getProtocol()

Gets the protocol value for this MessageStatusRequestData.

Returns:protocol
getToTimestamp
public String getToTimestamp()

Gets the toTimestamp value for this MessageStatusRequestData.

Returns:toTimestamp
getUsername
public String getUsername()

Get the username for authentication.

Returns:Get the username for authentication.
getWSEndpoint
public String getWSEndpoint()

Get the web service end point for this MessageStatusRequestData.

setChannelId
public void setChannelId(String channelId)

Sets the channelId value for this MessageStatusRequestData.

Parameters:
  • channelId
setChannelType
public void setChannelType(String channelType)

Sets the channelType value for this MessageStatusRequestData.

Parameters:
  • channelType
setConversationId
public void setConversationId(String conversationId)

Sets the conversationId value for this MessageStatusRequestData.

Parameters:
  • conversationId
setFileName
public void setFileName(String fileName)

Sets the fileName value for this MessageStatusRequestData.

Parameters:
  • fileName
setFolderName
public void setFolderName(String folderName)

Sets the folderName value for this MessageStatusRequestData.

Parameters:
  • folderName
setFromTimestamp
public void setFromTimestamp(Calendar fromTimestamp)

Sets the fromTimestamp value for this MessageStatusRequestData.

Parameters:
  • fromTimestamp
setLevelOfDetails
public void setLevelOfDetails(BigInteger levelOfDetails)

Sets the levelOfDetails value for this MessageStatusRequestData.

Parameters:
  • levelOfDetails
setLocale
public void setLocale(String locale)

Sets the locale value for this MessageStatusRequestData.

Parameters:
  • locale
setMessageId
public void setMessageId(String messageId)

Sets the messageId value for this MessageStatusRequestData.

Parameters:
  • messageId
setMessageStatus
public void setMessageStatus(String messageStatus)

Sets the messageStatus value for this MessageStatusRequestData.

Parameters:
  • messageStatus
setMessageType
public void setMessageType(String messageType)

Sets the messageType value for this MessageStatusRequestData.

Parameters:
  • messageType
setNumOfRecords
public void setNumOfRecords(BigInteger numOfRecords)

Sets the numOfRecords value for this MessageStatusRequestData.

Parameters:
  • numOfRecords
setOffset
public void setOffset(BigInteger offset)

Sets the offset value for this MessageStatusRequestData.

Parameters:
  • offset
setPartnershipId
public void setPartnershipId(String partnershipId)

Sets the partnershipId value for this MessageStatusRequestData.

Parameters:
  • partnershipId
setPassword
public void setPassword(String password)

Set the password for authentication.

setProtocol
public void setProtocol(String protocol)

Sets the protocol value for this MessageStatusRequestData.

Parameters:
  • protocol
setToTimestamp
public void setToTimestamp(Calendar toTimestamp)

Sets the toTimestamp value for this MessageStatusRequestData.

Parameters:
  • toTimestamp
setUsername
public void setUsername(String username)

Set the username for authentication.

Parameters:
  • username – The username for authentication.
setWSEndpoint
public void setWSEndpoint(String endpoint)

Set the web service end point for this MessageStatusRequestData.

Parameters:
  • endpoint – The new web service end point.
toString
public String toString()

toString method().

MessageStatusResponseData

public class MessageStatusResponseData extends KVPairData

The MessageStatusResponseData is the data structures representing the parameters set for the response in the message status requestquery. This is the WSDL schema for the message status WS request.

<xs:complexType name="MessageInfo.Type">
 <xs:sequence>
  <xs:element name="messageId" type="xs:string"/>
  <xs:element name="messageType" type="xs:string"/>
  <xs:element name="timestamp" type="xs:dateTime"/>
  <xs:element name="messageStatus" type="xs:string"/>
  <xs:element name="messageDetail" type="xs:string" minOccurs="0"/>
  <xs:element name="partnershipId" type="xs:string" minOccurs="0"/>
  <xs:element name="channelType" type="xs:string" minOccurs="0"/>
  <xs:element name="channelId" type="xs:string" minOccurs="0"/>
  <xs:element name="folderName" type="xs:string" minOccurs="0"/>
  <xs:element name="fileName" type="xs:string" minOccurs="0"/>
  <xs:element name="conversationId" type="xs:string" minOccurs="0"/>
 </xs:sequence>
</xs:complexType>

Creation Date: 19/3/2007

Author:Twinsen Tsang

Fields

PARAM_KEY_SET
public static final String[] PARAM_KEY_SET

This is the key set for XML serialization / de-serialization.

Constructors

MessageStatusResponseData
public MessageStatusResponseData()

Default Constructor.

Methods

getChannelId
public String getChannelId()

Gets the channelId value for this MessageInfoType.

Returns:channelId
getChannelType
public String getChannelType()

Gets the channelType value for this MessageInfoType.

Returns:channelType
getConversationId
public String getConversationId()

Gets the conversationId value for this MessageInfoType.

Returns:conversationId
getFileName
public String getFileName()

Gets the fileName value for this MessageInfoType.

Returns:fileName
getFolderName
public String getFolderName()

Gets the folderName value for this MessageInfoType.

Returns:folderName
getMessageDetail
public String getMessageDetail()

Gets the messageDetail value for this MessageInfoType.

Returns:messageDetail
getMessageId
public String getMessageId()

Gets the messageId value for this MessageInfoType.

Returns:messageId
getMessageStatus
public String getMessageStatus()

Gets the messageStatus value for this MessageInfoType.

Returns:messageStatus
getMessageType
public String getMessageType()

Gets the messageType value for this MessageInfoType.

Returns:messageType
getPartnershipId
public String getPartnershipId()

Gets the partnershipId value for this MessageInfoType.

Returns:partnershipId
getProperties
public Map getProperties()
Returns:the properties set for this MessageStatusResponseData.
getTimestamp
public String getTimestamp()

Gets the timestamp value for this MessageInfoType.

Returns:timestamp
setChannelId
public void setChannelId(String channelId)

Sets the channelId value for this MessageInfoType.

Parameters:
  • channelId
setChannelType
public void setChannelType(String channelType)

Sets the channelType value for this MessageInfoType.

Parameters:
  • channelType
setConversationId
public void setConversationId(String conversationId)

Sets the conversationId value for this MessageInfoType.

Parameters:
  • conversationId
setFileName
public void setFileName(String fileName)

Sets the fileName value for this MessageInfoType.

Parameters:
  • fileName
setFolderName
public void setFolderName(String folderName)

Sets the folderName value for this MessageInfoType.

Parameters:
  • folderName
setMessageDetail
public void setMessageDetail(String messageDetail)

Sets the messageDetail value for this MessageInfoType.

Parameters:
  • messageDetail
setMessageId
public void setMessageId(String messageId)

Sets the messageId value for this MessageInfoType.

Parameters:
  • messageId
setMessageStatus
public void setMessageStatus(String messageStatus)

Sets the messageStatus value for this MessageInfoType.

Parameters:
  • messageStatus
setMessageType
public void setMessageType(String messageType)

Sets the messageType value for this MessageInfoType.

Parameters:
  • messageType
setPartnershipId
public void setPartnershipId(String partnershipId)

Sets the partnershipId value for this MessageInfoType.

Parameters:
  • partnershipId
setProperties
public void setProperties(HashMap hm)

Set the message status request properties and overwrite the existing one.

Parameters:
  • hm – The new properties set.
setTimestamp
public void setTimestamp(Calendar timestamp)

Sets the timestamp value for this MessageInfoType.

Parameters:
  • timestamp
toString
public String toString()

toString method().

Payload

public class Payload implements Data

The Payload is a data object representing a payload in the SOAP message.

Author:Twinsen Tsang

Constructors

Payload
public Payload(String filePath, String contentType)

Explicit Constructor.

Parameters:
  • filePath – The payload filepath.
  • contentType – The content type of payload.
Payload
public Payload(InputStream inputStream, String contentType)
Parameters:
  • inputStream
  • contentType

Methods

getContentType
public String getContentType()
Returns:The content type of payload.
getFilePath
public String getFilePath()
Returns:The filepath of the payload.
getInputStream
public InputStream getInputStream()
Returns:The input stream of the payload
setFilePath
public void setFilePath(String filepath)

Set filepath of the payload. (This method is open to set the filename of payload for message receiver)

toString
public String toString()

toString method

PermitRedownloadData

public class PermitRedownloadData extends KVPairData

Fields

AS2_CONFIG_PREFIX
public static final String AS2_CONFIG_PREFIX
AS2_PARAM_PREFIX
public static final String AS2_PARAM_PREFIX
CONFIG_KEY_SET
public static final String[] CONFIG_KEY_SET
EBMS_CONFIG_PREFIX
public static final String EBMS_CONFIG_PREFIX
EBMS_PARAM_PREFIX
public static final String EBMS_PARAM_PREFIX
PARAM_KEY_SET
public static final String[] PARAM_KEY_SET
PROTOCOL_AS2
public static final String PROTOCOL_AS2
PROTOCOL_EBMS
public static final String PROTOCOL_EBMS

Constructors

PermitRedownloadData
public PermitRedownloadData(String protocol)

Methods

getEndpoint
public String getEndpoint()
getTargetMessageId
public String getTargetMessageId()
toString
public String toString()

SFRMStatusQueryData

public class SFRMStatusQueryData extends CorvusStatusQueryData

The CorvusStatusQueryData is the data structure representing the parameters set for status query web services for SFRM protocol using Corvus level. This is the sample WSDL request for the SFRM status query WS request.

<messageId> 20070418-124233-75006@147.8.177.42 </messageId>

Creation Date: 2/5/2007 Creation Date: 02/05/2007

Author:Twinsen Tsang

Fields

CONFIG_PREFIX
public static final String CONFIG_PREFIX

This is the configuration prefix for serialization / de-serialization.

PARAM_PREFIX
public static final String PARAM_PREFIX

This is the param prefix for serialzation / de-serialization.

Constructors

SFRMStatusQueryData
public SFRMStatusQueryData()

Default Constructor.

SFRMStatusQueryResponseData

public class SFRMStatusQueryResponseData extends KVPairData

The SFRMStatusQueryResponseData is the data structure representing the response data set for SFRM Message Status Query serivce. This is the sample WSDL response for the SFRM status query WS request.

<messageInfo>
<status> The current status of message </status>
<statusDescription> The current status description of message </statusDescription>
<numberOfSegments> Maximum number of segments </numberOfSegments>
<numberOfProcessedSegments> Number of processed segments </numberOfProcessedSegments>
<lastUpdatedTime>  The last updated timestamp  </lastUpdatedTime>
</messageInfo>

Creation Date: 10/5/2007

Author:Twinsen Tsang

Fields

PARAM_KEY_SET
public static final String[] PARAM_KEY_SET

This is the key set for XML serialization / de-serialization.

Constructors

SFRMStatusQueryResponseData
public SFRMStatusQueryResponseData()

Default Constructor.

Methods

getLastUpdatedTimestamp
public Timestamp getLastUpdatedTimestamp()

The last updated timestamp define the last time that the SFRM message was being processing. (last activity time).

Returns:the last active time for thie SFRM Message.
getMessageId
public String getMessageId()
Returns:the message ID of the SFRM message being queried.
getNumberOfProcessedSegments
public int getNumberOfProcessedSegments()
Returns:the number of processed segments for this SFRM Message.
getNumberOfSegments
public int getNumberOfSegments()
Returns:the number of segments for this SFRM Message.
getStatus
public String getStatus()
Returns:the current status of SFRM Message.
getStatusDescription
public String getStatusDescription()
Returns:the current status description of SFRM Message.

hk.hku.cecid.ebms.admin.listener

AgreementUploadPageletAdaptor

public class AgreementUploadPageletAdaptor extends AdminPageletAdaptor
Author:Donahue Sze

Fields

X_ATTR_PARTY_NAME
String X_ATTR_PARTY_NAME
X_CAN_SEND
String X_CAN_SEND
X_CHANNEL_ID
String X_CHANNEL_ID
X_COLLABORATION_PROTOCOL_AGREEMENT
String X_COLLABORATION_PROTOCOL_AGREEMENT
X_COLLABORATION_ROLE
String X_COLLABORATION_ROLE
X_DELIVERY_CHANNEL
String X_DELIVERY_CHANNEL
X_DOC_EXCHANGE
String X_DOC_EXCHANGE
X_EBXML_SENDER_BINDING
String X_EBXML_SENDER_BINDING
X_ENDPOINT
String X_ENDPOINT
X_MESSAGING_CHARACTERISTICS
String X_MESSAGING_CHARACTERISTICS
X_PARTY_INFO
String X_PARTY_INFO
X_RELIABLE_MESSAGING
String X_RELIABLE_MESSAGING
X_SENDER_DIGITAL_ENVELOPE
String X_SENDER_DIGITAL_ENVELOPE
X_SENDER_NON_REPUDIATION
String X_SENDER_NON_REPUDIATION
X_SERVICE
String X_SERVICE
X_SERVICE_BINDING
String X_SERVICE_BINDING
X_THIS_PARTY_ACTION_BINDING
String X_THIS_PARTY_ACTION_BINDING
X_TP_NAMESPACE
String X_TP_NAMESPACE
X_TRANSPORT
String X_TRANSPORT
X_TRANSPORT_RECEIVER
String X_TRANSPORT_RECEIVER
selectedPartyName
String selectedPartyName

Methods

getCenterSource
protected Source getCenterSource(HttpServletRequest request)

ChangeMessageStatusPageletAdaptor

public class ChangeMessageStatusPageletAdaptor extends AdminPageletAdaptor
Author:Donahue Sze

Methods

getCenterSource
protected Source getCenterSource(HttpServletRequest request)

EbmsPropertiesPageletAdaptor

public class EbmsPropertiesPageletAdaptor extends AdminPageletAdaptor
Author:Donahue Sze

Methods

getCenterSource
protected Source getCenterSource(HttpServletRequest request)

MessageHistoryOraclePageletAdaptor

public class MessageHistoryOraclePageletAdaptor extends MessageHistoryPageletAdaptor
Author:Donahue Sze

MessageHistoryPageletAdaptor

public class MessageHistoryPageletAdaptor extends AdminPageletAdaptor
Author:Donahue Sze

Methods

getCenterSource
protected Source getCenterSource(HttpServletRequest request)

MessageHistoryPageletAdaptorTest

public class MessageHistoryPageletAdaptorTest extends TestCase

Methods

setUp
public void setUp()
tearDown
public void tearDown()
testCheckEmptyAndReturnNull
public void testCheckEmptyAndReturnNull()
testCheckNullAndReturnEmpty
public void testCheckNullAndReturnEmpty()
testCheckStarAndConvertToPercent
public void testCheckStarAndConvertToPercent()

PartnershipPageletAdaptor

public class PartnershipPageletAdaptor extends AdminPageletAdaptor
Author:Donahue Sze

Methods

getCenterSource
protected Source getCenterSource(HttpServletRequest request)
getHashtable
public Hashtable getHashtable(HttpServletRequest request)

RepositoryAdaptor

public class RepositoryAdaptor extends HttpRequestAdaptor
Author:Donahue Sze

Methods

processRequest
public String processRequest(HttpServletRequest request, HttpServletResponse response)

ResendAsNewAdapter

public class ResendAsNewAdapter extends AdminPageletAdaptor

Methods

getCenterSource
protected Source getCenterSource(HttpServletRequest request)

hk.hku.cecid.ebms.handler

InboundMessageProcessorTest

public class InboundMessageProcessorTest extends TestCase

The InboundMessageProcessorTest is the testcase for InboundMessageProcessor.

Author:Philip Wong

See also: hk.hku.cecid.ebms.handler.InboundMessageProcessor

Methods

setUp
public void setUp()
tearDown
public void tearDown()
testCheckExpiredMessage
public void testCheckExpiredMessage()

hk.hku.cecid.ebms.pkg

AckRequested

public class AckRequested extends HeaderElement

An ebXML AckRequested in the SOAP Header of a HeaderContainer [ebMSS 6.3.1].

Author:cyng

Fields

ACK_REQUESTED
static final String ACK_REQUESTED

AckRequested element name.

ATTRIBUTE_SIGNED
static final String ATTRIBUTE_SIGNED

Name of the Signed attribute.

Constructors

AckRequested
AckRequested(SOAPEnvelope soapEnvelope, boolean signed)

Constructs a AckRequested with the given mandatory fields.

Parameters:
  • soapEnvelopeSOAPEnvelope, the header of which the AckRequested element is added to.
  • signed – Indicates if a signed acknowledgement response is requested. True if a signed response is requested; false otherwise.
Throws:
  • SOAPException
AckRequested
AckRequested(SOAPEnvelope soapEnvelope, SOAPElement soapElement)

Constructs a AckRequested with the given mandatory fields.

Parameters:
  • soapEnvelopeSOAPEnvelope, the header of which the AckRequested element is added to.
  • soapElementSOAPElement containing acknowledgement request.
Throws:
  • SOAPException

Methods

getSigned
public boolean getSigned()

Gets the flag that if a signed acknowledgement response is requested.

Returns:true if a signed acknowledgement response is requested; false otherwise.

Acknowledgment

public class Acknowledgment extends HeaderElement

An ebXML Acknowledgment in the SOAP Header of a HeaderContainer [ebMSS 6.3.2].

Author:cyng

Fields

ACKNOWLEDGMENT
static final String ACKNOWLEDGMENT

Acknowledgment element name

Constructors

Acknowledgment
Acknowledgment(SOAPEnvelope soapEnvelope, String timestamp, EbxmlMessage refToMessage, String fromPartyId, String fromPartyIdType)

Constructs an Acknowledgment with the given mandatory fields.

Parameters:
  • soapEnvelopeSOAPEnvelope, the header container of which the Acknowledgement is attached to.
  • timestamp – The time the message service handler received the message to be acknowledged.
  • refToMessage – The message this acknowledgement response is referring to.
  • fromPartyId – The identifier of the party generating the acknowledgement response message.
  • fromPartyIdType – PartyId type
Throws:
  • SOAPException
Acknowledgment
Acknowledgment(SOAPEnvelope soapEnvelope, SOAPElement soapElement)

Constructs an Acknowledgement object by parsing the given SOAPElement.

Parameters:
  • soapEnvelopeSOAPEnvelope, the header container of which the Acknowledgement is attached to.
  • soapElementSOAPElement containing acknowledgement response.
Throws:
  • SOAPException

Methods

addFromPartyId
public void addFromPartyId(String id)

Add sender’s PartyID into this Acknowledgement

Parameters:
  • id – Sender’s PartyID string.
Throws:
  • SOAPException
addFromPartyId
public void addFromPartyId(String id, String type)

Add sender’s PartyID and its type into this Acknowledgement

Parameters:
  • id – Sender’s PartyID string.
  • type – PartyID type.
Throws:
  • SOAPException
addSignatureReference
public void addSignatureReference(SignatureReference reference)
getFromPartyIds
public Iterator getFromPartyIds()

Get the identifiers of the party generating the acknowledgement response

Returns:Iterator of MessageHeader.PartyId
getRefToMessageId
public String getRefToMessageId()

Get the identifier of the message being acknowledged.

Returns:Identifier of the message being acknowledged.
getSignatureReferences
public Iterator getSignatureReferences()
getTimestamp
public String getTimestamp()

Get the time that the message being acknowledged is received.

Returns:Timestamp expressed in UTC format.

AttachmentDataSource

public class AttachmentDataSource implements DataSource

This is an implementation of javax.activation.DataSource that encapsulates attachment data in a SOAP message.

Author:cyng

Constructors

AttachmentDataSource
public AttachmentDataSource(byte[] data, String contentType)

Constructs an AttachmentDataSource object from an array of binary data.

Parameters:
  • data – Byte array containing data for the AttachmentDataSource
  • contentType – Content type of the data.
AttachmentDataSource
public AttachmentDataSource(byte[] data, String contentType, String name)

Constructs an AttachmentDataSource object from an array of binary data, and assign a name to the data source.

Parameters:
  • data – Byte array containing data for the AttachmentDataSource
  • contentType – Content type of the data.
  • name – Name assigned to the AttachmentDataSource
AttachmentDataSource
public AttachmentDataSource(byte[] data, String contentType, String encoding, String name)

Constructs an AttachmentDataSource object from an array of binary data, and assign a name to the data source.

Parameters:
  • data – Byte array containing data for the AttachmentDataSource
  • contentType – Content type of the data.
  • encoding – Content-Transfer-Encoding of the data.
  • name – Name assigned to the AttachmentDataSource
AttachmentDataSource
public AttachmentDataSource(String fileName, String contentType)

Constructs an AttachmentDataSource object from a file.

Parameters:
  • fileName – Name of the file to be loaded.
  • contentType – Content type of the file.
Throws:
  • IOException
AttachmentDataSource
public AttachmentDataSource(String fileName, String contentType, boolean loadToMem)

Constructs an AttachmentDataSource object from a file.

Parameters:
  • fileName – Name of the file to be loaded.
  • contentType – Content type of the file.
  • loadToMem – Load all data to memory upon creation
Throws:
  • IOException
AttachmentDataSource
public AttachmentDataSource(File file, String contentType)

Constructs an AttachmentDataSource object from a File object.

Parameters:
  • fileFile object containing information on the file to be loaded.
  • contentType – Content type of the file.
Throws:
  • IOException
AttachmentDataSource
public AttachmentDataSource(File file, String contentType, boolean loadToMem)

Constructs an AttachmentDataSource object from a File object.

Parameters:
  • fileFile object containing information on the file to be loaded.
  • contentType – Content type of the file.
  • loadToMem – Load all data to memory upon creation
Throws:
  • IOException
AttachmentDataSource
public AttachmentDataSource(InputStream in, String contentType)

Constructs an AttachmentDataSource object from an InputStream.

Parameters:
  • inInputStream from which the data is read and stored in the data source.
  • contentType – Content type of the data.
Throws:
  • IOException
AttachmentDataSource
public AttachmentDataSource(InputStream in, String contentType, String name)

Constructs an AttachmentDataSource object from an InputStream with a given name.

Parameters:
  • inInputStream from which the data is read and stored in the data source.
  • contentType – Content type of the data.
  • name – Name assigned to the AttachmentDataSource.
Throws:
  • IOException
AttachmentDataSource
public AttachmentDataSource(InputStream in, String contentType, String encoding, String name)

Constructs an AttachmentDataSource object from an InputStream with the specified Content-Transfer-Encoding and name.

Parameters:
  • inInputStream from which the data is read and stored in the data source.
  • contentType – Content type of the data.
  • encoding – Content-Transfer-Encoding of the data.
  • name – Name assigned to the AttachmentDataSource.
Throws:
  • IOException
AttachmentDataSource
public AttachmentDataSource(String fileName, long offset, long length, String contentType)

Constructs an AttachmentDataSource object using the data of length in a file starting from offset with the specified Content-Type.

Parameters:
  • fileName – Name of the file to be loaded.
  • offset – Offset from the start of the file.
  • length – Length of data to be read.
  • contentType – Content type of the data.
AttachmentDataSource
public AttachmentDataSource(String fileName, long offset, long length, String contentType, boolean loadToMem)

Constructs an AttachmentDataSource object using the data of length in a file starting from offset with the specified Content-Type.

Parameters:
  • fileName – Name of the file to be loaded.
  • offset – Offset from the start of the file.
  • length – Length of data to be read.
  • contentType – Content type of the data.
  • loadToMem – Load all data to memory upon creation
AttachmentDataSource
public AttachmentDataSource(String fileName, long offset, long length, String contentType, String encoding)

Constructs an AttachmentDataSource object using the data of length in a file starting from offset. with the specified Content-Type and Content-Transfer-Encoding.

Parameters:
  • fileName – Name of the file to be loaded.
  • offset – Offset from the start of the file.
  • length – Length of data to be read.
  • contentType – Content type of the data.
  • encoding – Content-Transfer-Encoding of the data.
AttachmentDataSource
public AttachmentDataSource(String fileName, long offset, long length, String contentType, String encoding, boolean loadToMem)

Constructs an AttachmentDataSource object using the data of length in a file starting from offset. with the specified Content-Type and Content-Transfer-Encoding.

Parameters:
  • fileName – Name of the file to be loaded.
  • offset – Offset from the start of the file.
  • length – Length of data to be read.
  • contentType – Content type of the data.
  • encoding – Content-Transfer-Encoding of the data.
  • loadToMem – Load all data to memory upon creation
AttachmentDataSource
public AttachmentDataSource(DataSource dataSource, long offset, long length, String contentType, String encoding, boolean loadToMem)

Methods

getByteArray
public byte[] getByteArray()

Gets a byte array of data in this data source.

Returns:A byte array of data.
getContentType
public String getContentType()

Gets the content type of data stored in this AttachmentDataSource.

Returns:Content type of data stored in data source.
getInputStream
public InputStream getInputStream()

Gets InputStream from which data in the AttachmentDataSource can be read.

Throws:
  • IOException
Returns:

An InputStream.

getLength
public long getLength()

Gets the length of data in this data source

Returns:length of data
getName
public String getName()

Gets the name of the AttachmentDataSource.

Returns:Name of data source.
getOutputStream
public OutputStream getOutputStream()

This method should never be called. It implements the getOutputStream() method of the javax.activation.DataSource interface and IOException will be thrown as the result of invocation.

Throws:
  • IOException
Returns:

This method always result in IOException; it never returns normally.

setName
public void setName(String name)

Sets the name of the AttachmentDataSource.

Parameters:
  • name – Name of data source.

AttachmentResolver

class AttachmentResolver extends ResourceResolverSpi

A ResourceResolver implementation used by Apache Security library. The URI in the Reference element of a digital signature points to some internal or external resources. This AttachmentResolver is used to provide the resources in the EbxmlMessage payload attachments and also the SOAPPart itself with Reference URI=””.

Author:cyng

Constructors

AttachmentResolver
AttachmentResolver(EbxmlMessage ebxmlMessage)

Methods

engineCanResolveURI
public boolean engineCanResolveURI(ResourceResolverContext context)
engineResolveURI
public XMLSignatureInput engineResolveURI(ResourceResolverContext context)

BodyElement

class BodyElement extends ExtensionElementImpl

An ExtensionElement in the SOAP Body of a HeaderContainer

Author:cyng

Constructors

BodyElement
BodyElement(SOAPEnvelope soapEnvelope, SOAPElement soapElement)
BodyElement
BodyElement(SOAPEnvelope soapEnvelope, String localName)

Constants

public class Constants

This class serves as a bag containing all the constants that fall in the following criteria: (1) Related to property settings (2) Public strings (3) Previously public strings that are declared multiple times in various locations.

Author:Frankie Lam

Fields

CHARACTER_ENCODING
public static final String CHARACTER_ENCODING

Default XML character encoding.

CHARACTER_SET
public static final String CHARACTER_SET

Content type character set attribute.

CONTENT_ID
public static final String CONTENT_ID

HTTP Header attribute specifying content id.

CONTENT_LENGTH
public static final String CONTENT_LENGTH

HTTP Header attribute specifying content length.

CONTENT_TRANSFER_ENCODING
public static final String CONTENT_TRANSFER_ENCODING

HTTP Header attribute specifying content transfer encoding.

CONTENT_TYPE
public static final String CONTENT_TYPE

HTTP Header attribute specifying content type

CRLF
public static final String CRLF

CRLF

DEFAULT_CONTENT_TRANSFER_ENCODING
public static final String DEFAULT_CONTENT_TRANSFER_ENCODING
MIME_BOUNDARY
public static final String MIME_BOUNDARY

MIME boundary.

MIME_BOUNDARY_PREFIX
public static final String MIME_BOUNDARY_PREFIX

Prefix to be applied to separate different parts of MIME data.

SERIALIZABLE_OBJECT
public static final String SERIALIZABLE_OBJECT

HTTP content type specifying binary data, which is a serialized command object in MessageServiceHandler.

START
public static final String START

Content type start attribute.

TEXT_XML_TYPE
public static final String TEXT_XML_TYPE

HTTP content type specifying xml data.

TIME_ZONE
public static final String TIME_ZONE

Reference time zone.

Description

public class Description

A Description inside a Reference

Author:cyng

Fields

DESCRIPTION
static final String DESCRIPTION

Constructors

Description
Description(String description, String lang)

Methods

getDescription
public String getDescription()
getLang
public String getLang()

EbxmlMessage

public class EbxmlMessage

A representation of an ebXML message. An ebXML message conforms to the ` SOAP 1.1 with Attachments Specification <http://www.w3.org/TR/2000/NOTE-SOAP-attachments-20001211>`_. This EbxmlMessage encapsulates a javax.xml.soap.SOAPMessage.

Author:cyng

Fields

CHARACTER_SET_ENCODING
public static final String CHARACTER_SET_ENCODING

Default value XML character set

SOAP_ACTION
public static final String SOAP_ACTION

SOAPAction in the SOAP message MIME header

SOAP_ACTION_VALUE
public static final String SOAP_ACTION_VALUE

SOAPAction value in the SOAP message MIME header

SOAP_PART_CONTENT_ID
public static final String SOAP_PART_CONTENT_ID

Default content id of soap part

WRITE_XML_DECLARATION
public static final boolean WRITE_XML_DECLARATION

Default value of writing XML declaration in front of message

mimeBoundary
public static final String mimeBoundary

MIME boundary generated

needPatch
public static boolean needPatch

Description of the Field

Constructors

EbxmlMessage
public EbxmlMessage()

Constructs an EbxmlMessage using the default JAXM MessageFactory implementation

Throws:
  • SOAPException – Description of the Exception
EbxmlMessage
public EbxmlMessage(MessageFactory messageFactory)

Constructs an EbxmlMessage using the provided javax.xml.soap.MessageFactory

Parameters:
  • messageFactoryMessageFactory for creating message.
Throws:
  • SOAPException – Description of the Exception
EbxmlMessage
public EbxmlMessage(File file)

construct an EbxmlMessage from File using the logic in MessageServer. The file must not contain any content header like Content-Type

Parameters:
  • file – the file contain the messsage.
Throws:
  • SOAPException – Description of the Exception
  • IOException – Description of the Exception
EbxmlMessage
public EbxmlMessage(InputStream inputStream)

constructs an EbxmlMessage from InputStream using the logic in MessageServer. The input stream must not contain any content headers like Content-type.

Parameters:
  • inputStream – Description of the Parameter
Throws:
  • SOAPException – Description of the Exception
  • IOException – Description of the Exception
EbxmlMessage
public EbxmlMessage(SOAPMessage soapMessage)

Constructs an EbxmlMessage using the given SOAPMessage

Parameters:
  • soapMessage
Throws:
  • SOAPException – Description of the Exception
EbxmlMessage
public EbxmlMessage(MimeHeaders headers, InputStream in)

Constructs a EbxmlMessage using the given InputStream and default JAXM MessageFactory implementation

Parameters:
  • headers – MIME headers to be included in the message.
  • in – Message content in form of InputStream.
Throws:
  • IOException – Description of the Exception
  • SOAPException – Description of the Exception

Methods

addAckRequested
public void addAckRequested(boolean signed)

Add acknowledgement request element to the message.

Parameters:
  • signed – The feature to be added to the AckRequested attribute
Throws:
  • SOAPException
addAcknowledgment
public void addAcknowledgment(String timestamp, EbxmlMessage refToMessage)

Add acknowledgement element to the message using given timestamp, refToMessageId.

Parameters:
  • timestamp – Timestamp string expressed in UTC format.
  • refToMessage – The feature to be added to the Acknowledgment attribute
Throws:
  • SOAPException – Description of the Exception
addAcknowledgment
public void addAcknowledgment(String timestamp, EbxmlMessage refToMessage, String fromPartyId)

Add acknowledgement element to the message using given timestamp, refToMessageId and fromPartyId.

Parameters:
  • timestamp – Timestamp string expressed in UTC format.
  • fromPartyId – Sender party ID.
  • refToMessage – The feature to be added to the Acknowledgment attribute
Throws:
  • SOAPException – Description of the Exception
addAcknowledgment
public void addAcknowledgment(String timestamp, EbxmlMessage refToMessage, String fromPartyId, String fromPartyIdType)

Add acknowledgement element to the message using given timestamp, refToMessageId, fromPartyId and fromPartyIdType.

Parameters:
  • timestamp – Timestamp string expressed in UTC format.
  • fromPartyId – Sender party ID.
  • fromPartyIdType – Sender party ID type.
  • refToMessage – The feature to be added to the Acknowledgment attribute
Throws:
  • SOAPException – Description of the Exception
addErrorList
public void addErrorList(String errorCode, String severity, String description)

Add an error list to the message using given error code, severity and description.

Parameters:
  • errorCode – [ebMSS 4.2.3.4]
  • severity – Valid values are “Error” and “Warning”.
  • description – Description of the error.
Throws:
  • SOAPException – Description of the Exception
addErrorList
public void addErrorList(String errorCode, String severity, String description, String location)

Add an error list to the message using given error code, severity and description.

Parameters:
  • errorCode – [ebMSS 4.2.3.4]
  • severity – Valid values are “Error” and “Warning”.
  • description – Description of the error.
  • location – Location of the message containing the error.
Throws:
  • SOAPException
addMessageHeader
public MessageHeader addMessageHeader(String fromPartyId, String toPartyId, String cpaId, String conversationId, String service, String action, String messageId, String timestamp)

Adds a MessageHeader to this EbxmlMessage with the given mandatory fields

Parameters:
  • fromPartyId – Party ID of the sender [ebMSS 3.1.1.1]
  • toPartyId – Party ID of the receiver [ebMSS 3.1.1.1]
  • cpaId – CPA Id [ebMSS 3.1.2]
  • conversationId – ID of the conversation in which this message is involved [ebMSS 3.1.3]
  • service – Service name [ebMSS 3.1.4]
  • action – Action name [ebMSS 3.1.5]
  • messageId – Unique identifier of the message [ebMSS 3.1.6.1]
  • timestamp – Date/time of the message header creation expressed as UTC [ebMSS 3.1.6.2]
Throws:
  • SOAPException – Description of the Exception
Returns:

the newly added MessageHeader

addMessageHeader
public MessageHeader addMessageHeader(String fromPartyId, String fromPartyIdType, String toPartyId, String toPartyIdType, String cpaId, String conversationId, String service, String action, String messageId, String timestamp)

Adds a MessageHeader to this EbxmlMessage with the given mandatory fields

Parameters:
  • fromPartyId – Party ID of the sender [ebMSS 3.1.1.1]
  • fromPartyIdType – PartyID type of the sender [ebMSS 3.1.1.1]
  • toPartyId – Party ID of the receiver [ebMSS 3.1.1.1]
  • toPartyIdType – PartyID type of the receiver [ebMSS 3.1.1.1]
  • cpaId – CPA Id [ebMSS 3.1.2]
  • conversationId – ID of the conversation in which this message is involved [ebMSS 3.1.3]
  • service – Service name [ebMSS 3.1.4]
  • action – Action name [ebMSS 3.1.5]
  • messageId – Unique identifier of the message [ebMSS 3.1.6.1]
  • timestamp – Date/time of the message header creation expressed as UTC [ebMSS 3.1.6.2]
Throws:
  • SOAPException – Description of the Exception
Returns:

the newly added MessageHeader

addMessageHeader
public MessageHeader addMessageHeader()

Adds a default MessageHeader to this EbxmlMessage.

Throws:
  • SOAPException
Returns:

the newly added MessageHeader

addMessageOrder
public void addMessageOrder(int status, int sequenceNumber)

Add a MessageOrder element to the header.

Parameters:
  • status – Status of the sequence number. It should have the value of either MessageOrder.STATUS_RESET or MessageOrder.STATUS_CONTINUE.
  • sequenceNumber – Sequence number to be assigned to this message.
Throws:
  • SOAPException – Description of the Exception
addPayloadContainer
public PayloadContainer addPayloadContainer(DataHandler dataHandler, String contentId, String description)

Add an ebXML message payload container.

Parameters:
  • dataHandler – the DataHandler that generates the payload content.
  • contentId – the contentId of this payload attachment. The contentId must be unique among all payload attachment.
  • description – the description of this payload.
Throws:
  • SOAPException
Returns:

the PayloadContainer object that is created and added.

addStatusRequest
public void addStatusRequest(String refToMessageId)

Add a status request element to the message.

Parameters:
  • refToMessageId – Identifier of the message it is referring to.
Throws:
  • SOAPException
addStatusResponse
public void addStatusResponse(String refToMessageId, String messageStatus)

Add a status response element to the message.

Parameters:
  • refToMessageId – Identifier of the message it is referring to.
  • messageStatus – Status string to be added in the response element.
Throws:
  • SOAPException
addStatusResponse
public void addStatusResponse(String refToMessageId, String messageStatus, String timestamp)

Add a status response element to the message.

Parameters:
  • refToMessageId – Identifier of the message it is referring to.
  • messageStatus – Status string to be added in the response element.
  • timestamp – Timestamp of the status response expressed in UTC format.
Throws:
  • SOAPException
addSyncReply
public void addSyncReply()

Add a SyncReply element to the message.

Throws:
  • SOAPException
getAckRequested
public AckRequested getAckRequested()

Get acknowledgement request element.

Returns:AckRequested object representing the element.
getAcknowledgment
public Acknowledgment getAcknowledgment()

Get acknowledgement element.

Returns:Acknowledgement object representing the element.
getAction
public String getAction()

Gets action name

Returns:Action name
getBytes
public byte[] getBytes()
Returns:Returns the bytestream.
getConversationId
public String getConversationId()

Gets conversationId

Returns:Conversation ID
getCpaId
public String getCpaId()

Gets cpaId

Returns:CPA ID
getDatasource
public DataSource getDatasource()
Returns:Returns the datasource.
getDuplicateElimination
public boolean getDuplicateElimination()

Gets the flag stating if duplicate elimination is enabled or not.

Returns:true if duplicate elimination is required; false otherwise.
getErrorList
public ErrorList getErrorList()

Get the error list in the message.

Returns:ErrorList object containing error list in the message. Returns null if it does not exist.
getFileName
public String getFileName()

Gets the fileName attribute of the EbxmlMessage object. This function will only be used by the Hermes Server itself, and it is not expected for the client to call it.

Returns:The fileName value
getFromPartyIds
public Iterator getFromPartyIds()

Gets the list of from party IDs. There can be multiple party IDs [ebMSS 3.1.1].

Returns:Iterator pointing to a list of party IDs.
getHeaderContainer
public HeaderContainer getHeaderContainer()
Returns:Returns the headerContainer.
getManifest
public Manifest getManifest()

Gets the Manifest element in this ebXML message

Returns:Manifest element
getMessageFromDataSource
public static Object getMessageFromDataSource(DataSource dataSource, boolean withAttachments)
getMessageHeader
public MessageHeader getMessageHeader()

Get the message header of this ebXML message.

Returns:MessageHeader of this ebXML message.
getMessageId
public String getMessageId()

Gets messageId

Returns:Unique message identifier
getMessageOrder
public MessageOrder getMessageOrder()

Get the message order element in the message.

Returns:MessageOrder object if it exists in the ebXML message; null otherwise.
getMimeHeaders
public Map getMimeHeaders()

Gets the MIME headers of this ebXML message

Throws:
  • IOException – Description of the Exception
  • SOAPException – Description of the Exception
Returns:

the MIME headers of this ebXML message

getMimeHeaders
public Map getMimeHeaders(String soapEncoding, String payloadEncoding)

Gets the MIME headers of this ebXML message

Parameters:
  • soapEncoding – content transfer encoding to be applied to SOAP part when computing length
  • payloadEncoding – content transfer encoding to be applied to payload when computing length
Throws:
  • IOException – Description of the Exception
  • SOAPException – Description of the Exception
Returns:

the MIME headers of this ebXML message

getPayloadContainer
public PayloadContainer getPayloadContainer(String contentId)

Gets the payload that is identified by the given content ID.

Parameters:
  • contentId – Content ID of the payload to be retrieved.
Returns:

PayloadContainer of the given content ID or null if no such PayloadContainer exists

getPayloadContainers
public Iterator getPayloadContainers()

Gets all PayloadContainers’ attached in this EbxmlMessage object.

Returns:An iterator point to a list of payload containers.
getPayloadCount
public int getPayloadCount()

Gets the number of payloads in this ebXML message

Returns:the number of payloads
getPayloadInError
public String getPayloadInError()

Checks whether the number of payloads in the SOAP message matches with the Manifest element in the header or not, and return the Content-ID of the inconsistent payload.

Returns:content-id of the inconsistent payload; null if all payloads are consistent.
getPersistenceHandler
public Object getPersistenceHandler()

get the persistence handler if it is stored. This function will only be used by the Hermes Server itself, and it is not expected for the client to call it.

Returns:the persistence handler
getPersistenceName
public String getPersistenceName()

get the Persistence name if it is stored. This function will only be used by the Hermes Server itself, and it is not expected for the client to call it.

Returns:the persitence name
getSOAPMessage
public SOAPMessage getSOAPMessage()

Gets the SOAPMessage encapsulated in this EbxmlMessage.

Returns:SOAPMessage representing this EbxmlMessage
getService
public String getService()

Gets service name

Returns:Service name.
getServiceType
public String getServiceType()

Gets service type

Returns:Service type.
getSignatures
public Iterator getSignatures()

Get the digital signatures in the message.

Returns:Iterator of Signature objects in the message.
getSoapEnvelopeBytes
byte[] getSoapEnvelopeBytes()

Get the soap envelope in bytes. This function will only be used by the Hermes Server itself, and it is not expected for the client to call it.

getSoapEnvelopeBytesFromStream
public static byte[] getSoapEnvelopeBytesFromStream(InputStream stream)

parse the message from InputStream and get the byte array of SOAP Envelope

Parameters:
  • stream – the InputStream contains the message
Throws:
  • MessageServerException – throw if there is error on parsing
Returns:

the byte array of the Soap Envelope

getStatusRequest
public StatusRequest getStatusRequest()

Get the status request element in the message.

Returns:Content of the status request element stored in StatusRequest object.
getStatusResponse
public StatusResponse getStatusResponse()

Get the status response element in the message.

Returns:Content of the status response element stored in StatusResponse object.
getSyncReply
public boolean getSyncReply()

Gets the flag stating if sync reply is enabled or not.

Returns:true if sync reply is enabled; false otherwise.
getTimeToLive
public String getTimeToLive()

Gets TimeToLive of the message

Returns:TimeToLive expressed in UTC format.
getTimestamp
public String getTimestamp()

Gets timestamp

Returns:Timestamp of the message expressed in UTC format.
getToPartyIds
public Iterator getToPartyIds()

Gets the list of to party IDs. There can be multiple party IDs [ebMSS 3.1.1].

Returns:Iterator pointing to a list of party IDs.
saveChanges
public void saveChanges()

Updates the encapsulated SOAPMessage with all changes that have been made to it.

Throws:
  • SOAPException

See also: javax.xml.soap.SOAPMessage.saveChanges()

saveRequired
public boolean saveRequired()

Indicates whether the encapsulated SOAPMessage need to be updated by calling saveChanges on it.

Returns:true if it is required to call saveChanges on the message; false otherwise.

See also: javax.xml.soap.SOAPMessage.saveRequired()

setBytes
public void setBytes(byte[] bytes)
Parameters:
  • bytes – The bytestream to set.
setFileName
public void setFileName(String filename)

Sets the fileName attribute of the EbxmlMessage object. This function will only be used by the Hermes Server itself, and it is not expected for the client to call it.

Parameters:
  • filename – The new fileName value
setPayloadContainers
public ArrayList setPayloadContainers(ArrayList payloads)

Sets the PayloadContainer

Parameters:
  • payloads – The new payloadContainers value
Returns:

The old payload container as an array list

setPersistenceInfo
public void setPersistenceInfo(String persistenceName, Object handler, DataSource datasource)

set the persistence info to the message This function will only be used by the Hermes Server itself, and it is not expected for the client to call it.

Parameters:
  • persistenceName – the name on the persistence handler
  • handler – the persistence handler
setSoapEnvelopeBytes
public void setSoapEnvelopeBytes(byte[] soapEnvelopeBytes)

set the soap envelope in bytes. Those bytes will be used to verify This function will only be used by the Hermes Server itself, and it is not expected for the client to call it. the signature.

writeTo
public void writeTo(OutputStream out)

Writes the encapsulated SOAPMessage to the given output stream. The externalization format is as defined by the SOAP 1.1 with Attachments Specification.

Parameters:
  • outOutputStream to write the message to.
Throws:
  • IOException – Description of the Exception
  • SOAPException – Description of the Exception
writeTo
public void writeTo(OutputStream out, String soapEncoding, String payloadEncoding)

Writes the encapsulated SOAPMessage to the given output stream. The externalization format is as defined by the SOAP 1.1 with Attachments Specification.

Parameters:
  • outOutputStream to write the message to.
  • soapEncoding – Description of the Parameter
  • payloadEncoding – Description of the Parameter
Throws:
  • IOException – Description of the Exception
  • SOAPException – Description of the Exception

EbxmlMessageFactory

public class EbxmlMessageFactory extends MessageFactory

Implementation of javax.xml.soap.MessageFactory

Author:cyng

Constructors

EbxmlMessageFactory
public EbxmlMessageFactory()

Initializes EbxmlMessageFactory object.

Methods

createEbxmlMessage
public EbxmlMessage createEbxmlMessage()

Create a simple ebXML message.

Throws:
  • SOAPException
Returns:

A new ebXML message.

createEbxmlMessage
public EbxmlMessage createEbxmlMessage(MimeHeaders headers, InputStream in)

Create an ebXML message with given MIME headers and content in form of input stream.

Parameters:
  • headers – MIME headers to be used in the new message.
  • in – Content of ebXML message in the form of input stream.
Throws:
  • IOException
  • SOAPException
Returns:

EbxmlMessage created.

createMessage
public SOAPMessage createMessage()

Creates a simple ebXML SOAP message.

Throws:
  • SOAPException
Returns:

SOAPMessage of the ebXML message created.

createMessage
public SOAPMessage createMessage(MimeHeaders headers, InputStream in)

Creates an ebXML SOAP message using given MIME headers and content in form of input stream.

Parameters:
  • headers – MIME headers to be used in the new message.
  • in – Content of ebXML message in the form of input stream.
Throws:
  • IOException
  • SOAPException
Returns:

SOAPMessage of the ebXML message created.

Element

interface Element

Encapsulation of a javax.xml.soap.SOAPElement

Author:cyng

Methods

addAttribute
Element addAttribute(Name name, String value)

Add an attribute of the given name and value to this Element

Parameters:
  • name – the attribute name in javax.xml.soap.Name representation
  • value – the attribute value
Returns:

this Element to which the attribute is added

addChildElement
Element addChildElement(Element child)

Add a child element to this Element

Parameters:
  • child – the child Element
Returns:

the newly added child Element

getAllAttributes
Iterator getAllAttributes()

Get all attributes of this Element. Each Iterator entry is in the form of Map.Entry representing a (javax.xml.soap.Name name, String value) pair.

getAttributeValue
String getAttributeValue(Name name)

Get the attribute value of the specified attribute name

getChildElements
Iterator getChildElements(Name name)

Get all descendant child elements of the specified javax.xml.soap.Name, in the order in which they are encountered in a preorder traversal of this Element tree. Each Iterator entry is in the form of an javax.xml.soap.SOAPElement.

getChildElements
Iterator getChildElements()

Get all immediate child elements in the form of an javax.xml.soap.SOAPElement in each Iterator entry

getElementName
Name getElementName()

Get the element name of this Element

getSOAPElement
SOAPElement getSOAPElement()

Return the javax.xml.soap.SOAPElement representation of this Element

getValue
String getValue()

Get the text node value of this Element. Returns null if it does not exist.

ErrorList

public class ErrorList extends HeaderElement

An ebXML ErrorList in the SOAP Header of a HeaderContainer

Author:cyng

Fields

ATTRIBUTE_CODE_CONTEXT
static final String ATTRIBUTE_CODE_CONTEXT

Name of the codeContext attribute [ebMSS 4.2.3.2.2].

ATTRIBUTE_ERROR_CODE
static final String ATTRIBUTE_ERROR_CODE

Name of the errorCode attribute [ebMSS 4.2.3.2.3].

ATTRIBUTE_HIGHEST_SEVERITY
static final String ATTRIBUTE_HIGHEST_SEVERITY

Name of highestSeverity attribute [ebMSS 4.2.3.1].

ATTRIBUTE_LOCATION
static final String ATTRIBUTE_LOCATION

Name of the location attribute [ebMSS 4.2.3.2.5].

ATTRIBUTE_SEVERITY
static final String ATTRIBUTE_SEVERITY

Name of the severity attribute [ebMSS 4.2.3.2.4].

CODE_DELIVERY_FAILURE
public static final String CODE_DELIVERY_FAILURE

Non-XML document error: message delivery failure [4.2.3.4.2].

CODE_INCONSISTENT
public static final String CODE_INCONSISTENT

Document error: element content or attribute value inconsistent with other elements or attributes [4.2.3.4.1].

CODE_MIME_PROBLEM
public static final String CODE_MIME_PROBLEM

Non-XML document error: URI resolve error.

CODE_NOT_SUPPORTED
public static final String CODE_NOT_SUPPORTED

Document error: element or attribute not supported [4.2.3.4.1].

CODE_OTHER_XML
public static final String CODE_OTHER_XML

Document error: other error in an element content or attribute value [4.2.3.4.1].

CODE_SECURITY_FAILURE
public static final String CODE_SECURITY_FAILURE

Non-XML document error: message security check failed [4.2.3.4.2].

CODE_TIME_TO_LIVE_EXPIRED
public static final String CODE_TIME_TO_LIVE_EXPIRED

Non-XML document error: message time to live expired [4.2.3.4.2].

CODE_UNKNOWN
public static final String CODE_UNKNOWN

Non-XML document error: Unknown error.

CODE_VALUE_NOT_RECOGNIZED
public static final String CODE_VALUE_NOT_RECOGNIZED

Document error: element content or attribute value not recognized [4.2.3.4.1].

ELEMENT_ERROR
static final String ELEMENT_ERROR

Error element name in ErrorList [ebMSS 4.2.3.2].

ERROR_LIST
static final String ERROR_LIST

ErrorList element name

SEVERITY_ERROR
public static final String SEVERITY_ERROR

Text for “Error” severity level.

SEVERITY_WARNING
public static final String SEVERITY_WARNING

Text for “Warning” severity level.

Constructors

ErrorList
ErrorList(SOAPEnvelope soapEnvelope, String errorCode, String severity, String description)

Constructs an ErrorList with the given mandatory fields.

Parameters:
  • soapEnvelopeSOAPEnvelope, the header of which the ErrorList is added.
  • errorCode – Error code value of the error.
  • severity – Severity of the error.
  • description – Description of the error.
Throws:
  • SOAPException
ErrorList
ErrorList(SOAPEnvelope soapEnvelope, String errorCode, String severity, String description, String lang)

Constructs an ErrorList with the given mandatory fields.

Parameters:
  • soapEnvelopeSOAPEnvelope, the header of which the ErrorList is added.
  • errorCode – Error code value of the error.
  • severity – Severity of the error.
  • description – Description of the error.
  • lang – Language of the description specified in ` RFC 1766 <http://www.ietf.org/rfc/rfc1766.txt>`_ and ISO639.
Throws:
  • SOAPException
ErrorList
ErrorList(SOAPEnvelope soapEnvelope, String errorCode, String severity, String description, String lang, String location)

Constructs an ErrorList with the given mandatory fields.

Parameters:
  • soapEnvelopeSOAPEnvelope, the header of which the ErrorList is added.
  • errorCode – Error code value of the error.
  • severity – Severity of the error.
  • description – Description of the error.
  • lang – Language of the description specified in ` RFC 1766 <http://www.ietf.org/rfc/rfc1766.txt>`_ and ISO639.
Throws:
  • SOAPException
ErrorList
ErrorList(SOAPEnvelope soapEnvelope, SOAPElement soapElement)

Constructs an ErrorList object by parsing the given SOAPElement object.

Parameters:
  • soapEnvelopeSOAPEnvelope, the header of which the ErrorList is added.
  • soapElementSOAPElement object to be read into the ErrorList object.
Throws:
  • SOAPException

Methods

addError
public void addError(String errorCode, String severity, String description)

Add an element to the error list.

Parameters:
  • errorCode – Error code value.
  • severity – Severity of the error.
  • description – Description of the error.
Throws:
  • SOAPException
addError
public void addError(String errorCode, String severity, String description, String lang)

Add an element to the error list.

Parameters:
  • errorCode – Error code value.
  • severity – Severity of the error.
  • description – Description of the error.
  • lang – Language of the description specified in ` RFC 1766 <http://www.ietf.org/rfc/rfc1766.txt>`_ and ISO639.
Throws:
  • SOAPException
addError
public void addError(String errorCode, String severity, String description, String lang, String location)

Add an element to the error list.

Parameters:
  • errorCode – Error code value.
  • severity – Severity of the error.
  • description – Description of the error.
  • lang – Language of the description specified in ` RFC 1766 <http://www.ietf.org/rfc/rfc1766.txt>`_ and ISO639.
  • location – Location of the message containing error.
Throws:
  • SOAPException
getErrors
public Iterator getErrors()

Gets all ErrorList.Errors in this ErrorList

getHighestSeverity
public String getHighestSeverity()

Get the highest severity of all the ErrorList.Error objects in the ErrorList.

Returns:Highest severity of the errors.

ErrorList.Error

public static final class Error

An Error inside an ErrorList

Constructors

Error
Error(String errorCode, String severity, Description description)

Initializes Error object using given error code, severity and description.

Parameters:
  • errorCode – Error code value. Please refer to [ebMSS 4.2.3.4.1] for a list of valid error codes.
  • severity – Severity of the error reported.
  • description – Human-readable description of error.
Error
Error(String errorCode, String severity, Description description, String location)

Initializes Error object using given error code, severity and description.

Parameters:
  • errorCode – Error code value. Please refer to [ebMSS 4.2.3.4.1] for a list of valid error codes.
  • severity – Severity of the error reported.
  • description – Human-readable description of error.
  • location – Location of the message containing the error.

Methods

getDescription
public Description getDescription()

Get the description contained in the object.

Returns:Description of the error.
getErrorCode
public String getErrorCode()

Get the error code contained in the object.

Returns:Error code.
getLocation
public String getLocation()

Get the location of the message containing the error.

Returns:Location string.
getSeverity
public String getSeverity()

Get the severity level contained in the object.

Returns:Severity level.

ExtensionElement

interface ExtensionElement extends Element

An ExtensionElement in the HeaderContainer

Author:cyng

Fields

ATTRIBUTE_ID
static final String ATTRIBUTE_ID

Name of the ID attribute.

ATTRIBUTE_LANG
static final String ATTRIBUTE_LANG

Name of the language attribute.

ATTRIBUTE_SCHEMA_LOCATION
static final String ATTRIBUTE_SCHEMA_LOCATION

Name of the Schema location attribute

ATTRIBUTE_VERSION
static final String ATTRIBUTE_VERSION

Name of the version attribute.

LANG_TYPE
static final String LANG_TYPE

Default language type of the MSH.

NAMESPACE_PREFIX_EB
static final String NAMESPACE_PREFIX_EB

Namespace prefix of ExtensionElement.

NAMESPACE_PREFIX_SOAP_ENVELOPE
static final String NAMESPACE_PREFIX_SOAP_ENVELOPE

Namespace prefix of SOAP envelope.

NAMESPACE_PREFIX_XML
static final String NAMESPACE_PREFIX_XML

Namespace prefix of XML.

NAMESPACE_PREFIX_XSI
static final String NAMESPACE_PREFIX_XSI

Namespace prefix of XML Schema Instance

NAMESPACE_URI_EB
static final String NAMESPACE_URI_EB

Namespace URI of ExtensionElement.

NAMESPACE_URI_SOAP_ENVELOPE
static final String NAMESPACE_URI_SOAP_ENVELOPE

Namespace URI of SOAP envelope.

NAMESPACE_URI_XML
static final String NAMESPACE_URI_XML

Namespace URI of XML.

NAMESPACE_URI_XSI
static final String NAMESPACE_URI_XSI

Namespace URI of XML Schema Instance

SCHEMA_LOCATION_SOAP_BODY
static final String SCHEMA_LOCATION_SOAP_BODY

URI of SOAP SOAP body schema location

SCHEMA_LOCATION_SOAP_ENVELOPE
static final String SCHEMA_LOCATION_SOAP_ENVELOPE

URI of SOAP envelope schema location

SCHEMA_LOCATION_SOAP_HEADER
static final String SCHEMA_LOCATION_SOAP_HEADER

URI of SOAP header schema location

VERSION
static final String VERSION

Version of ebXML Messaging Service.

XML_NS_DECL_PREFIX
static final String XML_NS_DECL_PREFIX

Attribute prefix for XML namespace declarations.

XML_NS_SEPARATOR
static final char XML_NS_SEPARATOR

Character that separates the namespace prefix and local name in an XML tag.

Methods

addAttribute
ExtensionElement addAttribute(String localName, String value)

Add an attribute whose namespace is the same as this ExtensionElement.

addAttribute
ExtensionElement addAttribute(String localName, String prefix, String uri, String value)

Add a namespace qualified attribute.

addChildElement
ExtensionElement addChildElement(String localName)

Add a child element without text node value and whose namespace is the same as this ExtensionElement, i.e., the parent.

addChildElement
ExtensionElement addChildElement(String localName, String value)

Add a child element with the specified value and whose namespace is the same as this ExtensionElement, i.e., the parent.

addChildElement
ExtensionElement addChildElement(String localName, String prefix, String uri)

Add a child element without text node value and with the specified namespace.

addChildElement
ExtensionElement addChildElement(String localName, String prefix, String uri, String value)

Add a child element with the specified value and namespace.

getAttributeValue
String getAttributeValue(String localName)

Get an attribute whose namespace is the same as this ExtensionElement.

getAttributeValue
String getAttributeValue(String localName, String prefix, String uri)

Get an attribute with the specified prefix and namespace

getChildElements
Iterator getChildElements(String localName)

Get all descendant child elements of the specified localName whose namespace is the same as this ExtensionElement, in the order in which they are encountered in a preorder traversal of this ExtensionElement tree. Each Iterator entry is in the form of an javax.xml.soap.SOAPElement.

ExtensionElementImpl

class ExtensionElementImpl implements ExtensionElement

An implementation of ExtensionElement.

Author:cyng

Fields

soapEnvelope
protected final SOAPEnvelope soapEnvelope

The javax.xml.soap.SOAPEnvelope encapsulating this ExtensionElement

Constructors

ExtensionElementImpl
ExtensionElementImpl(SOAPEnvelope soapEnvelope, SOAPElement soapElement)

Construct an ExtensionElement using the given SOAPEnvelope and SOAPElement

ExtensionElementImpl
ExtensionElementImpl(SOAPEnvelope soapEnvelope, String localName, boolean isHeaderElement)

Construct an ExtensionElement using the given SOAPEnvelope and whose namespace and URI are equal to that of SOAP extension element as defined in ebXML Messaging Service Specification

ExtensionElementImpl
ExtensionElementImpl(SOAPEnvelope soapEnvelope, String localName, String prefix, String uri, boolean isHeaderElement, boolean createSOAPElement)

Construct an ExtensionElement using the given SOAPEnvelope and the specified namespace and URI. Change the default namespace and URI of this ExtensionElement to the new one so that subsequent added children elements will inherit the new namespace and URI.

Methods

addAttribute
public ExtensionElement addAttribute(String localName, String value)

Add an attribute whose namespace is the same as this ExtensionElement

addAttribute
public ExtensionElement addAttribute(String localName, String prefix, String uri, String value)

Add a namespace qualified attribute

addAttribute
public Element addAttribute(Name name, String value)

Add an attribute of the given name and value to this Element. If the namespace is found to be non-null, non-empty and different from the current Element, the namespace is declared.

addChildElement
public ExtensionElement addChildElement(String localName)

Add a child element without text node value and whose namespace is the same as this ExtensionElement, i.e., the parent

addChildElement
public ExtensionElement addChildElement(String localName, String value)

Add a child element with the specified value and whose namespace is the same as this ExtensionElement, i.e., the parent

addChildElement
public ExtensionElement addChildElement(String localName, String prefix, String uri)

Add a child element without text node value and with the specified namespace

addChildElement
public ExtensionElement addChildElement(String localName, String prefix, String uri, String value)

Add a child element with the specified value and namespace. Change the default namespace and URI of this ExtensionElement to the new one so that subsequent added children elements will inherit the new namespace and URI.

addChildElement
public Element addChildElement(Element child)

Add a child element to this Element

getAllAttributes
public Iterator getAllAttributes()

Get all attributes of this Element. Each Iterator entry is in the form of Map.Entry representing a (javax.xml.soap.Name name, String value) pair.

getAttributeValue
public String getAttributeValue(String localName)

Get an attribute whose namespace is the same as this ExtensionElement

getAttributeValue
public String getAttributeValue(String localName, String prefix, String uri)

Get an attribute with the specified prefix and namespace

getAttributeValue
public String getAttributeValue(Name name)

Get the attribute value of the specified attribute name

getChildElements
public Iterator getChildElements(String localName)

Get all descendant child elements of the specified localName whose namespace is the same as this ExtensionElement, in the order in which they are encountered in a preorder traversal of this ExtensionElement tree. Each Iterator entry is in the form of an javax.xml.soap.SOAPElement.

getChildElements
public Iterator getChildElements(Name name)

Get all descendant child elements of the specified javax.xml.soap.Name, in the order in which they are encountered in a preorder traversal of this Element tree. Each Iterator entry is in the form of an javax.xml.soap.SOAPElement.

getChildElements
public Iterator getChildElements()

Get all immediate child elements in the form of an javax.xml.soap.SOAPElement in each Iterator entry

getElementName
public Name getElementName()

Get the element name of this Element

getSOAPElement
public SOAPElement getSOAPElement()

Return the javax.xml.soap.SOAPElement representation of this Element

getValue
public String getValue()

Get the text node value of this Element. Returns null if it does not exist.

HeaderContainer

class HeaderContainer

An encapsulation of the Header Container of an EbxmlMessage.

Author:cyng

Constructors

HeaderContainer
HeaderContainer(SOAPPart soapPart)

Creates a HeaderContainer using the specified SOAPPart

Methods

addExtensionElement
void addExtensionElement(ExtensionElement extensionElement)

Add an ExtensionElement, e.g. MessageHeader (a HeaderElement) or Manifest (a BodyElement), to this HeaderContainer

getAckRequested
AckRequested getAckRequested()
getAcknowledgment
Acknowledgment getAcknowledgment()
getErrorList
ErrorList getErrorList()
getManifest
Manifest getManifest()
getMessageHeader
MessageHeader getMessageHeader()
getMessageOrder
MessageOrder getMessageOrder()
getSignatures
Iterator getSignatures()
getStatusRequest
StatusRequest getStatusRequest()
getStatusResponse
StatusResponse getStatusResponse()
getSyncReply
SyncReply getSyncReply()

HeaderElement

class HeaderElement extends ExtensionElementImpl

An ExtensionElement in the SOAP Header of a HeaderContainer

Author:cyng

Fields

ACTOR_NEXT_MSH_SCHEMAS
static final String ACTOR_NEXT_MSH_SCHEMAS
ACTOR_NEXT_MSH_URN
static final String ACTOR_NEXT_MSH_URN
ACTOR_TO_PARTY_MSH_URN
static final String ACTOR_TO_PARTY_MSH_URN
ATTRIBUTE_ACTOR
static final String ATTRIBUTE_ACTOR
ATTRIBUTE_MUST_UNDERSTAND
static final String ATTRIBUTE_MUST_UNDERSTAND
MUST_UNDERSTAND
static final boolean MUST_UNDERSTAND

Constructors

HeaderElement
HeaderElement(SOAPEnvelope soapEnvelope, SOAPElement soapElement)
HeaderElement
HeaderElement(SOAPEnvelope soapEnvelope, String localName)
HeaderElement
HeaderElement(SOAPEnvelope soapEnvelope, String localName, String prefix, String uri)

Methods

getActor
public String getActor()
setActor
void setActor(String actor)

Manifest

public class Manifest extends BodyElement

An ebXML Manifest in the SOAP Body of a HeaderContainer

Author:cyng

Fields

MANIFEST
static final String MANIFEST

Manifest element name

Constructors

Manifest
Manifest(SOAPEnvelope soapEnvelope)

Constructs a Manifest

Manifest
Manifest(SOAPEnvelope soapEnvelope, SOAPElement soapElement)

Methods

addReference
public Reference addReference(String id, String href)
getReferences
public Iterator getReferences()

MessageHeader

public class MessageHeader extends HeaderElement

An ebXML MessageHeader in the SOAP Header of a HeaderContainer

Author:cyng

Fields

ATTRIBUTE_TYPE
static final String ATTRIBUTE_TYPE

MessageHeader Type attribute name

ELEMENT_ACTION
static final String ELEMENT_ACTION

MessageHeader Action element name

ELEMENT_CONVERSATION_ID
static final String ELEMENT_CONVERSATION_ID

MessageHeader ConversationID element name

ELEMENT_CPA_ID
static final String ELEMENT_CPA_ID

MessageHeader CPAID element name

ELEMENT_DUPLICATE_ELIMINATION
static final String ELEMENT_DUPLICATE_ELIMINATION

MessageHeader DuplicateElimination element name

ELEMENT_FROM
static final String ELEMENT_FROM

MessageHeader From element name

ELEMENT_MESSAGE_DATA
static final String ELEMENT_MESSAGE_DATA

MessageHeader MessageData element name

ELEMENT_MESSAGE_ID
static final String ELEMENT_MESSAGE_ID

MessageHeader MessageId element name

ELEMENT_PARTY_ID
static final String ELEMENT_PARTY_ID

MessageHeader PartyID element name

ELEMENT_REF_TO_MESSAGE_ID
static final String ELEMENT_REF_TO_MESSAGE_ID

MessageHeader RefToMessageID element name

ELEMENT_ROLE
static final String ELEMENT_ROLE

MessageHeader Role element name

ELEMENT_SERVICE
static final String ELEMENT_SERVICE

MessageHeader Service element name

ELEMENT_TIMESTAMP
static final String ELEMENT_TIMESTAMP

MessageHeader Timestamp element name

ELEMENT_TIME_TO_LIVE
static final String ELEMENT_TIME_TO_LIVE

MessageHeader TimeToLive element name

ELEMENT_TO
static final String ELEMENT_TO

MessageHeader To element name

MESSAGE_HEADER
static final String MESSAGE_HEADER

MessageHeader element name

TIME_ZONE
static final String TIME_ZONE

Standard time zone used in Message Service Handler

Constructors

MessageHeader
MessageHeader(SOAPEnvelope soapEnvelope)

Initializes data structures in MessageHeader object using the given SOAPEnvelope.

Parameters:
  • soapEnvelopeSOAPEnvelope into which the MessageHeader is added.
Throws:
  • SOAPException
MessageHeader
MessageHeader(SOAPEnvelope soapEnvelope, String fromPartyId, String fromPartyIdType, String toPartyId, String toPartyIdType, String cpaId, String conversationId, String service, String action, String messageId, String timestamp)

Constructs a MessageHeader with the given mandatory fields. No further modification on the fields specified are allowed.

Parameters:
  • soapEnvelopeSOAPEnvelope into which the MessageHeader is added.
  • fromPartyId – PartyID of the sender.
  • fromPartyIdType – PartyID type of the sender.
  • toPartyId – PartyID of the recipient.
  • toPartyIdType – PartyID type of the recipient.
  • cpaId – CPA ID.
  • conversationId – Conversation ID of the message.
  • service – Service name.
  • action – Action name.
  • messageId – Unique message identifier.
  • timestamp – Timestamp of the message header creation.
Throws:
  • SOAPException
MessageHeader
MessageHeader(SOAPEnvelope soapEnvelope, SOAPElement soapElement)

Constructs a MessageHeader with the given SOAPEnvelope and SOAPElement.

Parameters:
  • soapEnvelopeSOAPEnvelope into which the MessageHeader is added.
  • soapElementSOAPElement to be parsed and stored in the MessageHeader.
Throws:
  • SOAPException

Methods

addDescription
public void addDescription(String description)

Add element with default xml:lang

Parameters:
  • description – Description to be added to MessageHeader
Throws:
  • SOAPException
addDescription
public void addDescription(String description, String lang)

Add element with specified xml:lang. This method can be called repeatedly to add several descriptions to the MessageHeader

Parameters:
Throws:
  • SOAPException
addFromPartyId
public void addFromPartyId(String id)

Add sender’s PartyID into MessageHeader

Parameters:
  • id – Sender’s PartyID string.
Throws:
  • SOAPException
addFromPartyId
public void addFromPartyId(String id, String type)

Add sender’s PartyID and its type into MessageHeader

Parameters:
  • id – Sender’s PartyID string.
  • type – PartyID type.
Throws:
  • SOAPException
addToPartyId
public void addToPartyId(String id)

Add recipient’s PartyID into MessageHeader

Parameters:
  • id – Recipient’s PartyID string.
Throws:
  • SOAPException
addToPartyId
public void addToPartyId(String id, String type)

Add recipient’s PartyID and its type into MessageHeader

Parameters:
  • id – Recipient’s PartyID string.
  • type – PartyID type.
Throws:
  • SOAPException
getAction
public String getAction()

Get action name.

Returns:Action name.
getConversationId
public String getConversationId()

Get conversationId

Returns:Conversation ID of the message.
getCpaId
public String getCpaId()

Get cpaId.

Returns:Collaborative Protocol Agreement ID.
getDescriptionCount
public int getDescriptionCount()

Gets the number of Description elements in this MessageHeader.

Returns:The number of Description elements.
getDescriptions
public Iterator getDescriptions()

Get all Description elements in this MessageHeader.

Returns:an Iterator of Descriptions’.
getDuplicateElimination
public boolean getDuplicateElimination()

Get current setting of duplication elimination.

Returns:true if duplicate elimination is enabled; false otherwise.
getFrom
ExtensionElement getFrom()

Get From core extension element.

Returns:From extension element object.
getFromPartyIds
public Iterator getFromPartyIds()

Get Sender’s PartyId in header. It can have one or more occurrences.

Returns:Iterator pointing to a list of senders’ Party IDs.
getFromRole
public String getFromRole()

Get Role element in the From core extension element.

Returns:Role name.
getMessageData
ExtensionElement getMessageData()

Get MessageData core extension element.

Returns:MessageData ExtensionElement
getMessageId
public String getMessageId()

Get messageId.

Returns:Unique message identifier.
getRefToMessageId
public String getRefToMessageId()

Get the unique identifier of the message this message refers to.

Returns:ID of the message being referred to.
getService
public String getService()

Get service name

Returns:Service name.
getServiceType
public String getServiceType()

Get the service type string.

Returns:Service type string.
getTimeToLive
public String getTimeToLive()

Get TimeToLive

Returns:TimeToLive expressed in UTC format.
getTimestamp
public String getTimestamp()

Get header creation timestamp expressed in UTC format.

Returns:Timestamp expressed in UTC format.
getTo
ExtensionElement getTo()

Get To core extension element.

Returns:To extension element object.
getToPartyIds
public Iterator getToPartyIds()

Get recipient’s PartyId in header. It can have one or more occurrences.

Returns:Iterator pointing to a list of recipients’ Party IDs.
getToRole
public String getToRole()

Get Role element in the To core extension element.

Returns:Role name.
setAction
public void setAction(String action)

Set action name. This property can be set only once.

Parameters:
  • action – Action name.
Throws:
  • SOAPException
setConversationId
public void setConversationId(String conversationId)

Set conversationId. This property can be set only once.

Parameters:
  • conversationId – Conversation ID of the message.
Throws:
  • SOAPException
setCpaId
public void setCpaId(String cpaId)

Set cpaId of the message header. This property can be set only once.

Parameters:
  • cpaId – Collaborative Protocol Agreement ID.
Throws:
  • SOAPException
setDuplicateElimination
public void setDuplicateElimination()

Enable duplication elimination function. This property can be set only once.

Throws:
  • SOAPException
setFromRole
public void setFromRole(String role)

Set Role element in the From core extension element.

Parameters:
  • role – Role name.
Throws:
  • SOAPException
setMessageId
public void setMessageId(String messageId)

Set messageId. This property can be set only once.

Parameters:
  • messageId – Unique message identifier.
Throws:
  • SOAPException
setRefToMessageId
public void setRefToMessageId(String messageId)

Set optional “RefToMessageId” element. This property can be set only once.

Parameters:
  • messageId – Message ID to be set in the current message header.
Throws:
  • SOAPException
setService
public void setService(String serviceName)

Set service name. This property can be set only once.

Parameters:
  • serviceName – Service name.
Throws:
  • SOAPException
setService
public void setService(String serviceName, String serviceType)

Set service. This property can be set only once.

Parameters:
  • serviceName – Service name.
  • serviceType – Service type string.
Throws:
  • SOAPException
setServiceType
public void setServiceType(String type)

Set optional “type” attribute in service element

Throws:
  • SOAPException
setTimeToLive
public void setTimeToLive(String time)

Set optional “TimeToLive” element. This property can be set only once.

Parameters:
  • time – TimeToLive expressed in UTC format.
Throws:
  • SOAPException
setTimeToLive
public void setTimeToLive(Date time)

Convert local date/time to UTC string and set TimeToLive value. This property can be set only once.

Parameters:
  • time – Local date/time to be converted to UTC format and set as TimeToLive value.
Throws:
  • SOAPException
setTimestamp
public void setTimestamp(String timestamp)

Set timestamp.

Parameters:
  • timestamp – Header creation timestamp expressed in UTC format.
Throws:
  • SOAPException
setToRole
public void setToRole(String role)

Set Role element in the To core extension element.

Parameters:
  • role – Role name.
Throws:
  • SOAPException

MessageHeader.PartyId

public static final class PartyId

A PartyId inside From or To

Constructors

PartyId
PartyId(String id, String type)

Initializes PartyId object

Methods

getId
public String getId()

Gets party ID.

Returns:Party ID stored in this object.
getType
public String getType()

Gets value of the “type” attribute .

Returns:Value of the “type” attribute.

MessageHeader.Service

public static final class Service

A class representing service element in the MessageHeader

Constructors

Service
Service(String service, String type)

Initializes service object from given service name and type

Methods

getService
public String getService()

Gets service name.

Returns:Service name.
getType
public String getType()

Gets service type.

Returns:Service type.
setType
void setType(String type)

Sets service type.

Parameters:
  • type – Service type string.

MessageOrder

public class MessageOrder extends HeaderElement

An ebXML MessageOrder in the SOAP Header of a HeaderContainer [ebMSS 9.1].

Author:tslam

Fields

ATTRIBUTE_STATUS
static final String ATTRIBUTE_STATUS

Name of the status attribute

ELEMENT_SEQUENCE_NUMBER
static final String ELEMENT_SEQUENCE_NUMBER

SequenceNumber element name

MESSAGE_ORDER
static final String MESSAGE_ORDER

MessageOrder element name

STATUS_CONTINUE
public static final int STATUS_CONTINUE

Subsequent messages in the conversation and the sequence number is not reset.

STATUS_RESET
public static final int STATUS_RESET

First mesage in conversation / reset the sequence number counter.

VALUE_STATUS_CONTINUE
static final String VALUE_STATUS_CONTINUE

Name of the “Continue” status

VALUE_STATUS_RESET
static final String VALUE_STATUS_RESET

Name of the “Reset” status

Constructors

MessageOrder
MessageOrder(SOAPEnvelope soapEnvelope, int status, int sequenceNo)

Constructs a MessageOrder with the given mandatory fields.

Parameters:
  • soapEnvelopeSOAPEnvelope, the header container of which the MessageOrder is attached to.
  • status – Status of the sequence number.
  • sequenceNo – The sequence number in the converstaion.
Throws:
  • SOAPException
MessageOrder
MessageOrder(SOAPEnvelope soapEnvelope, SOAPElement soapElement)

Constructs an MessageOrder object by parsing the given SOAPElement.

Parameters:
  • soapEnvelopeSOAPEnvelope, the header container of which the MessageOrder is attached to.
  • soapElementSOAPElement containing SequenceNumber element.
Throws:
  • SOAPException

Methods

getSequenceNumber
public int getSequenceNumber()

Get the sequence number in the conversation. Note that although the word “conversation” is used in the specification, the sequence number is set and incremented by one party only. It means that both parties need to keep their own sequence numbers for all outgoing messages.

Returns:sequence number.
getStatus
public int getStatus()

Get the status of the sequence number which can be “Reset” or “Continue”.

Returns:Status of the sequence number.

PKISignatureImpl

class PKISignatureImpl extends Signature

An implementation of ebXML Signature, making use of Phoenix’s PKI library.

Author:kcyee

Fields

logger
static Logger logger

Constructors

PKISignatureImpl
PKISignatureImpl(EbxmlMessage ebxmlMessage)
PKISignatureImpl
PKISignatureImpl(EbxmlMessage ebxmlMessage, SOAPEnvelope soapEnvelope, SOAPElement soapElement)

Methods

addReference
void addReference(String uri)
sign
void sign(String alias, char[] password, String keyStoreLocation)
sign
void sign(String alias, char[] password, String keyStoreLocation, String algo)
sign
void sign(String alias, char[] password, String keyStoreLocation, String algo, String digestAlgo, boolean signEnvelopeOnly)
sign
void sign(String alias, char[] password)
sign
void sign(String alias, char[] password, String keyStoreLocation, String type, String provider)
sign
void sign(PrivateKey privateKey, X509Certificate[] certificates)
verify
boolean verify(char[] password, String keyStoreLocation, CertResolver certResolver, DataSource dataSource)
verify
boolean verify(Element documentElement, PublicKey key)
verify
boolean verify(PublicKey key)

PartialInputStream

class PartialInputStream extends InputStream

This is an implementation of java.io.InputStream that represents part of data read from an InputStream.

Author:cyng

Constructors

PartialInputStream
PartialInputStream(InputStream in, long offset, long length)

Constructor for the PartialInputStream object

Parameters:
  • in – the origninal input stream
  • offset – the offset the read data from the stream.
  • length – the length of the data to be read
Throws:
  • IOException – Description of the Exception

Methods

close
public void close()

close the stream

Throws:
  • IOException – thrown when IO error occur during closing
read
public int read()

read a byte from the stream

Throws:
  • IOException – thrown when IO error occur during reading.
Returns:

the byte in int value from the stream.

PayloadContainer

public class PayloadContainer

An encapsulation of the payload container in an EbxmlMessage [ebMSS 2.1.4].

A Payload Container contains an ebXML MIME header as well as application payload, as illustrated in the following diagram:

1
2
3
4
5
6
7
8
Content-ID:
Content-type: application/xml

<PurchaseOrder>
  <Product>...</Product>
  ...
</PurchaseOrder>
<!--Line 1-2: ebXML MIME headers. Line 4-7: Application payload-->

This class encapsulates the structure of payload container in an ebXML message.

Author:cyng

Fields

HREF_PREFIX
public static final String HREF_PREFIX

The prefix of “href” attribute of this PayloadContainer.

Constructors

PayloadContainer
public PayloadContainer(DataHandler dataHandler, String contentId, Reference reference)

Create a PayloadContainer from the specified DataHandler.

Methods

getContentId
public String getContentId()

Get contentId.

getContentLength
public long getContentLength()

Get the content length of this payload. Note that the content length returned will be -1 if this container is not created from AttachmentDataSource. Also, the length returned does not take Content-Transfer-Encoding into account, if any.

Returns:content length of this payload
getContentType
public String getContentType()

Get content type of this attachment.

getDataHandler
public DataHandler getDataHandler()

Get javax.activation.DataHandler of this attachment.

getHref
public String getHref()

Get “href” attribute which is equal to the prefixed contentId.

getMimeHeaders
public Map getMimeHeaders()
getReference
public Reference getReference()

Get Reference inside the Manifest associated with this PayloadContainer.

setMimeHeader
public void setMimeHeader(String name, String value)

Reference

public class Reference extends ExtensionElementImpl

A Reference inside a Manifest

Author:cyng

Fields

ATTRIBUTE_HREF
static final String ATTRIBUTE_HREF

Name of the required href attribute in Reference specifying the URI of the payload.

ATTRIBUTE_LOCATION
static final String ATTRIBUTE_LOCATION

Name of the required Location attribute of the Schema element.

ATTRIBUTE_ROLE
static final String ATTRIBUTE_ROLE

Name of the optional role attribute in Reference specifying the URI of the payload.

ATTRIBUTE_TYPE
static final String ATTRIBUTE_TYPE

Name of the type attribute in Reference specifying the type of XLINK link.

ELEMENT_SCHEMA
static final String ELEMENT_SCHEMA

Name of the Schema element

HREF_PREFIX
public static final String HREF_PREFIX

The prefix of “href” attribute of this Reference.

REFERENCE
static final String REFERENCE

Reference element name

Constructors

Reference
Reference(SOAPEnvelope soapEnvelope, SOAPElement soapElement)

Parse the given SOAPElement to reconstruct a Reference object with SOAPEnvelope as the parent.

Parameters:
  • soapEnvelopeSOAPEnvelope object into which the Reference object is added.
  • soapElementSOAPElement object to be parsed to reconstruct the Reference object.
Throws:
  • SOAPException

Methods

addDescription
public void addDescription(String description)

Add element with default xml:lang

Parameters:
  • description – Description to be added to the Reference.
Throws:
  • SOAPException
addDescription
public void addDescription(String description, String lang)

Add element with specified xml:lang

Parameters:
Throws:
  • SOAPException
addSchema
public void addSchema(String location, String version)

Create a Schema object using the given location and version, and add it to the Reference object.

Parameters:
  • location – URI of the schema.
  • version – Version identifier of the schema.
Throws:
  • SOAPException
getDescriptionCount
public int getDescriptionCount()

Gets the number of Description elements in this Reference.

Returns:The number of Description elements.
getDescriptions
public Iterator getDescriptions()

Get the descriptions in the Reference element.

Returns:An iterator pointing to a list of descriptions of type Description.
getHref
public String getHref()

Get href attribute of the Reference element.

Returns:Href attribute.
getId
public String getId()

Get ID attribute of the Reference element.

Returns:ID attribute.
getRole
public String getRole()
getSchemas
public Iterator getSchemas()

Get the schemas in the Reference element.

Returns:An iterator pointing to a list of schemas of type Schema.
setHref
void setHref(String href)
setId
void setId(String id)
setRole
public void setRole(String role)

Reference.Schema

public static final class Schema

A Schema inside a Reference [ebMSS 3.2.1.1]. The schema is not necessarily an XML or DTD schema; it can be any kind of schema such as Database schema.

Constructors

Schema
Schema(String location, String version)

Initializes the schema object using given location and version inforamtion.

Parameters:
  • location – URI of the schema.
  • version – Version identifier of the schema.

Methods

getLocation
public String getLocation()

Get the location URI of the schema.

Returns:URI of the schema.
getVersion
public String getVersion()

Get version identifier oif the schema.

Returns:Version identifier of the schema.

Signature

public abstract class Signature extends HeaderElement

An ebXML Signature is a HeaderElement in HeaderContainer [ebMSS 4.1.1 and 4.1.3].

This class is a partial implementation of the XML-Signature Syntax and Processing / RFC 3275. Please refer to these documents for details.

Author:cyng

See also: ` XML-Signature Syntax and Processing <http://www.w3.org/TR/xmldsig-core/>`_

Fields

ATTRIBUTE_ALGORITHM
public static final String ATTRIBUTE_ALGORITHM

Name of the Algorithm attribute.

ATTRIBUTE_ID
public static final String ATTRIBUTE_ID

Name of the Id attribute.

ATTRIBUTE_URI
public static final String ATTRIBUTE_URI

Name of the URI attribute.

CANONICALIZATION_METHOD
public static final String CANONICALIZATION_METHOD

Namespace URI of the canonicalization method as specified in Exclusive XML Canonicalization Version 1.0.

CHARACTER_ENCODING
public static final String CHARACTER_ENCODING

Default character coding.

DIGEST_ALGORITHM
public static final String DIGEST_ALGORITHM

Name of the message digest algorithm.

DIGEST_METHOD
public static final String DIGEST_METHOD

Name of the Digest method required, qualified by namespace [XMLDSIG 6.1].

ELEMENT_CANONICALIZATION_METHOD
public static final String ELEMENT_CANONICALIZATION_METHOD

Name of the Canonicalization Method element [ebMSS 4.1.3, XMLDSIG 4.3.1] used in signature generation.

ELEMENT_DIGEST_METHOD
public static final String ELEMENT_DIGEST_METHOD

Name of the DigestMethod element which specifies the digest algorithm to be applied to the signed object [XMLDSIG 4.3.3.5].

ELEMENT_DIGEST_VALUE
public static final String ELEMENT_DIGEST_VALUE

Name of the DigestValue element which contains the encoded value of the digest [XMLDSIG 4.3.3.6].

ELEMENT_KEY_INFO
public static final String ELEMENT_KEY_INFO

Name of the KeyInfo element which enables the recipient(s) to obtain the key needed to validate the signature [XMLDSIG 4.4].

ELEMENT_OBJECT
public static final String ELEMENT_OBJECT

Name of the Object element [XMLDSIG 4.5].

ELEMENT_REFERENCE
public static final String ELEMENT_REFERENCE

Name of the Reference element which specifies a digest algorithm and digest value and other optional information [ebMSS 4.1.3, XMLDSIG 4.3.3].

ELEMENT_SIGNATURE
public static final String ELEMENT_SIGNATURE

Name of the Signature element [ebMSS 4.1.1, XMLDSIG 4.1].

ELEMENT_SIGNATURE_METHOD
public static final String ELEMENT_SIGNATURE_METHOD

Name of the Signature Method element [ebMSS 4.1.3, XMLDSIG 4.3.2].

ELEMENT_SIGNATURE_VALUE
public static final String ELEMENT_SIGNATURE_VALUE

Name of the Signature Value element [ebMSS 4.1.3, XMLDSIG 4.2].

ELEMENT_SIGNED_INFO
public static final String ELEMENT_SIGNED_INFO

Name of the SignedInfo element [ebMSS 4.1.3, XMLDSIG 4.3] containing information about the signature. They include:

  • Canonicalization method
  • Signature method
  • References made during signature generation
ELEMENT_TRANSFORM
public static final String ELEMENT_TRANSFORM

Name of the Transform element which describes the transformation applied on the data object [XMLDSIG 4.3.3.4]. Transformation algorithms are described in XMLDSIG 6.6: Transform Algorithms.

ELEMENT_TRANSFORMS
public static final String ELEMENT_TRANSFORMS

Name of the Transforms element which is an ordered list of transformations applied to obtain the data object to be signed [XMLDSIG 4.3.3.4].

ELEMENT_X509_CERTIFICATE
public static final String ELEMENT_X509_CERTIFICATE

Name of the X509Certificate element which contains a binary (ASN.1 DER) X.509 Certificate [XMLDSIG 4.4].

ELEMENT_X509_DATA
public static final String ELEMENT_X509_DATA

Name of the X509Data element which contains identifier(s) of keys or X509 certificates [XMLDSIG 4.4.4].

ELEMENT_XPATH
public static final String ELEMENT_XPATH

Name of the XPath element [XMLDSIG 6.6.3].

NAMESPACE_PREFIX_DS
public static final String NAMESPACE_PREFIX_DS

Namespace prefix of Signature.

NAMESPACE_URI_DS
public static final String NAMESPACE_URI_DS

Namespace URI of Signature.

SIGNATURE_ALGORITHM
public static final String SIGNATURE_ALGORITHM

Name of the digital signature algorithm.

SIGNATURE_METHOD
public static final String SIGNATURE_METHOD

Name of the digital signature method required, qualified by the digital signature namespace [XMLDSIG 6.1].

TRANSFORM_ALGORITHM_ENVELOPED_SIGNATURE
public static final String TRANSFORM_ALGORITHM_ENVELOPED_SIGNATURE

Name of the enveloped signature required, qualified by the digital signature namespace [XMLDSIG 6.1].

TRANSFORM_ALGORITHM_XPATH
public static final String TRANSFORM_ALGORITHM_XPATH

Name of the XPath transform algorithm recommended [XMLDSIG 6.1].

TRANSFORM_XPATH
public static final String TRANSFORM_XPATH

XPath transform string used in the implementation.

references
final ArrayList references
signatureValue
String signatureValue

Constructors

Signature
Signature(SOAPEnvelope soapEnvelope, String localName, String prefix, String uri)

Initializes the Signature object using the given SOAPEnvelope, local name, namespace prefix and namespace URI.

Parameters:
  • soapEnvelopeSOAPEnvelope on which digital signature will be applied.
  • localName – Local name of the signature element.
  • prefix – Namespace prefix of the signature element.
  • uri – Namespace URI of the signature element.
Throws:
  • SOAPException
Signature
Signature(SOAPEnvelope soapEnvelope, SOAPElement soapElement)

Methods

addReference
abstract void addReference(String uri)

Add a reference URI to this Signature.

Parameters:
  • uri – Reference URI to be added.
Throws:
getReferences
public Iterator getReferences()
getSignatureValue
String getSignatureValue()
newInstance
static Signature newInstance(EbxmlMessage ebxmlMessage)

Get a new instance of Signature which will be used to sign or verify the given EbxmlMessage

newInstance
static Signature newInstance(SOAPEnvelope soapEnvelope, SOAPElement soapElement)
newInstance
static Signature newInstance(EbxmlMessage ebxmlMessage, SOAPEnvelope soapEnvelope, SOAPElement soapElement)
sign
abstract void sign(String username, char[] password)

Sign the EbxmlMessage with the username and password used to retrieve private key from the keystore.

Parameters:
  • username – User name required to open the private key.
  • password – Password required to open the private key.
Throws:
sign
abstract void sign(String username, char[] password, String keyStoreLocation, String algorithm)

Sign the EbxmlMessage with the username and password used to retrieve private key from the keystore

Parameters:
  • username – User name required to open the private key.
  • password – Password required to open the private key.
  • keyStoreLocation – File location of the keystore.
  • algorithm – Name of the algorithm used to sign the message.
Throws:
sign
abstract void sign(String username, char[] password, String keyStoreLocation, String algorithm, String digestAlgo, boolean signEnvelopeOnly)

Sign the EbxmlMessage with the username and password used to retrieve private key from the keystore

Parameters:
  • username – User name required to open the private key.
  • password – Password required to open the private key.
  • keyStoreLocation – File location of the keystore.
  • algorithm – Name of the algorithm used to sign the message.
  • digestAlgo – Name of the algorithm used to make the digest.
  • signEnvelopeOnly – whether sign the envelope only.,
Throws:
sign
abstract void sign(String username, char[] password, String keyStoreLocation)

Sign the EbxmlMessage with the username and password used to retrieve private key from the keystore

Parameters:
  • username – User name required to open the private key.
  • password – Password required to open the private key.
  • keyStoreLocation – File location of the keystore.
Throws:
sign
abstract void sign(String username, char[] password, String keyStoreLocation, String type, String provider)

Sign the EbxmlMessage with the username and password used to retrieve private key from the keystore.

Parameters:
  • username – User name required to open the private key.
  • password – Password required to open the private key.
  • keyStoreLocation – File location of the keystore
  • type
  • provider
Throws:
sign
abstract void sign(java.security.PrivateKey privateKey, java.security.cert.X509Certificate[] certificates)

Sign the EbxmlMessage using the private key supplied and attach X.509 certificates to the signature.

Parameters:
  • privateKey – Private key used to sign the message.
  • certificates – List of certificates to be included in the signature.
Throws:
verify
abstract boolean verify(char[] password, String keyStoreLocation, CertResolver certResolver, DataSource datasource)

Verify the message using trusted keystore.

Parameters:
  • password – Password to open the keystore.
  • keyStoreLocation – File location of the key store.
  • certResolver – Resolve a certificate chain in order to verify the message. If it is null, the certificate chain is extracted directly from the element in the message.
Throws:
Returns:

true if the digital signature is valid; false otherwise.

verify
abstract boolean verify(org.w3c.dom.Element documentElement, java.security.PublicKey publicKey)

Verify the XML signature of the EbxmlMessage

Parameters:
  • documentElement – Document fragment which contains the digital signature.
  • publicKey – Public key used to verify the digitall signature.
Throws:
Returns:

true if digital signature is valid; false otherwise.

verify
abstract boolean verify(java.security.PublicKey publicKey)

Verify the XML signature of the EbxmlMessage

Parameters:
  • publicKey – Public key used to verify the digitall signature.
Throws:
Returns:

true if digital signature is valid; false otherwise.

SignatureException

public class SignatureException extends Exception

A class used to encapsulate all kinds of exception thrown during the XML signature signing and verification process.

Author:cyng

Constructors

SignatureException
public SignatureException(String message)

Construct a SignatureException with the specified error message

SignatureException
public SignatureException(String message, Throwable e)

SignatureHandler

public class SignatureHandler
Author:Donahue Sze

Constructors

SignatureHandler
public SignatureHandler(EbxmlMessage message, String username, char[] password, String keyStoreLocation, X509TrustManager trustman)
SignatureHandler
public SignatureHandler(EbxmlMessage message, Certificate cert)

Methods

sign
public void sign()

Sign this EbxmlMessage with XML signature

Throws:
sign
public void sign(String algorithm)

Sign this EbxmlMessage with XML signature

Parameters:
Throws:
sign
public void sign(String algorithm, String digestAlgorithm, boolean signEnvelopeOnly)

Sign this EbxmlMessage with XML signature

Parameters:
  • algorithm – Specifies the algorithm used to generate the digital signature. Refer to ` XML-Signature Syntax and Processing: Algorithm Identifiers and Implementation Requirements <http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/#sec-AlgID>`_ for details.
  • signEnvelopeOnly – whether it should sign the envelope only, without signing the payload.
  • digestAlgorithm – Description of the Parameter
Throws:
verify
public boolean verify()

Verify the message using trusted keystore.

Throws:
Returns:

true if the digital signature is valid; false otherwise.

verifyByPublicKey
public boolean verifyByPublicKey()

SignatureReference

public class SignatureReference extends HeaderElement

element in .

Author:cyng

Fields

ATTRIBUTE_URI
static final String ATTRIBUTE_URI

URI attribute name

ELEMENT_DIGEST_VALUE
static final String ELEMENT_DIGEST_VALUE

element name

SIGNATURE_REFERENCE
static final String SIGNATURE_REFERENCE

element name

Constructors

SignatureReference
SignatureReference(SOAPEnvelope soapEnvelope, SOAPElement soapElement)

Methods

getDigestValue
public String getDigestValue()

Gets element of this .

Returns:element of this .
getUri
public String getUri()

Gets URI attribute of this .

Returns:URI attribute of this .

StatusRequest

public class StatusRequest extends BodyElement

An ebXML StatusRequest in the SOAP Body of a HeaderContainer [ebMSS 7.1.1].

Author:cyng

Fields

ELEMENT_REF_TO_MESSAGE_ID
static final String ELEMENT_REF_TO_MESSAGE_ID

Name of the RefToMessageID element.

STATUS_REQUEST
static final String STATUS_REQUEST

Name of the StatusRequest element.

Constructors

StatusRequest
StatusRequest(SOAPEnvelope soapEnvelope, String refToMessageId)

Constructs a StatusRequested with the given mandatory fields.

Parameters:
  • soapEnvelopeSOAPEnvelope, the header of which status request element will be added to.
  • refToMessageId – Identifier of the message that this status message intends to query.
Throws:
  • SOAPException
StatusRequest
StatusRequest(SOAPEnvelope soapEnvelope, SOAPElement soapElement)

Constructs a StatusRequest object by parsing the given SOAPElement.

Parameters:
  • soapEnvelopeSOAPEnvelope, the header of which status request element will be added to.
  • soapElementSOAPElement from which a StatusRequest object is constructed.
Throws:
  • SOAPException

Methods

getRefToMessageId
public String getRefToMessageId()

Get the identifier of the message the status request refers to.

Returns:Identifier of the message being referred to by status request.

StatusResponse

public class StatusResponse extends BodyElement

An ebXML StatusResponse in the SOAP Body of a HeaderContainer [ebMSS 7.1.2].

Author:cyng

Fields

ATTRIBUTE_MESSAGE_STATUS
static final String ATTRIBUTE_MESSAGE_STATUS

Name of the messageStatus attribute.

ELEMENT_REF_TO_MESSAGE_ID
static final String ELEMENT_REF_TO_MESSAGE_ID

Name of the RefToMessageID element.

ELEMENT_TIMESTAMP
static final String ELEMENT_TIMESTAMP

Name of the Timestamp element.

STATUS_RESPONSE
static final String STATUS_RESPONSE

StatusRequest element name

Constructors

StatusResponse
StatusResponse(SOAPEnvelope soapEnvelope, String refToMessageId, String messageStatus)

Constructs a StatusResponse with the given mandatory fields

Parameters:
  • soapEnvelopeSOAPEnvelope to which the status response element will be added.
  • refToMessageId – Identifier of the message whose status is being reported. [ebMSS 7.3.1].
  • messageStatus – Message status response string [ebMSS 7.3.3].
Throws:
  • SOAPException
StatusResponse
StatusResponse(SOAPEnvelope soapEnvelope, String refToMessageId, String messageStatus, String timestamp)

Constructs a StatusResponse with the given mandatory fields

Parameters:
  • soapEnvelopeSOAPEnvelope to which the status response element will be added.
  • refToMessageId – Identifier of the message whose status is being reported. [ebMSS 7.3.1].
  • messageStatus – Message status response string [ebMSS 7.3.3].
  • timestamp – Timestamp of the message the status is being reported.
Throws:
  • SOAPException
StatusResponse
StatusResponse(SOAPEnvelope soapEnvelope, SOAPElement soapElement)

Constructs a StatusResponse object by parsing the given SOAPElement.

Parameters:
  • soapEnvelopeSOAPEnvelope to which the status response element will be added.
  • soapElementSOAPElement from which a StatusResponse object is constructed.
Throws:
  • SOAPException

Methods

getMessageStatus
public String getMessageStatus()

Gets the status of the message whose status is reported.

Returns:Message status.
getRefToMessageId
public String getRefToMessageId()

Gets Identifier of the message whose status is reported.

Returns:Identifier of the message being referred.
getTimestamp
public String getTimestamp()

Get the timestamp of the message when it was received by the party who reported its status.

Returns:Message timestamp when it was received.

SyncReply

public class SyncReply extends HeaderElement

An ebXML SyncReply in the SOAP Header of a HeaderContainer [ebMSS 4.3].

Author:tslam

Fields

SYNC_REPLY
static final String SYNC_REPLY

SyncReply element name

Constructors

SyncReply
SyncReply(SOAPEnvelope soapEnvelope)

Constructs a SyncReply with the given mandatory fields.

Parameters:
  • soapEnvelopeSOAPEnvelope, the header container of which the SyncReply is attached to.
Throws:
  • SOAPException
SyncReply
SyncReply(SOAPEnvelope soapEnvelope, SOAPElement soapElement)

Constructs an SyncReply object by parsing the given SOAPElement.

Parameters:
  • soapEnvelopeSOAPEnvelope, the header container of which the SyncReply is attached to.
  • soapElement – Empty SOAPElement.
Throws:
  • SOAPException

Utility

public class Utility

Utility class for use by both clients and server.

Author:kcyee

Methods

fromUTCString
public static Date fromUTCString(String dateTime)

Convert a string of data type “dateTime” as specified by XML-Schema Part 2: Datatypes section 3.2.7 to local date/time. Only date/time represented as CCYY-MM-DDThh:mm:ssZ is supported.

Parameters:
  • dateTime – Date/time string in UTC.
Returns:

local time representation of the given UTC time string.

generateMessageId
public static String generateMessageId(Date date, EbxmlMessage ebxmlMessage)

Generate globally unique message ID according to the specified date and the information in ebXML message. Required fields are:

  • To/PartyId element [ebMSS 3.1.1.1]
  • CPAId [ebMSS 3.1.2]
  • Service element [ebMSS 3.1.4]
  • Action element [ebMSS 3.1.5]
Parameters:
  • date – Date to be used to generate message ID.
  • ebxmlMessage – ebXML message containing required fields.
Throws:
Returns:

Message ID derived from the given information.

generateMessageId
public static String generateMessageId(Date date, String toPartyId, String cpaId, String service, String action)

Generate message ID from the specified date, ToPartyId, CPAId, service name and action string.

Parameters:
  • date – Date from which message ID is generated.
  • toPartyId – Party ID of the recipient [ebMSS 3.1.1.1].
  • cpaId – CPAId [ebMSS 3.1.2].
  • service – Service name [ebMSS 3.1.4].
  • action – Action name [ebMSS 3.1.5].
Returns:

Message ID derived from the given information.

toUTCString
public static String toUTCString(Date date)

Get timestamp of the specified date in type “dateTime” as specified in XML-Schema Part 2: Datatypes section 3.2.7. Local time is converted to UTC time.

Parameters:
  • date – Local date to be converted to UTC time.
Returns:

UTC time string in CCYY-MM-DDThh:mm:ssZ format

hk.hku.cecid.ebms.pkg.pki

ApacheXMLDSigner

public class ApacheXMLDSigner implements XMLDSigner

This class hides the details for digital signature. The digital signature routines are provided by the Apache XML Security library. We defined a standard way to have the document signed as interface. Different classes will implement the interface using different library behind.

Author:kcyee

Fields

ACTOR_NEXT_MSH_SCHEMAS
public static final String ACTOR_NEXT_MSH_SCHEMAS
ACTOR_NEXT_MSH_URN
public static final String ACTOR_NEXT_MSH_URN
DIGEST_METHOD
public static final String DIGEST_METHOD

Name of the Digest method required, qualified by namespace [XMLDSIG 6.1]

ELEMENT_KEY_INFO
public static final String ELEMENT_KEY_INFO

Name of the KeyInfo element which enables the recipient(s) to obtain the key needed to validate the signature [XMLDSIG 4.4]

ELEMENT_SIGNATURE
public static final String ELEMENT_SIGNATURE

Name of the Signature element [ebMSS 4.1.1, XMLDSIG 4.1]

ELEMENT_XPATH
public static final String ELEMENT_XPATH

Name of the XPath element [XMLDSIG 6.6.3]

NAMESPACE_PREFIX_DS
public static final String NAMESPACE_PREFIX_DS

Namespace prefix of Signature.

NAMESPACE_PREFIX_SOAP_ENVELOPE
public static final String NAMESPACE_PREFIX_SOAP_ENVELOPE

Namespace prefix of SOAP envelope.

NAMESPACE_URI_DS
public static final String NAMESPACE_URI_DS

Namespace URI of Signature.

NAMESPACE_URI_SOAP_ENVELOPE
public static final String NAMESPACE_URI_SOAP_ENVELOPE

Namespace URI of SOAP envelope.

NAMESPACE_URI_XML_NS
public static final String NAMESPACE_URI_XML_NS

Namespace URI of xmlns.

SIGNATURE_METHOD
public static final String SIGNATURE_METHOD

Name of the digital signature method required, qualified by the digital signature namespace [XMLDSIG 6.1]

TRANSFORM_ALGORITHM_XPATH
public static final String TRANSFORM_ALGORITHM_XPATH

Name of the XPath transform algorithm recommended [XMLDSIG 6.1]

TRANSFORM_XPATH
public static final String TRANSFORM_XPATH

XPath transform string used in the implementation.

documents
protected ArrayList documents

Internal variable for holding the documents needed to be referred in the signature.

envelope
protected Document envelope

Internal variable for holding the envelope of the signature.

logger
protected static Logger logger

Logger

signature
protected XMLSignature signature

Internal variable of the Apache XML Security library signature object for doing the actual signing/verifying algorithm.

trusted
protected CompositeKeyStore trusted

Internal variable for holding the trusted anchor for certificate path verification.

Constructors

ApacheXMLDSigner
public ApacheXMLDSigner()

Default constructor to initialize the internal variables.

Methods

addCertResolver
public void addCertResolver(CertResolver certResolver, Object obj)
addDocument
public void addDocument(String uri, InputStream is, String contentType)

Adds a reference to a document attachment to the signature.

Parameters:
  • uri – the URI of the document attachment
  • is – the input stream of the content of the document
  • contentType – the content type of the document
getElement
public Element getElement()

Gets the DOM element of the signature generated.

Returns:the DOM element of the signature
setEnvelope
public void setEnvelope(Document doc, String algo, String digestAlgo)

Set the envelope to host the Signature element. That is the XML document where the Signature element to be added. The digital signature here will always be an enveloped signature. The envelope will be included in the process of signing.

Parameters:
  • doc – the XML document to host the Signature element
  • algo – the algorithm used for digital signature. Currently, only two values are tested: dsa-sha1 and rsa-sha1.
  • digestAlgo – the algorithm used for making digest value. Currently, one value is supported: sha1
Throws:
  • SignException – internal exception when doing initialization on Apache XML Security library
setEnvelope
public void setEnvelope(Document doc, String algo)

Set the envelope to host the Signature element. That is the XML document where the Signature element to be added. The digital signature here will always be an enveloped signature. The envelope will be included in the process of signing.

Parameters:
  • doc – the XML document to host the Signature element
  • algo – the algorithm used for digital signature. Currently, only two values are tested: dsa-sha1 and rsa-sha1.
Throws:
  • SignException – internal exception when doing initialization on Apache XML Security library
setEnvelope
public void setEnvelope(Document doc)

Set the envelope to host the Signature element. That is the XML document where the Signature element to be added. The digital signature here will always be an enveloped signature. The envelope will be included in the process of signing.

Parameters:
  • doc – the XML document to host the Signature element
Throws:
  • SignException – internal exception when doing initialization on Apache XML Security library
setTrustAnchor
public void setTrustAnchor(CompositeKeyStore ks)

Sets the trust anchor for verfication of certificate path.

Parameters:
  • ks – the keystore providing the trusted certificates
sign
public void sign(CompositeKeyStore ks, String alias, char[] password)

Signs the envelope and documents by using the specified key in the keystore.

Parameters:
  • ks – the keystore holding the key for signing
  • alias – the alias of the key for signing
  • password – the password for accessing the key for signing
Throws:
  • SignException – when there is any error in the processing of signing
verify
public boolean verify()

Verifies the signature in the envelope passed in, which may reference the documents specified using the addDocument method.

Throws:
  • VerifyException – when there is any error in the processing of verification
Returns:

true if the signature can be verified successfully, false if otherwise.

CRLFileSource

public class CRLFileSource extends CRLSource

This class extends CRLSource to add initialization procedure for loading a file-based CRL.

Author:kcyee

Fields

crlFile
protected File crlFile

The file holding the CRL

Constructors

CRLFileSource
public CRLFileSource()

Default constructor. It initializes the object. But the object is still unusable until init() is called.

CRLFileSource
public CRLFileSource(String crlFile)

Constructor with the file name of the CRL passed in. It initializes the object. But the object is still unusable until init() is called.

Parameters:
  • crlFile – the file name of the CRL
CRLFileSource
public CRLFileSource(File crlFile)

Constructor with the file object holding the CRL passed in. It initializes the object. But the object is still unusable until init() is called.

Parameters:
  • crlFile – the file object of the file holding the CRL

Methods

init
public void init()

Initializes the object. The CRL file is being loaded into the internal CRL object.

Throws:
  • CRLException – Initialization error occurs

CRLSource

public abstract class CRLSource

This is an abstract class for holding a X509 CRL instance. The functionality of CRL is given by this class. The sub-classes will provide different initialization method for loading the CRL, for example, through a file or through LDAP.

Author:kcyee

Fields

crl
protected X509CRL crl

Internal storage of X509 CRL

ready
protected boolean ready

Indicates the CRL has been loaded correctly or not

Constructors

CRLSource
public CRLSource()

Default constructor. It initializes the object. But the object is still unusable until init() is called.

Methods

getIssuer
public String getIssuer()

Gets the distinguished name (DN) of the issuer of the CRL.

Throws:
Returns:

the DN of the issuer

getNextUpdate
public Date getNextUpdate()

Gets the next update date of the CRL.

Throws:
Returns:

the next update date

getThisUpdate
public Date getThisUpdate()

Gets the last update date of the CRL.

Throws:
Returns:

the last update date

init
public abstract void init()

Initializes the object. The initialization procedure depends on the source of the CRL. So, we declare this method as abstract here, leaving the sub-classes to concern about the initialization.

Throws:
  • CRLException – Initialization error occurs
isReady
public boolean isReady()

Gets the readiness of the object. The object will be ready for use after init() is called. And the internal X509 CRL storage is populated.

Returns:true if the object is ready for use; false if otherwise
isRevoked
public boolean isRevoked(Certificate cert)

Checks the specified certificate against the CRL to see whether the certificate has been revoked or not.

Parameters:
  • cert – the certificate to be tested against the CRL
Throws:
Returns:

true if the specified certificate is revoked according to the CRL; false if otherwise

isRevoked
public boolean isRevoked(CertSource cert)

Checks the specified certificate against the CRL to see whether the certificate has been revoked or not.

Parameters:
  • cert – the certificate to be tested against the CRL
Throws:
Returns:

true if the specified certificate is revoked according to the CRL; false if otherwise

verifySignature
public boolean verifySignature(PublicKey pubKey)

Verifies the CRL to check whether is is signed by the private key corresponding to the specified public key or not.

Parameters:
  • pubKey – the public key used to verify
Throws:
Returns:

true if the CRL is signed by the private key corresponding to pubKey; false if otherwise

verifySignature
public boolean verifySignature(Certificate cert)

Verifies the CRL to check whether is is signed by the private key corresponding to the public key in the specified certificate or not.

Parameters:
  • cert – the certificate storing the public key to be used for verification
Throws:
Returns:

true if the CRL is signed by the private key corresponding to the public key stored in cert; false if otherwise

verifySignature
public boolean verifySignature(CertSource cert)

Verifies the CRL to check whether is is signed by the private key corresponding to the public key in the specified certificate or not.

Parameters:
  • cert – the certificate storing the public key to be used for verification
Throws:
Returns:

true if the CRL is signed by the private key corresponding to the public key stored in cert; false if otherwise

CertPathVerifier

public class CertPathVerifier

This class wraps the certificate path verification routine into a separate static method. This is useful when JDK1.3 is used, the cert path verification is skipped. And the JDK1.4 specific classes will not be loaded, as they are all called in this class.

Author:kcyee

Fields

logger
protected static Logger logger

Logger

Methods

verify
public static boolean verify(java.security.cert.Certificate[] certs, CompositeKeyStore trusted)

Verifies the specified certificate chain against the trusted anchors. The trusted anchors contains all public certificate that is trusted. This method will make use of JDK1.4’s utilities to verify the certificate chain.

Parameters:
  • certs – the certificate chain being verified
  • trusted – the keystore storing the trusted anchors.
Returns:

true if verification is succeeded; false otherwise

CertResolver

public interface CertResolver
Author:cyng

Methods

resolve
Certificate[] resolve(Object obj)

CertSource

public class CertSource

This class loads a X509 certificate file. Basically this class only acts as a convenience wrapper of java.security.cert.X509Certificate.

Author:kcyee

Fields

x509Cert
protected X509Certificate x509Cert

internal X509 certificate storage.

Constructors

CertSource
public CertSource()

Default constructor. The user should call load() to further initialize the certificate.

CertSource
public CertSource(File certFile)

Constructor with initialization parameters. The certificate will be loaded from the file specified.

Parameters:
  • certFile – the certificate file
Throws:
  • CertificateException – if the file specified cannot be read, or any errors occurred when loading the file.
CertSource
public CertSource(String certFile)

Constructor with initialization parameters. The certificate will be loaded from the file specified.

Parameters:
  • certFile – the file name of the certificate file
Throws:
  • CertificateException – if the file specified cannot be read, or any errors occurred when loading the file.
CertSource
public CertSource(X509Certificate cert)

Constructor with initialization parameters. The class will be initialized with the specified certificate.

Parameters:
  • cert – the preloaded certificate

Methods

getInternalCert
public X509Certificate getInternalCert()

Gets the X509Certificate stored internally.

Returns:the X509Certificate stored internally.
getIssuer
public String getIssuer()

Gets the distinguished name (DN) of the issuer of the certificate.

Throws:
Returns:

the DN of the issuer

getPublicKey
public PublicKey getPublicKey()

Gets the public key in this certificate.

Returns:the public key in this certificate.
isValid
public boolean isValid()

Checks whether the certificate is valid in current time.

Returns:true if the certificate is still valid, false if otherwise.
isValid
public boolean isValid(Date d)

Checks whether the certificate is valid in the specified time.

Parameters:
  • d – the specified time
Returns:

true if the certificate is valid, false if otherwise.

load
public void load(File certFile)

Loads the certificate file.

Parameters:
  • certFile – the certificate file
Throws:
  • CertificateException – if the file specified cannot be read, or any errors occurred when loading the file.
load
public void load(String certFile)

Loads the certificate file.

Parameters:
  • certFile – the file name of the certificate file
Throws:
  • CertificateException – if the file specified cannot be read, or any errors occurred when loading the file.
verify
public boolean verify(PublicKey pubKey)

Verifies whether the certificate is signed by the private key corresponding to the specified public key.

Parameters:
  • pubKey – the public key for verification
Returns:

true if the verification is passed, false if otherwise.

verify
public boolean verify(Certificate cert)

Verifies whether the certificate is signed by the private key corresponding to public key in the specified certificate.

Parameters:
  • cert – the certificate for verification
Returns:

true if the verification is passed, false if otherwise.

verify
public boolean verify(CertSource cert)

Verifies whether the certificate is signed by the private key corresponding to public key in the specified certificate.

Parameters:
  • cert – the certificate for verification
Returns:

true if the verification is passed, false if otherwise.

CompositeKeyStore

public class CompositeKeyStore

Composite keystore which manages keystores of different types. A typical Java keystore supports only one keystore type per file. That will be inconvenient for applications to manage several types of keystore. Also, this composite keystore supports managing multiple keystore files. This can be viewed as a keystore registry, that is, this object manages a pool of keystore files.

Author:kcyee

Fields

cache
protected Hashtable cache

Internal storage of the aliases inside the keystore file

keystores
protected Vector keystores

Internal storage of the keystore object

storage
protected Hashtable storage

Internal storage of the keystore file information

Constructors

CompositeKeyStore
public CompositeKeyStore()

Default constructor. The internal variables are being initialized.

Methods

addKeyStoreFile
public void addKeyStoreFile(String keyFile, String type, char[] password)

Adds a keystore file to the keystore management pool.

Parameters:
  • keyFile – the name of the keystore file
  • type – the type of the keystore
  • password – the password for accessing the keystore
addKeyStoreFile
protected void addKeyStoreFile(File keyFile, String type, char[] password)

Adds a keystore file to the keystore management pool.

Parameters:
  • keyFile – the keystore file
  • type – the type of the keystore
  • password – the password for accessing the keystore
aliases
public Enumeration aliases()

Gets all the aliases of the keystores pointed by this composite keystore.

Returns:an enumeration of string, holding the aliases of the keys
containsAlias
public boolean containsAlias(String alias)

Determines whether a given alias exists in one of the keystores pointed by this composite keystore or not.

Parameters:
  • alias – the alias of the key/certificate
Returns:

true if the alias exists in one of the keystores, false & otherwise

getCertificate
public Certificate getCertificate(String alias)

Gets the certificate named by the given alias, from the collection of keystores pointed by this composite keystore.

Parameters:
  • alias – the alias of the key/certificate
Throws:
  • KeyStoreException – the keystore is corrupted
Returns:

the certificate named by the given alias, null if not found

getCertificateAlias
public String getCertificateAlias(Certificate cert)

Gets the alias of the specified certificate.

Parameters:
  • cert – the certificate
Returns:

the alias of the certificate, if the certificate can be found in the collection of keystores pointed by this composite keystore. Otherwise, null will be returned

getCertificateChain
public Certificate[] getCertificateChain(String alias)

Gets the certificate chain by the specified alias.

Parameters:
  • alias – the alias of the key/certificate
Throws:
  • KeyStoreException – the keystore is corrupted
Returns:

the certificate chain by the specified alias, null if not found

getCreationDate
public Date getCreationDate(String alias)

Gets the creation date of the key/certificate by the specified alias.

Parameters:
  • alias – the alias of the key/certificate
Throws:
  • KeyStoreException – the keystore is corrupted
Returns:

the creation date of the key/certificate by the specified alias, null if not found

getKey
public Key getKey(String alias, char[] password)

Gets the key by the specified alias. A password should be given also to retrieve the key.

Parameters:
  • alias – the alias of the key/certificate
  • password – the password to retrieve the key
Throws:
  • KeyStoreException – the keystore is corrupted
  • NoSuchAlgorithmException – the keystore cannot be read
  • UnrecoverableKeyException – the keystore cannot be read
Returns:

the key specified by the alias, null if not found

getKeyStore
public KeyStore getKeyStore()

Gets the first KeyStore object from the keystore management pool.

Returns:the first KeyStore object from the keystore management pool
isCertificateEntry
public boolean isCertificateEntry(String alias)

Determines whether the specified alias is specifying a certificate or not.

Parameters:
  • alias – the alias of the key/certificate
Throws:
  • KeyStoreException – the keystore is corrupted
isKeyEntry
public boolean isKeyEntry(String alias)

Determines whether the specified alias is specifying a key or not.

Parameters:
  • alias – the alias of the key/certificate
Throws:
  • KeyStoreException – the keystore is corrupted
load
public void load(String storeFileName)

Loads the composite keystore from a persistent file in the file system.

Parameters:
  • storeFileName – the name of the composite keystore persistent file
Throws:
load
public void load(File storeFile)

Loads the composite keystore from a persistent file in the file system.

Parameters:
  • storeFile – the composite keystore persistent file
Throws:
loadCache
protected void loadCache()

Loads the keystores pointed by this composite keystore into memory and create a caching of aliases.

loadKeyStore
protected KeyStore loadKeyStore(String fileName, KeyStoreFileProp ksp)

Gets an instance of the keystore of correct type. This function will consider the Java version and determine whether to use JSSE or not. For Java version 1.4 or above, JSSE is built in. So, no need to call an external provider to create an instance of PKCS#12 formatted keystore. Otherwise, JSSE should be used, and we make use of dynamic binding to load the JSSE library.

Parameters:
  • fileName – the keystore file name to load
  • ksp – other keystore parameters for loading
Returns:

keystore instance of the correct type

removeKeyStoreFile
public void removeKeyStoreFile(String keyFile)

Removes a keystore file from the keystore management pool.

Parameters:
  • keyFile – the name of the keystore file
removeKeyStoreFile
protected void removeKeyStoreFile(File keyFile)

Removes a keystore file from the keystore management pool.

Parameters:
  • keyFile – the keystore file
size
public int size()

Gets the total number of keys/certificates in all the keystores pointed by this composite keystore.

Returns:the total number of keys/certificates
store
public void store(String storeFileName)

Stores the composite keystore to a persistent file in the file system.

Parameters:
  • storeFileName – the name of the composite keystore persistent file
Throws:
  • StoreException – the composite keystore is not successfully stored
store
public void store(File storeFile)

Stores the composite keystore to a persistent file in the file system.

Parameters:
  • storeFile – the composite keystore persistent file
Throws:
  • StoreException – the composite keystore is not successfully stored

DocumentDetail

public class DocumentDetail

A data structure class for holding the document attachment parameters.

Author:kcyee

Fields

contentType
public String contentType

The content type of the document.

stream
public InputStream stream

The input stream of the content of the document.

uri
public String uri

The URI of the document.

DocumentResolver

public class DocumentResolver extends ResourceResolverSpi

This class is needed by the Apache XML Security library for locating and loading the document attachments.

Author:kcyee

Fields

docs
protected DocumentDetail[] docs

Internal variable for holding the document parameters.

Constructors

DocumentResolver
public DocumentResolver(DocumentDetail[] docs)

Construct with an array of document parameters.

Parameters:
  • docs – array of document parameters

Methods

engineCanResolveURI
public boolean engineCanResolveURI(ResourceResolverContext context)

Sees whether the resolver can resolve the document specified by the URI or not.

Parameters:
  • uri
  • baseUri
Returns:

true if the resolver can locate the document specified, false if otherwise.

engineResolveURI
public XMLSignatureInput engineResolveURI(ResourceResolverContext context)

Gets the document (encapsulated in the XMLSignatureInput object) by specifying the URI.

Parameters:
  • uri
  • baseUri
Returns:

the document encapsulated in the XMLSignatureInput object

ErrorMessages

public class ErrorMessages

A class holding error codes and the corresponding error messages.

Author:kcyee

Fields

ERR_PKI_CANNOT_DECRYPT
public static final int ERR_PKI_CANNOT_DECRYPT
ERR_PKI_CANNOT_ENCRYPT
public static final int ERR_PKI_CANNOT_ENCRYPT
ERR_PKI_CANNOT_SIGN
public static final int ERR_PKI_CANNOT_SIGN
ERR_PKI_INVALID_KEYSTORE
public static final int ERR_PKI_INVALID_KEYSTORE
ERR_PKI_UNKNOWN_ERROR
public static final int ERR_PKI_UNKNOWN_ERROR
ERR_PKI_VERIFY_SIGNATURE_FAILED
public static final int ERR_PKI_VERIFY_SIGNATURE_FAILED
errorMsg
protected static TreeMap errorMsg
isConfigured
protected static boolean isConfigured

Methods

configure
protected static synchronized void configure()
getMessage
public static String getMessage(int code)
getMessage
public static String getMessage(int code, String extraMsg)
getMessage
public static String getMessage(int code, Throwable e)
getMessage
public static String getMessage(int code, Throwable e, String extraMsg)
load
protected static void load(int code, String msg)
main
public static void main(String[] args)

InitializationException

public class InitializationException extends Exception

Exception class representing the error during initialization.

Author:kcyee

Constructors

InitializationException
public InitializationException(String msg)

Construtor with message.

Parameters:
  • msg – the message of the exception
InitializationException
public InitializationException(String msg, Exception e)

Instantiate the exception with a nested exception

Parameters:
  • msg – the message of the exception
  • e – the exception to be wrapped

Methods

getMessage
public String getMessage()

It overrides the getMessage() method so it also reports the nested exception , if it exists.

Returns:the exception message.
getNestedException
public Exception getNestedException()
Returns:the nested exception

KeyStoreFileProp

public class KeyStoreFileProp implements Serializable

This class represents the data structure for holding parameters for accessing a keystore file. Since the parameters will be serialized to the file system, some fields (particularly password will be scrambled.

Author:kcyee

Fields

password
protected char[] password

Internal storage for the keystore password

type
protected String type

Internal storage for the keystore type

Constructors

KeyStoreFileProp
public KeyStoreFileProp(String type, char[] password)

Constructor that initializes the object with keystore parameters

Parameters:
  • type – the keystore type
  • password – the keystore password

Methods

decrypt
protected char[] decrypt(char[] password)

Decrypts the password. This is a helper function called internally to unscramble the password from storage.

Parameters:
  • password – the text to be decrypted
Returns:

the decrypted password

encrypt
protected char[] encrypt(char[] password)

Encrypts the password. This is a helper function called internally to scramble the password for storage.

Parameters:
  • password – the password to be encrypted
Returns:

the encrypted text

getPassword
public char[] getPassword()

Gets the keystore password

Returns:the keystore password
getType
public String getType()

Gets the keystore type

Returns:the keystore type

SMIMEException

public class SMIMEException extends Exception

The exception will be thrown when generating SMIME mime body or mime message

Author:achong

Constructors

SMIMEException
public SMIMEException(String msg)

Construtor with message.

Parameters:
  • msg – the message of the exception
SMIMEException
public SMIMEException(String msg, Exception e)

Instantiate the exception with a nested exception

Parameters:
  • msg – the message of the exception
  • e – the exception to be wrapped

Methods

getMessage
public String getMessage()

It overrides the getMessage() method so it also reports the nested exception , if it exists.

Returns:the exception message.
getNestedException
public Exception getNestedException()
Returns:the nested exception

SMIMEHandler

public class SMIMEHandler

It is the base class of SMIMEEncrypter and SMIMEDecrypter. The BouncyCastle ‘s SMIME engine only works properly with BouncyCastle ‘s JCE provider. The subclass should call the method initiate(), which add the BouncyCastle ‘s Provider and setup which DataHandler for what types of content type.

Methods

initiate
static void initiate()

Add the BouncyCastle ‘s Provider and setup which DataHandler for what types of content type.

SignException

public class SignException extends Exception

Exception class representing the error during signing the digital signature.

Author:kcyee

Constructors

SignException
public SignException(String message)

Construtor with message.

Parameters:
  • message – the message of the exception

StoreException

public class StoreException extends Exception

Exception class representing the error during storing the composite keystore.

Author:kcyee

Constructors

StoreException
public StoreException(String msg)

Construtor with message.

Parameters:
  • msg – the message of the exception

VerifyException

public class VerifyException extends Exception

Exception class representing the error during verification of digital signature.

Author:kcyee

Constructors

VerifyException
public VerifyException(String message)

Construtor with message.

Parameters:
  • message – the message of the exception

XMLDSigner

public interface XMLDSigner

This interface defines a standard way to have the document signed. Different classes will implement the interface using different library behind.

Author:kcyee

Methods

addDocument
public void addDocument(String uri, InputStream is, String contentType)

Adds a reference to a document attachment to the signature.

Parameters:
  • uri – the URI of the document attachment
  • is – the input stream of the content of the document
  • contentType – the content type of the document
getElement
public Element getElement()

Gets the DOM element of the signature generated.

Returns:the DOM element of the signature
setEnvelope
public void setEnvelope(Document doc)

Set the envelope to host the Signature element. That is the XML document where the Signature element to be added. The digital signature here will always be an enveloped signature. The envelope will be included in the process of signing.

Parameters:
  • doc – the XML document to host the Signature element
Throws:
setTrustAnchor
public void setTrustAnchor(CompositeKeyStore ks)

Sets the trust anchor for verfication of certificate path.

Parameters:
  • ks – the keystore providing the trusted certificates
sign
public void sign(CompositeKeyStore ks, String alias, char[] password)

Signs the envelope and documents by using the specified key in the keystore.

Parameters:
  • ks – the keystore holding the key for signing
  • alias – the alias of the key for signing
  • password – the password for accessing the key for signing
Throws:
  • SignException – when there is any error in the processing of signing
verify
public boolean verify()

Verifies the signature in the envelope passed in, which may reference the documents specified using the addDocument method.

Throws:
  • VerifyException – when there is any error in the processing of verification
Returns:

true if the signature can be verified successfully, false if otherwise.

hk.hku.cecid.ebms.pkg.validation

BodyValidator

public class BodyValidator

Class for validating the body of an ebXML message. EbxmlValidationException will be thrown in case of error.

Author:Frankie Lam

Methods

validate
public void validate(EbxmlMessage ebxmlMessage)

EbxmlMessageValidator

public class EbxmlMessageValidator

Class for validating an ebXML message. EbxmlValidationException will be thrown in case of error.

Author:Frankie Lam

Methods

validate
public void validate(EbxmlMessage ebxmlMessage)

EbxmlValidationException

public class EbxmlValidationException extends ValidationException

Exception class that can generate ebXML error messages from the information it has been given.

Author:Frankie Lam

Fields

ACTION
public static final String ACTION

Error action reserved for standalone errors described in ebXML Message Service Specification [ebMSS 4.2.4.3].

EBXML_ERROR_DELIVERY_FAILURE
public static final String EBXML_ERROR_DELIVERY_FAILURE

ebXML message cannot be delivered.

EBXML_ERROR_INCONSISTENT
public static final String EBXML_ERROR_INCONSISTENT

ebXML error indicating that the ebXML message is inconsistent.

EBXML_ERROR_MIME_PROBLEM
public static final String EBXML_ERROR_MIME_PROBLEM

xlink:href error cannot be resolved.

EBXML_ERROR_NOT_SUPPORTED
public static final String EBXML_ERROR_NOT_SUPPORTED

ebXML error indicating that the function is not supported.

EBXML_ERROR_OTHER_XML
public static final String EBXML_ERROR_OTHER_XML

ebXML error indicating that the ebXML message do not conform to the rules or constraints specified in the specification, and cannot be represented using other error codes.

EBXML_ERROR_SECURITY_FAILURE
public static final String EBXML_ERROR_SECURITY_FAILURE

Validation of signatures or authenticity / authority has failed.

EBXML_ERROR_TIME_TO_LIVE_EXPIRED
public static final String EBXML_ERROR_TIME_TO_LIVE_EXPIRED

ebXML message is expired.

EBXML_ERROR_UNKNOWN
public static final String EBXML_ERROR_UNKNOWN

An error has occurred but cannot be represented by other error codes.

EBXML_ERROR_VALUE_NOT_RECOGNIZED
public static final String EBXML_ERROR_VALUE_NOT_RECOGNIZED

ebXML error indicating that the value of an element / attribute cannot be recognized.

SERVICE
public static final String SERVICE

Service name reserved for services described in ebXML Message Service Specification [ebMSS 3.1.4].

SEVERITY_ERROR
public static final String SEVERITY_ERROR

Error severity level

SEVERITY_WARNING
public static final String SEVERITY_WARNING

Warning severity level

location
protected final String location

location of the message containing the error.

refToMessage
protected EbxmlMessage refToMessage

The ebXML message being referred to.

severity
protected final String severity

Severity of the error.

Constructors

EbxmlValidationException
public EbxmlValidationException(String errorCode, String severity, String errorString)

Constructs a EbxmlValidationException object given its error code, severity level, error string and the ebXML message being referred.

Parameters:
  • errorCode – One of the error codes defined in ebMS 4.2.3.4.1.
  • severity – Severity level of the error, which should be either SEVERITY_WARNING or SEVERITY_ERROR
  • errorString – String describing the error.
EbxmlValidationException
public EbxmlValidationException(String errorCode, String severity, String errorString, String location)

Constructs a EbxmlValidationException object given its error code, severity level, error string and the ebXML message being referred.

Parameters:
  • errorCode – One of the error codes defined in ebMS 4.2.3.4.1.
  • severity – Severity level of the error, which should be either SEVERITY_WARNING or SEVERITY_ERROR
  • errorString – String describing the error.
  • location – Location of the message containing the error.

Methods

getEbxmlMessage
public EbxmlMessage getEbxmlMessage()

Get EbxmlMessage error message from the information given int this object.

Returns:EbxmlMessage containing the error information.
getLocation
public String getLocation()

Get the location attribute of the ebXML error element.

Returns:Value of location attribute; null if it is unspecified.
getSOAPMessage
public SOAPMessage getSOAPMessage()

Get the error message in SOAP format.

Returns:javax.xml.soap.SOAPMessage object.
setRefToMessage
public void setRefToMessage(EbxmlMessage refToMessage)

Set the EbxmlMessage being referred to by the error message.

Parameters:
  • refToMessageEbxmlMessage object to be referred to.

HeaderValidator

public class HeaderValidator

Class for validating the header of an ebXML message. EbxmlValidationException will be thrown in case of error.

Author:Frankie Lam

Methods

validate
public void validate(EbxmlMessage ebxmlMessage)

Validate the header of an ebXML message.

Parameters:
  • ebxmlMessage – The header of the EbxmlMessage object to be validated.
validatePartyId
protected void validatePartyId(Iterator partyIds)

Validates the list of party IDs. The following rules are enforced:

  • Attribute “type” MUST be unique within the list of party IDs.
  • The party ID without the “type” attribute MUST be a URI.
Parameters:
  • partyIds
validatePayload
protected void validatePayload(EbxmlMessage ebxmlMessage)

Validate payload. The following checks are applied: - All payload references with “cid:” as the prefix must exist. - All payload references must be a valid URI.

validateService
protected void validateService(String service, String serviceType)

Validate service element. The following rules are enforced: - Service attribute must be a URI in the absence of type attribute.

Parameters:
  • service
validateURI
protected boolean validateURI(String uri)

Check if a URI is valid.

Parameters:
  • uri – URI in string format to be validated.
Returns:

true if the URI is valid; false otherwise.

SOAPValidationException

public class SOAPValidationException extends ValidationException

Exception class that can generate SOAP fault messages from the information it has been given.

Author:Frankie Lam

Fields

ELEMENT_ERROR
static final String ELEMENT_ERROR

Error element to be embedded in the detail entries

NAMESPACE_PREFIX_CECID
static final String NAMESPACE_PREFIX_CECID

CECID namespace prefix

NAMESPACE_PREFIX_SOAP_ENVELOPE
static final String NAMESPACE_PREFIX_SOAP_ENVELOPE

SOAP Envelope namespace prefix.

NAMESPACE_URI_CECID
static final String NAMESPACE_URI_CECID

CECID Elements namespace

NAMESPACE_URI_SOAP_ENVELOPE
static final String NAMESPACE_URI_SOAP_ENVELOPE

SOAP Envelope namespace.

SOAP_FAULT_CLIENT
public static final String SOAP_FAULT_CLIENT

SOAP Fault code indicating a client fault that the message should not be resent without change.

SOAP_FAULT_MUST_UNDERSTAND
public static final String SOAP_FAULT_MUST_UNDERSTAND

SOAP Fault code indicating that the client cannot interpret an immediate child of the header element having mustUnderstand equals to “1”.

SOAP_FAULT_SERVER
public static final String SOAP_FAULT_SERVER

SOAP Fault code indicating a server fault that the message may succeed by resending at a later time.

SOAP_FAULT_VERSION_MISMATCH
public static final String SOAP_FAULT_VERSION_MISMATCH

SOAP Fault code indicating version mismatch.

detail
protected final String detail

SOAP Fault detail.

faultActor
protected final String faultActor

SOAP Fault Actor.

Constructors

SOAPValidationException
public SOAPValidationException(String faultCode, String faultString)

Constructs a SOAPValidationException object given its fault code and fault string.

Parameters:
  • faultCode – Fault codes as specified in the SOAP 1.1 specification
  • faultString – Human readable explanation of the fault.
SOAPValidationException
public SOAPValidationException(String faultCode, String faultString, String detail)

Constructs a SOAPValidationException object given its fault code and fault string.

Parameters:
  • faultCode – Fault codes as specified in the SOAP 1.1 specification
  • faultString – Human readable explanation of the fault.
  • detail – Specific error information related to the SOAP Body element. It must be present if the SOAP Body cannot be processed successfully, and must NOT be present if the error is caused by header entries.
SOAPValidationException
public SOAPValidationException(String faultCode, String faultString, String faultActor, String detail)

Constructs a SOAPValidationException object given its fault code and fault string.

Parameters:
  • faultCode – Fault codes as specified in the SOAP 1.1 specification
  • faultString – Human readable explanation of the fault.
  • faultActor – Information on who caused the fault to happen.
  • detail – Specific error information related to the SOAP Body element. It must be present if the SOAP Body cannot be processed successfully, and must NOT be present if the error is caused by header entries.

Methods

getSOAPMessage
public SOAPMessage getSOAPMessage()

Get SOAP Fault message from the information given.

Returns:SOAPMessage object containing Fault element.

ValidationException

public abstract class ValidationException extends SOAPException

Base class for message validation exceptions. All classes extending this class must be able to generate a SOAP message to indicate the error, but it is not necessary a SOAP Fault message (e.g. an ebXML message containing ErrorList element).

Author:Frankie Lam

Fields

ERROR_EBXML
public static final int ERROR_EBXML

The error represented by this exception is caused by an incorrectly packaged ebXML message.

ERROR_SOAP
public static final int ERROR_SOAP

The error represented by this exception is a SOAP Fault

ERROR_UNKNOWN
public static final int ERROR_UNKNOWN

The error represented by this exception is unknown.

errorCode
protected final String errorCode

Error code.

errorString
protected final String errorString

A string describing the error occurred.

errorType
protected final int errorType

The type of error represented by this exception object.

Constructors

ValidationException
public ValidationException(int errorType, String errorCode, String errorString)

Constructs a ValidationException object.

Parameters:
  • errorType – The type of error represented by this exception object.
  • errorCode – An error code in string to be processed by the applications.
  • errorString – A human-readable description string.

Methods

getSOAPMessage
public abstract SOAPMessage getSOAPMessage()

Get the SOAP message containing the error information.

Returns:SOAPMessage object containing the error information.

hk.hku.cecid.ebms.service

EbmsMessageStatusQueryService

public class EbmsMessageStatusQueryService extends WebServicesAdaptor

EbmsMessageStatusQueryService

Author:Donahue Sze

Methods

isCacheEnabled
protected boolean isCacheEnabled()
replaceNullToEmpty
public String replaceNullToEmpty(String value)
serviceRequested
public void serviceRequested(WebServicesRequest request, WebServicesResponse response)

hk.hku.cecid.ebms.spa

EbmsProcessor

public class EbmsProcessor implements PluginHandler
Author:Donahue Sze

Fields

ACTIVE_MODULE_INBOX_COLLECTOR
public static String ACTIVE_MODULE_INBOX_COLLECTOR

Inbox collector active task module ID name

ACTIVE_MODULE_MAIL_COLLECTOR
public static String ACTIVE_MODULE_MAIL_COLLECTOR

POP mail collector active task module ID name

ACTIVE_MODULE_OUTBOX_COLLECTOR
public static String ACTIVE_MODULE_OUTBOX_COLLECTOR

Outbox collector active task module ID name

core
public static SystemModule core

Methods

getKeyStoreManagerForDecryption
public static KeyStoreManager getKeyStoreManagerForDecryption()
getKeyStoreManagerForSignature
public static KeyStoreManager getKeyStoreManagerForSignature()
getModuleGroup
public static ModuleGroup getModuleGroup()
Returns:the Ebms module group
processActivation
public void processActivation(Plugin plugin)
processDeactivation
public void processDeactivation(Plugin arg0)

EbmsUtility

public class EbmsUtility

An utility for converting from java datetime to UTC conformed datetime and vice versa.

  1. Fixed a bug that it parses UTC datetime with ‘Z’ timezone incorrectly becasue it used wrong timezone (GMT, but not UTC). (Thank Martin Kalen for figure out this)
  2. Added datetime / calendar two UTC convertion.
Author:Twinsen Tsang, (modifier Philip Wong)

Methods

GMT2Calender
public static Calendar GMT2Calender(String dateTime)

Convert an GMT representation of string dateTime to java calendar object.

Parameters:
  • dateTime – A string representing a GMT datetime.
Throws:
Returns:

The millisecond representing the dateTime

GMT2Date
public static Date GMT2Date(String dateTime)

Convert an GMT representation of string dateTime to java Date object.

Parameters:
  • dateTime – A string representing a GMT datetime.
Throws:
Returns:

A java date object representing the dateTime

GMT2MS
public static long GMT2MS(String dateTime)

Convert an GMT representation of string dateTime to millisecond.

Parameters:
  • dateTime – A string representing a GMT datetime.
Throws:
Returns:

The millisecond representing the dateTime

GMT2Timestamp
public static Timestamp GMT2Timestamp(String dateTime)

Convert an GMT representation of string dateTime to java Timestamp object.

Parameters:
  • dateTime – A string representing a GMT datetime.
Throws:
Returns:

A java timestamp object representing the dateTime

UTC2Calendar
public static Calendar UTC2Calendar(String dateTime)

Convert an UTC representation of string dateTime to java calendar object. Followings are UTC conformed patterns:

  • 2007-07-16T13:24:56
  • 2007-07-16T13:24:56Z
  • 2007-07-16T13:24:56.789
  • 2007-07-16T13:24:56.789Z
  • 2007-07-16T13:24:56+02:00
  • 2007-07-16T13:24:56-02:00
  • 2007-07-16T13:24:56.789+02:00
  • 2007-07-16T13:24:56.789-02:00
Parameters:
  • dateTime – A string representing a UTC datetime.
Throws:
Returns:

A java clendar object representing the dateTime

UTC2Date
public static Date UTC2Date(String dateTime)

Convert an UTC representation of string dateTime to java Date object. Followings are UTC conformed patterns:

  • 2007-07-16T13:24:56
  • 2007-07-16T13:24:56Z
  • 2007-07-16T13:24:56.789
  • 2007-07-16T13:24:56.789Z
  • 2007-07-16T13:24:56+02:00
  • 2007-07-16T13:24:56-02:00
  • 2007-07-16T13:24:56.789+02:00
  • 2007-07-16T13:24:56.789-02:00
Parameters:
  • dateTime – A string representing a UTC datetime.
Throws:
Returns:

A java date object representing the dateTime.

UTC2MS
public static long UTC2MS(String dateTime)

Convert an UTC representation of string dateTime to millisecond. Followings are UTC conformed patterns:

  • 2007-07-16T13:24:56
  • 2007-07-16T13:24:56Z
  • 2007-07-16T13:24:56.789
  • 2007-07-16T13:24:56.789Z
  • 2007-07-16T13:24:56+02:00
  • 2007-07-16T13:24:56-02:00
  • 2007-07-16T13:24:56.789+02:00
  • 2007-07-16T13:24:56.789-02:00
Parameters:
  • dateTime – A string representing a UTC datetime.
Throws:
Returns:

The millisecond representing by dateTime.

UTC2Timestamp
public static Timestamp UTC2Timestamp(String dateTime)

Convert an UTC representation of string dateTime to java Timestamp object. Followings are UTC conformed patterns:

  • 2007-07-16T13:24:56
  • 2007-07-16T13:24:56Z
  • 2007-07-16T13:24:56.789
  • 2007-07-16T13:24:56.789Z
  • 2007-07-16T13:24:56+02:00
  • 2007-07-16T13:24:56-02:00
  • 2007-07-16T13:24:56.789+02:00
  • 2007-07-16T13:24:56.789-02:00
Parameters:
  • dateTime – A string representing a UTC datetime.
Throws:
Returns:

A java timestamp object representing the dateTime.

calendar2UTC
public static String calendar2UTC(Calendar dateTime)

Convert a calendar dateTime to UTC conformed representation of string.

Parameters:
  • dateTime – A java calendar representing the time you want to convert.
Throws:
Returns:

an UTC conformed representation with time specified by dateTime

date2UTC
public static String date2UTC(Date dateTime, TimeZone timeZone)

Convert a date dateTime to UTC conformed representation of string. (e.g. 2007-07-16T13:24:56.789+13:00)

Parameters:
  • dateTime – A java date representing the time you want to convert.
  • timeZone – The timezone of the dateTime. If it is null, it use the default timezone in the machine.
Throws:
Returns:

an UTC conformed representation with time specified by dateTime

getCurrentUTCDateTime
public static String getCurrentUTCDateTime()
Returns:Get the current datetime with respect to the default timezone in UTC conformed representation.

EbmsUtilityTest

public class EbmsUtilityTest extends TestCase

The EbmsUtilityTest is the testcase for EbmsUtility.

Author:Twinsen Tsang

Methods

getLocalTimezone
public String getLocalTimezone()

Get the local timezone represenetation from the UTC. The returned format is “GMT+hh:mm”. For example, if you are located in Asia/Hong Kong, the returned string should be “GMT+08:00”.

setUp
public void setUp()
tearDown
public void tearDown()
testDate2UTC_Pos0
public void testDate2UTC_Pos0()

Test for converting from a java date object to UTC conformed representation string. Testing for the scenario the dateTime is represented as java calendar and under the timezone same as the machine running.

testDate2UTC_Pos1
public void testDate2UTC_Pos1()

Test for converting from a java date object to UTC conformed representation string. Testing for the scenario the dateTime is represented as java calendar and under the timezone under UTC.

testDate2UTC_Pos2
public void testDate2UTC_Pos2()

Test for converting from a java date object to UTC conformed representation string. Testing for the scenario the dateTime is represented as java calendar and under the timezone under GMT-12:00 (boundary case)

testDate2UTC_Pos3
public void testDate2UTC_Pos3()

Test for converting from a java date object to UTC conformed representation string. Testing for the scenario the dateTime is represented as java calendar and under the timezone under GMT+13:00 (boundary case)

testGMT2Date_Pos0
public void testGMT2Date_Pos0()

Test for converting from GMT datetime representation to java date object.

testGetCurrentUTCDateTime_Pos0
public void testGetCurrentUTCDateTime_Pos0()
Throws:
testMartinKalenIssue1
public void testMartinKalenIssue1()

Test for the scenario issued by Martin Kalen from the google group. QUOTED FROM martin said:

Hermes sends ebMS ACK messages with a non-standard timezone part of
the timestamp (timezone info is not according to ebXML-specification,
see background below)

Background on #1:
The recent fix for Hermes UTC timestamps uses the Java
SimpleDateFormat "Z"-pattern for timezone, which is unfortunately
incompatible with the ebXML specification for time zone refering to
the XML schema data-type "dateTime" specified here:
http://www.w3.org/TR/xmlschema-2/#dateTime

Snippets from the spec:
"dateTime consists of finite-length sequences of characters of the
form: '-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)?
(zzzzzz)?"
"zzzzzz (if present) represents the timezone"

From 3.2.7.3 Timezones The lexical representation of a timezone is a string of the form:
(('+' | '-') hh ':' mm) | 'Z'"
In Java the ':' character is missing between the "hh" and "mm" parts.
More details on the Java SimpleDateFormat vs XSD dateTime
incompatibility can be found here:

Detail: http://groups.google.com/group/cecid-hermes2/browse_thread/thread/46cca8b51ca21524

testMartinKalenIssue2
public void testMartinKalenIssue2()

Test for the scenario issued by Martin Kalen from the google group.

   I live in the UTC+02:00 timezone and today at 14:01 my time (=12:01
UTC time) an incoming ebXML message with the following TTL timestamp
was considered expired by Hermes: "2007-07-10T12:04:14Z".
Without the change in EbmsUtility above, Hermes regards the incoming
timestamp as 12:04 in my timezone which mutates the expected
12:04:14UTC to 10:04:14UTC = incorrect expiry notification to the
sender.

Detail: http://groups.google.com/group/cecid-hermes2/browse_thread/thread/46cca8b51ca21524

testUTC2Calendar_Neg0
public void testUTC2Calendar_Neg0()

Test the conversation from UTC to java calendar object negatively. Testing for the scenario all invalid UTC format representation.

testUTC2Calendar_Pos0
public void testUTC2Calendar_Pos0()

Test the conversation from UTC to java calendar object. Testing for the scenario the dateTime is represented as UTC and under the timezone in UTC (GMT+00:00) using ‘Z’ designator.

testUTC2Calendar_Pos1
public void testUTC2Calendar_Pos1()

Test the conversation from UTC to java calendar object. Testing for the scenario the dateTime is represented as UTC and under the timezone in UTC (GMT+00:00) using +00:00

testUTC2Calendar_Pos2
public void testUTC2Calendar_Pos2()

Test the conversation from UTC to java calendar object. Testing for the scenario the dateTime is represented as UTC and under the timezone GMT+08:00 (non zero timezone)

testUTC2Calendar_Pos3
public void testUTC2Calendar_Pos3()

Test the conversation from UTC to java calendar object. Testing for the scenario the dateTime is represented as UTC and under the timezone GMT+13:00 (boundary case)

testUTC2Calendar_Pos4
public void testUTC2Calendar_Pos4()

Test the conversation from UTC to java calendar object. Testing for the scenario the dateTime is represented as UTC and under the timezone GMT-12:00 (boundary case)

testUTC2Calendar_Pos5
public void testUTC2Calendar_Pos5()

Test the conversation from UTC to java calendar object. Testing for the scenario the dateTime is represented as UTC without millisecond and under the timezone UTC.

testUTC2Calendar_Pos6
public void testUTC2Calendar_Pos6()

Test the conversation from UTC to java calendar object. Testing for the scenario the dateTime is represented as UTC without millisecond and under any timezone other than UTC.

testUTC2Calendar_Pos7
public void testUTC2Calendar_Pos7()

Test the conversation from UTC to java calendar object. Testing for the scenario the dateTime is represented as UTC without millisecond and ‘Z’ and under any timezone other than UTC.

testUTC2Calendar_Pos8
public void testUTC2Calendar_Pos8()

Test the conversation from UTC to java calendar object. Testing for the scenario the dateTime is represented as UTC with ‘Z’ and under any timezone other than UTC.

validateCalendar
public void validateCalendar(Calendar cal, int expectedYear, int expectedMonth, int expectedDay, int expectedHour, int expectedMins, int expectedSecond, int expectedMillisecond, String expectedTz)

A common method to validate cirtical field for specified cal

Parameters:
  • cal – The calendar to test against.
  • expectedYear – The expected year.
  • expectedMonth – The expected month.
  • expectedDay – The expected day.
  • expectedHour – The expected hour.
  • expectedMins – The expected mins.
  • expectedSecond – The expected second.
  • expectedMillisecond – The expected millisecond.
  • expectedTz – The expected timezone.
validateCalendar
public void validateCalendar(Calendar target, Calendar control)

A common method to validate cirtical field for specified target by the value in the calendar control.

Parameters:
  • target – The target calendar to test for.
  • control – The reference calendar to test for.

hk.hku.cecid.ebms.spa.dao

InboxDAO

public interface InboxDAO extends DAO
Author:Donahue Sze

Methods

addInbox
public void addInbox(InboxDVO data)
deleteInbox
public void deleteInbox(InboxDVO data)
findInbox
public boolean findInbox(InboxDVO data)
findInboxNextOrderNo
public long findInboxNextOrderNo()

Returns next value of inbox order no. from DB sequence. it determines message order being retrieved by client.

Returns:the value of next inbox order no.
updateInbox
public boolean updateInbox(InboxDVO data)

InboxDVO

public interface InboxDVO extends DVO
Author:Donahue Sze

Methods

getMessageId
public String getMessageId()
Returns:Returns the ackRequested.
getOrderNo
public long getOrderNo()
setMessageId
public void setMessageId(String messageId)
Parameters:
  • messageId – The messageId to set.
setOrderNo
public void setOrderNo(long orderNo)

InboxDataSourceDAO

public class InboxDataSourceDAO extends DataSourceDAO implements InboxDAO
Author:Donahue Sze Window - Preferences - Java - Code Style - Code Templates

Methods

addInbox
public void addInbox(InboxDVO data)
createDVO
public DVO createDVO()
deleteInbox
public void deleteInbox(InboxDVO data)
findInbox
public boolean findInbox(InboxDVO data)
findInboxNextOrderNo
public long findInboxNextOrderNo()

Returns next value of inbox order no. from DB sequence. it determines message order being retrieved by client. For DB, PostgreSQL & Oracle built-in auto number (sequence) will be used. Otherwise for mySQL, max(order_no) + 1 will be returned. Default starting order no is 1.

Returns:the value of next inbox order no.
updateInbox
public boolean updateInbox(InboxDVO data)

InboxDataSourceDAOTest

public class InboxDataSourceDAOTest extends DAOTest<InboxDataSourceDAO>

Methods

getTableName
public String getTableName()
testFindInboxNextOrderNo
public void testFindInboxNextOrderNo()

InboxDataSourceDVO

public class InboxDataSourceDVO extends DataSourceDVO implements InboxDVO
Author:Donahue Sze Window - Preferences - Java - Code Style - Code Templates

Constructors

InboxDataSourceDVO
public InboxDataSourceDVO()

Methods

getMessageId
public String getMessageId()
getOrderNo
public long getOrderNo()
setMessageId
public void setMessageId(String messageId)
setOrderNo
public void setOrderNo(long orderNo)

MessageDAO

public interface MessageDAO extends DAO
Author:Donahue Sze, Twinsen Tsang (modifiers)

Methods

addMessage
public void addMessage(MessageDVO data)
deleteMessage
public void deleteMessage(MessageDVO data)
findInboxPendingMessagesByTimestamp
public List findInboxPendingMessagesByTimestamp(MessageDVO messageDVO)
findInboxReadyMaxSequenceNoByCpa
public int findInboxReadyMaxSequenceNoByCpa(MessageDVO data)
findMaxSequenceGroupByMessageBoxAndCpa
public int findMaxSequenceGroupByMessageBoxAndCpa(MessageDVO data)
findMaxSequenceNoByMessageBoxAndCpa
public int findMaxSequenceNoByMessageBoxAndCpa(MessageDVO data)
findMessage
public boolean findMessage(MessageDVO data)
findMessageByCpa
public List findMessageByCpa(MessageDVO data, int numberOfMessage)
findMessagesBeforeTime
public List findMessagesBeforeTime(int time_period)
findMessagesByHistory
public List findMessagesByHistory(MessageDVO data, int numberOfMessage, int offset)
findMessagesByTime
public List findMessagesByTime(int time_period, MessageDVO data, int numberOfMessage, int offset)
findNumOfMessagesByMessageBoxAndCpaAndSequenceGroup
public int findNumOfMessagesByMessageBoxAndCpaAndSequenceGroup(MessageDVO data)
findNumberOfMessagesByHistory
public int findNumberOfMessagesByHistory(MessageDVO data)
findOrderedMessageByMessageBoxAndCpaAndSequenceGroupAndSequenceNo
public boolean findOrderedMessageByMessageBoxAndCpaAndSequenceGroupAndSequenceNo(MessageDVO data)
findOrderedMessagesByMessageBoxAndCpaAndStatus
public List findOrderedMessagesByMessageBoxAndCpaAndStatus(MessageDVO data)
findOutboxPendingMessagesByTimestamp
public List findOutboxPendingMessagesByTimestamp(MessageDVO messageDVO)
findOutboxProcessingMessagesByTimestamp
public List findOutboxProcessingMessagesByTimestamp(MessageDVO messageDVO)
findRefToMessage
public boolean findRefToMessage(MessageDVO data)
updateMessage
public boolean updateMessage(MessageDVO data)
updateTimedOutMessageStatus
public int updateTimedOutMessageStatus(String status, Date currentTime)

Update the status of all timed-out message to status. A message is considered as timed-out if the timeout timestamp is earlier than the currentTime.

Throws:
  • DAOException – When status is null or Error in persistence connectivity.

See also: hk.hku.cecid.ebms.spa.dao.MessageDVO.getTimeoutTimestamp(), hk.hku.cecid.ebms.spa.dao.MessageDVO.setTimeoutTimestamp(java.sql.Timestamp)

MessageDVO

public interface MessageDVO extends DVO

The MessageDataSourceDVO is a implementation of interface MesageDVO and representing one persistence record in the table message.

Author:Donahue Sze, Twinsen Tsang (modifier)

Methods

getAckRequested
public String getAckRequested()
Returns:Returns the ackRequested.
getAckSignRequested
public String getAckSignRequested()
getAction
public String getAction()
Returns:Returns the action.
getConvId
public String getConvId()
Returns:Returns the convId.
getCpaId
public String getCpaId()
Returns:Returns the cpaId.
getDupElimination
public String getDupElimination()
Returns:Returns the dupElimination.
getFromPartyId
public String getFromPartyId()
Returns:Returns the fromPartyId.
getFromPartyRole
public String getFromPartyRole()
Returns:Returns the fromPartyRole.
getHasResendAsNew
public String getHasResendAsNew()
Returns:“true” if message has triggered “Resend as New”, “false” if otherwise.
getMessageBox
public String getMessageBox()
Returns:Returns the messageType.
getMessageId
public String getMessageId()
Returns:Returns the messageId.
getMessageType
public String getMessageType()
Returns:Returns the messageType.
getPartnershipId
public String getPartnershipId()
getPrimalMessageId
public String getPrimalMessageId()
Returns:String primalMessageId refer to the message that triggered “Resend as New”
getPrincipalId
public String getPrincipalId()
Returns:Returns the principal id of this message.
getRefToMessageId
public String getRefToMessageId()
Returns:Returns the refToMessageId.
getSequenceGroup
public int getSequenceGroup()
getSequenceNo
public int getSequenceNo()
Returns:Returns the sequenceNo.
getSequenceStatus
public int getSequenceStatus()
getService
public String getService()
Returns:Returns the service.
getStatus
public String getStatus()
Returns:Returns the status.
getStatusDescription
public String getStatusDescription()
getSyncReply
public String getSyncReply()
Returns:Return whether the response EbMS message should be included in same SOAP connection.
getTimeStamp
public Timestamp getTimeStamp()
Returns:Returns the timeStamp.
getTimeToLive
public Timestamp getTimeToLive()
Returns:Returns the timeToLive.
getTimeoutTimestamp
public Timestamp getTimeoutTimestamp()
Returns:Returns the timeout timestamp for this message. return null if the message does not requires acknowledgment.
getToPartyId
public String getToPartyId()
Returns:Returns the toPartyId.
getToPartyRole
public String getToPartyRole()
Returns:Returns the toPartyRole.
setAckRequested
public void setAckRequested(String ackRequested)
Parameters:
  • ackRequested – The ackRequested to set.
setAckSignRequested
public void setAckSignRequested(String ackSignRequested)
setAction
public void setAction(String action)
Parameters:
  • action – The action to set.
setConvId
public void setConvId(String convId)
Parameters:
  • convId – The convId to set.
setCpaId
public void setCpaId(String cpaId)
Parameters:
  • cpaId – The cpaId to set.
setDupElimination
public void setDupElimination(String dupElimination)
Parameters:
  • dupElimination – The dupElimination to set.
setFromPartyId
public void setFromPartyId(String fromPartyId)
Parameters:
  • fromPartyId – The fromPartyId to set.
setFromPartyRole
public void setFromPartyRole(String fromPartyRole)
Parameters:
  • fromPartyRole – The fromPartyRole to set.
setHasResendAsNew
public void setHasResendAsNew(String hasResendAsNew)
Parameters:
  • hasResendAsNew – Set to “true” if message has triggered “Resend as New”, “false” if otherwise
setMessageBox
public void setMessageBox(String messageBox)
Parameters:
  • messageBox – The messageBox to set.
setMessageId
public void setMessageId(String messageId)
Parameters:
  • messageId – The messageId to set.
setMessageType
public void setMessageType(String messageType)
Parameters:
  • messageType – The messageType to set.
setPartnershipId
public void setPartnershipId(String partnershipId)
setPrimalMessageId
public void setPrimalMessageId(String primalMessageId)

Set the primalMessageID which represent the message triggered “Resend as New”

Parameters:
  • primalMessageId
setPrincipalId
public void setPrincipalId(String principalId)
Parameters:
  • principalId – The principalId to set.
setRefToMessageId
public void setRefToMessageId(String refToMessageId)
Parameters:
  • refToMessageId – The refToMessageId to set.
setSequenceGroup
public void setSequenceGroup(int sequenceGroup)
setSequenceNo
public void setSequenceNo(int sequenceNo)
Parameters:
  • sequenceNo – The sequenceNo to set.
setSequenceStatus
public void setSequenceStatus(int sequenceStatus)
setService
public void setService(String service)
Parameters:
  • service – The service to set.
setStatus
public void setStatus(String status)
Parameters:
  • status – The status to set.
setStatusDescription
public void setStatusDescription(String statusDescription)
setSyncReply
public void setSyncReply(String syncReply)

The available syncReply option in EbMS are listed below:

  1. mshSignalsOnly (same connection reply)
  2. none (different connection reply)
Parameters:
  • syncReply – The syncReply option for this message.
setTimeStamp
public void setTimeStamp(Timestamp timeStamp)
Parameters:
  • timeStamp – The timeStamp to set.
setTimeToLive
public void setTimeToLive(Timestamp timeToLive)
Parameters:
  • timeToLive – The timeToLive to set.
setTimeoutTimestamp
public void setTimeoutTimestamp(Timestamp timeoutTimestamp)
Parameters:
  • timeoutTimestamp – The timeout timestamp for this message.
setToPartyId
public void setToPartyId(String toPartyId)
Parameters:
  • toPartyId – The toPartyId to set.
setToPartyRole
public void setToPartyRole(String toPartyRole)
Parameters:
  • toPartyRole – The toPartyRole to set.

MessageDataSourceDAO

public class MessageDataSourceDAO extends DataSourceDAO implements MessageDAO
Author:Donahue Sze Window - Preferences - Java - Code Style - Code Templates

Methods

addMessage
public void addMessage(MessageDVO data)
createDVO
public DVO createDVO()
deleteMessage
public void deleteMessage(MessageDVO data)
findInboxPendingMessagesByTimestamp
public List findInboxPendingMessagesByTimestamp(MessageDVO data)

Find all the pending messages for inbox collector order by timestamp.

Parameters:
  • data – The message data value object.
Throws:
  • DAOException – if errors found when retrieving data from the data source.
Returns:

a List of DVO resulted from the specified SQL query. An empty List will be returned if there is no matching data.

findInboxReadyMaxSequenceNoByCpa
public int findInboxReadyMaxSequenceNoByCpa(MessageDVO data)

Find max sequence no. of inbox message in PS or DL status by CPA Only for EbMS Inbox Collector Service

Parameters:
  • data – The message data value object.
Throws:
  • DAOException – if errors found when retrieving data from the data source.
Returns:

max sequence no. -1 will be returned if there is no matching data.

findMaxSequenceGroupByMessageBoxAndCpa
public int findMaxSequenceGroupByMessageBoxAndCpa(MessageDVO data)
findMaxSequenceNoByMessageBoxAndCpa
public int findMaxSequenceNoByMessageBoxAndCpa(MessageDVO data)

Find max sequence no. of message by CPA and message box

Parameters:
  • data – The message data value object.
Throws:
  • DAOException – if errors found when retrieving data from the data source.
Returns:

max sequence no. -1 will be returned if there is no matching data.

findMessage
public boolean findMessage(MessageDVO data)
findMessageByCpa
public List findMessageByCpa(MessageDVO data, int numberOfMessage)

Find all the message by CPA, status, message type and message box. Only for EbMS Message Collector Service

Parameters:
  • data – The message data value object.
  • numberOfMessage – The no. of message return.
Throws:
  • DAOException – if errors found when retrieving data from the data source.
Returns:

a List of DVO resulted from the specified SQL query. An empty List will be returned if there is no matching data.

findMessagesBeforeTime
public List findMessagesBeforeTime(int time_period)
findMessagesByHistory
public List findMessagesByHistory(MessageDVO data, int numberOfMessage, int offset)

Find messages order by descending timestamp by different criteria.

Parameters:
  • data – The message data value object carrying query criteria.
  • numberOfMessage – max no. of message in return.
  • offset – no. of starting record in return.
Throws:
findMessagesByTime
public List findMessagesByTime(int time_period, MessageDVO data, int numberOfMessage, int offset)
findNumOfMessagesByMessageBoxAndCpaAndSequenceGroup
public int findNumOfMessagesByMessageBoxAndCpaAndSequenceGroup(MessageDVO data)
findNumberOfMessagesByHistory
public int findNumberOfMessagesByHistory(MessageDVO data)

Find number of messages by different criteria.

Parameters:
  • data – The message data value object carrying query criteria.
Throws:
findOrderedMessageByMessageBoxAndCpaAndSequenceGroupAndSequenceNo
public boolean findOrderedMessageByMessageBoxAndCpaAndSequenceGroupAndSequenceNo(MessageDVO data)
findOrderedMessagesByMessageBoxAndCpaAndStatus
public List findOrderedMessagesByMessageBoxAndCpaAndStatus(MessageDVO data)
findOutboxPendingMessagesByTimestamp
public List findOutboxPendingMessagesByTimestamp(MessageDVO data)

Find all the pending messages for outbox collector order by timestamp.

Parameters:
  • data – The message data value object.
Throws:
  • DAOException – if errors found when retrieving data from the data source.
Returns:

a List of DVO resulted from the specified SQL query. An empty List will be returned if there is no matching data.

findOutboxProcessingMessagesByTimestamp
public List findOutboxProcessingMessagesByTimestamp(MessageDVO data)

Find all the processing messages for outbox collector order by timestamp.

Parameters:
  • data – The message data value object.
Throws:
  • DAOException – if errors found when retrieving data from the data source.
Returns:

a List of DVO resulted from the specified SQL query. An empty List will be returned if there is no matching data.

findRefToMessage
public boolean findRefToMessage(MessageDVO data)
updateMessage
public boolean updateMessage(MessageDVO data)
updateTimedOutMessageStatus
public int updateTimedOutMessageStatus(String status, Date currentTime)

Update the status of all timed-out message to status. A message is considered as timed-out if the timeout timestamp is earlier than the currentTime.

Throws:
  • DAOException – When status is null or Error in persistence connectivity.

See also: hk.hku.cecid.ebms.spa.dao.MessageDVO.getTimeoutTimestamp(), hk.hku.cecid.ebms.spa.dao.MessageDVO.setTimeoutTimestamp(java.sql.Timestamp)

MessageDataSourceDAOTest

public class MessageDataSourceDAOTest extends DAOTest<MessageDataSourceDAO>

Methods

getTableName
public String getTableName()
testFindInboxReadyMaxSequenceNoByCpa
public void testFindInboxReadyMaxSequenceNoByCpa()
testFindMessageByCpa
public void testFindMessageByCpa()
testFindMessagesByHistory
public void testFindMessagesByHistory()
testFindNumberOFMessagesByHistory
public void testFindNumberOFMessagesByHistory()

MessageDataSourceDVO

public class MessageDataSourceDVO extends DataSourceDVO implements MessageDVO

The MessageDataSourceDVO is a implementation of interface MesageDVO and representing one persistence record in the table message.

Author:Donahue Sze, Twinsen Tsang (modifier)

Constructors

MessageDataSourceDVO
public MessageDataSourceDVO()

Methods

getAckRequested
public String getAckRequested()
Returns:Returns the ackRequested.
getAckSignRequested
public String getAckSignRequested()
Returns:String
getAction
public String getAction()
Returns:Returns the action.
getConvId
public String getConvId()
Returns:Returns the conversation id of the message record.
getCpaId
public String getCpaId()
Returns:Returns the cpaId.
getDupElimination
public String getDupElimination()
Returns:Returns the dupElimination.
getFromPartyId
public String getFromPartyId()
Returns:Returns the fromPartyId.
getFromPartyRole
public String getFromPartyRole()
Returns:Returns the fromPartyRole.
getHasResendAsNew
public String getHasResendAsNew()
Returns:“true” if message has triggered “Resend as New”, “false” if otherwise
getMessageBox
public String getMessageBox()
Returns:Returns the messageType.
getMessageId
public String getMessageId()
Returns:Returns the messageId.
getMessageType
public String getMessageType()
Returns:Returns the messageType.
getPartnershipId
public String getPartnershipId()
getPrimalMessageId
public String getPrimalMessageId()
Returns:The primalMessageID which represent the message triggered “Resend as New”
getPrincipalId
public String getPrincipalId()
Returns:Returns the principalId.
getRefToMessageId
public String getRefToMessageId()
Returns:Returns the refToMessageId.
getSequenceGroup
public int getSequenceGroup()
Returns:Returns the sequenceGroup.
getSequenceNo
public int getSequenceNo()
Returns:Returns the sequenceNo.
getSequenceStatus
public int getSequenceStatus()
getService
public String getService()
Returns:Returns the service.
getStatus
public String getStatus()
Returns:Returns the status.
getStatusDescription
public String getStatusDescription()
getSyncReply
public String getSyncReply()
Returns:Return whether the response EbMS message should be included in same SOAP connection.
getTimeStamp
public Timestamp getTimeStamp()
Returns:Returns the timeStamp.
getTimeToLive
public Timestamp getTimeToLive()
Returns:Returns the timeToLive.
getTimeoutTimestamp
public Timestamp getTimeoutTimestamp()
Returns:Returns the timeout timestamp for this message. return null if the message does not requires acknowledgment.
getToPartyId
public String getToPartyId()
Returns:Returns the toPartyId.
getToPartyRole
public String getToPartyRole()
Returns:Returns the toPartyRole.
setAckRequested
public void setAckRequested(String ackRequested)
Parameters:
  • ackRequested – The ackRequested to set.
setAckSignRequested
public void setAckSignRequested(String ackSignRequested)
Parameters:
  • ackSignRequested
setAction
public void setAction(String action)
Parameters:
  • action – The action to set.
setConvId
public void setConvId(String convId)
Parameters:
  • convId – The coversation id of this message record.
setCpaId
public void setCpaId(String cpaId)
Parameters:
  • cpaId – The cpaId to set.
setDupElimination
public void setDupElimination(String dupElimination)
Parameters:
  • dupElimination – The dupElimination to set.
setFromPartyId
public void setFromPartyId(String fromPartyId)
Parameters:
  • fromPartyId – The fromPartyId to set.
setFromPartyRole
public void setFromPartyRole(String fromPartyRole)
Parameters:
  • fromPartyRole – The fromPartyRole to set.
setHasResendAsNew
public void setHasResendAsNew(String hasResendAsNew)
Parameters:
  • hasResendAsNew – Set to “true” if message has triggered “Resend as New”, “false” if otherwise
setMessageBox
public void setMessageBox(String messageBox)
Parameters:
  • messageBox – The messageBox to set.
setMessageId
public void setMessageId(String messageId)
Parameters:
  • messageId – The messageId to set.
setMessageType
public void setMessageType(String messageType)
Parameters:
  • messageType – The messageType to set.
setPartnershipId
public void setPartnershipId(String partnershipId)
setPrimalMessageId
public void setPrimalMessageId(String primalMessageId)

Set the primalMessageID which represent the message triggered “Resend as New”

Parameters:
  • primalMessageId
setPrincipalId
public void setPrincipalId(String principalId)
Parameters:
  • principalId – The principalId to set.
setRefToMessageId
public void setRefToMessageId(String refToMessageId)
Parameters:
  • refToMessageId – The refToMessageId to set.
setSequenceGroup
public void setSequenceGroup(int sequenceGroup)
Parameters:
  • sequenceGroup – The sequenceGroup to set.
setSequenceNo
public void setSequenceNo(int sequenceNo)
Parameters:
  • sequenceNo – The sequenceNo to set.
setSequenceStatus
public void setSequenceStatus(int sequenceStatus)
setService
public void setService(String service)
Parameters:
  • service – The service to set.
setStatus
public void setStatus(String status)
Parameters:
  • status – The status to set.
setStatusDescription
public void setStatusDescription(String statusDescription)
setSyncReply
public void setSyncReply(String syncReply)

The available syncReply option in EbMS are listed below:

  1. mshSignalsOnly (same connection reply)
  2. none (different connection reply)
Parameters:
  • syncReply – The syncReply option for this message.
setTimeStamp
public void setTimeStamp(Timestamp timeStamp)
Parameters:
  • timeStamp – The timeStamp to set.
setTimeToLive
public void setTimeToLive(Timestamp timeToLive)
Parameters:
  • timeToLive – The timeToLive to set.
setTimeoutTimestamp
public void setTimeoutTimestamp(Timestamp timeoutTimestamp)
Parameters:
  • timeoutTimestamp – The timeout timestamp for this message.
setToPartyId
public void setToPartyId(String toPartyId)
Parameters:
  • toPartyId – The toPartyId to set.
setToPartyRole
public void setToPartyRole(String toPartyRole)
Parameters:
  • toPartyRole – The toPartyRole to set.

MessageServerDAO

public interface MessageServerDAO extends DAO
Author:Donahue Sze

Methods

clearMessage
public void clearMessage(MessageDVO data)
storeMessage
public void storeMessage(MessageDVO messageDVO, RepositoryDVO repositoryDVO)
storeOutboxMessage
public void storeOutboxMessage(MessageDVO messageDVO, RepositoryDVO repositoryDVO, OutboxDVO outboxDVO, MessageDVO primalMsgDVO)

MessageServerDVO

public interface MessageServerDVO extends DVO
Author:Donahue Sze

MessageServerDataSourceDAO

public class MessageServerDataSourceDAO extends DataSourceDAO implements MessageServerDAO
Author:Donahue Sze

Methods

clearMessage
public void clearMessage(MessageDVO data)
createDVO
public DVO createDVO()
storeMessage
public void storeMessage(MessageDVO messageDVO, RepositoryDVO repositoryDVO)
storeOutboxMessage
public void storeOutboxMessage(MessageDVO messageDVO, RepositoryDVO repositoryDVO, OutboxDVO outboxDVO, MessageDVO primalMsgDVO)

MessageServerDataSourceDVO

public class MessageServerDataSourceDVO extends DataSourceDVO implements MessageServerDVO
Author:Donahue Sze

OutboxDAO

public interface OutboxDAO extends DAO
Author:Donahue Sze

Methods

addOutbox
public void addOutbox(OutboxDVO data)
deleteOutbox
public void deleteOutbox(OutboxDVO data)
findOutbox
public boolean findOutbox(OutboxDVO data)
selectOutbox
public List selectOutbox()
updateOutbox
public boolean updateOutbox(OutboxDVO data)

OutboxDVO

public interface OutboxDVO extends DVO
Author:Donahue Sze

Methods

getMessageId
public String getMessageId()
Returns:Returns the ackRequested.
getRetried
public int getRetried()
Returns:Returns the retried.
setMessageId
public void setMessageId(String messageId)
Parameters:
  • messageId – The messageId to set.
setRetried
public void setRetried(int retried)
Parameters:
  • retried – The retried to set.

OutboxDataSourceDAO

public class OutboxDataSourceDAO extends DataSourceDAO implements OutboxDAO
Author:Donahue Sze Window - Preferences - Java - Code Style - Code Templates

Methods

addOutbox
public void addOutbox(OutboxDVO data)
createDVO
public DVO createDVO()
deleteOutbox
public void deleteOutbox(OutboxDVO data)
findOutbox
public boolean findOutbox(OutboxDVO data)
selectOutbox
public List selectOutbox()
updateOutbox
public boolean updateOutbox(OutboxDVO data)

OutboxDataSourceDVO

public class OutboxDataSourceDVO extends DataSourceDVO implements OutboxDVO
Author:Donahue Sze Window - Preferences - Java - Code Style - Code Templates

Constructors

OutboxDataSourceDVO
public OutboxDataSourceDVO()

Methods

getMessageId
public String getMessageId()
getRetried
public int getRetried()
setMessageId
public void setMessageId(String messageId)
setRetried
public void setRetried(int retried)

PartnershipDAO

public interface PartnershipDAO extends DAO
Author:Donahue Sze

Methods

findAllPartnerships
public List findAllPartnerships()
findPartnershipByCPA
public boolean findPartnershipByCPA(PartnershipDVO data)
findPartnershipsByCPA
public List findPartnershipsByCPA(PartnershipDVO data)

PartnershipDVO

public interface PartnershipDVO extends DVO
Author:Donahue Sze

Methods

getAckRequested
public String getAckRequested()
getAckSignRequested
public String getAckSignRequested()
getAction
public String getAction()
Returns:Returns the action.
getActor
public String getActor()
getCpaId
public String getCpaId()
Returns:Returns the cpaId.
getDisabled
public String getDisabled()
Returns:Returns the disabled.
getDsAlgorithm
public String getDsAlgorithm()
getDupElimination
public String getDupElimination()
getEncryptAlgorithm
public String getEncryptAlgorithm()
getEncryptCert
public byte[] getEncryptCert()
getEncryptRequested
public String getEncryptRequested()
getIsHostnameVerified
public String getIsHostnameVerified()
getMdAlgorithm
public String getMdAlgorithm()
getMessageOrder
public String getMessageOrder()
Returns:Returns the messageOrder.
getPartnershipId
public String getPartnershipId()
Returns:Returns the channelId.
getPersistDuration
public String getPersistDuration()
Returns:Returns the persistDuration.
getPrincipalId
public String getPrincipalId()
Returns:Returns the principalId.
getRetries
public int getRetries()
Returns:Returns the retries.
getRetryInterval
public int getRetryInterval()
Returns:Returns the retryInterval.
getService
public String getService()
Returns:Returns the service.
getSignCert
public byte[] getSignCert()
getSignRequested
public String getSignRequested()
getSyncReplyMode
public String getSyncReplyMode()
Returns:Returns the syncReplyMode.
getTransportEndpoint
public String getTransportEndpoint()
Returns:Returns the transportEndpoint.
getTransportProtocol
public String getTransportProtocol()
Returns:Returns the transportProtocol.
setAckRequested
public void setAckRequested(String ackRequested)
setAckSignRequested
public void setAckSignRequested(String ackSignRequested)
setAction
public void setAction(String action)
Parameters:
  • action – The action to set.
setActor
public void setActor(String actor)
setCpaId
public void setCpaId(String cpaId)
Parameters:
  • cpaId – The cpaId to set.
setDisabled
public void setDisabled(String disabled)
Parameters:
  • disabled – The disabled to set.
setDsAlgorithm
public void setDsAlgorithm(String dsAlgorithm)
setDupElimination
public void setDupElimination(String dupElimination)
setEncryptAlgorithm
public void setEncryptAlgorithm(String encryptAlgorithm)
setEncryptCert
public void setEncryptCert(byte[] encryptCert)
setEncryptRequested
public void setEncryptRequested(String encryptRequested)
setIsHostnameVerified
public void setIsHostnameVerified(String isHostnameVerified)
setMdAlgorithm
public void setMdAlgorithm(String mdAlgorithm)
setMessageOrder
public void setMessageOrder(String messageOrder)
Parameters:
  • messageOrder – The messageOrder to set.
setPartnershipId
public void setPartnershipId(String partnershipId)
Parameters:
  • partnershipId – The partnershipId to set.
setPersistDuration
public void setPersistDuration(String persistDuration)
Parameters:
  • persistDuration – The persistDuration to set.
setPrincipalId
public void setPrincipalId(String principalId)
Parameters:
  • principalId – The principalId to set.
setRetries
public void setRetries(int retries)
Parameters:
  • retries – The retries to set.
setRetryInterval
public void setRetryInterval(int retryInterval)
Parameters:
  • retryInterval – The retryInterval to set.
setService
public void setService(String service)
Parameters:
  • service – The service to set.
setSignCert
public void setSignCert(byte[] signCert)
setSignRequested
public void setSignRequested(String signRequested)
setSyncReplyMode
public void setSyncReplyMode(String syncReplyMode)
Parameters:
  • syncReplyMode – The syncReplyMode to set.
setTransportEndpoint
public void setTransportEndpoint(String transportEndpoint)
Parameters:
  • transportEndpoint – The transportEndpoint to set.
setTransportProtocol
public void setTransportProtocol(String transportProtocol)
Parameters:
  • transportProtocol – The transportProtocol to set.

PartnershipDataSourceDAO

public class PartnershipDataSourceDAO extends DataSourceDAO implements PartnershipDAO
Author:Donahue Sze

Methods

createDVO
public DVO createDVO()
findAllPartnerships
public List findAllPartnerships()
findPartnershipByCPA
public boolean findPartnershipByCPA(PartnershipDVO data)
findPartnershipsByCPA
public List findPartnershipsByCPA(PartnershipDVO data)

PartnershipDataSourceDVO

public class PartnershipDataSourceDVO extends DataSourceDVO implements PartnershipDVO
Author:Donahue Sze

Constructors

PartnershipDataSourceDVO
public PartnershipDataSourceDVO()

Methods

getAckRequested
public String getAckRequested()
getAckSignRequested
public String getAckSignRequested()
getAction
public String getAction()
Returns:Returns the action.
getActor
public String getActor()
getCpaId
public String getCpaId()
Returns:Returns the cpaId.
getDisabled
public String getDisabled()
Returns:Returns the disabled.
getDsAlgorithm
public String getDsAlgorithm()
getDupElimination
public String getDupElimination()
getEncryptAlgorithm
public String getEncryptAlgorithm()
getEncryptCert
public byte[] getEncryptCert()
getEncryptRequested
public String getEncryptRequested()
getIsHostnameVerified
public String getIsHostnameVerified()
getMdAlgorithm
public String getMdAlgorithm()
getMessageOrder
public String getMessageOrder()
Returns:Returns the messageOrder.
getPartnershipId
public String getPartnershipId()
Returns:Returns the partnershipId.
getPersistDuration
public String getPersistDuration()
Returns:Returns the persistDuration.
getPrincipalId
public String getPrincipalId()
Returns:Returns the principalId.
getRetries
public int getRetries()
Returns:Returns the retries.
getRetryInterval
public int getRetryInterval()
Returns:Returns the retryInterval.
getService
public String getService()
Returns:Returns the service.
getSignCert
public byte[] getSignCert()
getSignRequested
public String getSignRequested()
getSyncReplyMode
public String getSyncReplyMode()
Returns:Returns the syncReplyMode.
getTransportEndpoint
public String getTransportEndpoint()
Returns:Returns the transportEndpoint.
getTransportProtocol
public String getTransportProtocol()
Returns:Returns the transportProtocol.
setAckRequested
public void setAckRequested(String ackRequested)
setAckSignRequested
public void setAckSignRequested(String ackSignRequested)
setAction
public void setAction(String action)
Parameters:
  • action – The action to set.
setActor
public void setActor(String actor)
setCpaId
public void setCpaId(String cpaId)
Parameters:
  • cpaId – The cpaId to set.
setDisabled
public void setDisabled(String disabled)
Parameters:
  • disabled – The disabled to set.
setDsAlgorithm
public void setDsAlgorithm(String dsAlgorithm)
setDupElimination
public void setDupElimination(String dupElimination)
setEncryptAlgorithm
public void setEncryptAlgorithm(String encryptAlgorithm)
setEncryptCert
public void setEncryptCert(byte[] encryptCert)
setEncryptRequested
public void setEncryptRequested(String encryptRequested)
setIsHostnameVerified
public void setIsHostnameVerified(String isHostnameVerified)
setMdAlgorithm
public void setMdAlgorithm(String mdAlgorithm)
setMessageOrder
public void setMessageOrder(String messageOrder)
Parameters:
  • messageOrder – The messageOrder to set.
setPartnershipId
public void setPartnershipId(String partnershipId)
Parameters:
  • partnershipId – The partnershipId to set.
setPersistDuration
public void setPersistDuration(String persistDuration)
Parameters:
  • persistDuration – The persistDuration to set.
setPrincipalId
public void setPrincipalId(String principalId)
Parameters:
  • principalId – The principalId to set.
setRetries
public void setRetries(int retries)
Parameters:
  • retries – The retries to set.
setRetryInterval
public void setRetryInterval(int retryInterval)
Parameters:
  • retryInterval – The retryInterval to set.
setService
public void setService(String service)
Parameters:
  • service – The service to set.
setSignCert
public void setSignCert(byte[] signCert)
setSignRequested
public void setSignRequested(String signRequested)
setSyncReplyMode
public void setSyncReplyMode(String syncReplyMode)
Parameters:
  • syncReplyMode – The syncReplyMode to set.
setTransportEndpoint
public void setTransportEndpoint(String transportEndpoint)
Parameters:
  • transportEndpoint – The transportEndpoint to set.
setTransportProtocol
public void setTransportProtocol(String transportProtocol)
Parameters:
  • transportProtocol – The transportProtocol to set.

RepositoryDAO

public interface RepositoryDAO extends DAO
Author:Donahue Sze

Methods

addRepository
public void addRepository(RepositoryDVO data)
deleteRepository
public void deleteRepository(RepositoryDVO data)
findRepository
public boolean findRepository(RepositoryDVO data)
updateRepository
public boolean updateRepository(RepositoryDVO data)

RepositoryDVO

public interface RepositoryDVO extends DVO
Author:Donahue Sze

Methods

getContent
public byte[] getContent()
Returns:Returns the content.
getContentType
public String getContentType()
getMessageBox
public String getMessageBox()
Returns:Returns the messageBox.
getMessageId
public String getMessageId()
Returns:Returns the messageId.
getTimeStamp
public Timestamp getTimeStamp()
Returns:Returns the timeStamp.
setContent
public void setContent(byte[] content)
Parameters:
  • content – The content to set.
setContent
public void setContent(InputStream is)
setContentType
public void setContentType(String contentType)
setMessageBox
public void setMessageBox(String messageBox)
Parameters:
  • messageBox – The messageBox to set.
setMessageId
public void setMessageId(String messageId)
Parameters:
  • messageId – The messageId to set.
setTimeStamp
public void setTimeStamp(Timestamp timeStamp)
Parameters:
  • timeStamp – The timeStamp to set.

RepositoryDataSourceDAO

public class RepositoryDataSourceDAO extends DataSourceDAO implements RepositoryDAO
Author:Donahue Sze Window - Preferences - Java - Code Style - Code Templates

Methods

addRepository
public void addRepository(RepositoryDVO data)
createDVO
public DVO createDVO()
deleteRepository
public void deleteRepository(RepositoryDVO data)
findRepository
public boolean findRepository(RepositoryDVO data)
updateRepository
public boolean updateRepository(RepositoryDVO data)

RepositoryDataSourceDVO

public class RepositoryDataSourceDVO extends DataSourceDVO implements RepositoryDVO
Author:Donahue Sze Window - Preferences - Java - Code Style - Code Templates

Constructors

RepositoryDataSourceDVO
public RepositoryDataSourceDVO()

Methods

getContent
public byte[] getContent()
getContentType
public String getContentType()
getMessageBox
public String getMessageBox()
Returns:Returns the messageBox.
getMessageId
public String getMessageId()
getTimeStamp
public Timestamp getTimeStamp()
Returns:Returns the timeStamp.
setContent
public void setContent(byte[] content)
setContent
public void setContent(InputStream is)
setContentType
public void setContentType(String contentType)
setMessageBox
public void setMessageBox(String messageBox)
Parameters:
  • messageBox – The messageBox to set.
setMessageId
public void setMessageId(String messageId)
setTimeStamp
public void setTimeStamp(Timestamp timeStamp)
Parameters:
  • timeStamp – The timeStamp to set.

hk.hku.cecid.ebms.spa.handler

EbxmlMessageDAOConvertor

public class EbxmlMessageDAOConvertor

The EbxmlMessageDAOConvertor construct the necessary DAO Data from EbxmlMessage.

Author:Donahue Sze

Constructors

EbxmlMessageDAOConvertor
public EbxmlMessageDAOConvertor(EbxmlMessage ebxmlMessage, String messageBox, String messageType)

Create a new instance of Ebxml Message to DAO Data Convertor

Parameters:
  • ebxmlMessage – Ebxml Message to be converted
  • messageBox – Message box the message will be stored
  • messageType – The type of the message

Methods

getEbxmlMessage
public static EbxmlMessage getEbxmlMessage(String messageId, String messageBox)
getInboxDVO
public InboxDVO getInboxDVO()

Get the inbox DAO data

Throws:
Returns:

The inbox DAO data

getMessageDVO
public MessageDVO getMessageDVO()

Get the message dao data

Throws:
Returns:

The message dao data

getOutboxDVO
public OutboxDVO getOutboxDVO()

Get the outbox DAO data

Throws:
Returns:

The outbox DAO data

getRepositoryDVO
public RepositoryDVO getRepositoryDVO()

Get the repository DAO data

Throws:
Returns:

The repository DAO data

InboundMessageProcessor

public class InboundMessageProcessor
Author:Donahue Sze Preferences - Java - Code Style - Code Templates

Fields

inboundMessageProcessor
static InboundMessageProcessor inboundMessageProcessor
inboundMessageProcessor_initFlag
static boolean inboundMessageProcessor_initFlag

Methods

getInstance
public static InboundMessageProcessor getInstance()
processIncomingMessage
public void processIncomingMessage(EbmsRequest request, EbmsResponse response)

MessageClassifier

public class MessageClassifier
Author:Donahue Sze

Fields

ACTION_ACKNOWLEDGMENT
public static String ACTION_ACKNOWLEDGMENT
ACTION_MESSAGE_ERROR
public static String ACTION_MESSAGE_ERROR
ACTION_PING
public static String ACTION_PING
ACTION_PONG
public static String ACTION_PONG
ACTION_STATUS_REQUEST
public static String ACTION_STATUS_REQUEST
ACTION_STATUS_RESPONSE
public static String ACTION_STATUS_RESPONSE
INTERNAL_STATUS_DELIVERED
public static String INTERNAL_STATUS_DELIVERED
INTERNAL_STATUS_DELIVERY_FAILURE
public static String INTERNAL_STATUS_DELIVERY_FAILURE
INTERNAL_STATUS_PENDING
public static String INTERNAL_STATUS_PENDING
INTERNAL_STATUS_PROCESSED
public static String INTERNAL_STATUS_PROCESSED
INTERNAL_STATUS_PROCESSED_ERROR
public static String INTERNAL_STATUS_PROCESSED_ERROR
INTERNAL_STATUS_PROCESSING
public static String INTERNAL_STATUS_PROCESSING
INTERNAL_STATUS_RECEIVED
public static String INTERNAL_STATUS_RECEIVED
MESSAGE_BOX_INBOX
public static String MESSAGE_BOX_INBOX
MESSAGE_BOX_OUTBOX
public static String MESSAGE_BOX_OUTBOX
MESSAGE_TYPE_ACKNOWLEDGEMENT
public static String MESSAGE_TYPE_ACKNOWLEDGEMENT
MESSAGE_TYPE_ERROR
public static String MESSAGE_TYPE_ERROR
MESSAGE_TYPE_ORDER
public static String MESSAGE_TYPE_ORDER
MESSAGE_TYPE_PING
public static String MESSAGE_TYPE_PING
MESSAGE_TYPE_PONG
public static String MESSAGE_TYPE_PONG
MESSAGE_TYPE_PROCESSED_ERROR
public static String MESSAGE_TYPE_PROCESSED_ERROR
MESSAGE_TYPE_STATUS_REQUEST
public static String MESSAGE_TYPE_STATUS_REQUEST
MESSAGE_TYPE_STATUS_RESPONSE
public static String MESSAGE_TYPE_STATUS_RESPONSE
SERVICE
public static String SERVICE
STATUS_FORWARDED
public static String STATUS_FORWARDED
STATUS_NOT_RECOGNIZED
public static String STATUS_NOT_RECOGNIZED
STATUS_PROCESSED
public static String STATUS_PROCESSED
STATUS_RECEIVED
public static String STATUS_RECEIVED
STATUS_UN_AUTHORIZED
public static String STATUS_UN_AUTHORIZED

Constructors

MessageClassifier
public MessageClassifier(EbxmlMessage ebxmlMessage)

Methods

getMessageType
public String getMessageType()
Returns:Returns the messageType.
isAckRequested
public boolean isAckRequested()
Returns:Returns the isAckRequested.
isDupElimination
public boolean isDupElimination()
Returns:Returns the isDupElimination.
isMessageOrder
public boolean isMessageOrder()
Returns:Returns the isMessageOrder.
isSeqeunceStatusReset
public boolean isSeqeunceStatusReset()
Returns:Returns the isSeqeunceStatusReset.
isSync
public boolean isSync()
Returns:Returns the isSync.

MessageServiceHandler

public class MessageServiceHandler

EbxmlMessageDAOConvertor Service Handler that supports asynchronous communication and reliable messaging.

Author:cyng

Fields

INBOX
public String INBOX
OUTBOX
public String OUTBOX
PEEK_THREAD_COUNT
public String PEEK_THREAD_COUNT
THREAD_COUNT
public String THREAD_COUNT
messageServiceHandler_destroyFlag
static boolean messageServiceHandler_destroyFlag
messageServiceHandler_initFlag
static boolean messageServiceHandler_initFlag
popFolder
public String popFolder
popHost
public String popHost
popPassword
public String popPassword
popPort
public String popPort
popProtocol
public String popProtocol
popUsername
public String popUsername
smtpFromMailAddress
public String smtpFromMailAddress
smtpHost
public String smtpHost
smtpPassword
public String smtpPassword
smtpPort
public String smtpPort
smtpProtocol
public String smtpProtocol
smtpUsername
public String smtpUsername

Methods

createSignatureHandler
public static SignatureHandler createSignatureHandler(EbxmlMessage message)
createSignatureHandler
public static SignatureHandler createSignatureHandler(EbxmlMessage message, Certificate certificate)
destroy
public synchronized void destroy()
getInstance
public static synchronized MessageServiceHandler getInstance()
isHasPop
public boolean isHasPop()
Returns:Returns the hasPop.
isHasSmtp
public boolean isHasSmtp()
Returns:Returns the hasSmtp.
isInboundAgreementCheck
public boolean isInboundAgreementCheck()
Returns:Returns the isInboundAgreementCheck.
isOutboundAgreementCheck
public boolean isOutboundAgreementCheck()
Returns:Returns the isOutboundAgreementCheck.
isSignHeaderOnly
public boolean isSignHeaderOnly()
Returns:Returns the isSignHeaderOnly.
processInboundMessage
public void processInboundMessage(EbmsRequest request, EbmsResponse response)
processOutboundMessage
public void processOutboundMessage(EbmsRequest request, EbmsResponse response)

MessageServiceHandlerException

public class MessageServiceHandlerException extends hk.hku.cecid.piazza.commons.GenericException

DeliveryException represents all kinds of exception occuring in delivery.

Author:Hugo Y. K. Lam

Constructors

MessageServiceHandlerException
public MessageServiceHandlerException()

Creates a new instance of DeliveryException.

MessageServiceHandlerException
public MessageServiceHandlerException(String message)

Creates a new instance of DeliveryException.

Parameters:
  • message – the error message.
MessageServiceHandlerException
public MessageServiceHandlerException(Throwable cause)

Creates a new instance of DeliveryException.

Parameters:
  • cause – the cause of this exception.
MessageServiceHandlerException
public MessageServiceHandlerException(String message, Throwable cause)

Creates a new instance of DeliveryException.

Parameters:
  • message – the error message.
  • cause – the cause of this exception.

OutboundMessageProcessor

public class OutboundMessageProcessor
Author:Donahue Sze

Fields

outboundMessageProcessor
static OutboundMessageProcessor outboundMessageProcessor
outboundMessageProcessor_initFlag
static boolean outboundMessageProcessor_initFlag

Methods

getInstance
public static synchronized OutboundMessageProcessor getInstance()
processOutgoingMessage
public void processOutgoingMessage(EbmsRequest request, EbmsResponse response)
resendAsNew
public EbxmlMessage resendAsNew(String primalMessageId)

SignalMessageGenerator

public class SignalMessageGenerator

SignalMessageGenerator is an utility api for the user to generate some signal message

Author:pykoon

Methods

generateAcknowledgment
public static EbxmlMessage generateAcknowledgment(EbxmlMessage ackRequestedMessage, String refToMessageId)

Generates acknowledgement message from the given acknowledgement request message and the refToMessageId. Note that the acknowledgment message is not signed.

Parameters:
  • ackRequestedMessage – Acknowledgement request message.
  • refToMessageId – MessageId of the message to which the acknowledgement response should be referred.
Throws:
  • SOAPException
Returns:

Acknowledgement message.

generateAcknowledgment
public static EbxmlMessage generateAcknowledgment(EbxmlMessage ackRequestedMessage)

Generates acknowledgement message from the given acknowledgement request message and the refToMessageId. Note that the acknowledgment message is not signed.

Parameters:
  • ackRequestedMessage – Acknowledgement request message.
Throws:
  • SOAPException
Returns:

Acknowledgement message.

generateErrorMessage
public static EbxmlMessage generateErrorMessage(EbxmlMessage ebxmlMessage, String errorCode, String severity, String description, String location)

Generates an error message containing the specfied error code [ebMSS 4.2.3.4.1].

Parameters:
  • ebxmlMessage – ebXML message to which error list should be attached.
  • errorCode – Error code of the message.
  • severity – Error severity, either ERROR or WARNING.
  • description – Human-readable description of the error message.
  • location – Source of the error.
Throws:
  • SOAPException
Returns:

ebXML message containing error code.

generateErrorMessageBySender
public static EbxmlMessage generateErrorMessageBySender(EbxmlMessage ebxmlMessage, String errorCode, String severity, String description, String location)
generatePongMessage
public static EbxmlMessage generatePongMessage(EbxmlMessage pingMessage)

Generates pong message from the given ping message [ebMSS 8.2].

Parameters:
  • pingMessage – Incoming ping message.
Throws:
  • SOAPException
Returns:

Pong message in response of the incoming ping message.

generateStatusResponseMessage
public static EbxmlMessage generateStatusResponseMessage(EbxmlMessage statusRequestMessage, String status, Date timestamp)

Generates response message from the given status request message and the status string [ebMSS 7.1.2].

Parameters:
  • statusRequestMessage – Status request message.
  • status – Current status of the message service handler.
Throws:
  • SOAPException
Returns:

Status response message.

hk.hku.cecid.ebms.spa.listener

EbmsAdaptor

public abstract class EbmsAdaptor extends SOAPHttpAdaptor
Author:Donahue Sze Window - Preferences - Java - Code Style - Code Templates

Methods

processRequest
public abstract void processRequest(EbmsRequest request, EbmsResponse response)
processRequest
public void processRequest(SOAPRequest soapRequest, SOAPResponse soapResponse)

EbmsInboundListener

public class EbmsInboundListener extends EbmsAdaptor
Author:Donahue Sze

Methods

listenerCreated
public void listenerCreated()

Handles event for servlet start up

listenerDestroyed
public void listenerDestroyed()
processRequest
public void processRequest(EbmsRequest request, EbmsResponse response)

EbmsOutboundListener

public class EbmsOutboundListener extends EbmsAdaptor
Author:Donahue Sze

Methods

listenerCreated
public void listenerCreated()

Handles event for servlet start up

listenerDestroyed
public void listenerDestroyed()
processRequest
public void processRequest(EbmsRequest request, EbmsResponse response)

EbmsRequest

public class EbmsRequest
Author:Donahue Sze

Constructors

EbmsRequest
public EbmsRequest()
EbmsRequest
public EbmsRequest(Object source)

Methods

getMessage
public EbxmlMessage getMessage()
Returns:Returns the msg.
getSource
public Object getSource()
Returns:Returns the source.
setMessage
public void setMessage(EbxmlMessage message)
Parameters:
  • message – The msg to set.
setSource
public void setSource(Object source)
Parameters:
  • source – The source to set.

EbmsResponse

public class EbmsResponse
Author:Donahue Sze

Constructors

EbmsResponse
public EbmsResponse()
EbmsResponse
public EbmsResponse(Object target)

Methods

getMessage
public EbxmlMessage getMessage()
Returns:Returns the msg.
getTarget
public Object getTarget()
Returns:Returns the target.
setMessage
public void setMessage(EbxmlMessage message)
Parameters:
  • message – The msg to set.
setTarget
public void setTarget(Object target)
Parameters:
  • target – The target to set.

hk.hku.cecid.ebms.spa.service

EbmsConfigService

public class EbmsConfigService extends WebServicesAdaptor

Methods

isCacheEnabled
protected boolean isCacheEnabled()
replaceNullToEmpty
public String replaceNullToEmpty(String value)
serviceRequested
public void serviceRequested(WebServicesRequest request, WebServicesResponse response)

EbmsMessageHistoryService

public class EbmsMessageHistoryService extends WebServicesAdaptor

Fields

MAX_NUMBER
public static int MAX_NUMBER
NAMESPACE
public static String NAMESPACE

Methods

serviceRequested
public void serviceRequested(WebServicesRequest request, WebServicesResponse response)

EbmsMessageHistoryServiceTest

public class EbmsMessageHistoryServiceTest

Fields

historyService
EbmsMessageHistoryService historyService

Methods

checkMessageBox
public void checkMessageBox()
checkMessageBox_Fail
public void checkMessageBox_Fail()
checkMessageStatus
public void checkMessageStatus()
checkMessageStatus_Fail
public void checkMessageStatus_Fail()
setUp
public void setUp()
tearDown
public void tearDown()

EbmsMessageReceiverListService

public class EbmsMessageReceiverListService extends WebServicesAdaptor

EbmsMessageReceiverListService

Author:Donahue Sze

Fields

MAX_NUMBER
public static int MAX_NUMBER
NAMESPACE
public static String NAMESPACE

Methods

isCacheEnabled
protected boolean isCacheEnabled()
serviceRequested
public void serviceRequested(WebServicesRequest request, WebServicesResponse response)

EbmsMessageReceiverService

public class EbmsMessageReceiverService extends WebServicesAdaptor

AS2MessageReceiverListService

Author:Donahue Sze

Fields

NAMESPACE
public static String NAMESPACE

Methods

isCacheEnabled
protected boolean isCacheEnabled()
serviceRequested
public void serviceRequested(WebServicesRequest request, WebServicesResponse response)

EbmsMessageSenderService

public class EbmsMessageSenderService extends WebServicesAdaptor

EbmsMessageSenderService

Author:Hugo Y. K. Lam

Fields

NAMESPACE
public static final String NAMESPACE

Methods

isCacheEnabled
protected boolean isCacheEnabled()
serviceRequested
public void serviceRequested(WebServicesRequest request, WebServicesResponse response)

EbmsPermitRedownloadService

public class EbmsPermitRedownloadService extends WebServicesAdaptor

Fields

NAMESPACE
public static String NAMESPACE

Methods

serviceRequested
public void serviceRequested(WebServicesRequest request, WebServicesResponse response)

hk.hku.cecid.ebms.spa.task

AgreementHandler

public class AgreementHandler
Author:Donahue Sze

Constructors

AgreementHandler
public AgreementHandler(MessageDVO message, boolean isCheckAgreement)
AgreementHandler
public AgreementHandler(EbxmlMessage ebxmlMessage, String messageBox, String messageType, boolean isCheckAgreement)

Methods

getActor
public String getActor()
Returns:Returns the actor.
getDsAlgorithm
public String getDsAlgorithm()
Returns:Returns the dsAlgorithm.
getEncryptAlgorithm
public String getEncryptAlgorithm()
Returns:Returns the encryptAlgorithm.
getEncryptCert
public byte[] getEncryptCert()
Returns:Returns the encryptCert.
getMdAlgorithm
public String getMdAlgorithm()
Returns:Returns the mdAlgorithm.
getRetries
public int getRetries()
Returns:Returns the retries.
getRetryInterval
public int getRetryInterval()
Returns:Returns the retryInterval.
getSignCert
public byte[] getSignCert()
Returns:Returns the signCert.
getToPartyProtocol
public String getToPartyProtocol()
Returns:Returns the toPartyProtocol.
getToPartyURL
public URL getToPartyURL()
Returns:Returns the toPartyURL.
isEncrypt
public boolean isEncrypt()
Returns:Returns the isEncrypt.
isHostnameVerified
public boolean isHostnameVerified()
Returns:Returns the isHostnameVerified.
isSign
public boolean isSign()
Returns:Returns the isSign.

DeliveryException

public class DeliveryException extends hk.hku.cecid.piazza.commons.GenericException

DeliveryException represents all kinds of exception occuring in delivery.

Author:Hugo Y. K. Lam

Constructors

DeliveryException
public DeliveryException()

Creates a new instance of DeliveryException.

DeliveryException
public DeliveryException(String message)

Creates a new instance of DeliveryException.

Parameters:
  • message – the error message.
DeliveryException
public DeliveryException(Throwable cause)

Creates a new instance of DeliveryException.

Parameters:
  • cause – the cause of this exception.
DeliveryException
public DeliveryException(String message, Throwable cause)

Creates a new instance of DeliveryException.

Parameters:
  • message – the error message.
  • cause – the cause of this exception.

EbmsEventListener

public abstract class EbmsEventListener extends Component

Methods

errorOccurred
public abstract void errorOccurred(EbxmlMessage errorMessage)
messageReceived
public abstract void messageReceived(EbxmlMessage requestMessage)
messageSent
public abstract void messageSent(EbxmlMessage requestMessage)
responseReceived
public abstract void responseReceived(EbxmlMessage acknowledgement)

EbmsEventModule

public class EbmsEventModule extends EventModule<EbmsEventListener>

Constructors

EbmsEventModule
public EbmsEventModule(String descriptorLocation, ClassLoader loader)
EbmsEventModule
public EbmsEventModule(String descriptorLocation, boolean shouldInitialize)
EbmsEventModule
public EbmsEventModule(String descriptorLocation, ClassLoader loader, boolean shouldInitialize)
EbmsEventModule
public EbmsEventModule(String descriptorLocation)

Methods

fireErrorOccurred
public void fireErrorOccurred(EbxmlMessage errorMessage)
fireMessageReceived
public void fireMessageReceived(EbxmlMessage requestMessage)
fireMessageSent
public void fireMessageSent(EbxmlMessage requestMessage)
fireResponseReceived
public void fireResponseReceived(EbxmlMessage acknowledgement)

InboxCollector

public class InboxCollector extends ActiveTaskList
Author:Donahue Sze

Methods

getTaskList
public List getTaskList()

InboxTask

public class InboxTask implements ActiveTask
Author:Donahue Sze

Constructors

InboxTask
public InboxTask(MessageDVO message, long nextOrderNo)

Methods

execute
public void execute()
getMaxRetries
public int getMaxRetries()
getRetryInterval
public long getRetryInterval()
isRetryEnabled
public boolean isRetryEnabled()
isSucceedFast
public boolean isSucceedFast()
onAwake
public void onAwake()
onFailure
public void onFailure(Throwable arg0)
setRetried
public void setRetried(int arg0)

MailCollector

public class MailCollector extends ActiveTaskList
Author:Donahue Sze

Methods

getTaskList
public List getTaskList()

MailTask

public class MailTask implements ActiveTask
Author:Donahue Sze

Constructors

MailTask
public MailTask(Message message)

Methods

execute
public void execute()
getMaxRetries
public int getMaxRetries()
getRetryInterval
public long getRetryInterval()
isRetryEnabled
public boolean isRetryEnabled()
isSucceedFast
public boolean isSucceedFast()
main
public static void main(String[] args)
onAwake
public void onAwake()
onFailure
public void onFailure(Throwable arg0)
setRetried
public void setRetried(int arg0)

MessageMonitor

public class MessageMonitor extends ActiveModule

The MessageMonitor is a monitor which correct all Creation Date: 14/05/2007

Author:Twinsen Tsang

Constructors

MessageMonitor
public MessageMonitor(String descriptorLocation, ClassLoader loader, boolean shouldInitialize)

Creates a new instance of MessageMonitor.

Parameters:
  • descriptorLocation – the module descriptor.
  • loader – the class loader for this module.
  • shouldInitialize – true if the module should be initialized.
Throws:
  • ModuleException – if errors encountered when loading the module descriptor.

Methods

execute
public boolean execute()

The method is invoked constantly with interval defined in the configuration descriptor or 60 second by default. It update the status of all timed-out message to PENDING so that they can be re-sending by Outbox Collector.

Returns:true if this method should be invoked again after a defined interval.

See also: hk.hku.cecid.ebms.spa.task.OutboxCollector, hk.hku.cecid.ebms.spa.task.OutboxTask

init
public void init()

Invoke for initialization.

initialize
public void initialize()

Post/Lazy initialization. This method is invoked at the firs time only this module execute. The purpose of this can guarantee the DAO Factory has been initialized successfully before creating it.

MessageValidationException

public class MessageValidationException extends hk.hku.cecid.piazza.commons.GenericException

DeliveryException represents all kinds of exception occuring in delivery.

Author:Hugo Y. K. Lam

Constructors

MessageValidationException
public MessageValidationException()

Creates a new instance of DeliveryException.

MessageValidationException
public MessageValidationException(String message)

Creates a new instance of DeliveryException.

Parameters:
  • message – the error message.
MessageValidationException
public MessageValidationException(Throwable cause)

Creates a new instance of DeliveryException.

Parameters:
  • cause – the cause of this exception.
MessageValidationException
public MessageValidationException(String message, Throwable cause)

Creates a new instance of DeliveryException.

Parameters:
  • message – the error message.
  • cause – the cause of this exception.

OutboxCollector

public class OutboxCollector extends ActiveTaskList
Author:Donahue Sze

Fields

isFirstTime
boolean isFirstTime

Methods

getTaskList
public List getTaskList()

OutboxTask

public class OutboxTask implements ActiveTask
Author:Donahue Sze, Twinsen Tsang (modifiers)

Constructors

OutboxTask
public OutboxTask(MessageDVO message)

Explicit Constructor.

Parameters:
  • message

Methods

execute
public void execute()

The main execution of OutboxTask. The overview procedure is listed in below:

  1. Extract the EbXMLMessage from the messageDVO.
  2. Sign the EbXMLMessage by it’s keystore if necessary.
  3. Send the EbXMLMessage through HTTP/HTTPS/SMTP protocol.
  4. Update the number of retry attempted to deliver for this EbXMLMessage.
getMaxRetries
public int getMaxRetries()

Get the maximum execution times for this task. It returns the total number of times that the EbXML Message can be attempted to deliver (including non-retry delivery). For EbXML Message does not requests ACK, this method always return zero because it does not support retry / re-sending schema when ACK does not requested. [ebMSS section 6.4.3] It is calculated by : Max(maximum retry defined in partnership for this message - 1,0) + 1.

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.getMaxRetries(), hk.hku.cecid.ebms.spa.dao.PartnershipDVO.getRetries(), hk.hku.cecid.ebms.spa.dao.OutboxDVO.getRetried()

getRetryInterval
public long getRetryInterval()
isRetryEnabled
public boolean isRetryEnabled()
isSucceedFast
public boolean isSucceedFast()
onAwake
public void onAwake()
onFailure
public void onFailure(Throwable t)

Invoke when execute() throw any kind of uncaught exception.

setRetried
public void setRetried(int retried)
Parameters:
  • retried – The number of times that this active task has been retried (local retired times).

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.setRetried(int)

hk.hku.cecid.ebms.spa.util

EbmsMessageStatusReverser

public class EbmsMessageStatusReverser

Reverse message status for message redownload and resend

Author:franz

Methods

updateToDownload
public void updateToDownload(String messageId)
updateToSend
public MessageDVO updateToSend(String messageId)

Reverse OUTBOX message status back to PENDING. Hence, the message can be resent again.

Parameters:
  • messageId
    • Message Id of the message to be resent
Throws:
Returns:

MessageDVO of the message to be resent

hk.hku.cecid.edi.as2

AS2Exception

public class AS2Exception extends hk.hku.cecid.piazza.commons.GenericException

AS2Exception represents all kinds of exception related to AS2 processing.

Author:Hugo Y. K. Lam

Constructors

AS2Exception
public AS2Exception()

Creates a new instance of AS2Exception.

AS2Exception
public AS2Exception(String message)

Creates a new instance of AS2Exception.

Parameters:
  • message – the error message.
AS2Exception
public AS2Exception(Throwable cause)

Creates a new instance of AS2Exception.

Parameters:
  • cause – the cause of this exception.
AS2Exception
public AS2Exception(String message, Throwable cause)

Creates a new instance of AS2Exception.

Parameters:
  • message – the error message.
  • cause – the cause of this exception.

AS2PlusProcessor

public class AS2PlusProcessor extends PluginProcessor

AS2Processor

Author:Hugo Y. K. Lam

Methods

getIncomingMessageProcessor
public IncomingMessageProcessor getIncomingMessageProcessor()
getInstance
public static AS2PlusProcessor getInstance()
getKeyStoreManager
public KeyStoreManager getKeyStoreManager()
getModuleGroupImpl
protected ModuleGroup getModuleGroupImpl()
getOutgoingMessageProcessor
public OutgoingMessageProcessor getOutgoingMessageProcessor()
getOutgoingPayloadRepository
public PayloadRepository getOutgoingPayloadRepository()
processActivation
public void processActivation(Plugin plugin)

See also: hk.hku.cecid.piazza.commons.spa.PluginHandler.processActivation(hk.hku.cecid.piazza.commons.spa.Plugin)

setModuleGroupImpl
protected void setModuleGroupImpl(ModuleGroup moduleGroup)

AS2Processor

public class AS2Processor implements PluginHandler

AS2Processor

Author:Hugo Y. K. Lam

Fields

core
public static SystemModule core

Methods

getIncomingMessageProcessor
public static IncomingMessageProcessor getIncomingMessageProcessor()
getIncomingPayloadRepository
public static PayloadRepository getIncomingPayloadRepository()
getKeyStoreManager
public static KeyStoreManager getKeyStoreManager()
getMessageRepository
public static MessageRepository getMessageRepository()
getModuleGroup
public static ModuleGroup getModuleGroup()
getOutgoingPayloadRepository
public static PayloadRepository getOutgoingPayloadRepository()
getSystemModule
public static SystemModule getSystemModule()
processActivation
public void processActivation(Plugin plugin)

See also: hk.hku.cecid.piazza.commons.spa.PluginHandler.processActivation(hk.hku.cecid.piazza.commons.spa.Plugin)

processDeactivation
public void processDeactivation(Plugin plugin)

See also: hk.hku.cecid.piazza.commons.spa.PluginHandler.processDeactivation(hk.hku.cecid.piazza.commons.spa.Plugin)

hk.hku.cecid.edi.as2.admin.listener

ChangeMessageStatusPageletAdaptor

public class ChangeMessageStatusPageletAdaptor extends AdminPageletAdaptor
Author:Donahue Sze

Methods

getCenterSource
protected Source getCenterSource(HttpServletRequest request)

MessageHistoryOraclePageletAdaptor

public class MessageHistoryOraclePageletAdaptor extends MessageHistoryPageletAdaptor
Author:Donahue Sze

MessageHistoryPageletAdaptor

public class MessageHistoryPageletAdaptor extends AdminPageletAdaptor
Author:Donahue Sze

Methods

getCenterSource
protected Source getCenterSource(HttpServletRequest request)

MessageHistoryPageletAdaptorTest

public class MessageHistoryPageletAdaptorTest extends TestCase

Methods

setUp
public void setUp()
tearDown
public void tearDown()
testCheckEmptyAndConvertToPercent
public void testCheckEmptyAndConvertToPercent()
testCheckNullAndReturnEmpty
public void testCheckNullAndReturnEmpty()
testCheckStarAndConvertToPercent
public void testCheckStarAndConvertToPercent()

PartnershipPageletAdaptor

public class PartnershipPageletAdaptor extends AdminPageletAdaptor
Author:Donahue Sze

Methods

getCenterSource
protected Source getCenterSource(HttpServletRequest request)
getHashtable
public Hashtable getHashtable(HttpServletRequest request)

RepositoryAdaptor

public class RepositoryAdaptor extends HttpRequestAdaptor
Author:Donahue Sze

Methods

processRequest
public String processRequest(HttpServletRequest request, HttpServletResponse response)

ResendAsNewAdapter

public class ResendAsNewAdapter extends AdminPageletAdaptor

Methods

getCenterSource
protected Source getCenterSource(HttpServletRequest request)

hk.hku.cecid.edi.as2.dao

AS2DAOHandler

public class AS2DAOHandler

AS2DAOHandler

Author:Hugo Y. K. Lam

Constructors

AS2DAOHandler
public AS2DAOHandler(DAOFactory daoFactory)
AS2DAOHandler
public AS2DAOHandler(DAOFactory daoFactory, Principal principal)

Methods

createMessageDAO
public MessageDAO createMessageDAO()
createMessageDVO
public MessageDVO createMessageDVO(AS2Message message, boolean isIncoming)
createMessageStore
public MessageStoreDAO createMessageStore()
createPartnershipDAO
public PartnershipDAO createPartnershipDAO()
createRawRepositoryDAO
public RawRepositoryDAO createRawRepositoryDAO()
createRawRepositoryDVO
public RawRepositoryDVO createRawRepositoryDVO(AS2Message message)
createRepositoryDAO
public RepositoryDAO createRepositoryDAO()
createRepositoryDVO
public RepositoryDVO createRepositoryDVO(AS2Message message, boolean isIncoming)
findMessageDVO
public MessageDVO findMessageDVO(String messageId, String messageBox)
findPartnership
public PartnershipDVO findPartnership(AS2Message message, boolean isIncoming)
findPartnership
public PartnershipDVO findPartnership(String partnershipId)
findPartnership
public PartnershipDVO findPartnership(String fromParty, String toParty)
findRawRepositoryDVO
public RawRepositoryDVO findRawRepositoryDVO(String messageId)

MessageDAO

public interface MessageDAO extends DAO
Author:Donahue Sze

Methods

findMessageByOriginalMessageID
public List findMessageByOriginalMessageID(String oriMessageID, String oriMessageBox)
findMessagesBeforeTime
public List findMessagesBeforeTime(int months)
findMessagesByHistory
public List findMessagesByHistory(MessageDVO data, int numberOfMessage, int offset)
findMessagesByStatus
public List findMessagesByStatus(String status, String messageBox)
findMessagesByTime
public List findMessagesByTime(int time_period, MessageDVO data, int numberOfMessage, int offset)
findNumberOfMessagesByHistory
public int findNumberOfMessagesByHistory(MessageDVO data)
recoverProcessingMessages
public int recoverProcessingMessages()

MessageDVO

public interface MessageDVO extends DVO
Author:Donahue Sze

Fields

MSGBOX_IN
public static String MSGBOX_IN
MSGBOX_OUT
public static String MSGBOX_OUT
STATUS_DELIVERED
public static String STATUS_DELIVERED
STATUS_DELIVERY_FAILURE
public static String STATUS_DELIVERY_FAILURE
STATUS_PENDING
public static String STATUS_PENDING
STATUS_PROCESSED
public static String STATUS_PROCESSED
STATUS_PROCESSED_ERROR
public static String STATUS_PROCESSED_ERROR
STATUS_PROCESSING
public static String STATUS_PROCESSING
STATUS_RECEIVED
public static String STATUS_RECEIVED

Methods

getAs2From
public String getAs2From()
Returns:Returns the AS2 From.
getAs2To
public String getAs2To()
Returns:Returns the AS2 To.
getHasResendAsNew
public String getHasResendAsNew()
Returns:“true” if message has triggered “Resend as New”, “false” if otherwise.
getMessageBox
public String getMessageBox()
Returns:Returns the messageType.
getMessageId
public String getMessageId()
Returns:Returns the messageId.
getMicValue
public String getMicValue()
Returns:Returns the MIC value.
getOriginalMessageId
public String getOriginalMessageId()
Returns:Returns the originalToMessageId.
getPartnershipId
public String getPartnershipId()
getPrimalMessageId
public String getPrimalMessageId()
Returns:String primalMessageId refer to the message that triggered “Resend as New”
getReceiptUrl
public String getReceiptUrl()
getStatus
public String getStatus()
Returns:Returns the status.
getStatusDescription
public String getStatusDescription()
getTimeStamp
public Date getTimeStamp()
Returns:Returns the timeStamp.
isAcknowledged
public boolean isAcknowledged()
isReceipt
public boolean isReceipt()
isReceiptRequested
public boolean isReceiptRequested()
setAs2From
public void setAs2From(String as2From)
Parameters:
  • as2From – The AS2 From to set.
setAs2To
public void setAs2To(String as2To)
Parameters:
  • as2To – The AS2 To to set.
setHasResendAsNew
public void setHasResendAsNew(String hasResendAsNew)
Parameters:
  • hasResendAsNew – Set to “true” if message has triggered “Resend as New”, “false” if otherwise
setIsAcknowledged
public void setIsAcknowledged(boolean isAcknowledged)
Parameters:
  • isAcknowledged – The isAcknowledged to set.
setIsReceipt
public void setIsReceipt(boolean isReceipt)
Parameters:
  • isReceipt – The isReceipt to set.
setIsReceiptRequested
public void setIsReceiptRequested(boolean isReceiptRequested)
Parameters:
  • isReceiptRequested – The isReceiptRequested to set.
setMessageBox
public void setMessageBox(String messageBox)
Parameters:
  • messageBox – The messageBox to set.
setMessageId
public void setMessageId(String messageId)
Parameters:
  • messageId – The messageId to set.
setMicValue
public void setMicValue(String micValue)
Parameters:
  • micValue – The MIC value to set.
setOriginalMessageId
public void setOriginalMessageId(String originalToMessageId)
Parameters:
  • originalToMessageId – The originalToMessageId to set.
setPartnershipId
public void setPartnershipId(String partnershipId)
setPrimalMessageId
public void setPrimalMessageId(String primalMessageId)

Set the primalMessageID which represent the message triggered “Resend as New”

Parameters:
  • primalMessageId
setReceiptUrl
public void setReceiptUrl(String url)
setStatus
public void setStatus(String status)
Parameters:
  • status – The status to set.
setStatusDescription
public void setStatusDescription(String desc)
setTimeStamp
public void setTimeStamp(Date timeStamp)
Parameters:
  • timeStamp – The timeStamp to set.

MessageDataSourceDAO

public class MessageDataSourceDAO extends DataSourceDAO implements MessageDAO
Author:Donahue Sze

Methods

createDVO
public DVO createDVO()
findMessageByOriginalMessageID
public List findMessageByOriginalMessageID(String oriMessageID, String oriMessageBox)
findMessagesBeforeTime
public List findMessagesBeforeTime(int time_period)
findMessagesByHistory
public List findMessagesByHistory(MessageDVO data, int numberOfMessage, int offset)
findMessagesByStatus
public List findMessagesByStatus(String status, String messageBox)
findMessagesByTime
public List findMessagesByTime(int time_period, MessageDVO data, int numberOfMessage, int offset)
findNumberOfMessagesByHistory
public int findNumberOfMessagesByHistory(MessageDVO data)
recoverProcessingMessages
public int recoverProcessingMessages()

MessageDataSourceDVO

public class MessageDataSourceDVO extends DataSourceDVO implements MessageDVO
Author:Donahue Sze

Constructors

MessageDataSourceDVO
public MessageDataSourceDVO()

Methods

getAs2From
public String getAs2From()
Returns:Returns the AS2 From.
getAs2To
public String getAs2To()
Returns:Returns the AS2 To.
getHasResendAsNew
public String getHasResendAsNew()
Returns:“true” if message has triggered “Resend as New”, “false” if otherwise
getMessageBox
public String getMessageBox()
Returns:Returns the messageBox.
getMessageId
public String getMessageId()
Returns:Returns the messageId.
getMicValue
public String getMicValue()
Returns:Returns the MIC value.
getOriginalMessageId
public String getOriginalMessageId()
Returns:Returns the originalToMessageId.
getPartnershipId
public String getPartnershipId()
getPrimalMessageId
public String getPrimalMessageId()
Returns:The primalMessageID which represent the message triggered “Resend as New”
getReceiptUrl
public String getReceiptUrl()

getReceiptUrl

Returns:@see hk.hku.cecid.edi.as2.dao.MessageDVO#getReceiptUrl()
getStatus
public String getStatus()
Returns:Returns the status.
getStatusDescription
public String getStatusDescription()

getStatusDescription

Returns:String

See also: hk.hku.cecid.edi.as2.dao.MessageDVO.getStatusDescription()

getTimeStamp
public Date getTimeStamp()
Returns:Returns the timeStamp.
isAcknowledged
public boolean isAcknowledged()

isAcknowledged

Returns:@see hk.hku.cecid.edi.as2.dao.MessageDVO#isAcknowledged()
isReceipt
public boolean isReceipt()

isReceipt

Returns:@see hk.hku.cecid.edi.as2.dao.MessageDVO#isReceipt()
isReceiptRequested
public boolean isReceiptRequested()

isReceiptRequested

Returns:@see hk.hku.cecid.edi.as2.dao.MessageDVO#isReceiptRequested()
setAs2From
public void setAs2From(String as2From)
Parameters:
  • as2From – The AS2 From to set.
setAs2To
public void setAs2To(String as2To)
Parameters:
  • as2To – The AS2 To to set.
setHasResendAsNew
public void setHasResendAsNew(String hasResendAsNew)
Parameters:
  • hasResendAsNew – Set to “true” if message has triggered “Resend as New”, “false” if otherwise
setIsAcknowledged
public void setIsAcknowledged(boolean isAcknowledged)

setIsAcknowledged

Parameters:
  • isAcknowledged

See also: hk.hku.cecid.edi.as2.dao.MessageDVO.setIsAcknowledged(boolean)

setIsReceipt
public void setIsReceipt(boolean isReceipt)

setIsReceipt

Parameters:
  • isReceipt

See also: hk.hku.cecid.edi.as2.dao.MessageDVO.setIsReceipt(boolean)

setIsReceiptRequested
public void setIsReceiptRequested(boolean isReceiptRequested)

setIsReceiptRequested

Parameters:
  • isReceiptRequested

See also: hk.hku.cecid.edi.as2.dao.MessageDVO.setIsReceiptRequested(boolean)

setMessageBox
public void setMessageBox(String messageBox)
Parameters:
  • messageBox – The messageBox to set.
setMessageId
public void setMessageId(String messageId)
Parameters:
  • messageId – The messageId to set.
setMicValue
public void setMicValue(String micValue)
Parameters:
  • micValue – The MIC value to set.
setOriginalMessageId
public void setOriginalMessageId(String originalToMessageId)
Parameters:
  • originalToMessageId – The originalToMessageId to set.
setPartnershipId
public void setPartnershipId(String partnershipId)
setPrimalMessageId
public void setPrimalMessageId(String primalMessageId)

Set the primalMessageID which represent the message triggered “Resend as New”

Parameters:
  • primalMessageId
setReceiptUrl
public void setReceiptUrl(String url)

setReceiptUrl

Parameters:
  • url

See also: hk.hku.cecid.edi.as2.dao.MessageDVO.setReceiptUrl(java.lang.String)

setStatus
public void setStatus(String status)
Parameters:
  • status – The service to set.
setStatusDescription
public void setStatusDescription(String desc)

setStatusDescription

Parameters:
  • desc

See also: hk.hku.cecid.edi.as2.dao.MessageDVO.setStatusDescription(java.lang.String)

setTimeStamp
public void setTimeStamp(Date timeStamp)
Parameters:
  • timeStamp – The timeStamp to set.

MessageStoreDAO

public interface MessageStoreDAO extends DAO
Author:Donahue Sze

Methods

storeMessage
public void storeMessage(MessageDVO primalMsgDVO, MessageDVO msgDVO, RepositoryDVO repoDVO, RawRepositoryDVO rawRepoDVO)
storeMessage
public void storeMessage(MessageDVO[] messageDVO, RepositoryDVO[] repositoryDVO)
storeMessage
public void storeMessage(MessageDVO messageDVO, RepositoryDVO repositoryDVO)
storeReceipt
public void storeReceipt(MessageDVO receiptMessageDVO, RepositoryDVO receiptRepositoryDVO, MessageDVO originalMessageDVO)

MessageStoreDataSourceDAO

public class MessageStoreDataSourceDAO extends DataSourceDAO implements MessageStoreDAO
Author:Donahue Sze

Methods

createDVO
public DVO createDVO()
storeMessage
public void storeMessage(MessageDVO primalMsgDVO, MessageDVO msgDVO, RepositoryDVO repoDVO, RawRepositoryDVO rawRepoDVO)
storeMessage
public void storeMessage(MessageDVO messageDVO, RepositoryDVO repositoryDVO)
storeMessage
public void storeMessage(MessageDVO[] messageDVO, RepositoryDVO[] repositoryDVO)
storeReceipt
public void storeReceipt(MessageDVO receiptMessageDVO, RepositoryDVO receiptRepositoryDVO, MessageDVO originalMessageDVO)

PartnershipDAO

public interface PartnershipDAO extends DAO
Author:Donahue Sze

Methods

findAllPartnerships
public List findAllPartnerships()
findByParty
public PartnershipDVO findByParty(String fromParty, String toParty)
findPartnershipsByPartyID
public List findPartnershipsByPartyID(String fromParty, String toParty)

PartnershipDVO

public interface PartnershipDVO extends DVO
Author:Donahue Sze

Fields

ALG_ENCRYPT_3DES
public static final String ALG_ENCRYPT_3DES
ALG_ENCRYPT_RC2
public static final String ALG_ENCRYPT_RC2
ALG_MIC_MD5
public static final String ALG_MIC_MD5
ALG_MIC_SHA1
public static final String ALG_MIC_SHA1
ALG_SIGN_MD5
public static final String ALG_SIGN_MD5
ALG_SIGN_SHA1
public static final String ALG_SIGN_SHA1

Methods

getAS2From
public String getAS2From()
getAs2To
public String getAs2To()
getEffectiveVerifyCertificate
public X509Certificate getEffectiveVerifyCertificate()
getEncryptAlgorithm
public String getEncryptAlgorithm()
getEncryptCert
public byte[] getEncryptCert()
getEncryptX509Certificate
public X509Certificate getEncryptX509Certificate()
getMicAlgorithm
public String getMicAlgorithm()
getPartnershipId
public String getPartnershipId()
getReceiptAddress
public String getReceiptAddress()
getRecipientAddress
public String getRecipientAddress()
getRetries
public int getRetries()
getRetryInterval
public int getRetryInterval()
getSignAlgorithm
public String getSignAlgorithm()
getSubject
public String getSubject()
getVerifyCert
public byte[] getVerifyCert()
getVerifyX509Certificate
public X509Certificate getVerifyX509Certificate()
isDisabled
public boolean isDisabled()
isHostnameVerified
public boolean isHostnameVerified()
isInboundEncryptRequired
public boolean isInboundEncryptRequired()
isInboundSignRequired
public boolean isInboundSignRequired()
isOutboundCompressRequired
public boolean isOutboundCompressRequired()
isOutboundEncryptRequired
public boolean isOutboundEncryptRequired()
isOutboundSignRequired
public boolean isOutboundSignRequired()
isReceiptRequired
public boolean isReceiptRequired()
isReceiptSignRequired
public boolean isReceiptSignRequired()
isSyncReply
public boolean isSyncReply()
setAs2From
public void setAs2From(String as2From)
setAs2To
public void setAs2To(String as2To)
setEncryptAlgorithm
public void setEncryptAlgorithm(String encryptAlgorithm)
setEncryptCert
public void setEncryptCert(byte[] encryptCert)
setIsDisabled
public void setIsDisabled(boolean isDisabled)
setIsHostnameVerified
public void setIsHostnameVerified(boolean isHostnameVerified)
setIsInboundEncryptRequired
public void setIsInboundEncryptRequired(boolean isInboundEncryptRequired)
setIsInboundSignRequired
public void setIsInboundSignRequired(boolean isInboundSignRequired)
setIsOutboundCompressRequired
public void setIsOutboundCompressRequired(boolean isOutboundEncryptRequired)
setIsOutboundEncryptRequired
public void setIsOutboundEncryptRequired(boolean isOutboundEncryptRequired)
setIsOutboundSignRequired
public void setIsOutboundSignRequired(boolean isOutboundSignRequired)
setIsReceiptRequired
public void setIsReceiptRequired(boolean isReceiptRequired)
setIsReceiptSignRequired
public void setIsReceiptSignRequired(boolean isReceiptSignRequired)
setIsSyncReply
public void setIsSyncReply(boolean IsSyncReply)
setMicAlgorithm
public void setMicAlgorithm(String micAlgorithm)
setPartnershipId
public void setPartnershipId(String partnershipId)
setReceiptAddress
public void setReceiptAddress(String receiptAddress)
setRecipientAddress
public void setRecipientAddress(String recipientAddress)
setRetries
public void setRetries(int retries)
setRetryInterval
public void setRetryInterval(int retryInterval)
setSignAlgorithm
public void setSignAlgorithm(String signAlgorithm)
setSubject
public void setSubject(String subject)
setVerifyCert
public void setVerifyCert(byte[] verifyCert)

PartnershipDataSourceDAO

public class PartnershipDataSourceDAO extends DataSourceDAO implements PartnershipDAO
Author:Donahue Sze

Methods

createDVO
public DVO createDVO()
findAllPartnerships
public List findAllPartnerships()
findByParty
public PartnershipDVO findByParty(String fromParty, String toParty)
findPartnershipsByPartyID
public List findPartnershipsByPartyID(String fromParty, String toParty)

PartnershipDataSourceDVO

public class PartnershipDataSourceDVO extends DataSourceDVO implements PartnershipDVO
Author:Donahue Sze

Methods

getAS2From
public String getAS2From()
getAs2To
public String getAs2To()
getEffectiveVerifyCertificate
public X509Certificate getEffectiveVerifyCertificate()
getEncryptAlgorithm
public String getEncryptAlgorithm()
getEncryptCert
public byte[] getEncryptCert()
getEncryptX509Certificate
public X509Certificate getEncryptX509Certificate()
getMicAlgorithm
public String getMicAlgorithm()
getPartnershipId
public String getPartnershipId()
getReceiptAddress
public String getReceiptAddress()
getRecipientAddress
public String getRecipientAddress()
getRetries
public int getRetries()
getRetryInterval
public int getRetryInterval()
getSignAlgorithm
public String getSignAlgorithm()
getSubject
public String getSubject()
getVerifyCert
public byte[] getVerifyCert()
getVerifyX509Certificate
public X509Certificate getVerifyX509Certificate()
isDisabled
public boolean isDisabled()
isHostnameVerified
public boolean isHostnameVerified()
isInboundEncryptRequired
public boolean isInboundEncryptRequired()
isInboundSignRequired
public boolean isInboundSignRequired()
isOutboundCompressRequired
public boolean isOutboundCompressRequired()
isOutboundEncryptRequired
public boolean isOutboundEncryptRequired()
isOutboundSignRequired
public boolean isOutboundSignRequired()
isReceiptRequired
public boolean isReceiptRequired()
isReceiptSignRequired
public boolean isReceiptSignRequired()
isSyncReply
public boolean isSyncReply()
setAs2From
public void setAs2From(String as2From)
setAs2To
public void setAs2To(String as2To)
setEncryptAlgorithm
public void setEncryptAlgorithm(String encryptAlgorithm)
setEncryptCert
public void setEncryptCert(byte[] encryptCert)
setIsDisabled
public void setIsDisabled(boolean isDisabled)
setIsHostnameVerified
public void setIsHostnameVerified(boolean isHostnameVerified)
setIsInboundEncryptRequired
public void setIsInboundEncryptRequired(boolean isInboundEncryptRequired)
setIsInboundSignRequired
public void setIsInboundSignRequired(boolean isInboundSignRequired)
setIsOutboundCompressRequired
public void setIsOutboundCompressRequired(boolean isOutboundCompressRequired)
setIsOutboundEncryptRequired
public void setIsOutboundEncryptRequired(boolean isOutboundEncryptRequired)
setIsOutboundSignRequired
public void setIsOutboundSignRequired(boolean isOutboundSignRequired)
setIsReceiptRequired
public void setIsReceiptRequired(boolean isReceiptRequired)
setIsReceiptSignRequired
public void setIsReceiptSignRequired(boolean isReceiptSignRequired)
setIsSyncReply
public void setIsSyncReply(boolean isSyncReply)
setMicAlgorithm
public void setMicAlgorithm(String micAlgorithm)
setPartnershipId
public void setPartnershipId(String partnershipId)
setReceiptAddress
public void setReceiptAddress(String receiptAddress)
setRecipientAddress
public void setRecipientAddress(String recipientAddress)
setRetries
public void setRetries(int retries)
setRetryInterval
public void setRetryInterval(int retryInterval)
setSignAlgorithm
public void setSignAlgorithm(String signAlgorithm)
setSubject
public void setSubject(String subject)
setVerifyCert
public void setVerifyCert(byte[] verifyCert)

RawRepositoryDAO

public interface RawRepositoryDAO extends DAO

RawRepositoryDVO

public interface RawRepositoryDVO extends DVO

Methods

getContent
public byte[] getContent()
Returns:Returns the content.
getMessageId
public String getMessageId()
Returns:Returns the messageId.
setContent
public void setContent(byte[] content)
Parameters:
  • content – The action to set.
setMessageId
public void setMessageId(String messageId)
Parameters:
  • messageId – The messageId to set.

RawRepositoryDataSourceDAO

public class RawRepositoryDataSourceDAO extends DataSourceDAO implements RawRepositoryDAO

Methods

createDVO
public DVO createDVO()

RawRepositoryDataSourceDVO

public class RawRepositoryDataSourceDVO extends DataSourceDVO implements RawRepositoryDVO

Methods

getContent
public byte[] getContent()
getMessageId
public String getMessageId()
setContent
public void setContent(byte[] content)
setMessageId
public void setMessageId(String messageId)

RepositoryDAO

public interface RepositoryDAO extends DAO
Author:Donahue Sze

RepositoryDVO

public interface RepositoryDVO extends DVO
Author:Donahue Sze

Methods

getContent
public byte[] getContent()
Returns:Returns the content.
getMessageBox
public String getMessageBox()
Returns:Returns the messageBox.
getMessageId
public String getMessageId()
Returns:Returns the messageId.
setContent
public void setContent(byte[] content)
Parameters:
  • content – The action to set.
setMessageBox
public void setMessageBox(String messageBox)
Parameters:
  • messageBox – The messageBox to set.
setMessageId
public void setMessageId(String messageId)
Parameters:
  • messageId – The messageId to set.

RepositoryDataSourceDAO

public class RepositoryDataSourceDAO extends DataSourceDAO implements RepositoryDAO
Author:Donahue Sze

Methods

createDVO
public DVO createDVO()

RepositoryDataSourceDVO

public class RepositoryDataSourceDVO extends DataSourceDVO implements RepositoryDVO
Author:Donahue Sze

Constructors

RepositoryDataSourceDVO
public RepositoryDataSourceDVO()

Methods

getContent
public byte[] getContent()
getMessageBox
public String getMessageBox()
Returns:Returns the messageBox.
getMessageId
public String getMessageId()
setContent
public void setContent(byte[] content)
setMessageBox
public void setMessageBox(String messageBox)
Parameters:
  • messageBox – The messageBox to set.
setMessageId
public void setMessageId(String messageId)

hk.hku.cecid.edi.as2.listener

AS2InboundListener

public class AS2InboundListener extends AS2RequestAdaptor

AS2InboundListener

Author:Hugo Y. K. Lam

Methods

processRequest
public void processRequest(AS2Request request, AS2Response response)

See also: hk.hku.cecid.edi.as2.listener.AS2RequestAdaptor.processRequest(hk.hku.cecid.edi.as2.listener.AS2Request,hk.hku.cecid.edi.as2.listener.AS2Response)

AS2ReceiptListener

public class AS2ReceiptListener extends AS2RequestAdaptor

AS2InboundListener

Author:Hugo Y. K. Lam

Methods

processRequest
public void processRequest(AS2Request request, AS2Response response)

See also: hk.hku.cecid.edi.as2.listener.AS2RequestAdaptor.processRequest(hk.hku.cecid.edi.as2.listener.AS2Request,hk.hku.cecid.edi.as2.listener.AS2Response)

AS2Request

public class AS2Request

The AS2Request class represents a SOAP request. It is independent of which transport protocol it is using and contains the SOAP message of the original request.

Author:Hugo Y. K. Lam

Constructors

AS2Request
AS2Request()

Creates a new instance of AS2Request.

AS2Request
AS2Request(Object source)

Creates a new instance of AS2Request.

Parameters:
  • source – the source which initiated this request.

Methods

getMessage
public AS2Message getMessage()

Gets the SOAP message of this request.

Returns:the SOAP message of this request.
getSource
public Object getSource()

Gets the source which initiated this request.

Returns:the source which initiated this request.
setMessage
void setMessage(AS2Message message)

Sets the SOAP message of this request.

Parameters:
  • message – the SOAP message of this request.
setSource
void setSource(Object source)

Sets the source which initiated this request.

Parameters:
  • source – the source which initiated this request.

AS2RequestAdaptor

public abstract class AS2RequestAdaptor extends HttpRequestAdaptor

AS2RequestAdaptor

Author:Hugo Y. K. Lam

Methods

processRequest
public String processRequest(HttpServletRequest request, HttpServletResponse response)

processRequest

Parameters:
  • request
  • response
Throws:
Returns:

String

See also: hk.hku.cecid.piazza.commons.servlet.http.HttpRequestListener.processRequest(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)

processRequest
public abstract void processRequest(AS2Request request, AS2Response response)

AS2Response

public class AS2Response

The AS2Response class represents a SOAP response. It is independent of which transport protocol it is using and contains the SOAP message of the target response.

Author:Hugo Y. K. Lam

Constructors

AS2Response
AS2Response()

Creates a new instance of AS2Response.

AS2Response
AS2Response(Object target)

Creates a new instance of AS2Response.

Parameters:
  • target – the target that this response should be committed to.

Methods

getMessage
public AS2Message getMessage()

Gets the SOAP message of this response.

Returns:the SOAP message of this response.
getTarget
public Object getTarget()

Gets the target that this response should be committed to.

Returns:the target that this response should be committed to.
setMessage
public void setMessage(AS2Message message)

Sets the SOAP message of this response.

Parameters:
  • message – the SOAP message of this response.
setTarget
void setTarget(Object target)

Sets the target that this response should be committed to.

Parameters:
  • target – the target that this response should be committed to.

hk.hku.cecid.edi.as2.module

AS2EventListener

public abstract class AS2EventListener extends Component

Methods

errorOccurred
public abstract void errorOccurred(AS2Message errorResponse)
messageReceived
public abstract void messageReceived(AS2Message requestMessage)
messageSent
public abstract void messageSent(AS2Message requestMessage)
responseReceived
public abstract void responseReceived(AS2Message response)

AS2EventModule

public class AS2EventModule extends EventModule<AS2EventListener>

Constructors

AS2EventModule
public AS2EventModule(String descriptorLocation, ClassLoader loader)
AS2EventModule
public AS2EventModule(String descriptorLocation, boolean shouldInitialize)
AS2EventModule
public AS2EventModule(String descriptorLocation, ClassLoader loader, boolean shouldInitialize)
AS2EventModule
public AS2EventModule(String descriptorLocation)

Methods

fireErrorOccurred
public void fireErrorOccurred(AS2Message errorResponse)
fireMessageReceived
public void fireMessageReceived(AS2Message requestMessage)
fireMessageSent
public void fireMessageSent(AS2Message requestMessage)
fireResponseReceived
public void fireResponseReceived(AS2Message receipt)

IncomingMessage

class IncomingMessage

IncomingMessage

Author:Hugo Y. K. Lam

Constructors

IncomingMessage
public IncomingMessage(AS2Message requestMessage, KeyStoreManager keyman, AS2DAOHandler daoHandler, Logger logger)

Methods

generateReceipt
public AS2Message generateReceipt()
getDecrytedMessage
public AS2Message getDecrytedMessage()
getDisposition
public Disposition getDisposition()
processSMime
public Disposition processSMime()

IncomingMessageList

public class IncomingMessageList extends ActiveTaskList

IncomingMessageList

Author:Hugo Y. K. Lam

Methods

getTaskList
public List getTaskList()

IncomingMessageProcessor

public class IncomingMessageProcessor extends SystemComponent

IncomingMessageProcessor

Author:Hugo Y. K. Lam

Methods

processMessage
public AS2Message processMessage(AS2Message requestMessage)
processReceipt
public void processReceipt(AS2Message receipt)
processReceivedMessage
protected AS2Message processReceivedMessage(AS2Message requestMessage)

IncomingMessageTask

public class IncomingMessageTask implements ActiveTask

OutgoingMessageTask

Author:Hugo Y. K. Lam

Constructors

IncomingMessageTask
public IncomingMessageTask(MessageDVO messageData)
Throws:
  • AS2Exception

Methods

execute
public void execute()

execute

Throws:

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.execute()

getMaxRetries
public int getMaxRetries()

getMaxRetries

Returns:int

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.getMaxRetries()

getRetryInterval
public long getRetryInterval()

getRetryInterval

Returns:long

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.getRetryInterval()

isRetryEnabled
public boolean isRetryEnabled()

isRetryEnabled

Returns:boolean

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.isRetryEnabled()

isSucceedFast
public boolean isSucceedFast()

isSucceedFast

Returns:boolean

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.isSucceedFast()

onAwake
public void onAwake()

onAwake

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.onAwake()

onFailure
public void onFailure(Throwable e)

onFailure

Parameters:
  • e

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.onFailure(java.lang.Throwable)

setRetried
public void setRetried(int retried)

setRetried

Parameters:
  • retried

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.setRetried(int)

MessageRepository

public class MessageRepository extends PayloadRepository

MessageRepository

Author:Hugo Y. K. Lam

Constructors

MessageRepository
public MessageRepository()

Methods

init
protected void init()
persistMessage
public void persistMessage(AS2Message message)
persistMessage
public void persistMessage(MessageDVO message, InputStream content)

OutgoingMessageList

public class OutgoingMessageList extends ActiveTaskList

OutgoingMessageList

Author:Hugo Y. K. Lam

Methods

getTaskList
public List getTaskList()

OutgoingMessageProcessor

public class OutgoingMessageProcessor extends SystemComponent

Methods

calculateMIC
public String calculateMIC(SMimeMessage smime, PartnershipDVO partnership)
init
protected void init()
resendAsNew
public AS2Message resendAsNew(String primalMessageId)
storeOutgoingMessage
public AS2Message storeOutgoingMessage(String messageID, String type, PartnershipDVO partnership, DataSource attachementSource)
storeOutgoingMessage
public AS2Message storeOutgoingMessage(String messageID, String type, PartnershipDVO partnership, DataSource attachementSource, MessageDVO primalMsgDVO)

OutgoingMessageTask

public class OutgoingMessageTask implements ActiveTask

OutgoingMessageTask

Author:Hugo Y. K. Lam

Constructors

OutgoingMessageTask
public OutgoingMessageTask(MessageDVO message)
Throws:
  • AS2Exception

Methods

execute
public void execute()

execute

Throws:

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.execute()

getMaxRetries
public int getMaxRetries()

getMaxRetries

Returns:int

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.getMaxRetries()

getRetryInterval
public long getRetryInterval()

getRetryInterval

Returns:long

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.getRetryInterval()

isRetryEnabled
public boolean isRetryEnabled()

isRetryEnabled

Returns:boolean

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.isRetryEnabled()

isSucceedFast
public boolean isSucceedFast()

isSucceedFast

Returns:boolean

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.isSucceedFast()

onAwake
public void onAwake()

onAwake

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.onAwake()

onFailure
public void onFailure(Throwable e)

onFailure

Parameters:
  • e

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.onFailure(java.lang.Throwable)

setRetried
public void setRetried(int retried)

setRetried

Parameters:
  • retried

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.setRetried(int)

OutgoingPayloadList

public class OutgoingPayloadList extends ActiveTaskList

OutgoingPayloadList

Author:Hugo Y. K. Lam

Methods

getTaskList
public List getTaskList()

OutgoingPayloadTask

public class OutgoingPayloadTask implements ActiveTask

OutgoingPayloadTask

Author:Hugo Y. K. Lam

Constructors

OutgoingPayloadTask
public OutgoingPayloadTask(PayloadCache payload)
Throws:
  • AS2Exception

Methods

execute
public void execute()

execute

Throws:

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.execute()

getMaxRetries
public int getMaxRetries()

getMaxRetries

Returns:int

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.getMaxRetries()

getRetryInterval
public long getRetryInterval()

getRetryInterval

Returns:long

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.getRetryInterval()

isRetryEnabled
public boolean isRetryEnabled()

isRetryEnabled

Returns:boolean

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.isRetryEnabled()

isSucceedFast
public boolean isSucceedFast()

isSucceedFast

Returns:boolean

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.isSucceedFast()

onAwake
public void onAwake()

onAwake

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.onAwake()

onFailure
public void onFailure(Throwable e)

onFailure

Parameters:
  • e

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.onFailure(java.lang.Throwable)

setRetried
public void setRetried(int retried)

setRetried

Parameters:
  • retried

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.setRetried(int)

PayloadCache

public class PayloadCache

PayloadCache

Author:Hugo Y. K. Lam

Constructors

PayloadCache
public PayloadCache(PayloadRepository repository, String messageID, String fromPartyID, String toPartyID, String type)
PayloadCache
public PayloadCache(PayloadRepository repository, File file)

Methods

checkIn
public boolean checkIn()
checkOut
public boolean checkOut()
clear
public boolean clear()
getCache
public File getCache()
getContentType
public String getContentType()
getFromPartyID
public String getFromPartyID()
getMessageID
public String getMessageID()
getToPartyID
public String getToPartyID()
getType
public String getType()
isCheckedOut
public boolean isCheckedOut()
isValid
public boolean isValid()
load
public InputStream load()
save
public void save(InputStream content)
toString
public String toString()

PayloadRepository

public class PayloadRepository extends Component

PayloadRepository

Author:Hugo Y. K. Lam

Constructors

PayloadRepository
public PayloadRepository()

Methods

createPayloadCache
public PayloadCache createPayloadCache(String messageID, String fromPartyID, String toPartyID, String type)
getPayloadCaches
public List getPayloadCaches()
getPayloadContentType
public String getPayloadContentType(String type)
getPayloadType
public String getPayloadType(String contentType)
getPayloadTypes
public Map getPayloadTypes()
getRepository
public File getRepository()
init
protected void init()
initRepository
protected void initRepository(String repository)
initRepository
protected void initRepository(File repository)
setPayloadTypes
public void setPayloadTypes(Map m)

hk.hku.cecid.edi.as2.pkg

AS2Header

public class AS2Header

AS2Header represents a set of AS2 message headers.

Author:Hugo Y. K. Lam

Fields

AS2_FROM
public static final String AS2_FROM
AS2_TO
public static final String AS2_TO
AS2_VERSION
public static final String AS2_VERSION
CONTENT_TYPE_APPLICATION_PKCS7_MIME
public static final String CONTENT_TYPE_APPLICATION_PKCS7_MIME
CONTENT_TYPE_APPLICATION_PKCS7_SIGNATURE
public static final String CONTENT_TYPE_APPLICATION_PKCS7_SIGNATURE
CONTENT_TYPE_MESSAGE_DISPOSITION_NOTIFICATION
public static final String CONTENT_TYPE_MESSAGE_DISPOSITION_NOTIFICATION
CONTENT_TYPE_MULTIPART_REPORT
public static final String CONTENT_TYPE_MULTIPART_REPORT
CONTENT_TYPE_MULTIPART_SIGNED
public static final String CONTENT_TYPE_MULTIPART_SIGNED
DATE
public static final String DATE
DISPOSITION_NOTIFICATION_OPTIONS
public static final String DISPOSITION_NOTIFICATION_OPTIONS
DISPOSITION_NOTIFICATION_TO
public static final String DISPOSITION_NOTIFICATION_TO
FROM
public static final String FROM
MESSAGE_ID
public static final String MESSAGE_ID
RECEIPT_DELIVERY_OPTION
public static final String RECEIPT_DELIVERY_OPTION
RECIPIENT_ADDRESS
public static final String RECIPIENT_ADDRESS
SUBJECT
public static final String SUBJECT

AS2Message

public class AS2Message

AS2Message represents an AS2 message.

Author:Hugo Y. K. Lam

Constructors

AS2Message
public AS2Message()

Creates a new instance of AS2Message.

AS2Message
public AS2Message(InputStream message)

Creates a new instance of AS2Message.

Parameters:
  • message – the message as input stream.
Throws:
  • AS2MessageException – if unable to construct from the given input stream.
AS2Message
public AS2Message(InternetHeaders headers, InputStream content)

Creates a new instance of AS2Message.

Parameters:
  • headers – the headers of this message.
  • content – the content stream.
Throws:
  • AS2MessageException – if unable to construct from the given content stream.

Methods

addHeader
public void addHeader(String name, String value)

Adds a message header of the specified name.

Parameters:
  • name – the header name.
  • value – the header value.
generateID
public static String generateID()

Generates a new AS2 message ID.

Returns:a new AS2 message ID.
getBodyPart
public MimeBodyPart getBodyPart()

Gets the MIME body part of this message.

Returns:the MIME body part.
getContent
public Object getContent()

Gets the content of this message.

Throws:
Returns:

the content part.

getContentStream
public InputStream getContentStream()

Gets the content stream of this message.

Throws:
Returns:

the content stream of this message.

getContentType
public String getContentType()

Gets the content type.

Throws:
Returns:

the content type.

getDispositionNotification
public DispositionNotification getDispositionNotification()

Gets the MDN of this message.

Throws:
Returns:

the MDN.

getDispositionNotificationOptions
public DispositionNotificationOptions getDispositionNotificationOptions()

Gets the disposition notification options.

Returns:the disposition notification options.
getFromPartyID
public String getFromPartyID()

Gets the “from” party ID.

Returns:the “from” party ID.
getHeader
public String getHeader(String name)

Gets a message header of the specified name.

Parameters:
  • name – the header name.
Returns:

the header value.

getHeader
public String getHeader(String name, String def)

Gets a message header of the specified name.

Parameters:
  • name – the header name.
  • def – the default value.
Returns:

the header value.

getHeaders
public InternetHeaders getHeaders()

Gets the headers of this message.

Returns:a copy of the headers of this message.
getInputStream
public InputStream getInputStream()

Gets the input stream of this message’s content. Any transfer encodings will be decoded before the input stream is provided.

Throws:
Returns:

the input stream of this message’s content.

getMessageID
public String getMessageID()

Gets the message ID.

Returns:the message ID.
getToPartyID
public String getToPartyID()

Gets the “to” party ID.

Returns:the “to” party ID.
isDispositionNotification
public boolean isDispositionNotification()

Checks if this message is an MDN.

Returns:true if this message is an MDN.
isReceiptRequested
public boolean isReceiptRequested()

Checks if receipt of message is requested.

Returns:true if receipt of message is requested.
isReceiptSynchronous
public boolean isReceiptSynchronous()

Checks if the receipt of message should be sent synchronously.

Returns:true if the receipt of message should be sent synchronously.
removeHeader
public void removeHeader(String name)

Removes a message header of the specified name.

Parameters:
  • name – the header name.
reply
public AS2Message reply()

Replies this message.

Throws:
Returns:

the reply message.

requestReceipt
public void requestReceipt(String returnUrl, String micAlg)
setBodyPart
public void setBodyPart(MimeBodyPart bp)

Sets the MIME body part of this message.

setContent
public void setContent(Object content, String contentType)

Sets a content to this message.

Parameters:
  • content – the content part.
  • contentType – the content type.
Throws:
setFromPartyID
public void setFromPartyID(String id)
setHeader
public void setHeader(String name, String value)

Sets a message header of the specified name.

Parameters:
  • name – the header name.
  • value – the header value.
setMessageID
public void setMessageID(String id)
setToPartyID
public void setToPartyID(String id)
toByteArray
public byte[] toByteArray()

Returns a byte array which represents this message.

Throws:
Returns:

a byte array which represents this message.

toString
public String toString()

Returns a string representation of this message.

Returns:a string representation of this message.

See also: java.lang.Object.toString()

writeTo
public void writeTo(OutputStream outs)

Writes the message to the given output stream.

Parameters:
  • outs – the output stream to be written.
Throws:

AS2MessageException

public class AS2MessageException extends GenericException

AS2MessageException represents an exception related to AS2 message.

Author:Hugo Y. K. Lam

Constructors

AS2MessageException
public AS2MessageException()

Creates a new instance of AS2MessageException.

AS2MessageException
public AS2MessageException(String message)

Creates a new instance of AS2MessageException.

Parameters:
  • message – the error message.
AS2MessageException
public AS2MessageException(Throwable cause)

Creates a new instance of AS2MessageException.

Parameters:
  • cause – the cause of this exception.
AS2MessageException
public AS2MessageException(String message, Throwable cause)

Creates a new instance of AS2MessageException.

Parameters:
  • message – the error message.
  • cause – the cause of this exception.

Disposition

public class Disposition

Disposition represents an AS2 disposition.

Author:Hugo Y. K. Lam

Fields

ACTION_MODE_AUTOMATIC
public static final String ACTION_MODE_AUTOMATIC
ACTION_MODE_MANUAL
public static final String ACTION_MODE_MANUAL
DESC_AUTHENTICATION_FAILED
public static final String DESC_AUTHENTICATION_FAILED
DESC_DECOMPRESSION_FAILED
public static final String DESC_DECOMPRESSION_FAILED
DESC_DECRYPTION_FAILED
public static final String DESC_DECRYPTION_FAILED
DESC_INSUFFICIENT_MESSAGE_SECURITY
public static final String DESC_INSUFFICIENT_MESSAGE_SECURITY
DESC_INTEGRITY_CHECK_FAILED
public static final String DESC_INTEGRITY_CHECK_FAILED
DESC_UNEXPECTED_PROCESSING_ERROR
public static final String DESC_UNEXPECTED_PROCESSING_ERROR
DESC_UNSUPPORTED_FORMAT
public static final String DESC_UNSUPPORTED_FORMAT
DESC_UNSUPPORTED_MIC_ALGORITHM
public static final String DESC_UNSUPPORTED_MIC_ALGORITHM
MODIFIER_ERROR
public static final String MODIFIER_ERROR
MODIFIER_FAILURE
public static final String MODIFIER_FAILURE
MODIFIER_WARNING
public static final String MODIFIER_WARNING
SENDING_MODE_AUTOMATIC
public static final String SENDING_MODE_AUTOMATIC
SENDING_MODE_MANUAL
public static final String SENDING_MODE_MANUAL
TYPE_FAILED
public static final String TYPE_FAILED
TYPE_PROCESSED
public static final String TYPE_PROCESSED

Constructors

Disposition
public Disposition()
Disposition
public Disposition(String actionMode, String sendingMode, String type)
Disposition
public Disposition(String actionMode, String sendingMode, String type, String modifier, String statusDescription)
Disposition
public Disposition(String disposition)

Methods

getActionMode
public String getActionMode()
getDescription
public String getDescription()
getDispositionMode
public String getDispositionMode()
getModifier
public String getModifier()
getSendingMode
public String getSendingMode()
getType
public String getType()
isError
public boolean isError()
isWarning
public boolean isWarning()
setActionMode
public void setActionMode(String action)
setDescription
public void setDescription(String statusDescription)
setModifier
public void setModifier(String statusModifier)
setSendingMode
public void setSendingMode(String mdnAction)
setType
public void setType(String status)
toString
public String toString()
validate
public void validate()

DispositionException

public class DispositionException extends RuntimeException

DispositionException is a runtime exception representing an error-level disposition.

Author:Hugo Y. K. Lam

Constructors

DispositionException
public DispositionException(Disposition disposition, String text, Throwable cause)
DispositionException
public DispositionException(Disposition disposition, String text)

Methods

getDisposition
public Disposition getDisposition()
getText
public String getText()
setDisposition
public void setDisposition(Disposition disposition)
setText
public void setText(String string)

DispositionNotification

public class DispositionNotification

DispositionNotification represents an AS2 disposition notification.

Author:Hugo Y. K. Lam

Fields

DISPOSITION
public static final String DISPOSITION
FINAL_RECIPIENT
public static final String FINAL_RECIPIENT
ORIG_MESSAGE_ID
public static final String ORIG_MESSAGE_ID
ORIG_RECIPIENT
public static final String ORIG_RECIPIENT
RECEIVED_CONTENT_MIC
public static final String RECEIVED_CONTENT_MIC
REPORTING_UA
public static final String REPORTING_UA

Constructors

DispositionNotification
public DispositionNotification()
DispositionNotification
DispositionNotification(AS2Message as2Message)

Methods

getBodyPart
public MimeBodyPart getBodyPart()
getDisposition
public Disposition getDisposition()
getOriginalMessageID
public String getOriginalMessageID()
getReceivedContentMIC
public String getReceivedContentMIC()
getReportValue
public String getReportValue(String key)
getText
public String getText()
matchOriginalContentMIC
public boolean matchOriginalContentMIC(String originalMIC)
replyTo
public void replyTo(AS2Message message, String reportingUA)
setDisposition
public void setDisposition(Disposition disposition)
setOriginalMessageID
public void setOriginalMessageID(String messageID)
setReceivedContentMIC
public void setReceivedContentMIC(String mic)
setReceivedContentMIC
public void setReceivedContentMIC(String mic, String alg)
setReportValue
public void setReportValue(String key, Object value)
setText
public void setText(String text)

DispositionNotificationOption

public class DispositionNotificationOption

DispositionNotificationOption represents an AS2 disposition notification option.

Author:Hugo Y. K. Lam

Fields

IMPORTANCE_OPTIONAL
public static final String IMPORTANCE_OPTIONAL
IMPORTANCE_REQURIED
public static final String IMPORTANCE_REQURIED
SIGNED_RECEIPT_MICALG_MD5
public static final String SIGNED_RECEIPT_MICALG_MD5
SIGNED_RECEIPT_MICALG_SHA1
public static final String SIGNED_RECEIPT_MICALG_SHA1
SIGNED_RECEIPT_PROTOCOL_PKCS7
public static final String SIGNED_RECEIPT_PROTOCOL_PKCS7

Constructors

DispositionNotificationOption
public DispositionNotificationOption()
DispositionNotificationOption
public DispositionNotificationOption(String option)
DispositionNotificationOption
public DispositionNotificationOption(String name, String importance, String[] values)

Methods

addValue
public void addValue(String value)
containsValue
public boolean containsValue(String value)
countValues
public int countValues()
getImportance
public String getImportance()
getName
public String getName()
getValue
public String getValue()
getValue
public String getValue(int pos)
getValues
public Iterator getValues()
isRequired
public boolean isRequired()
removeValue
public void removeValue(int pos)
removeValues
public void removeValues()
setImportance
public void setImportance(String importance)
setName
public void setName(String name)
toString
public String toString()

DispositionNotificationOptions

public class DispositionNotificationOptions

DispositionNotificationOption represents the AS2 disposition notification options.

Author:Hugo Y. K. Lam

Fields

SIGNED_RECEIPT_MICALG
public static final String SIGNED_RECEIPT_MICALG
SIGNED_RECEIPT_PROTOCOL
public static final String SIGNED_RECEIPT_PROTOCOL

Constructors

DispositionNotificationOptions
public DispositionNotificationOptions()
DispositionNotificationOptions
public DispositionNotificationOptions(String options)

Methods

addOption
public void addOption(DispositionNotificationOption option)
addOption
public DispositionNotificationOption addOption(String name)
getOption
public DispositionNotificationOption getOption(String name)
toString
public String toString()

hk.hku.cecid.edi.as2.service

AS2ConfigService

public class AS2ConfigService extends WebServicesAdaptor

This is a AS2 Configuration Web Service. The XML SOAP Message should be liked this.

<active-module-status> true | false </active-module-status>
<inmessage-interval>15000 </inmessage-interval>
<inmessage-maxthread>0</inmessage-maxthread>
<outmessage-interval>15000</outmessage-interval>
<outmessage-maxthread>0</outmessage-maxthread>
<outpayload-interval>15000</outpayload-interval>
<outpayload-maxthread>0</outpayload-maxthread>
Author:Twinsen Tsang.

Methods

isCacheEnabled
protected boolean isCacheEnabled()
replaceNullToEmpty
public String replaceNullToEmpty(String value)
serviceRequested
public void serviceRequested(WebServicesRequest request, WebServicesResponse response)

AS2MessageHistoryService

public class AS2MessageHistoryService extends WebServicesAdaptor

Fields

MAX_NUMBER
public static int MAX_NUMBER
NAMESPACE
public static String NAMESPACE

Methods

serviceRequested
public void serviceRequested(WebServicesRequest request, WebServicesResponse response)

AS2MessageReceiverListService

public class AS2MessageReceiverListService extends WebServicesAdaptor

AS2MessageReceiverListService

Author:Donahue Sze

Fields

NAMESPACE
public static final String NAMESPACE

Methods

isCacheEnabled
protected boolean isCacheEnabled()
serviceRequested
public void serviceRequested(WebServicesRequest request, WebServicesResponse response)

AS2MessageReceiverService

public class AS2MessageReceiverService extends WebServicesAdaptor

AS2MessageReceiverListService

Author:Donahue Sze

Fields

NAMESPACE
public static String NAMESPACE

Methods

isCacheEnabled
protected boolean isCacheEnabled()
serviceRequested
public void serviceRequested(WebServicesRequest request, WebServicesResponse response)

AS2MessageSenderService

public class AS2MessageSenderService extends WebServicesAdaptor

AS2MessageSenderService

Author:Hugo Y. K. Lam

Fields

NAMESPACE
public static final String NAMESPACE

Methods

isCacheEnabled
protected boolean isCacheEnabled()
serviceRequested
public void serviceRequested(WebServicesRequest request, WebServicesResponse response)

AS2MessageStatusQueryService

public class AS2MessageStatusQueryService extends WebServicesAdaptor

AS2MessageStatusQueryService

Author:Donahue Sze

Methods

isCacheEnabled
protected boolean isCacheEnabled()
replaceNullToEmpty
public String replaceNullToEmpty(String value)
serviceRequested
public void serviceRequested(WebServicesRequest request, WebServicesResponse response)

AS2PermitRedownloadService

public class AS2PermitRedownloadService extends WebServicesAdaptor

Fields

NAMESPACE
public static String NAMESPACE

Methods

serviceRequested
public void serviceRequested(WebServicesRequest request, WebServicesResponse response)

hk.hku.cecid.edi.as2.util

AS2MessageStatusReverser

public class AS2MessageStatusReverser

Reverse message status for message redownload and resend

Author:franz

Methods

updateToDownload
public void updateToDownload(String messageId)

Reverse INBOX message status back to PROCESSED. Hence, the message can be downloaded again.

Parameters:
  • messageId
    • MessageId to query inbox message
Throws:
updateToSend
public MessageDVO updateToSend(String messageId)

Reverse OUTBOX message status back to PENDING. Hence, the message can be resent again.

Parameters:
  • messageId
    • Message Id of the message to be resent
Throws:
Returns:

MessageDVO of the message to be resent

AS2Util

public class AS2Util

Methods

getFileNameFromMIMEHeader
public static String getFileNameFromMIMEHeader(String[] contentDispositions)

hk.hku.cecid.edi.sfrm.activation

EmptyDataSource

public class EmptyDataSource implements DataSource

NullDataSource is an implementation of the javax.activation.DataSource that represents a empty, but not null. datasource Creation Date: 7/11/2006

Author:Twinsen Tsang

Constructors

EmptyDataSource
public EmptyDataSource()

Default Constructor. The name is set to empty and the content type is set to application/octect-stream.

EmptyDataSource
public EmptyDataSource(String name, String contentType)

Explicit Constructor.

Parameters:
  • name – The name of the datasource.
  • contentType – The content type of the datasource.

Methods

getContentType
public String getContentType()

Get the name of content type.

getInputStream
public InputStream getInputStream()

This method will return an InputStream representing the the data and will throw an IOException if it can not do so. This method will return a new instance of NullInputStream with each invocation

See also: hk.hku.cecid.edi.sfrm.io.NullInputStream

getName
public String getName()

Get the name of the datasource.

getOutputStream
public OutputStream getOutputStream()

This method always throw IO exception.

Throws:
  • IOException – as output stream is not supported by this data source.

See also: javax.activation.DataSource.getOutputStream()

FileRegionDataSource

public class FileRegionDataSource extends FileDataSource

ByteBufferDataSource is an implementation of the javax.activation.DataSource that represents a data source of a region in the file. Creation Date: 2/11/2006

Author:Twinsen Tsang

Constructors

FileRegionDataSource
public FileRegionDataSource(File file, long position, long size)

Explicit Constructor.

Parameters:
  • file – The file associated to this datasource.
  • position – The start position of the region.
  • size – The size of the region.
FileRegionDataSource
public FileRegionDataSource(String filepath, long position, long size)

Explicit Constructor.

Parameters:
  • filepath – The file path associated to this datasource.
  • position – The start position of the region.
  • size – The size of the region

Methods

finalize
protected void finalize()
getByteBuffer
public ByteBuffer getByteBuffer()

This method will return an ByteBuffer representing the the data region and will throw an IOException if it can not do so or OutOfMemory error. For OutOfMemory error in direct memory usage, it’s still an issue in Java. http://bugs.sun.com/view_bug.do?bug_id=5025281 Properly reuse of the memory and set runtime parameter may solve the problem.

See also: java.nio.channels.FileChannel

getInputStream
public InputStream getInputStream()

This method will return an InputStream representing the the data and will throw an IOException if it can not do so. This method will return a new instance of ByteBufferInputStream with the direct byte buffer inside for each invocation.

See also: java.nio.channels.FileChannel, hk.hku.cecid.edi.sfrm.io.ByteBufferInputStream

getOutputStream
public OutputStream getOutputStream()

This method always throw IO exception.

Throws:
  • IOException – as output stream is not supported by this data source.

See also: javax.activation.DataSource.getOutputStream()

SFRMDataContentHandler

public class SFRMDataContentHandler implements DataContentHandler

Methods

getContent
public Object getContent(DataSource ds)
getTransferData
public Object getTransferData(DataFlavor df, DataSource ds)
getTransferDataFlavors
public DataFlavor[] getTransferDataFlavors()
writeTo
public void writeTo(Object obj, String mime, OutputStream os)

hk.hku.cecid.edi.sfrm.admin.listener

MessageHistoryPageletAdaptor

public class MessageHistoryPageletAdaptor extends AdminPageletAdaptor
Author:Patrick Yip

Methods

getCenterSource
protected Source getCenterSource(HttpServletRequest request)

MessageHistoryPageletAdaptorTest

public class MessageHistoryPageletAdaptorTest extends TestCase

Methods

setUp
public void setUp()
tearDown
public void tearDown()
testCheckEmptyAndReturnNull
public void testCheckEmptyAndReturnNull()
testCheckNullAndReturnEmpty
public void testCheckNullAndReturnEmpty()
testCheckStarAndConvertToPercent
public void testCheckStarAndConvertToPercent()

PartnershipPageletAdaptor

public class PartnershipPageletAdaptor extends AdminPageletAdaptor
Author:Patrick Yip

Methods

getCenterSource
protected Source getCenterSource(HttpServletRequest request)
getHashtable
public Hashtable getHashtable(HttpServletRequest request)

PartnershipPageletAdaptorTest

public class PartnershipPageletAdaptorTest extends TestCase

Fields

FIXTURE_LOADER
protected ClassLoader FIXTURE_LOADER
baseFile
protected File baseFile

Methods

setUp
public void setUp()
tearDown
public void tearDown()
testValidatePartnershipNeg10Test
public void testValidatePartnershipNeg10Test()
testValidatePartnershipNeg1Test
public void testValidatePartnershipNeg1Test()
testValidatePartnershipNeg2Test
public void testValidatePartnershipNeg2Test()
testValidatePartnershipNeg3Test
public void testValidatePartnershipNeg3Test()
testValidatePartnershipNeg4Test
public void testValidatePartnershipNeg4Test()
testValidatePartnershipNeg5Test
public void testValidatePartnershipNeg5Test()
testValidatePartnershipNeg6Test
public void testValidatePartnershipNeg6Test()
testValidatePartnershipNeg7Test
public void testValidatePartnershipNeg7Test()
testValidatePartnershipNeg8Test
public void testValidatePartnershipNeg8Test()
testValidatePartnershipNeg9Test
public void testValidatePartnershipNeg9Test()
testValidatePartnershipTest
public void testValidatePartnershipTest()

hk.hku.cecid.edi.sfrm.archive

Archiver

public interface Archiver

An Archiver is the interface that provide the basic archive operations like:

  • Compress operations
  • Extract operations
  • List operations

Creation Date: 13/11/2006

Author:Twinsen Tsang

Methods

compress
public boolean compress(File src, File dest, boolean includeItself)

Compress the src to dest in the archive form. If the src is a file, then the resulting archive contains only that file. If the src is a directory, then the resulting archive contains all files (recursively) in the src. If the flag includeItself is true , then the src will also include in the archive as the root.

Parameters:
  • src – The source of the file(s) to be archive.
  • dest – The destination of the arhived file.
  • includeItself – the source directory includes in the archive if it is true, vice versa.
Throws:
  • IOException – if any kind of I/O Erros
Returns:

true if the operations run successfully.

compress
public boolean compress(FileSystem src, File dest)

Compress the src to dest in the archive form.

Parameters:
  • src – The source of the file(s) to be archive.
  • dest – The destination of the arhived file.
  • includeItself – the source directory includes in the archive if it is true, vice versa.
Throws:
  • IOException – if any kind of I/O Errors.
Returns:

true if the operations run successfully.

extract
public boolean extract(File archive, File dest)

Extract the archive to the dest directory.

Parameters:
  • archive – The archive to be extract.
  • dest – The destination directory extract to.
Throws:
Returns:

true if the operations run successfully.

extract
public boolean extract(File archive, FileSystem dest)

Extract the archive to the dest directory.

Parameters:
  • archive – The archive to be extract.
  • dest – The destination directory extract to.
Throws:
  • IOException – Any kind of I/O Errors.
Returns:

true if the operations run successfully.

guessCompressedSize
public long guessCompressedSize(File src)

Guess how big is the compressed file without compressing actually.

Parameters:
  • src – The source of the file(s) to be archive.
Throws:
  • NullPointerException – if the src is null.
  • IOException – if one of the file in the folders does not exist in some reason.
guessCompressedSize
public long guessCompressedSize(FileSystem src)

Guess how big is the compressed file without compressing actually.

Parameters:
  • src – The source of the file(s) to be archive.
Throws:
  • NullPointerException – if the src is null.
  • IOException – if one of the file in the folders does not exist in some reason.
isSupportArchive
public boolean isSupportArchive(File archive)

Check whether the archive is supported by this type of archiver. The execution time of this method solely depends on how the archiver structure look like. For example, ArchiverZIP return immediately because it checks only with the extension of the archive file, without the actual content.

Parameters:
  • archive – The archive to be tested.
Returns:

true if the archiver support this archive.

listAsFile
public List listAsFile(File archive)

List the files inside the archive.

Parameters:
  • archive – The archive to be listed.
Throws:
  • IOException – if any kind of I/O Errors.
Returns:

A list of java.io.File object that represents each entry in the archive.

listAsFilename
public List listAsFilename(File archive)

List the files inside the archive.

Parameters:
  • archive – The archive to be listed.
Throws:
  • IOException – Any kind of I/O Errors.
Returns:

A list of String objects that represents the filename of each entry in the archive.

ArchiverNULL

public abstract class ArchiverNULL implements Archiver

An ArchiverNULL is a null packaging device that provides some useful method for the sub-class which enhance code design and ease to read.

  • Pre-error Handling of compress,list and extract

Creation Date: 13/11/2006

Author:Twinsen Tsang

Methods

compress
public boolean compress(File src, File dest, boolean includeItself)

The NULL archiver validates all fields in the parameters and return false in the end.

Parameters:
  • src – The source of the file(s) to be archive.
  • dest – The destination of the arhived file.
  • includeItself – the source directory includes in the archive if it is true, vice versa.
Throws:
  • IOException – if any kind of I/O Erros
Returns:

true if the operations run successfully.

See also: hk.hku.cecid.edi.sfrm.archive.Archiver.compress(File,File,boolean)

extract
public boolean extract(File archive, File dest)

The NULL archiver validates all fields in the parameters and return false in the end. If the destination directory does not exist, the NULL archiver will create one for you.

Parameters:
  • archive – The archive to be extract.
  • dest – The destination directory extract to.
Throws:
Returns:

true if the operations run successfully.

getBaseArchivingDirectory
protected String getBaseArchivingDirectory(File src, boolean includeItself)

Get the base directory for archiving. The base directory is the path that all archive entry relative to it. NOTE: This method should only be used inside the compress method.

Returns:the base directory.
listAllToArchive
protected Iterator listAllToArchive(File src)
listAsFile
public List listAsFile(File archive)

List the files inside the archive.

Parameters:
  • archive – The archive to be listed.
Throws:
  • IOException – if any kind of I/O Errors.
Returns:

A list of java.io.File object that represents each entry in the archive.

listAsFilename
public List listAsFilename(File archive)

List the files inside the archive.

Parameters:
  • archive – The archive to be listed.
Throws:
  • IOException – Any kind of I/O Errors.
Returns:

A list of String objects that represents the filename of each entry in the archive.

listFilesToArchive
protected Iterator listFilesToArchive(File src)

List out all files that need to be archive in a compress(File,File,boolean) call. NOTE: This method should only be used inside the compress method.

Parameters:
  • src – The source of the file(s) to be archive.
Returns:

An iterator whichs contains a list of files object to archive.

ArchiverTar

public class ArchiverTar extends ArchiverNULL
Author:Patrick Yip

Fields

TAR_ENTRY_SIZE
public static int TAR_ENTRY_SIZE

Methods

compress
public boolean compress(List<File> src, File dest, boolean includeItself)
compress
public boolean compress(File src, File dest, boolean includeItself)

Compress the src to dest in the archive form. If the src is a file, then the resulting archive contains only that file. If the src is a directory, then the resulting archive contains all files (recursively) in the src. The src file sets will be archived to TAR format which is comes from Apache Ant Tools Tar. For more details, read Apache Ant Tool Tar

Parameters:
  • src – The source of the file(s) to be archive.
  • dest – The destination of the arhived file.
  • includeItself – the source directory includes in the archive if it is true, vice versa.
Throws:
  • IOException – if any kind of I/O Erros
Returns:

true if the operations run successfully.

See also: hk.hku.cecid.edi.sfrm.archive.Archiver.compress(File,File,boolean)

compress
public boolean compress(FileSystem src, File dest)
extract
public boolean extract(File archive, File dest)

Extract the archive to the dest directory.

Parameters:
  • archive – The archive to be extract.
  • dest – The destination directory extract to.
Throws:
Returns:

true if the operations run successfully.

extract
public boolean extract(File archive, FileSystem dest)

Extract the archive to the dest directory.

Parameters:
  • archive – The archive to be extract.
  • dest – The destination directory extract to.
Throws:
  • IOException – Any kind of I/O Errors.
Returns:

true if the operations run successfully.

guessCompressedSize
public long guessCompressedSize(File src)

Guess how big is the compressed file without compressing actually. The algorithm of guessing the tar size as follow: For each of file Each header size is TAR_ENTRY_SIZE bytes, and for the data content block. It use TAR_ENTRY_SIZE as a block of data. If for last block of data is not TAR_ENTRY_SIZE, then the rest will padding with the empty bytes. Such that the final guessed size is ceil((file_length/TAR_ENTRY_SIZE)+1)*TAR_ENTRY_SIZE. More details of tar file format can found from this.

Parameters:
  • src – The source of the file(s) to be archive.
Throws:
  • NullPointerException – if the src is null.
  • IOException – if one of the file in the folders does not exist in some reason.
Returns:

guessed file size in byte

guessCompressedSize
public long guessCompressedSize(FileSystem src)
isSupportArchive
public boolean isSupportArchive(File archive)
listAsFile
public List listAsFile(File archive)

List the files inside the archive. This operation is quite slow and pending to optimize.

Parameters:
  • archive – The archive to be listed.
Returns:

A list of java.io.File object that represents each entry in the archive.

listAsFilename
public List listAsFilename(File archive)

List the files inside the archive.

Parameters:
  • archive – The archive to be listed.
Returns:

A list of String objects that represents the filename of each entry in the archive.

ArchiverTarTest

public class ArchiverTarTest extends TestCase
Author:Patrick Yip

Methods

setUp
public void setUp()
tearDown
public void tearDown()
testCompressFile
public void testCompressFile()

Test for tar a file

Throws:
testCompressLongFileName
public void testCompressLongFileName()

Test for tar the file with long filename, for traditional tar format , it only support the tar entry name <= 100 characters

Throws:
testExtractFile
public void testExtractFile()

Test for untar the file Notice: Run this test should have at least 4GB disk space

Throws:

SFRMTarEntry

public class SFRMTarEntry extends TarEntry
Author:Patrick

Constructors

SFRMTarEntry
public SFRMTarEntry(String name)

Construct an entry with only a name. This allows the programmer to construct the entry’s header “by hand”. File is set to null.

Parameters:
  • name – the entry name
SFRMTarEntry
public SFRMTarEntry(String name, byte linkFlag)

Construct an entry with a name an a link flag.

Parameters:
  • name – the entry name
  • linkFlag – the entry link flag.
SFRMTarEntry
public SFRMTarEntry(File file)

Construct an entry for a file. File is set to file, and the header is constructed from information from the file.

Parameters:
  • file – The file that the entry represents.
SFRMTarEntry
public SFRMTarEntry(byte[] headerBuf)

Construct an entry from an archive’s header bytes. File is set to null.

Parameters:
  • headerBuf – The header bytes from a tar archive entry.

Methods

parseTarHeader
public void parseTarHeader(byte[] header)

Parse an entry’s header information from a header buffer.

Parameters:
  • header – The tar entry header buffer to get information from.
writeEntryHeader
public void writeEntryHeader(byte[] outbuf)

Write an entry’s header information to a header buffer.

Parameters:
  • outbuf – The tar entry header buffer to fill in.

SFRMTarInputStream

public class SFRMTarInputStream extends TarInputStream
Author:Patrick Yip

Constructors

SFRMTarInputStream
public SFRMTarInputStream(InputStream arg0)
SFRMTarInputStream
public SFRMTarInputStream(InputStream is, int blockSize)
SFRMTarInputStream
public SFRMTarInputStream(InputStream is, int blockSize, int recordSize)

Methods

getNextEntry
public TarEntry getNextEntry()

Get the next entry in this tar archive. This will skip over any remaining data in the current entry, if there is one, and place the input stream at the header of the next entry, and read the header and instantiate a new TarEntry from the header bytes and return that entry. If there are no more entries in the archive, null will be returned to indicate that the end of the archive has been reached.

Throws:
  • IOException – on error
Returns:

The next TarEntry in the archive, or null.

SFRMTarOutputStream

public class SFRMTarOutputStream extends TarOutputStream
Author:Patrick Yip

Constructors

SFRMTarOutputStream
public SFRMTarOutputStream(OutputStream os)
SFRMTarOutputStream
public SFRMTarOutputStream(OutputStream os, int blockSize)
SFRMTarOutputStream
public SFRMTarOutputStream(OutputStream os, int blockSize, int recordSize)

Methods

putNextEntry
public void putNextEntry(TarEntry entry)

Put an entry on the output stream. This writes the entry’s header record and positions the output stream for writing the contents of the entry. Once this method is called, the stream is ready for calls to write() to write the entry’s contents. Once the contents are written, closeEntry() MUST be called to ensure that all buffered data is completely written to the output stream.

Parameters:
  • entry – The TarEntry to be written to the archive.
Throws:
  • IOException – on error

SFRMTarUtils

public class SFRMTarUtils
Author:Patrick Yip

Fields

NAME_ENCODING
public static final String NAME_ENCODING

Methods

getNameBytes
public static int getNameBytes(StringBuffer name, byte[] buf, int offset, int length)

Determine the number of bytes in an entry name.

Parameters:
  • name – The header name from which to parse.
  • buf – The buffer from which to parse.
  • offset – The offset into the buffer from which to parse.
  • length – The number of header bytes to parse.
Returns:

The number of bytes in a header’s entry name.

parseName
public static String parseName(byte[] header, int offset, int length)

Parse an entry name from a header buffer.

Parameters:
  • header – The header buffer from which to parse.
  • offset – The offset into the buffer from which to parse.
  • length – The number of header bytes to parse.
Returns:

The header’s entry name.

hk.hku.cecid.edi.sfrm.com

FoldersPayload

public class FoldersPayload extends NamedPayloads

A folders payload represent a folder hierarchical with the set of payloads. Creation Date: 5/10/2006

Author:Twinsen Tsang

Constructors

FoldersPayload
protected FoldersPayload(String payloadsName, int initialState, PayloadsRepository owner)

Protected Explicit Constructor. This constructor is mainly used for creating a new payload proxy including the physical file and the proxy object.

Parameters:
  • payloadsName – The name of the newly created payload.
  • initialState – The initialState of the payloads, see PayloadsState for details.
  • owner – The owner of the payloads.
Throws:
  • Exception – Any kind of exceptions.
FoldersPayload
protected FoldersPayload(File payloads, PayloadsRepository owner)

Protected Explicit Constructor.

Parameters:
  • payloads – The payloads directory.
  • owner – The owner of this payload.
Throws:
  • IOException – If the payload is not directory.

Methods

clearPayloadCache
public void clearPayloadCache()

Clear all the content and the folder for this payload.

decode
protected void decode()

Decode the payload root to become some useful information. Only the partnershipId (the first token) is assigned.

Throws:
encode
protected void encode()
getMessageId
public String getMessageId()
Returns:the message of the payloads.
getNumOfFiles
public int getNumOfFiles()
Returns:the number of files within the folders.
getPartnershipId
public String getPartnershipId()
Returns:the partnership id of the payloads.
getSize
public long getSize()
Returns:the total size within the folders.
load
public InputStream load()

The outgoing payload does not support load method.

loadChannel
public ReadableByteChannel loadChannel()

The outgoing payload does not support loadChannel method.

save
public void save(InputStream content, boolean append)

The outgoing payload does not support save method.

toString
public String toString()

toString method

NamedPayloads

public abstract class NamedPayloads

A Named payloads is a kind of payload (file attachment) that use it’s filename to provide some informations for the system. It is a proxy design pattern that control the behavior of the actual files. In SFRM plugin, the default style of named payload is shown on the below:

  • Outgoing Payload Repository - <service>$<message_id>$timestamp>
  • Packaged Payload Repository - <service>$<message_id>
  • Incoming Payload Repository - <service>$<message_id>

Creation Date: 6/10/2006.

Author:Twinsen Tsang

Fields

decodeDelimiters
protected static final String decodeDelimiters

The delimitier used for decoding.

filenameEndBracket
protected static final String filenameEndBracket

The end bracket to enclose the filename of the single file, not packed payload

filenameStartBracket
protected static final String filenameStartBracket

The start bracket to enclose the filename of the single file, not packed payload

processedPrefix
protected static final String processedPrefix

The prefix of uploading payload.

processingPrefix
protected static final String processingPrefix

The prefix of processing payload.

uploadingPrefix
protected static final String uploadingPrefix

The prefix of uploading payload.

Constructors

NamedPayloads
public NamedPayloads(String payloadsName, int initialState, PayloadsRepository owner)

Explicit Constructor. This constructor is mainly used for creating a new payload proxy including the physical file and the proxy object. NOTE: The physical file is not created until it is necessary.

Parameters:
  • payloadsName – The name of the newly created payload.
  • initialState – The initialState of the payloads, see PayloadsState for details.
  • owner – The owner of the payloads.
Throws:
  • NullPointerException – if the owner is null
  • IllegalArgumentException – if the payloadsName is null or the initialState is not invalid.

See also: hk.hku.cecid.edi.sfrm.com.PayloadsRepostory, hk.hku.cecid.edi.sfrm.com.PayloadsState

NamedPayloads
public NamedPayloads(File payloads, PayloadsRepository owner)

Explicit Constructor. The constructor is mainly used for creating the new payload proxy object only.

Parameters:
  • payloads – The file payload object.
  • owner – The owner of the payloads.

See also: hk.hku.cecid.edi.sfrm.PayloadsRepostory

Methods

clearPayloadCache
public void clearPayloadCache()

Clear / Delete the payload cache to free some space.

clearTokens
public void clearTokens()

Clear the tokens to free some memory.

decode
protected abstract void decode()

Decode the payload root to become some useful information.

Throws:
encode
protected abstract void encode()

Encode the payload root back to a filename.

getContentType
public String getContentType()
Returns:the contentType
getExtension
public String getExtension()
Returns:the extension
getOriginalRootname
public String getOriginalRootname()
Returns:the original file name of the payload root.
getOwner
public PayloadsRepository getOwner()
Returns:get the owner of this payload.
getRoot
public File getRoot()
Returns:the directory of this payload set.
getSize
public long getSize()
Returns:get the size of the payload, return 0 if the payload does not exist.
getStateForm
public static String getStateForm(int state)

Get the state form string according to the specified state.

Parameters:
  • state – The state you want to retrieve.
Throws:
getTokens
protected List getTokens()
Returns:a list of token under the decode delimiters.
isProcessed
public boolean isProcessed()
Returns:true if the payload’s name is starting with processed prefix.
isProcessing
public boolean isProcessing()
Returns:true if the payload’s name is startting with processing prefix.
isUploading
public boolean isUploading()
Returns:true if the payload’s name is startting with processing prefix.
load
public InputStream load()

Load the payload content from the input stream. NOTE: This method returns a new instance of input stream.

Throws:
  • IOException – Throws if the payload file does not exist.
Returns:

the content input stream.

loadChannel
public ReadableByteChannel loadChannel()

Load the payload content from the input stream channel.

Throws:
  • IOException – Throws if the payload file does not exist.
Returns:

the content input channel.

moveRoot
public boolean moveRoot(String newPath, boolean force)

Move the root to the specified path.

Parameters:
  • newPath – The absolute new path
  • force – force to move the file to specified path if there is a file with same name already exist in that path.
Returns:

true if the moving operation successfully.

moveToRepository
public boolean moveToRepository(PayloadsRepository newOwner)

Move the root to another payloads repository. The owner of this payloads will changes to newOwner after invocation of this method.

Parameters:
  • newOwner – The new owner of the payload repository.
Returns:

true if the moving operation successfully, false if the newOwner is null or moving operation fail.

moveToRepositoryForce
public boolean moveToRepositoryForce(PayloadsRepository newOwner)

Move the root to another payloads repository force. The owner of this payloads will changes to newOwner after invocation of this method.

Parameters:
  • newOwner – The new owner of the payload repository.
Returns:

true if the moving operation successfully, false if the newOwner is null or moving operation fail.

renameRoot
public boolean renameRoot(String newName)

Rename the root to the specified name. (The file path has not been changed after each invocation.

Parameters:
  • newName – The name of the root.
Throws:
  • IOException – if any kinds of I/O Exception.
Returns:

true if the operation run successfully.

save
public void save(InputStream content, boolean append)

Save the content from the input stream to this payloads. If the content stream is null, it save the file with empty content.

Parameters:
  • content – The input content stream.
  • append – true if the new content is added to the existing content, false if the new content overwrite the existing.
setToPending
public boolean setToPending()

Set the status of payload to pending.

Returns:true if the operation run sucessfully.
setToProcessed
public boolean setToProcessed()

Set the status of payload to processed.

Returns:true if the operation run sucessfully.
setToProcessing
public boolean setToProcessing()

Set the status of payload to processing.

Returns:true if the operation run sucessfully.
setToUploading
public boolean setToUploading()

Set the status of payload to uploading.

Returns:true if the operation run sucessfully.
toString
public String toString()

toString method

OutgoingPayloadsRepository

public class OutgoingPayloadsRepository extends PayloadsRepository

The outgoing payloads repository retrieves the payload which is in the form of directory. Creation Date: 5/10/2006

Author:Twinsen Tsang

Constructors

OutgoingPayloadsRepository
public OutgoingPayloadsRepository(String path)

Methods

createPayloads
public NamedPayloads createPayloads(Object[] params, int initialState)

Create a customizing payloads for the specified parameter. Since the outgoing payloads is in the form of <partnership_id>$<message_id>, so the size of parameters size should have at least 2.

Parameters:
  • params – An array object parameters set for creating the payload.
Throws:
createPayloadsProxy
protected NamedPayloads createPayloadsProxy(File proxyObj)

Create a customizing payloads for this repository.

Parameters:
  • proxyObj – The file object for the payloads.
Returns:

a customizing payloads.

getPayload
public NamedPayloads getPayload(Object[] params, int state)

Get a particular payload in the payload repository by the specified parameters. Since the outgoing payloads is in the form of <partnership_id>$<message_id>, so the size of parameters size should have at least 2.

Parameters:
  • params – An array object parameters set for creating the payload.
  • state – The current state of that payload.
Returns:

the payload with the specified params or null if it does not exist.

getPayloads
public Collection getPayloads()
Returns:A set of directories which contains the payloads set.
getProcessingPayloads
public Collection getProcessingPayloads()
Returns:Get the list of processing payloads in the payload repositoy;

PackagedPayloads

public class PackagedPayloads extends NamedPayloads

A packaged payloads represent a archive file typed payloads. Creation Date: 6/10/2006

Author:Twinsen Tsang

Constructors

PackagedPayloads
protected PackagedPayloads(String payloadsName, int initialState, PayloadsRepository owner)

Protected Explicit Constructor. This constructor is mainly used for creating a new payload proxy including the physical file and the proxy object. NOTE: The physical file is not created until it is necessary.

Parameters:
  • payloadsName – The name of the newly created payload.
  • initialState – The initialState of the payloads, see PayloadsState for details.
  • owner – The owner of the payloads.
Throws:
  • Exception – Any kind of exceptions.
PackagedPayloads
protected PackagedPayloads(File payload, PayloadsRepository owner)

Protected Explicit Constructor.

Parameters:
  • payloads – The payloads directory.
  • owner – The owner of this payload.
Throws:
  • IOException – If the payload is not directory.

Methods

decode
protected void decode()

Decode the payload root to become some useful information.

encode
protected void encode()
getFilename
public String getFilename()

Get the filename of the payload, if it is not packed in tar format

Returns:filename of the payload
getFoldersPayload
public FoldersPayload getFoldersPayload(PayloadsRepository repo, int state, boolean isCreateFolder)

To create a FoldersPayload object for this payload, create the folder in the file system when needed

Parameters:
  • repo – owner repository of this folder payload
  • state – state of the payload folder @see PayloadsState
  • isCreateFolder – whether to create the specific folder in the file system
Throws:
  • IOException – if isCreateFolder is true and cannot create folder successfully
  • PayloadException – if isCreateFolder is true and the folder already existing
Returns:

FoldersPayload object

getPartnershipId
public String getPartnershipId()
Returns:the partnership id.
getRefMessageId
public String getRefMessageId()
Returns:the reference to message id.
isPacked
public boolean isPacked()

Get whether the payload is packed in tar format

Returns:true for packed, false otherwise
save
public void save(InputStream content, boolean append)

Save the content from the input stream to this payloads. If the content stream is null, it save the file with empty content. This method is rarely used in this class because it’s semantics here is to copy the bytes from the inputstream to the package payload.

Parameters:
  • content – The input content stream.
  • append – true if the new content is added to the existing content, false if the new content overwrite the existing.
toString
public String toString()

toString method

PackagedPayloadsRepository

public class PackagedPayloadsRepository extends PayloadsRepository

The outgoing payloads repository retrieves the payload which is in the form of zip files. Creation Date: 5/10/2006

Author:Twinsen Tsang

Fields

PACKAGE_EXT
public static final String PACKAGE_EXT

The packaged payload extension.

Methods

createPayloads
public NamedPayloads createPayloads(Object[] params, int initialState)

Create a customizing payloads for the specified parameter. Since the packaged payloads is in the form of <partnership_id>$<message_id>, so the size of parameters size should have at least 2.

Parameters:
  • params – An array object parameters set for creating the payload.
Throws:
createPayloadsProxy
protected NamedPayloads createPayloadsProxy(File proxyObj)

Create a customizing payloads for this repository.

Parameters:
  • proxyObj – The file object for the payloads.
Returns:

a customizing payloads.

getPayload
public NamedPayloads getPayload(Object[] params, int state)

Get a particular payload in the payload repository by the specified parameters. Since the outgoing payloads is in the form of <partnership_id>$<message_id>, so the size of parameters size should have at least 2.

Parameters:
  • params – An array object parameters set for creating the payload.
  • state – The current state of that payload.
Returns:

the payload with the specified params or null if it does not exist.

getPayloads
public Collection getPayloads()
Returns:return a set of packaged payload.
getProcessingPayloads
public Collection getProcessingPayloads()
Returns:Get the list of processing payloads in the payload repositoy;
getReadyPayloads
public Collection getReadyPayloads()
Returns:return a set of ready to sent payload
init
protected void init()

Invoke for component initialization.

main
public static void main(String[] args)
toString
public String toString()

toString method

PackagedPayloadsRepositoryTest

public class PackagedPayloadsRepositoryTest extends SystemComponentTest<PackagedPayloadsRepository>

Methods

getSystemComponentId
public String getSystemComponentId()
setUp
public void setUp()
tearDown
public void tearDown()
testCreateProcessingPayload
public void testCreateProcessingPayload()

Test creating a processing payload

Throws:
testFindingRepository
public void testFindingRepository()
testGetPayloads
public void testGetPayloads()

Test number of payload in repository

Throws:
testGetReadyPayloads
public void testGetReadyPayloads()

Test whether it can retreive the payload that is ready to send

Throws:
testRenamePayloadToProcessed
public void testRenamePayloadToProcessed()

Test renaming the payload to processed status

Throws:
testRenamePayloadToProcessing
public void testRenamePayloadToProcessing()

Test renaming the payload to processing status

Throws:

PayloadException

public class PayloadException extends GenericException

PayloadException represents all kinds of exception related to SFRM payload. Creation Date: 6/3/2009

Author:Patrick Yip

Constructors

PayloadException
public PayloadException()

Creates a new instance of SFRMException.

PayloadException
public PayloadException(String message)

Creates a new instance of SFRMException.

Parameters:
  • message – the error message.
PayloadException
public PayloadException(Throwable cause)

Creates a new instance of SFRMException.

Parameters:
  • cause – the cause of this exception.
PayloadException
public PayloadException(String message, Throwable cause)

Creates a new instance of SFRMException.

Parameters:
  • message – the error message.
  • cause – the cause of this exception.

PayloadsRepository

public abstract class PayloadsRepository extends SystemComponent

A Generic repository for collect a set of payloads that satisfies some criteria. SPA Component Guideline:

  1. Add a new parameter with the name is “location”.
  2. The value of newly parameter should be the absolute repository path.

Example If the location is C:corvusrepositorytest-repository,

<component id="test" name="Test Repository">
    <class>hk.hku.cecid.edi.sfrm.com.XXXXRepository</class>
    <parameter name="location" value="C:corvusrepositorytest-repository"/>
</component>
  • Creation Date: 5/10/2006
Author:Twinsen

Constructors

PayloadsRepository
public PayloadsRepository()

Constructor.

PayloadsRepository
public PayloadsRepository(String repoPath)

Methods

createPayloads
public abstract NamedPayloads createPayloads(Object[] params, int initialState)

Create a customizing payloads for the specified parameter.

Parameters:
  • params – An array object parameters set for creating the payload.
  • initialState – The initial state of the payloads, see PayloadsState for details
Throws:
createPayloadsProxy
protected abstract NamedPayloads createPayloadsProxy(File proxyObj)

Create a customizing payloads for this repository.

Parameters:
  • proxyObj – The file object for the payloads.
Returns:

a customizing payloads.

getPayload
public NamedPayloads getPayload(String name)

Get a particular payload in the payload repository.

Parameters:
  • name – The physical file name of the payload.
Returns:

the payload with the specified name or null if it does not exist.

getPayload
public abstract NamedPayloads getPayload(Object[] params, int state)

Get a particular payload in the payload repository by the specified parameters.

Parameters:
  • params – An array object parameters set for creating the payload.
  • state – The current state of that payload.
Returns:

the payload with the specified params or null if it does not exist.

getPayloads
public abstract Collection getPayloads()
Returns:Get the list of pending payloads in the payload repository.
getProcessingPayloads
public abstract Collection getProcessingPayloads()
Returns:Get the list of processing payloads in the payload repositoy;
getRepository
public File getRepository()

Get the repository.

Returns:Return the repository.
getRepositoryPath
public String getRepositoryPath()
Returns:get the repository absolute path.
getRepositorySystem
public FileSystem getRepositorySystem()

Get the repository system

Returns:Return the repository.
init
protected void init()

Component Initialization.

Throws:
initRepository
protected void initRepository(String repository)

Initialize the repository. Create the repository if it does not exist.

Parameters:
  • repository
initRepository
protected void initRepository(File repository)

Initialize the repository. Create the repository if it does not exist.

Parameters:
  • repository
toString
public String toString()

toString method.

PayloadsState

public interface PayloadsState

The payload status interface. Creation Date: 13/11/2006

Author:Twinsen

Fields

PLS_FAILED
public int PLS_FAILED
PLS_PENDING
public int PLS_PENDING
PLS_PROCESSED
public int PLS_PROCESSED
PLS_PROCESSING
public int PLS_PROCESSING
PLS_UPLOADING
public int PLS_UPLOADING

hk.hku.cecid.edi.sfrm.dao

CacheException

public class CacheException extends Exception

The CacheException indicate an error for DVO cacher. Creation Date: 12/2/2007

Author:Twinsen Tsang

Constructors

CacheException
public CacheException()

Creates a new instance of CacheException.

CacheException
public CacheException(String message)

Creates a new instance of CacheException.

Parameters:
  • message – the error message.
CacheException
public CacheException(Throwable cause)

Creates a new instance of CacheException.

Parameters:
  • cause – the cause of this exception.
CacheException
public CacheException(String message, Throwable cause)

Creates a new instance of CacheException.

Parameters:
  • message – the error message.
  • cause – the cause of this exception.

DVOCacher

public interface DVOCacher

The DVOCacher is a component that caches the DVO(s) into partiular format designated in the sub-class. To store DVO that have multiple key, it is recommended to combine the key as a string by a separator “_”. For example, If the messageDVO has the key message_id and message_box, You should use combined key message_id_message_box. Creation Date: 12/2/2007

Author:Twinsen Tsang

Methods

activeSize
int activeSize()

The activs size is defined how many DVO are already stored in the cacher.

Returns:Get the active size of DVO cacher.
efficieny
double efficieny()

This method is used to calculate the getDVO(String) efficieny (eff) of the cacher. It is formulated :

            cacheHit
eff = (--------------------) * 100
       cacheHit + cacheMiss
Returns:the efficiency of the cacher.
getDVO
DVO getDVO(String key)

Get the DVO cache from the particular key.

Parameters:
  • key – The key field of the DVO.
Returns:

Return null if the cache record does not exist.

maxSize
int maxSize()

The maximum size is defined how many DVO are the cacher can store before swapping out happens.

Returns:Get the maximum size of DVO cacher.
putDVO
void putDVO(String key, DVO cacheItem)

Store the DVO cacheItem into the cacher with the specified Key. If the DVO in the key is already exist, it throws CacheException indicating cache duplication.

Parameters:
  • key – The key field of the DVO.
  • cacheItem – The DVO item to be cached.
Throws:

See also: .putOrUpdateDVO(String,DVO);

putOrUpdateDVO
void putOrUpdateDVO(String key, DVO cacheItem)

Store or Update the DVO cacheItem into the cacher with the specified Key.

Parameters:
  • key – The key field of the DVO.
  • cacheItem – The DVO item to be cached.
removeAll
void removeAll()

Remove all the cache record.

removeDVO
void removeDVO(String key)

Remove the cache record with the key field equal to key.

Parameters:
  • key – The DVO’s key field to remove.

SFRMMessageDAO

public interface SFRMMessageDAO extends DAO

The Interface of SFRM message dao. Creation Date: 3/10/2006

Author:Twinsen Tsang

Methods

findMessageByMessageBoxAndPartnershipIdAndStatus
public List findMessageByMessageBoxAndPartnershipIdAndStatus(String messageBox, String partnershipId, String status)

Find a list of message record according to the message box and partnership id and status.

Parameters:
  • messageBox – The message box of the message.
  • partnershipId – The partnership id of the message.
  • status – The status of the message.
Throws:
Returns:

a list of message record the satisfy this condition.

findMessageByMessageBoxAndStatus
public List findMessageByMessageBoxAndStatus(String messageBox, String status)

Find a list of message record according to the message box and it’s status.

Parameters:
  • messageBox – The message box of message. it should be “INBOX” or “OUTBOX”.
  • status – The status of the message.
Throws:
Returns:

a list of message record that satisfy this condition.

findMessageByMessageIdAndBox
public SFRMMessageDVO findMessageByMessageIdAndBox(String messageId, String messageBox)

Find a message record with specified message id.

Parameters:
  • messageId – The message id of message to be found.
  • messageBox – The message box of message. it should be “INBOX” or “OUTBOX”.
Throws:
Returns:

return null if not found, otherwise a message record.

findMessageByMessageIdAndBox
public SFRMMessageDVO findMessageByMessageIdAndBox(SFRMMessageDVO message)

Find a message record with specified message record. The field “message id” and “message box” will be used for record finding.

Parameters:
  • message – The message record object to be used for searching.
Throws:
Returns:

return null if not found, otherwise a message record.

findMessageForAcknowledgement
public List findMessageForAcknowledgement(int numberOfMessage, int offset)

Find the message that is ready for requesting the acknowledgement

Parameters:
  • numberOfMessage – Number of message show in the page
  • offset – Offset of the data in the list of the search result
Throws:
Returns:

List of SFRMMessageDVO that is determined for ready to request for acknowledgement

findMessagesByHistory
public List findMessagesByHistory(SFRMMessageDVO data, int numberOfMessage, int offset)

Find messages order by descending timestamp by different criteria.

Parameters:
  • data – The message data value object carrying query criteria.
  • numberOfMessage – max no. of message in return.
  • offset – no. of starting record in return.
Throws:
findMessagesByTime
public List findMessagesByTime(int time_period, SFRMMessageDVO data, int numberOfMessage, int offset)

Find the message by the bound of certain time period

Parameters:
  • time_period – How many month before today
  • data – Criteria to search the message for
  • numberOfMessage – Number of message show in the page
  • offset – Offset of the data in the list of the search result
Throws:
Returns:

List of SFRMMessageDVO that contain the search result

findNumberOfMessagesByHistory
public int findNumberOfMessagesByHistory(SFRMMessageDVO dao)

Find number of the message in the message history by a given search criteria given by dao

Parameters:
  • dao – Search Criteria
Returns:

Number of message found

SFRMMessageDVO

public interface SFRMMessageDVO extends DVO

This is the object that represents a record of SFRMMessage in the database. Creation Date: 29/9/2006

Author:Twinsen Tsang

Methods

getCompletedTimestamp
public Timestamp getCompletedTimestamp()
getCreatedTimestamp
public Timestamp getCreatedTimestamp()
getEncryptAlgorithm
public String getEncryptAlgorithm()
getFilename
public String getFilename()
getIsHostnameVerified
public boolean getIsHostnameVerified()
getMessageBox
public String getMessageBox()
Returns:the message box of the Message DVO.
getMessageId
public String getMessageId()
Returns:the message id of the Message DVO.
getPartnerCertContent
public String getPartnerCertContent()
getPartnerEndpoint
public String getPartnerEndpoint()
Returns:the partnership endpoint of the Message DVO.
getPartnerX509Certificate
public X509Certificate getPartnerX509Certificate()
getPartnershipId
public String getPartnershipId()
Returns:the partnership id of the Message DVO.
getProceedTimestamp
public Timestamp getProceedTimestamp()
getSignAlgorithm
public String getSignAlgorithm()
getStatus
public String getStatus()
getStatusDescription
public String getStatusDescription()
getTotalSegment
public int getTotalSegment()
getTotalSize
public long getTotalSize()
setCompletedTimestamp
public void setCompletedTimestamp(Timestamp completedTimestamp)
setCreatedTimestamp
public void setCreatedTimestamp(Timestamp createdTimestamp)
setEncryptAlgorithm
public void setEncryptAlgorithm(String encryptAlgorithm)
setFilename
public void setFilename(String filename)
setIsHostnameVerified
public void setIsHostnameVerified(boolean isVerified)
setMessageBox
public void setMessageBox(String messageBox)
Parameters:
  • messageBox – the message box of the Message DVO.
setMessageId
public void setMessageId(String messageId)
Parameters:
  • messageId – the message id of the Message DVO.
setPartnerCertContent
public void setPartnerCertContent(String certContent)
setPartnerEndpoint
public void setPartnerEndpoint(String partnerEndpoint)
Parameters:
  • partnerEndpoint – the partnership endpoint of the Message DVO.
setPartnershipId
public void setPartnershipId(String partnershipId)
Parameters:
  • partnershipId – the partnership id of the Message DVO.
setProceedTimestamp
public void setProceedTimestamp(Timestamp proceedTimestamp)
setSignAlgorithm
public void setSignAlgorithm(String aignAlgorithm)
setStatus
public void setStatus(String status)
setStatusDescription
public void setStatusDescription(String statusDescription)
setTotalSegment
public void setTotalSegment(int totalSegment)
setTotalSize
public void setTotalSize(long totalSize)

SFRMMessageSegmentDAO

public interface SFRMMessageSegmentDAO extends DAO

Creation Date: 3/10/2006

Author:Twinsen Tsang

Methods

findIncompleteSegments
public List findIncompleteSegments(String messageBox, String status, String type, int limit)

Find-out all segments which are incomplete in SFRM semantic. Incomplete Segments are defined as their corresponding message is not in the status of either ‘DF’ or ‘PS’. The query support wildcard on status by using ‘%’ string.

findLastUpdatedMessageSegmentByMessageIdAndBoxAndType
public SFRMMessageSegmentDVO findLastUpdatedMessageSegmentByMessageIdAndBoxAndType(String messageId, String messageBox, String type)

Find a message segment recrod with specified parameters. The field “message id”, “message box” and “type” will be used for record searching. The message segment extracted is the last updated segments by other module.

Parameters:
  • messageId – The message id of the message segment.
  • messageBox – The message box of the message segment.
  • type – The type of the message segment
Throws:
Returns:

A message segment record if found.

findMaxSegmentNoByMessageIdAndBoxAndType
public int findMaxSegmentNoByMessageIdAndBoxAndType(String messageId, String messageBox, String type)

Find the maximum number of segment no in the database from the specified parameters.

Parameters:
  • messageId – The message id of the message segment.
  • messageBox – The message box of the message segment.
  • type – The type of the message segment
findMessageSegmentByMessageBoxAndStatusAndTypeAndMessageStatusNotEqualTo
public List findMessageSegmentByMessageBoxAndStatusAndTypeAndMessageStatusNotEqualTo(String messageBox, String status, String type, String messageStatus, int limit)

TODO: Refactor

Parameters:
  • messageBox
  • status
  • type
  • messageStatus
  • limit
Throws:
findMessageSegmentByMessageIdAndBoxAndType
public SFRMMessageSegmentDVO findMessageSegmentByMessageIdAndBoxAndType(String messageId, String messageBox, int segmentNo, String type)

Find a message segment record with specified parameters. The field “message id”, “message box” , “segment no” and “segment type” will be used for record searching.

Parameters:
  • messageId – The message id of the message segment.
  • messageBox – The message box of the message segment.
  • segmentNo – The segment no of the message segment.
  • type – The type of the message segment
Throws:
Returns:

A message segment record if found.

findMessageSegmentsByMessageBoxAndStatus
public List findMessageSegmentsByMessageBoxAndStatus(String messageBox, String status, int limit)

Find a set of message segment record with specified message box and message status.

Parameters:
  • messageBox – The message box of the message segment.
  • status – The status of the message segment.
  • limit – The maximum message segment can be retrieved at one invocation.
Throws:
Returns:

A set of message segment which meets the specified condition or empty list if no record matched.

findMessageSegmentsByMessageBoxAndStatusAndMessageStatusNotEqualTo
public List findMessageSegmentsByMessageBoxAndStatusAndMessageStatusNotEqualTo(String messageBox, String status, String messageStatus, int limit)

Find a set of message segment record with specified message box and message status.

Parameters:
  • messageBox – The message box of the message segment.
  • status – The status of the message segment.
  • messageStatus – The associated main message status of the segment.
  • limit – The maximum message segment can be retrieved at one invocation.
Throws:
Returns:

A set of message segment which meets the specified condition or empty list if no record matched.

findNumOfBytesSentByMessageIdAndBoxAndTypeAndStatues
public long findNumOfBytesSentByMessageIdAndBoxAndTypeAndStatues(String messageId, String messageBox, String type, long proceedTime, List<String> statues)

Find how many segments is available into the database.

Parameters:
  • messageId – The message id of the message segment.
  • messageBox – The message box of the message segment.
  • type – The segment type of the message segment.
  • statues – The statues of the message segment.
Throws:
findNumOfSegmentByMessageIdAndBoxAndTypeAndStatus
public int findNumOfSegmentByMessageIdAndBoxAndTypeAndStatus(String messageId, String messageBox, String type, String status)

Find how many segments is available into the database.

Parameters:
  • messageId – The message id of the message segment.
  • messageBox – The message box of the message segment.
  • type – The segment type of the message segment.
  • status – The status of the message segment.
Throws:
findSegmentByMessageIdAndBoxAndTypeAndNos
public List findSegmentByMessageIdAndBoxAndTypeAndNos(String messageId, String messageBox, String type, List<Integer> segmentNos)

Find segment by their message id, message box, type and list of segment number

Parameters:
  • messageId – message ID
  • messageBox – message box
  • type – segment type
  • segmentNos – list of segment number
Throws:
Returns:

list of SFRMMessageSegmentDVO

findSegmentsByMessageIdAndBoxAndTypeAndStatus
public List findSegmentsByMessageIdAndBoxAndTypeAndStatus(String messageId, String messageBox, String type, String status)

Find segment by their message Id, nessage box, message type and message status

Parameters:
  • messageId – The message id of the message segment.
  • messageBox – The message box of the message segment.
  • type – The segment type of the message segment.
  • status – The status of the message segment.
Throws:
updateBatchSegmentsRecoveryStatus
public int updateBatchSegmentsRecoveryStatus(String status, String messageId, String messageBox, String segmentType, List<Integer> segNums)
updateBatchSegmentsStatus
public int updateBatchSegmentsStatus(String status, Timestamp completeTime, String messageId, String messageBox, String segmentType, List<Integer> segNums)

SFRMMessageSegmentDVO

public interface SFRMMessageSegmentDVO extends DVO

Methods

getCompletedTimestamp
public Timestamp getCompletedTimestamp()
getCreatedTimestamp
public Timestamp getCreatedTimestamp()
getMD5Value
public String getMD5Value()
getMessageBox
public String getMessageBox()
getMessageId
public String getMessageId()
getProceedTimestamp
public Timestamp getProceedTimestamp()
getRetried
public int getRetried()
getSegmentEnd
public long getSegmentEnd()
getSegmentNo
public int getSegmentNo()
getSegmentStart
public long getSegmentStart()
getSegmentType
public String getSegmentType()
getStatus
public String getStatus()
setCompletedTimestamp
public void setCompletedTimestamp(Timestamp completedTimestamp)
setCreatedTimestamp
public void setCreatedTimestamp(Timestamp createdTimestamp)
setMD5Value
public void setMD5Value(String MD5Value)
setMessageBox
public void setMessageBox(String messageBox)
setMessageId
public void setMessageId(String messageId)
setProceedTimestamp
public void setProceedTimestamp(Timestamp proceedTimestamp)
setRetried
public void setRetried(int retried)
setSegmentEnd
public void setSegmentEnd(long segmentEnd)
setSegmentNo
public void setSegmentNo(int segmentNo)
setSegmentStart
public void setSegmentStart(long segmentStart)
setSegmentType
public void setSegmentType(String segmentType)
setStatus
public void setStatus(String status)

SFRMPartnershipDAO

public interface SFRMPartnershipDAO extends DAO
Author:Twinsen Tsang

Methods

findAllPartnerships
public List findAllPartnerships()

Find all of the partnership existing in the database

Returns:return a list of partnership
findPartnershipById
public SFRMPartnershipDVO findPartnershipById(SFRMPartnershipDVO partnershipDVO)

Find the partnership by the partnership object specified in the parameter object. The partnership id field will be retreived and used for the finder.

Parameters:
  • partnershipDVO
Returns:

return null if no partnership found, otherwise the a sfrm partnership.

findPartnershipById
public SFRMPartnershipDVO findPartnershipById(String partnershipId)

Find the partnership by the service string specified in the parameter.

Parameters:
  • partnershipId – The partnership id to used for search partnership.
Returns:

return null if no partnership found, otherwise the a sfrm partnership.

findPartnershipBySeq
public SFRMPartnershipDVO findPartnershipBySeq(SFRMPartnershipDVO partnershipDVO)

Find the partnership by the partnership object specified in the parameter object. The partnership seq field will be retreived and used for the finder.

Parameters:
  • partnershipDVO
Throws:
Returns:

return null if no partnership found, otherwise the a sfrm partnership.

findPartnershipBySeq
public SFRMPartnershipDVO findPartnershipBySeq(int partnershipId)

Find the partnership by it’s seq id.

Parameters:
  • partnershipId
Returns:

return null if no partnership found, otherwise the a sfrm partnership.

SFRMPartnershipDVO

public interface SFRMPartnershipDVO extends DVO

Creation Date: 27/9/2006

Author:Twinsen

Fields

ALG_ENCRYPT_3DES
public static final String ALG_ENCRYPT_3DES
ALG_ENCRYPT_RC2
public static final String ALG_ENCRYPT_RC2
ALG_SIGN_MD5
public static final String ALG_SIGN_MD5
ALG_SIGN_SHA1
public static final String ALG_SIGN_SHA1
CONTEXT_PATH
public static final String CONTEXT_PATH

The context path for sfrm inbound.

PARTNERSHIPID_REGEXP
public static final String PARTNERSHIPID_REGEXP

Methods

getCreationTimestamp
public Timestamp getCreationTimestamp()
getDescription
public String getDescription()
getEncryptAlgorithm
public String getEncryptAlgorithm()
getEncryptX509Certificate
public X509Certificate getEncryptX509Certificate()
getEncryptX509CertificateBase64
public String getEncryptX509CertificateBase64()
getModifiedTimestamp
public Timestamp getModifiedTimestamp()
getOrgPartnerEndpoint
public String getOrgPartnerEndpoint()
getPartnerCertFingerprint
public String getPartnerCertFingerprint()
getPartnerEndpoint
public String getPartnerEndpoint()
getPartnershipId
public String getPartnershipId()
getPartnershipSeq
public int getPartnershipSeq()
getRetryInterval
public int getRetryInterval()
getRetryMax
public int getRetryMax()
getSignAlgorithm
public String getSignAlgorithm()
getVerifyX509Certificate
public X509Certificate getVerifyX509Certificate()
isDisabled
public boolean isDisabled()
isHostnameVerified
public boolean isHostnameVerified()
setCreationTimestamp
public void setCreationTimestamp(Timestamp creationTimestamp)
setDescription
public void setDescription(String description)
setEncryptAlgorithm
public void setEncryptAlgorithm(String encryptAlgorithm)
setIsDisabled
public void setIsDisabled(boolean isDisabled)
setIsHostnameVerified
public void setIsHostnameVerified(boolean isHostnameVerified)
setModifiedTimestamp
public void setModifiedTimestamp(Timestamp modifiedTimestamp)
setPartnerCertFingerprint
public void setPartnerCertFingerprint(String partnerCertFingerprint)
setPartnerEndPoint
public void setPartnerEndPoint(String endpoint)
setPartnershipId
public void setPartnershipId(String partnershipId)
setPartnershipSeq
public void setPartnershipSeq(int partnershipSeq)
setRetryInterval
public void setRetryInterval(int retryInterval)
setRetryMax
public void setRetryMax(int retryMax)
setSignAlgorithm
public void setSignAlgorithm(String signAlgorithm)

SimpleLRUDVOCacher

public class SimpleLRUDVOCacher extends Component implements DVOCacher

The SimpleLRUDVOCacher is the simple DVO cacher which possess LRU, Least-Recently Used features. When there is not enough room to store the DVO as a cache. It tries to remove the oldest record (the one that has not retrieved for longest times). Creation Date: 12/2/2007

Author:Twinsen Tsang

Constructors

SimpleLRUDVOCacher
public SimpleLRUDVOCacher()

Constructor. Use SimpleLRUDVOCacher(int) instead of this constructor. This is reserved for Piazza Common component initialization only.

SimpleLRUDVOCacher
public SimpleLRUDVOCacher(int cacheSize)

Explicit Constructor.

Parameters:
  • cacheSize – The maximum size of the cache.

Methods

activeSize
public int activeSize()

The activs size is defined how many DVO are already stored in the cacher.

Returns:Get the active size of DVO cacher.
efficieny
public double efficieny()

This method is used to calculate the getDVO(String) efficieny (eff) of the cacher. It is formulated :

            cacheHit
eff = (--------------------) * 100
       cacheHit + cacheMiss
Returns:the efficiency of the cacher.
getDVO
public DVO getDVO(String key)

Get the DVO cache from the particular key.

Parameters:
  • key – The key field of the DVO.
Returns:

Return null if the cache record does not exist.

init
protected void init()

Invoked for initialization.

maxSize
public int maxSize()

The maximum size is defined how many DVO are the cacher can store before swapping out happens.

Returns:Get the maximum size of DVO cacher.
putDVO
public void putDVO(String key, DVO cacheItem)

Store the DVO cacheItem into the cacher with the specified Key. If the DVO in the key is already exist, it throws CacheException indicating cache duplication.

Parameters:
  • key – The key field of the DVO.
  • cacheItem – The DVO item to be cached.
Throws:

See also: .putOrUpdateDVO(String,DVO);

putOrUpdateDVO
public void putOrUpdateDVO(String key, DVO cacheItem)

Store or Update the DVO cacheItem into the cacher with the specified Key.

Parameters:
  • key – The key field of the DVO.
  • cacheItem – The DVO item to be cached.
removeAll
public void removeAll()

Remove all the cache record.

removeDVO
public void removeDVO(String key)

Remove the cache record with the key field equal to key.

Parameters:
  • key – The DVO’s key field to remove.

hk.hku.cecid.edi.sfrm.dao.ds

SFRMMessageDSDAO

public class SFRMMessageDSDAO extends DataSourceDAO implements SFRMMessageDAO

The data access object controller for the database table sfrm_message. It provides some useful database-level queries. Creation Date: 29/9/2006

Author:Twinsen Tsang

Methods

createDVO
public DVO createDVO()

Create a new SFRM Message record Object.

Returns:a new SFRM Message record Object.
findMessageByMessageBoxAndPartnershipIdAndStatus
public List findMessageByMessageBoxAndPartnershipIdAndStatus(String messageBox, String partnershipId, String status)

Find a list of message record according to the message box and partnership id and status.

Parameters:
  • messageBox – The message box of the message.
  • partnershipId – The partnership id of the message.
  • status – The status of the message.
Throws:
Returns:

a list of message record the satisfy this condition.

findMessageByMessageBoxAndStatus
public List findMessageByMessageBoxAndStatus(String messageBox, String status)

Find a message record according to the message box and it’s status

Parameters:
  • messageBox – The message box of message. it should be “INBOX” or “OUTBOX”.
  • status – The status of the message.
Throws:
Returns:

a list of message record that satisfy this condition.

findMessageByMessageIdAndBox
public SFRMMessageDVO findMessageByMessageIdAndBox(String messageId, String messageBox)

Find a message record with specified message id.

Parameters:
  • messageId – The message id of message to be found.
  • messageBox – The message box of message. it should be “INBOX” or “OUTBOX”.
Throws:
Returns:

return null if not found, otherwise a message record.

findMessageByMessageIdAndBox
public SFRMMessageDVO findMessageByMessageIdAndBox(SFRMMessageDVO message)

Find a message record with specified message record. The field “message id” and “message box” will be used for record finding.

Parameters:
  • message – The message record object to be used for searching.
Throws:
Returns:

return null if not found, otherwise a message record.

findMessageForAcknowledgement
public List findMessageForAcknowledgement(int numberOfMessage, int offset)
findMessagesByHistory
public List findMessagesByHistory(SFRMMessageDVO data, int numberOfMessage, int offset)

Find messages order by descending timestamp by different criteria.

Parameters:
  • data – The message data value object carrying query criteria.
  • numberOfMessage – max no. of message in return.
  • offset – no. of starting record in return.
Throws:
findMessagesByTime
public List findMessagesByTime(int time_period, SFRMMessageDVO data, int numberOfMessage, int offset)

Find the message by the bound of certain time period. The bounded time period is in term of completed timestamp of message

Parameters:
  • time_period – How many month before today
  • data – Criteria to search the message for
  • numberOfMessage – Number of message show in the page
  • offset – Offset of the data in the list of the search result
Returns:

List of SFRMMessageDVO that contain the search result

findNumberOfMessagesByHistory
public int findNumberOfMessagesByHistory(SFRMMessageDVO data)

Find number of the message in the message history by a given search criteria given by dao

Parameters:
  • dao – Search Criteria
Returns:

Number of message found

SFRMMessageDSDAOTest

public class SFRMMessageDSDAOTest extends DAOTest<SFRMMessageDSDAO>

Test cases for SFRMMessageDAO

Author:Patrick Yip

Methods

getTableName
public String getTableName()
testFindMessageForAcknowledgement
public void testFindMessageForAcknowledgement()

SFRMMessageDSDVO

public class SFRMMessageDSDVO extends DataSourceDVO implements SFRMMessageDVO

The SFRMMessageDSDVO is a data value object that represent a tabular row in sfrm_message at the persistence layer. It possesses caching automatically for most frequently fields shown below:

  1. message id
  2. message box
  3. partnership id
  4. partnership endpoint
  5. requires signing / encryption
  6. status

So developers do not need to worry the issue of thread contention and can freely call the get and set with no performance impact. Creation Date: 29/9/2006 Version 1.0.3 -

  • Added cache for hot access field, it requires extra 22 bytes per SFRMMessageDSDVO object.

Version 1.0.2 -

  • Added conversation id

Version 2.0.0 -

  • Added sign algorithm
  • Removed is signed
  • Added encrypt algorithm
  • Removed is encrypted
Author:Twinsen Tsang

Methods

getCompletedTimestamp
public Timestamp getCompletedTimestamp()

[@GET, THREAD-SAFETY]

Returns:the timstamp that the message has been processed completely.
getCreatedTimestamp
public Timestamp getCreatedTimestamp()

[@GET, THREAD-SAFETY]

Returns:the creation timestamp of this message.
getEncryptAlgorithm
public String getEncryptAlgorithm()
Returns:the encrypt algorithm of this message, return null if message not need to encrypt
getFilename
public String getFilename()

[@GET, THREAD-SAFETY]

Returns:filename field that represent the filename of the original file, if the message payload is not packed in tar format
getIsHostnameVerified
public boolean getIsHostnameVerified()
getMessageBox
public String getMessageBox()

[@GET, THREAD-SAFETY, CACHABLE]

Returns:the message box from the message DVO.
getMessageId
public String getMessageId()

[@GET, THREAD-SAFETY, CACHABLE] Get the message id from the message DVO.

getPartnerCertContent
public String getPartnerCertContent()
getPartnerEndpoint
public String getPartnerEndpoint()

[@GET, THREAD-SAFETY, CACHABLE]

Returns:the partnership endpoint from the message DVO.
getPartnerX509Certificate
public X509Certificate getPartnerX509Certificate()
getPartnershipId
public String getPartnershipId()

[@GET, THREAD-SAFETY, CACHABLE]

Returns:the partnership id from the message DVO.
getProceedTimestamp
public Timestamp getProceedTimestamp()

[@GET, THREAD-SAFETY]

Returns:the timestamp that message is proceeding.
getSignAlgorithm
public String getSignAlgorithm()
Returns:the sign algorithm of this message, return null if message not need to sign
getStatus
public String getStatus()

[@GET, THREAD-SAFETY, CACHABLE]

Returns:get the status of the message DVO.
getStatusDescription
public String getStatusDescription()

[@GET, THREAD-SAFETY]

Returns:the brief description about the message status.
getTotalSegment
public int getTotalSegment()

[@GET, THREAD-SAFETY]

Returns:the total segment of this message DVO.
getTotalSize
public long getTotalSize()

[@GET, THREAD-SAFETY]

Returns:the total size of this message DVO.
setCompletedTimestamp
public void setCompletedTimestamp(Timestamp completedTimestamp)

[@SET, THREAD-SAFETY]

Parameters:
  • the – timestamp that the message has been processed completely.
setCreatedTimestamp
public void setCreatedTimestamp(Timestamp createdTimestamp)

[@SET, THREAD-SAFETY]

Parameters:
  • createdTimestamp – set the creation timestamp of this message.
setData
public void setData(Hashtable hs)

[@OVERRIDE] set the DVO interval dataset and update some boolean cached values.

setEncryptAlgorithm
public void setEncryptAlgorithm(String eAlgorithm)

Set the encrypt algorithm of this message

Parameters:
  • eAlgorithm – encrypt algorithm, null if message didn’t require encryption
setFilename
public void setFilename(String filename)

[@SET, THREAD-SAFETY]

Parameters:
  • filename – filename field that represent the filename of the original file, if the message payload is not packed in tar format
setIsHostnameVerified
public void setIsHostnameVerified(boolean isHostnameVerified)
setMessageBox
public void setMessageBox(String messageBox)

[@SET, THREAD-SAFETY, CACHABLE] Set the message box to the message DVO.

Parameters:
  • message – box either INBOX OR OUTBOX
setMessageId
public void setMessageId(String messageId)

[@SET, THREAD-SAFETY, CACHABLE] Set the message id from the message DVO.

Parameters:
  • messageId – the new message id.
setPartnerCertContent
public void setPartnerCertContent(String partnerCertContent)
setPartnerEndpoint
public void setPartnerEndpoint(String partnerEndpoint)

[@SET, THREAD-SAFETY, CACHABLE] Set the partnership endpoint to the message DVO.

Parameters:
  • partnershipId – the partnership endpoint of this message DVO.
setPartnershipId
public void setPartnershipId(String partnershipId)

[@SET, THREAD-SAFETY, CACHABLE] Set the partnership id to the message DVO.

Parameters:
  • partnershipId – the partnership id of this message DVO.
setProceedTimestamp
public void setProceedTimestamp(Timestamp proceedTimestamp)

[@SET, THREAD-SAFETY]

Parameters:
  • proceedTimestamp – set the timestamp that message is proceeding.
setSignAlgorithm
public void setSignAlgorithm(String sAlgorithm)

Set the signing algorithm of this message

Parameters:
  • sAlgorithm – sign algorithm, null if message didn’t require signing
setStatus
public void setStatus(String status)

[@SET, THREAD-SAFETY, CACHABLE]

Parameters:
  • status – The new status of message DVO.
setStatusDescription
public void setStatusDescription(String statusDescription)

[@SET, THREAD-SAFETY] Set the brief description about the message status.

Parameters:
  • statusDescription – the brief description about the message status.
setTotalSegment
public void setTotalSegment(int totalSegment)

[@SET, THREAD-SAFETY] Set the total segment of this message DVO.

Parameters:
  • totalSegment – the total segment of this message DVO.
setTotalSize
public void setTotalSize(long totalSize)

[@SET, THREAD-SAFETY] Set the total size of this message DVO.

Parameters:
  • totalSegment – the total size of this message DVO.

SFRMMessageSegmentDSDAO

public class SFRMMessageSegmentDSDAO extends DataSourceDAO implements SFRMMessageSegmentDAO

The data access object controller for the database table sfrm_message_segment. It provides some useful database-level queries. Creation Date: 29/9/2006

Author:Twinsen Tsang

Methods

createDVO
public DVO createDVO()

Create a new SFRM Message Segment Object.

Returns:a new SFRM Message Segment Object.
findIncompleteSegments
public List findIncompleteSegments(String messageBox, String status, String type, int limit)

Find-out all segments which are incomplete in SFRM semantic. Incomplete Segments are defined as their corresponding message is not in the status of either ‘DF’ or ‘PS’. The query support wildcard on status by using ‘%’ string.

findLastUpdatedMessageSegmentByMessageIdAndBoxAndType
public SFRMMessageSegmentDVO findLastUpdatedMessageSegmentByMessageIdAndBoxAndType(String messageId, String messageBox, String type)

Find a message segment recrod with specified parameters. The field “message id”, “message box” and “type” will be used for record searching. The message segment extracted is the last updated segments by other module.

Parameters:
  • messageId – The message id of the message segment.
  • messageBox – The message box of the message segment.
  • type – The type of the message segment
Throws:
Returns:

A message segment record if found.

findMaxSegmentNoByMessageIdAndBoxAndType
public int findMaxSegmentNoByMessageIdAndBoxAndType(String messageId, String messageBox, String type)

Find the maximum number of segment no in the database from the specified parameters.

Parameters:
  • messageId – The message id of the message segment.
  • messageBox – The message box of the message segment.
  • type – The type of the message segment
findMessageSegmentByMessageBoxAndStatusAndTypeAndMessageStatusNotEqualTo
public List findMessageSegmentByMessageBoxAndStatusAndTypeAndMessageStatusNotEqualTo(String messageBox, String status, String type, String messageStatus, int limit)
findMessageSegmentByMessageIdAndBoxAndType
public SFRMMessageSegmentDVO findMessageSegmentByMessageIdAndBoxAndType(String messageId, String messageBox, int segmentNo, String type)

Find a message segment record with specified parameters. The field “message id”, “message box” , “segment no” and “segment type” will be used for record finding.

Parameters:
  • messageId – The message id of the message segment.
  • messageBox – The message box of the message segment.
  • type – The status of the message segment
Throws:
Returns:

A set of message segment which meets the specified condition or empty list if no record matched.

findMessageSegmentsByMessageBoxAndStatus
public List findMessageSegmentsByMessageBoxAndStatus(String messageBox, String status, int limit)

Find a set of message segment record with specified message box and message status.

Parameters:
  • messageBox – The message box of the message segment.
  • status – The status of the message segment.
  • limit – The maximum message segment can be retrieved at one invocation.
Throws:
Returns:

A set of message segment which meets the specified condition or empty list if no record matched.

findMessageSegmentsByMessageBoxAndStatusAndMessageStatusNotEqualTo
public List findMessageSegmentsByMessageBoxAndStatusAndMessageStatusNotEqualTo(String messageBox, String status, String messageStatus, int limit)

Find a set of message segment record with specified message box and message status.

Parameters:
  • messageBox – The message box of the message segment.
  • status – The status of the message segment.
  • messageStatus – The associated main message status of the segment.
  • limit – The maximum message segment can be retrieved at one invocation.
Throws:
Returns:

A set of message segment which meets the specified condition or empty list if no record matched.

findNumOfBytesSentByMessageIdAndBoxAndTypeAndStatues
public long findNumOfBytesSentByMessageIdAndBoxAndTypeAndStatues(String messageId, String messageBox, String type, long proceedTime, List<String> statues)
findNumOfSegmentByMessageIdAndBoxAndTypeAndStatus
public int findNumOfSegmentByMessageIdAndBoxAndTypeAndStatus(String messageId, String messageBox, String type, String status)

Find how many segments is available into the database.

Parameters:
  • messageId – The message id of the message segment.
  • messageBox – The message box of the message segment.
Throws:
findSegmentByMessageIdAndBoxAndTypeAndNos
public List findSegmentByMessageIdAndBoxAndTypeAndNos(String messageId, String messageBox, String type, List<Integer> segmentNos)
findSegmentsByMessageIdAndBoxAndTypeAndStatus
public List findSegmentsByMessageIdAndBoxAndTypeAndStatus(String messageId, String messageBox, String type, String status)

Find segment by their message Id, nessage box, message type and message status

Parameters:
  • messageId – The message id of the message segment.
  • messageBox – The message box of the message segment.
  • type – The segment type of the message segment.
  • status – The status of the message segment.
Throws:
updateBatchSegmentsRecoveryStatus
public int updateBatchSegmentsRecoveryStatus(String status, String messageId, String messageBox, String segmentType, List<Integer> segNums)

Update the message segment status in batch

Parameters:
  • status – status of message segments to update to
  • segNums – list of segment number to be update
updateBatchSegmentsStatus
public int updateBatchSegmentsStatus(String status, Timestamp completeTime, String messageId, String messageBox, String segmentType, List<Integer> segNums)

SFRMMessageSegmentDSDAOTest

public class SFRMMessageSegmentDSDAOTest extends DAOTest<SFRMMessageSegmentDSDAO>
Author:Patrick Yip

Methods

getTableName
public String getTableName()
testFindNumOfSegmentByMessageIdAndBoxAndTypeAndStatues
public void testFindNumOfSegmentByMessageIdAndBoxAndTypeAndStatues()
testFindSegmentByMessageIdAndBoxAndTypeAndNos
public void testFindSegmentByMessageIdAndBoxAndTypeAndNos()
testUpdateBatchSegmentsStatus
public void testUpdateBatchSegmentsStatus()

SFRMMessageSegmentDSDVO

public class SFRMMessageSegmentDSDVO extends DataSourceDVO implements SFRMMessageSegmentDVO

Creation Date: 29/9/2006

Author:Twinsen Tsang

Methods

getCompletedTimestamp
public Timestamp getCompletedTimestamp()
getCreatedTimestamp
public Timestamp getCreatedTimestamp()
getMD5Value
public String getMD5Value()
getMessageBox
public String getMessageBox()
getMessageId
public String getMessageId()
getProceedTimestamp
public Timestamp getProceedTimestamp()
getRetried
public int getRetried()
getSegmentEnd
public long getSegmentEnd()
getSegmentNo
public int getSegmentNo()
getSegmentStart
public long getSegmentStart()
getSegmentType
public String getSegmentType()
getStatus
public String getStatus()
setCompletedTimestamp
public void setCompletedTimestamp(Timestamp completedTimestamp)
setCreatedTimestamp
public void setCreatedTimestamp(Timestamp createdTimestamp)
setMD5Value
public void setMD5Value(String MD5Value)
setMessageBox
public void setMessageBox(String messageBox)
setMessageId
public void setMessageId(String messageId)
setProceedTimestamp
public void setProceedTimestamp(Timestamp proceedTimestamp)
setRetried
public void setRetried(int retried)
setSegmentEnd
public void setSegmentEnd(long segmentEnd)
setSegmentNo
public void setSegmentNo(int segmentNo)
setSegmentStart
public void setSegmentStart(long segmentStart)
setSegmentType
public void setSegmentType(String segmentType)
setStatus
public void setStatus(String status)

SFRMPartnershipDSDAO

public class SFRMPartnershipDSDAO extends DataSourceDAO implements SFRMPartnershipDAO

Creation Date: 27/9/2007

Author:Twinsen

Constructors

SFRMPartnershipDSDAO
public SFRMPartnershipDSDAO()

Constructor.

Methods

createDVO
public DVO createDVO()

Create a new SFRM Partnership Object.

Returns:a new SFRM Partnership Object.
findAllPartnerships
public List findAllPartnerships()

Find all partnership order by the partnership id

Returns:return a list of partnership existing in the database
findPartnershipById
public SFRMPartnershipDVO findPartnershipById(SFRMPartnershipDVO partnershipDVO)

Find the partnership by the partnership object specified in the parameter object. The partnership id field will be retreived and used for the finder.

Parameters:
  • partnershipDVO
Returns:

return null if no partnership found, otherwise the a sfrm partnership.

findPartnershipById
public SFRMPartnershipDVO findPartnershipById(String partnershipId)

Find the partnership by the service string specified in the parameter.

Parameters:
  • partnershipId
Returns:

return null if no partnership found, otherwise the a sfrm partnership.

findPartnershipBySeq
public SFRMPartnershipDVO findPartnershipBySeq(SFRMPartnershipDVO partnershipDVO)

Find the partnership by the partnership object specified in the parameter object. The partnership id field will be retreived and used for the finder.

Parameters:
  • partnershipDVO
Throws:
Returns:

return null if no partnership found, otherwise the a sfrm partnership.

findPartnershipBySeq
public SFRMPartnershipDVO findPartnershipBySeq(int partnershipId)

Find the partnership by it’s id.

Parameters:
  • partnershipId
Returns:

return null if no partnership found, otherwise the a sfrm partnership.

SFRMPartnershipDSDAOTest

public class SFRMPartnershipDSDAOTest extends DAOTest<SFRMPartnershipDSDAO>

Methods

getTableName
public String getTableName()
testCheckAllFields
public void testCheckAllFields()
testDeletePartnership
public void testDeletePartnership()
testFindAllPartnerships
public void testFindAllPartnerships()
testFindPartnershipById
public void testFindPartnershipById()
testFindPartnershipByIdNeg
public void testFindPartnershipByIdNeg()
testFindPartnershipByIdObj
public void testFindPartnershipByIdObj()
testFindPartnershipByIdObjNeg
public void testFindPartnershipByIdObjNeg()
testFindPartnershipBySeq
public void testFindPartnershipBySeq()
testFindPartnershipBySeqNeg
public void testFindPartnershipBySeqNeg()
testFindPartnershipBySeqObj
public void testFindPartnershipBySeqObj()
testFindPartnershipBySeqObjNeg
public void testFindPartnershipBySeqObjNeg()
testInsertPartnership
public void testInsertPartnership()
testInsertPartnershipNeg
public void testInsertPartnershipNeg()
testUpdatePartnership
public void testUpdatePartnership()
testUpdatePartnershipNeg
public void testUpdatePartnershipNeg()

SFRMPartnershipDSDVO

public class SFRMPartnershipDSDVO extends DataSourceDVO implements SFRMPartnershipDVO

The SFRMPartnershipDSDVO is a data value object representing a tabular row in the sfrm_partnership in the persistence layer. Creation Date: 27/9/2006 It possesses caching automatically for most frequently fields shown below:

  1. partnership Id
  2. partnership endpoint
  3. maximum retry allowed
  4. retry interval
  5. X509 verfication / encryption cerfiticates

So developers do not need to worry the issue of thread contention and can freely call the get and set with no performance impact. Version 1.0.1 -

  1. Added cache for hot access field, it requires extra 17 bytes + 1 soft reference per SFRMPartnershipDSDVO object.
Author:Twinsen Tsang

Constructors

SFRMPartnershipDSDVO
public SFRMPartnershipDSDVO()

Constructor.

Methods

getCreationTimestamp
public Timestamp getCreationTimestamp()

[@GET, THREAD-SAFETY]

Parameters:
  • get – the creation timestamp of this partnership record.
getDescription
public String getDescription()

[@GET, THREAD-SAFETY] Get the description of the partnership DVO.

getEncryptAlgorithm
public String getEncryptAlgorithm()
getEncryptX509Certificate
public X509Certificate getEncryptX509Certificate()

Get X509 certificate from trusted certificate store specified in SFRM properties

Throws:
Returns:

X509 certificate

getEncryptX509CertificateBase64
public String getEncryptX509CertificateBase64()
getModifiedTimestamp
public Timestamp getModifiedTimestamp()

[@GET, THREAD-SAFETY]

Returns:Get the last modified timestamp
getOrgPartnerEndpoint
public String getOrgPartnerEndpoint()

Get the sending endpoint of the partnership without appended the context path

getPartnerCertFingerprint
public String getPartnerCertFingerprint()

[@GET, THREAD-SAFETY] Get the partnership endpoint of this partnership DVO.

getPartnerEndpoint
public String getPartnerEndpoint()

[@GET, THREAD-SAFETY] Get the sending endpoint of the partnership. The endpoint in the database stores only the address of receiver. For example, like http://127.0.0.1:8080/ or http://sfrm.partnership.com:8080/ But the endpoint returned here will concat a designated conext path = “corvus/httpd/sfrm/inbound”.

getPartnershipId
public String getPartnershipId()

[@GET, THREAD-SAFETY, CACHABLE] Get the partnership from this partnership DVO.

getPartnershipSeq
public int getPartnershipSeq()

[@GET, THREAD-SAFETY] Get the partnership sequence no from this partnership DVO.

getRetryInterval
public int getRetryInterval()

[@GET, NON-THREAD-SAFETY] Get the retry interval of this partnership DVO.

getRetryMax
public int getRetryMax()

[@GET, THREAD-SAFETY] Get the maximum retry allowed for this partnership DVO.

getSignAlgorithm
public String getSignAlgorithm()
getVerifyX509Certificate
public X509Certificate getVerifyX509Certificate()

Get X509 certificate from trusted certificate store specified in SFRM properties

Throws:
Returns:

X509 certificate

isDisabled
public boolean isDisabled()
isHostnameVerified
public boolean isHostnameVerified()

[@GET, THREAD-SAFETY] whether the partnership requires SSL hostname verified.

setCreationTimestamp
public void setCreationTimestamp(Timestamp creationTimestamp)

[@SET, THREAD-SAFETY] Set the creation timestamp.

Parameters:
  • creationTimestamp – the new value of the creation time stamp for this partnership DVO.
setDescription
public void setDescription(String description)

[@SET, THREAD-SAFETY] Set the new description to this partnership DVO.

Parameters:
  • description – The new description.
setEncryptAlgorithm
public void setEncryptAlgorithm(String encryptAlgorithm)
setIsDisabled
public void setIsDisabled(boolean isDisabled)
setIsHostnameVerified
public void setIsHostnameVerified(boolean isHostnameVerified)

[@SET, THREAD-SAFETY] set whether the partnership requires SSL hostname verified.

setModifiedTimestamp
public void setModifiedTimestamp(Timestamp modifiedTimestamp)

[@GET, THREAD-SAFETY] Set the last modified timestamp

Parameters:
  • modifiedTimestamp – the last modified timestamp.
setPartnerCertFingerprint
public void setPartnerCertFingerprint(String partnerCertFingerprint)

[@SET, THREAD-SAFETY] Set the partnership endpoint of this partnership DVO.

setPartnerEndPoint
public void setPartnerEndPoint(String endpoint)

[@GET, THREAD-SAFETY] Set the partnership endpoint of the partnership DVO.

Parameters:
  • endpoint – The new partnership endpoint.
setPartnershipId
public void setPartnershipId(String partnershipId)

[@SET, THREAD-SAFETY] Set the new partnership id to this partnership DVO.

Parameters:
  • partnershipId – The new partnership Id.
setPartnershipSeq
public void setPartnershipSeq(int partnershipSeq)

[@SET, THREAD-SAFETY] Set the partnership sequence

setRetryInterval
public void setRetryInterval(int retryInterval)

[@SET, THREAD-SAFETY] Set the retry interval of this partnership DVO.

setRetryMax
public void setRetryMax(int retryMax)

[@SET, THREAD-SAFETY] Set the maximum retry allowed for this partnership DVO.

setSignAlgorithm
public void setSignAlgorithm(String signAlgorithm)

hk.hku.cecid.edi.sfrm.handler

AcknowledgementHandler

public class AcknowledgementHandler extends SFRMComponent

Methods

getInstance
public static AcknowledgementHandler getInstance()
init
protected void init()

Initialization of this Component

processAcknowledgementResponse
public void processAcknowledgementResponse(String responseContent)

AcknowledgementHandlerTest

public class AcknowledgementHandlerTest extends PluginTest<SFRMProcessor>

Methods

getDBName
public String getDBName()
getDSDAO
public DataSourceDAO getDSDAO()
init
public void init()
postSetUp
public void postSetUp()
postTearDown
public void postTearDown()
testMarkMessagePreCompleted
public void testMarkMessagePreCompleted()

Test if the message status will change to pre-processed, accordingly to the acknowledgement response

Throws:
testUpdateMessageDF
public void testUpdateMessageDF()

Test for dealing with the DF response from receiver

Throws:
testUpdateMessagePS
public void testUpdateMessagePS()

Test for dealing with the PS response from receiver

Throws:
testUpdateMessageSD
public void testUpdateMessageSD()

Test for dealing with the SD response from receiver

Throws:
testUpdateMessageSegmentForPRMessage
public void testUpdateMessageSegmentForPRMessage()

Test if the segment was updated corrspending to the message segment acknowledgement response

Throws:

DSHandler

public abstract class DSHandler extends SystemComponent

The class DSHandler provides abstract interface for getting the actual DAO from the implementation class. Creation Date: 3/10/2006. V1.0.2 - support DVO Caching

Author:Twinsen Tsang

Fields

cacher
protected DVOCacher cacher

The DVO cache.

dao
protected DAO dao

The singleton dao.

isCacheEnable
protected boolean isCacheEnable

The flag indicating whether the cache is enabled ?.

Methods

clearCache
public abstract void clearCache(DVO dvo)

Clear the cache ONLY by a particular dvo object;

getDAOInstance
public DAO getDAOInstance()

The public interface used for other class to access DAO.

Returns:Get the DAO singleton instance.
getInstance
protected abstract DAO getInstance()

Create / Get the instance of DAO.

init
protected void init()

Invoked for initialization. There is following parameters that can be set in this component:

  1. cache-enable: The flag whether the cache should be enabled. [Boolean]
  2. cache-size : The size of cache that can hold without LRU swapping. [Integer]

IncomingMessageHandler

public class IncomingMessageHandler extends SFRMComponent

The incoming message handler is the core class for handling all incoming SFRM segment. It also handles:

  1. Allocation of disk space for HANDSHAKING segment.
  2. Insertion of data content to specified file for PAYLOAD segment.
  3. RECEIPT Response handling
  4. RECOVERY when data integrity check fails.
  5. Error Definition and handling

For details, read processIncomingMessage(SFRMMessage,Object[]) as the entry point for knowing how this class work. Creation Date: 11/10/2006

Author:Twinsen Tsang

Methods

extractPartnership
public SFRMPartnershipDVO extractPartnership(SFRMMessage incomingMessage)

Validate whether the partnership for the incoming message is exist and return that partnership as return value. [SINGLE-THREADED].

Parameters:
  • incomingMessage – The incoming SFRM message.
Throws:
  • MalformedURLException – throw if the partnership does not found or any other database error.
Returns:

A SFRM partnership record.

getInstance
public static IncomingMessageHandler getInstance()
Returns:an instnace of IncomingMessageHandler.
init
protected void init()

Invoked for initialization. The IMH has serval properties :

  1. maxActive: The number of parallel threads for handling incoming segments. The default value is 10. [Integer]
initGuardForSegment
public boolean initGuardForSegment(SFRMMessage incomingMessage)

initalize the Guard so that there is ONLY ONE THREAD working per the incomingMessage.

Parameters:
  • incomgMessage – The incoming SFRM Message.
isDuplicateSegment
public boolean isDuplicateSegment(SFRMMessage incomingMessage)

Validate whether the incoming segment message has been received once.

Parameters:
  • incomingMessage – The incoming SFRM message.
Throws:
  • DAOException – throw if there is any kind of database error.
Returns:

true if it is a duplicated (received already).

isNotEnoughRoom
public boolean isNotEnoughRoom(SFRMMessage incomingMessage, long threshold)

Validate whether the harddisk has enough space for this message. The validation formula is liked this:

 pS  : total payload size
 T   : threshold (the minimum hard disk space)
 HDDS: the remaining hard disk space

true iff (HDDS >= pS + T)
false iff (HDDS < ps + T)
Parameters:
  • incomingMessage – The incoming SFRM message.
  • threshold – The remaining disk space threshold. if the remaining disk space is lower than (this value + the payload size), in this case, it always return false.
Returns:

true if there is enough hard disk space or the associated payloads is created already in the harddisk. vice versa.

isProcessingMessage
public boolean isProcessingMessage(SFRMMessage incomingMessage)

Validate whether the associated message of this incoming segment is processing. Any state except SFRMConstant.MSGS_PROCESSING return false for this method invocation. If the message record does not exist in receiver, we treat this as failure because every segment should has handshaking steps before sending.

Parameters:
  • incomingMessage – The incoming SFRM message.
Throws:
  • DAOException – throw if there is any kind of database error.
  • SFRMMesageException
Returns:

true if it is processing.

logMessage
protected void logMessage(SFRMMessage incomingMessage)

Log the whole message for debug purpose.

Parameters:
  • incomingMessage – The incoming sfrm message.
logMessageType
protected void logMessageType(String type)

Log the message type for debug purpose. The message type currently support for this version is META, PAYLOAD ,RECEIPT and RECOVERY.

Parameters:
  • type – The message type.
processAcknowledgement
public SFRMMessage processAcknowledgement(SFRMMessage msg, SFRMPartnershipDVO pDVO)
processHandshakingMessage
public SFRMMessage processHandshakingMessage(SFRMMessage rawMessage, Object[] params)

Process handshaking for a new message. [SINGLE-THREADED]. The message segment is also META type. In the handshaking steps, it create the message record and check whether it has enough space for receiving the message. This method does not block and return immediately to let the sender know does the receiver is available to receive this message.

Parameters:
  • rawMessage – The incoming SFRM Message.
  • params – RESERVED.
Throws:
Returns:

RESERVED.

processIncomingMessage
public SFRMMessage processIncomingMessage(SFRMMessage incomingMessage, Object[] params)

Process all kind of incoming SFRM message.. This method is invoked when the received HTTP request is transformed to SFRM Message from the SFRM inbound listener.

Parameters:
  • incomingMessage – The incoming SFRM Message.
  • params – RESERVED
Throws:
Returns:

A SFRM message for response message.

processMetaMessage
public SFRMMessage processMetaMessage(SFRMMessage inputMessage, SFRMPartnershipDVO partnershipDVO, Object[] params)

Process all meta-typed message segment. [MULTI-THREADED]. This method pre-allocates the payload and it blocks until the file has been created.

Parameters:
  • inputMessage – The incoming SFRM Message. (unsigned and decrypted)
  • partnershipDVO – The partnership DVO for this incoming message.
  • params – RESERVED.
Throws:
Returns:

RESERVED.

processPDFAck
public String processPDFAck(SFRMMessageDVO mDVO)

Process the acknowledgement with PDF status

Parameters:
  • messageId – message ID
Throws:
Returns:

the acknowledgement response content

processPPSAck
public String processPPSAck(SFRMMessageDVO mDVO)

Process the acknowledgement with PPS status

Parameters:
  • messageId – message ID
Throws:
Returns:

the acknowledgement response content

processPRAck
public String processPRAck(SFRMMessageDVO mDVO, SFRMAcknowledgementParser parser)

Process the acknowledgement request with PR status

Parameters:
  • messageId – message id
  • parser – parser that content the acknowledgement request parsing
Throws:
Returns:

the acknowledgement response content

processPRSAck
public String processPRSAck(SFRMMessageDVO mDVO)

Process the acknowledgement with PRS status

Parameters:
  • messageId – message ID
Throws:
Returns:

the acknowledgement response content

processPSDAck
public String processPSDAck(SFRMMessageDVO mDVO)

Process the acknowledgement with PSD status

Parameters:
  • messageId – message ID
Throws:
Returns:

the acknowledgement response content

processSegmentMessage
public SFRMMessage processSegmentMessage(SFRMMessage rawMessage, Object[] params)

Process payload-typed segment message. What the method has done:

  • Create a segment file in the incoming segment repository.
  • Create a inbox message segment record for the incoming message.
Parameters:
  • inputMessage – The packed SFRMMessage.
  • rawMessage – The unpacked SFRM Message. (i.e. no sign and encrypt here)
  • params – RESERVED
Returns:

A SFRM message for response message.

releaseGuardForSegment
public boolean releaseGuardForSegment(SFRMMessage incomingMessage)

Release the ONE THREAD working GUARD for incomingMessage

Parameters:
  • incomingMessage – The incoming SFRM Message.
resolveGuardOwnerForSegment
public boolean resolveGuardOwnerForSegment(SFRMMessage incomingMessage)

Resolve the guard for the incomingMessage to the new owner (another thread that process the incomingMessage.

Parameters:
  • incomingMesasge – The incoming SFRM Message.
unpackIncomingMessage
public void unpackIncomingMessage(SFRMMessage message, SFRMPartnershipDVO partnershipDVO)

Unpack the SMIME (secure MIME) message to become raw SFRM Message.

Parameters:
  • incomingMessage – The incoming SFRM Message.
  • partnershipDVO – The partnership to valid against to.
Throws:
Returns:

The raw SFRM Message.

IncomingMessageHandlerTest

public class IncomingMessageHandlerTest extends PluginTest<SFRMProcessor>
Author:Patrick Yip

Methods

getDBName
public String getDBName()
getDSDAO
public DataSourceDAO getDSDAO()
init
public void init()
postSetUp
public void postSetUp()
postTearDown
public void postTearDown()
testMetaReceived
public void testMetaReceived()
testMetaReceivedPartnershipNonExist
public void testMetaReceivedPartnershipNonExist()
testProcessPDFAck
public void testProcessPDFAck()
testProcessPPSAck
public void testProcessPPSAck()
testProcessPRAck
public void testProcessPRAck()
testProcessPRSAck
public void testProcessPRSAck()
testProcessPSDAck
public void testProcessPSDAck()

MessageStatusQueryHandler

public class MessageStatusQueryHandler extends SFRMComponent

Handler to hold all the speed measurement class for active transferring SFRM Message. Active transferring message mean the message status is in PS processing

Author:Patrick Yip

Methods

addMessageSpeedQuery
public StatusQuery addMessageSpeedQuery(String messageId)

Add a message for monitoring the message status

Parameters:
  • messageId – SFRM Message ID
Returns:

newly created StatusQuery

getInstance
public static MessageStatusQueryHandler getInstance()
getMessageList
public Iterator<String> getMessageList()

Get the list of message ID which is monitoring by this handler

Returns:iterator of message ID
getMessageSpeedQuery
public StatusQuery getMessageSpeedQuery(String messageId)

Get the StatusQuery for a particular message

Parameters:
  • messageId
Returns:

StatusQuery for a given message, null if is non-exist

getTotalSpeed
public double getTotalSpeed()

Get the total speed for the currently transfering message

Returns:total speed
init
protected void init()
removeMessageSpeedQuery
public StatusQuery removeMessageSpeedQuery(String messageId)

Remove the status query for particular message

Parameters:
  • messageId – SFRM Message ID
Returns:

removed SpeedQuery

OutgoingMessageHandler

public class OutgoingMessageHandler extends SFRMComponent

The outgoing message handler is a singleton classes that provides service for processing outgoing SFRM message. Creation Date: 5/12/2006

Author:Twinsen Tsang

Methods

getInstance
public static OutgoingMessageHandler getInstance()
Returns:an instance of OutgoingMessageHandler.
init
protected void init()

Initialization of this Component

packOutgoingMessage
protected SFRMMessage packOutgoingMessage(SFRMMessage message, String signAlgorithm, String encryptAlgorithm, X509Certificate encryptCert)

Pack the SMIME (secure MIME) message to become secured SFRM Message. Currently, the packing mechanisms support:

  1. Digitial Signing using MD5 or SHA-1
  2. Encryption using RC2_CBC or DES_EDE3_CBC
Parameters:
  • message – The outgoing SFRM Message.
  • msgDVO – The message record associated to this SFRM message.
  • pDVO
Throws:
  • UnrecoverableKeyException
  • NoSuchAlgorithmException
  • SFRMException
Returns:

The secured SFRM message.

sendMessage
public FastHttpConnector sendMessage(SFRMMessage message, String endpoint, boolean isHostVerified, String signAlg, String encryptAlg, X509Certificate encryptCert)

Send SFRM message.

Parameters:
  • message – The original SFRM Message.
  • isSign – Digital signature is required
  • isEncryptReq – Encryption is required
  • signAlg – Signing algorithm
  • encryptAlg – Encryption algorithm
  • encrypt – Partner public certificate for encryption
Throws:
Returns:

HTTP response

sendMessageWithMessageResponse
public SFRMMessage sendMessageWithMessageResponse(SFRMMessage message, String endpoint, boolean isHostVerified, String signAlg, String encryptAlg, X509Certificate encryptCert)

OutgoingMessageHandlerTest

public class OutgoingMessageHandlerTest extends SystemComponentTest<OutgoingMessageHandler>
Author:Patrick Yip

Methods

getSystemComponentId
public String getSystemComponentId()
setUp
public void setUp()
tearDown
public void tearDown()
testCreateHandshakingRequest
public void testCreateHandshakingRequest()
testEncryptDES3MetaMessge
public void testEncryptDES3MetaMessge()
testEncryptMetaMessgeFailed
public void testEncryptMetaMessgeFailed()
testEncryptRC2MetaMessge
public void testEncryptRC2MetaMessge()
testMetaMessgeHeader
public void testMetaMessgeHeader()
testOutgoingMetaMessageFail
public void testOutgoingMetaMessageFail()

Test for sending the handshaking message

Throws:
testPlainMetaMessge
public void testPlainMetaMessge()
testSendMetaMessage
public void testSendMetaMessage()

Test for sending the handshaking message

Throws:
testSignEncryptMetaMessge
public void testSignEncryptMetaMessge()
testSignMD5MetaMessge
public void testSignMD5MetaMessge()
testSignMetaMessgeFailed
public void testSignMetaMessgeFailed()
testSignSHA1MetaMessge
public void testSignSHA1MetaMessge()

SFRMDoSHandler

public class SFRMDoSHandler extends Component

The SFRMDoSHandler is a simple barrier to ensure there is ONLY one-thread working per segment. When an incoming message is received and prepare to process, the IMH invoke enter(SFRMMessage) asking the DoSHandler to insert the working record for this segment. Then if there is a duplicate message received, the DosHandler reject it due to the working record has already exist. Thus it guarantees ONE THREAD WORKING per segment semantics. CAUTION: When the thread in the working record is not alive, the DoSHandler considers the working record is redundant and ALLOW message with same composite key owning a barrier for that message. Creation Date: 28/6/2007

Author:Twinsen Tsang

Methods

enter
public boolean enter(SFRMMessage message)

Invoke for requesting a barrier for message. For this case, the requested barrier does not expire.

Parameters:
  • message – The incoming SFRM Message.
Returns:

if the message has been entered by other thread before, it return false. otherwise, the barrier for this message is created and the owner is the invocation thread.

enter
public boolean enter(SFRMMessage message, long lifetime)

Invoke for requesting a barrier for message.

Parameters:
  • message – The incoming SFRM Message.
  • lifetime – How long is the barrier expire in millisecond. The common use for this is managing timeout/retry for a message.
Returns:

if the message has been entered by other thread before, it return false. otherwise, the barrier for this message is created and the owner is the invocation thread.

exit
public boolean exit(SFRMMessage message)

Invoke for removing the barrier for a message. The internal barrier for this message is removed and therefore invocating enter(SFRMMessage) for this mesasge return true again.

Parameters:
  • message – The incoming SFRM Message.
Returns:

it returns true iff the working record exists and remove successfully.

getResolvedKey
public String getResolvedKey(SFRMMessage message)

Get the composite key from the message. What it does is generating one string indentifying the message. For example:

Input message id: test@message-id
Input segment type: PAYLOAD
Input segment number: 999

Then the resolved key is test@message-id_INBOX_PAYLOAD_999
Parameters:
  • message – The incoming SFRM Message.
Returns:

the composite key of thie SFRM Message.

SFRMDoSHandlerTest

public class SFRMDoSHandlerTest extends TestCase

The test-case of SFRMDoSHandler. Creation Date: 03/07/2007

Author:Twinsen Tsang

Methods

setUp
protected void setUp()

Invoke for setup.

testEnterAfterThreadDie_Pos_0
public void testEnterAfterThreadDie_Pos_0()

Testcase for entering the message after previous thread owner has been died.

testEnterAfterThreadDie_Pos_1
public void testEnterAfterThreadDie_Pos_1()

Testcase for entering the message being owner by other active thread.

testEnterWithLifetime_Pos_0
public void testEnterWithLifetime_Pos_0()

Testcase for a message entering the DoSHandler with a specified lifetime. The record should be removed after at least (1 + sweeping_interval) seconds.

testEnterWithLifetime_Pos_1
public void testEnterWithLifetime_Pos_1()

Testcase for a message entering the DosHandler with a specified lifetime. The record should exist within the lifetime.

testEnter_Neg_0
public void testEnter_Neg_0()

Testcase for duplicate message entering the DosHandler.

testEnter_Pos_0
public void testEnter_Pos_0()

Simplest Testcase for a message entering the DoS Handler.

testEnter_Pos_1
public void testEnter_Pos_1()

Testcase for multiple message entering the DoS Handler.

testExit_Neg_0
public void testExit_Neg_0()

Testcase for entering one record, but with a illegal message exiting.

testExit_Pos_0
public void testExit_Pos_0()

Testcase for entering and exiting for one record.

SFRMExternalRequestHandler

public class SFRMExternalRequestHandler extends SFRMComponent
Author:Patrick Yip

Methods

getInstance
public SFRMExternalRequestHandler getInstance()
init
protected void init()
resumeMessage
public synchronized void resumeMessage(String messageId)
suspendMessage
public synchronized void suspendMessage(String messageId)

SFRMExternalRequestHandlerTest

public class SFRMExternalRequestHandlerTest extends PluginTest<SFRMProcessor>

Methods

getDBName
public String getDBName()
getDSDAO
public DataSourceDAO getDSDAO()
init
public void init()
testResumeMessage
public void testResumeMessage()
testResumeNonExistingMessage
public void testResumeNonExistingMessage()

Test if client want to resume the non-existing message

Throws:
testResumeProcessedMessage
public void testResumeProcessedMessage()

Test if client want to resume the processed message

Throws:
testSuspendMessage
public void testSuspendMessage()
testSuspendNonExistMessage
public void testSuspendNonExistMessage()
testSuspendProcessedMessage
public void testSuspendProcessedMessage()

SFRMMessageFactory

public class SFRMMessageFactory extends Component

It is the [FACTORY] of the SFRM Message. It provides API for creating all kinds of SFRM Message in the version 1.0.3 specification. Creation Date: 5/12/2006

Author:Twinsen Tsang

See also: hk.hku.cecid.edi.sfrm.pkg.SFRMMessage

Methods

createAcknowledgement
public SFRMMessage createAcknowledgement(SFRMMessageDVO mDVO, SFRMPartnershipDVO pDVO, String segType, String ackContent)
createHandshakingRequest
public SFRMMessage createHandshakingRequest(String messageId, String partnershipId, int totalSegment, long totalSize, String filename)

Create a handshaking request which is used for communicate to the receiver for delivery confirmation. This kind of SFRMMessage segment has the type called “META”.

Parameters:
  • messageId – The message Id of segment.
  • partnershipId – The partnership Id of segment.
  • totalSegment – The total segment of message.
  • totalSize – The total size of message.
Throws:
Returns:

A new handshaking SFRM Message.

createPayloadRequest
public SFRMMessage createPayloadRequest(String messageId, String partnershipId, int segmentNo, long segmentOffset, long segmentLength, long totalSize, File payload, String contentType)
Parameters:
  • messageId
  • partnershipId
  • segmentNo
  • segmentOffset
  • segmentLength
  • totalSize
  • payload
  • contentType
Throws:
getInstance
public static SFRMMessageFactory getInstance()
Returns:an instnace of SFRMMessageFactory.
setupMessage
protected void setupMessage(SFRMMessage ret, String messageId, String partnershipId, String segmentType, String convId, int segmentNo, File payload, String contentType)

Setup the message field according to the specified parameters.

Parameters:
  • ret
  • messageId
  • partnershipId
  • segmentType
  • convId
  • segmentNo

SFRMMessageHandler

public class SFRMMessageHandler extends DSHandler

THe SFRM Message handler is a proxy object of DAO layers. It wraps with some useful query like retrieve message and create message by the SFRM Meta Header. Creation Date: 3/10/2006 V1.0.1 - supports DVO caching.

Author:Twinsen Tsang

Methods

clearCache
public void clearCache(DVO dvo)

Clear the cache ONLY by a particular dvo object;

createMessageBySFRMMetaMessage
public SFRMMessageDVO createMessageBySFRMMetaMessage(SFRMMessage msg, SFRMPartnershipDVO pDVO, String messageBox, String status, String statusDesc)

Create a new message record by a SFRM Mesasge which is meta type.

Parameters:
  • msg – The SFRM message.
  • pDVO – The partnership associated with this message.
  • messageBox – The message box of the new message record.
  • status – The status of the new message record.
  • statusDesc – The status description of the new message record.
Throws:
  • DAOException – If the sfrm message is null or with segment no not equal to zero , or other database error.
  • SFRMException
  • IOException
  • FileNotFoundException
Returns:

return null if database error, otherwise a new message record.

getInstance
protected DAO getInstance()

Create / Get the instance of DAO.

removeMessage
public boolean removeMessage(SFRMMessageDVO msgDVO)

Remove the msgDVO to the pesistence DB. Developer SHOULD use this method instead of hk.hku.cecid.piazza.commons.dao.DAO.remove(hk.hku.cecid.piazza.commons.dao.DVO) because this invocation also manage the DVO cache.

Parameters:
  • msgDVO – The message DVO to be update.
Throws:
Returns:

true if operation success, fail vice versa.

retrieveAcknowledgmentMessages
public List retrieveAcknowledgmentMessages(int numOfMessage, int offset)

Retrieve a set of messages that is required to ack the acknowledgement from receiver

Parameters:
  • numOfMessage – number of messages for acknowledgement request
  • offset – offset in the message records
Throws:
Returns:

a list of message that is required to ack the acknowledgement

retrieveMessage
public SFRMMessageDVO retrieveMessage(String messageId, String messageBox)

Retrieve a message from the specified parameters. This method support caching. If the particular DVO is already in the cache, it returned immediately without JDBC calls.

Parameters:
  • messageId – The message id of the message.
  • messageBox – The message box of the message. either inbox or outbox.
Throws:
Returns:

return null if not found by the specified parameter, otherwise a message record.

retrieveMessages
public List retrieveMessages(String messageBox, String status)

Retrieve a set of messages from the specified parameters.

Parameters:
  • messageBox – The message box of the message. either inbox or outbox.
  • status – The status of the message.
Throws:
Returns:

return a list of message that fit the criteria.

updateMessage
public boolean updateMessage(SFRMMessageDVO msgDVO)

Update the msgDVO to the pesistence DB. Developer SHOULD use this method instead of hk.hku.cecid.piazza.commons.dao.DAO.persist(hk.hku.cecid.piazza.commons.dao.DVO) because this invocation also manage the DVO cache.

Parameters:
  • msgDVO – The message DVO to be update.
Returns:

true if operation success, fail vice versa.

SFRMMessageSegmentHandler

public class SFRMMessageSegmentHandler extends DSHandler

The SFRM Message Segment handler is a proxy object of DAO layers. It wraps with some useful query like retrieve message segment and create message by the SFRM Message Header. Creation Date: 9/10/2006

Author:Twinsen Tsang

Methods

clearCache
public void clearCache(DVO dvo)

DOES NOT SUPPORT CACHING.

createMessageSegmentBySFRMMessage
public SFRMMessageSegmentDVO createMessageSegmentBySFRMMessage(SFRMMessage message, String messageBox, String status)

Create an Message Segment according to the SFRM message.

Parameters:
  • message – The message segmented used for generating the message segment record.
  • messageBox – The message box for the mesasge. It should either be “inbox” or “outbox”.
  • status – The status for the new message segment record. if this field is null, we conside the status is PENDING.
Throws:
Returns:

a message segment dvo if the operation runs succesfully.

getInstance
protected DAO getInstance()

Create / Get the instance of DAO.

retrieveDeliveredSegmentForMessage
public List retrieveDeliveredSegmentForMessage(String messageId)
retrieveIncompleteSegments
public List retrieveIncompleteSegments(String messageBox, String status, String type, int limit)
retrieveLastUpdatedMessageSegment
public SFRMMessageSegmentDVO retrieveLastUpdatedMessageSegment(String messageId, String messageBox, String type)

Select the last updated message segment with the specified parameter. The last updated message segment is defined as the message segment which has the latest proceedTimestamp value.

Parameters:
  • messageId – The message id of the message segment belong to.
  • messageBox – The message box of the message segment. It should either “inbox” or “outbox”.
  • type – The segment type (META, PAYLOAD, RECEIPT, RECOVERY)
Throws:
Returns:

A message segment dvo if the operation runs succesfully.

retrieveLastUpdatedTimestamp
public Timestamp retrieveLastUpdatedTimestamp(String messageId, String messageBox, String type)

Select the last updated timestamp with the specified parameter. The last updated message segment is defined as the message segment which has the latest proceedTimestamp value.

Parameters:
  • messageId – The message id of the message segment belong to.
  • messageBox – The message box of the message segment. It should either “inbox” or “outbox”.
  • type – The segment type (META, PAYLOAD, RECEIPT, RECOVERY)
Throws:
Returns:

A message segment dvo if the operation runs succesfully.

retrieveMaxMessageSegmentNumber
public int retrieveMaxMessageSegmentNumber(String messageId, String messageBox, String type)

Find the maximum segment number it has in the DB for the specified message.

Parameters:
  • messageId – The message id of the message segment belong to.
  • messageBox – The message box of the message segment.
  • type – The segment type (META, PAYLOAD, RECEIPT, RECOVERY)
Throws:
retrieveMessageSegment
public SFRMMessageSegmentDVO retrieveMessageSegment(String messageId, String messageBox, int segmentNo, String type)

Select a message segment with the specified parameter.

Parameters:
  • messageId – The message id of the message segment belong to.
  • messageBox – The message box of the message segment. It should either “inbox” or “outbox”.
  • segmentNo – The segment number of the segment
  • type – The segment type (META, PAYLOAD, RECEIPT, RECOVERY)
Throws:
Returns:

A message segment dvo if the operation runs succesfully.

retrieveMessageSegment
public SFRMMessageSegmentDVO retrieveMessageSegment(SFRMMessage message, String messageBox)

Select a message segment with the specified parameter. The segment type is omitted here is this query.

Parameters:
  • message – The message segmented used for get the message segment record.
  • messageBox – The message box for the mesasge. It should either be “inbox” or “outbox”.
Throws:
Returns:

A message segment dvo if the operation runs succesfully.

retrieveMessageSegmentCount
public int retrieveMessageSegmentCount(String messageId, String messageBox, String type, String status)

Find how many message for the partiucalur message id and message box are available in the database.

Parameters:
  • messageId – The message id of the message segment belong to.
  • messageBox – The message box of the message segment. Either inbox or outbox can be allowed.
  • type – The segment type of the message segment.
  • status – The status of the message segment
Throws:
retrieveMessages
public List retrieveMessages(String messageBox, String status, int limit)

Retrieve a set of messages from the specified parameters.

Parameters:
  • messageBox – The message box of the message segment. Either inbox or outbox can be allowed.
  • status – The status of the message segment.
  • limit – The maximum message that can be retrieved.
Throws:
Returns:

Return a list of message that fit the criteria.

retrieveMessages
public List retrieveMessages(String messageBox, String status, String messageStatus, int limit)
retrieveMessages
public List retrieveMessages(String messageBox, String status, String type, String messageStatus, int limit)
retrieveMessages
public List retrieveMessages(String messageId, String messageBox, String messageType, String[] status)

Find message segment by providing the message ID, message box, message type and a list of status

Parameters:
  • messageId – The message id of the mesage segment belong to
  • messageBox – The message box of the message segment
  • messageType – The segment type (META, PAYLOAD, ACK)
  • status – The status of message status
Throws:
Returns:

List of SFRMMessageSegmentDVO

retrieveMessages
public List retrieveMessages(String messageId, String messageBox, String type, List<Integer> segmentNums)

SFRMPartnershipHandler

public class SFRMPartnershipHandler extends DSHandler

Creation Date: 28/9/2006 V1.0.1 - supports DVO caching.

Author:Twinsen

Methods

addPartnership
public boolean addPartnership(SFRMPartnershipDVO pDVO, String mID)

Add a SFRM Partnership by partnership object specified in the parmeter.

Parameters:
  • pDVO – The SFRM Partnership to be added for.
  • mID – The message id for the requesting partnership.
Throws:
Returns:

false if operation fails to execute, otherwise true.

clearCache
public void clearCache(DVO dvo)

[Overriden] Clear the cache ONLY by a particular dvo object. NOT YET IMPLEMENTED.

Parameters:
  • dvo – The partnership object to be removed in the cache.
clearCache
public void clearCache(String pID, String mID)

Clear the cache ONLY by a particular partnership id.

Parameters:
  • pID – The partnership object has pID to be removed in the cache.
  • mID – The message id for the requesting partnership.
createPartnership
public SFRMPartnershipDVO createPartnership()

Create a SFRM Partnership object.

Throws:
Returns:

A new SFRM Partnership object.

getInstance
protected DAO getInstance()

Create / Get the instance of DAO.

removePartnership
public boolean removePartnership(SFRMPartnershipDVO pDVO)

Remove a SFRM Partnership by partnership object specified in the parameter.

Parameters:
  • pDVO
Throws:
Returns:

false if operation fails to execute, otherwise true.

retreivePartnership
public SFRMPartnershipDVO retreivePartnership(String pID, String mID)

Select a SFRM Partnership by the service parameter.

Parameters:
  • pID – The partnership id name of the partnership id to be search.
  • mID – The message id for the requesting partnership.
Throws:
Returns:

null if not found, otherwise the SFRM Partnership.

retreivePartnership
public SFRMPartnershipDVO retreivePartnership(SFRMPartnershipDVO pDVO, String mID)

Select a SFRM Partnership by the keys specified in the parameter.

Parameters:
  • pDVO – The SFRM Partnership to be found for.
  • mID – The message id for the requesting partnership.
Throws:
Returns:

null if not found, otherwise the SFRM Partnership.

retreivePartnership
public SFRMPartnershipDVO retreivePartnership(SFRMMessage msg)

Select a SFRM Partnership by the SFRM message.

Parameters:
  • msg – The SFRM Message record used for finding it’s associate partnership.
Throws:
Returns:

null if not found, otherwise the SFRM Partnership.

updatePartnership
public boolean updatePartnership(SFRMPartnershipDVO pDVO, String mID)

Update a SFRM Partnership by partnership object specified in the parameter.

Parameters:
  • pDVO – The SFRM Partnership to be updated for.
  • mID – The message id for the requesting partnership.
Throws:
Returns:

false if operation fails to execute, otherwise true.

hk.hku.cecid.edi.sfrm.io

ByteBufferInputStream

public class ByteBufferInputStream extends InputStream

A ByteBufferInputStream contains an internal buffer that contains direct or non-direct byte buffer that may be read from the stream. Creation Date: 24/10/2006

Author:Twinsen Tsang

Fields

buf
protected ByteBuffer buf

The internal byte buffer.

Constructors

ByteBufferInputStream
public ByteBufferInputStream(ByteBuffer buffer)

Creates a ByteBufferInputStream so that it uses buf as its byte buffer. The buffer array is not copied.

Parameters:
  • buf – the input buffer.

Methods

available
public int available()

Returns the number of bytes that can be read from this input stream without blocking. The value returned is limit of byte buffer. which is the number of bytes remaining to be read from the input buffer.

Returns:the number of bytes that can be read from the input stream without blocking.
close
public void close()

Close the stream.

getChannel
public ReadableByteChannel getChannel()

Returns the readable byte channel object associated with this byte buffer input stream.

Returns:a readable byte channel for this byte buffer.

See also: java.nio.channels.Channels

mark
public synchronized void mark(int readlimit)

Mark this stream.

markSupported
public boolean markSupported()

Mark is support by this InputStream.

Returns:always true
read
public int read()

Reads the next byte of data from this input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned.

read
public int read(byte[] b)
read
public int read(byte[] b, int off, int len)
reset
public synchronized void reset()

Resets the buffer to the marked position. The marked position is 0 unless another position was marked or an offset was specified in the constructor.

ChecksumException

public class ChecksumException extends IOException

An exception that should be thrown when the check sum value for a file is invalid. Creation Date: 21/12/2006

Author:Twinsen

Constructors

ChecksumException
public ChecksumException()

Creates a new instance of ChecksumException.

ChecksumException
public ChecksumException(String message)

Creates a new instance of ChecksumException.

Parameters:
  • message – the error message.

NullInputStream

public class NullInputStream extends InputStream

A NullInputStream discards any bytes and always return negative one for read operations. Creation Date: 7/11/2006

Author:Twinsen

Methods

available
public int available()

It returns -1.

markSupported
public boolean markSupported()

It returns false.

read
public int read(byte[] b, int off, int len)

It returns -1.

read
public int read(byte[] b)

It returns -1.

read
public int read()

It returns -1.

reset
public synchronized void reset()

DUMMY Methods.

NullOutputStream

public class NullOutputStream extends OutputStream

A NullOutputStream discards any bytes in write operations. Creation Date: 11/10/2006

Author:Twinsen Tsang

Methods

close
public void close()

DUMMY

flush
public void flush()

DUMMY

write
public void write(int b)

DUMMY.

write
public void write(byte[] b, int off, int len)

DUMMY

write
public void write(byte[] b)

DUMMY

hk.hku.cecid.edi.sfrm.listener

SFRMInboundListener

public class SFRMInboundListener extends SFRMRequestAdaptor

This is the inbound listener for receiving the payload segment from the sender.

Author:Twinsen

Methods

processRequest
public void processRequest(SFRMRequest request, SFRMResponse response)

See also: hk.hku.cecid.edi.sfrm.listener.SFRMRequestAdaptor.processRequest(hk.hku.cecid.edi.as2.listener.SFRMRequest,hk.hku.cecid.edi.as2.listener.SFRMResponse)

SFRMRequest

public class SFRMRequest

The SFRMRequest class represents a wrapper of HTTP request wrapping the SFRMMessage inside.

Author:Twinsen Tsang

Constructors

SFRMRequest
SFRMRequest()

Creates a new instance of SFRM Request.

SFRMRequest
SFRMRequest(Object source)

Creates a new instance of SFRM Request.

Parameters:
  • source – the source which initiated this request.

Methods

getMessage
public SFRMMessage getMessage()

Gets the SOAP message of this request.

Returns:the SOAP message of this request.
getSource
public Object getSource()

Gets the source which initiated this request.

Returns:the source which initiated this request.
setMessage
void setMessage(SFRMMessage message)

Sets the SOAP message of this request.

Parameters:
  • message – the SOAP message of this request.
setSource
void setSource(Object source)

Sets the source which initiated this request.

Parameters:
  • source – the source which initiated this request.

SFRMRequestAdaptor

public abstract class SFRMRequestAdaptor extends HttpRequestAdaptor

This is the sfrm customizied HTTP Request Adaptor.

Author:Twinsen

See also: hk.hku.cecid.piazza.commons.servlet.http.HttpRequestAdaptor

Methods

processFail
public String processFail(HttpServletRequest request, HttpServletResponse response, Exception cause)

It process a HTTP request from the piazza corvus framework when there is exception thrown from underlying handler.

Parameters:
  • request – The HTTP Request
  • response – The HTTP Response
  • cause – The exception cause to fail.
processRequest
public String processRequest(HttpServletRequest request, HttpServletResponse response)

It process a HTTP request from the piazza corvus framework.

Parameters:
  • request – The HTTP Request
  • response – The HTTP Response
Throws:

See also: hk.hku.cecid.piazza.commons.servlet.http.HttpRequestListener.processRequest(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)

processRequest
public abstract void processRequest(SFRMRequest request, SFRMResponse response)
Parameters:
  • request
  • response
Throws:

SFRMResponse

public class SFRMResponse

The SFRMResponse class represents a wrapper of HTTP response wrapping the SFRMMessage inside.

Author:Twinsen Tsang

Constructors

SFRMResponse
SFRMResponse()

Creates a new instance of AS2Response.

SFRMResponse
SFRMResponse(Object target)

Creates a new instance of AS2Response.

Parameters:
  • target – the target that this response should be committed to.

Methods

getMessage
public SFRMMessage getMessage()

Gets the SOAP message of this response.

Returns:the SOAP message of this response.
getTarget
public Object getTarget()

Gets the target that this response should be committed to.

Returns:the target that this response should be committed to.
setMessage
public void setMessage(SFRMMessage message)

Sets the SOAP message of this response.

Parameters:
  • message – the SOAP message of this response.
setTarget
void setTarget(Object target)

Sets the target that this response should be committed to.

Parameters:
  • target – the target that this response should be committed to.

hk.hku.cecid.edi.sfrm.net

FastHttpConnector

public class FastHttpConnector extends HttpConnector

Creation Date: 10/10/2006 Modified Date: 17/06/2009

Author:Twinsen, Philip

Constructors

FastHttpConnector
public FastHttpConnector(Object destUrl)

Creates a new instance of HttpConnector.

Parameters:
  • destUrl – the destination URL, either in String or URL format.
Throws:
  • MalformedURLException – if the URL is malformed.

Methods

getResponseCode
public int getResponseCode()

Sends an HTTP/S request using the given HTTP connection.

Parameters:
  • request – the HTTP request content or null for a simple get request.
  • internet – headers
Throws:
Returns:

an input stream for reading the reply from the host.

getResponseContentStream
public InputStream getResponseContentStream()
getResponseHeaders
public InternetHeaders getResponseHeaders()
send
public HttpURLConnection send(InputStream request, InternetHeaders headers)

hk.hku.cecid.edi.sfrm.pkg

SFRMAcknowledgementBuilder

public class SFRMAcknowledgementBuilder
Author:Patrick Yip To build the SFRM Acknowledgement content body

Fields

ID_ATTR
public static final String ID_ATTR
MESSAGES_TAG
public static final String MESSAGES_TAG
MESSAGE_NODE_XPATH_PARAM
public static final String MESSAGE_NODE_XPATH_PARAM
MESSAGE_SEGMENT_NODE_XPATH_PARAM
public static final String MESSAGE_SEGMENT_NODE_XPATH_PARAM
MESSAGE_SEGMENT_XPATH_PARAM
public static final String MESSAGE_SEGMENT_XPATH_PARAM
MESSAGE_TAG
public static final String MESSAGE_TAG
MESSAGE_XPATH
public static final String MESSAGE_XPATH
NUM_ATTR
public static final String NUM_ATTR
PARAM_TOKEN
public static final String PARAM_TOKEN
SEGMENTS_TAG
public static final String SEGMENTS_TAG
SEGMENT_TAG
public static final String SEGMENT_TAG
STATUS_ATTR
public static final String STATUS_ATTR
STATUS_TAG
public static final String STATUS_TAG

Constructors

SFRMAcknowledgementBuilder
public SFRMAcknowledgementBuilder()

Constructor for Acknowledgement Builder, create an empty acknowledgement content

Methods

getMessageSegmentXPath
public static String getMessageSegmentXPath(String messageId, int segmentNum)
getMessageXPath
public static String getMessageXPath(String messageId)
getSegmentsXPath
public static String getSegmentsXPath(String messageId)
setMessage
public Element setMessage(String messageId, String status)

Set the message information to the acknowledgment content, if the message is not present, it will create an entry, otherwise it will modify the entry

Parameters:
  • messageId – message id
  • status – message status
Returns:

the newly created or modified XML element

setSegment
public Element setSegment(String messageId, int segmentNum, String segmentStatus)

Set the message segment information for a given message id, if the message segment is present, it will create one, otherwise it will modify the existing entry

Parameters:
  • messageId – message id for message segment
  • segmentNum – segment number
  • segmentStatus – segment status
Throws:
Returns:

the newly created or modified XML element

toString
public String toString()

SFRMAcknowledgementBuilderTest

public class SFRMAcknowledgementBuilderTest extends TestCase
Author:Patrick Yip

Methods

setUp
protected void setUp()
tearDown
protected void tearDown()
testSimpleCreate
public void testSimpleCreate()

SFRMAcknowledgementParser

public class SFRMAcknowledgementParser

Constructors

SFRMAcknowledgementParser
public SFRMAcknowledgementParser(String xmlContent)

Methods

getMessageSegmentNums
public List<Integer> getMessageSegmentNums(String messageId)

Get a list of mesasge segmnet num for the specific message

Parameters:
  • messageId – message ID
Returns:

list of message segment number

getMessageSegmentStatus
public String getMessageSegmentStatus(String messageId, int segmentNum)

Get status for specific message segment

Parameters:
  • messageId – message ID
  • segmentNum – segment number
Returns:

message segment status

getMessageStatus
public String getMessageStatus(String messageId)

Get status for a specific message

Parameters:
  • messageId – message ID
Returns:

message status

getMessagesIDs
public List<String> getMessagesIDs()

Get the list of message ID in the acknowledgement

Returns:list of message ID
getNumMessageSegment
public int getNumMessageSegment(String messageId)

Get the number of message segment for specific message

Parameters:
  • messageId – message ID
Returns:

number of message segments

getNumMessages
public int getNumMessages()

Get the number of message in the acknowledgement

Returns:number of messages

SFRMAcknowledgementParserTest

public class SFRMAcknowledgementParserTest extends TestCase

Methods

setUp
public void setUp()
tearDown
public void tearDown()
testGetMessageList
public void testGetMessageList()
testGetMessageSegmentList
public void testGetMessageSegmentList()
testGetNumMessageSegment
public void testGetNumMessageSegment()
testGetNumMessages
public void testGetNumMessages()
testMessageSegmentStatus
public void testMessageSegmentStatus()
testMessageStatus
public void testMessageStatus()

SFRMConstant

public final class SFRMConstant

The constant field for SFRM Message. Creation Date: 13/11/2006 Version 1.0.1 - Added Message status Description Constant.

Author:Twinsen Tsang

Fields

DEFAULT_CONTENT_TYPE
public static final String DEFAULT_CONTENT_TYPE
MESSAGE_DIGEST_MD5
public static final String MESSAGE_DIGEST_MD5
MESSAGE_DIGEST_SHA1
public static final String MESSAGE_DIGEST_SHA1
MSGBOX_IN
public static final String MSGBOX_IN
MSGBOX_OUT
public static final String MSGBOX_OUT
MSGSDESC_HANDSHAKING
public static final String MSGSDESC_HANDSHAKING
MSGSDESC_NODISKSPACE
public static final String MSGSDESC_NODISKSPACE
MSGSDESC_PACAKGED
public static final String MSGSDESC_PACAKGED
MSGSDESC_PACKAGING
public static final String MSGSDESC_PACKAGING
MSGSDESC_PRE_DELIVERY_FAILED
public static final String MSGSDESC_PRE_DELIVERY_FAILED
MSGSDESC_PRE_PROCESSED
public static final String MSGSDESC_PRE_PROCESSED
MSGSDESC_PRE_RESUME
public static final String MSGSDESC_PRE_RESUME
MSGSDESC_PRE_SUSPENDED
public static final String MSGSDESC_PRE_SUSPENDED
MSGSDESC_PROCESSED
public static final String MSGSDESC_PROCESSED
MSGSDESC_PROCESSING
public static final String MSGSDESC_PROCESSING
MSGSDESC_SEGMENTING
public static final String MSGSDESC_SEGMENTING
MSGSDESC_SUSPENDED
public static final String MSGSDESC_SUSPENDED

New description for SFRM V2

MSGSDESC_UNPACKAGING
public static final String MSGSDESC_UNPACKAGING
MSGS_DELIVERED
public static final String MSGS_DELIVERED
MSGS_DELIVERY_FAILURE
public static final String MSGS_DELIVERY_FAILURE
MSGS_HANDSHAKING
public static final String MSGS_HANDSHAKING
MSGS_PACKAGED
public static final String MSGS_PACKAGED
MSGS_PACKAGING
public static final String MSGS_PACKAGING
MSGS_PENDING
public static final String MSGS_PENDING
MSGS_PRE_DELIVERY_FAILED
public static final String MSGS_PRE_DELIVERY_FAILED
MSGS_PRE_PROCESSED
public static final String MSGS_PRE_PROCESSED
MSGS_PRE_RESUME
public static final String MSGS_PRE_RESUME
MSGS_PRE_SUSPENDED
public static final String MSGS_PRE_SUSPENDED
MSGS_PROCESSED
public static final String MSGS_PROCESSED
MSGS_PROCESSING
public static final String MSGS_PROCESSING
MSGS_PROCESSING_ERROR
public static final String MSGS_PROCESSING_ERROR
MSGS_SEGMENTING
public static final String MSGS_SEGMENTING
MSGS_SUSPENDED
public static final String MSGS_SUSPENDED

New status for SFRM V2

MSGS_UNPACKAGING
public static final String MSGS_UNPACKAGING
MSGT_ACK_REQUEST
public static final String MSGT_ACK_REQUEST
MSGT_ACK_RESPONSE
public static final String MSGT_ACK_RESPONSE
MSGT_ERROR
public static final String MSGT_ERROR
MSGT_META
public static final String MSGT_META
MSGT_PAYLOAD
public static final String MSGT_PAYLOAD
WILDCARD
public static final String WILDCARD
XML_CONTENT_TYPE
public static final String XML_CONTENT_TYPE

Methods

getStatusDescription
public static String getStatusDescription(String status)

SFRMHeader

public class SFRMHeader

SFRMHeader represents a set of SFRM message headers. Version 1.0.2 - Added Converation Id. Version 1.0.1 - Header schema updated for the impl of on-the-fly sending and recv mode. Remove deprecated fields. Version 2.0.0 - Add Is-Packed header field Add Filename header field

Author:Twinsen Tsang

Fields

MESSAGE_ID
public static final String MESSAGE_ID

The SFRM message id field.

SFRM_CONVERATION
public static final String SFRM_CONVERATION

The SFRM converation id field. This field is RESERVED.

SFRM_FILENAME
public static final String SFRM_FILENAME

The SFRM field to represent the file name of the payload. This field is significance when the Is-Packed file is set to No.

SFRM_META_TOTAL_SEGMENT
public static final String SFRM_META_TOTAL_SEGMENT

The SFRM total segment field for meta message.

SFRM_PARTNERSHIP
public static final String SFRM_PARTNERSHIP

The SFRM partnership id field.

SFRM_RECEIPT_LAST
public static final String SFRM_RECEIPT_LAST

The SFRM flag for representing it is a the last receipt / ack of the message.

SFRM_SEGMENT_LENGTH
public static final String SFRM_SEGMENT_LENGTH

The SFRM segment length field.

SFRM_SEGMENT_NO
public static final String SFRM_SEGMENT_NO

The SFRM segment no field.

SFRM_SEGMENT_OFFSET
public static final String SFRM_SEGMENT_OFFSET

The SFRM segment offset field.

SFRM_SEGMENT_TYPE
public static final String SFRM_SEGMENT_TYPE

The SFRM segment type field.

SFRM_TOTAL_SIZE
public static final String SFRM_TOTAL_SIZE

The SFRM total size field for message.

SFRM_VERSION
public static final String SFRM_VERSION

The SFRM version field. The current value of this field is 1.0.2.

SFRMMessage

public class SFRMMessage implements Cloneable

This is the SFRM Message used for wrapping the payload and send it to the receiver side. Specification: Creation Date: 29/9/2006 Version 1.0.2 -

  • Add a message classifier for recognizing the message nature much easily.

Version 1.0.1 -

  • MIC Value is stored into ContentMD5 in the MimeBodyPart.
  • Support cloning.
Author:Twinsen Tsang

Fields

ALG_ENCRYPT_3DES
public static final String ALG_ENCRYPT_3DES
ALG_ENCRYPT_RC2
public static final String ALG_ENCRYPT_RC2
ALG_SIGN_MD5
public static final String ALG_SIGN_MD5
ALG_SIGN_SHA1
public static final String ALG_SIGN_SHA1
SFRM_MESSAGE_VERSION
public static final String SFRM_MESSAGE_VERSION

The current version of SFRM Message.

Constructors

SFRMMessage
public SFRMMessage()

Creates a new instance of SFRM Message.

SFRMMessage
public SFRMMessage(InputStream message)

Creates a new instance of SFRM Message.

Parameters:
  • message – the message as input stream.
Throws:
  • SFRMMessageException – if unable to construct from the given input stream.
SFRMMessage
public SFRMMessage(InternetHeaders headers, InputStream content)

Creates a new instance of SFRMMessage.

Parameters:
  • headers – the headers of this message.
  • ins – the content stream.
Throws:
  • SFRMMessageException – if unable to construct from the given content stream.

Methods

addHeader
public void addHeader(String name, String value)

Adds a message header of the specified name.

Parameters:
  • name – the header name.
  • value – the header value.
clone
protected Object clone()
Returns:returns a clone for this Message.
decrypt
public void decrypt(X509Certificate cert, PrivateKey privateKey)
digest
public static String digest(InputStream inStream)
digest
public static String digest(FileRegionDataSource frds)
digest
public String digest()
encrypt
public void encrypt(X509Certificate cert, String encryptAlg)
getBodyPart
public MimeBodyPart getBodyPart()

Gets the MIME body part of this message.

Returns:the MIME body part.
getClassifier
public SFRMMessageClassifier getClassifier()
Returns:a message classifier for this message.
getContent
public Object getContent()

Gets the content of payload from this message.

Throws:
Returns:

the content part.

getContentStream
public InputStream getContentStream()

Gets the content stream of this message.

Returns:the content stream of this message. null if there is no content.
getContentType
public String getContentType()

Gets the content type of the payload from this message.

Throws:
Returns:

the content type.

getConverationId
public String getConverationId()
Returns:the SFRM conversation id from the message.
getFilename
public String getFilename()

Get the filename of SFRM payload

Returns:filename of the SFRM payload
getHeader
public String getHeader(String name)

Gets a message header of the specified name.

Parameters:
  • name – the header name.
Returns:

the header value.

getHeader
public String getHeader(String name, String def)

Gets a message header of the specified name.

Parameters:
  • name – the header name.
  • def – the default value.
Returns:

the header value.

getHeaders
public InternetHeaders getHeaders()

Gets the headers of this message.

Returns:a copy of the headers of this message.
getHostname
public String getHostname()
Returns:the host name of the message.
getInputStream
public InputStream getInputStream()

Gets the input stream of this message’s content. Any transfer encodings will be decoded before the input stream is provided.

Throws:
Returns:

the input stream of this message’s content.

getMessageID
public String getMessageID()

Gets the message ID.

Returns:the message ID.
getMicValue
public String getMicValue()
Returns:the mic value of this message.
getPartnershipId
public String getPartnershipId()
Returns:the SFRM partnership id from the message.
getSegmentLength
public long getSegmentLength()
Returns:the SFRM segment length from this message.
getSegmentNo
public int getSegmentNo()
Returns:the SFRM segmet no from the message.
getSegmentOffset
public long getSegmentOffset()
Returns:the SFRM segment offset position from the message.
getSegmentType
public String getSegmentType()
Returns:the SFRM segment type from the message.
getTotalSegment
public int getTotalSegment()
Returns:get the total segment in the meta message.
getTotalSize
public long getTotalSize()
Returns:the total size of payload in the meta message.
getVersion
public String getVersion()
Returns:the SFRM Version from the message.
isEncryptedContentType
public boolean isEncryptedContentType()
isSignedContentType
public boolean isSignedContentType()
removeHeader
public void removeHeader(String name)

Removes a message header of the specified name.

Parameters:
  • name – the header name.
setBodyPart
public void setBodyPart(MimeBodyPart bp)

Sets the MIME body part of this message.

Parameters:
  • bp – the new MIME body part.
setContent
public void setContent(Object content, String contentType)

Sets a content to this message.

Parameters:
  • content – the content part.
  • contentType – the content type.
Throws:
setContent
public void setContent(Object content, String contentType, String transferEncoding)
setConversationId
public void setConversationId(String conversationId)

Set the conversation id of this message.

Parameters:
  • conversationId – The conversation id.
setFilename
public void setFilename(String filename)

Set the filename of the SFRM payload

Parameters:
  • filename – the filename of the SFRM payload to be set
setHeader
public void setHeader(String name, String value)

Sets a message header of the specified name.

Parameters:
  • name – the header name.
  • value – the header value.
setIsEncrypted
public void setIsEncrypted(boolean isEncrypted)

Set whether the message is encrypted.

Parameters:
  • isEncrypted – true if encrypted, false vice versa.
setIsSigned
public void setIsSigned(boolean isSigned)

Set whether the message is signed.

Parameters:
  • isSigned – true if signed, false vice versa.
setMessageID
public void setMessageID(String messageId)

Set the message id of this message.

Parameters:
  • messageId – The message id of this message.
setMicValue
public void setMicValue(String micValue)

Set the MIC value of the message. I.e. the checksum of this message.

Parameters:
  • micValue – the mic value of this message.
setPartnershipId
public void setPartnershipId(String partnershipId)

Set the partnership id of the message.

setSegmentLength
public void setSegmentLength(long length)

Set the segment payload into this message. The segment length will only be set when it is greater than or equal to zero.

Parameters:
  • length – The length of this segment.
setSegmentNo
public void setSegmentNo(int segmentNo)

Set the segment number of the message. The segment number will only be set when it is greater than or equal to zero.

Parameters:
  • segmentNo – The segment number of message.
setSegmentOffset
public void setSegmentOffset(long offset)

Set the segment offset of this message. The segment offset will only be set when it is greater than or equal to zero.

Parameters:
  • offset – The offset of this segment.
setSegmentType
public void setSegmentType(String segmentType)

Set the segment type of the message. It can only be either “META”, “PAYLOAD”, “RECEIPT” AND “RECOVERY”.

Parameters:
  • segmentType – The segment type of the message.
setTotalSegment
public void setTotalSegment(int totalSegment)

Set the total segment in the meta message.

Parameters:
  • totalSegment – The total segment of the message.
setTotalSize
public void setTotalSize(long totalSize)

Set the total size in the meta message.

Parameters:
  • totalSize – The total size of the message.
sign
public void sign(X509Certificate cert, PrivateKey privateKey, String digestAlg)
toByteArray
public byte[] toByteArray()

Returns a byte array which represents this message contnet.

Throws:
Returns:

a byte array which represents this message.

toByteBuffer
public ByteBuffer toByteBuffer(boolean hardwareBuffer)

Returns a byte buffer which represents this message content, i.e. a MIME body part byte buffer.

Parameters:
  • hardwareBuffer
toString
public String toString()

Returns a string representation of this message.

Returns:a string representation of this message.

See also: java.lang.Object.toString()

verify
public void verify(X509Certificate cert)
writeTo
public void writeTo(OutputStream outs)

Writes the message to the given output stream.

Parameters:
  • outs – the output stream to be written.
Throws:

SFRMMessageClassifier

public class SFRMMessageClassifier

The SFRMMessageClassifier is a classifier for SFRM segments. It provide very fast and efficient access to crtiical information for it’s corresponding segment. Creation Date: 10/11/2006

Author:Twinsen Tsang

Constructors

SFRMMessageClassifier
public SFRMMessageClassifier(SFRMMessage message)

Explicit Constructor.

Parameters:
  • message – The sfrm message need to be classify.
Throws:
  • NullPointerException – if the message is null.
  • SFRMMessageException
  • Exception

Methods

getMagicNumber
public byte getMagicNumber()
Returns:Get the internal presentation of the message structure.
isAcknowledgementRequest
public boolean isAcknowledgementRequest()
isEncrypted
public boolean isEncrypted()
Returns:true if the message is encrypted.
isError
public boolean isError()
Returns:true if it is a error message.
isMeta
public boolean isMeta()
Returns:true if it is a meta message.
isPayload
public boolean isPayload()
Returns:true if it is a payload message.
isSigned
public boolean isSigned()
Returns:true if the message is signed.
setEncrypted
protected void setEncrypted(boolean isEncrypt)

[Protected]

Parameters:
  • isEncrypt – the flag indicate whether the messags is encrypted or not.
setSigned
protected void setSigned(boolean isSign)

[Protected]

Parameters:
  • isSign – the flag indicate whether the message is signed or not.

SFRMMessageClassifierTest

public class SFRMMessageClassifierTest extends TestCase

Methods

setUp
public void setUp()
tearDown
public void tearDown()
testIsAck
public void testIsAck()
testIsNotAck
public void testIsNotAck()

SFRMMessageException

public class SFRMMessageException extends GenericException

SFRMMessageException represents an exception related to SFRM message.

Author:Twinsen

Constructors

SFRMMessageException
public SFRMMessageException()

Creates a new instance of AS2MessageException.

SFRMMessageException
public SFRMMessageException(String message)

Creates a new instance of AS2MessageException.

Parameters:
  • message – the error message.
SFRMMessageException
public SFRMMessageException(Throwable cause)

Creates a new instance of AS2MessageException.

Parameters:
  • cause – the cause of this exception.
SFRMMessageException
public SFRMMessageException(String message, Throwable cause)

Creates a new instance of AS2MessageException.

Parameters:
  • message – the error message.
  • cause – the cause of this exception.

SFRMMessageTest

public class SFRMMessageTest extends TestCase
Author:Patrick Yip

Methods

setUp
public void setUp()
tearDown
public void tearDown()
testLargeFileMD5
public void testLargeFileMD5()

hk.hku.cecid.edi.sfrm.service

SFRMMessageResumeService

public class SFRMMessageResumeService extends WebServicesAdaptor
Author:Patrick Yip

Methods

serviceRequested
public void serviceRequested(WebServicesRequest request, WebServicesResponse response)

SFRMMessageStatusQueryService

public class SFRMMessageStatusQueryService extends WebServicesAdaptor

The SFRMMessageStatusQueryService is a SOAP-based Web services for querying the current status of particular SFRM message. The web services schema is defined here: Input XML tag:

<messageId> messageId</messageId>

Output XML tag:

<messageInfo>
    <status> The current status of message </status>
    <statusDescription> The current status description of message </statusDescription>
    <numberOfSegments> Maximum number of segments </numberOfSegments>
    <numberOfProcessedSegments> Number of processed segments </numberOfProcessedSegments>
    <lastUpdatedTime>  The last updated timestamp  </lastUpdatedTime>
</messageInfo>

There are some situation that the returned value may differ than your expectation and they are listed below:

  1. When the SFRM message is in status of handshaking (HS), the number of segments is
    maximum integer. This is because the number of segments can not be determined at that moment.
  2. When the SFRM message can’t be found by the web service parameter. The returned tuple is [“N/A”,””, “2147483647”,”0”,”current time].

Creation Date: 26/4/2007

Author:Twinsen Tsang

Methods

isCacheEnabled
protected boolean isCacheEnabled()
serviceRequested
public void serviceRequested(WebServicesRequest request, WebServicesResponse response)

Process the web services call by the client.

Parameters:
  • request – The SOAP-based Web services request.
  • response – The SOAP-based Web services response.
Throws:

SFRMMessageSuspendService

public class SFRMMessageSuspendService extends WebServicesAdaptor

Methods

serviceRequested
public void serviceRequested(WebServicesRequest request, WebServicesResponse response)

Process the web services call by the client.

Parameters:
  • request – The SOAP-based Web services request.
  • response – The SOAP-based Web services response.
Throws:

hk.hku.cecid.edi.sfrm.spa

SFRMComponent

public abstract class SFRMComponent extends SystemComponent
Author:Patrick Yip

Methods

getAcknowledgementHandler
public AcknowledgementHandler getAcknowledgementHandler()
getExternalRequestHandler
public SFRMExternalRequestHandler getExternalRequestHandler()
getIncomingMessageHandler
public IncomingMessageHandler getIncomingMessageHandler()
getIncomingRepository
public PackagedPayloadsRepository getIncomingRepository()
getKeyStoreManager
public KeyStoreManager getKeyStoreManager()
getMessageHandler
public SFRMMessageHandler getMessageHandler()
getMessageSegmentHandler
public SFRMMessageSegmentHandler getMessageSegmentHandler()
getMessageSpeedQueryHandler
public MessageStatusQueryHandler getMessageSpeedQueryHandler()
getOSManager
public OSManager getOSManager()
getOutgoingMessageHandler
public OutgoingMessageHandler getOutgoingMessageHandler()
getOutgoingRepository
public PackagedPayloadsRepository getOutgoingRepository()
getPartnershipHandler
public SFRMPartnershipHandler getPartnershipHandler()

SFRMException

public class SFRMException extends GenericException

SFRMException represents all kinds of exception related to SFRM processing. Creation Date: 27/9/2006

Author:Twinsen Tsang

Constructors

SFRMException
public SFRMException()

Creates a new instance of SFRMException.

SFRMException
public SFRMException(String message)

Creates a new instance of SFRMException.

Parameters:
  • message – the error message.
SFRMException
public SFRMException(Throwable cause)

Creates a new instance of SFRMException.

Parameters:
  • cause – the cause of this exception.
SFRMException
public SFRMException(String message, Throwable cause)

Creates a new instance of SFRMException.

Parameters:
  • message – the error message.
  • cause – the cause of this exception.

SFRMLog

public interface SFRMLog

The SFRMLog is the log code for the logging statement in the sfrm.log files. For detail, please read “doc/logcode.txt”.

Author:Twinsen Tsang

Fields

ATC_CALLER
public static final String ATC_CALLER

The constant field for indicating the log prefix for AcknowledgementCollector log.

AT_CALLER
public static final String AT_CALLER

The constant field for indicating the log prefix for AcknowledgementTask log.

CREATE_SGT
public static final String CREATE_SGT

The constant field for indicating creating segment in the log.

DECRYPT_SGT
public static final String DECRYPT_SGT

The constant field for indicating the de-crypting segment in the log.

ENCRYPT_SGT
public static final String ENCRYPT_SGT

The constant field for indicating the encrypting segment in the log.

FAIL_CRC
public static final String FAIL_CRC

The constant field for indicating CRC fail in the log.

FAIL_HDSK
public static final String FAIL_HDSK

The constant field for indicating failure in processing handshaking request in the log.

FIRST_LOAD
public static final String FIRST_LOAD

The constant field for indicating the first load in the collector.

ILLEGAL_SGT
public static final String ILLEGAL_SGT

The constant field for receiving a illegal segment.

IMH_CALLER
public static final String IMH_CALLER

The constant field for the prefix of the Incoming Message Handler log.

INSERT_SGTS
public static final String INSERT_SGTS

The constant field for indicating insertion segments in the log.

IPTC_CALLER
public static final String IPTC_CALLER

The constant field for indicating the log prefix for IncomingPayloadCollector log.

IPT_CALLER
public static final String IPT_CALLER

The constant field for the prefix of the Incoming Payloads Task log.

MSC_CALLER
public static final String MSC_CALLER

The constant field for indicating the log prefix for MessageStatusCollecotr log.

MSGID_PREFIX
public static final String MSGID_PREFIX

The constant field for logging message id prefix.

MSHDAO_CALLER
public static final String MSHDAO_CALLER

The constant field for indicating the log prefix for SFRMMessageSegmentHandler log.

NOTIFY_REPT
public static final String NOTIFY_REPT

The constant field for indicating the last receipt has been sent and notify to all thread waiting in the global lock.

OMH_CALLER
public static final String OMH_CALLER

The constant field for the prefix of the Outgoing Message Handler log.

OPPTC_CALLER
public static final String OPPTC_CALLER

The constant field for indicating the log prefix for OutgoingPackagedPayloadCollector log.

OPPT_CALLER
public static final String OPPT_CALLER

The constant field for the prefix of the log. Outgoing Packaged Payload Task log.

OPTC_CALLER
public static final String OPTC_CALLER

The constant field for indicating the log prefix for OutgoingPayloadCollector log.

OPT_CALLER
public static final String OPT_CALLER

The constant field for the prefix of the log. Outgoing Payload Task log.

OSPTC_CALLER
public static final String OSPTC_CALLER

The constant field for indicating the log prefix for OutgoingSegmentPayloadsCollector log.

OSPT_CALLER
public static final String OSPT_CALLER

The constant field for the prefix of the log. Outgoing Segment Payload Task log.

OUTG_TASK
public static final String OUTG_TASK

The constant field for indicating a new outgoing task is executing in the log.

PACK_MSG
public static final String PACK_MSG

The constant field for indicating packing message in the log.

QUERY_STATUS
public static final String QUERY_STATUS

The constant field for indicating there is web services client query the status of particular SFRM message.

RECEIVE_ALL
public static final String RECEIVE_ALL

The constant field for receiving all in the log.

RECEIVE_DUP
public static final String RECEIVE_DUP

The constant field for receiving duplication in the log.

RECEIVE_FAIL
public static final String RECEIVE_FAIL

The constant field for indicating fail to receive in incoming message handler.

RECEIVE_HDSK
public static final String RECEIVE_HDSK

The constant field for receiving handshaking request in the log.

RECEIVE_META
public static final String RECEIVE_META

The constant field for indicating received meta in the log.

RECEIVE_SGT
public static final String RECEIVE_SGT

The constant field for receiving msg in the log.

RESOLVE_FAIL
public static final String RESOLVE_FAIL

The constant field for failure to resolve the segment barrier.

ROLL_BACK
public static final String ROLL_BACK

The constant field for indicating the roll back action in outgoing payload task.

SEND_ALL
public static final String SEND_ALL

The constant field for indicating sending all segment with reliable receipt.

SEND_HDSK
public static final String SEND_HDSK

The constant field for indicating sending handshaking message in the log.

SEND_SGT
public static final String SEND_SGT

The constant field for indicating sending outgoing message in the log.

SGTNO_PREFIX
public static final String SGTNO_PREFIX

The constant field for logging segment number prefix.

SIGNING_SGT
public static final String SIGNING_SGT

The constant field for indicating the signing segment in the log.

SPANNED_THRD
public static final String SPANNED_THRD

The constant field for indicating a new thread is spanning in the Incoming Message Handler for handling the segment request.

SQS_CALLER
public static final String SQS_CALLER

The constant field for indicating the log prefix for SFRMMessageStatusQueryService log.

SUCCESS_CRC
public static final String SUCCESS_CRC

The constant field for indicating CRC successfully in the log.

UNPACK_MSG
public static final String UNPACK_MSG

The constant field for indicating the un-packing message in the log.

UNPACK_SGT
public static final String UNPACK_SGT

The constant field for indicating the un-packing segment in the log.

VERIFY_SGT
public static final String VERIFY_SGT

The constant field for indicating the verifiying segment in the log.

WAIT_REPT
public static final String WAIT_REPT

The constant field for indicating the need to wait for all receipt to be done.

SFRMLogUtil

public class SFRMLogUtil

The SFRMLogUtil Creation Date: 03/07/2007

Author:Twinsen Tsang

Fields

DEFAULT_BUFFER_LENGTH
public static final int DEFAULT_BUFFER_LENGTH

Methods

debug
public static void debug(String caller, String action, String segmentType)
log
public static void log(String caller, String action, String messageId, int segmentNumber)
Parameters:
  • caller
  • action
  • messageId
  • segmentNumber
log
public static void log(String caller, String action, int segmentNumber)
Parameters:
  • caller
  • action
  • segmentNumber
logInfo
public static String logInfo(String caller, String action, SFRMMessage message)
Parameters:
  • caller
  • action
  • message

SFRMProcessor

public class SFRMProcessor extends PluginProcessor

The SFRM SPA plugin processor for initiating and containing the references to all SFRM components. Creation Date: 27/9/2006

Author:Twinsen, Philip

Fields

moduleGroup
protected static ModuleGroup moduleGroup

Methods

createLock
public static synchronized Object createLock(String key)

[@SYNCRHONIZED] Create a Global lock for a particular key.

Parameters:
  • key
getAcknowledgementHandler
public AcknowledgementHandler getAcknowledgementHandler()
getExternalRequestHandler
public SFRMExternalRequestHandler getExternalRequestHandler()
getIncomingMessageHandler
public IncomingMessageHandler getIncomingMessageHandler()
getIncomingRepository
public PayloadsRepository getIncomingRepository()
getInstance
public static SFRMProcessor getInstance()
getKeyStoreManager
public KeyStoreManager getKeyStoreManager()
getLock
public static synchronized Object getLock(String key)

[@SYNCRHONIZED] Get a global lock for a particular key.

getMessageHandler
public SFRMMessageHandler getMessageHandler()
getMessageSegmentHandler
public SFRMMessageSegmentHandler getMessageSegmentHandler()
getMessageSpeedQueryHandler
public MessageStatusQueryHandler getMessageSpeedQueryHandler()
getModuleGroupImpl
protected ModuleGroup getModuleGroupImpl()
getOSManager
public OSManager getOSManager()
getOutgoingRepository
public PackagedPayloadsRepository getOutgoingRepository()
getPartnershipHandler
public SFRMPartnershipHandler getPartnershipHandler()
processActivation
public void processActivation(Plugin plugin)
removeLock
public static synchronized void removeLock(String key)

[@SYNCRHONIZED] Remove a global lock for a particular key.

Parameters:
  • key
setModuleGroupImpl
protected void setModuleGroupImpl(ModuleGroup mg)

SFRMProperties

public class SFRMProperties

Provide fast access of constant field defined in the properties files. It is originally come from POC1. Creation Date: 3/10/2006 V1.0.2 - Added Mailcaps properties.

Author:Twinsen

Fields

XPATH_MAILCAPS
public static final String XPATH_MAILCAPS

The XML Path for the data content handler (DCH) for the activiation framework.

XPATH_MAX_PAYLOAD_SIZE
public static final String XPATH_MAX_PAYLOAD_SIZE

The XML Path for the maximum payload size that can be sent. The typical value is 5GB.

XPATH_SEGMENT_SIZE
public static final String XPATH_SEGMENT_SIZE

The XML Path for the sfrm segment size. The typical size is 1 mb.

XPATH_SEPARATOR
public static final String XPATH_SEPARATOR

The constant field for default XML separator.

XPATH_SFRM
public static final String XPATH_SFRM

The sfrm XML namespace name.

XPATH_SPEED_MAXIMUM
public static final String XPATH_SPEED_MAXIMUM

The XML Path for the maximum speed that user specified (Bandwidth Optimizer)

XPATH_SPEED_TICK_INTERVAL
public static final String XPATH_SPEED_TICK_INTERVAL

The XML Path for the interval for ticking the speed of the sending message

XPATH_TRUSTED_CERTS
public static final String XPATH_TRUSTED_CERTS

The XML Path for the trusted certificates location.

Methods

getAvailableMailCaps
public static String[] getAvailableMailCaps()
Returns:the available mail caps for the activiation framework available in the SFRM plugin.
getMaxPayloadSize
public static long getMaxPayloadSize()
Returns:the max payload size allowed.
getPayloadSegmentSize
public static int getPayloadSegmentSize()

Get the fixed size of each payload segment.

Returns:the size of each segment.
getSpeedTickInterval
public static long getSpeedTickInterval()
getTrustedCertStore
public static String getTrustedCertStore()

Get the location of trusted certificate store.

Returns:a absolute path storing the trusted certificate store.
toString
public String toString()

toString method.

hk.hku.cecid.edi.sfrm.task

AcknowledgementCollector

public class AcknowledgementCollector extends LimitedActiveTaskList
Author:Patrick Yip

Methods

getTaskList
public List getTaskList()

AcknowledgementTask

public class AcknowledgementTask extends ActiveTaskAdaptor

Active task responsible for handling the action of sending the acknowledgement request to receiver

Author:Patrick Yip

Constructors

AcknowledgementTask
public AcknowledgementTask(SFRMMessageDVO messageDVO, SFRMPartnershipDVO partenershipDVO)

Methods

execute
public void execute()
onFaulure
public void onFaulure(Throwable e)

Invoke when failure occur

Parameters:
  • e
unpackIncomingMessage
public void unpackIncomingMessage(SFRMMessage message, SFRMPartnershipDVO partnershipDVO)

MessageStatusCollector

public class MessageStatusCollector extends LimitedActiveTaskList
Author:Patrick Yip Collector to query the status of active message periodically. The status of message includes
  • status code
  • status description
  • number of processed segment
  • message speed (KB/s)

Methods

getTaskList
public List getTaskList()

OutgoingPayloadsCollector

public class OutgoingPayloadsCollector extends LimitedActiveTaskList

The outgoing message payloads collector collects all packaged message from the DB with the associated payload which then create DB segments for send. The looking query for packaged message.

select * from sfrm_message where message_box = ? and status = ?

Creation Date: 5/10/2006.

Author:Twinsen Tsang

Methods

getTaskList
public List getTaskList()

It get the set of payload directory from the packaged payloads repository and pass to outgoing message payload tasks for process.

Returns:A list of Outgoing message payload task.

OutgoingPayloadsTask

public class OutgoingPayloadsTask extends ActiveTaskAdaptor

What the task does

  • Update the status of message to segmentating (status: ST).
  • Analyze the payload and save the segment record to the database.
  • Update the status of message to processing (status: PR).

Creation Date: 24/10/2006.

Author:Twinsen Tsang

Constructors

OutgoingPayloadsTask
public OutgoingPayloadsTask(PackagedPayloads payload, SFRMPartnershipDVO pDVO, String status)

Explicit Constructor.

Parameters:
  • payload – The packaged payload file.
  • pDVO – TODO
  • status – The status of the for process
Throws:
  • NullPointerException – if the input payload is null.
  • DAOException – if fail to retreve the partnership.
  • IOException

Methods

execute
public void execute()

Execute the active task.

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.execute()

getMaxRetries
public int getMaxRetries()
getRetryInterval
public long getRetryInterval()
isRetryEnabled
public boolean isRetryEnabled()
onFailure
public void onFailure(Throwable e)

Invoke when failure.

setRetried
public void setRetried(int retried)

OutgoingPayloadsTaskTest

public class OutgoingPayloadsTaskTest extends PluginTest<SFRMProcessor>

Methods

getDBName
public String getDBName()
getDSDAO
public DataSourceDAO getDSDAO()
init
public void init()
postSetUp
public void postSetUp()
postTearDown
public void postTearDown()
testSendMeta
public void testSendMeta()

Test if handshaking is success

Throws:
testSendMetaFailed
public void testSendMetaFailed()

Test with handshaking, that the mock server responsed with 400 bad request

Throws:
testSendMetaFailedNotConnection
public void testSendMetaFailedNotConnection()

Test if the mock server was not started up, not connection establish

Throws:

OutgoingSegmentCollector

public class OutgoingSegmentCollector extends LimitedActiveTaskList

The outgoing segment payloads collector collect all segmented payload at the database which is ready for sending to receiver. (status: PS). Creation Date: 25/10/2006

Author:Twinsen Tsang

Methods

getTaskList
public List getTaskList()

It get the set of payload directory from the segmented payloads repository and pass to outgoing segmented payload tasks for process.

Returns:A list of Outgoing segmented payloads task.
init
protected void init()

OutgoingSegmentTask

public class OutgoingSegmentTask extends ActiveTaskAdaptor

Creation Date: 9/10/2006

Author:Twinsen Tsang

Constructors

OutgoingSegmentTask
public OutgoingSegmentTask(SFRMMessageSegmentDVO sgtDVO, SFRMPartnershipDVO pDVO, SFRMMessageDVO msgDVO, PackagedPayloads payload)

Explicit Constructor.

Parameters:
  • sgtDVO – The payload need to be send out.
  • pDVO – The partnership record associated to this segment.
  • msgDVO – The message record associated to this segment.
  • payload – The packaged payloads
Throws:
  • NullPointerException – If the message, partnership and segment is null.

Methods

execute
public void execute()

Execute the active task.

See also: hk.hku.cecid.piazza.commons.module.ActiveTask.execute()

getMaxRetries
public int getMaxRetries()
Returns:return the max retries allowed for this active task.
getRetryInterval
public long getRetryInterval()
Returns:return the interval between each sending retry.
isRetryEnabled
public boolean isRetryEnabled()
Returns:return true if this task can be retried.
onFailure
public void onFailure(Throwable e)

The method is invoked upon the task fails to send. The message segment and message will treat as FAIL. with status DF (Delivery Failure). Also, if the outgoing segment is a RECEIPT, then the PAYLOAD segment corresponding to this RECEIPT is also treated as FAIL.

Parameters:
  • e – The failure cause.
setRetried
public void setRetried(int retried)

Set the retries of active task. The parameter retried is useless here as we use the field “retried” in the database segment table for reference.

Parameters:
  • retried – The number of times that has been tried.

hk.hku.cecid.edi.sfrm.util

BandWidthOptimizer

public class BandWidthOptimizer
Author:Patrick Yip To regulate the execution interval of the collector, to improve the performance and use as least resource as possible to reach the maximum speed

Constructors

BandWidthOptimizer
public BandWidthOptimizer(ActiveTaskModule collector)

Methods

adjustSpeed
public long adjustSpeed(double currentSpeed, double expectedSpeed, long currentExecutionInterval)

Adjust the current speed to the specified speed

Parameters:
  • currentSpeed – current speed
  • expectedSpeed – expected speed
Returns:

the adjusted execution interval

findMaxSpeed
public boolean findMaxSpeed()
getCurrentEI
public long getCurrentEI()
getOptimizedEI
public long getOptimizedEI()
getOptimizedSpeed
public double getOptimizedSpeed()
isFoundOptimized
public boolean isFoundOptimized()
printIntervalRetriedMap
public void printIntervalRetriedMap()
printIntervalSpeedMap
public void printIntervalSpeedMap()
reset
public void reset()

Reset the bandwidth optimizer

setAdjustEIDelta
public void setAdjustEIDelta(long delta)
setAdjustEIMin
public void setAdjustEIMin(long min)
setAdjustSpeedTolerance
public void setAdjustSpeedTolerance(double tolerance)
setEIIncrement
public void setEIIncrement(long increment)
setEISpeedGradientTolerance
public void setEISpeedGradientTolerance(double tolerance)
setMaxExecutionInterval
public void setMaxExecutionInterval(long maxEI)
setMaxRound
public void setMaxRound(int maxRound)
setMinExecutionInterval
public void setMinExecutionInterval(long minEI)
setSpeedGradientTolerance
public void setSpeedGradientTolerance(double tolerance)

PathHelper

public class PathHelper

It provides some useful method for handling the file path issue. version 1.0.1 - Added getRelativePath(String,String).

Author:Twinsen

Methods

createPath
public static void createPath(String path)

Create the path specified in parameter. This method will create any missing directory from the path.

Throws:
  • IOException
getCanonicalPath
public static String getCanonicalPath(String basePath, String path)

Get the canonical path from the basePath and relative path.

Parameters:
  • basePath
  • path
Throws:
  • IOException
Returns:

the canonical path from the “path”.

getExtension
public static String getExtension(String path)

Get the file extension from the specified path.

Parameters:
  • path – The filepath for getting it’s extension.
Returns:

return the extension of the path. It returns empty string if the path is not directory or file without extension.

getFilename
public static String getFilename(String path)

Get the filename of the particular path. If the filename of the path does not exist, throws IOException.

Parameters:
  • path
Throws:
  • IOException – if the file does not exist or it is a directory.
getRelativePath
public static String getRelativePath(String basePath, String path)

Get the relative path from the canoical basepath and path.

Parameters:
  • basePath
  • path
Throws:
  • IOException
removeExtension
public static String removeExtension(String path)

Remove the file extension from the specified path.

Parameters:
  • path
Returns:

return the path without extension.

renameTo
public static File renameTo(File source, String newName)

Rename the file specified to the new name specified in parameters.

Parameters:
  • source – The source file object.
  • newName – The new name of the object.
Returns:

The new file object for the new path.

StatusQuery

public class StatusQuery
Author:Patrick Yip

Constructors

StatusQuery
public StatusQuery(String messageId, SFRMMessageSegmentDAO dao)

Methods

getCurrentSpeed
public double getCurrentSpeed()
getEstimatedTime
public int getEstimatedTime()
getLastUpdatedTime
public Timestamp getLastUpdatedTime()
getMessageId
public String getMessageId()
getNumOfProcessedSegments
public int getNumOfProcessedSegments()
getNumOfSegments
public int getNumOfSegments()
getSegmentSize
public long getSegmentSize()
getStatus
public String getStatus()
getStatusDesc
public String getStatusDesc()
init
public void init()
start
public void start()
stop
public void stop()
tick
public void tick()
toString
public String toString()
updateCurrentSpeed
public void updateCurrentSpeed()
updateCurrentSpeedFromMsg
public void updateCurrentSpeedFromMsg()
updateEstimatedTime
public void updateEstimatedTime()
updateProgress
public void updateProgress()

StatusQueryTest

public class StatusQueryTest extends PluginTest<SFRMProcessor>
Author:Patrick Yip

Methods

getDBName
public String getDBName()
getDSDAO
public DataSourceDAO getDSDAO()
init
public void init()
testCheckMessageStatus
public void testCheckMessageStatus()

Test for checking the message progress status

Throws:
testCheckMessageStatusNotStarted
public void testCheckMessageStatusNotStarted()

Test for if checking the message without called start method of StatusQuery

Throws:
testCheckNonExistingMessageStatus
public void testCheckNonExistingMessageStatus()

Test for checking the message which is non-existing

Throws:

StopWatch

public class StopWatch

Creation Date: 5/12/2006

Author:Twinsen Tsang

Methods

getCurrentTimestamp
public static final Timestamp getCurrentTimestamp()
getElapsedTime
public long getElapsedTime()
getElapsedTimeInSecond
public double getElapsedTimeInSecond()
getEndTime
public long getEndTime()
getStartTime
public long getStartTime()
reset
public void reset()
start
public void start()
stop
public void stop()

TimedOutEntryListener

public interface TimedOutEntryListener

The TimedOutEntryListener is the callback listener for TimedOutHashTable. It is invoked when a hash key-value pair is considered timed-out and prepare to delete the entry. Creation Date: 26/6/2007

Author:Twinsen Tsang

See also: hk.hku.cecid.piazza.commons.util.TimedOutHashTable.

Methods

timeOut
public void timeOut(Object key, Object value)
Parameters:
  • key – The key of the entry that prepare to delete in the hashtable.
  • value – The value of the entry that prepare to delete in the hashtable.

TimedOutHashTable

public class TimedOutHashTable extends Hashtable

The TimedOutDHashTable is the hashtable that provides time out features. All timed-out key and value will be cleared in the hashtable. The default interval for sweeping away all timed out record is 5 second. For the release of JDK5.0 , this class can inherit java.util.conncurrent.ConcurrentHashMap for better performance. Creation Date: 25/6/2007 17/7/2007 1. Bug Fixed that return false for invoking containsValue(Object) because of invalid implementation of TimedOutEntry.equals(Object). 2. Bug Fixed that the memory leak issue when de-referecing timed-out hashtable due to there is one reference in the internal TimedOutTask. Now you are required to call complete() when you want to gc the hashtable.

Author:Twinsen Tsang

Constructors

TimedOutHashTable
public TimedOutHashTable()

Constructor.

TimedOutHashTable
public TimedOutHashTable(long sweepInterval)

Explicit Constructor.

Parameters:
  • sweepInterval – The sweepInterval for sweeping away the timed-out hash-record.

Methods

complete
public void complete()

Invoke this method when you no longer want to use the hashtable anymore. (it will be gc soon).

contains
public boolean contains(Object value)
containsValue
public boolean containsValue(Object value)
get
public Object get(Object key)
getSweepInterval
public long getSweepInterval()
Returns:the sweeping interval for the hash table.
put
public Object put(Object key, Object value)
put
public Object put(Object key, Object value, long timeOutInMs)

Maps the specified key to the specified value in this hashtable. Neither the key nor the value can be null. The value can be retrieved by calling the get method with a key that is equal to the original key.

Parameters:
  • key – the hashtable key.
  • value – the value
  • timeOutInMS – how long does this record time out.
Returns:

the previous value of the specified key in this hashtable, or null if it did not have one.

put
public Object put(Object key, Object value, Date timeOutDate)

Maps the specified key to the specified value in this hashtable. Neither the key nor the value can be null. The value can be retrieved by calling the get method with a key that is equal to the original key.

Parameters:
  • key – the hashtable key.
  • value – the value
  • timeOutDate – how long does this record time out in date object.
Returns:

the previous value of the specified key in this hashtable, or null if it did not have one.

setListener
public void setListener(TimedOutEntryListener listener)
Parameters:
  • listener – The listener for receiving removal event of timed-out entry.

See also: hk.hku.cecid.piazza.commons.util.TimedOutEntryListener.

TimedOutHashTableTest

public class TimedOutHashTableTest extends TestCase

The test case for TimedOutHashTable. Creation Date: 25/6/2007

Author:Twinsen Tsang

Methods

setUp
public void setUp()

Setup for testing.

tearDown
public void tearDown()

Invoked for completing one testcase

testContain
public void testContain()

Test for existence of the putting object using method contain.

testContainValue
public void testContainValue()

Test for existence of the putting object using method containValue.

testGet
public void testGet()

Test for getting object from the hashtable using get

testMultiplePutWithMixed
public void testMultiplePutWithMixed()

Test for putting multiple object with some time out specified while some don’t. It then check whether some records are swept out after [sweeping_interval + timeout value].

testMultiplePutWithTimeout
public void testMultiplePutWithTimeout()

Test for putting multiple object with time out specified and see whether all records are swept out after [sweeping_interval + timeout value].

testPut
public void testPut()

Test for simple and normal scenario for putting object.

testPutWithTimeout
public void testPutWithTimeout()

Test for putting a object with time out specific and see whether it will timeout after maximum time [sweeping_interval + timeout value].

testSetListener
public void testSetListener()

Test for setting the customized listener for handling timeout entry.

TimedOutHashTableTest.SimpleTimedOutEntryListener

public static class SimpleTimedOutEntryListener implements TimedOutEntryListener

The simple timed out entry listener which print the timed out entry to system console.

Methods

timeOut
public void timeOut(Object key, Object value)

hk.hku.cecid.hermes.api

Constants

public class Constants

Fields

CONTENT_TYPE
public static final String CONTENT_TYPE
DEFAULT_PARTNERSHIP_ACK_REQUESTED
public static final String DEFAULT_PARTNERSHIP_ACK_REQUESTED
DEFAULT_PARTNERSHIP_ACK_SIGN_REQUESTED
public static final String DEFAULT_PARTNERSHIP_ACK_SIGN_REQUESTED
DEFAULT_PARTNERSHIP_DISABLED
public static final String DEFAULT_PARTNERSHIP_DISABLED
DEFAULT_PARTNERSHIP_DUPLICATE_ELIMINATION
public static final String DEFAULT_PARTNERSHIP_DUPLICATE_ELIMINATION
DEFAULT_PARTNERSHIP_ENCRYPT_REQUESTED
public static final String DEFAULT_PARTNERSHIP_ENCRYPT_REQUESTED
DEFAULT_PARTNERSHIP_HOSTNAME_VERIFY
public static final String DEFAULT_PARTNERSHIP_HOSTNAME_VERIFY
DEFAULT_PARTNERSHIP_MESSAGE_ORDER
public static final String DEFAULT_PARTNERSHIP_MESSAGE_ORDER
DEFAULT_PARTNERSHIP_RETRY_COUNT
public static final int DEFAULT_PARTNERSHIP_RETRY_COUNT
DEFAULT_PARTNERSHIP_RETRY_INTERVAL
public static final int DEFAULT_PARTNERSHIP_RETRY_INTERVAL
DEFAULT_PARTNERSHIP_SIGN_REQUESTED
public static final String DEFAULT_PARTNERSHIP_SIGN_REQUESTED
DEFAULT_PARTNERSHIP_SYNC_REPLY_MODE
public static final String DEFAULT_PARTNERSHIP_SYNC_REPLY_MODE
DEFAULT_PARTNERSHIP_TRANSPORT_PROTOCOL
public static final String DEFAULT_PARTNERSHIP_TRANSPORT_PROTOCOL
EBMS_PROTOCOL
public static final String EBMS_PROTOCOL
HEALTHY
public static final String HEALTHY
METHOD_DELETE
public static final String METHOD_DELETE
METHOD_GET
public static final String METHOD_GET
METHOD_POST
public static final String METHOD_POST

ErrorCode

public class ErrorCode

Fields

ERROR_DATA_NOT_FOUND
public static final int ERROR_DATA_NOT_FOUND
ERROR_EXTRACTING_PAYLOAD_FROM_MESSAGE
public static final int ERROR_EXTRACTING_PAYLOAD_FROM_MESSAGE
ERROR_MISSING_REQUIRED_PARAMETER
public static final int ERROR_MISSING_REQUIRED_PARAMETER
ERROR_PARSING_REQUEST
public static final int ERROR_PARSING_REQUEST
ERROR_PROTOCOL_UNSUPPORTED
public static final int ERROR_PROTOCOL_UNSUPPORTED
ERROR_READING_DATABASE
public static final int ERROR_READING_DATABASE
ERROR_READING_REQUEST
public static final int ERROR_READING_REQUEST
ERROR_RECORD_ALREADY_EXIST
public static final int ERROR_RECORD_ALREADY_EXIST
ERROR_SENDING_MESSAGE
public static final int ERROR_SENDING_MESSAGE
ERROR_UNKNOWN
public static final int ERROR_UNKNOWN
ERROR_WRITING_DATABASE
public static final int ERROR_WRITING_DATABASE
ERROR_WRITING_MESSAGE
public static final int ERROR_WRITING_MESSAGE

hk.hku.cecid.hermes.api.listener

HermesAbstractApiListener

public class HermesAbstractApiListener extends HttpRequestAdaptor

HermesAbstractApiListener

Author:Patrick Yee

Constructors

HermesAbstractApiListener
public HermesAbstractApiListener()

Methods

createActionResult
protected Map<String, Object> createActionResult(String id, boolean success)
createError
protected Map<String, Object> createError(int code, String message)
fillDate
protected void fillDate(Map<String, Object> dictionary)
getDictionaryFromRequest
protected Map<String, Object> getDictionaryFromRequest(HttpServletRequest request)
processApi
protected Map<String, Object> processApi(RestRequest request)
processDeleteRequest
protected Map<String, Object> processDeleteRequest(RestRequest request)
processGetRequest
protected Map<String, Object> processGetRequest(RestRequest request)
processPostRequest
protected Map<String, Object> processPostRequest(RestRequest request)
processRequest
public String processRequest(HttpServletRequest request, HttpServletResponse response)

processRequest

Parameters:
  • request
  • response
Throws:
Returns:

String

See also: hk.hku.cecid.piazza.commons.servlet.http.HttpRequestListener.processRequest(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)

HermesAbstractApiListenerTest

public class HermesAbstractApiListenerTest

HermesAbstractApiListenerTest

Author:Patrick Yee

Methods

testCreaetError
public void testCreaetError()
testFillDate
public void testFillDate()

HermesApiListener

public class HermesApiListener extends HermesAbstractApiListener

HermesApiListener

Author:Patrick Yee

Methods

createStatusObject
protected Map<String, Object> createStatusObject()
processGetRequest
protected Map<String, Object> processGetRequest(RestRequest request)

HermesApiListenerTest

public class HermesApiListenerTest

HermesApiListenerTest

Author:Patrick Yee

Methods

testCreateStatusObject
public void testCreateStatusObject()

HermesMessageReceiveApiListener

public class HermesMessageReceiveApiListener extends HermesProtocolApiListener

HermesMessageReceiveApiListener

Author:Patrick Yee

Fields

MAX_NUMBER
public static int MAX_NUMBER

Methods

processGetRequest
protected Map<String, Object> processGetRequest(RestRequest request)
processPostRequest
protected Map<String, Object> processPostRequest(RestRequest request)

HermesMessageSendApiListener

public class HermesMessageSendApiListener extends HermesProtocolApiListener

HermesMessageSendApiListener

Author:Patrick Yee

Methods

processGetRequest
protected Map<String, Object> processGetRequest(RestRequest request)
processPostRequest
protected Map<String, Object> processPostRequest(RestRequest request)

HermesPartnershipApiListener

public class HermesPartnershipApiListener extends HermesProtocolApiListener

HermesPartnershipApiListener

Author:Patrick Yee

Methods

processDeleteRequest
protected Map<String, Object> processDeleteRequest(RestRequest request)
processGetRequest
protected Map<String, Object> processGetRequest(RestRequest request)
processPostRequest
protected Map<String, Object> processPostRequest(RestRequest request)

HermesProtocolApiListener

public class HermesProtocolApiListener extends HermesAbstractApiListener

HermesProtocolApiListener

Author:Patrick Yee

Methods

parseFromPathInfo
protected ArrayList<String> parseFromPathInfo(String pathInfo)
parseFromPathInfo
protected ArrayList<String> parseFromPathInfo(String pathInfo, int numActionParts)

Returns a list of three strings: [ action, protocol, parameter ]

HermesProtocolApiListenerTest

public class HermesProtocolApiListenerTest

HermesProtocolApiListenerTest

Author:Patrick Yee

Fields

listener
protected HermesProtocolApiListener listener

Methods

setup
public void setup()
testGetProtocolFromPathInfo_end_with_slash
public void testGetProtocolFromPathInfo_end_with_slash()
testGetProtocolFromPathInfo_four_segments
public void testGetProtocolFromPathInfo_four_segments()
testGetProtocolFromPathInfo_four_segments_no_prefix
public void testGetProtocolFromPathInfo_four_segments_no_prefix()
testGetProtocolFromPathInfo_multiple_action_parts
public void testGetProtocolFromPathInfo_multiple_action_parts()
testGetProtocolFromPathInfo_multiple_action_parts_with_empty_segment
public void testGetProtocolFromPathInfo_multiple_action_parts_with_empty_segment()
testGetProtocolFromPathInfo_no_segment
public void testGetProtocolFromPathInfo_no_segment()
testGetProtocolFromPathInfo_one_segment
public void testGetProtocolFromPathInfo_one_segment()
testGetProtocolFromPathInfo_some_empty_segment
public void testGetProtocolFromPathInfo_some_empty_segment()
testGetProtocolFromPathInfo_three_segments
public void testGetProtocolFromPathInfo_three_segments()
testGetProtocolFromPathInfo_two_segments
public void testGetProtocolFromPathInfo_two_segments()

hk.hku.cecid.hermes.api.spa

ApiPlugin

public class ApiPlugin implements PluginHandler
Author:Patrick Yee

Fields

core
public static SystemModule core

Methods

getModuleGroup
public static ModuleGroup getModuleGroup()
Returns:the Api module group
processActivation
public void processActivation(Plugin plugin)
processDeactivation
public void processDeactivation(Plugin arg0)

hk.hku.cecid.piazza.commons

GenericException

public class GenericException extends Exception

GenericException represents all kinds of non-runtime exception in the application.

Author:Hugo Y. K. Lam

Constructors

GenericException
public GenericException()

Creates a new instance of GenericException.

GenericException
public GenericException(String message)

Creates a new instance of GenericException.

Parameters:
  • message – the error message.
GenericException
public GenericException(Throwable cause)

Creates a new instance of GenericException.

Parameters:
  • cause – the cause of this exception.
GenericException
public GenericException(String message, Throwable cause)

Creates a new instance of GenericException.

Parameters:
  • message – the error message.
  • cause – the cause of this exception.

Methods

toString
public String toString()

Returns a string representation of this exception.

Returns:a string representation of this exception.

See also: java.lang.Object.toString()

Sys

public final class Sys

Sys represents a system in an application and contains one system module, which is described by a module descriptor. The descriptor location and the system module class will be looked up from a module group descriptor which is located by the following logic:

  1. Search for the Sys properties (sys.properties) in the classpaths of the classloader used to load the Sys class.
  2. If the properties was not found, use the Java System Properties.
  3. Look for a property ‘sys.module.group’ for the system module group descriptor location.
  4. If the property is not found, the location will be default to ‘hk/hku/cecid/piazza/commons/conf/sys.module-group.xml’
Author:Hugo Y. K. Lam

See also: hk.hku.cecid.piazza.commons.module.Module, hk.hku.cecid.piazza.commons.module.ModuleGroup

Fields

main
public static final SystemModule main

The main system module.

Methods

getModuleGroup
public static ModuleGroup getModuleGroup()

Gets the system module group.

Returns:the system module group.

hk.hku.cecid.piazza.commons.activation

ByteArrayDataSource

public class ByteArrayDataSource implements DataSource

ByteArrayDataSource is an implementation of the javax.activation.DataSource that represents a data source of a byte array.

Author:Hugo Y. K. Lam

Constructors

ByteArrayDataSource
public ByteArrayDataSource(byte[] bytes)

Creates a new instance of ByteArrayDataSource.

Parameters:
  • bytes – the bytes source.
ByteArrayDataSource
public ByteArrayDataSource(byte[] bytes, String contentType)

Creates a new instance of ByteArrayDataSource.

Parameters:
  • bytes – the bytes source.
  • contentType – the content type.
ByteArrayDataSource
public ByteArrayDataSource(byte[] bytes, String contentType, String name)

Creates a new instance of ByteArrayDataSource.

Parameters:
  • bytes – the bytes source.
  • contentType – the content type.
  • name – the name of the underlying content.

Methods

getContentType
public String getContentType()

Gets the content type.

Returns:the content type.

See also: javax.activation.DataSource.getContentType()

getInputStream
public InputStream getInputStream()

Returns a new input stream representing the bytes source.

Returns:a new byte array input stream.

See also: javax.activation.DataSource.getInputStream()

getName
public String getName()

Gets the name of the underlying content.

Returns:the name of the underlying content.

See also: javax.activation.DataSource.getName()

getOutputStream
public OutputStream getOutputStream()

This method always throw IO exception.

Throws:
  • IOException – as output stream is not supported by this data source.

See also: javax.activation.DataSource.getOutputStream()

ByteStreamDataContentHandler

public class ByteStreamDataContentHandler implements DataContentHandler

ByteStreamDataContentHandler is an implementation of the javax.activation.DataContentHandler that represents a data content handler of a byte stream.

Author:Hugo Y. K. Lam

Constructors

ByteStreamDataContentHandler
public ByteStreamDataContentHandler()

Creates a new instance of ByteStreamDataContentHandler.

Methods

getContent
public Object getContent(DataSource ds)

Returns a byte stream, which is described by the first DataFlavor returned by the getTransferDataFlavors() method, representing the specified data.

Parameters:
  • ds – the data source representing the data to be converted.
Throws:
  • IOException – if unable to convert the data.
Returns:

the byte stream representing the data.

See also: javax.activation.DataContentHandler.getContent(javax.activation.DataSource)

getTransferData
public Object getTransferData(DataFlavor df, DataSource ds)

Returns a byte stream which represents the data to be transferred, ignoring the specified flavor.

Parameters:
  • df – the data flavor representing the requested type.
  • ds – the DataSource representing the data to be converted.
Throws:
  • IOException – if unable to convert the data.
Returns:

the byte stream representing the data.

See also: javax.activation.DataContentHandler.getTransferData(java.awt.datatransfer.DataFlavor,javax.activation.DataSource)

getTransferDataFlavors
public DataFlavor[] getTransferDataFlavors()

Returns an array of DataFlavor objects indicating the flavors the data can be provided in.

Returns:an array of DataFlavor objects.

See also: javax.activation.DataContentHandler.getTransferDataFlavors()

writeTo
public void writeTo(Object obj, String mimeType, OutputStream os)

Converts the object to a byte stream of the specified MIME type and write it to the output stream.

Parameters:
  • obj – the object to be converted.
  • mimeType – the requested MIME type of the resulting byte stream.
  • os – the output stream into which to write the converted byte stream.
Throws:
  • IOException – if unable to convert the given object.

See also: javax.activation.DataContentHandler.writeTo(java.lang.Object,java.lang.String,java.io.OutputStream)

InputStreamDataSource

public class InputStreamDataSource implements DataSource

InputStreamDataSource is an implementation of the javax.activation.DataSource It is designed to be used by SOAPMailSender as a bridge of InputStream and OutputStream for base64 encoding transformation.

Author:Philip Wong

See also: hk.hku.cecid.piazza.commons.soap.SOAPMailSender

Constructors

InputStreamDataSource
public InputStreamDataSource(InputStream is, String contentType, String name)

Creates a new instance of InputStreamDataSource by BodyPart.

Parameters:
  • is – the input stream.
  • contentType – the content type.
  • name – the filename if any.

Methods

getContentType
public String getContentType()

Gets the content type.

Returns:the content type when this data source created.
getInputStream
public InputStream getInputStream()

Gets the input stream.

Returns:the input stream when this data source created.
getName
public String getName()

Gets the filename.

Returns:the content type when this data source created.
getOutputStream
public OutputStream getOutputStream()

Returns new byte array from a new BytesArrayOutStream always. Logically, it is required to copy binary content from the input stream to output stream. But it is found the same result without touching binary content.

Returns:the content type when this data source created.

Mailcap

public class Mailcap

Mailcap represents a single mailcap in the MailcapCommandMap. It is a convenient class for constructing a mailcap to be added to the MailcapCommandMap and for easy comparison if necessary.

Author:Kevin Tsang

See also: javax.activation.MailcapCommandMap

Constructors

Mailcap
public Mailcap(String mimeType, String commandName, String className)

Creates a new instance of Mailcap.

Parameters:
  • mimeType – the MIME type.
  • commandName – the command name.
  • className – the handling class name.

Methods

getClassName
public String getClassName()

Gets the handling class name.

Returns:the handling class name.
getCommandName
public String getCommandName()

Gets the command name.

Returns:the command name.
getMimeType
public String getMimeType()

Gets the MIME type.

Returns:the MIME type.
toString
public String toString()

Returns a string representation of this mailcap.

Returns:a mailcap formatted string.

See also: java.lang.Object.toString()

hk.hku.cecid.piazza.commons.dao

AbstractDVO

public abstract class AbstractDVO implements DVO

The AbstractDVO, which implements the DVO interface, is simply a convenient abstract class for managing the data of a DVO. It implemented the methods of the DVO interface, provides some convenient methods and is backed by a Hashtable.

Author:Hugo Y. K. Lam

Constructors

AbstractDVO
protected AbstractDVO()

Creates a new instance of AbstractDVO.

AbstractDVO
protected AbstractDVO(Hashtable data)

Creates a new instance of AbstractDVO.

Parameters:
  • data – the source data of this DVO.

Methods

equals
public boolean equals(Object obj)

Indicates whether the given object is equal to this one. The objects are equal if and only if the given object is an AbstractDVO object and the values contained in that object match with this one’s.

Parameters:
  • obj – the object to be compared.
Returns:

true if the given object is equal to this one.

See also: java.lang.Object.equals(java.lang.Object)

get
public Object get(Object key)

Gets a value object back from this DVO by its key.

Parameters:
  • key – the key referencing the value to be retrieved.
Returns:

the value object retrieved by the specified key.

getBoolean
public boolean getBoolean(Object key)

Retrieves the value by the specified key in this AbstractDVO as an boolean.

Parameters:
  • key – the key referencing the value to be retrieved.
Returns:

the value retrieved by the specified key.

getData
public Hashtable getData()

Gets the source data of this DVO.

Returns:the source data of this DVO.
getDate
public java.util.Date getDate(Object key)

Retrieves the value by the specified key in this AbstractDVO as a java.util.Date.

Parameters:
  • key – the key referencing the value to be retrieved.
Returns:

the value retrieved by the specified key.

getDirties
public String[] getDirties()

Gets the keys which reference the dirty values.

Returns:the keys referencing the dirty values.
getDouble
public double getDouble(Object key)

Retrieves the value by the specified key in this AbstractDVO as a double.

Parameters:
  • key – the key referencing the value to be retrieved.
Returns:

the value retrieved by the specified key.

getInt
public int getInt(Object key)

Retrieves the value by the specified key in this AbstractDVO as an int.

Parameters:
  • key – the key referencing the value to be retrieved.
Returns:

the value retrieved by the specified key or Integer.MIN_VALUE if the underlying value is null.

getLong
public long getLong(Object key)

Retrieves the value by the specified key in this AbstractDVO as a long.

Parameters:
  • key – the key referencing the value to be retrieved.
Returns:

the value retrieved by the specified key or Long.MIN_VALUE if the underlying value is null.

getObject
public Object getObject(Object key, Class c)

Gets an Object from this DVO by its referencing key. If the value object is not of the Class specified, it will try to create an instance of the Class with the Object as the parameter.

Parameters:
  • key – The key referencing the String value.
  • c – the Class of the returning Object.
Returns:

the Object retrieved by its referencing key. If the value object is not of the Class specified, it will be an instance of the Class with the Object as the parameter. Null if the mentioned cannot be achieved.

getSQLDate
public java.sql.Date getSQLDate(Object key)

Retrieves the value by the specified key in this AbstractDVO as a java.sql.Date.

Parameters:
  • key – the key referencing the value to be retrieved.
Returns:

the value retrieved by the specified key.

getString
public String getString(Object key)

Gets a String value from this DVO by its key reference.

Parameters:
  • key – the key referencing the String value.
Returns:

the String value retrieved by the specified key.

getTimestamp
public java.sql.Timestamp getTimestamp(Object key)

Retrieves the value by the specified key in this AbstractDVO as a java.sql.Timestamp. It can transform java.sql.Date, java.util.Date and Oracle DATE and TIMESTAMP.

Parameters:
  • key – the key referencing the value to be retrieved.
Returns:

the value retrieved by the specified key.

put
public Object put(Object key, Object value)

Sets a single value to this DVO with a key as its reference.

Parameters:
  • key – the key referencing the value to be set.
  • value – the value object to be set to this DVO.
Returns:

the previous value of the specified key in this hashtable, or null if it did not have one.

remove
public Object remove(Object key)

Removes a value object from this DVO.

Parameters:
  • key – the key referencing the value to be removed.
Returns:

the value to which the key had been mapped in this DVO, or null if the key did not have a mapping.

setBoolean
public void setBoolean(Object key, boolean value)

Sets a Boolean value to this DVO.

Parameters:
  • key – the key referencing the Boolean value.
  • value – the Boolean value to be set.
setData
public void setData(Hashtable data)

Sets the source data of this DVO.

Parameters:
  • data – the source data of this DVO.
setDate
public void setDate(Object key, Object obj)

Sets a java.util.Date and java.sql.Date value to this DVO.

Parameters:
  • key – the key referencing the Date value.
  • obj – the Date value to be set.
setDouble
public void setDouble(Object key, double value)

Sets a Double value to this DVO.

Parameters:
  • key – the key referencing the Double value.
  • value – the Double value to be set.
setInt
public void setInt(Object key, int value)

Sets an Integer value to this DVO.

Parameters:
  • key – the key referencing the Integer value.
  • value – the Integer value to be set.
setLong
public void setLong(Object key, long value)

Sets a Long value to this DVO.

Parameters:
  • key – the key referencing the Long value.
  • value – the Long value to be set.
setString
public void setString(Object key, Object value)

Sets a String value to this DVO.

Parameters:
  • key – the key referencing the String value.
  • value – the String value to be set.
toString
public String toString()

Returns a string representation of this AbstractDVO object in the form of a set of entries.

Returns:a string representation of this AbstractDVO.

AbstractDVOTest

public class AbstractDVOTest extends TestCase

Methods

setUp
public void setUp()
tearDown
public void tearDown()
testBlob
public void testBlob()
testBoolean
public void testBoolean()
testDouble
public void testDouble()
testInt
public void testInt()
testLong
public void testLong()
testString
public void testString()
testTimestamp
public void testTimestamp()

DAO

public interface DAO

The Data Access Object is the primary object of the DAO pattern. The Data Access Object abstracts the underlying data access implementation for the Business Object to enable transparent access to the data source. The Business Object also delegates data load and store operations to the Data Access Object.

Author:Hugo Y. K. Lam

Methods

create
public void create(DVO data)

Creates the given DAO data, which is managed by this DAO, in the underlying data source.

Parameters:
  • data – the DAO data.
Throws:
createDVO
public DVO createDVO()

Creates a data value object for this DAO.

Returns:a new data value object for this DAO.
daoCreated
public void daoCreated()

Invoked after the dao has been created successfully.

getFactory
public DAOFactory getFactory()

Gets the DAO factory of this DAO.

Returns:the DAO factory.
getParameters
public Properties getParameters()

Gets the parameters of this DAO.

Returns:the parameters of this DAO.
getTransaction
public Transaction getTransaction()

Gets the transaction of this DAO.

Throws:
Returns:

the transaction of this DAO or null if there is none.

persist
public boolean persist(DVO data)

Persists the given DAO data, which is managed by this DAO, to the underlying data source.

Parameters:
  • data – the DAO data.
Throws:
Returns:

true if the data is found and persisted.

remove
public boolean remove(DVO data)

Removes the given DAO data, which is managed by this DAO, from the underlying data source.

Parameters:
  • data – the DAO data.
Throws:
Returns:

true if the data is found and removed.

retrieve
public boolean retrieve(DVO data)

Retrieves the given DAO data, which is managed by this DAO, from the underlying data source.

Parameters:
  • data – the DAO data.
Throws:
Returns:

true if the data is found and retrieved.

setTransaction
public void setTransaction(Transaction transaction)

Sets a transaction to this DAO.

Parameters:
  • transaction – the transaction of this DAO.
Throws:
  • DAOException – if the transaction is not supported by this DAO.

DAOException

public class DAOException extends hk.hku.cecid.piazza.commons.GenericException

DAOException is a class representing the exception related to or thrown in the DAO framework.

Author:Hugo Y. K. Lam

Constructors

DAOException
public DAOException()

Creates a new DAOException.

DAOException
public DAOException(String message)

Creates a new instance of DAOException.

Parameters:
  • message – the error message.
DAOException
public DAOException(Throwable cause)

Creates a new instance of DAOException.

Parameters:
  • cause – the cause of this exception.
DAOException
public DAOException(String message, Throwable cause)

Creates a new instance of DAOException.

Parameters:
  • message – the error message.
  • cause – the cause of this exception.

DAOFactory

public abstract class DAOFactory extends Component

The DAO pattern can be made highly flexible by adopting the Abstract Factory and the Factory Method Patterns.

The Factory Method pattern can be used to produce a number of DAOs needed by the application when the underlying storage is not subject to change from one implementation to another. When it is subject to change, the Abstract Factory pattern can in turn build on and use the Factory Method Implementation. In this case, it provides an abstract DAO factory object that can construct various types of concrete DAO factories, each factory supporting a different type of persistent storage implementation. Once you obtain the concrete DAO factory for a specific implementation, you use it to produce DAOs supported and implemented in that implementation.

Author:Hugo Y. K. Lam

Constructors

DAOFactory
protected DAOFactory()

Creates a new instance of DAOFactory.

Methods

createDAO
public DAO createDAO(Class inf)

Creates a new DAO.

Parameters:
  • inf – the DAO interface class.
Throws:
  • DAOException – if there is any problem in looking up the DAO with the interface specified.
Returns:

the DAO retrieved by the interface specified.

createDAO
public DAO createDAO(String daoname)

Creates a new DAO.

Parameters:
  • daoname – the DAO name.
Throws:
  • DAOException – if there is any problem in looking up the DAO with the name specified.
Returns:

the DAO retrieved by the name specified.

See also: .initDAO(DAO)

createDAOFactory
public static DAOFactory createDAOFactory(String name, String provider, Properties params, ClassLoader loader)

Creates a DAO Factory.

Parameters:
  • name – the DAO Factory name.
  • provider – the provider of the DAO Factory.
  • params – the parameters for creating the DAO Factory.
  • loader – the class loader for loading the factory class.
Throws:
  • DAOException – if there is any error when creating the DAO Factory using the specified parameters.
Returns:

the DAO Factory created by the parameters specified.

createTransaction
public Transaction createTransaction()

Creates a new transaction.

Throws:
Returns:

a new transaction.

getParameter
protected String getParameter(String key)

Gets a parameter from the parameters of this DAOFactory.

Parameters:
  • key – the parameter key.
Throws:
  • DAOException – if there is no parameter matching the specified key.
Returns:

the parameter value associated with the specified key.

getParameter
protected String getParameter(String key, String def)

Gets a parameter from the parameters of this DAOFactory.

Parameters:
  • key – the parameter key.
  • def – the default value.
Returns:

the parameter value associated with the specified key. The default value will be returned if there is no parameter matching the specified key.

init
protected void init()

Initializes the DAO Factory.

Throws:
  • DAOException – when there is any error in the initialization.

See also: .initFactory()

initDAO
protected abstract void initDAO(DAO dao)

Invoked by the createDAO() method for initializing the given DAO.

Parameters:
  • dao – the DAO.
Throws:

See also: .createDAO(Class), .createDAO(String)

initFactory
protected abstract void initFactory()

Invoked by the init() method for initializing the implementing factory.

Throws:

See also: .init()

DVO

public interface DVO extends java.io.Serializable

A DVO represents a value object in the DAO model. The Data Access Object may use a value object to return data to the client. The Data Access Object may also receive a value object for updating and querying.

Author:Hugo Y. K. Lam

Transaction

public interface Transaction

The Transaction interface allows operations to be performed against the transaction in the target Transaction object. A Transaction object is created by a corresponding DAO factory. Before any transaction starts, the Transaction object should be notified by the invocation of its begin() method. When the transaction is finished, either commit() or rollback should be invoked and the resources it acquired should be released accordingly.

Author:Hugo Y. K. Lam

Methods

begin
public void begin()

Begins the transaction.

Throws:
commit
public void commit()

Commits the transaction.

Throws:
rollback
public void rollback()

Rolls back the transaction.

Throws:

hk.hku.cecid.piazza.commons.dao.ds

DataSourceDAO

public abstract class DataSourceDAO implements DAO

The abstract DataSourceDAO class encapsulates a DataSourceDAOFactory object. It basically provides methods, such as getTransaction() and createTransaction(), for any subclasses to get or create a transaction for accessing the underlying data source. It also provides some convenient methods for the subclasses to access, like querying and updating, the data source.

When using the convenient methods, some basic parameters need to be defined. The parameters should be stored in the Properties object which can be retrieved by calling getProperties().

The key-value pairs of the parameters must be in the following format:

Key Value Used by
finder:key The key finder SQL statement findByKey()
finder: {alias name} The finder SQL statement find()
column: {name in the data source} The column’s key in the DVO getColumnCodeName(), executeQuery()
sql: {alias name} The SQL statement getSQL(), update()
Author:Hugo Y. K. Lam

Constructors

DataSourceDAO
protected DataSourceDAO()

Creates a new instance of DataSourceDAO.

Methods

create
public void create(DVO data)

Creates the given value object in the data source.

Parameters:
  • data – the value object.
Throws:

See also: hk.hku.cecid.piazza.commons.dao.DAO.create(hk.hku.cecid.piazza.commons.dao.DVO)

createTransaction
protected DataSourceTransaction createTransaction()

Creates a new DataSourceTransaction object from the underlying data source factory.

Throws:
Returns:

a new DataSourceTransaction object.

daoCreated
public void daoCreated()

Initializes this DAO.

See also: hk.hku.cecid.piazza.commons.dao.DAO.daoCreated()

executeQuery
protected List executeQuery(String sql)

Executes a SQL query on the data source and returns a List of DVO which matches.

Parameters:
  • sql – the SQL query statement.
Throws:
  • DAOException – if errors found when retrieving data from the data source.
Returns:

a List of DVO resulted from the specified SQL query. An empty List will be returned if there is no matching data.

executeQuery
protected List executeQuery(DataSourceTransaction tx, String sql)

Executes a SQL query on the data source and returns a List of DVO which matches.

Parameters:
  • tx – the DataSourceTransaction to be used in execution.
  • sql – the SQL query statement.
Throws:
  • DAOException – if errors found when retrieving data from the data source.
Returns:

a List of DVO resulted from the specified SQL query. An empty List will be returned if there is no matching data.

executeQuery
protected List executeQuery(String sql, Object[] paras)

Executes a SQL query on the data source and returns a List of DVO which matches.

Parameters:
  • sql – the SQL query statement.
  • paras – the parameter values used by the specified SQL statement. The number, format, and sequence of the parameter values should match the statement. null if there is no parameter for the statement.
Throws:
  • DAOException – if errors found when retrieving data from the data source.
Returns:

a List of DVO resulted from the specified SQL query. An empty List will be returned if there is no matching data.

executeQuery
protected List executeQuery(DataSourceTransaction tx, String sql, Object[] paras)

Executes a SQL query on the data source and returns a List of DVO which matches.

Parameters:
  • tx – the DataSourceTransaction to be used in execution.
  • sql – the SQL query statement.
  • paras – the parameter values used by the specified SQL statement. The number, format, and sequence of the parameter values should match the statement. null if there is no parameter for the statement.
Throws:
  • DAOException – if errors found when retrieving data from the data source.
Returns:

a List of DVO resulted from the specified SQL query. An empty List will be returned if there is no matching data.

executeRawQuery
protected List executeRawQuery(String sql, Object[] paras)

Executes a SQL query on the data source and returns a List of raw data which matches.

Parameters:
  • sql – the SQL query statement.
  • paras – the parameter values used by the specified SQL statement. The number, format, and sequence of the parameter values should match the statement. null if there is no parameter for the statement.
Throws:
  • DAOException – if errors found when retrieving data from the data source.
Returns:

a List of DVO resulted from the specified SQL query. An empty List will be returned if there is no matching data.

executeRawQuery
protected List executeRawQuery(DataSourceTransaction tx, String sql, Object[] paras)

Executes a SQL query on the data source and returns a List of raw data which matches.

Parameters:
  • tx – the DataSourceTransaction to be used in execution.
  • sql – the SQL query statement.
  • paras – the parameter values used by the specified SQL statement. The number, format, and sequence of the parameter values should match the statement. null if there is no parameter for the statement.
Throws:
  • DAOException – if errors found when retrieving data from the data source.
Returns:

a List of DVO resulted from the specified SQL query. An empty List will be returned if there is no matching data.

executeUpdate
protected int executeUpdate(String sql)

Executes a SQL update on the data source and returns an integer indicating the update result.

Parameters:
  • sql – the SQL update statement.
Throws:
  • DAOException – if errors found when updating data to the data source.
Returns:

an integer indicating the update results. Same as the value returned by java.sql.Statement.executeUpdate().

executeUpdate
protected int executeUpdate(DataSourceTransaction tx, String sql)

Executes a SQL update on the data source and returns an integer indicating the update result.

Parameters:
  • tx – the DataSourceTransaction to be used in execution.
  • sql – the SQL update statement.
Throws:
  • DAOException – if errors found when updating data to the data source.
Returns:

an integer indicating the update results. Same as the value returned by java.sql.Statement.executeUpdate().

executeUpdate
protected int executeUpdate(String sql, Object[] paras)

Executes a SQL update on the data source and returns an integer indicating the update result.

Parameters:
  • sql – the SQL update statement.
  • paras – the parameter values used by the specified SQL statement. The number, format, and sequence of the parameter values should match the statement. null if there is no parameter for the statement.
Throws:
  • DAOException – if errors found when updating data to the data source.
Returns:

an integer indicating the update results. Same as the value returned by java.sql.Statement.executeUpdate().

executeUpdate
protected int executeUpdate(DataSourceTransaction tx, String sql, Object[] paras)

Executes a SQL update on the data source and returns an integer indicating the update result.

Parameters:
  • tx – the DataSourceTransaction to be used in execution.
  • sql – the SQL update statement.
  • paras – the parameter values used by the specified SQL statement. The number, format, and sequence of the parameter values should match the statement. null if there is no parameter for the statement.
Throws:
  • DAOException – if errors found when updating data to the data source.
Returns:

an integer indicating the update results. Same as the value returned by java.sql.Statement.executeUpdate()

executeUpdate
protected int[] executeUpdate(String sql, Object[][] paras)

Executes a SQL update on the data source and returns an array of integers indicating the update results.

Parameters:
  • sql – the SQL update statement.
  • paras – the parameter values used by the specified SQL statement. The number, format, and sequence of the parameter values should match the statement. null if there is no parameter for the statement and multiple sets if it is a batch update.
Throws:
  • DAOException – if errors found when updating data to the data source.
Returns:

an array of integers indicating the update results. Same as the value returned by java.sql.Statement.executeUpdate().

executeUpdate
protected int[] executeUpdate(DataSourceTransaction tx, String sql, Object[][] paras)

Executes a SQL update on the data source and returns an array of integers indicating the update results.

Parameters:
  • tx – the DataSourceTransaction to be used in execution.
  • sql – the SQL update statement.
  • paras – the parameter values used by the specified SQL statement. The number, format, and sequence of the parameter values should match the statement. null if there is no parameter for the statement and multiple sets if it is a batch update.
Throws:
  • DAOException – if errors found when updating data to the data source.
Returns:

an array of integers indicating the update results. Same as the value returned by java.sql.Statement.executeUpdate().

find
protected List find(String finder, Object[] paras)

Retrieves data from the data source as a List of DVO by searching with the specified data values.

Parameters:
  • finder – the name of the finder SQL statement.
  • paras – the parameter values used by the finder statement.
Throws:
  • DAOException – if errors found when retrieving data from the data source.
Returns:

a List of DVO found by the specified data values. An empty List will be returned if there is no matching data.

findByKey
protected DVO findByKey(Object[] keys)

Retrieves data from the data source by searching with the specified key values.

Parameters:
  • keys – the key values for querying the data source.
Throws:
  • DAOException – if errors found when retrieving data from the data source.
Returns:

a DVO found by the specified key values. If there are more than one DVO found, the first one will be returned. null will be returned if nothing was found.

getColumnCodeName
protected String getColumnCodeName(String name)

Gets the code name of the specified column in the data source.

Parameters:
  • name – the name of the column.
Returns:

the code name of the specified column.

getFactory
public DAOFactory getFactory()

Gets the DAO factory of this DAO.

Returns:the DAO factory.
getFilter
protected String getFilter(String name)

Gets the filter partial SQL statement with the specified name.

Parameters:
  • name – the name which refers to the filter partial SQL statement.
Returns:

the filter partial SQL statement associated with the specified name.

getFinder
protected String getFinder(String name)

Gets the finder SQL statement with the specified name.

Parameters:
  • name – the name which refers to the finder SQL statement.
Returns:

the finder SQL statement associated with the specified name.

getOrder
protected String getOrder(String name)

Gets the order partial SQL statement with the specified name.

Parameters:
  • name – the name which refers to the order partial SQL statement.
Returns:

the order partial SQL statement associated with the specified name.

getParameters
public Properties getParameters()

Gets the parameters of this DAO.

Returns:a Properties which stored the parameters for this DAO.
getSQL
protected String getSQL(String name)

Gets the SQL statement with the specified name.

Parameters:
  • name – the name which refers to the SQL statement.
Returns:

the SQL statement associated with the specified name.

getTransaction
public Transaction getTransaction()

Gets the transaction of this DAO. This method returns null if this DAO is not under a transaction.

Throws:
Returns:

the transaction of this DAO.

See also: hk.hku.cecid.piazza.commons.dao.DAO.getTransaction()

getTransaction
protected DataSourceTransaction getTransaction(boolean create)

Gets the transaction of this DAO. This method returns a new transaction if and only if this DAO is not under a transaction and the create parameter is set to true. Notice that a newly created transaction will not be set as the transaction of this DAO. It is only created for convenience of use.

Parameters:
  • create – true if a new transaction should be created if this DAO is not under a transaction.
Throws:
Returns:

the transaction of this DAO or a new transaction.

isUnderTransaction
public boolean isUnderTransaction()

Checks if this DAO is under a transaction.

Returns:true if this DAO is under a transaction.
persist
public boolean persist(DVO data)

Persists the given value object to the data source.

Parameters:
  • data – the value object.
Throws:
Returns:

true if the data is found and persisted.

See also: hk.hku.cecid.piazza.commons.dao.DAO.persist(hk.hku.cecid.piazza.commons.dao.DVO)

remove
public boolean remove(DVO data)

Removes the given value object from the data source.

Parameters:
  • data – the value object.
Throws:
Returns:

true if the data is found and removed.

See also: hk.hku.cecid.piazza.commons.dao.DAO.remove(hk.hku.cecid.piazza.commons.dao.DVO)

retrieve
public boolean retrieve(DVO data)

Retrieves the given value object from the data source.

Parameters:
  • data – the value object.
Throws:
Returns:

true if the data is found and retrieved.

See also: hk.hku.cecid.piazza.commons.dao.DAO.retrieve(hk.hku.cecid.piazza.commons.dao.DVO)

setFactory
void setFactory(DataSourceDAOFactory factory)

Sets the DAO factory of this DAO.

Parameters:
  • factory – the DAO factory.
setTransaction
public void setTransaction(Transaction tx)

Sets the transaction of this DAO.

Parameters:
  • tx – the transaction of this DAO.
Throws:
  • DAOException – if the given transaction is not supported.
update
protected int update(String sqlname, Object[] paras)

Updates the data source with the specified data values.

Parameters:
  • sqlname – the name of the SQL statement to be used.
  • paras – the data values to be updated to the data source.
Throws:
  • DAOException – if errors found when updating data to the data source.
Returns:

an integer indicating the update result. Same as the value returned by java.sql.Statement.executeUpdate()

DataSourceDAOFactory

public class DataSourceDAOFactory extends DAOFactory

The DataSourceDAOFactory has implemented the DAOFactory and provides an implementation for accessing the data source by Java DataSource. Notice that the DAO created by the createDAO() method is a DataSourceDAO object since this factory is a DataSourceDAOFactory.

Author:Hugo Y. K. Lam

Constructors

DataSourceDAOFactory
public DataSourceDAOFactory()

Creates a new instance of DataSourceDAOFactory.

Methods

createTransaction
public Transaction createTransaction()

Creates a data source transaction.

Throws:
  • TransactionException – if unable to create the data source transaction.
Returns:

a new data source transaction.

See also: hk.hku.cecid.piazza.commons.dao.DAOFactory.createTransaction()

getDataSource
protected DataSource getDataSource()

Gets the underlying DataSource object.

Returns:the underlying DataSource object.
initDAO
protected void initDAO(DAO dao)

Initializes the given DAO.

Parameters:
  • dao – the DAO.
Throws:
initFactory
public void initFactory()

Initializes this DAOFactory.

setDataSource
protected void setDataSource(DataSource source)

Sets the underlying DataSource object.

Parameters:
  • source – the underlying DataSource object.

DataSourceDVO

public abstract class DataSourceDVO extends AbstractDVO

The DataSourceDVO, which implements the DVO interface, is simply a subclass of the AbstractDVO. It is expected to be used by a DataSourceDAOFactory.

Author:Hugo Y. K. Lam

Constructors

DataSourceDVO
protected DataSourceDVO()

Creates a new instance of DataSourceDVO.

DataSourceDVO
protected DataSourceDVO(Hashtable data)

Creates a new instance of DataSourceDVO.

Parameters:
  • data – the source data of this DVO.

DataSourceProcess

public abstract class DataSourceProcess

DataSourceProcess represents a data source transaction process. Subclasses are required to implement the doTransaction() method for the transaction process.

This process will only manage, for example commit or rollback, the transaction encapsulated if its DataSourceDAO is not under a transaction and it is not explicitly instructed, in construction, to use a specified transaction.

Author:Hugo Y. K. Lam

Constructors

DataSourceProcess
public DataSourceProcess(DataSourceDAO dao)

Creates a new instance of DataSourceProcess.

Parameters:
  • dao – the DAO to which this process correspond.
DataSourceProcess
public DataSourceProcess(DataSourceDAO dao, DataSourceTransaction transaction)

Creates a new instance of DataSourceProcess.

Parameters:
  • dao – the DAO to which this process correspond.
  • transaction – the transaction in which this process should execute.

Methods

doTransaction
protected abstract void doTransaction(DataSourceTransaction tx)

Executes the transaction process.

Parameters:
  • tx – the DataSourceTransaction object in which this process executes.
Throws:
getDAO
protected DataSourceDAO getDAO()

Gets the DAO to which this process correspond.

Returns:the DAO to which this process correspond.
getParameterCount
protected int getParameterCount(PreparedStatement pStmt, String sql)

Counts the number of parameters required by the prepared statement. If a parameter meta data is not available, it counts the occurrences of ‘?’ in the given SQL statement.

Parameters:
  • pStmt – the prepared statement.
  • sql – the SQL statement.
Returns:

the numbder of parameters.

getResult
public Object getResult()

Gets the result of this process.

Returns:the result of this process.
isCommitted
public boolean isCommitted()

Checks if this process has committed the transaction.

Returns:true if this process has committed the transaction.
isRolledBack
public boolean isRolledBack()

Checks if this process has rolled back the transaction.

Returns:true if this process has rolled back the transaction.
isStarted
public boolean isStarted()

Checks if this process has already been started.

Returns:true if the this process has already been started.
setParameter
protected void setParameter(PreparedStatement pStmt, int pos, Object param)

Sets a parameter to the prepared statement.

Parameters:
  • pStmt – the prepared statement.
  • pos – the position of the parameter.
  • param – the parameter.
Throws:
  • SQLException – if unable to set the parameter.
setResult
protected void setResult(Object result)

Sets the result of this process.

Parameters:
  • result – the result of this process.
start
public synchronized void start()

Starts executing this process. A process can only be started if it has not yet been started.

Throws:
  • DAOException – if there is any error in the execution or the process has already been started.
toString
public String toString()

Returns a string representation of this process.

Returns:a string representation of this process.

See also: java.lang.Object.toString()

DataSourceQuery

class DataSourceQuery extends DataSourceProcess

DataSourceQuery is a data source DAO process which handles a SQL query process.

Author:Hugo Y. K. Lam

Constructors

DataSourceQuery
DataSourceQuery(DataSourceDAO dao, DataSourceTransaction transaction, String sql, Object[] params)

Creates a new instance of DataSourceQuery.

Parameters:
  • dao – the DAO to which this process correspond.
  • transaction – the transaction for this process.
  • sql – the SQL query statement.
  • params – the parameter values used by the specified SQL statement. The number, format, and sequence of the parameter values should match the statement. null if there is no parameter for the statement.

Methods

doTransaction
protected void doTransaction(DataSourceTransaction tx)

Executes the query and stores the result as a list of DataSourceDVO or raw data list.

Throws:

See also: hk.hku.cecid.piazza.commons.dao.ds.DataSourceProcess.doTransaction(DataSourceTransaction)

isRawResult
public boolean isRawResult()

Checks if the result data is in raw format.

Returns:true if the result data is in raw format.

See also: .setRawResult(boolean)

setRawResult
public void setRawResult(boolean isRawResult)

Sets whether the result data should be in raw format. If true, the result data will be a list of DataSourceDVO. Otherwise, it will be a list of list which contains the data values in order with the query.

Parameters:
  • isRawResult – true if the result data should be in raw format.

DataSourceTransaction

public class DataSourceTransaction implements Transaction

DataSourceTransaction is an implementation of a DAO transaction. It should not be created directly and is usually created through DataSourceDAOFactory.

Author:Hugo Y. K. Lam

See also: DataSourceDAOFactory

Constructors

DataSourceTransaction
protected DataSourceTransaction(DataSourceDAOFactory dsFactory)

Creates a new instance of DataSourceTransaction.

Parameters:
  • dsFactory – the data source factory which creates this transaction.
Throws:
  • DAOException – if the no data source factory specified.

Methods

begin
public void begin()

Begins the transaction.

Throws:
  • DAOException – if unable to begin the transaction or the transaction has already begun.

See also: hk.hku.cecid.piazza.commons.dao.Transaction.begin()

commit
public void commit()

Commits the transaction.

Throws:

See also: hk.hku.cecid.piazza.commons.dao.Transaction.commit()

getConnection
public Connection getConnection()

Gets the connection that this transaction manages.

Throws:
  • DAOException – if the transaction has not begun or has been ended.
Returns:

the connection this transaction manages.

releaseConnection
public void releaseConnection()

Releases the connection that this transaction manages.

rollback
public void rollback()

Rolls back the transaction.

Throws:

See also: hk.hku.cecid.piazza.commons.dao.Transaction.rollback()

DataSourceUpdate

class DataSourceUpdate extends DataSourceProcess

DataSourceUpdate is a data source DAO process which handles a SQL update process.

Author:Hugo Y. K. Lam

Constructors

DataSourceUpdate
DataSourceUpdate(DataSourceDAO dao, DataSourceTransaction transaction, String sql, Object[][] params)

Creates a new instance of DataSourceUpdate.

Parameters:
  • dao – the DAO to which this process correspond.
  • transaction – the transaction for this process.
  • sql – the SQL update statement.
  • params – the parameter values used by the specified SQL statement. The number, format, and sequence of the parameter values should match the statement. null if there is no parameter for the statement and multiple sets if it is a batch update.

Methods

doTransaction
protected void doTransaction(DataSourceTransaction tx)

Executes the update and stores the result as an array of integers which indicates the update results.

Throws:

See also: hk.hku.cecid.piazza.commons.dao.ds.DataSourceProcess.doTransaction(DataSourceTransaction)

NullableObject

public class NullableObject

NullableObject is a wrapper class for any object which has a corresponding SQL type. It indicates if the object wrapped is null and provide the type, java.sql.Types, information of the object.

Constructors

NullableObject
public NullableObject(Object o, int type)

Creates a new instance of NullableObject.

Parameters:
  • o – The object to be wrapped by this NullableObject.
  • type – The type of the object to be wrapped.

Methods

getObject
public Object getObject()

Retrieves the object wrapped by this NullableObject.

Returns:the object wrapped.
getType
public int getType()

Retrieves the type information of the object wrapped.

Returns:the type information of the object wrapped. -1 if not specified in the creation of this instance.
isNull
public boolean isNull()

Reports whether the wrapped object is null.

Returns:true if the object wrapped is null and false if it is not.
toString
public String toString()

Returns a string representation of the object wrapped.

Returns:a string representation of the object wrapped. ‘null’ if the object wrapped is null.

SQLBuilder

public class SQLBuilder

SQLBuilder is a tool which can construct prepared SQL statements from the specified table, keys, and columns.

Author:Hugo Y. K. Lam

Constructors

SQLBuilder
public SQLBuilder(String table, String key, String[] columns)

Creates a new instance of SQLBuilder.

Parameters:
  • table – the table name.
  • key – the comma delimited set of keys of the table.
  • columns – the columns of the table.
SQLBuilder
public SQLBuilder(String table, String[] keys, String[] columns)

Creates a new instance of SQLBuilder.

Parameters:
  • table – the table name.
  • keys – the keys of the table.
  • columns – the columns of the table.

Methods

getColumns
public String[] getColumns()

Gets the columns.

Returns:the columns.
getDeleteStatement
public String getDeleteStatement()

Gets the DELETE statement.

Returns:the DELETE statement.
getInsertStatement
public String getInsertStatement()

Gets the INSERT statement.

Returns:the INSERT statement.
getInsertStatement
public String getInsertStatement(String[] cols)

Gets the INSERT statement.

Parameters:
  • cols – the columns to be updated.
Returns:

the INSERT statement.

getKeys
public String[] getKeys()

Gets the keys.

Returns:the keys.
getSelectStatement
public String getSelectStatement()

Gets the SELECT statement.

Returns:the SELECT statement.
getTable
public String getTable()

Gets the table name.

Returns:the table name.
getUpdateStatement
public String getUpdateStatement()

Gets the UPDATE statement.

Returns:the UPDATE statement.
getUpdateStatement
public String getUpdateStatement(String[] cols)

Gets the UPDATE statement.

Parameters:
  • cols – the columns to be updated.
Returns:

the UPDATE statement.

isValid
public boolean isValid()

Checks if this SQL builder is valid. It is valid if and only if the table, columns, and keys have been defined.

Returns:true if this SQL builder is valid.

SimpleDSDAO

public class SimpleDSDAO extends DataSourceDAO

SimpleDSDAO is a concrete subclass of DataSourceDAO which provides some convenient methods for querying and updating its underlying data source. It should not be used directly when the underlying persistent storage would be changed to any kind that does not support Java DataSource.

Author:Hugo Y. K. Lam

Constructors

SimpleDSDAO
public SimpleDSDAO()

Creates a new instance of SimpleDSDAO.

Methods

createDVO
public DVO createDVO()

Creates a new instance of SimpleDSDVO.

find
public SimpleDSDVO find(Object[] keys)

Retrieves data from the data source by searching with the specified key values.

Parameters:
  • keys – the key values for querying the data source. The number, format, and sequence of the parameter values should match the key finder statement.
Throws:
  • DAOException – if errors found when retrieving data from the data source.
Returns:

a SimpleDSDVO found by the specified key values. If there are more than one DVO found, the first one will be returned. null will be returned if nothing was found.

find
public List find(String finder, Object[] paras)

Retrieves data from the data source as a List of DVO by searching with the specified data values.

Parameters:
  • finder – the name of the finder SQL statement.
  • paras – the parameter values used by the specified finder statement. The number, format, and sequence of the parameter values should match the statement. null if there is no parameter for the statement.
Throws:
  • DAOException – if errors found when retrieving data from the data source.
Returns:

a List of SimpleDSDVO found by the specified data values. An empty List will be returned if there is no matching data.

update
public int update(String sqlname, Object[] paras)

Update the data source with the specified data values.

Parameters:
  • sqlname – the name of the SQL statement to be used.
  • paras – the data values to be updated to the data source.
Throws:
  • DAOException – if errors found when updating data to the data source.
Returns:

an integer indicating the update result. Same as the value returned by java.sql.Statement.executeUpdate().

SimpleDSDAOFactory

public class SimpleDSDAOFactory extends DataSourceDAOFactory

SimpleDSDAOFactory is a subclass of DataSourceDAOFactory and provides an implementation for accessing the data source by a simple DataSource object which is backed by the DriverManager and provides no pooling.

Notice that the DAO created by the createDAO() method shall be an instance of DataSourceDAO since this factory is a DataSourceDAOFactory.

Author:Hugo Y. K. Lam

Constructors

SimpleDSDAOFactory
public SimpleDSDAOFactory()

Creates a new instance of SimpleDSDAOFactory.

Methods

initFactory
public void initFactory()

Initializes this DAOFactory.

SimpleDSDVO

public class SimpleDSDVO extends DataSourceDVO

SimpleDSDVO is just a concrete subclass of DataSourceDVO. It should not be used directly when the underlying persistent storage would be changed to any kind that does not support Java DataSource.

Author:Hugo Y. K. Lam

Constructors

SimpleDSDVO
public SimpleDSDVO()

Creates a new instance of SimpleDSDVO.

SimpleDSDVO
public SimpleDSDVO(Hashtable data)

Creates a new instance of SimpleDSDVO.

Parameters:
  • data – the source data of this DVO.

hk.hku.cecid.piazza.commons.ejb

AbstractEntityBean

public class AbstractEntityBean implements EntityBean

The AbstractEntityBean class is an abstract class which implements the methods required for an Entity Bean, except the ejbCreateXXX() methods which have been defined in the home interface.

Author:Hugo Y. K. Lam

Fields

context
protected EntityContext context

The entity context.

Constructors

AbstractEntityBean
public AbstractEntityBean()

Creates a new instance of AbstractEntityBean.

Methods

ejbActivate
public void ejbActivate()

A container invokes this method when the instance is taken out of the pool of available instances to become associated with a specific EJB object.

See also: javax.ejb.EntityBean.ejbActivate()

ejbLoad
public void ejbLoad()

A container invokes this method to instruct the instance to synchronize its state by loading it state from the underlying database.

See also: javax.ejb.EntityBean.ejbLoad()

ejbPassivate
public void ejbPassivate()

A container invokes this method on an instance before the instance becomes disassociated with a specific EJB object.

See also: javax.ejb.EntityBean.ejbPassivate()

ejbRemove
public void ejbRemove()

A container invokes this method before it removes the EJB object that is currently associated with the instance.

See also: javax.ejb.EntityBean.ejbRemove()

ejbStore
public void ejbStore()

See also: javax.ejb.EntityBean.ejbStore()

setEntityContext
public void setEntityContext(EntityContext ctx)

Sets the associated entity context.

See also: javax.ejb.EntityBean.setEntityContext(javax.ejb.EntityContext)

unsetEntityContext
public void unsetEntityContext()

Unset the associated entity context.

See also: javax.ejb.EntityBean.unsetEntityContext()

AbstractMessageDrivenBean

public abstract class AbstractMessageDrivenBean implements javax.ejb.MessageDrivenBean, javax.jms.MessageListener

The AbstractMessageDrivenBean class is an abstract class which implements the methods required for a Message Driven Bean, excepts the onMessage() method.

Author:Hugo Y. K. Lam

Fields

mdc
protected MessageDrivenContext mdc

Methods

ejbCreate
public void ejbCreate()

A container invokes this method before it begins the life of the message-driven object.

ejbRemove
public void ejbRemove()

A container invokes this method before it ends the life of the message-driven object.

setMessageDrivenContext
public void setMessageDrivenContext(MessageDrivenContext mdc)

Sets the associated message-driven context. The container calls this method after the instance creation.

Parameters:
  • mdc – A MessageDrivenContext interface for the instance.

AbstractSessionBean

public class AbstractSessionBean implements SessionBean

The AbstractSessionBean class is an abstract class which implements the methods required for a Session Bean, except the ejbCreate(...) methods and the business methods.

Author:Hugo Y. K. Lam

Fields

context
protected SessionContext context

The session context.

Constructors

AbstractSessionBean
public AbstractSessionBean()

Creates a new instance of AbstractSessionBean.

Methods

ejbActivate
public void ejbActivate()

A container invokes this method when the instance is activated from its “passive” state.

See also: javax.ejb.SessionBean.ejbActivate()

ejbCreate
public void ejbCreate()

A container invokes this method when the instance is created. This is a default and mandatory creator in a stateless session bean.

See also: javax.ejb.SessionBean.ejbActivate()

ejbPassivate
public void ejbPassivate()

A container invokes this method before the instance enters the “passive” state.

See also: javax.ejb.SessionBean.ejbPassivate()

ejbRemove
public void ejbRemove()

A container invokes this method before it ends the life of the session object.

See also: javax.ejb.SessionBean.ejbRemove()

setSessionContext
public void setSessionContext(SessionContext ctx)

Set the associated session context.

See also: javax.ejb.SessionBean.setSessionContext(javax.ejb.SessionContext)

EjbConnection

public class EjbConnection

An EjbConnection represents a connection to the initial context by which the specified EJBHome can be looked up. The URL connection string for an EJBConnection should comply the following format: PROVIDER_URL@INITIAL_CONTEXT_FACTORY {@SECURITY_PROTOCOL}

Author:Hugo Y. K. Lam

Constructors

EjbConnection
public EjbConnection(String url, String username, String password)

Creates a new instance of EjbConnection.

Methods

close
public synchronized void close()

Closes this connection and releases any resources associated.

Throws:
  • EjbConnectionException – if errors occurred during closing the connection or, the connection has not yet been connected or has been closed already.
connect
public synchronized void connect()

Connects to the destination URL using the username and password stored in this connection.

Throws:
connect
public synchronized void connect(String username, String password)

Connects to the destination URL using the specified username and password.

Parameters:
  • username – the username used to connect. null if authentication is not required.
  • password – the password used to connect. null if authentication is not required.
Throws:
  • EjbConnectionException – if errors occurred during the establishment of connection or, the connection has been connected or closed already.
finalize
protected void finalize()

Closes this connection in finalization.

See also: java.lang.Object.finalize()

getUrl
public String getUrl()

Gets the URL of this connection.

Returns:the URL of this connection.
getUsername
public String getUsername()

Gets the username used for this connection.

Returns:the username used in this connection.
lookupHome
public Object lookupHome(String jndiName, Class narrowTo)

Retrieves the EJBHome by looking it up using the specified JNDI name. The EJBHome will be narrowed to the specified class if it is a remote interface.

Parameters:
  • jndiName – the JNDI name for the EJBHome to be looked up.
  • narrowTo – the class to which the EJBHome should be narrowed.
Throws:
Returns:

the EJBHome bound to the specified JNDI name.

toString
public String toString()

Returns a string representation of this object, which is the URL.

See also: java.lang.Object.toString()

EjbConnectionException

public class EjbConnectionException extends Exception

EjbConnectionException represents all kinds of exception occurred in an EJB connection.

Author:Hugo Y. K. Lam

Constructors

EjbConnectionException
public EjbConnectionException()

Default constructor of EjbConnectionException.

EjbConnectionException
public EjbConnectionException(String message)

Constructor of EjbConnectionException.

Parameters:
  • message – the error message
EjbConnectionException
public EjbConnectionException(Throwable cause)

Constructor of EjbConnectionException.

Parameters:
  • cause – the cause of this exception
EjbConnectionException
public EjbConnectionException(String message, Throwable cause)

Constructor of EjbConnectionException.

Parameters:
  • message – the error message
  • cause – the cause of this exception

EjbConnectionFactory

public final class EjbConnectionFactory

EjbConnectionFactory is a concrete factory class for creating EjbConnection by using a pre-defined set of properties.

Author:Hugo Y. K. Lam

Methods

configure
public static void configure(URL url)

Configures the EjbConnectionFactory from the configuration located by the specifed URL. Expected to be called before any other methods are called.

Parameters:
  • url – The URL of the configuration file.
Throws:
createConnection
public static EjbConnection createConnection()

Creates a new EjbConnection. The url, username and password will be retrieved from the default properties.

Returns:a new EjbConnection.
createConnection
public static EjbConnection createConnection(String url)

Creates a new EjbConnection. The username and password will be retrieved from the default properties.

Parameters:
  • url – the URL for this connection.
Returns:

a new EjbConnection.

createConnection
public static EjbConnection createConnection(String url, String username, String password)

Creates a new EjbConnection.

Parameters:
  • url – the URL for this connection.
  • username – the username for authentication.
  • password – the password for authentication.
Returns:

a new EjbConnection.

hk.hku.cecid.piazza.commons.ejb.util

RemoteCommand

public interface RemoteCommand extends javax.ejb.EJBObject

RemoteCommand is the remote interface of RemoteCommandBean. It can execute a remote command with the given parameters.

Author:Hugo Y. K. Lam

See also: RemoteCommandBean, RemoteCommandHandler

Methods

execute
public Object execute(String cmdName, Object[] parameters)

Executes a registered command with the given parameters.

Parameters:
  • cmdName – the command name.
  • parameters – parameters for the target method invocation.
Throws:
  • java.rmi.RemoteException – if there is a remote exception occurred.
  • InstanceException – if the instance of the target class cannot be created or the method could not be invoked.
  • InvocationTargetException – if the invoked method has thrown an exception.
  • NullPointerException – if the command is not registered.
Returns:

the object returned by the invoked method.

RemoteCommandBean

public class RemoteCommandBean extends AbstractSessionBean

RemoteCommandBean is the session bean class of RemoteCommand. It can execute a registered command with the given parameters.

Author:Hugo Y. K. Lam

See also: RemoteCommand, RemoteCommandHandler

Methods

execute
public Object execute(String cmdName, Object[] parameters)

Executes a registered command with the given parameters.

Parameters:
  • cmdName – the command name.
  • parameters – parameters for the target method invocation.
Throws:
  • InstanceException – if the instance of the target class cannot be created or the method could not be invoked.
  • InvocationTargetException – if the invoked method has thrown an exception.
  • NullPointerException – if the command is not registered.
Returns:

the object returned by the invoked method.

RemoteCommandHandler

public final class RemoteCommandHandler

RemoteCommandHandler is a handler class for invoking the RemoteCommand bean. It invokes the bean by using the command name and parameters specified by the caller. The given command must be registered beforehand on both side with a set of command properties in Java properties format:

Key Value
url The connection URL (see EjbConnection)
username The username for the connection
password The password for the connection
class The class name/object to be excuted
method The method of the class to be excuted
parameters The parameter types, separated by comma, of the method to be excuted

If it fails to invoke the bean, it will invoke the target class locally.

Author:Hugo Y. K. Lam

See also: RemoteCommandBean, EjbConnection

Methods

execute
public static Object execute(String cmdName, Object[] parameters)

Executes a registered command with the given parameters.

Parameters:
  • cmdName – the command name.
  • parameters – parameters for the target method invocation.
Throws:
  • RemoteException – if there is a remote exception occurred.
  • InstanceException – if the instance of the target class cannot be created or the method could not be invoked.
  • InvocationTargetException – if the invoked method has thrown an exception.
  • NullPointerException – if the command is not registered.
Returns:

the object returned by the invoked method.

executeLocal
static Object executeLocal(String cmdName, Object[] parameters)

Executes a registered command locally with the given parameters.

Parameters:
  • cmdName – the command name.
  • parameters – parameters for the target method invocation.
Throws:
  • InstanceException – if the instance of the target class cannot be created or the method could not be invoked.
  • InvocationTargetException – if the invoked method has thrown an exception.
  • NullPointerException – if the command is not registered.
Returns:

the object returned by the invoked method.

getCommand
public static Properties getCommand(String name)

Gets the command properties by its name.

Parameters:
  • name – the command name.
Throws:
Returns:

the command properties.

getCommandNames
public static Enumeration getCommandNames()

Gets the names of the regsitered commands.

Returns:the names of the regsitered commands.
register
public static void register(String cmdName, Properties command)

Register a command to this handler.

Parameters:
  • cmdName – the command name.
  • command – the command properties.
unregister
public static void unregister(String cmdName)

Unregister a command from this handler.

Parameters:
  • cmdName – the command name.

RemoteCommandHome

public interface RemoteCommandHome extends javax.ejb.EJBHome

RemoteCommandHome is the home interface of RemoteCommand.

Author:Hugo Y. K. Lam

See also: RemoteCommand

Methods

create
public RemoteCommand create()

Creates a remote instance of RemoteCommand.

Throws:
Returns:

a RemoteCommand remote instance.

hk.hku.cecid.piazza.commons.io

FileSystem

public class FileSystem

FileSystem encapsulates a root directory and provides accessors for querying and modifying this root.

Author:Hugo Y. K. Lam

Fields

TYPE_ALL
public static int TYPE_ALL

Type All.

TYPE_DIR
public static int TYPE_DIR

Type Directory.

TYPE_FILE
public static int TYPE_FILE

Type File.

Constructors

FileSystem
public FileSystem(File root)

Creates a new instance of FileSystem.

Parameters:
  • root – the root of this file system. If root is null, it will be set to the current user directory.

Methods

exists
public boolean exists()

Checks if the root of this file system exists.

Returns:true if the root of this file system exists.
getDirectories
public Collection getDirectories(boolean isRecursive)

Retrieves a collection of directory-only File objects from the root of this file system.

Parameters:
  • isRecursive – true if the search should be recursive.
Returns:

a collection of File objects resulted from the search.

getDirectories
public Collection getDirectories(boolean isRecursive, String pattern)

Retrieves a collection of directory-only File objects from the root of this file system.

Parameters:
  • isRecursive – true if the search should be recursive.
  • pattern – the filename’s pattern for filtering the result. null if no filtering should be applied.
Returns:

a collection of File objects resulted from the search.

getFiles
public Collection getFiles(boolean isRecursive)

Retrieves a collection of file-only File objects from the root of this file system.

Parameters:
  • isRecursive – true if the search should be recursive.
Returns:

a collection of File objects resulted from the search.

getFiles
public Collection getFiles(boolean isRecursive, String pattern)

Retrieves a collection of file-only File objects from the root of this file system.

Parameters:
  • isRecursive – true if the search should be recursive.
  • pattern – the filename’s pattern for filtering the result. null if no filtering should be applied.
Returns:

a collection of File objects resulted from the search.

getFiles
public Collection getFiles(boolean isRecursive, int type, String pattern)

Retrieves a collection of File objects from the root of this file system.

Parameters:
  • isRecursive – true if the search should be recursive.
  • type – the file type to be searched.
  • pattern – the filename’s pattern for filtering the result. null if no filtering should be applied.
Returns:

a collection of File objects resulted from the search.

getFiles
public Collection getFiles(Collection c, boolean isRecursive, int type, String pattern)

Retrieves a collection of File objects from the root of this file system.

Parameters:
  • c – the collection into which the result will be stored.
  • isRecursive – true if the search should be recursive.
  • type – the file type to be searched.
  • pattern – the filename’s pattern for filtering the result. null if no filtering should be applied.
Returns:

a collection of File objects resulted from the search.

getRoot
public File getRoot()

Gets the root of this file system.

Returns:the root of this file system.
purge
public void purge()

Removes the files, including the directories, under the root directory of this file system recursively. If there are files that cannot be removed immediately, the files will be deleted on exit. This method will also remove the root directory itself.

purge
public void purge(boolean isSelfRemoved)

Removes the files, including the directories, under the root directory of this file system recursively. If there are files that cannot be removed immediately, the files will be deleted on exit.

Parameters:
  • isSelfRemoved – true if the root directory itself should be removed.
remove
public boolean remove()

Removes the files, including the directories, under the root directory of this file system recursively. The operation ceases when it encounters any error in removing any file. If the operation is successful, the root directory itself will be removed as well.

Returns:true if and only if all the files are removed successfully.
remove
public boolean remove(boolean isSelfRemoved)

Removes the files, including the directories, under the root of this file system recursively. The operation ceases when it encounters any error in removing any file.

Parameters:
  • isSelfRemoved – true if the root directory itself should be removed.
Returns:

true if and only if all the files are removed successfully.

toString
public String toString()

Returns the absolute path of the root of this file system.

Returns:the absolute path of the root of this file system.

See also: java.lang.Object.toString()

IOHandler

public final class IOHandler

IOHandler provides some convenient methods for handling some basic input and output funtions.

Author:Hugo Y. K. Lam

Methods

merge
public static InputStream merge(InputStream ins1, InputStream ins2)

Merges the given input streams into one input stream.

Parameters:
  • ins1 – the first input stream to be merged.
  • ins2 – the second input stream to be merged.
Returns:

the merged input stream.

pipe
public static void pipe(InputStream ins, OutputStream out)

Pipes an input stream to an output stream.

Parameters:
  • ins – the input stream to be read.
  • out – the output stream to be written.
Throws:
  • IOException – if there is IO error occurred during the operation.
pipe
public static void pipe(Reader reader, Writer writer)

Pipes a reader to a writer.

Parameters:
  • reader – the reader to be read.
  • writer – the writer to be written.
Throws:
  • IOException – if there is IO error occurred during the operation.
readBytes
public static byte[] readBytes(InputStream ins)

Reads an array of bytes from an input stream.

Parameters:
  • ins – the input stream to be read.
Throws:
  • IOException – if there is IO error occurred during the operation.
Returns:

an array of bytes read from the specified input stream.

readBytes
public static byte[] readBytes(Reader reader, Charset charset)

Reads an array of bytes from a reader.

Parameters:
  • reader – the reader to be read.
  • charset – the charset used to convert the characters.
Throws:
  • IOException – if there is IO error occurred during the operation.
Returns:

an array of bytes read from the specified reader.

readString
public static String readString(InputStream ins, Charset charset)

Reads a string from an input stream.

Parameters:
  • ins – the input stream to be read.
  • charset – the charset used to convert the bytes.
Throws:
  • IOException – if there is IO error occurred during the operation.
Returns:

a string read from the specified input stream.

readString
public static String readString(Reader reader)

Reads a string from a reader.

Parameters:
  • reader – the reader to be read.
Throws:
  • IOException – if there is IO error occurred during the operation.
Returns:

a string read from the specified reader.

writeBytes
public static void writeBytes(byte[] bytes, OutputStream out)

Writes an array of bytes to an output stream.

Parameters:
  • bytes – an array of bytes to write.
  • out – the output stream to be written.
Throws:
  • IOException – if there is IO error occurred during the operation.
writeBytes
public static void writeBytes(byte[] bytes, Writer writer, Charset charset)

Writes an array of bytes to a writer.

Parameters:
  • bytes – an array of bytes to write.
  • writer – to writer to be written.
  • charset – the charset used to convert the bytes.
Throws:
  • IOException – if there is IO error occurred during the operation.
writeString
public static void writeString(String s, OutputStream out, Charset charset)

Writes a string to an output stream.

Parameters:
  • s – the string to write.
  • out – the output stream to be written.
  • charset – the charset used to convert the characters.
Throws:
  • IOException – if there is IO error occurred during the operation.
writeString
public static void writeString(String s, Writer writer)

Writes a string to a writer.

Parameters:
  • s – the string to write.
  • writer – the writer to be written.
Throws:
  • IOException – if there is IO error occurred during the operation.

MergedInputStream

public class MergedInputStream extends InputStream

MergedInputStream is an input stream which can merge two input streams into one. When the read() method is called, the first input stream will be read at first. However, if it has already reached the end, the second input stream will be read.

Author:Hugo Y. K. Lam

Constructors

MergedInputStream
public MergedInputStream(InputStream ins1, InputStream ins2)

Creates a new instance of MergedInputStream.

Parameters:
  • ins1 – the first input stream to be merged.
  • ins2 – the second input stream to be merged.

Methods

read
public int read()

Reads the first input stream and if it has reached the end, reads the second input stream. After this input stream has positioned to the second input stream, it will never come back to the first one.

See also: java.io.InputStream.read()

NIOHandler

public class NIOHandler

NIOHandler provides some convenient methods for handling some basic input and output funtions which has adopted the features of java NIO package. Creation Date: 5/10/2006

Author:Twinsen

See also: hk.hku.cecid.piazza.commons.io.IOHandler, java.nio.ByteBuffer, java.nio.MappedByteBuffer, java.nio.channels.Channels

Fields

DEFAULT_PAGE_SIZE
public static final int DEFAULT_PAGE_SIZE

The default page size for memory mapped stream.

MAX_BUFFER_SIZE
public static final int MAX_BUFFER_SIZE

The max buffer size of ByteBuffer is 10mb.

Methods

pipe
public static void pipe(FileInputStream fins, OutputStream out)

Pipes an file input stream to an output stream.

Parameters:
  • fins – the file input stream to be read.
  • out – the output stream to be written.
Throws:
  • IOException – if there is IO error occurred during the operation.
pipe
public static void pipe(FileInputStream fins, OutputStream out, int startPosition, long size)

Pipes an file input stream to an output stream.

Parameters:
  • fins – the file input stream to be read.
  • out – the output stream to be written.
Throws:
  • IOException – if there is IO error occurred during the operation.
pipe
public static void pipe(InputStream ins, OutputStream out)

Pipes an input stream to an output stream.

Parameters:
  • ins – the input stream to be read.
  • out – the output stream to be written.
Throws:
  • IOException – if there is IO error occurred during the operation.
readByteBuffer
public static ByteBuffer readByteBuffer(InputStream ins)

Reads an array of bytes from an input stream.

Parameters:
  • ins – the input stream to be read.
Throws:
  • IOException – if there is IO error occurred during the operation.
Returns:

a bytes buffer read from the specified input stream.

readBytes
public static byte[] readBytes(InputStream ins)

Reads an array of bytes from an input stream.

Parameters:
  • ins – the input stream to be read.
Throws:
  • IOException – if there is IO error occurred during the operation.
Returns:

an array of bytes read from the specified input stream.

writeBytes
public static void writeBytes(byte[] bytes, OutputStream out)

Writes an array of bytes to an output stream.

Parameters:
  • bytes – an array of bytes to write.
  • out – the output stream to be written.
Throws:
  • IOException – if there is IO error occurred during the operation.
writeBytes
public static void writeBytes(ByteBuffer src, OutputStream out)

Writes a byte buffer to an output stream.

Parameters:
  • src – a byte buffer to write.
  • out – the output stream to be written.
Throws:
  • IOException – if there is IO error occurred during the operation.

hk.hku.cecid.piazza.commons.json

JsonParseException

public class JsonParseException extends Exception

Constructors

JsonParseException
public JsonParseException(String message)
JsonParseException
public JsonParseException(Exception exception)

JsonUtil

public class JsonUtil

Methods

fromDictionary
public static String fromDictionary(Map<String, Object> dictionary)
toDictionary
public static Map<String, Object> toDictionary(String source)

hk.hku.cecid.piazza.commons.mail

SmtpMail

public class SmtpMail

A class that handles sending SMTP messages.

Author:Administrator

Constructors

SmtpMail
public SmtpMail(boolean useSSL)

Create a new SmtpMail instance.

Parameters:
  • useSSL
Throws:
  • SmtpMailException
SmtpMail
public SmtpMail(SmtpMailProperties sprops, boolean useSSL)

Create a new SmtpMail instance with the given SmtpMailProperties object.

Parameters:
  • sprops
  • useSSL
Throws:
  • SmtpMailException

Methods

getSession
public Session getSession()
isConnected
public boolean isConnected()

Checks whether the transport associated with this instance is connected.

Returns:boolean
send
public void send(SMTPMessage msg, Address[] to)

Send the SMTPMessage to the address(es) using the SMTP transport

Parameters:
  • msg
  • to
Throws:
send
public void send(String source, Address from, Address[] to, String subject)

Convenience method for composing a simple text MIME Message with the source.

Parameters:
  • source
  • from
  • to
  • subject
Throws:
transportClose
public void transportClose()

Attempts to close the transport connection. If the transport is not connected, will not do anything.

Throws:
transportConnect
public void transportConnect()

Attempts to connect the smtp transport object using the default values from the session.

Throws:
transportConnect
public void transportConnect(String host, int port, String password, String username)

Attempts to connect the smtp transport object. Use -1 for the default port, and null for the default values from the session.

Throws:

SmtpMailException

public class SmtpMailException extends Exception

General SmtpMail exception

Author:Joel Matsumoto

Constructors

SmtpMailException
public SmtpMailException()

Create a SmtpMail exception with no message.

SmtpMailException
public SmtpMailException(String msg)

Create a SmtpMail exception with a message.

Parameters:
  • msg
SmtpMailException
public SmtpMailException(String msg, Exception e)

Create a SmtpMail exception with a message and exception e.

Parameters:
  • msg
  • e
SmtpMailException
public SmtpMailException(Exception e)

Create a SmtpMail exception with the exception e.

Parameters:
  • e

SmtpMailProperties

public class SmtpMailProperties

A class wrapping the SMTP Properties.

Author:Joel Matsumoto

Constructors

SmtpMailProperties
public SmtpMailProperties()

Methods

getFrom
public String getFrom()

Get the from property.

Returns:String
getHost
public String getHost()

Return the host.

Returns:host
getPassword
public String getPassword()

Get the password

Returns:String
getPort
public int getPort()

Get the port number.

Returns:int
getProperties
public Properties getProperties()

Get the properties data structure.

Returns:Properties
getProperty
public String getProperty(String key)

Get the value of the key.

Parameters:
  • key
Returns:

String

getUsername
public String getUsername()

Get the default username

Returns:username
setFrom
public void setFrom(String from)

Set the from property. If no from is set, uses msg.getFrom() or InternetAddress.getLocalAddress().

Parameters:
  • from
setHost
public void setHost(String host)

Set the default host to connect to.

Parameters:
  • host
setPassword
public void setPassword(String pw)

Set the password for servers needing authentication

Parameters:
  • pw
setPort
public void setPort(int port)

Set the port number. Defaults to 25.

Parameters:
  • port
setProperty
public void setProperty(String key, String value)

Add the key/value pair to trhe property structure.

Parameters:
  • key
  • value
setUsername
public void setUsername(String user)

Set the default username to be used

Parameters:
  • user

hk.hku.cecid.piazza.commons.module

ActiveModule

public abstract class ActiveModule extends Module implements Runnable

ActiveModule is a runnable module which runs as a separated thread after started. Subclasses are expected to implement the run() method in the Runnable interface.

Author:Hugo Y. K. Lam

Constructors

ActiveModule
public ActiveModule(String descriptorLocation)

Creates a new instance of ActiveModule.

Parameters:
  • descriptorLocation – the module descriptor.
Throws:
  • ModuleException – if errors encountered when loading the module descriptor.
ActiveModule
public ActiveModule(String descriptorLocation, boolean shouldInitialize)

Creates a new instance of ActiveModule.

Parameters:
  • descriptorLocation – the module descriptor.
  • shouldInitialize – true if the module should be initialized.
Throws:
  • ModuleException – if errors encountered when loading the module descriptor.
ActiveModule
public ActiveModule(String descriptorLocation, ClassLoader loader)

Creates a new instance of ActiveModule.

Parameters:
  • descriptorLocation – the module descriptor.
  • loader – the class loader for this module.
Throws:
  • ModuleException – if errors encountered when loading the module descriptor.
ActiveModule
public ActiveModule(String descriptorLocation, ClassLoader loader, boolean shouldInitialize)

Creates a new instance of ActiveModule.

Parameters:
  • descriptorLocation – the module descriptor.
  • loader – the class loader for this module.
  • shouldInitialize – true if the module should be initialized.
Throws:
  • ModuleException – if errors encountered when loading the module descriptor.

Methods

execute
public abstract boolean execute()

Invoked by the run() method to execute this module’s job.

Returns:true if this method should be invoked again after a defined interval.
getThread
public Thread getThread()

Gets the thread of this module.

Returns:the thread of this module.
init
public void init()

Initializes this module by the following module parameters:

  • group-execution: all - started and stopped by its group; start - only started by its group; stop - only stopped by its group; none - not started or stopped by its group.
  • execution-interval: the interval (milliseconds) that this module should wait until the next execution. A negative number indicates a one-time execution.
  • stop-timeout: the maximum time (milliseconds) to wait for stopping this module.
isGroupStart
public boolean isGroupStart()

Checks if this module should be started by its group, if any.

Returns:true if this module should be started by its group.
isGroupStop
public boolean isGroupStop()

Checks if this module should be stopped by its group, if any.

Returns:true if this module should be stopped by its group.
onStart
public void onStart()

Invoked when this module starts.

See also: .start()

onStop
public void onStop()

Invoked when this module stops.

See also: .stop()

run
public void run()

Invoked by the start() method and will continuously call the execute() method to carry out the execution. This method should not be invoked directly.

See also: .start(), .execute(), java.lang.Runnable.run()

setExecutionInterval
public void setExecutionInterval(long newInterval)

Set the execution interval in the module.

start
public synchronized void start()

Starts this module. This method will invoke onStart() before starting its own thread.

See also: java.lang.Thread.start(), .onStart()

stop
public synchronized void stop()

Stops this module. This method will invoke onStop() before waiting for its thread to die.

See also: .waitForStop(), .onStop()

waitForStop
public synchronized void waitForStop()

Waits for this module’s thread to die.

ActiveMonitor

public class ActiveMonitor

ActiveMonitor is a thread monitor of active threads.

Author:Hugo Y. K. Lam

See also: ActiveThread

Constructors

ActiveMonitor
public ActiveMonitor()

Creares a new instance of ActiveMonitor.

Methods

acquireThread
public synchronized ActiveThread acquireThread()

Acquires a new active thread. This method will block if the maximum number of threads has been reached.

Returns:a new active thread or null if the monitor is suspended.
getMaxThreadCount
public int getMaxThreadCount()

Gets the maximum number of threads this monitor allows to acquire.

Returns:the maximum number.
getPeekThreadCount
public int getPeekThreadCount()

Gets the peek number of threads being acquired.

Returns:the peek number of threads being acquired.
getThreadCount
public int getThreadCount()

Gets the current number of threads being acquired.

Returns:the current number of threads being acquired.
releaseThread
public synchronized void releaseThread(ActiveThread thread)

Releases a previously acquired thread.

Parameters:
  • thread – the previously acquired thread.
resume
public synchronized void resume()

Resumes this monitor.

setMaxThreadCount
public void setMaxThreadCount(int maxThreadCount)

Sets the maximum number of threads this monitor allows to acquire.

Parameters:
  • maxThreadCount – the maximum number.
suspend
public synchronized void suspend()

Suspends this monitor.

See also: .waitForEmpty()

waitForEmpty
public synchronized void waitForEmpty()

Waits until all the acquired threads have been released.

ActiveTask

public interface ActiveTask

ActiveTask represents a task which can be executed under a separated thread.

Author:Hugo Y. K. Lam

Methods

execute
public void execute()

Executes this task.

Throws:
  • Exception – if unable to carry out the task.
getMaxRetries
public int getMaxRetries()

Gets the maximum number of retries.

Returns:the maximum number of retries.
getRetryInterval
public long getRetryInterval()

Gets the retry interval in milliseconds.

Returns:the retry interval.
isRetryEnabled
public boolean isRetryEnabled()

Indicates if retry should be enabled.

Returns:true if retry should be enabled.
isSucceedFast
public boolean isSucceedFast()

Indicates if the task should succeed fast. false if this task should be retried depending solely on the indication of isRetryEnabled().

Returns:true if the task should succeed fast.

See also: .isRetryEnabled()

onAwake
public void onAwake()

Invoked when the retry interval has passed and before execution.

onFailure
public void onFailure(Throwable e)

Invoked when there is any exception thrown from the execution.

Parameters:
  • e – the exception cause.
setRetried
public void setRetried(int retried)

Sets the number of times this task has been retried.

Parameters:
  • retried – the number of times this task has been retried.

ActiveTaskAdaptor

public class ActiveTaskAdaptor implements ActiveTask

A Active Task Adaptor is a dummy class for the interface active task. Creation Date: 24/10/2006.

Author:Twinsen Tsang

See also: hk.hku.cecid.piazza.commons.module.ActiveTask

Methods

execute
public void execute()
getMaxRetries
public int getMaxRetries()
getRetryInterval
public long getRetryInterval()
isRetryEnabled
public boolean isRetryEnabled()
isSucceedFast
public boolean isSucceedFast()
onAwake
public void onAwake()
onFailure
public void onFailure(Throwable e)
setRetried
public void setRetried(int retried)

ActiveTaskList

public abstract class ActiveTaskList extends Component

ActiveTaskList is a module component which represents a collection of active tasks.

Author:Hugo Y. K. Lam

See also: ActiveTask

Methods

getTaskList
public abstract List getTaskList()

Gets the active task list.

Returns:the active task list.

ActiveTaskModule

public class ActiveTaskModule extends ActiveModule

ActiveTaskModule is an active module which manages an active task list. As an active module, it runs as a separated thread and loops through the task list for executing the tasks. It also contains an active monitor responsible for monitoring and controlling the thread count.

Author:Hugo Y. K. Lam

Constructors

ActiveTaskModule
public ActiveTaskModule(String descriptorLocation)

Creates a new instance of ActiveTaskModule.

Parameters:
  • descriptorLocation – the module descriptor.
Throws:
  • ModuleException – when errors encountered when loading the module descriptor.
ActiveTaskModule
public ActiveTaskModule(String descriptorLocation, boolean shouldInitialize)

Creates a new instance of ActiveTaskModule.

Parameters:
  • descriptorLocation – the module descriptor.
  • shouldInitialize – true if the module should be initialized.
Throws:
  • ModuleException – when errors encountered when loading the module descriptor.
ActiveTaskModule
public ActiveTaskModule(String descriptorLocation, ClassLoader loader)

Creates a new instance of ActiveTaskModule.

Parameters:
  • descriptorLocation – the module descriptor.
  • loader – the class loader for this module.
Throws:
  • ModuleException – when errors encountered when loading the module descriptor.
ActiveTaskModule
public ActiveTaskModule(String descriptorLocation, ClassLoader loader, boolean shouldInitialize)

Creates a new instance of ActiveTaskModule.

Parameters:
  • descriptorLocation – the module descriptor.
  • loader – the class loader for this module.
  • shouldInitialize – true if the module should be initialized.
Throws:
  • ModuleException – when errors encountered when loading the module descriptor.

Methods

execute
public boolean execute()

Invoked by the start() method to start executing the managed task list and its tasks.

Returns:true if the active monitor of this module is not suspended.

See also: hk.hku.cecid.piazza.commons.module.ActiveModule.execute()

getMonitor
public ActiveMonitor getMonitor()

Gets the monitor of this module.

Returns:the monitor of this module.
init
public void init()

Initializes this module by loading the active task list component named “task-list”. The component may have the following parameters:

  • max-thread-count: the maximum number of threads which can be acquired to execute the tasks in the task list. A number smaller than 1 indicates the tasks should be run under the same thread as this module.
  • wait-for-list: true if the tasks in the task list should be completely executed before being refreshed.

See also: hk.hku.cecid.piazza.commons.module.Module.init()

onStart
public void onStart()

Resumes the active monitor so that new threads can be acquired for executing tasks.

See also: hk.hku.cecid.piazza.commons.module.ActiveModule.start(), hk.hku.cecid.piazza.commons.module.ActiveModule.onStart()

onStop
public void onStop()

Suspends the active monitor so that no more threads can be acquired for executing tasks.

See also: hk.hku.cecid.piazza.commons.module.ActiveModule.stop(), hk.hku.cecid.piazza.commons.module.ActiveModule.onStop()

ActiveThread

public class ActiveThread implements Runnable

ActiveThread is a thread which executes its associated task and manages the retry of the task. An active thread may or may not be managed by an active monitor.

Author:Hugo Y. K. Lam

See also: ActiveTask, ActiveMonitor

Constructors

ActiveThread
public ActiveThread()

Creates a new instance of ActiveThread.

ActiveThread
public ActiveThread(ActiveMonitor monitor)

Creates a new instance of ActiveThread.

Parameters:
  • monitor – the active monitor from which this active thread is acquired.

Methods

getTask
public ActiveTask getTask()

Gets the active task of this thread.

Returns:the active task of this thread.
run
public void run()

Executes its associated task and manages the retry of the task.

See also: java.lang.Runnable.run()

setTask
public void setTask(ActiveTask task)

Sets the active task of this thread.

Parameters:
  • task – the active task to be executed.
start
public void start()

Starts a new thread to execute the associated task.

See also: .run()

Component

public abstract class Component

Component represents a module component. Subclasses should override the init() method for their own initializations.

Author:Hugo Y. K. Lam

See also: Module

Methods

getId
public String getId()

Gets the component ID.

Returns:the component ID.
getModule
public Module getModule()

Gets the parent module of this component.

Returns:the parent module of this component.
getName
public String getName()

Gets the name of this component.

Returns:the name of this component.
getParameters
public Properties getParameters()

Gets the parameters of this component.

Returns:the parameters of this component.
init
protected void init()

Invoked for initialization.

Throws:
  • Exception – if there is any error in the initialization.
setId
public void setId(String id)

Sets the component ID.

Parameters:
  • id – the component ID.
setModule
protected void setModule(Module module)

Sets the parent module of this component.

Parameters:
  • module – the parent module of this component.
setName
protected void setName(String name)

Sets the name of this component.

Parameters:
  • name – the name of this component.
setParameters
protected void setParameters(Properties parameters)

Sets the parameters of this component.

Parameters:
  • parameters – the parameters of this component.

ComponentException

public class ComponentException extends GenericException

ComponentException represents an exception related to a component.

Author:Hugo Y. K. Lam

Constructors

ComponentException
public ComponentException()

Creates a new instance of ComponentException.

ComponentException
public ComponentException(String message)

Creates a new instance of ComponentException.

Parameters:
  • message – the error message.
ComponentException
public ComponentException(Throwable cause)

Creates a new instance of ComponentException.

Parameters:
  • cause – the cause of this exception.
ComponentException
public ComponentException(String message, Throwable cause)

Creates a new instance of ComponentException.

Parameters:
  • message – the error message.
  • cause – the cause of this exception.

EventModule

public class EventModule<TEventListener> extends Module

Fields

MODULE_ID
public static final String MODULE_ID
eventListenerList
protected List<TEventListener> eventListenerList

Constructors

EventModule
public EventModule(String descriptorLocation, ClassLoader loader)
EventModule
public EventModule(String descriptorLocation, boolean shouldInitialize)
EventModule
public EventModule(String descriptorLocation, ClassLoader loader, boolean shouldInitialize)
EventModule
public EventModule(String descriptorLocation)

Methods

getListeners
public Collection<TEventListener> getListeners()
hasListeners
public boolean hasListeners()
init
public void init()

LimitedActiveTaskList

public abstract class LimitedActiveTaskList extends ActiveTaskList

A limited active task list is a active task list that can be set it’s limit in the parameters list. But it has not effect on how big the active task list can return (no bound, only a limit value). Creation Date: 31/10/2006.

Author:Twinsen

Methods

getMaxTasksPerList
public int getMaxTasksPerList()
Returns:the maxTasksPerList
init
protected void init()

Component Initialization.

Throws:

Module

public class Module extends Component

A Module is described by a module descriptor and contains zero to many components. Each module has its own classloader for loading its components, which are defined in the module descriptor, and its resources.

Author:Hugo Y. K. Lam

See also: Component

Constructors

Module
public Module(String descriptorLocation)

Creates and initializes a new instance of Module.

Parameters:
  • descriptorLocation – the module descriptor.
Throws:
  • ModuleException – if errors encountered when loading the module descriptor.
Module
public Module(String descriptorLocation, boolean shouldInitialize)

Creates a new instance of Module.

Parameters:
  • descriptorLocation – the module descriptor.
  • shouldInitialize – true if the module should be initialized.
Throws:
  • ModuleException – if errors encountered when loading the module descriptor.
Module
public Module(String descriptorLocation, ClassLoader loader)

Creates and initializes a new instance of Module.

Parameters:
  • descriptorLocation – the module descriptor.
  • loader – the class loader for this module.
Throws:
  • ModuleException – if errors encountered when loading the module descriptor.
Module
public Module(String descriptorLocation, ClassLoader loader, boolean shouldInitialize)

Creates a new instance of Module.

Parameters:
  • descriptorLocation – the module descriptor.
  • loader – the class loader for this module.
  • shouldInitialize – true if the module should be initialized.
Throws:
  • ModuleException – if errors encountered when loading the module descriptor.

Methods

createComponents
protected void createComponents()

Creates all the components defined in the module descriptor.

Throws:
getClassLoader
public ClassLoader getClassLoader()

Gets the class loader that this module uses to load classes.

Returns:the class loader for this module.
getComponent
public Component getComponent(String id)

Gets the specified component in this module.

Parameters:
  • id – the ID of the module component.
Returns:

the module component.

getComponentCount
public int getComponentCount()

Gets the number of components in this module.

Returns:the number of components in this module.
getComponents
public Collection getComponents()

Gets all the components in this module.

Returns:all module components
getDescriptor
public URL getDescriptor()

Gets the module descriptor.

Returns:the module descriptor.
getGroup
public ModuleGroup getGroup()

Gets the module group to which this module belongs.

Returns:the module group.
getLogger
public Logger getLogger()

Gets the logger of this module.

Returns:the logger of this module.
getRequiredParameter
protected String getRequiredParameter(String key)

Get the mandatory parameter from the current module, throw ModuleException if not found.

Parameters:
  • key – the key in the parameters list.
Throws:
Returns:

The value of the parameter if found.

getResource
public URL getResource(String name)

Gets a resource as URL.

Parameters:
  • name – the name of the resource.
Returns:

the URL of the resource.

See also: .getResource(String,ClassLoader)

getResource
public static URL getResource(String name, ClassLoader loader)

Gets a resource as URL.

The specified name can be an absolute path or a relative path to the current directory or classpaths.

If the specified name is a relative path, it will be searched through the current directory and then the classpaths.

Parameters:
  • name – the name of the resource.
  • loader – the class loader for finding the resource.
Returns:

the URL of the resource.

getResourceAsStream
public InputStream getResourceAsStream(String name)

Gets a resource as stream.

Parameters:
  • name – the name of the resource.
Returns:

an input stream of the resource.

See also: .getResource(String)

getString
protected String getString(String key)

Gets the string value of the specified key from the module descriptor.

Parameters:
  • key – the key in the resource bundle.
Returns:

the string value.

getVersion
public String getVersion()

Gets the version of this module.

Returns:the version of this module.
init
public void init()

Initializes the module and all its components.

Throws:
initComponents
protected void initComponents()

Initializes all the created components.

Throws:
setComponent
public void setComponent(Component component)

Sets a component to this module.

Parameters:
  • component – the component to be set.
setGroup
public void setGroup(ModuleGroup group)

Sets the module group to which this module belongs.

Parameters:
  • group – the module group.
toString
public String toString()

Returns a string representation of this module.

Returns:a string representation of this module.

See also: java.lang.Object.toString()

ModuleException

public class ModuleException extends RuntimeException

ModuleException represents a module’s runtime exception.

Author:Hugo Y. K. Lam

Constructors

ModuleException
public ModuleException()

Creates a new instance of ModuleException.

ModuleException
public ModuleException(String message)

Creates a new instance of ModuleException.

Parameters:
  • message – the error message.
ModuleException
public ModuleException(Throwable cause)

Creates a new instance of ModuleException.

Parameters:
  • cause – the cause of this exception.
ModuleException
public ModuleException(String message, Throwable cause)

Creates a new instance of ModuleException.

Parameters:
  • message – the error message.
  • cause – the cause of this exception.

Methods

toString
public String toString()

Returns a string representation of this exception.

Returns:a string representation of this exception.

See also: java.lang.Object.toString()

ModuleGroup

public class ModuleGroup

ModuleGroup represents a group of modules and is capable of starting and stopping its active modules. A module group can have multiple system modules and the first one defined in the module group descriptor will be treated as the default system module.

Author:Hugo Y. K. Lam

Constructors

ModuleGroup
public ModuleGroup(String descriptorLocation)

Creates a new instance of ModuleGroup.

Parameters:
  • descriptorLocation – the descriptor location.
ModuleGroup
public ModuleGroup(String descriptorLocation, ClassLoader loader)

Creates a new instance of ModuleGroup.

Parameters:
  • descriptorLocation – the descriptor location.
  • loader – the class loader for loading the modules.

Methods

addChild
public void addChild(ModuleGroup group)

Adds a child module group.

Parameters:
  • group – the child module group.
getChildren
public Collection getChildren()

Gets the child module groups.

Returns:the child module groups.
getModule
public Module getModule(String id)

Gets the specified module in this module group.

Parameters:
  • id – the module ID.
Returns:

the specified module.

getModules
public Collection getModules()

Gets all modules in this module group.

Returns:all modules in this module group.
getName
public String getName()

Gets the name of this module group.

Returns:the name of this module group.
getParent
public ModuleGroup getParent()

Gets the parent module group.

Returns:the parent module group.
getSystemModule
public SystemModule getSystemModule()

Gets the default system module.

Returns:the default system module or null if there is none.
removeChild
public void removeChild(ModuleGroup group)
setParent
public void setParent(ModuleGroup parent)

Sets the parent module group.

Parameters:
  • parent – the parent module group.
startActiveModules
public void startActiveModules()

Starts all active modules.

stopActiveModules
public void stopActiveModules()

Stops all active modules.

toString
public String toString()

Returns a string representation of this module group.

Returns:a string representation of this module group.

See also: java.lang.Object.toString()

PersistentComponent

public abstract class PersistentComponent extends Component

PersistentComponent represents a component that is persistent. Subclasses should override the loading(URL) and storing(URL) methods to provide their specific implementations.

Author:Hugo Y. K. Lam

Constructors

PersistentComponent
public PersistentComponent()

Creates a new instance of PersistentComponent.

PersistentComponent
public PersistentComponent(URL url)

Creates a new instance of PersistentComponent.

Parameters:
  • url – the url representing this component.
Throws:
  • Exception – when there is any error in loading the source.

Methods

getURL
public URL getURL()

Gets the url representing this component.

Returns:the url representing this component.
init
protected void init()

Initializes this component from the URL specified in the parameter ‘config’. The load() method will then be invoked to handle the loading of this component.

See also: .load(URL), Component.init(), Component.getParameters()

load
public void load(URL url)

Loads this component from the specified url.

Parameters:
  • url – the url representing this component.
Throws:
  • Exception – when there is any error in loading.

See also: .loading(URL)

load
public void load()

Loads this component from the URL representing it.

Throws:

See also: .load(URL)

loading
protected void loading(URL url)

Invoked by the load() method and should be overridden by subclasses to provide implementation.

See also: .load(URL)

store
public void store(URL url)

Stores this component to the specified url.

Parameters:
  • url – the url representing this component.
Throws:
  • Exception – when there is any error in storing.

See also: .storing(URL)

store
public void store()

Stores this component to the URL representing it.

Throws:

See also: .store(URL)

storing
protected void storing(URL url)

Invoked by the store() method and should be overridden by subclasses to provide implementation.

See also: .store(URL)

PluginProcessor

public abstract class PluginProcessor implements PluginHandler

Methods

getDAOFactory
public DAOFactory getDAOFactory()
getLogger
public Logger getLogger()
getModuleGroup
public ModuleGroup getModuleGroup()
getModuleGroupImpl
protected abstract ModuleGroup getModuleGroupImpl()
getProperties
public PropertySheet getProperties()
getProperties
public String[] getProperties(String key)
getProperty
public String getProperty(String key)
getProperty
public String getProperty(String key, String def)
getSystemComponent
public Component getSystemComponent(String id)
getSystemModule
public SystemModule getSystemModule()
processActivation
public void processActivation(Plugin plugin)

See also: hk.hku.cecid.piazza.commons.spa.PluginHandler.processActivation(Plugin)

processDeactivation
public void processDeactivation(Plugin plugin)

See also: hk.hku.cecid.piazza.commons.spa.PluginHandler.processDeactivation(Plugin)

setModuleGroup
public void setModuleGroup(ModuleGroup moduleGroup)
setModuleGroupImpl
protected abstract void setModuleGroupImpl(ModuleGroup moduleGroup)

SystemComponent

public abstract class SystemComponent extends Component

Methods

getComponent
public Component getComponent(String id)
getDAOFactory
public DAOFactory getDAOFactory()
getLogger
public Logger getLogger()
getProperties
public PropertySheet getProperties()
getSystemModule
public SystemModule getSystemModule()

SystemModule

public class SystemModule extends Module

SystemModule is a module which contains some utility members which are common to a system.

Author:Hugo Y. K. Lam

Fields

dao
public final DAOFactory dao

The system DAO factory, having a component name ‘daofactory’.

log
public final Logger log

The system logger, having a component name ‘logger’.

messages
public final Messages messages

The system messages, having a component name ‘messages’.

properties
public final PropertySheet properties

The system properties, having a component name ‘properties’.

Constructors

SystemModule
public SystemModule(String descriptorLocation)

Creates a new instance of SystemModule.

Parameters:
  • descriptorLocation – the module descriptor.
Throws:
  • ModuleException – if errors encountered when loading the module descriptor.
SystemModule
public SystemModule(String descriptorLocation, boolean shouldInitialize)

Creates a new instance of SystemModule.

Parameters:
  • descriptorLocation – the module descriptor.
  • shouldInitialize – true if the module should be initialized.
Throws:
  • ModuleException – if errors encountered when loading the module descriptor.
SystemModule
public SystemModule(String descriptorLocation, ClassLoader loader)

Creates a new instance of SystemModule.

Parameters:
  • descriptorLocation – the module descriptor.
  • loader – the class loader for this module.
Throws:
  • ModuleException – if errors encountered when loading the module descriptor.
SystemModule
public SystemModule(String descriptorLocation, ClassLoader loader, boolean shouldInitialize)

Creates a new instance of SystemModule.

Parameters:
  • descriptorLocation – the module descriptor.
  • loader – the class loader for this module.
  • shouldInitialize – true if the module should be initialized.
Throws:
  • ModuleException – if errors encountered when loading the module descriptor.

Methods

getLogger
public Logger getLogger()

See also: hk.hku.cecid.piazza.commons.module.Module.getLogger()

hk.hku.cecid.piazza.commons.net

ConnectionException

public class ConnectionException extends hk.hku.cecid.piazza.commons.GenericException

ConnectionException represents all kinds of exception related to connectivity.

Author:Hugo Y. K. Lam

Constructors

ConnectionException
public ConnectionException()

Creates a new instance of ConnectionException.

ConnectionException
public ConnectionException(String message)

Creates a new instance of ConnectionException.

Parameters:
  • message – the error message.
ConnectionException
public ConnectionException(Throwable cause)

Creates a new instance of ConnectionException.

Parameters:
  • cause – the cause of this exception.
ConnectionException
public ConnectionException(String message, Throwable cause)

Creates a new instance of ConnectionException.

Parameters:
  • message – the error message.
  • cause – the cause of this exception.

HttpConnector

public class HttpConnector

HttpConnector is a connector for making HTTP/S connections to an URL.

Author:Hugo Y. K. Lam

Constructors

HttpConnector
public HttpConnector(Object destUrl)

Creates a new instance of HttpConnector.

Parameters:
  • destUrl – the destination URL, either in String or URL format.
Throws:
  • MalformedURLException – if the URL is malformed.

Methods

addKeyManager
public void addKeyManager(KeyManager km)

Adds a key manager for SSL connection.

Parameters:
  • km – the key manager.
addTrustManager
public void addTrustManager(TrustManager tm)

Adds a trust manager for SSL connection.

Parameters:
  • tm – the trust manager.
createConnection
public HttpURLConnection createConnection()

Creates a new HTTP connection based on this connector’s properties.

Throws:
Returns:

a new HTTP connection.

getHostnameVerifier
public HostnameVerifier getHostnameVerifier()

Gets the host verifier for SSL connection.

Returns:the host name verifier.
getRequestHeaders
public Map getRequestHeaders()

Gets the HTTP request headers.

Returns:the HTTP headers, or null.
getSSLSocketFactory
public SSLSocketFactory getSSLSocketFactory()

Gets the SSL socket factory which is used in SSL connection.

Throws:
Returns:

the SSL socket factory.

send
public InputStream send(InputStream request)

Sends an HTTP/S request using the given HTTP connection.

Parameters:
  • request – the HTTP request content or null for a simple get request.
Throws:
Returns:

an input stream for reading the reply from the host.

send
public InputStream send(InputStream request, HttpURLConnection connection)

Sends an HTTP/S request using the given HTTP connection.

Parameters:
  • request – the HTTP request content or null for a simple get request.
  • connection – the HTTP connection for sending the request.
Throws:
Returns:

an input stream for reading the reply from the host.

setHostnameVerifier
public void setHostnameVerifier(HostnameVerifier hostnameVerifier)

Sets a host name verifier for SSL connection.

Parameters:
  • hostnameVerifier – the host name verifier.
setRequestHeaders
public void setRequestHeaders(Map headers)

Sets the HTTP request headers.

Parameters:
  • headers – the HTTP headers.

MailConnector

public abstract class MailConnector

MailConnector is an abstract connector for making connection to mail hosts. The configuration of mail connector is mainly through the standard java properties injection. You can always use either addProperties(Properties) or getProperties() to set or get the current configuration of this mail connector. For the detail of the properties key, read here 1.0.1 - Add help method for enabling black box debug mode through setDebug(boolean)

Author:Hugo Y. K. Lam,, Twinsen Tsang (modifers)

Constructors

MailConnector
public MailConnector(String protocol, String host)

Creates a new instance of MailConnector.

Parameters:
  • protocol – the mail protocol.
  • host – the mail host.
MailConnector
public MailConnector(String protocol, String host, String username, String password)

Creates a new instance of MailConnector.

Parameters:
  • protocol – the mail protocol.
  • host – the mail host.
  • username – the user name for authentication.
  • password – the password for authentication.

Methods

addProperties
public void addProperties(Properties properties)

Adds the given mail properties to the underlying mail properties used by this connector.

Parameters:
  • properties – the properties to be added.
addProperty
public void addProperty(String propKey, String propValue)

Adds a property to the underlying mail properties used by this connector.

Parameters:
  • propKey – the property key.
  • propValue – the property value.
createSession
public Session createSession()

Creates a mail session from the underlying mail properties.

Returns:the mail session.
getHost
public String getHost()

Gets the host to which this mail connector connects.

Returns:the mail host.
getIsDebug
public boolean getIsDebug()

Get whether the mail connector is under debug mode.

getProperties
public Properties getProperties()

Gets the underlying mail properties used by this connector.

Returns:the mail properties.
getProtocol
public String getProtocol()

Gets the protocol that this mail connector uses.

Returns:the mail protocol.
setDebug
public void setDebug(boolean on)

Set whether the mail connector is under debug mode.

Parameters:
  • on – The flag whether debug mode is switched on for this mail connector.

MailReceiver

public class MailReceiver extends MailConnector

MailReceiver is a mail connector for making connections to incoming mail servers.

Author:Hugo Y. K. Lam

Constructors

MailReceiver
public MailReceiver(String host, String username, String password)

Creates a new instance of MailReceiver. The default protocol is POP3.

Parameters:
  • host – the mail host.
  • username – the user name for authentication.
  • password – the password for authentication.
MailReceiver
public MailReceiver(String protocol, String host, String username, String password)

Creates a new instance of MailReceiver.

Parameters:
  • protocol – the mail protocol.
  • host – the mail host.
  • username – the user name for authentication.
  • password – the password for authentication.

Methods

connect
public synchronized void connect()

Connects to the incoming mail server.

Throws:
  • ConnectionException – if unable to connect to the incoming mail server or a connection to the server has already been established.
disconnect
public synchronized void disconnect()

Disconnects from the incoming mail server.

Throws:
  • ConnectionException – if unable to disconnect from the incoming mail server or the connection to the server has not been established.
openFolder
public synchronized Folder openFolder(String folderName)

Opens a specified folder for read-write access.

Parameters:
  • folderName – the name of the folder to be opened.
Throws:
  • ConnectionException – if unable to open the specified folder or the connection to the incoming mail server has not yet been established.
Returns:

the opened folder.

openFolder
public synchronized Folder openFolder(String folderName, boolean readOnly)

Opens a specified folder.

Parameters:
  • folderName – the name of the folder to be opened.
  • readOnly – true if the folder should be readonly.
Throws:
  • ConnectionException – if unable to open the specified folder or the connection to the incoming mail server has not yet been established.
Returns:

the opened folder.

openInbox
public synchronized Folder openInbox()

Opens the inbox for read-write access.

Throws:
  • ConnectionException – if unable to open the inbox or the connection to the incoming mail server has not yet been established.
Returns:

the opened inbox.

MailSender

public class MailSender extends MailConnector

MailSender is a mail connector for making connections to outgoing mail servers.

Author:Hugo Y. K. Lam

Constructors

MailSender
public MailSender(String host)

Creates a new instance of MailSender. The default protocol is SMTP.

Parameters:
  • host – the mail host.
MailSender
public MailSender(String host, String username, String password)

Creates a new instance of MailSender. The default protocol is SMTP.

Parameters:
  • host – the mail host.
  • username – the user name for authentication.
  • password – the password for authentication.
MailSender
public MailSender(String protocol, String host)

Creates a new instance of MailSender.

Parameters:
  • protocol – the mail protocol.
  • host – the mail host.
MailSender
public MailSender(String protocol, String host, String username, String password)

Creates a new instance of MailSender.

Parameters:
  • protocol – the mail protocol.
  • host – the mail host.
  • username – the user name for authentication.
  • password – the password for authentication.

Methods

createMessage
public MimeMessage createMessage()

Creates a MIME message from the underlying mail properties.

Returns:a new MIME message.
createMessage
public MimeMessage createMessage(Session session)

Creates a MIME message from the given mail session.

Parameters:
  • session – the mail session.
Returns:

a new MIME message.

createMessage
public MimeMessage createMessage(String from, String to, String cc, String subject)

Creates a simple MIME message with some basic headers.

Parameters:
  • from – the ‘from’ mail address.
  • to – the ‘to’ mail address(es).
  • cc – the ‘cc’ mail address(es).
  • subject – the mail subject.
Throws:
Returns:

a new MIME message.

createMessage
public MimeMessage createMessage(String from, String to, String cc, String subject, Session session)

Creates a simple MIME message with some basic headers.

Parameters:
  • from – the ‘from’ mail address.
  • to – the ‘to’ mail address(es).
  • cc – the ‘cc’ mail address(es).
  • subject – the mail subject.
  • session – the mail session.
Throws:
Returns:

a new MIME message.

send
public void send(String from, String to, String cc, String subject, String body)

Sends a simple mail message.

Parameters:
  • from – the ‘from’ mail address.
  • to – the ‘to’ mail address(es).
  • cc – the ‘cc’ mail address(es).
  • subject – the mail subject.
  • body – the message content.
Throws:
send
public void send(Message msg)

Sends a mail message.

Parameters:
  • msg – the mail message to be sent.
Throws:

hk.hku.cecid.piazza.commons.os

OSCommander

public class OSCommander

The OS Manager provides interface for executing platform command console so that it can execute the console command through this interface. Creation Date: 04/05/2009

Author:Philip Wong

Fields

ONE_GB
public static final long ONE_GB
REDIRECT_ERROR_STREAM
public static boolean REDIRECT_ERROR_STREAM

Constructors

OSCommander
public OSCommander()
OSCommander
public OSCommander(SystemComponent sys)

Methods

createDummyFile
public void createDummyFile(String path, long size)

Create a dummy file with the specified path and size for Linux, Mac OS X & SunOS.

Parameters:
  • path – The absolute path of the dummy files.
  • size – The size of dummy files.
Throws:
  • IOException
Returns:

true if the operation run successfully.

execNoWaitAsInputStream
public BufferedInputStream execNoWaitAsInputStream(String... args)
execNoWaitAsInputStream
public BufferedInputStream execNoWaitAsInputStream(File dir, String... args)
execNoWaitAsProcess
protected Process execNoWaitAsProcess(String... args)
execNoWaitAsProcess
protected Process execNoWaitAsProcess(File dir, String... args)
execNoWaitAsReader
public BufferedReader execNoWaitAsReader(String... args)
execNoWaitAsReader
public BufferedReader execNoWaitAsReader(File dir, String... args)
execWaitAsOutputStream
public void execWaitAsOutputStream(OutputStream os, String... args)
execWaitAsOutputStream
public void execWaitAsOutputStream(OutputStream os, File dir, String... args)
execWaitAsString
public String execWaitAsString(String... args)
execWaitAsString
public String execWaitAsString(File dir, String... args)
getDiskFreespace
public long getDiskFreespace(String path)
getOSName
public String getOSName()
getOSVersion
public String getOSVersion()
init
protected void init()
writeTo
public void writeTo(InputStream is, OutputStream os)

OSManager

public class OSManager extends SystemComponent

The OSManager acts as a bridge between OSCommander and Piazza Commons framework. It provides convenient way for components to execute system command. Creation Date: 04/05/2009

Author:Philip Wong

Fields

osCommander
protected OSCommander osCommander

Methods

getCommander
public OSCommander getCommander()
getName
public String getName()
init
public void init()

hk.hku.cecid.piazza.commons.pagelet

HttpPageletAdaptor

public abstract class HttpPageletAdaptor extends HttpRequestAdaptor

HttpPageletAdaptor is an HTTP request adaptor which generates a page from a template pagelet. A template pagelet may contain the content, or part of the content, of the page to be generated. It also describes the layout of other pagelets in the page.

The tag in the template which declares a pagelet should follow the convention stated below:

<!-- template-[pagelet-id] -->

By default, there are two generation modes of the page.

  1. full - Generate the page according to the template pre-defined by this adaptor. This is the default generation mode.
  2. raw - Generate the page according to the dynamically specified pagelet.

Note: All the pagelets, including the template, must be saved in UTF-8 encoding.

Author:Hugo Y. K. Lam

See also: Pagelet, PageletStore, Template

Fields

REQ_PARAM_ACTION
protected static final String REQ_PARAM_ACTION

The name of the request parameter which specifies an action. This parameter is named ‘action’.

REQ_PARAM_PAGELET
protected static final String REQ_PARAM_PAGELET

The name of the request parameter which specifies a pagelet ID. This parameter is named ‘pagelet’.

REQ_PARAM_PAGEMODE
protected static final String REQ_PARAM_PAGEMODE

The name of the request parameter which specifies the generation mode. This parameter is named ‘mode’.

Methods

getErrorPagelet
protected Pagelet getErrorPagelet(HttpServletRequest request)

Gets the error pagelet. This method invokes getPagelet() with a parameter “&pagelet-error”.

Parameters:
  • request – the servlet request.
Returns:

the template pagelet.

getPagelet
protected Pagelet getPagelet(String id)

Gets the pagelet from the underlying pagelet store. If the specified ID is preceded by an ampersand, it indicates the pagelet id should be firstly treated as a listener parameter name which has a value of the target pagelet ID. In this case, if there is a corresponding listener parameter, its value will be used as the target pagelet ID. Otherwise, the specified id will be matched against the underlying pagelet store as if there is no ampersand indicator.

Parameters:
  • id – the pagelet ID.
Returns:

the corresponding pagelet or null if not found.

getPageletStore
protected abstract PageletStore getPageletStore()

Gets the pagelet store which holds all the registered pagelets of this adaptor.

Returns:a pagelet store.
getTemplate
protected Pagelet getTemplate(HttpServletRequest request)

Gets the template pagelet. This method invokes getPagelet() with a parameter “&pagelet-template”.

Parameters:
  • request – the servlet request.
Returns:

the template pagelet.

processError
protected void processError(TemplateElement element, Throwable error, HttpServletRequest request, HttpServletResponse response)

Processes the error generated when processing a pagelet.

Parameters:
  • element – the template element which represents the pagelet.
  • error – the error generated by the pagelet process.
  • request – the servlet request.
  • response – the servlet response.
Throws:

See also: .processTemplate(HttpServletRequest,HttpServletResponse)

processPagelet
protected void processPagelet(TemplateElement element, Pagelet pagelet, HttpServletRequest request, HttpServletResponse response)

Processes the pagelet of the generating page by reading the content from the pagelet and generates it to the output.

Parameters:
  • element – the template element which represents the pagelet.
  • pagelet – the pagelet to be processed.
  • request – the servlet request.
  • response – the servlet response.
Throws:

See also: .processTemplate(HttpServletRequest,HttpServletResponse)

processRequest
public String processRequest(HttpServletRequest request, HttpServletResponse response)

Processes the page request. This method determines if the generation mode is “raw”. If not, it invokes processTemplate() to complete the rest of the generation.

See also: .processTemplate(HttpServletRequest,HttpServletResponse), hk.hku.cecid.piazza.commons.servlet.http.HttpRequestListener.processRequest(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)

processTemplate
protected void processTemplate(HttpServletRequest request, HttpServletResponse response)

Processes the template of the generating page. This method invokes getTemplate() to retrieve the template pagelet. It then generates the page according to the pagelet. The content of the template pagelet will be parsed according to the following alogirthm:

  • When it encounters any text other than a template tag, it invokes processText() to generate the content.
  • When it encounters a template tag in the template, it invokes processPagelet() to generate the content.
  • When it encounters any errors while invoking processPagelet(), it will invokes processError() to generate the content.
Parameters:
  • request – the servlet request.
  • response – the servlet response.
Throws:

See also: .getTemplate(HttpServletRequest), .processText(TemplateElement,String,HttpServletRequest,HttpServletResponse), .processPagelet(TemplateElement,Pagelet,HttpServletRequest,HttpServletResponse), .processError(TemplateElement,Throwable,HttpServletRequest,HttpServletResponse)

processText
protected void processText(TemplateElement element, String text, HttpServletRequest request, HttpServletResponse response)

Processes the text part of the generating page by simply generating the text to the output.

Parameters:
  • element – the template element which represents the text.
  • text – the text to be processed.
  • request – the servlet request.
  • response – the servlet response.
Throws:

See also: .processTemplate(HttpServletRequest,HttpServletResponse)

Pagelet

public class Pagelet

A Pagelet contains a URL representing a page or a fragment of a page. By default, it caches the content of the pagelet softly. Therefore, each invocation of openStream() may or may not cause an actual access to the pagelet URL, depending on the memory status and whether caching is enabled.

Author:Hugo Y. K. Lam

See also: PageletStore

Constructors

Pagelet
public Pagelet(String id, URL pagelet)

Creates a new instance of Pagelet.

Parameters:
  • id – the pagelet ID.
  • pagelet – the pagelet URL.

Methods

getId
public String getId()

Gets the pagelet ID.

Returns:the pagelet ID.
getURL
public URL getURL()

Gets the URL of the pagelet.

Returns:the URL of the pagelet.
isCacheEnabled
public boolean isCacheEnabled()

Checks if caching is enabled.

Returns:true if caching is enabled.
openStream
public InputStream openStream()

Opens an input stream for reading the content of the pagelet.

Throws:
  • IOException – if unable to create a new input stream.
Returns:

the input stream of the pagelet.

setCacheEnabled
public void setCacheEnabled(boolean isCacheEnabled)

Sets whether caching should be enabled.

Parameters:
  • isCacheEnabled – true if caching should be enabled.
toString
public String toString()

Returns a string representation of this pagelet.

Returns:a string representation of this pagelet.

See also: java.lang.Object.toString()

PageletStore

public class PageletStore

A PageletStore is a holder which stores a set of pagelets for a certain context.

Author:Hugo Y. K. Lam

See also: Pagelet

Constructors

PageletStore
public PageletStore()

Creates a new instance of PageletStore.

Methods

addPagelet
public Pagelet addPagelet(Pagelet pagelet)

Adds a pagelet to this store.

Parameters:
  • pagelet – the pagelet to be added.
Returns:

the previous pagelet, if any, which has the same ID with the given pagelet.

getPagelet
public Pagelet getPagelet(String id)

Retrieves a pagelet from this store.

Parameters:
  • id – the pagelet ID.
Returns:

the corresponding pagelet, if any.

removePagelet
public Pagelet removePagelet(String id)

Removes a pagelet from this store.

Parameters:
  • id – the pagelet ID.
Returns:

the removed pagelet, if any.

Template

public class Template

A Template is a parser which tokenizes a given template into a list of template elements. There are two types of template elements:

  1. Text
  2. Template Tag

Hence, a template is composed of a mixture of text and template tags. A template tag is recognized by the following pattern in the content: <!--[\\s]*template-((.*?))[\\s]*-->

Author:Hugo Y. K. Lam

See also: TemplateElement

Constructors

Template
public Template(String s)

Creates a new instance of Template.

Parameters:
  • s – the template.

Methods

hasMoreElements
public boolean hasMoreElements()

Checks if there are anymore elements in this template. This method will always return false if this template is not yet parsed. More, each invocation of nextElement() may also affect the result of this method.

Returns:true if there are more elements in this template.

See also: .nextElement()

nextElement
public TemplateElement nextElement()

Gets the next template element. This method will always return null if this template is not yet parsed.

Returns:the next template element.
parse
public void parse()

Parses the template content and initializes this template.

toString
public String toString()

Returns a string representation of this template. This method simply returns the original template content.

Returns:a string representation of this template.

See also: java.lang.Object.toString()

TemplateElement

public class TemplateElement

A TemplateElement represents a composing element of a template. There are two types of template elements:

  1. Text
  2. Template Tag
Author:Hugo Y. K. Lam

See also: Template

Constructors

TemplateElement
public TemplateElement(String name)

Creates a new instance of TemplateElement which represents a template tag element.

Parameters:
  • name – the element name.
TemplateElement
public TemplateElement(String s, boolean isText)

Creates a new instance of TemplateElement.

Parameters:
  • s – the element name or text if it is a text element.
  • isText – true if this element is a text element.

Methods

getName
public String getName()

Gets the element name.

Returns:the element name or null if it is a text element.
getText
public String getText()

Gets the text of this element.

Returns:the text of this element or null if it is a template tag element.
isText
public boolean isText()

Checks if this element is a text element.

Returns:true if this element is a text element.
toString
public String toString()

Returns a string representation of this element.

Returns:the text of this element if it is a text element or the element name otherwise.

See also: java.lang.Object.toString()

hk.hku.cecid.piazza.commons.pagelet.xslt

BorderLayoutPageletAdaptor

public abstract class BorderLayoutPageletAdaptor extends HttpXsltPageletAdaptor

BorderLayoutPageletAdaptor is an HTTP-XSLT pagelet adaptor which supports a border layout of pagelets.

A border layout can be divided into five regions:

  1. north
  2. east
  3. west
  4. south
  5. center

Each region maps to a pagelet which has an ID same as the region’s name.

Author:Hugo Y. K. Lam

Methods

getCenterSource
protected Source getCenterSource(HttpServletRequest request)

Gets the transformation source for the center region.

Parameters:
  • request – the servlet request.
Returns:

the transformation source or null by default.

getEastSource
protected Source getEastSource(HttpServletRequest request)

Gets the transformation source for the east region.

Parameters:
  • request – the servlet request.
Returns:

the transformation source or null by default.

getNorthSource
protected Source getNorthSource(HttpServletRequest request)

Gets the transformation source for the north region.

Parameters:
  • request – the servlet request.
Returns:

the transformation source or null by default.

getPageletSource
protected Source getPageletSource(TemplateElement element, Pagelet pagelet, HttpServletRequest request)

Determines the border layout region that the given template element refers to and invokes the corresponding method for retrieving the transformation source.

See also: .getNorthSource(HttpServletRequest), .getEastSource(HttpServletRequest), .getWestSource(HttpServletRequest), .getSouthSource(HttpServletRequest), hk.hku.cecid.piazza.commons.pagelet.xslt.HttpXsltPageletAdaptor.getPageletSource(hk.hku.cecid.piazza.commons.pagelet.TemplateElement,hk.hku.cecid.piazza.commons.pagelet.Pagelet,javax.servlet.http.HttpServletRequest)

getSouthSource
protected Source getSouthSource(HttpServletRequest request)

Gets the transformation source for the south region.

Parameters:
  • request – the servlet request.
Returns:

the transformation source or null by default.

getWestSource
protected Source getWestSource(HttpServletRequest request)

Gets the transformation source for the west region.

Parameters:
  • request – the servlet request.
Returns:

the transformation source or null by default.

HttpXsltPageletAdaptor

public abstract class HttpXsltPageletAdaptor extends HttpPageletAdaptor

HttpXsltPageletAdaptor is an HTTP pagelet adaptor which employs the XSLT technology for content rendering. It is basically same as the HTTP pagelet adpator except that all the involved pagelets, excluding the template, are XSL documents.

This pagelet adaptor supports an additional generation mode, “xml”, which suppresses the XSL transformation. If the generation mode is “xml”, no rendering will be done and the output will only be a trunk of consecutive XML sources.

Author:Hugo Y. K. Lam

Methods

getErrorSource
protected Source getErrorSource(TemplateElement element, Throwable error, HttpServletRequest request)

Gets the transformation source for the XSL error pagelet.

Parameters:
  • element – the template element which represents the pagelet.
  • error – the error generated by the XSL pagelet process.
  • request – the servlet request.
Throws:
Returns:

the transformation source of the XSL error pagelet or null by default.

See also: .processError(TemplateElement,Throwable,HttpServletRequest,HttpServletResponse)

getPageletSource
protected Source getPageletSource(TemplateElement element, Pagelet pagelet, HttpServletRequest request)

Gets the transformation source for the given XSL pagelet.

Parameters:
  • element – the template element which represents the pagelet.
  • pagelet – the XSL pagelet.
  • request – the servlet request.
Throws:
Returns:

the transformation source of the given XSL pagelet or null by default.

See also: .processPagelet(TemplateElement,Pagelet,HttpServletRequest,HttpServletResponse)

processError
protected void processError(TemplateElement element, Throwable exception, HttpServletRequest request, HttpServletResponse response)

Processes the error generated by the XSL pagelet. The transformation source for the XSL error pagelet will be retrieved by invoking the getErrorSource() method.

Throws:

See also: .transform(Pagelet,Source,HttpServletRequest,HttpServletResponse), .getErrorSource(TemplateElement,Throwable,HttpServletRequest), hk.hku.cecid.piazza.commons.pagelet.HttpPageletAdaptor.processError(hk.hku.cecid.piazza.commons.pagelet.TemplateElement,java.lang.Throwable,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)

processPagelet
protected void processPagelet(TemplateElement element, Pagelet pagelet, HttpServletRequest request, HttpServletResponse response)

Processes the XSL pagelet. The transformation source for the given XSL pagelet will be retrieved by invoking the getPageletSource() method.

Parameters:
  • pagelet – the XSL pagelet.
Throws:

See also: .transform(Pagelet,Source,HttpServletRequest,HttpServletResponse), .getPageletSource(TemplateElement,Pagelet,HttpServletRequest), hk.hku.cecid.piazza.commons.pagelet.HttpPageletAdaptor.processPagelet(hk.hku.cecid.piazza.commons.pagelet.TemplateElement,hk.hku.cecid.piazza.commons.pagelet.Pagelet,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)

processText
protected void processText(TemplateElement element, String text, HttpServletRequest request, HttpServletResponse response)

Processes the text part of the generating page if the generation mode is not “xml”.

See also: hk.hku.cecid.piazza.commons.pagelet.HttpPageletAdaptor.processText(hk.hku.cecid.piazza.commons.pagelet.TemplateElement,java.lang.String,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)

transform
protected void transform(Pagelet xsl, Source source, HttpServletRequest request, HttpServletResponse response)

Transforms a given XML source using the specified XSL and writes the output to the response output stream.

Parameters:
  • xsl – the XSL for the transformation.
  • source – the XML source.
  • request – the servlet request.
  • response – the servlet response.
Throws:
  • IOException – if an I/O exception occurs during openning the XSL stream.
  • TransformerException – if an unrecoverable error occurs during the course of the transformation.

hk.hku.cecid.piazza.commons.rest

RestRequest

public class RestRequest

The RestRequest class represents a Restful service request. It is independent of which access protocol it is using and contains the bodies of the request message.

Author:Patrick Yee

Constructors

RestRequest
public RestRequest()

Creates a new instance of RestRequest.

RestRequest
public RestRequest(Object source)

Creates a new instance of RestRequest.

Parameters:
  • source – the source which initiated this request.

Methods

getSource
public Object getSource()

Gets the source which initiated this request.

Returns:the source which initiated this request.
setSource
public void setSource(Object source)

Sets the source which initiated this request.

Parameters:
  • source – the source which initiated this request.

hk.hku.cecid.piazza.commons.security

KeyStoreComponent

abstract class KeyStoreComponent extends Component

KeyStoreComponent is a module component which embeds a key store.

Author:Hugo Y. K. Lam

Fields

alias
String alias

The alias name.

keyPass
char[] keyPass

The key password

keyStore
KeyStore keyStore

The embeded key store.

location
String location

The key store location.

provider
Object provider

The key store provider.

storePass
char[] storePass

The key store password

storeType
String storeType

The key store type.

Constructors

KeyStoreComponent
public KeyStoreComponent()

Creates a new instance of KeyStoreComponent.

Methods

init
protected void init()

Initializes this key store component.

Component parameters:

  • keystore-location: the key store location
  • keystore-password: the key store password
  • key-alias: the alias name
  • key-password: the key password
  • keystore-type: the key store type.
  • keystore-provider: the key store provider
Throws:

See also: .init(String,String,String,String,String,Object), hk.hku.cecid.piazza.commons.module.Component.init()

init
protected void init(KeyStore keyStore, String alias, String keyPass)

Initializes this key store component.

Parameters:
  • keyStore
  • alias – the alias name.
  • keyPass – the key password.
Throws:
init
protected void init(String location, String storePass, String alias, String keyPass, String storeType, Object provider)

Initializes this key store component.

Parameters:
  • location – the key store location.
  • storePass – the key store password.
  • alias – the alias name.
  • keyPass – the key password.
  • storeType – the key store type.
  • provider – the key store provider.
Throws:

KeyStoreKeyManager

public class KeyStoreKeyManager extends KeyStoreComponent implements X509KeyManager

KeyStoreKeyManager implements javax.net.ssl.X509KeyManager, which manages a given key store of X509 certificate-based key pairs and authenticates the local side of a secure socket.

Author:Hugo Y. K. Lam

Constructors

KeyStoreKeyManager
public KeyStoreKeyManager()

Creates a new instance of KeyStoreKeyManager.

KeyStoreKeyManager
public KeyStoreKeyManager(KeyStoreManager keyman)

Creates a new instance of KeyStoreKeyManager.

Parameters:
  • keyman – the key store manager used for authentication.
Throws:
  • KeyStoreManagementException – if the specified key store manager is null.
KeyStoreKeyManager
public KeyStoreKeyManager(KeyStore keyStore, String alias, String password)

Creates a new instance of KeyStoreKeyManager.

Parameters:
  • keyStore – the initialized key store used for authentication.
  • alias – the alias name associated with the key.
  • password – the key password.
Throws:
  • KeyStoreManagementException – if the specified key store is null.

Methods

chooseClientAlias
public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket)

Chooses an alias to authenticate the client side of a secure socket. This method always returns the predefined alias.

Parameters:
  • keyType – the key algorithm type name(s), ordered with the most-preferred key type first.
  • issuers – the list of acceptable CA issuer subject names or null if it does not matter which issuers are used.
  • socket – the socket to be used for this connection or null.
Returns:

the alias name.

See also: javax.net.ssl.X509KeyManager.chooseClientAlias(java.lang.String[],java.security.Principal[],java.net.Socket)

chooseServerAlias
public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket)

Chooses an alias to authenticate the server side of a secure socket. This method always returns the predefined alias.

Parameters:
  • keyType – the key algorithm type name.
  • issuers – the list of acceptable CA issuer subject names or null if it does not matter which issuers are used.
  • socket – the socket to be used for this connection or null.
Returns:

the alias name.

See also: javax.net.ssl.X509KeyManager.chooseServerAlias(java.lang.String,java.security.Principal[],java.net.Socket)

getCertificateChain
public X509Certificate[] getCertificateChain(String alias)

Gets the certificate chain associated with the given alias.

Parameters:
  • alias – the alias name.
Returns:

the certificate chain.

See also: javax.net.ssl.X509KeyManager.getCertificateChain(java.lang.String)

getClientAliases
public String[] getClientAliases(String keyType, Principal[] issuers)

Gets the aliases for authenticating the client side of a secure socket. This method always returns the predefined alias.

Parameters:
  • keyType – the key algorithm type name.
  • issuers – the list of acceptable CA issuer subject names or null if it does not matter which issuers are used.
Returns:

the aliases for authenticating the client side of a secure socket.

See also: javax.net.ssl.X509KeyManager.getClientAliases(java.lang.String,java.security.Principal[])

getPrivateKey
public PrivateKey getPrivateKey(String alias)

Gets the key associated with the given alias.

Parameters:
  • alias – the alias name.
Throws:
Returns:

the private key.

See also: javax.net.ssl.X509KeyManager.getPrivateKey(java.lang.String)

getServerAliases
public String[] getServerAliases(String keyType, Principal[] issuers)

Gets the aliases for authenticating the server side of a secure socket. This method always returns the predefined alias.

Parameters:
  • keyType – the key algorithm type name.
  • issuers – the list of acceptable CA issuer subject names or null if it does not matter which issuers are used.
Returns:

the aliases for authenticating the server side of a secure socket.

See also: javax.net.ssl.X509KeyManager.getServerAliases(java.lang.String,java.security.Principal[])

KeyStoreManagementException

public class KeyStoreManagementException extends hk.hku.cecid.piazza.commons.GenericException

KeyStoreManagementException represents all kinds of exception related to KeyStoreManager.

Author:Hugo Y. K. Lam

Constructors

KeyStoreManagementException
public KeyStoreManagementException()

Creates a new instance of KeyStoreManagementException.

KeyStoreManagementException
public KeyStoreManagementException(String message)

Creates a new instance of KeyStoreManagementException.

Parameters:
  • message – the error message.
KeyStoreManagementException
public KeyStoreManagementException(Throwable cause)

Creates a new instance of KeyStoreManagementException.

Parameters:
  • cause – the cause of this exception.
KeyStoreManagementException
public KeyStoreManagementException(String message, Throwable cause)

Creates a new instance of KeyStoreManagementException.

Parameters:
  • message – the error message.
  • cause – the cause of this exception.

KeyStoreManager

public class KeyStoreManager extends KeyStoreComponent

KeyStoreManager manages a key store and provides convenient methods such as method that retrieves an X509Certificate or retrieves a private key.

Author:Hugo Y. K. Lam

Constructors

KeyStoreManager
public KeyStoreManager()

Creates a new instance of KeyStoreManager.

KeyStoreManager
public KeyStoreManager(KeyStore keyStore)

Creates a new instance of KeyStoreManager.

Parameters:
  • keyStore – the initialized keystore to be managed.
Throws:
  • KeyStoreManagementException – if the specified key store is null.
KeyStoreManager
public KeyStoreManager(KeyStore keyStore, String alias, String keyPass)

Creates a new instance of KeyStoreManager.

Parameters:
  • keyStore – the initialized keystore to be managed.
  • alias – the alias name associating with the managed key.
  • keyPass – the key password.
Throws:
  • KeyStoreManagementException – if the specified key store is null.
KeyStoreManager
public KeyStoreManager(String location, String storePass)

Creates a new instance of KeyStoreManager.

Parameters:
  • location – the key store location.
  • storePass – the key store password.
Throws:
  • KeyStoreManagementException – if unable to initialize the key store with the given paramemeters.
KeyStoreManager
public KeyStoreManager(String location, String storePass, String alias, String keyPass)

Creates a new instance of KeyStoreManager.

Parameters:
  • location – the key store location.
  • storePass – the key store password.
  • alias – the alias name.
  • keyPass – the key password.
Throws:
  • KeyStoreManagementException – if unable to initialize the key store with the given paramemeters.
KeyStoreManager
public KeyStoreManager(String location, String storePass, String storeType, Object provider)

Creates a new instance of KeyStoreManager.

Parameters:
  • location – the key store location.
  • storePass – the key store password.
  • storeType – the key store type.
  • provider – the key store provider.
Throws:
  • KeyStoreManagementException – if unable to initialize the key store with the given paramemeters.
KeyStoreManager
public KeyStoreManager(String location, String storePass, String alias, String keyPass, String storeType, Object provider)

Creates a new instance of KeyStoreManager.

Parameters:
  • location – the key store location.
  • storePass – the key store password.
  • alias – the alias name.
  • keyPass – the key password.
  • storeType – the key store type.
  • provider – the key store provider.
Throws:
  • KeyStoreManagementException – if unable to initialize the key store with the given paramemeters.

Methods

getAlias
public String getAlias()

Gets the managed alias.

Returns:the managed alias.
getAliases
public String[] getAliases()

Gets all the aliases in the managed key store.

Returns:all the aliases in the managed key store.
getCertificate
public Certificate getCertificate()

Gets the managed certificate.

Returns:the managed certificate.
getCertificate
public Certificate getCertificate(String alias)

Gets the certificate asscoiated with the given alias name.

Parameters:
  • alias – the alias name.
Returns:

the certificate.

getCertificateChain
public Certificate[] getCertificateChain()

Gets the managed certificate chain.

Returns:the managed certificate chain.
getCertificateChain
public Certificate[] getCertificateChain(String alias)

Gets the certificate chain asscoiated with the given alias name.

Parameters:
  • alias – the alias name.
Returns:

the certificate chain.

getKeyStore
public KeyStore getKeyStore()

Gets the managed key store.

Returns:the key store.
getPrivateKey
public PrivateKey getPrivateKey()

Gets the managed private key.

Throws:
  • NoSuchAlgorithmException – if the algorithm for recovering the key cannot be found.
  • UnrecoverableKeyException – if the key cannot be recovered (e.g., the given password is wrong).
Returns:

the private key.

getPublicKey
public PublicKey getPublicKey()

Gets the managed public key.

Returns:the public key.
getX509Certificate
public X509Certificate getX509Certificate()

Gets the managed X509 certificate.

Throws:
Returns:

the managed X509 certificate.

getX509Certificate
public X509Certificate getX509Certificate(String alias)

Gets the managed X509 certificate.

Parameters:
  • alias – the alias name.
Throws:
Returns:

the managed X509 certificate.

getX509CertificateChain
public X509Certificate[] getX509CertificateChain()

Gets the managed X509 certificate chain.

Returns:the managed certificate chain.
getX509CertificateChain
public X509Certificate[] getX509CertificateChain(String alias)

Gets the X509 certificate chain asscoiated with the given alias name.

Parameters:
  • alias – the alias name.
Returns:

the certificate chain.

isCertificateTrusted
public boolean isCertificateTrusted()

Checks if the managed certificate is trusted.

Returns:true if the managed certificate is trusted.
isCertificateTrusted
public boolean isCertificateTrusted(String alias)

Checks if the certificate asscoiated with the given alias name is trusted.

Returns:true the certificate is trusted.

KeyStoreTrustManager

public class KeyStoreTrustManager extends KeyStoreComponent implements X509TrustManager

This class implements the javax.net.ssl.X509TrustManager, which trusts a Certificate Chain if any of the certificate in the certificate chain is stored in the KeyStore.

Author:Bob P. Y. Koon

Constructors

KeyStoreTrustManager
public KeyStoreTrustManager()

Creates a new instance of KeyStoreTrustManger.

KeyStoreTrustManager
public KeyStoreTrustManager(KeyStoreManager keyman)

Creates a new instance of KeyStoreTrustManger.

Parameters:
  • keyman – the trusted key store manager.
Throws:
  • KeyStoreManagementException – if the specified key store manager is null.
KeyStoreTrustManager
public KeyStoreTrustManager(KeyStore keyStore)

Creates a new instance of KeyStoreTrustManger.

Parameters:
  • keyStore – the initialized trusted key store.
Throws:
  • KeyStoreManagementException – if the specified key store is null.

Methods

checkClientTrusted
public void checkClientTrusted(X509Certificate[] chain, String authType)

Checks if the client is trusted. It trusts the certificate chain if the embeded key store contains one of the certificate in the chain.

Parameters:
  • chain – the peer certificate chain.
  • authType – the key exchange algorithm used.
Throws:
  • IllegalArgumentException – if null or zero-length chain is passed in for the chain parameter or if null or zero-length string is passed in for the authType parameter.
  • CertificateException – if the certificate chain is not trusted by this TrustManager.

See also: javax.net.ssl.X509TrustManager.checkClientTrusted(java.security.cert.X509Certificate[],java.lang.String)

checkServerTrusted
public void checkServerTrusted(X509Certificate[] chain, String authType)

Checks if the server is trusted. It trusts the certificate chain if the embeded key store contains one of the certificate in the chain.

Parameters:
  • chain – the peer certificate chain.
  • authType – the key exchange algorithm used.
Throws:
  • IllegalArgumentException – if null or zero-length chain is passed in for the chain parameter or if null or zero-length string is passed in for the authType parameter.
  • CertificateException – if the certificate chain is not trusted by this TrustManager.

See also: javax.net.ssl.X509TrustManager.checkServerTrusted(java.security.cert.X509Certificate[],java.lang.String)

getAcceptedIssuers
public X509Certificate[] getAcceptedIssuers()

Returns an array of certificate authority certificates which are stored in the embeded key store.

Returns:a non-null (possibly empty) array of acceptable CA issuer certificates.

SMimeException

public class SMimeException extends hk.hku.cecid.piazza.commons.GenericException

SMimeException represents all kinds of exception related to SMIME.

Author:Hugo Y. K. Lam

Constructors

SMimeException
public SMimeException()

Creates a new instance of SMimeException.

SMimeException
public SMimeException(String message)

Creates a new instance of SMimeException.

Parameters:
  • message – the error message.
SMimeException
public SMimeException(Throwable cause)

Creates a new instance of SMimeException.

Parameters:
  • cause – the cause of this exception.
SMimeException
public SMimeException(String message, Throwable cause)

Creates a new instance of SMimeException.

Parameters:
  • message – the error message.
  • cause – the cause of this exception.

SMimeMessage

public class SMimeMessage

SMimeMessage represents a Secure MIME Message. It encapsulates a MIME body part and provides methods for digital signing, signature verification, encryption, decryption, compression, and decompression.

Author:Hugo Y. K. Lam

Fields

CONTENT_TRANSFER_ENC_BASE64
public static final String CONTENT_TRANSFER_ENC_BASE64

Content transfer encoding: Base 64

CONTENT_TRANSFER_ENC_BINARY
public static final String CONTENT_TRANSFER_ENC_BINARY

Content transfer encoding: Binary

DIGEST_ALG_MD5
public static final String DIGEST_ALG_MD5

Digest algorithm: MD5

DIGEST_ALG_SHA1
public static final String DIGEST_ALG_SHA1

Digest algorithm: SHA

ENCRYPT_ALG_DES_EDE3_CBC
public static final String ENCRYPT_ALG_DES_EDE3_CBC

Encryption algorithm: DES EDE3

ENCRYPT_ALG_RC2_CBC
public static final String ENCRYPT_ALG_RC2_CBC

Encryption algorithm: RC2

Constructors

SMimeMessage
public SMimeMessage(MimeBodyPart bodyPart)

Creates a new instance of SMimeMessage.

Parameters:
  • bodyPart – the original MIME body part.
SMimeMessage
public SMimeMessage(MimeBodyPart bodyPart, X509Certificate cert)

Creates a new instance of SMimeMessage.

Parameters:
  • bodyPart – the original MIME body part.
  • cert – the certificate for signature verification or encryption.
SMimeMessage
public SMimeMessage(MimeBodyPart bodyPart, X509Certificate cert, Session session)

Creates a new instance of SMimeMessage.

Parameters:
  • bodyPart – the original MIME body part.
  • cert – the certificate for signature verification or encryption.
  • session – the mail session.
SMimeMessage
public SMimeMessage(MimeBodyPart bodyPart, X509Certificate cert, PrivateKey privateKey)

Creates a new instance of SMimeMessage.

Parameters:
  • bodyPart – the original MIME body part.
  • cert – the certificate for signature verification or encryption.
  • privateKey – the private key for digital signing or decryption.
SMimeMessage
public SMimeMessage(MimeBodyPart bodyPart, X509Certificate cert, PrivateKey privateKey, Session session)

Creates a new instance of SMimeMessage.

Parameters:
  • bodyPart – the original MIME body part.
  • cert – the certificate for signature verification or encryption.
  • privateKey – the private key for digital signing or decryption.
  • session – the mail session.
SMimeMessage
protected SMimeMessage(MimeBodyPart bodyPart, SMimeMessage smime)

Creates a new instance of SMimeMessage.

Parameters:
  • bodyPart – the original MIME body part.
  • smime – the S/MIME message from which the configuration is copied.

Methods

compress
public SMimeMessage compress()

Compresses the encapsulated MIME body part.

Throws:
Returns:

an S/MIME message encapsulating the compressed MIME body part.

decompress
public SMimeMessage decompress()

Decompresses the encapsulated MIME body part.

Throws:
Returns:

an S/MIME message encapsulating the decompressed MIME body part.

decrypt
public SMimeMessage decrypt()

Decrypts the encapsulated MIME body part.

Throws:
Returns:

an S/MIME message encapsulating the decrypted MIME body part.

decrypt
public SMimeMessage decrypt(PrivateKey privateKey)

Decrypts the encapsulated MIME body part.

Parameters:
  • privateKey – the private key for decryption.
Throws:
Returns:

an S/MIME message encapsulating the decrypted MIME body part.

digest
public String digest()

Digests the encapsulated MIME body part.

Throws:
Returns:

the digested value in Base 64 format.

digest
public String digest(String digestAlg, boolean isHeadersIncluded)

Digests the encapsulated MIME body part.

Parameters:
  • digestAlg – digest algorithm.
  • isHeadersIncluded – true if the digest should be computed on both the headers and the content of the encapsulated body part.
Throws:
Returns:

the digested value in Base 64 format.

encrypt
public SMimeMessage encrypt()

Encrypts the encapsulated MIME body part.

Throws:
Returns:

an S/MIME message encapsulating the encrypted MIME body part.

encrypt
public SMimeMessage encrypt(X509Certificate cert)

Encrypts the encapsulated MIME body part.

Parameters:
  • cert – the certificate for encryption.
Throws:
Returns:

an S/MIME message encapsulating the encrypted MIME body part.

getBodyPart
public MimeBodyPart getBodyPart()

Gets the encapsulated MIME body part.

Returns:the encapsulated MIME body part.
getContentTransferEncoding
public String getContentTransferEncoding()

Gets the content transfer encoding which will be used in encryption, digital signing, and compression.

Returns:the content transfer encoding.
getDigestAlgorithm
public String getDigestAlgorithm()

Gets the digest algorithm which will be used in digital signing.

Returns:the digest algorithm.
getEncryptAlgorithm
public String getEncryptAlgorithm()

Gets the encryption algorithm which will be used in encryption.

Returns:the encryption algorithm.
isCompressed
public boolean isCompressed()

Checks if the encapsulated MIME body part is compressed.

Throws:
Returns:

true if the encapsulated MIME body part is compressed.

isEncrypted
public boolean isEncrypted()

Checks if the encapsulated MIME body part is encrypted.

Throws:
Returns:

true if the encapsulated MIME body part is encrypted.

isSigned
public boolean isSigned()

Checks if the encapsulated MIME body part is signed.

Throws:
Returns:

true if the encapsulated MIME body part is signed.

setContentTransferEncoding
public void setContentTransferEncoding(String contentTransferEncoding)

Sets the content transfer encoding to used in encryption, digital signing, and compression.

Parameters:
  • contentTransferEncoding – the content transfer encoding.
setDigestAlgorithm
public void setDigestAlgorithm(String digestAlgorithm)

Sets the digest algorithm to used in digital signing.

Parameters:
  • digestAlgorithm – the digest algorithm.
setEncryptAlgorithm
public void setEncryptAlgorithm(String encryptAlgorithm)

Sets the encryption algorithm to be used in encryption.

Parameters:
  • encryptAlgorithm – the encryption algorithm.
sign
public SMimeMessage sign()

Signs the encapsulated MIME body part.

Throws:
Returns:

an S/MIME message encapsulating the signed MIME body part.

unsign
public SMimeMessage unsign()

Unsigns the encapsulated MIME body part.

Throws:
Returns:

the an S/MIME message encapsulating the signed content.

verify
public SMimeMessage verify()

Verifies the encapsulated MIME body part.

Throws:
Returns:

an S/MIME message encapsulating the signed content.

verify
public SMimeMessage verify(X509Certificate cert)

Verifies the encapsulated MIME body part.

Parameters:
  • cert – the certificate for verification.
Throws:
Returns:

an S/MIME message encapsulating the signed content.

TrustedHostnameVerifier

public class TrustedHostnameVerifier implements HostnameVerifier

TrustedHostnameVerifier is a HostnameVerifier which verifies the host name in an SSL session based on a list of pre-defined hostnames. If there is no such a list in this verifier, it defaults to trust any host name.

Author:Hugo Y. K. Lam

Constructors

TrustedHostnameVerifier
public TrustedHostnameVerifier()

Creates a new intance of TrustedHostnameVerifier. The verifier will be set to trust all hostnames on verification.

TrustedHostnameVerifier
public TrustedHostnameVerifier(Collection hostnames)

Creates a new intance of TrustedHostnameVerifier.

Parameters:
  • hostnames – the host names to be trusted on verification.

Methods

verify
public boolean verify(String hostname, SSLSession sslSession)

Verifies that the host name is an acceptable match with the trusted host names pre-defined in this verifier.

Parameters:
  • hostname – the host name.
  • sslSession – the SSL session used on the connection to the host.
Returns:

true if the host name is acceptable.

See also: javax.net.ssl.HostnameVerifier.verify(java.lang.String, javax.net.ssl.SSLSession)

hk.hku.cecid.piazza.commons.servlet

RequestListener

public interface RequestListener

RequestListener is a listener for handling servlet requests.

Author:Hugo Y. K. Lam

Methods

getParameters
public Properties getParameters()

Gets the parameters of this listener.

Returns:the parameters of this listener.
listenerCreated
public void listenerCreated()

Invoked after the listener has been created and before it can handle any request.

Throws:
listenerDestroyed
public void listenerDestroyed()

Invoked after the listener has been taken out from service and before disposal.

Throws:

RequestListenerException

public class RequestListenerException extends hk.hku.cecid.piazza.commons.GenericException

RequestListenerException represents all kinds of exception related to RequestListener.

Author:Hugo Y. K. Lam

Constructors

RequestListenerException
public RequestListenerException()

Creates a new instance of RequestListenerException.

RequestListenerException
public RequestListenerException(String message)

Creates a new instance of RequestListenerException.

Parameters:
  • message – the error message.
RequestListenerException
public RequestListenerException(Throwable cause)

Creates a new instance of RequestListenerException.

Parameters:
  • cause – the cause of this exception.
RequestListenerException
public RequestListenerException(String message, Throwable cause)

Creates a new instance of RequestListenerException.

Parameters:
  • message – the error message.
  • cause – the cause of this exception.

StatefulServletContext

public class StatefulServletContext

A StatefulServletContext represents a context of a stateful servlet. A stateful servlet has two states, a halted state and a running state.

Author:Hugo Y. K. Lam

See also: StatefulServletContextListener

Constructors

StatefulServletContext
public StatefulServletContext()

Creates a new instance of StatefulServletContext.

Methods

acquire
public synchronized void acquire()

Acquires a permission from this context. Any servlet which employs this stateful context must call this method before processing any requests.

Throws:
  • UnavailableException – if the context is currently halted.
addContextListener
public boolean addContextListener(Object contextListener)

Adds a context listener for receiving events from this context.

Parameters:
  • contextListener – the stateful servlet context listener.
Returns:

true if the operation is successful, false otherwise.

getContextListeners
public Collection getContextListeners()

Gets all the stateful servlet context listeners in this context.

Returns:all the stateful servlet context listeners in this context.
getCurrentThreadCount
public int getCurrentThreadCount()

Gets the current count of threads running under this context.

Returns:the current count of threads running under this context.
getRequestEncoding
public String getRequestEncoding()

Gets the request encoding that the servlet should use.

Returns:the request encoding.
getResponseEncoding
public String getResponseEncoding()

Gets the response encoding that the servlet should use.

Returns:the response encoding.
halt
public synchronized boolean halt()

Halts this context. The calling thread will be blocked until a lock on the context has been acquired and no more threads are running under this context. Nothing will be done if the servlet is already halted.

Returns:true if and only if this context is not halted or being halted.
isHalted
public boolean isHalted()

Checks if the context is currently halted.

Returns:true if the servlet is currently halted.
isHalting
public boolean isHalting()

Checks if the context is currently being halted.

Returns:true if the servlet is currently being halted.
release
public synchronized void release()

Releases a permission to this context. Any servlet which employs this stateful context must call this method after processing any requests.

resume
public synchronized boolean resume()

Resumes this context. The calling thread will be blocked until a lock on the context has been acquired. Nothing will be done if the servlet is not halted.

Returns:true if and only if this context is halted and not being halted.
setRequestEncoding
public void setRequestEncoding(String requestEncoding)

Sets the request encoding that the servlet should use.

Parameters:
  • requestEncoding – the request encoding.
setResponseEncoding
public void setResponseEncoding(String responseEncoding)

Sets the response encoding that the servlet should use.

Parameters:
  • responseEncoding – the response encoding.

StatefulServletContextListener

public interface StatefulServletContextListener

StatefulServletContextListener is a listener for listening the events from a stateful servlet context.

Author:Hugo Y. K. Lam

See also: StatefulServletContext

Methods

servletContextHalted
public void servletContextHalted()

Invoked when the context it is listening has been halted.

servletContextResumed
public void servletContextResumed()

Invoked when the context it is listening has been resumed.

hk.hku.cecid.piazza.commons.servlet.http

HttpDispatcher

public class HttpDispatcher extends HttpServlet

HttpDispatcher is an HttpServlet which dispatches Http request to the Http request listeners registered in its Http dispatcher context.

Author:Hugo Y. K. Lam

See also: HttpDispatcherContext

Fields

CONFIG_KEY
public static final String CONFIG_KEY

The request attribute key of the servlet config.

Methods

destroy
public void destroy()

Destroys the servlet.

doDelete
protected void doDelete(HttpServletRequest request, HttpServletResponse response)

Handles the HTTP POST method.

Parameters:
  • request – the servlet request.
  • response – the servlet response.
doGet
protected void doGet(HttpServletRequest request, HttpServletResponse response)

Handles the HTTP GET method.

Parameters:
  • request – the servlet request.
  • response – the servlet response.
doPost
protected void doPost(HttpServletRequest request, HttpServletResponse response)

Handles the HTTP POST method.

Parameters:
  • request – the servlet request.
  • response – the servlet response.
fireRequestAcceptedEvent
protected boolean fireRequestAcceptedEvent(HttpRequestEvent event)

Invoked before a request is processed by the listener registered at the request context path which is relative to this servlet’s context path.

Parameters:
  • event – the HTTP request event.
Returns:

true if the request should be accepted and processed by the registered listener.

fireRequestProcessedEvent
protected void fireRequestProcessedEvent(HttpRequestEvent event)

Invoked when a request has been processed by the listener registered at the request context path which is relative to this servlet’s context path.

Parameters:
  • event – the HTTP request event.
getServletInfo
public String getServletInfo()

Gets a short description of this servlet.

Returns:a short description of this servlet.
init
public void init(ServletConfig config)

Initializes the servlet.

Parameters:
  • config – the ServletConfig.
Throws:
  • ServletException – if error occurred in initialization.
processRequest
protected void processRequest(HttpServletRequest request, HttpServletResponse response)

Processes requests for both HTTP GET and POST methods.

Parameters:
  • request – servlet request.
  • response – servlet response.

HttpDispatcherContext

public class HttpDispatcherContext extends StatefulServletContext

An HttpDispatcherContext is a StatefulServletContext. Additionally it manages the Http request listeners for the HttpDispatcher.

Author:Hugo Y. K. Lam

See also: HttpDispatcher, HttpRequestListener

Constructors

HttpDispatcherContext
public HttpDispatcherContext()

Creates a new instance of HttpDispatcherContext.

Methods

addContext
public static void addContext(String id, HttpDispatcherContext context)

Adds an Http dispatcher context to the embeded context store.

Parameters:
  • id – the ID of the Http dispatcher context.
  • context – the Http dispatcher context.
addRequestFilter
public boolean addRequestFilter(Object requestFilter)

Adds a request filter for receiving request events.

Parameters:
  • requestFilter – the request filter.
Returns:

true if the operation is successful, false otherwise.

getContext
public static HttpDispatcherContext getContext(String id)

Gets an Http dispatcher context from the embeded context store.

Parameters:
  • id – the ID of the Http dispatcher context.
Returns:

the Http dispatcher context.

getDefaultContext
public static HttpDispatcherContext getDefaultContext()

Gets the default Http dispatcher context.

Returns:the default Http dispatcher context.
getListener
public HttpRequestListener getListener(String pathInfo)

Gets the Http request listener for the specified path which is relative to its corresponding servlet’s context path. If there is an exact match on the specified path, the registered listener will be returned. Else if there is a wildcard path which matches the specified path, its corresponding registered listener will be returned. Otherwise, null will be returned.

Parameters:
  • pathInfo – the path information.
Returns:

the HttpRequestListener registered at the specified path.

getPathInfo
public String getPathInfo(HttpServletRequest request)

Gets the path information from the specified request. The path information will be fixed according to the internal logic of this context if necessary.

Parameters:
  • request – the Http servlet request.
Returns:

the path information.

getRegisteredListenersInfo
public Properties getRegisteredListenersInfo()

Gets the information of all registered Http request listeners. The resulted properties will contain a set of pathInfo-listenerName pairs.

Returns:the information as properties.
getRequestFilters
public Collection getRequestFilters()

Gets all the request filters in this context.

Returns:all the request filters in this context.
register
public boolean register(String pathInfo, Object requestListener)

Registers an Http request listener at a specified path which is relative to its corresponding servlet’s context path.

Parameters:
  • pathInfo – the path information.
  • requestListener – the Http request listener, the class name of the listener, or the class of the listener.
Returns:

true if the operation is successful, false otherwise.

register
public boolean register(String pathInfo, Object requestListener, Properties params)

Registers an Http request listener at a specified path which is relative to its corresponding servlet’s context path.

Parameters:
  • pathInfo – the path information.
  • requestListener – the Http request listener, the class name of the listener, or the class of the listener.
  • params – the parameters of the listener.
Returns:

true if the operation is successful, false otherwise.

unregister
public boolean unregister(String pathInfo)

Unregisters an Http request listener at a specified path which is relative to its corresponding servlet’s context path.

Parameters:
  • pathInfo – the path information.
Returns:

true if the operation is successful, false otherwise.

unregisterAll
public void unregisterAll()

Unregisters all Http request listeners in this context.

HttpRequestAdaptor

public abstract class HttpRequestAdaptor implements HttpRequestListener

HttpRequestAdaptor is an abstract adapter class for handling HTTP requests. The methods in this class are empty. This class exists as convenience for creating listener objects.

Author:Hugo Y. K. Lam

Fields

parameters
protected final Properties parameters

The parameters of this listener.

Methods

doEndRequest
public void doEndRequest(HttpServletRequest request, HttpServletResponse response)

See also: hk.hku.cecid.piazza.commons.servlet.http.HttpRequestListener.doEndRequest(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)

doStartRequest
public boolean doStartRequest(HttpServletRequest request, HttpServletResponse response)

See also: hk.hku.cecid.piazza.commons.servlet.http.HttpRequestListener.doStartRequest(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)

listenerCreated
public void listenerCreated()

See also: hk.hku.cecid.piazza.commons.servlet.RequestListener.listenerCreated()

listenerDestroyed
public void listenerDestroyed()

See also: hk.hku.cecid.piazza.commons.servlet.RequestListener.listenerDestroyed()

HttpRequestEvent

public class HttpRequestEvent

HttpRequestEvent represents an event of an HTTP request.

Author:Hugo Y. K. Lam

Constructors

HttpRequestEvent
HttpRequestEvent()

Creates a new instance of HttpRequestEvent.

HttpRequestEvent
HttpRequestEvent(String pathInfo, HttpServletRequest request, HttpServletResponse response)

Creates a new instance of HttpRequestEvent.

Parameters:
  • pathInfo – the path information.
  • request – the request object.
  • response – the response object.

Methods

getPathInfo
public String getPathInfo()

Gets the path information.

Returns:the path information.
getRequest
public HttpServletRequest getRequest()

Gets the request object.

Returns:the request object.
getResponse
public HttpServletResponse getResponse()

Gets the response object.

Returns:the response object.
setPathInfo
void setPathInfo(String pathInfo)

Sets the path information.

Parameters:
  • pathInfo – the path information.
setRequest
void setRequest(HttpServletRequest request)

Sets the request object.

Parameters:
  • request – the request object.
setResponse
void setResponse(HttpServletResponse response)

Sets the response object.

Parameters:
  • response – the response object.
toString
public String toString()

Returns a string representation of this event.

Returns:a string representation of this event.

See also: java.lang.Object.toString()

HttpRequestFilter

public interface HttpRequestFilter

HttpRequestFilter

Author:Hugo Y. K. Lam

Methods

requestAccepted
public boolean requestAccepted(HttpRequestEvent event)

Invoked when the an HTTP request is accepted.

Parameters:
  • event – the HTTP request event.
requestProcessed
public void requestProcessed(HttpRequestEvent event)

Invoked when the an HTTP request has been processed.

Parameters:
  • event – the HTTP request event.

HttpRequestListener

public interface HttpRequestListener extends RequestListener

HttpRequestListener is a listener for handling requests for both HTTP GET and POST methods.

Author:Hugo Y. K. Lam

Methods

doEndRequest
public void doEndRequest(HttpServletRequest request, HttpServletResponse response)

Invoked after invoking processRequest().

Parameters:
  • request – the servlet request.
  • response – the servlet response.
Throws:
doStartRequest
public boolean doStartRequest(HttpServletRequest request, HttpServletResponse response)

Invoked before invoking processRequest().

Parameters:
  • request – the servlet request.
  • response – the servlet response.
Throws:
Returns:

true if processRequest() should be invoked.

processRequest
public String processRequest(HttpServletRequest request, HttpServletResponse response)

Processes requests for both HTTP GET and POST methods.

Parameters:
  • request – the servlet request.
  • response – the servlet response.
Throws:
Returns:

the forwarding path.

hk.hku.cecid.piazza.commons.soap

SOAPFaultException

public class SOAPFaultException extends SOAPRequestException

SOAPFaultException represents a SOAP fault in a SOAP request.

Author:Hugo Y. K. Lam

Fields

SOAP_FAULT_CLIENT
public static String SOAP_FAULT_CLIENT
SOAP_FAULT_MUST_UNDERSTAND
public static String SOAP_FAULT_MUST_UNDERSTAND
SOAP_FAULT_SERVER
public static String SOAP_FAULT_SERVER
SOAP_FAULT_VERSION_MISMATCH
public static String SOAP_FAULT_VERSION_MISMATCH

Constructors

SOAPFaultException
public SOAPFaultException(String code, String message)

Creates a new instance of SOAPFaultException.

Parameters:
  • code – the fault code.
  • message – the fault string.
SOAPFaultException
public SOAPFaultException(String code, String message, String actor)

Creates a new instance of SOAPFaultException.

Parameters:
  • code – the fault code.
  • message – the fault string.
  • actor – the fault actor.
SOAPFaultException
public SOAPFaultException(String code, String message, Throwable cause)

Creates a new instance of SOAPFaultException.

Parameters:
  • code – the fault code.
  • message – the fault string.
  • cause – the cause of this exception.
SOAPFaultException
public SOAPFaultException(String code, String message, String actor, Throwable cause)

Creates a new instance of SOAPFaultException.

Parameters:
  • code – the fault code.
  • message – the fault string.
  • actor – the fault actor.
  • cause – the cause of this exception.

Methods

addDetailEntry
public void addDetailEntry(Name name, Object message)

Adds a SOAP fault detail entry.

Parameters:
  • name – the entry name.
  • message – the message of the detail entry.
getDetailEntryNames
public Iterator getDetailEntryNames()

Gets the SOAP fault detail entry names.

Returns:the SOAP fault detail entry Name objects.
getDetailEntryValue
public Object getDetailEntryValue(Name name)

Gets the SOAP fault detail entry value with the specified name.

Returns:the SOAP fault detail entry value.
getFaultActor
public String getFaultActor()

Gets the fault actor.

Returns:the fault actor.
getFaultCode
public String getFaultCode()

Gets the fault code.

Returns:the fault code.
getFaultString
public String getFaultString()

Gets the fault string.

Returns:the fault string.
hasDetailEntries
public boolean hasDetailEntries()

Checks if there are any SOAP fault detail entries.

Returns:true if there are any SOAP fault detail entries.
init
protected void init(String code, String message, String actor)

Initializes this SOAP fault exception.

Parameters:
  • code – the fault code.
  • message – the fault string.
  • actor – the fault actor.

SOAPHttpAdaptor

public abstract class SOAPHttpAdaptor extends HttpRequestAdaptor implements SOAPRequestListener

SOAPHttpAdaptor is both an HttpRequestListener and SOAPRequestListener. It is an adaptor for handling SOAP on Http requests.

Author:Hugo Y. K. Lam

Fields

msgFactory
protected MessageFactory msgFactory

A SOAP message factory.

soapFactory
protected SOAPFactory soapFactory

A SOAP factory.

Methods

isCacheEnabled
protected boolean isCacheEnabled()

Checks if cache in memory should be enabled. If this method returns false, it indicates that the SOAP request object will not provide a byte array cache of the original SOAP request.

Returns:true if cache in memory should be enabled.
isSOAPFaultEnabled
protected boolean isSOAPFaultEnabled()

Checks if errors in the request process should be reported as a SOAP fault to the client.

Returns:true if SOAP fault reporting is enabled.
listenerCreated
public void listenerCreated()

Creates a new instance of MessageFactory.

Throws:

See also: hk.hku.cecid.piazza.commons.servlet.RequestListener.listenerCreated()

listenerDestroyed
public void listenerDestroyed()

Cleans up resources.

See also: hk.hku.cecid.piazza.commons.servlet.RequestListener.listenerDestroyed()

processRequest
public String processRequest(HttpServletRequest request, HttpServletResponse response)

Processes the HTTP request and transforms it into a SOAP request.

See also: hk.hku.cecid.piazza.commons.servlet.http.HttpRequestListener.processRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)

SOAPHttpConnector

public class SOAPHttpConnector extends HttpConnector

SOAPHttpConnector is an HTTP connector for making HTTP SOAP connections to an endpoint.

Author:Hugo Y. K. Lam

Constructors

SOAPHttpConnector
public SOAPHttpConnector(Object endpoint)

Creates a new instance of SOAPHttpConnector.

Parameters:
  • endpoint – the end point, either in String or URL format.
Throws:
  • MalformedURLException – if the end point is malformed.

Methods

send
public SOAPMessage send(SOAPMessage request)

Sends an HTTP SOAP request.

Parameters:
  • request – the SOAP request message.
Throws:
  • ConnectionException – if failed in sending the HTTP SOAP request or creating a new connection.
Returns:

the SOAP reply message responsed from the host.

send
public SOAPMessage send(SOAPMessage request, HttpURLConnection connection)

Sends an HTTP SOAP request using the given HTTP connection.

Parameters:
  • request – the SOAP request message.
  • connection – the HTTP connection for sending the request.
Throws:
Returns:

the SOAP reply message responsed from the host.

SOAPMailSender

public class SOAPMailSender extends MailSender

SOAPMailSender is a mail sender responsible for sending SOAP message.

Author:Hugo Y. K. Lam

Constructors

SOAPMailSender
public SOAPMailSender(String host)

Creates a new instance of SOAPMailSender.

Parameters:
  • host – the mail host.
SOAPMailSender
public SOAPMailSender(String protocol, String host)

Creates a new instance of SOAPMailSender.

Parameters:
  • protocol – the mail protocol.
  • host – the mail host.
SOAPMailSender
public SOAPMailSender(String host, String username, String password)

Creates a new instance of SOAPMailSender.

Parameters:
  • host – the mail host.
  • username – the user name for authentication.
  • password – the password for authentication.
SOAPMailSender
public SOAPMailSender(String protocol, String host, String username, String password)

Creates a new instance of SOAPMailSender.

Parameters:
  • protocol – the mail protocol.
  • host – the mail host.
  • username – the user name for authentication.
  • password – the password for authentication.

Methods

createMessage
public MimeMessage createMessage(String from, String to, String cc, String subject, SOAPMessage soapMessage)

Creates a MIME message from a SOAP message.

Parameters:
  • from – the ‘from’ mail address.
  • to – the ‘to’ mail address(es).
  • cc – the ‘cc’ mail address(es).
  • subject – the mail subject.
  • soapMessage – the SOAP message.
Throws:
Returns:

a new MIME message.

See also: hk.hku.cecid.piazza.commons.net.MailSender.createMessage(java.lang.String,java.lang.String,java.lang.String,java.lang.String,javax.mail.Session)

createMessage
public MimeMessage createMessage(String from, String to, String cc, String subject, SOAPMessage soapMessage, Session session)

Creates a MIME message from a SOAP message.

Parameters:
  • from – the ‘from’ mail address.
  • to – the ‘to’ mail address(es).
  • cc – the ‘cc’ mail address(es).
  • subject – the mail subject.
  • soapMessage – the SOAP message.
  • session – the mail session.
Throws:
Returns:

a new MIME message.

See also: hk.hku.cecid.piazza.commons.net.MailSender.createMessage(java.lang.String,java.lang.String,java.lang.String,java.lang.String,javax.mail.Session)

send
public void send(String from, String to, String cc, String subject, SOAPMessage soapMessage)

Sends a SOAP message.

Parameters:
  • from – the ‘from’ mail address.
  • to – the ‘to’ mail address(es).
  • cc – the ‘cc’ mail address(es).
  • subject – the mail subject.
  • soapMessage – the SOAP message.
Throws:

See also: hk.hku.cecid.piazza.commons.net.MailSender.send(java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String)

SOAPMailSenderTest

public class SOAPMailSenderTest extends TestCase

Methods

setUp
public void setUp()
tearDown
public void tearDown()
testCreatedMessage
public void testCreatedMessage()
testCreatedMessageLineMaxLimit
public void testCreatedMessageLineMaxLimit()

SOAPRequest

public class SOAPRequest

The SOAPRequest class represents a SOAP request. It is independent of which transport protocol it is using and contains the SOAP message of the original request.

Author:Hugo Y. K. Lam

Constructors

SOAPRequest
SOAPRequest()

Creates a new instance of SOAPRequest.

SOAPRequest
SOAPRequest(Object source)

Creates a new instance of SOAPRequest.

Parameters:
  • source – the source which initiated this request.

Methods

getBytes
public byte[] getBytes()

Gets the SOAP message as bytes.

Returns:the byte array of the SOAP message.
getHeaders
public MimeHeaders getHeaders()

Gets the mime headers of the request.

Returns:the mime headers of the request.
getMessage
public SOAPMessage getMessage()

Gets the SOAP message of this request.

Returns:the SOAP message of this request.
getSource
public Object getSource()

Gets the source which initiated this request.

Returns:the source which initiated this request.
setBytes
void setBytes(byte[] bs)

Sets the bytes of the SOAP message.

Parameters:
  • bs – the byte array of the SOAP message.
setHeaders
void setHeaders(MimeHeaders headers)

Sets the mime headers of the request.

Parameters:
  • headers – the mime headers of the request.
setMessage
void setMessage(SOAPMessage message)

Sets the SOAP message of this request.

Parameters:
  • message – the SOAP message of this request.
setSource
void setSource(Object source)

Sets the source which initiated this request.

Parameters:
  • source – the source which initiated this request.

SOAPRequestException

public class SOAPRequestException extends hk.hku.cecid.piazza.commons.GenericException

SOAPRequestException represents all kinds of exception related to a SOAP request or its process.

Author:Hugo Y. K. Lam

Constructors

SOAPRequestException
public SOAPRequestException()

Creates a new instance of SOAPRequestException.

SOAPRequestException
public SOAPRequestException(String message)

Creates a new instance of SOAPRequestException.

Parameters:
  • message – the error message.
SOAPRequestException
public SOAPRequestException(Throwable cause)

Creates a new instance of SOAPRequestException.

Parameters:
  • cause – the cause of this exception.
SOAPRequestException
public SOAPRequestException(String message, Throwable cause)

Creates a new instance of SOAPRequestException.

Parameters:
  • message – the error message.
  • cause – the cause of this exception.

Methods

getSOAPFault
public SOAPFaultException getSOAPFault()

Gets the SOAP fault exception which caused this exception.

Returns:the SOAP fault exception which caused this exception or null if there is none.
isSOAPFault
public boolean isSOAPFault()

Checks if this exception is caused by a SOAP fault exception.

Returns:true if this exception is caused by a SOAP fault exception.

SOAPRequestListener

public interface SOAPRequestListener

SOAPRequestListener is a listener for handling SOAP requests.

Author:Hugo Y. K. Lam

Methods

processRequest
public void processRequest(SOAPRequest request, SOAPResponse response)

Processes the SOAP request.

Parameters:
  • request – the SOAP request.
  • response – the SOAP response.
Throws:

SOAPResponse

public class SOAPResponse

The SOAPResponse class represents a SOAP response. It is independent of which transport protocol it is using and contains the SOAP message of the target response.

Author:Hugo Y. K. Lam

Constructors

SOAPResponse
SOAPResponse()

Creates a new instance of SOAPResponse.

SOAPResponse
SOAPResponse(Object target)

Creates a new instance of SOAPResponse.

Parameters:
  • target – the target that this response should be committed to.

Methods

addFault
public SOAPFault addFault(String code, String actor, String desc)

Adds a SOAP fault to the SOAP message of this response.

Parameters:
  • code – the fault code.
  • actor – the fault actor.
  • desc – the fault description.
Throws:
  • SOAPException – a SOAP error occurred when adding the the fault.
Returns:

the SOAP fault which has been added to the SOAP message. null if there is no SOAP message in this response or the fault has already been added.

addFault
public SOAPFault addFault(Throwable cause)

Adds a SOAP fault to the SOAP message of this response.

Parameters:
  • cause – the exception cause.
Throws:
  • SOAPException – a SOAP error occurred when adding the the fault.
Returns:

the SOAP fault which has been added to the SOAP message. null if there is no SOAP message in this response or the fault has already been added.

getMessage
public SOAPMessage getMessage()

Gets the SOAP message of this response.

Returns:the SOAP message of this response.
getTarget
public Object getTarget()

Gets the target that this response should be committed to.

Returns:the target that this response should be committed to.
setMessage
public void setMessage(SOAPMessage message)

Sets the SOAP message of this response.

Parameters:
  • message – the SOAP message of this response.
setTarget
void setTarget(Object target)

Sets the target that this response should be committed to.

Parameters:
  • target – the target that this response should be committed to.

WebServicesAdaptor

public abstract class WebServicesAdaptor extends SOAPHttpAdaptor

WebServicesAdaptor is a SOAPHttpAdaptor which handles web services request. This adaptor can only handles document style web services. It invokes either one of the following methods in the subclass for handling the request:

  1. public Element[] serviceRequested(Element[] bodies)
  2. public SOAPElement[] serviceRequested(SOAPElement[] bodies)
  3. public void serviceRequested(SOAPMessage req, SOAPMessage resp)
  4. public void serviceRequested(WebServicesRequest req, WebServicesResponse resp)
Author:Hugo Y. K. Lam

Methods

createElement
protected SOAPElement createElement(String name, String value, String namespace, String xsdType)

Creates a SOAP element.

Parameters:
  • name – the element name.
  • value – the element value.
  • namespace – the namespace.
  • xsdType – the XSD data type.
Throws:
  • SOAPException – if unable to create the element.
Returns:

the newly created element.

createElement
protected SOAPElement createElement(String local, String namespace)
createElement
protected SOAPElement createElement(String local, String namespace, String value)
createText
protected SOAPElement createText(String name, String value, String namespace)

Creates a text element.

Parameters:
  • name – the element name.
  • value – the element value.
  • namespace – the namespace.
Throws:
  • SOAPException – if unable to create the element.
Returns:

the newly created text element.

doStartRequest
public boolean doStartRequest(HttpServletRequest request, HttpServletResponse response)

Responses with a web services descriptor if the request’s query is “wsdl” or the request is a “get” method.

Parameters:
  • request – the servlet request.
  • response – the servlet response.
Throws:
Returns:

true if the request is not a “wsdl” request, false otherwise.

See also: hk.hku.cecid.piazza.commons.servlet.http.HttpRequestListener.doStartRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)

getChildElementArray
protected SOAPElement[] getChildElementArray(SOAPElement element)
getText
protected String getText(Element[] elements, String nodename)

Gets the text value of the element with the specified node name in the given elements.

Parameters:
  • elements – the elements containing the target node.
  • nodename – the target node name.
Returns:

the text value of the specified node.

isElement
protected boolean isElement(SOAPElement element, String local, String namespace)
processDescriptorRequest
protected void processDescriptorRequest(OutputStream outs)

Processes the WSDL request. Override to provide specific descriptor.

Parameters:
  • outs – the output stream to which the descriptor should be written.
Throws:
processRequest
public void processRequest(SOAPRequest request, SOAPResponse response)

Prcoesses the SOAP request.

Parameters:
  • request – the SOAP request.
  • response – the SOAP response.
Throws:

See also: hk.hku.cecid.piazza.commons.soap.SOAPRequestListener.processRequest(hk.hku.cecid.piazza.commons.soap.SOAPRequest, hk.hku.cecid.piazza.commons.soap.SOAPResponse)

WebServicesRequest

public class WebServicesRequest

The WebServicesRequest class represents a Web Services request. It is independent of which access protocol it is using and contains the bodies of the request message.

Author:Hugo Y. K. Lam

Constructors

WebServicesRequest
WebServicesRequest()

Creates a new instance of WebServicesRequest.

WebServicesRequest
WebServicesRequest(Object source)

Creates a new instance of WebServicesRequest.

Parameters:
  • source – the source which initiated this request.

Methods

getBodies
public Element[] getBodies()

Gets the body elements of the Web Services request message.

Returns:the bodies of the Web Services request message.
getSource
public Object getSource()

Gets the source which initiated this request.

Returns:the source which initiated this request.
setBodies
void setBodies(Element[] bs)

Sets the body elements of the Web Services request message.

Parameters:
  • bs – the bodies of the Web Services request message.
setSource
void setSource(Object source)

Sets the source which initiated this request.

Parameters:
  • source – the source which initiated this request.

WebServicesResponse

public class WebServicesResponse

The WebServicesResponse class represents a Web Services response. It is independent of which access protocol it is using and contains the bodies of the response message.

Author:Hugo Y. K. Lam

Constructors

WebServicesResponse
WebServicesResponse()

Creates a new instance of WebServicesResponse.

WebServicesResponse
WebServicesResponse(Object target)

Creates a new instance of WebServicesResponse.

Parameters:
  • target – the target that this response should be committed to.

Methods

getBodies
public Element[] getBodies()

Gets the body elements of the Web Services response message.

Returns:the bodies of the Web Services response message.
getTarget
public Object getTarget()

Gets the target that this response should be committed to.

Returns:the target that this response should be committed to.
setBodies
public void setBodies(Element[] bs)

Sets the body elements of the Web Services response message.

Parameters:
  • bs – the bodies of the Web Services response message.
setTarget
void setTarget(Object target)

Sets the target that this response should be committed to.

Parameters:
  • target – the target that this response should be committed to.

hk.hku.cecid.piazza.commons.spa

Extension

public class Extension extends PluginComponent

An Extension is a plugin component which represents the extension element in the plugin descriptor.

Author:Hugo Y. K. Lam

See also: Plugin, ExtensionPoint

Constructors

Extension
public Extension(PluginComponent parent, String point, String name)

Creates a new instance of Extension.

Parameters:
  • parent – the parent plugin component.
  • point – the extension point this extension extends.
  • name – the extension name.
Extension
public Extension(PluginComponent parent, String point, String name, Properties parameters)

Creates a new instance of Extension.

Parameters:
  • parent – the parent plugin component.
  • point – the extension point this extension extends.
  • name – the extension name.
  • parameters – the extension parameters.

Methods

getName
public String getName()

Gets the extension name.

Returns:the extension name.
getParameter
public String getParameter(String key)

Gets an extension parameter.

Parameters:
  • key – the key of the parameter.
Returns:

the parameter.

getParameters
public Properties getParameters()

Gets the extension parameters.

Returns:the parameters.
getPoint
public String getPoint()

Gets the extension point this extension extends.

Returns:the extension point.
toString
public String toString()

Returns a string representation of this extension.

Returns:a string representation of this extension.

See also: java.lang.Object.toString()

ExtensionPoint

public class ExtensionPoint extends PluginComponent

An ExtensionPoint is a plugin component which represents the extension-point element in the plugin descriptor.

Author:Hugo Y. K. Lam

See also: Plugin, Extension, ExtensionPointHandler

Constructors

ExtensionPoint
public ExtensionPoint(PluginComponent parent, String id, String name, String handlerClass)

Creates a new instance of ExtensionPoint.

Parameters:
  • parent – the parent plugin component.
  • id – the extension point ID.
  • handlerClass – the handler class of this extension point.

Methods

getHandlerClass
public String getHandlerClass()

Gets the handler class of this extension point.

Returns:the handler class of this extension point.
getId
public String getId()

Gets the ID of this extention point.

Returns:the ID of this extention point.
getName
public String getName()

Gets the name of this extension point.

Returns:the name of this extension point.
processExtensions
public void processExtensions(Collection extensions)

Processes extensions by invoking the handler class of this extension point.

Parameters:
  • extensions – the extensions to be processed.
Throws:
  • PluginException – if there is error in processing extensions by the handler
toString
public String toString()

Returns a string representation of this extension point.

Returns:a string representation of this extension point.

See also: java.lang.Object.toString()

ExtensionPointHandler

public interface ExtensionPointHandler

An ExtensionPointHandler handles all the extensions of the extension point it represents.

Author:Hugo Y. K. Lam

See also: ExtensionPoint

Methods

processExtensions
public void processExtensions(Collection extensions)

Processes the extensions of the extension point it represents. It is invoked when the plugin registry is being activated.

Parameters:
  • extensions – the extensions of the extension point it represents.
Throws:

ExtensionPointIteratedHandler

public abstract class ExtensionPointIteratedHandler implements ExtensionPointHandler

An ExtensionPointIteratedHandler handles all the extensions of the extension point it represents one by one.

Author:Hugo Y. K. Lam

See also: ExtensionPoint

Methods

isFaultTolerated
protected boolean isFaultTolerated()

Checks if fault tolerance is enabled.

Returns:true if fault tolerance is enabled.
processExtension
public abstract void processExtension(Extension extension)

Invoked by processExtensions() for processing each extension.

Parameters:
  • extension – the extension to be processed.
processExtensions
public void processExtensions(Collection extensions)

Processes the extensions one by one. If fault tolerance is enabled, no exception will be thrown and processes will be carried on even if there are any exceptions.

Parameters:
  • extensions – the extensions of the extension point it represents.
Throws:

See also: hk.hku.cecid.piazza.commons.spa.ExtensionPointHandler.processExtensions(java.util.Collection)

Import

public class Import extends PluginComponent

An Import is a plugin component which represents the import element in the plugin descriptor.

Author:Hugo Y. K. Lam

See also: Plugin

Constructors

Import
public Import(PluginComponent parent, String importedPluginId)

Creates a new instance of Import.

Parameters:
  • parent – the parent plugin component.
  • importedPluginId – the ID of the imported plugin.

Methods

getImportedPlugin
public Plugin getImportedPlugin()

Gets the imported plugin.

Returns:the imported plugin.
getImportedPluginId
public String getImportedPluginId()

Gets the ID of the imported plugin.

Returns:the ID of the imported plugin.
toString
public String toString()

Returns a string representation of this import.

Returns:a string representation of this import.

See also: java.lang.Object.toString()

Library

public class Library extends PluginComponent

A Library is a plugin component which represents the library element in the plugin descriptor.

Author:Hugo Y. K. Lam

See also: Plugin

Constructors

Library
public Library(PluginComponent parent, String name)

Creates a new instance of Library.

Parameters:
  • parent – the parent plugin component.
  • name – the name of this library.

Methods

getName
public String getName()

Gets the name of this library.

Returns:the name of this library.
toString
public String toString()

Returns a string representation of this library.

Returns:a string representation of this library.

See also: java.lang.Object.toString()

Plugin

public class Plugin extends PluginComponent

A Plugin represents a plugin descriptor. It contains the elements specified in the descriptor. It also contains a class loader for loading classes which stored in the libraries specified in the descriptor. If there is a plugin handler specified in the descriptor, it will be invoked when the plugin is being activated.

Author:Hugo Y. K. Lam

See also: PluginRegistry, PluginClassLoader, PluginHandler

Constructors

Plugin
public Plugin(PluginRegistry registry, File folder, String descriptor)

Creates a new instance of Plugin.

Parameters:
  • registry – the plugin registry which stores this plugin.
  • folder – the folder which holds this plugin.
  • descriptor – the descriptor of this plugin.
Throws:
  • PluginException – if this plugin cannot be initialized according to its plugin descriptor.

Methods

activate
public synchronized void activate()

Activates this plugin by invoking the plugin handler specified in the plugin descriptor. If the plugin has already been activated, nothing will be done.

Throws:
  • PluginException – if there is any error in processing activation by the handler.
deactivate
public synchronized void deactivate()

Deactivates this plugin by invoking the plugin handler specified in the plugin descriptor. If the plugin has not yet been activated, nothing will be done.

Throws:
  • PluginException – if there is any error in processing deactivation by the handler.
getClassLoader
public PluginClassLoader getClassLoader()

Gets the class loader for this plugin.

Returns:the class loader for this plugin.
getExtensionPoints
public Collection getExtensionPoints()

Gets all the extension points declared in the plugin descriptor.

Returns:all the extension points declared in the plugin descriptor.
getExtensions
public Collection getExtensions()

Gets all extensions declared in the plugin descriptor.

Returns:all extensions declared in the plugin descriptor.
getExtensions
public Collection getExtensions(String point)

Gets all extensions declared in the plugin descriptor which extends the specified extension point.

Parameters:
  • point – the extension point.
Returns:

all extensions declared in the plugin descriptor which extends the specified extension point.

getHandlerClass
public String getHandlerClass()

Gets the handler class of this plugin.

Returns:the handler class of this plugin.
getId
public String getId()

Gets the plugin ID.

Returns:the plugin ID.
getImports
public Collection getImports()

Gets all plugin imports declared in the plugin descriptor.

Returns:all plugin imports declared in the plugin descriptor.
getLibraries
public Collection getLibraries()

Gets all libraries declared in the plugin descriptor.

Returns:all libraries declared in the plugin descriptor.
getName
public String getName()

Gets the plugin name.

Returns:the plugin name.
getParameters
public Properties getParameters()

Gets the parameters of this plugin.

Returns:the parameters of this plugin.
getPluginRegistry
public PluginRegistry getPluginRegistry()

Gets the plugin registry of this plugin.

Returns:the plugin registry of this plugin.
getProviderName
public String getProviderName()

Gets the provider name of this plugin.

Returns:the provider name of this plugin.
getVersion
public String getVersion()

Gets the version of this plugin.

Returns:the version of this plugin.
isActivated
public boolean isActivated()

Checks if this plugin has been activated.

Returns:true if this plugin has been activated.
loadClass
public Class loadClass(String name)

Loads a class from this plugin’s class loader.

Parameters:
  • name – the class name.
Throws:
Returns:

the Class instance for the specified class name.

toString
public String toString()

Returns a string representation of this plugin.

Returns:a string representation of this plugin.

See also: java.lang.Object.toString()

PluginClassLoader

public class PluginClassLoader extends URLClassLoader

A PluginClassLoader is a class loader for loading classes which stored in the libraries specified in a plugin descriptor.

Author:Hugo Y. K. Lam

See also: Plugin

Constructors

PluginClassLoader
public PluginClassLoader(Plugin plugin, URL[] urls)

Creates a new instance of PluginClassLoader.

Parameters:
  • plugin – the Plugin corresponds to this class loader.
  • urls – the search paths.
PluginClassLoader
public PluginClassLoader(Plugin plugin, URL[] urls, ClassLoader parent)

Creates a new instance of PluginClassLoader.

Parameters:
  • plugin – the Plugin corresponds to this class loader.
  • urls – the search paths.
  • parent – the parent class loader.
PluginClassLoader
public PluginClassLoader(Plugin plugin, URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory)

Creates a new instance of PluginClassLoader.

Parameters:
  • plugin – the Plugin corresponds to this class loader.
  • urls – the search paths.
  • parent – the parent class loader.
  • factory – the URL stream handler factory.

Methods

findClass
protected Class findClass(String name)

Finds and loads the class with the specified name from the URL search path. Any URLs referring to JAR files are loaded and opened as needed until the class is found. If the class is not found from the search paths of this class loader, it will be searched from the imported class loaders.

Parameters:
  • name – the name of the class.
Throws:
Returns:

the resulting class.

See also: java.lang.ClassLoader.findClass(java.lang.String)

findImportedClass
protected Class findImportedClass(String name)

Finds and loads the class with the specified name from the imported class loaders.

Parameters:
  • name – the name of the class.
Throws:
Returns:

the resulting class.

See also: java.lang.ClassLoader.findClass(java.lang.String)

findResource
public URL findResource(String name)

Finds the resource with the specified name on the URL search paths.

Parameters:
  • name – the name of the resource.
Returns:

a URL for the resource, or null if the resource could not be found.

See also: java.lang.ClassLoader.findResource(java.lang.String)

getPlugin
public Plugin getPlugin()

Gets the plugin corresponds to this class loader.

Returns:the plugin corresponds to this class loader.
importClassLoader
void importClassLoader(ClassLoader loader)

Imports a class loader.

Parameters:
  • loader – the class loader to be imported.
toString
public String toString()

Returns a string representation of this class loader.

Returns:a string representation of this class loader.

See also: java.lang.Object.toString()

PluginComponent

public class PluginComponent

A PluginComponent represents any components compose the plugin, including the plugin itself.

Author:Hugo Y. K. Lam

Constructors

PluginComponent
public PluginComponent(PluginComponent parent)

Creates a new instance of PluginComponent.

Parameters:
  • parent – the parent component.

Methods

getParent
public PluginComponent getParent()

Gets the parent component of this plugin component.

Returns:the parent component of this plugin component.
getPlugin
public Plugin getPlugin()

Gets the plugin which holds this plugin component.

Returns:the plugin which holds this plugin component.

PluginDescriptor

public class PluginDescriptor

PluginDescriptor is a descriptor containing the configurations of the plugin it represents.

<plugin id="nmtoken" name="nmtoken"? version="nmtoken"? provider-name="nmtoken"? class="nmtoken"?>

       <parameters>?
               <parameter name="nmtoken" value="nmtoken" />*
       </parameters>

       <runtime>?
               <library name="nmtoken" />*
       </runtime>

       <requires>?
               <import plugin="nmtoken" />*
       </requires>

       <extension-point id="nmtoken" class="nmtoken" name="nmtoken"? />*

       <extension point="nmtoken" name="nmtoken"?>*
               <parameter name="nmtoken" value="nmtoken" />*
       </extension>

</plugin>
Author:Hugo Y. K. Lam

Fields

DEFAULT_DESCRIPTOR_NAME
public static final String DEFAULT_DESCRIPTOR_NAME

The default descriptor name (plugin.xml).

Constructors

PluginDescriptor
public PluginDescriptor(File file)

Creates a new instance of PluginDescriptor.

Parameters:
  • file – the plugin descriptor file.
Throws:
  • PluginException – if unable to create the plugin descriptor.
  • FileNotFoundException – if the descriptor file does not exist.
PluginDescriptor
public PluginDescriptor(InputStream ins)

Creates a new instance of PluginDescriptor.

Parameters:
  • ins – the plugin descriptor input stream.
Throws:
  • PluginException – if unable to create the plugin descriptor.

Methods

getExtensionPoints
public Collection getExtensionPoints()

Creates a collection of extension points according to the specified plugin descriptor.

Returns:a collection of extension points.
getExtensions
public Collection getExtensions()

Creates a collection of extensions according to the specified plugin descriptor.

Returns:a collection of extensions.
getHandlerClass
public String getHandlerClass()

Gets the handler class of the plugin.

Returns:the handler class of the plugin.
getId
public String getId()

Gets the plugin ID.

Returns:the plugin ID.
getImports
public Collection getImports()

Creates a collection of imports according to the specified plugin descriptor.

Returns:a collection of imports.
getLibraries
public Collection getLibraries()

Creates a collection of libraries according to the specified plugin descriptor.

Returns:a collection of libraries.
getName
public String getName()

Gets the plugin name.

Returns:the plugin name.
getParameters
public Properties getParameters()

Gets the plugin parameters.

Returns:the plugin parameters.
getParent
public PluginComponent getParent()

Gets the parent plugin component of this descriptor.

Returns:the parent plugin component of this descriptor.
getProviderName
public String getProviderName()

Gets the plugin provider name.

Returns:the plugin provider name.
getVersion
public String getVersion()

Gets the plugin version.

Returns:the plugin version.
setParent
public void setParent(PluginComponent parent)

Sets the parent plugin component of this descriptor.

Parameters:
  • parent – the parent plugin component of this descriptor.

PluginException

public class PluginException extends hk.hku.cecid.piazza.commons.GenericException

PluginException represents all kinds of exception related to the plugin framework.

Author:Hugo Y. K. Lam

Constructors

PluginException
public PluginException()

Creates a new instance of PluginException.

PluginException
public PluginException(String message)

Creates a new instance of PluginException.

Parameters:
  • message – the error message.
PluginException
public PluginException(Throwable cause)

Creates a new instance of PluginException.

Parameters:
  • cause – the cause of this exception.
PluginException
public PluginException(String message, Throwable cause)

Creates a new instance of PluginException.

Parameters:
  • message – the error message.
  • cause – the cause of this exception.

PluginFile

public class PluginFile

A PluginFile represents an archive file containing all the plugin required files, including the plugin descriptor.

Author:Hugo Y. K. Lam

Fields

DEFAULT_FILE_EXT
public static final String DEFAULT_FILE_EXT

The default file extension (spa) of the plugin file.

Constructors

PluginFile
public PluginFile(File pluginFile)

Create a new instance of PluginFile.

Parameters:
  • pluginFile – the plugin file.
Throws:
  • PluginException – if unable to create the plugin file instance.
PluginFile
public PluginFile(File pluginFile, String descriptorName)

Create a new instance of PluginFile.

Parameters:
  • pluginFile – the plugin file.
  • descriptorName – the plugin descriptor name.
Throws:
  • PluginException – if unable to create the plugin file instance.
PluginFile
public PluginFile(InputStream pluginStream)

Create a new instance of PluginFile.

Parameters:
  • pluginStream – the plugin stream.
Throws:
  • PluginException – if unable to create the plugin file instance.
PluginFile
public PluginFile(InputStream pluginStream, String descriptorName)

Create a new instance of PluginFile.

Parameters:
  • pluginStream – the plugin stream.
  • descriptorName – the plugin descriptor name.
Throws:
  • PluginException – if unable to create the plugin file instance.

Methods

getDescriptor
public PluginDescriptor getDescriptor()

Gets the plugin descriptor.

Returns:the plugin descriptor.
getPluginContent
public byte[] getPluginContent()

Gets the plugin content.

Returns:the plugin content.

PluginHandler

public interface PluginHandler

A PluginHandler handles the activation process of a plugin.

Author:Hugo Y. K. Lam

See also: Plugin

Methods

processActivation
public void processActivation(Plugin plugin)

Processes the activation of the plugin this handler represents. It is invoked when the plugin is being activated.

Parameters:
  • plugin – the plugin this handler represents.
Throws:
processDeactivation
public void processDeactivation(Plugin plugin)

Processes the deactivation of the plugin this handler represents. It is invoked when the plugin is being deactivated.

Parameters:
  • plugin – the plugin this handler represents.
Throws:

PluginRegistry

public class PluginRegistry

A PluginRegistry is a registry which stores all the plugin configurations. It has a fixed registry location and the plugin configurations are specified in plugin descriptors.

Author:Hugo Y. K. Lam

See also: Plugin

Constructors

PluginRegistry
public PluginRegistry(String registry)

Creates a new instance of PluginRegistry.

Parameters:
  • registry – the registry location.
Throws:
  • PluginException – if the registry is invalid.
PluginRegistry
public PluginRegistry(File registry)

Creates a new instance of PluginRegistry.

Parameters:
  • registry – the registry location.
Throws:
  • PluginException – if the registry is invalid.
PluginRegistry
public PluginRegistry(String registry, String descriptor)

Creates a new instance of PluginRegistry.

Parameters:
  • registry – the registry location.
  • descriptor – the plugin descriptor name.
Throws:
  • PluginException – if the registry is invalid.
PluginRegistry
public PluginRegistry(File registry, String descriptor)

Creates a new instance of PluginRegistry.

Parameters:
  • registry – the registry location.
  • descriptor – the plugin descriptor name.
Throws:
  • PluginException – if the registry is invalid.

Methods

activate
public synchronized void activate()

Activates the plugin registry if it is not yet activated.

deactivate
public synchronized void deactivate()

Deactivates the plugin registry if it is activated.

deploy
public String deploy(InputStream spa)

Deploys a plugin to the plugin registry.

Parameters:
  • spa – the SPA file input stream.
Throws:
Returns:

the plugin ID of the deployed plugin.

getAllExtensions
public Collection getAllExtensions(String point)

Gets all extensions corresponding to the specified extension point.

Parameters:
  • point – the extension point.
Returns:

all extensions corresponding to the specified extension point.

getLocation
public String getLocation()

Gets the plugin registry location.

Returns:the plugin registry location.
getPlugin
public Plugin getPlugin(String id)

Gets a plugin from this plugin registry.

Parameters:
  • id – the plugin ID.
Returns:

the plugin corresponding to the specified plugin ID.

getPlugins
public Collection getPlugins()

Gets all plugins in this plugin registry.

Returns:all plugins in this plugin registry.
hasErrors
public boolean hasErrors()

Checks if there is any error occurred during the initialization or activation of this plugin registry.

Returns:true if there is any error occurred during the activation of this plugin registry.
isActivated
public boolean isActivated()

Checks if this plugin registry has already been activated.

Returns:true if this plugin registry has already been activated.
toString
public String toString()

Returns a string representation of this plugin registry.

Returns:a string representation of this plugin registry.

See also: java.lang.Object.toString()

undeploy
public void undeploy(String pluginID)

Undeploys a plugin from the plugin registry.

Parameters:
  • pluginID – the plugin ID to undeploy.
Throws:

hk.hku.cecid.piazza.commons.swallow

DiagnosticUtilities

public class DiagnosticUtilities

The DiagnosticUtilities is is a utility for providing useful information for monitoring and debugging the JVM.

Author:Twinsen Tsang

Methods

dumpAllThread
public void dumpAllThread()

Dump all threads information from the current JVM.

dumpAllThread
public void dumpAllThread(OutputStream os, int stackTraceDepth)

Dump all threads information from the current JVM to the specified OutputStream os.

Parameters:
  • os – The output stream to dump the threads information.
  • stackTraceDepth – The depth of stack trace to dump, default is 3.
Throws:
dumpAllThread
public void dumpAllThread(Writer w, int stackTraceDepth)

Dump all threads information from the current JVM to the specified OutputStream w.

Parameters:
  • w – The writer used to dump the threads information.
  • stackTraceDepth – The depth of stack trace to dump, default is 3.
Throws:
getInstance
public static DiagnosticUtilities getInstance()

Get the single instance of DiagnosticUtilities.

Returns:the single instance of DiagnosticUtilities.
getNewInstance
public static DiagnosticUtilities getNewInstance()

Get the new instance of DiagnosticUtilities.

Returns:the new instance of DiagnosticUtilities.
main
public static void main(String[] args)

DiagnosticUtilitiesUnitTest

public class DiagnosticUtilitiesUnitTest

The DiagnoisticUtilitiesUnitTest is MANUAL unit test of DiagnoisticUtilities.

Author:Twinsen Tsang

Methods

testDumpAllThread
public void testDumpAllThread()

It is not an automated test-case. Just for manual diagnostic method.

testDumpAllThreadWithIllegalStackTraceDepth
public void testDumpAllThreadWithIllegalStackTraceDepth()

Test whether operation dumpAllThread throws IllegalArgumentException when stack trace depth is less than zero.

testDumpAllThreadWithNullStream
public void testDumpAllThreadWithNullStream()

Test whether operation dumpAllThread throws NullPointerException when output stream is null.

testGetInstance
public void testGetInstance()

Test whether the singleton instance is instantiated successfully through DiagnosticUtilities.getInstance()

ShutdownHookEmailModule

public class ShutdownHookEmailModule extends Module

The ShutdownHookEmailModule is a piazza common module which send email to the specified when the JVM is terminated. It is typical used to notify the operator for the termination of long-running java process like application server (for instance, Tomcat) through email. Background about this: This component is emerged when project swallow requires the detection of application crashes and therefore we want a reusable generic component for doing such. Sample Module Descriptor

<module id="shutdown.email.module" name="Email shutdown hook module">
 <parameters>
  <parameter name="host" value="intraflow2.cs.hku.hk"/>
  <parameter name="protocol" value="smtp"/>
  <parameter name="username" value=""/>
  <parameter name="password" value=""/>
  <parameter name="from" value="yourDaemon@cecid.hku.hk"/>
  <parameter name="to" value="yourEmailAddress"/>
  <parameter name="cc" value="yourCCEmailAddress"/>
  <parameter name="verbose" value="false"/>
 </parameters>
</module>
Author:Twinsen Tsang

Constructors

ShutdownHookEmailModule
public ShutdownHookEmailModule(String descriptorLocation, boolean shouldInitialize)

Creates a new instance of ShutdownHookEmailModule.

Parameters:
  • descriptorLocation – the module descriptor.
Throws:
  • ModuleException – if errors encountered when loading the module descriptor.
ShutdownHookEmailModule
public ShutdownHookEmailModule(String descriptorLocation, ClassLoader loader, boolean shouldInitialize)

Creates a new instance of ShutdownHookEmailModule.

Parameters:
  • descriptorLocation – the module descriptor.
  • shouldInitialize – true if the module should be initialized.
Throws:
  • ModuleException – if errors encountered when loading the module descriptor.
ShutdownHookEmailModule
public ShutdownHookEmailModule(String descriptorLocation, ClassLoader loader)

Creates a new instance of ShutdownHookEmailModule.

Parameters:
  • descriptorLocation – the module descriptor.
  • loader – the class loader for this module.
Throws:
  • ModuleException – if errors encountered when loading the module descriptor.
ShutdownHookEmailModule
public ShutdownHookEmailModule(String descriptorLocation)

Creates a new instance of ShutdownHookEmailModule.

Parameters:
  • descriptorLocation – the module descriptor.

Methods

createShutdownHookWorker
protected Thread createShutdownHookWorker()

Create the thread executed during JVM shutdown. By default, it create an new instance of ShutdownHookEmailThread associated with the property defined in this module descriptor. The thread created must conform the rule specified in the Java API. For detail, read here

Throws:
  • Throwable – any kind of execution for setup the shutdown hook worker.
Returns:

The thread executed during JVM shutdown

getThread
protected Thread getThread()
init
public void init()

Invoked for initialization. Wire up all property from the XML.

stop
public synchronized void stop()

A special hack for remove the shutdown hook registered during the init() phrase of this module. This is used for testing the module only. You rarely call this in your application.

ShutdownHookEmailModuleUnitTest

public class ShutdownHookEmailModuleUnitTest extends ModuleTest<ShutdownHookEmailModule>

The ShutdownHookEmailModuleUnitTest is unit test of ShutdownHookEmailModule.

Author:Twinsen Tsang

Fields

MODULE_DESCRIPTORS
public static final String[] MODULE_DESCRIPTORS

Constructors

ShutdownHookEmailModuleUnitTest
public ShutdownHookEmailModuleUnitTest(String moduleDescriptor)

Create an instance of parameterized (parameter=module descriptor) ShutdownHookEmailModuleUnitTest.

Parameters:
  • moduleDescriptor – The parameterized module descriptor.

Methods

getModuleDescription
public String getModuleDescription()
getModuleDescriptionSet
public static Collection getModuleDescriptionSet()
initAtOnce
public boolean initAtOnce()
tearDown
public void tearDown()
testCreateShutdownHookWorker
public void testCreateShutdownHookWorker()

Test whether the ShutdownHookEmailModule.createShutdownHookWorker() able to wire up all properties from the module descriptor and it is an instance of ShutdownHookEmailThread. Note that the assertion actually take place in a helper class called CreateShudownHookWorkerAssertionThread. It is essential because the ShutdownHook worker thread is loaded through a clone of current class loader and therefore the class only appear in that domain.

testGetThread
public void testGetThread()

Test whether ShutdownHookEmailModule.getThread() always return non null value.

testOnCreateMailNotificationBody
public void testOnCreateMailNotificationBody()

This test has not implemented yet because the mail subject is subject to change.

testOnCreateMailNotificationSubject
public void testOnCreateMailNotificationSubject()

This test has not implemented yet because the mail subject is subject to change.

testShutdownHookRegisteredToRuntime
public void testShutdownHookRegisteredToRuntime()

Test whether the thread from ShutdownHookEmailModule.getThread() is registered inside the runtime shutdown hook.

testStop
public void testStop()

This test has not implemented yet because it is not a automated test case (it is for debugging purpose only).

ShutdownHookEmailModuleUnitTest.CreateShudownHookWorkerAssertionThread

public static class CreateShudownHookWorkerAssertionThread extends Thread

Constructors

CreateShudownHookWorkerAssertionThread
public CreateShudownHookWorkerAssertionThread(Properties assertionProperties, Thread shutdownThread)

Methods

run
public void run()

ShutdownHookEmailThread

public class ShutdownHookEmailThread extends Thread

The ShutdownHookEmailThread is the actual worker thread executing during the JVM shutdown.

Fields

DEFAULT_SHUTDOWN_MAIL_SUBJECT
public static final String DEFAULT_SHUTDOWN_MAIL_SUBJECT
ccs
protected String ccs
from
protected String from
host
protected String host
password
protected String password
protocol
protected String protocol
subject
protected String subject
tos
protected String tos
username
protected String username
verbose
protected boolean verbose

Constructors

ShutdownHookEmailThread
public ShutdownHookEmailThread(String protocol, String host, String username, String password, String from, String tos, String ccs, String subject, boolean verbose)

Create an instance of ShutdownHookEmailThread for delivering shutdown notification mail.

Parameters:
  • protocol – The protocol for delivering email. default: smtp.
  • host – The host-name of email server.
  • username – The user-name for authenticating the email server, if necessary.
  • password – The password for authenticating the email server, if necessary.
  • from – The source email address of the shutdown notification email.
  • tos – The to email address of recipient notification email.
  • ccs – The cc email address of recipient notification email.
  • subject – The subject of the email address.
  • verbose – Enable debug mode ?

Methods

getCcs
public String getCcs()

Get the carbon copy address of the shutdown alert email.

Returns:Get the carbon copy address of the shutdown alert email.
getFrom
public String getFrom()

Get the source address of the shutdown alert email.

Returns:Get the source address of the shutdown alert email.
getHost
public String getHost()

Get the email host of the shutdown alert email.

Returns:Get the email host of the shutdown alert email.
getIsVerbose
public boolean getIsVerbose()

Get whether the shutdown hook output verbosely.

Returns:Get whether the shutdown hook output verbosely.
getPassword
public String getPassword()

Get the password (if any) for authenticating the email host for delivering the alert email.

Returns:Get the password (if any) for authenticating the email host.
getProtocol
public String getProtocol()

Get the email protocol of the shutdown alert email.

Returns:Get the email protocol of the shutdown alert email.
getSubject
public String getSubject()

Get the subject title of the shutdown alert email.

Returns:Get the subject title of the shutdown alert email.
getTos
public String getTos()

Get the recipient address of the shutdown alert email.

Returns:Get the recipient address of the shutdown alert email.
getUsername
public String getUsername()

Get the user-name (if any) for authenticating the email host for delivering the alert email.

Returns:Get the user-name (if any) for authenticating the email host.
onCreateMailNotificationBody
protected String onCreateMailNotificationBody()

Return the body of notification email. The default return the snapshot of all thread dump information. Sub-class may override this to customize the subject of notification email.

Returns:Return the body of notification email.
onCreateMailNotificationSubject
protected String onCreateMailNotificationSubject()

Return the subject of notification email. Sub-class may override this to customize the subject of notification email.

Returns:Return the subject of notification email, default is DEFAULT_SHUTDOWN_MAIL_SUBJECT
run
public void run()

The shutdown thread execution.

hk.hku.cecid.piazza.commons.util

ArrayUtilities

public final class ArrayUtilities

ArrayUtilities is a convenient class for handling some common array processing.

Author:Hugo Y. K. Lam

Methods

forNames
public static Class[] forNames(String[] classNames)

Returns the Class object array associated with the class or interface with the given string name array.

Parameters:
  • classNames – the fully qualified names of the desired classes.
Throws:
Returns:

the Class object array for the classes with the specified names.

forObjects
public static Class[] forObjects(Object[] objs)

Returns the Class object array associated with the class or interface with the given object array.

Parameters:
  • objs – the objects of the desired classes.
Returns:

the Class object array for the classes with the specified objects.

toArray
public static String[] toArray(String s, String delim)

Tokenizes a string by the specified delimiter(s) and converts it into a string array.

Parameters:
  • s – the string to be tokenized.
  • delim – the delimiter(s).
Returns:

the tokenized strings as a string array.

toArray
public static Object[] toArray(Iterator it)

Converts an iterator into an object array.

Parameters:
  • it – the iterator to be converted.
Returns:

an array representation of the iterator.

toArray
public static Object[] toArray(Iterator it, Object[] a)

Converts an iterator into an object array.

Parameters:
  • it – the iterator to be converted.
  • a – the array into which the elements of this list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
Returns:

an array representation of the iterator.

toArray
public static Object[] toArray(Enumeration enumeration)

Converts an enumeration into an object array.

Parameters:
  • enumeration – the enumeration to be converted.
Returns:

an array representation of the enumeration.

toArray
public static Object[] toArray(Enumeration enumeration, Object[] a)

Converts an enumeration into an object array.

Parameters:
  • enumeration – the enumeration to be converted.
  • a – the array into which the elements of this list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
Returns:

an array representation of the enumeration.

toClasses
public static Class[] toClasses(Object[] objs)

CSVTokenizer

public class CSVTokenizer

CSVTokenizer is a tokenizer which can parses a given CSV and represent its content as multiple rows and columns.

Author:Hugo Y. K. Lam

Constructors

CSVTokenizer
public CSVTokenizer(Reader csv)

Creates a new instance of CSVTokenizer.

Parameters:
  • csv – the CSV content.
Throws:
  • IOException – if unable to read the content from the given reader.
CSVTokenizer
public CSVTokenizer(String csv)

Creates a new instance of CSVTokenizer.

Parameters:
  • csv – the CSV content.

Methods

getColumn
public String getColumn(int pos)

Gets a column’s value.

Parameters:
  • pos – the position of the column.
Returns:

the specified column’s value.

getColumnCount
public int getColumnCount()

Gets the number of columns in the current row.

Returns:the number of columns.
hasMoreRows
public boolean hasMoreRows()

Checks if there are any more rows in this tokenizer.

Returns:true if there are more rows in this tokenizer.
nextRow
public void nextRow()

Proceeds to tokenize the next row.

Caller

public class Caller

A Caller represents the class calling the method which generates this Caller. It retrieves information from the stack trace and is a relatively expensive operation. As a result, it should be used only when there is an absolute need.

Author:Hugo Y. K. Lam

Constructors

Caller
public Caller()

Creates a new instance of Caller.

Caller
public Caller(int backSteps)

Creates a new instance of Caller.

Parameters:
  • backSteps – number of steps backward from the point of the immediate caller in the trace.

Methods

getClassName
public String getClassName()

Gets the name of the calling class.

Returns:the name of the calling class.
getFileName
public String getFileName()

Gets the file name of the calling class.

Returns:the file name of the calling class.
getLineNumber
public int getLineNumber()

Gets the line number in the source file of the caller class at which the call is made.

Returns:the line number in the source file.
getMethodName
public String getMethodName()

Gets the method name of the method, which makes the call, in the caller class.

Returns:the method name.
getName
public static String getName()

Gets the name of the calling class.

Returns:the name of the calling class.
isUnknown
public boolean isUnknown()

Checks if the calling class is undetermined.

Returns:true if the calling class is undetermined.
toString
public String toString()

Returns a string representation of this Caller.

Returns:a string representation of this Caller.

See also: java.lang.Object.toString()

ConsoleLogger

public class ConsoleLogger extends Component implements Logger

ConsoleLogger is a logger which logs messages to System.out and System.err.

Author:Hugo Y. K. Lam

Constructors

ConsoleLogger
public ConsoleLogger()

Creates a new instance of ConsoleLogger.

Methods

debug
public void debug(Object msg)

See also: hk.hku.cecid.piazza.commons.util.Logger.debug(java.lang.Object)

debug
public void debug(Object msg, Throwable throwable)

See also: hk.hku.cecid.piazza.commons.util.Logger.debug(java.lang.Object,java.lang.Throwable)

error
public void error(Object msg)

See also: hk.hku.cecid.piazza.commons.util.Logger.error(java.lang.Object)

error
public void error(Object msg, Throwable throwable)

See also: hk.hku.cecid.piazza.commons.util.Logger.error(java.lang.Object,java.lang.Throwable)

fatal
public void fatal(Object msg)

See also: hk.hku.cecid.piazza.commons.util.Logger.fatal(java.lang.Object)

fatal
public void fatal(Object msg, Throwable throwable)

See also: hk.hku.cecid.piazza.commons.util.Logger.fatal(java.lang.Object,java.lang.Throwable)

getInstance
public static ConsoleLogger getInstance()

Gets the default instance.

Returns:the default instance.
info
public void info(Object msg)

See also: hk.hku.cecid.piazza.commons.util.Logger.info(java.lang.Object)

info
public void info(Object msg, Throwable throwable)

See also: hk.hku.cecid.piazza.commons.util.Logger.info(java.lang.Object,java.lang.Throwable)

warn
public void warn(Object msg)

See also: hk.hku.cecid.piazza.commons.util.Logger.warn(java.lang.Object)

warn
public void warn(Object msg, Throwable throwable)

See also: hk.hku.cecid.piazza.commons.util.Logger.warn(java.lang.Object,java.lang.Throwable)

Convertor

public final class Convertor

A Convertor is mainly responsible for data format conversion.

Author:Hugo Y. K. Lam

Methods

convertObject
public static Object convertObject(Object source, Class target)

Converts the given source Object to an instance of the specified target class. The constructor of the target class which has an argument of the source object type will be looked up first. It it succeeds, the source Object will be passed in as the argument. Otherwise, the constructor which has a String argument will be looked up and the source object will be passed in as a String by calling its toString method. Null will be returned if the conversion cannot be performed.

Parameters:
  • source – the source Object.
  • target – the target class.
Returns:

an instance of the target class representing the given source Object.

deepCopy
public static Object deepCopy(Serializable obj)

Performs a deep copy of the given serializable Object.

Parameters:
  • obj – the serializable Object to be copied.
Returns:

a copy of the given Object.

toFile
public static File toFile(URL url)

Converts a java.net.URL into a java.io.File.

Parameters:
  • url – the java.net.URL to be converted.
Returns:

a java.io.File representing the given URL.

toSQLDate
public static java.sql.Date toSQLDate(java.util.Date date)

Converts a java.util.Date to a java.sql.Date.

Parameters:
  • date – The java.util.Date to be converted.
Returns:

a java.sql.Date representing the given date.

toTimestamp
public static java.sql.Timestamp toTimestamp(java.util.Date date)

Converts a java.util.Date to a java.sql.Timestamp.

Parameters:
  • date – The java.util.Date to be converted.
Returns:

a java.sql.Timestamp representing the given date.

toVector
public static Vector toVector(Object obj)

Converts the given Object to a Vector. If the given Object is already a Vector, the Object will be directly returned. Otherwise, the Oobject will be added to a new Vector and the Vector will be returned.

Parameters:
  • obj – The Object to be converted.
Returns:

The Vector converted by the given Object.

translateProperties
public static void translateProperties(javax.servlet.http.HttpServletRequest request, Object bean)

Translates the request parameters in the given HttpServletRequest to the properties in the given bean Object.

Parameters:
  • request – the HttpServletRequest which contains the request parameters to be translated.
  • bean – the bean Object into which the request parameters to be translated.

DataFormatter

public final class DataFormatter

DataFormatter is a convenient class for formatting objects into or from string. Objects like Date, Time, and Decimal will be formatted according to the following default patterns if none is specified or configured beforehand:

  • date-format: yyyyMMdd
  • time-format: HHmmss
  • datetime-format: yyyyMMddHHmmss
  • timestamp-format: yyyyMMddHHmmssSSS
  • timestamp-suffix: 000
  • decimal-format: 0.00
Author:Hugo Y. K. Lam

Constructors

DataFormatter
public DataFormatter(Properties config)

Creates a new instance of DataFormatter.

Parameters:
  • config – configuration properties of the data format.

Methods

formatDate
public String formatDate(java.util.Date d)

Formats a java.util.Date value into a date String.

Parameters:
  • d – The value to be formatted.
Returns:

The String represenation of the value.

formatDate
public String formatDate(java.util.Date date, String pattern)

Formats a given java.util.Date into a String according to the specified pattern.

Parameters:
  • date – The date to be formatted.
  • pattern – The pattern to be followed in formatting.
Returns:

The formatted String of the date.

formatDate
public String formatDate(java.util.Date date, String pattern, Locale locale)

Formats a given java.util.Date into a String according to the specified pattern.

Parameters:
  • locale – The locale used in formatting.
  • date – The date to be formatted.
  • pattern – The pattern to be followed in formatting.
Returns:

The formatted String of the date.

formatDateTime
public String formatDateTime(java.util.Date d)

Formats a java.util.Date value into a date-time String.

Parameters:
  • d – The value to be formatted.
Returns:

The String represenation of the value.

formatDecimal
public String formatDecimal(double d)

Formats a double value into a String.

Parameters:
  • d – The value to be formatted.
Returns:

The String represenation of the value.

formatDecimal
public String formatDecimal(double d, String pattern)

Formats a given double into a String according to the specified pattern.

Parameters:
  • d – The double to be formatted.
  • pattern – The pattern to be followed in formatting.
Returns:

The formatted String of the double.

formatDecimal
public String formatDecimal(Double d)

Formats a Double value into a String.

Parameters:
  • d – The value to be formatted.
Returns:

The String represenation of the value.

formatTime
public String formatTime(java.util.Date d)

Formats a java.util.Date value into a time String.

Parameters:
  • d – The value to be formatted.
Returns:

The String represenation of the value.

formatTimestamp
public String formatTimestamp(java.util.Date d)

Formats a java.util.Date value into a timestamp String.

Parameters:
  • d – The value to be formatted.
Returns:

The String represenation of the value.

getInstance
public static DataFormatter getInstance()

Gets a default instance of DataFormatter.

Returns:a default instance of DataFormatter.
parseDate
public java.util.Date parseDate(String s)

Parses a date String and formats it into a java.util.Date object.

Parameters:
  • s – The value to be parsed.
Returns:

The Object represenation of the value.

parseDate
public java.util.Date parseDate(String date, String pattern)

Parses a date string and returns a java.util.Date object.

Parameters:
  • date – The date string to be parsed.
  • pattern – The pattern of the date string.
Returns:

A java.util.Date object that represents the given date string.

parseDate
public java.util.Date parseDate(String date, String pattern, Locale locale)

Parses a date string and returns a java.util.Date object.

Parameters:
  • date – The date string to be parsed.
  • pattern – The pattern of the date string.
  • locale – The locale used in parsing the date string.
Returns:

A java.util.Date object that represents the given date string.

parseDateTime
public java.util.Date parseDateTime(String s)

Parses a date-time String and formats it into a java.util.Date object.

Parameters:
  • s – The value to be parsed.
Returns:

The Object represenation of the value.

parseTime
public java.util.Date parseTime(String s)

Parses a time String and formats it into a java.util.Date object.

Parameters:
  • s – The value to be parsed.
Returns:

The Object represenation of the value.

parseTimestamp
public java.util.Date parseTimestamp(String s)

Parses a timestamp String and formats it into a java.util.Date object.

Parameters:
  • s – The value to be parsed.
Returns:

The Object represenation of the value.

Debugger

public final class Debugger

Debugger is a convenient tool for logging different Java objects, like string, collection, map, and etc., on debugging purpose. Since the logging of such objects may be expensive, the logging will only be turned on when the debug flag in the system module attached to this debugger is on.

Author:Hugo Y. K. Lam

Methods

attach
public static synchronized void attach(Module m)

Attach a system module to this debugger. All debugging logs will be logged to the specified system module.

Parameters:
  • m – the system module to be attached.
detach
public static synchronized void detach(Module m)

Detach a system module from this debugger. All debugging logs will be logged to the main system module.

Parameters:
  • m – the system module to be detached.
print
public static void print(Object obj)

Prints debugging logs of the specified object. If the given object is a collection set, like iterator and list, its elements will be printed accordingly.

Parameters:
  • obj – the object to be printed.

Generator

public class Generator

Generator is a convenient class for generating various standard objects. For instance, a message ID which conforms to RFC2822.

Author:Hugo Y. K. Lam

Methods

generateMessageID
public static String generateMessageID()

Generates a message ID which conforms to RFC2822

Returns:the message ID.
generateUUID
public static String generateUUID()

Generates a UUID which conforms to ISO/IEC 11578:1996

Returns:the UUID.

Headers

public class Headers

The Headers class represents the headers of an HTTP URL connection or of the HTTP servlet request and response.

Author:Hugo Y. K. Lam

Constructors

Headers
public Headers(HttpURLConnection connection)

Creates a new instance of Headers.

Parameters:
  • connection – the HTTP connection for getting or setting the headers.
Headers
public Headers(HttpServletRequest request, HttpServletResponse response)

Creates a new instance of Headers.

Parameters:
  • request – the servlet request for getting the headers.
  • response – the servlet response for setting the headers.

Methods

getInputStreamHeaders
public InputStream getInputStreamHeaders()

Gets the headers as an input stream from the underlying request object.

Returns:an input stream of the headers.
getInternetHeaders
public InternetHeaders getInternetHeaders()

Gets the Internet headers from the underlying request object.

Returns:the Internet headers.
getMimeHeaders
public MimeHeaders getMimeHeaders()

Gets the mime headers from the underlying request object.

Returns:the mime headers.
putInternetHeaders
public void putInternetHeaders(InternetHeaders headers)

Puts the Internet headers into the underlying response object.

Parameters:
  • headers – the Internet headers.
putMimeHeaders
public void putMimeHeaders(MimeHeaders headers)

Puts the mime headers into the underlying response object.

Parameters:
  • headers – the mime headers.

Instance

public final class Instance

Instance represents an object instance. It wraps the actual object instance and provides methods for invoking the object’s methods.

Author:Hugo Y. K. Lam

Constructors

Instance
public Instance(Object source)

Creates a new instance of Instance.

Parameters:
  • source – an object instance, its class, or its class name.
Throws:
  • InstanceException – if errors occurred in the creation of the instance.
Instance
public Instance(Object source, ClassLoader loader)

Creates a new instance of Instance.

Parameters:
  • source – an object instance, its class, or its class name.
  • loader – the class loader for loading the instance’s class.
Throws:
  • InstanceException – if errors occurred in the creation of the instance.
Instance
public Instance(Object source, Class[] initargTypes, Object[] initargs)

Creates a new instance of Instance.

Parameters:
  • source – an object instance, its class, or its class name.
  • initargTypes – the constructor’s parameter types.
  • initargs – the constructor’s parameters.
Throws:
  • InstanceException – if errors occurred in the creation of the instance.
Instance
public Instance(Object source, ClassLoader loader, Class[] initargTypes, Object[] initargs)

Creates a new instance of Instance.

Parameters:
  • source – an object instance, its class, or its class name.
  • loader – the class loader for loading the instance’s class.
  • initargTypes – the constructor’s parameter types.
  • initargs – the constructor’s parameters.
Throws:
  • InstanceException – if errors occurred in the creation of the instance.

Methods

getObject
public Object getObject()

Gets the object this instance represents.

Returns:the object this instance represents.
invoke
public Object invoke(String methodName)

Invokes a method in the object that this instance represents.

Parameters:
  • methodName – the method name.
Throws:
  • InstanceException – if the method could not be invoked.
  • InvocationTargetException – if the invoked method has thrown an exception.
Returns:

the object returned by the invoked method.

invoke
public Object invoke(String methodName, Object[] parameters)

Invokes a method in the object that this instance represents.

Parameters:
  • methodName – the method name.
  • parameters – the parameters.
Throws:
  • InstanceException – if the method could not be invoked.
  • InvocationTargetException – if the invoked method has thrown an exception.
Returns:

the object returned by the invoked method.

invoke
public Object invoke(String methodName, Object[] pt, Object[] parameters)

Invokes a method in the object that this instance represents.

Parameters:
  • methodName – the method name.
  • pt – the parameter types.
  • parameters – the parameters.
Throws:
  • InstanceException – if the method could not be invoked.
  • InvocationTargetException – if the invoked method has thrown an exception.
Returns:

the object returned by the invoked method.

isMethodExist
public boolean isMethodExist(String name, Object[] pt)

Check if the specified method exists.

Parameters:
  • name – the method name.
  • pt – the parameter types.
Returns:

true if the specified method exists.

InstanceException

public class InstanceException extends hk.hku.cecid.piazza.commons.GenericException

InstanceException represents all kinds of exception in creating an instance or invoking a method by reflection.

Author:Hugo Y. K. Lam

Constructors

InstanceException
public InstanceException()

Creates a new instance of InstanceException.

InstanceException
public InstanceException(String message)

Creates a new instance of InstanceException.

Parameters:
  • message – the error message.
InstanceException
public InstanceException(Throwable cause)

Creates a new instance of InstanceException.

Parameters:
  • cause – the cause of this exception.
InstanceException
public InstanceException(String message, Throwable cause)

Creates a new instance of InstanceException.

Parameters:
  • message – the error message.
  • cause – the cause of this exception.

Logger

public interface Logger

Logger is a common interface of a logger.

Author:Hugo Y. K. Lam

Methods

debug
public void debug(Object msg)

Logs a debug message.

Parameters:
  • msg – the message to be logged.
debug
public void debug(Object msg, Throwable throwable)

Logs a debug message.

Parameters:
  • msg – the message to be logged.
  • throwable – the associated exception.
error
public void error(Object msg)

Logs an error message.

Parameters:
  • msg – the message to be logged.
error
public void error(Object msg, Throwable throwable)

Logs an error message.

Parameters:
  • msg – the message to be logged.
  • throwable – the associated exception.
fatal
public void fatal(Object msg)

Logs a fatal error message.

Parameters:
  • msg – the message to be logged.
fatal
public void fatal(Object msg, Throwable throwable)

Logs a fatal error message.

Parameters:
  • msg – the message to be logged.
  • throwable – the associated exception.
info
public void info(Object msg)

Logs an informative message.

Parameters:
  • msg – the message to be logged.
info
public void info(Object msg, Throwable throwable)

Logs an informative message.

Parameters:
  • msg – the message to be logged.
  • throwable – the associated exception.
warn
public void warn(Object msg)

Logs a warning error message.

Parameters:
  • msg – the message to be logged.
warn
public void warn(Object msg, Throwable throwable)

Logs a warning error message.

Parameters:
  • msg – the message to be logged.
  • throwable – the associated exception.

LoggerLog4j

public class LoggerLog4j extends PersistentComponent implements hk.hku.cecid.piazza.commons.util.Logger

LoggerLog4j is an implementation of a Logger and is backed by a Log4j logger.

Author:Hugo Y. K. Lam

See also: org.apache.log4j.Logger

Constructors

LoggerLog4j
public LoggerLog4j()

Creates a new instance of LoggerLog4j.

LoggerLog4j
public LoggerLog4j(URL url)

Creates a new instance of LoggerLog4j.

Parameters:
  • url – the url of the configuration file.
Throws:
  • ComponentException – if the configuration could not be loaded from the specified url.
LoggerLog4j
public LoggerLog4j(String name)

Creates a new instance of LoggerLog4j.

Parameters:
  • name – the logger category name. null if the name should be looked up dynamically in logging.
LoggerLog4j
public LoggerLog4j(String name, URL url)

Creates a new instance of LoggerLog4j.

Parameters:
  • name – the logger category name. null if the name should be looked up dynamically in logging.
  • url – the url of the configuration file.
Throws:
  • UtilitiesException – if the configuration could not be loaded from the specified url.

Methods

debug
public void debug(Object msg)

See also: hk.hku.cecid.piazza.commons.util.Logger.debug(java.lang.Object)

debug
public void debug(Object msg, Throwable throwable)

See also: hk.hku.cecid.piazza.commons.util.Logger.debug(java.lang.Object,java.lang.Throwable)

error
public void error(Object msg)

See also: hk.hku.cecid.piazza.commons.util.Logger.error(java.lang.Object)

error
public void error(Object msg, Throwable throwable)

See also: hk.hku.cecid.piazza.commons.util.Logger.error(java.lang.Object,java.lang.Throwable)

fatal
public void fatal(Object msg)

See also: hk.hku.cecid.piazza.commons.util.Logger.fatal(java.lang.Object)

fatal
public void fatal(Object msg, Throwable throwable)

See also: hk.hku.cecid.piazza.commons.util.Logger.fatal(java.lang.Object,java.lang.Throwable)

info
public void info(Object msg)

See also: hk.hku.cecid.piazza.commons.util.Logger.info(java.lang.Object)

info
public void info(Object msg, Throwable throwable)

See also: hk.hku.cecid.piazza.commons.util.Logger.info(java.lang.Object,java.lang.Throwable)

init
protected void init()

Initializes this logger and sets a default logger if specified.

Throws:
  • Exception – if error occurred in initialization.

See also: hk.hku.cecid.piazza.commons.module.Component.init()

isDebugEnabled
public boolean isDebugEnabled()

Checks if the logger itself is in debug mode.

Returns:true if the logger itself is in debug mode.
loading
protected void loading(URL url)

Loads the configuration from the specified url location. A DOM configuration will be triggered if the url ends with ”.xml”.

Parameters:
  • url – the url of the configuration source.
Throws:
  • Exception – if the operation is unsuccessful.

See also: hk.hku.cecid.piazza.commons.module.PersistentComponent.loading(java.net.URL)

warn
public void warn(Object msg)

See also: hk.hku.cecid.piazza.commons.util.Logger.warn(java.lang.Object)

warn
public void warn(Object msg, Throwable throwable)

See also: hk.hku.cecid.piazza.commons.util.Logger.warn(java.lang.Object,java.lang.Throwable)

Messages

public interface Messages

Messages is a common interface of a collection of messages.

Author:Hugo Y. K. Lam

Methods

getDefaultLocale
public String getDefaultLocale()

Gets the default locale of this messenger.

Returns:the default locale.
getDefaultMessage
public String getDefaultMessage()

Gets the default message of this messenger.

Returns:the default message.
getErrorMessage
public String getErrorMessage(String name)

Gets an error message.

Parameters:
  • name – the name of the message.
Returns:

the message with the specified name.

getErrorMessage
public String getErrorMessage(String name, String def)

Gets an error message.

Parameters:
  • name – the name of the message.
  • def – a default message.
Returns:

the message with the specified name.

getMessage
public String getMessage(String name)

Gets a general message.

Parameters:
  • name – the name of the message.
Returns:

the message with the specified name.

getMessage
public String getMessage(String name, String def)

Gets a general message.

Parameters:
  • name – the name of the message.
  • def – a default message.
Returns:

the message with the specified name.

getMessage
public String getMessage(String name, String def, String type)

Gets a message of the specified type.

Parameters:
  • name – the name of the message.
  • def – a default message.
  • type – the type of the message.
Returns:

the message with the specified name.

getMessage
public String getMessage(String name, String def, String type, String locale)

Gets a message of the specified type and locale.

Parameters:
  • name – the name of the message.
  • def – a default message.
  • type – the type of the message.
  • locale – the locale of the message.
Returns:

the message with the specified name.

getWarningMessage
public String getWarningMessage(String name)

Gets a warning message.

Parameters:
  • name – the name of the message.
Returns:

the message with the specified name.

getWarningMessage
public String getWarningMessage(String name, String def)

Gets a warning message.

Parameters:
  • name – the name of the message.
  • def – a default message.
Returns:

the message with the specified name.

setDefaultLocale
public void setDefaultLocale(String locale)

Sets the default locale of this messenger.

Parameters:
  • locale – the default locale
setDefaultMessage
public void setDefaultMessage(String string)

Sets the default message of this messenger.

Parameters:
  • string – the default message.

MessagesTree

public class MessagesTree extends PersistentComponent implements Messages

MessagesTree is an implementation of a Messenger. It represents a messenger with a tree structure and is actually backed by a PropertiesTree object.

Author:Hugo Y. K. Lam

Constructors

MessagesTree
public MessagesTree()

Creates a new instance of MessagesTree.

MessagesTree
public MessagesTree(URL url)

Creates a new instance of MessagesTree.

Parameters:
  • url – the url of the messenger properties source.
Throws:
  • ComponentException – if the properties could not be loaded from the specified url.

Methods

getDefaultLocale
public String getDefaultLocale()

See also: hk.hku.cecid.piazza.commons.util.Messages.getDefaultLocale()

getDefaultMessage
public String getDefaultMessage()

See also: hk.hku.cecid.piazza.commons.util.Messages.getDefaultMessage()

getErrorMessage
public String getErrorMessage(String name)

See also: hk.hku.cecid.piazza.commons.util.Messages.getErrorMessage(java.lang.String)

getErrorMessage
public String getErrorMessage(String name, String def)

See also: hk.hku.cecid.piazza.commons.util.Messages.getErrorMessage(java.lang.String,java.lang.String)

getMessage
public String getMessage(String name)

See also: hk.hku.cecid.piazza.commons.util.Messages.getMessage(java.lang.String)

getMessage
public String getMessage(String name, String def)

See also: hk.hku.cecid.piazza.commons.util.Messages.getMessage(java.lang.String,java.lang.String)

getMessage
public String getMessage(String name, String def, String type)

See also: hk.hku.cecid.piazza.commons.util.Messages.getMessage(java.lang.String,java.lang.String,java.lang.String)

getMessage
public String getMessage(String name, String def, String type, String locale)

See also: hk.hku.cecid.piazza.commons.util.Messages.getMessage(java.lang.String,java.lang.String,java.lang.String,java.lang.String)

getWarningMessage
public String getWarningMessage(String name)

See also: hk.hku.cecid.piazza.commons.util.Messages.getWarningMessage(java.lang.String)

getWarningMessage
public String getWarningMessage(String name, String def)

See also: hk.hku.cecid.piazza.commons.util.Messages.getWarningMessage(java.lang.String,java.lang.String)

loading
protected void loading(URL url)

Loads the messenger properties from the specified url location.

Parameters:
  • url – the url of the messenger properties source.
Throws:
  • Exception – if the operation is unsuccessful.

See also: hk.hku.cecid.piazza.commons.module.PersistentComponent.loading(java.net.URL)

setDefaultLocale
public void setDefaultLocale(String locale)

See also: hk.hku.cecid.piazza.commons.util.Messages.setDefaultLocale(java.lang.String)

setDefaultMessage
public void setDefaultMessage(String string)

See also: hk.hku.cecid.piazza.commons.util.Messages.setDefaultMessage(java.lang.String)

PropertyMap

public class PropertyMap extends PersistentComponent implements PropertySheet

PropertyMap is an implementation of a PropertySheet. It represents a property sheet with a map structure and is actually backed by a Properties object.

Author:Hugo Y. K. Lam

See also: java.util.Properties

Constructors

PropertyMap
public PropertyMap()

Creates a new instance of PropertyMap.

PropertyMap
public PropertyMap(Properties p)

Creates a new instance of PropertyMap.

Parameters:
  • p – the Properties object which backs this map.
PropertyMap
public PropertyMap(URL url)

Creates a new instance of PropertyMap.

Parameters:
  • url – the url of the properties source.
Throws:
  • ComponentException – if the properties could not be loaded from the specified url.

Methods

append
public boolean append(PropertySheet p)

Appends a property sheet to this property map. The specified property sheet can only be appended if it is of the PropertyMap type.

Parameters:
  • p – the property sheet to be appended.
Returns:

true if the operation is successful. false otherwise.

See also: hk.hku.cecid.piazza.commons.util.PropertySheet.append(hk.hku.cecid.piazza.commons.util.PropertySheet)

containsKey
public boolean containsKey(String key)

Checks if the specified key exists in this property map.

Parameters:
  • key – the property key.
Returns:

true if the specified key exists in this property map.

See also: hk.hku.cecid.piazza.commons.util.PropertySheet.containsKey(java.lang.String)

createProperties
public Properties createProperties(String keyPrefix)

Creates a Properties object which stores the properties retrieved by the specified key prefix.

Parameters:
  • keyPrefix – the property key prefix.
Returns:

a Properties object which stores the retrieved properties.

See also: hk.hku.cecid.piazza.commons.util.PropertySheet.createProperties(java.lang.String)

getProperties
public String[] getProperties(String keyPrefix)

Gets a list of properties with the specified key.

Parameters:
  • keyPrefix – the property key prefix.
Returns:

the properties with the specified key.

See also: hk.hku.cecid.piazza.commons.util.PropertySheet.getProperties(java.lang.String)

getProperties
public String[][] getProperties(String keyPrefix, String keySuffixes)

Gets a two-dimensional list of properties with the specified key prefix and key suffixes. The key prefix, along with the suffixes, will define the first dimension of the list while the key suffixes will define the second dimension. E.g.

# Properties content
application.listener1.id=MyListener
application.listener1.name=My Listener
application.listener2.id=MyListener2
application.listener2.name=My Listener 2

Key Prefix: application.listener
Key Suffixes: id,name

Note that the resulted array will be sorted alphabetically according to the original
keys but not the specified key suffixes order or the property values.

Returned array:
{{"MyListener","My Listener"},{"MyListener2","My Listener 2"}}
Parameters:
  • keyPrefix – the property key prefix.
  • keySuffixes – the property key suffixes delimited by either ‘,’, ‘;’ or ‘|’.
Returns:

a two-dimensional list of properties with the specified keys.

See also: hk.hku.cecid.piazza.commons.util.PropertySheet.getProperties(java.lang.String, java.lang.String)

getProperty
public String getProperty(String key)

Gets a property with the specified key.

Parameters:
  • key – the property key.
Returns:

the property with the specified key.

See also: hk.hku.cecid.piazza.commons.util.PropertySheet.getProperty(java.lang.String)

getProperty
public String getProperty(String key, String def)

Gets a property with the specified key.

Parameters:
  • key – the property key.
  • def – the default value.
Returns:

the property with the specified key.

See also: hk.hku.cecid.piazza.commons.util.PropertySheet.getProperty(java.lang.String, java.lang.String)

getPropertyNames
protected String[] getPropertyNames(String keyPrefix)

Gets all property names with the specified key prefix.

Parameters:
  • keyPrefix – the property key prefix.
Returns:

the property names with the specified key prefix.

loading
protected void loading(URL url)

Loads the properties from the specified url location.

Parameters:
  • url – the url of the properties source.
Throws:
  • Exception – if the operation is unsuccessful.

See also: hk.hku.cecid.piazza.commons.module.PersistentComponent.loading(java.net.URL)

propertyNames
public Enumeration propertyNames()

Gets all the existing property names.

Returns:all the existing property names.

See also: hk.hku.cecid.piazza.commons.util.PropertySheet.propertyNames()

removeProperty
public boolean removeProperty(String key)

Removes a property with the specified key.

Parameters:
  • key – the property key.
Returns:

true if the operation is successful. false otherwise.

See also: hk.hku.cecid.piazza.commons.util.PropertySheet.removeProperty(java.lang.String)

setProperty
public boolean setProperty(String key, String value)

Sets a property value with the specified key.

Parameters:
  • key – the property key.
  • value – the property value.
Returns:

true if the operation is successful. false otherwise.

See also: hk.hku.cecid.piazza.commons.util.PropertySheet.setProperty(java.lang.String, java.lang.String)

storing
protected void storing(URL url)

Stores the properties to the specified url location.

Parameters:
  • url – the url of the properties source.
Throws:
  • Exception – if the operation is unsuccessful.

See also: hk.hku.cecid.piazza.commons.module.PersistentComponent.storing(java.net.URL)

PropertySheet

public interface PropertySheet

PropertySheet is a common interface of a properties container.

Author:Hugo Y. K. Lam

Methods

append
public boolean append(PropertySheet p)

Appends a property sheet to this property sheet.

Parameters:
  • p – the property sheet to be appended.
Returns:

true if the operation is successful. false otherwise.

containsKey
public boolean containsKey(String key)

Checks if the specified key exists in this property sheet.

Parameters:
  • key – the property key.
Returns:

true if the specified key exists in this property sheet.

createProperties
public Properties createProperties(String key)

Creates a Properties object which stores the properties retrieved by the specified key.

Parameters:
  • key – the property key.
Returns:

a Properties object which stores the retrieved properties.

getProperties
public String[] getProperties(String key)

Gets a list of properties with the specified key.

Parameters:
  • key – the property key.
Returns:

the properties with the specified key.

getProperties
public String[][] getProperties(String key, String key2)

Gets a two-dimensional list of properties with the specified keys. The first key will define the first dimension of the list and the second key will define the second dimension.

Parameters:
  • key – the first property key.
  • key2 – the second property key.
Returns:

a two-dimensional list of properties with the specified keys.

getProperty
public String getProperty(String key)

Gets a property with the specified key.

Parameters:
  • key – the property key.
Returns:

the property with the specified key.

getProperty
public String getProperty(String key, String def)

Gets a property with the specified key.

Parameters:
  • key – the property key.
  • def – the default value.
Returns:

the property with the specified key.

load
public void load()

Loads the properties from a persistent storage.

Throws:
  • Exception – if the operation is unsuccessful.
propertyNames
public Enumeration propertyNames()

Gets all the existing property names.

Returns:all the existing property names.
removeProperty
public boolean removeProperty(String key)

Removes a property with the specified key.

Parameters:
  • key – the property key.
Returns:

true if the operation is successful. false otherwise.

setProperty
public boolean setProperty(String key, String value)

Sets a property value with the specified key.

Parameters:
  • key – the property key.
  • value – the property value.
Returns:

true if the operation is successful. false otherwise.

store
public void store()

Stores the properties to a persistent storage.

Throws:
  • Exception – if the operation is unsuccessful.

PropertyTree

public class PropertyTree extends PersistentComponent implements PropertySheet

PropertyTree is an implementation of a PropertySheet. It represents a property sheet with a tree structure and is actually backed by a Document object.

Author:Hugo Y. K. Lam

See also: org.dom4j.Document

Constructors

PropertyTree
public PropertyTree()

Creates a new instance of PropertyTree.

PropertyTree
public PropertyTree(URL url)

Creates a new instance of PropertyTree.

Parameters:
  • url – the url of the properties source.
Throws:
  • ComponentException – if the properties could not be loaded from the specified url.
PropertyTree
public PropertyTree(org.w3c.dom.Node node)

Creates a new instance of PropertyTree.

Parameters:
  • node – the root node of the properties source.
Throws:
  • ComponentException – if the properties could not be constructed from the specified node.
PropertyTree
public PropertyTree(InputStream ins)

Creates a new instance of PropertyTree.

Parameters:
  • ins – the input stream of the properties source.
Throws:
  • ComponentException – if the properties could not be loaded from the specified input stream.

Methods

addProperty
protected boolean addProperty(String xpath, String value)

Adds a property to this property tree.

Parameters:
  • xpath – the property xpath.
  • value – the property value.
Returns:

true if the operation is successful. false otherwise.

append
public boolean append(PropertySheet p)

Appends a property sheet to this property tree. The specified property sheet can only be appended if it is of the PropertyTree type.

Parameters:
  • p – the property sheet to be appended.
Returns:

true if the operation is successful. false otherwise.

See also: hk.hku.cecid.piazza.commons.util.PropertySheet.append(hk.hku.cecid.piazza.commons.util.PropertySheet)

containsKey
public boolean containsKey(String xpath)

Checks if the specified xpath exists in this property tree.

Parameters:
  • xpath – the property xpath.
Returns:

true if the specified xpath exists in this property tree.

See also: hk.hku.cecid.piazza.commons.util.PropertySheet.containsKey(java.lang.String)

countProperties
public int countProperties(String xpath)

Counts the number of properties with the specified xpath.

Parameters:
  • xpath – the properties xpath.
Returns:

the number of properties with the specified xpath.

createProperties
public Properties createProperties(String xpath)

Creates a Properties object which stores the properties retrieved by the specified xpath.

Parameters:
  • xpath – the properties xpath.
Returns:

a Properties object which stores the retrieved properties.

See also: hk.hku.cecid.piazza.commons.util.PropertySheet.createProperties(java.lang.String)

getProperties
public String[] getProperties(String xpath)

Gets a list of properties with the specified xpath.

Parameters:
  • xpath – the properties xpath.
Returns:

the properties with the specified xpath.

See also: hk.hku.cecid.piazza.commons.util.PropertySheet.getProperties(java.lang.String)

getProperties
public String[][] getProperties(String xpath, String xpath2)

Gets a two-dimensional list of properties with the specified xpaths. The first xpath will define the first dimension of the list while the second xpath will define the second dimension. E.g.

<!- Properties content -->
<application>
  <listener>
    <id>MyListener</id>
    <name>My Listener</name>
  </listener>
  <listener>
    <id>MyListener2</id>
    <name>My Listener 2</name>
  </listener>
</application>

First xpath: /application/listener
Second xpath: ./id|./name

Returned array:
{{"MyListener","My Listener"},{"MyListener2","My Listener 2"}}
Parameters:
  • xpath – the first xpath.
  • xpath2 – the second xpath.
Returns:

a two-dimensional list of properties with the specified xpaths.

See also: hk.hku.cecid.piazza.commons.util.PropertySheet.getProperties(java.lang.String, java.lang.String)

getProperty
public String getProperty(String xpath)

Gets a property with the specified xpath. If the xpath refers to more than one properpty, the first one will be returned.

Parameters:
  • xpath – the property xpath.
Returns:

the property with the specified xpath.

See also: hk.hku.cecid.piazza.commons.util.PropertySheet.getProperty(java.lang.String)

getProperty
public String getProperty(String xpath, String def)

Gets a property with the specified xpath. If the xpath refers to more than one properpty, the first one will be returned.

Parameters:
  • xpath – the property xpath.
  • def – the default value.
Returns:

the property with the specified xpath.

See also: hk.hku.cecid.piazza.commons.util.PropertySheet.getProperty(java.lang.String, java.lang.String)

getPropertyNode
protected Node getPropertyNode(String xpath)

Gets a property node with the specified xpath. If the xpath refers to more than one properpty node, the first one will be returned.

Parameters:
  • xpath – the property xpath.
Returns:

the property node with the specified xpath.

getPropertyNodes
protected List getPropertyNodes(String xpath)

Gets a list of property nodes with the specified xpath.

Parameters:
  • xpath – the properties xpath.
Returns:

the property nodes with the specified xpath.

getSource
public Source getSource()

Gets the docment source.

Returns:the document source.
loading
protected void loading(URL url)

Loads the properties from the specified url location.

Parameters:
  • url – the url of the properties source.
Throws:
  • Exception – if the operation is unsuccessful.

See also: hk.hku.cecid.piazza.commons.module.PersistentComponent.loading(java.net.URL)

propertyNames
public Enumeration propertyNames()

Gets all the existing property xpaths.

Returns:all the existing property xpaths.

See also: hk.hku.cecid.piazza.commons.util.PropertySheet.propertyNames()

removeProperty
public boolean removeProperty(String xpath)

Removes a property with the specified xpath. If the xpath refers to more than one properpty, the first one will be removed.

Parameters:
  • xpath – the property xpath.
Returns:

true if the operation is successful. false otherwise.

See also: hk.hku.cecid.piazza.commons.util.PropertySheet.removeProperty(java.lang.String)

setProperty
public boolean setProperty(String xpath, String value)

Sets a property value with the specified key.

Parameters:
  • xpath – the property xpath.
  • value – the property value.
Returns:

true if the operation is successful. false otherwise.

See also: hk.hku.cecid.piazza.commons.util.PropertySheet.setProperty(java.lang.String, java.lang.String)

storing
protected void storing(URL url)

Stores the properties to the specified url location.

Parameters:
  • url – the url of the properties source.
Throws:
  • Exception – if the operation is unsuccessful.

See also: hk.hku.cecid.piazza.commons.module.PersistentComponent.storing(java.net.URL)

subtree
public PropertyTree subtree(String xpath)

Creates a sub-tree from this property tree.

Parameters:
  • xpath – the xpath for locating the subtree.
Returns:

a new property tree.

toDocument
public org.w3c.dom.Document toDocument()

Returns a W3C document representation of this property tree.

Returns:a new W3C document.
toString
public String toString()

Returns a string representation of this property tree, which is the XML text.

Returns:a string representation of this property tree.

See also: java.lang.Object.toString()

StringUtilities

public final class StringUtilities

A StringUtilities is a convenient class for handling some common text processing.

Author:Hugo Y. K. Lam

Fields

LINE_SEPARATOR
public static final String LINE_SEPARATOR

Methods

addLeadingCharacter
public static String addLeadingCharacter(String s, char c, int len)

Adds specified leading characters to the specified length. Nothing will be done if the length of the given string is equal to or greater than the specified length.

Parameters:
  • s – the source string.
  • c – the leading character(s) to be added.
  • len – the length of the target string.
Returns:

the string after adding the specified leading character(s).

addLeadingSpace
public static String addLeadingSpace(String s, int len)

Adds leading spaces to the given string to the specified length. Nothing will be done if the length of the given string is equal to or greater than the specified length.

Parameters:
  • s – the source string.
  • len – the length of the target string.
Returns:

the string after adding leading spaces.

addLeadingZero
public static String addLeadingZero(String s, int len)

Adds leading zeros to the given string to the specified length. Nothing will be done if the length of the given string is equal to or greater than the specified length.

Parameters:
  • s – the source string.
  • len – the length of the target string.
Returns:

the string after adding leading zeros.

addPrefix
public static String addPrefix(String s, String prefix)

Adds a prefix to a given string if it does not start with.

Parameters:
  • s – the string to be added.
  • prefix – the prefix.
Returns:

the string with the specified prefix.

addSuffix
public static String addSuffix(String s, String suffix)

Adds a suffix to a given string if it does not end with.

Parameters:
  • s – the string to be added.
  • suffix – the suffix.
Returns:

the string with the specified suffix.

appendCharacter
public static String appendCharacter(String s, char c, int len)

Appends specified characters to the given string to the specified length. Nothing will be done if the length of the given string is equal to or greater than the specified length.

Parameters:
  • s – the source string.
  • c – the character(s) to be appended.
  • len – the length of the target string.
Returns:

@return the string after appending the specified character(s).

appendSpace
public static String appendSpace(String s, int len)

Appends spaces to the given string to the specified length. Nothing will be done if the length of the given string is equal to or greater than the specified length.

Parameters:
  • s – the source string.
  • len – the length of the target string.
Returns:

@return the string after appending spaces.

appendZero
public static String appendZero(String s, int len)

Appends zeros to the given string to the specified length. Nothing will be done if the length of the given string is equal to or greater than the specified length.

Parameters:
  • s – the source string.
  • len – the length of the target string.
Returns:

the string after appending zeros.

concat
public static String concat(String[] tokens, String delim)

Concatenates a string array (string tokens) into a string with the specified delimiter string.

Parameters:
  • tokens – a string array to be concatenated.
  • delim – the delimiter.
Returns:

the concatenated string.

concat
public static String concat(String[] tokens, String tokenPrefix, String tokenSuffix, String delim)

Concatenates a string array (string tokens) into a string with the specified delimiter string, token’s prefix, and token’s suffix.

Parameters:
  • tokens – a string array to be concatenated.
  • tokenPrefix – the token’s prefix to be concatenated.
  • tokenSuffix – the token’s suffix to be concatenated.
  • delim – the delimiter.
Returns:

the concatenated string.

contains
public static boolean contains(String[] tokens, String target)

Checks if a given string array contains the specified search string.

Parameters:
  • tokens – a string array to be searched.
  • target – the target search string.
Returns:

true if the given string array contains the specified search string, false otherwise.

getLength
public static int getLength(String s)

Gets the length of the given string.

Parameters:
  • s – the string.
Returns:

the length of the given string or 0 if it is null.

isAllDigit
public static boolean isAllDigit(String s)

Checks if a given string contains only digits.

Parameters:
  • s – a string to be checked.
Returns:

true if the given string contains only digits, false otherwise.

isEmptyString
public static boolean isEmptyString(String s)

Checks if a given string is null or empty after trimmed.

Parameters:
  • s – the string to be checked.
Returns:

true if the given string is null or empty after trimmed, false otherwise.

isWrappedWith
public static boolean isWrappedWith(String s, String prefix, String suffix)

Checks if the given string is wrapped with the specified prefix and suffix.

Parameters:
  • s – the string to be checked.
  • prefix – the prefix.
  • suffix – the suffix.
Returns:

true if the given string is wrapped with the prefix and suffix.

parseBoolean
public static boolean parseBoolean(String s)

Parses the given string and returns the boolean value it represents.

Parameters:
  • s – the string to be parsed.
Returns:

true if and only if the given string equals, ignoring case, “true”.

parseBoolean
public static boolean parseBoolean(String s, boolean def)

Parses the given string and returns the boolean value it represents.

Parameters:
  • s – the string to be parsed.
  • def – the default boolean value when s is null.
Returns:

true if and only if the given string equals, ignoring case, “true”.

parseDouble
public static double parseDouble(String s)

Parses the given string and returns the double value it represents.

Parameters:
  • s – the string to be parsed.
Returns:

the double value the string represents or Double.NaN if unable to parse the string.

parseDouble
public static double parseDouble(String s, double def)

Parses the given string and returns the double value it represents.

Parameters:
  • s – the string to be parsed.
Returns:

the double value the string represents or the default value if unable to parse the string.

parseInt
public static int parseInt(String s)

Parses the given string and returns the integer value it represents.

Parameters:
  • s – the string to be parsed.
Returns:

the integer value the string represents or Integer.MIN_VALUE if unable to parse the string.

parseInt
public static int parseInt(String s, int def)

Parses the given string and returns the integer value it represents.

Parameters:
  • s – the string to be parsed.
Returns:

the integer value the string represents or the default value if unable to parse the string.

parseLong
public static long parseLong(String s)

Parses the given string and returns the long value it represents.

Parameters:
  • s – the string to be parsed.
Returns:

the long value the string represents or Long.MIN_VALUE if unable to parse the string.

parseLong
public static long parseLong(String s, long def)

Parses the given string and returns the long value it represents.

Parameters:
  • s – the string to be parsed.
Returns:

the long value the string represents or the default value if unable to parse the string.

removeLeadingCharacter
public static String removeLeadingCharacter(String s, char c)

Removes specified leading characters from the given string, if any.

Parameters:
  • s – the source string.
  • c – the leading character(s) to be removed.
Returns:

the string after removing the specified leading character(s).

removeLeadingSpace
public static String removeLeadingSpace(String s)

Removes leading spaces from the given string, if any.

Parameters:
  • s – the source string.
Returns:

the string after removing leading spaces.

removeLeadingZero
public static String removeLeadingZero(String s)

Removes leading zeros from the given string, if any.

Parameters:
  • s – the source string.
Returns:

the string after removing leading zeros.

repeat
public static String repeat(String s, int occurs)

Repeats a given string in the specified number of times, then concatenates and returns it.

Parameters:
  • s – a string to be repeated and concatenated.
  • occurs – the number of times of the given string to be repeated.
Returns:

the concatenated string.

toArray
public static String[] toArray(String s, String delim, int size)

Converts the tokenized string into a string array.

Parameters:
  • s – the string to be tokenized.
  • delim – the delimiters.
  • size – the size of the converted array.
Returns:

the string array.

toArray
public static String[] toArray(String s, int occurs)

Converts a given string into a string array.

Parameters:
  • s – the string to be converted.
  • occurs – the number of occurrences.
Returns:

the string array.

toArray
public static String[] toArray(String s)

Converts a given string into a string array. The resulted array will contain only one element, which is the specified string parameter.

Parameters:
  • s – the string to be converted.
Returns:

the string array.

toCharArray
public static char[] toCharArray(String s)

Converts the given string into an array of characters.

Parameters:
  • s – the string to be converted.
Returns:

an array of characters representing the given string or an empty array if the given string is null or empty.

toGMTString
public static String toGMTString(Date d)

Returns a string representation of the given Date object of the form: d MMM yyyy hh:mm:ss GMT

Parameters:
  • d – the date.
Returns:

the GMT string representation of the given date.

toHexString
public static String toHexString(byte[] b)

To Convert the byte array to the String in Hexdecimal format

Parameters:
  • b – byte array to convert
Throws:
Returns:

String in hexdecimal representation

toString
public static String toString(Throwable e)

Returns a string representation of the given throwable object, empty string if it is null. The resulted string contains a cause trace of the given throwable object.

Parameters:
  • e – the throwable object for getting its string representation.
Returns:

a string represenation of the given Object.

toString
public static String toString(Object obj)

Returns a string representation of the given object, empty string if it is null.

Parameters:
  • obj – the object for getting its string representation.
Returns:

a string represenation of the given Object.

tokenize
public static String[] tokenize(String str, String delim)

Tokenizes a given string according to the specified delimiters. The characters in the delim argument are the delimiters for separating tokens. Delimiter characters themselves will not be treated as tokens.

Parameters:
  • str – a string to be parsed.
  • delim – the delimiters.
Returns:

the tokens in a string array.

tokenize
public static String[] tokenize(String str, int fixedLength)

Tokenizes a given string according to a fixed length. If the last token’s length is less than the fixed length specified, it will be ignored.

Parameters:
  • str – a string to be parsed.
  • fixedLength – the fixed length.
Returns:

the tokens in a string array.

trim
public static String trim(String s)

Trims a given string. An empty string will be returned if the given string is null.

Parameters:
  • s – the string to be trimmed.
Returns:

the trimmed string.

trim
public static String trim(String s, String prefix, String suffix)

Trims the given string. If the given string starts with the specified prefix and ends with the specified suffix, both the prefix and the suffix will be trimmed out.

Parameters:
  • s – the string to be trimmed.
  • prefix – the prefix.
  • suffix – the suffix.
Returns:

the trimmed string.

trimAndVerifySize
public static String trimAndVerifySize(String s, int size)

Trims a given string and then verifies its size against the specified size. If the sizes do not match, null will be returned.

Parameters:
  • s – the string to be trimmed and verified.
  • size – the size for the verification.
Returns:

the trimmed string or null if the size verification failed.

wraps
public static String wraps(String s, String prefix, String suffix)

Wraps a given string with the specified prefix and suffix, if it is not alreay wrapped.

Parameters:
  • s – the string to be wrapped.
  • prefix – the prefix.
  • suffix – the suffix.
Returns:

the wrapped string.

UtilitiesException

public class UtilitiesException extends hk.hku.cecid.piazza.commons.GenericException

UtilitiesException represents all kinds of exception occuring in the utility functions.

Author:Hugo Y. K. Lam

Constructors

UtilitiesException
public UtilitiesException()

Creates a new instance of UtilitiesException.

UtilitiesException
public UtilitiesException(String message)

Creates a new instance of UtilitiesException.

Parameters:
  • message – the error message.
UtilitiesException
public UtilitiesException(Throwable cause)

Creates a new instance of UtilitiesException.

Parameters:
  • cause – the cause of this exception.
UtilitiesException
public UtilitiesException(String message, Throwable cause)

Creates a new instance of UtilitiesException.

Parameters:
  • message – the error message.
  • cause – the cause of this exception.

Zip

public final class Zip

Zip is a tool which can compress a set of files contained in a directory into a zip file. Likewise, it can also extract a set of files compressed in a zip file to a directory.

Author:Hugo Y. K. Lam

Methods

compress
public static void compress(File toFile, File dir)

Compresses a set of files contained in a directory into a zip file.

Parameters:
  • toFile – the zip file.
  • dir – the directory which contains the files to be compressed.
Throws:
extract
public static void extract(File fromFile, File dir)

Extracts a set of files compressed in a zip file to a directory.

Parameters:
  • fromFile – the zip file.
  • dir – the directory to which the files to be extracted. Current user directory will be chosen if it is null.
Throws:

hk.hku.cecid.piazza.commons.xpath

XPathExecutor

public class XPathExecutor

XPathExecutor is an executor which evaluates a given xpath and yields the result.

Example:

XPathExecutor exec = new XPathExecutor(getDocument("doc.xml"));

exec.registerFunction("http://example.com", "sum", new MySum());

System.out.println(exec.eval( "3 + number('3') + eg:sum(3, 4, '5.1') + /values/one  - 2"));

// The result will be '17.1'
Author:Hugo Y. K. Lam

Constructors

XPathExecutor
public XPathExecutor()

Creates a new instance of XPathExecutor.

XPathExecutor
public XPathExecutor(Node document)

Creates a new instance of XPathExecutor.

Parameters:
  • document – the document containing the context being queried and the namespaces being referenced.
XPathExecutor
public XPathExecutor(Node context, Node namespaces)

Creates a new instance of XPathExecutor.

Parameters:
  • context – the document containing the context being queried.
  • namespaces – the document containing the namespaces being referenced.

Methods

eval
public Object eval(String expression)

Evaluates an XPath expression.

Parameters:
  • expression – the XPath expression.
Throws:
  • TransformerException – if unable to transform the expression.
Returns:

the evaluated result.

eval
public Object eval(String expression, Node context)

Evaluates an XPath expression.

Parameters:
  • expression – the XPath expression.
  • context – the document containing the context being queried.
Throws:
  • TransformerException – if unable to transform the expression.
Returns:

the evaluated result.

registerFunction
public void registerFunction(String ns, String funcName, XPathFunction func)

Registers a function to be used in an XPath.

Parameters:
  • ns – the namespace of the function.
  • funcName – the function name.
  • func – the function implementation.
visit
public void visit(String expression, XPathVisitor visitor)

Evaluates an XPath expression.

Parameters:
  • expression – the XPath expression.
  • visitor – the XPath visitor.
Throws:
  • TransformerException – if unable to transform the expression.

XPathFunction

public interface XPathFunction

XPathFunction is an interface of any customized XPath functions.

Author:Hugo Y. K. Lam

Methods

execute
public Object execute(Vector args)

Invoked when evaluating its corresponding function in the XPath.

Parameters:
  • args – the arguments specifed in the XPath.
Returns:

the result after execution.

XPathFunctionsProvider

class XPathFunctionsProvider implements ExtensionsProvider

XPathFunctionsProvider implements the Apache XPath Extensions Provider. It is solely used by the XPathExecutor in building an Apache XPath Context.

Author:Hugo Y. K. Lam

Methods

elementAvailable
public boolean elementAvailable(String ns, String elemName)

Checks if the given element is available.

Parameters:
  • ns – the namespace of the element.
  • elemName – the element name.
Returns:

false in any way.

See also: org.apache.xpath.ExtensionsProvider.elementAvailable(java.lang.String,java.lang.String)

extFunction
public Object extFunction(String ns, String funcName, Vector argVec, Object methodKey)

Executes the extension function.

Parameters:
  • ns – the namespace of the function.
  • funcName – the function name.
  • argVec – the function arguments.
  • methodKey – the method key.
Throws:
  • TransformerException – if the function executed with errors or the function is not available.
Returns:

the execution result.

See also: org.apache.xpath.ExtensionsProvider.extFunction(java.lang.String,java.lang.String,java.util.Vector,java.lang.Object)

extFunction
public Object extFunction(FuncExtFunction funcExtFunction, Vector vec)
functionAvailable
public boolean functionAvailable(String ns, String funcName)

Checks if the given function is available.

Parameters:
  • ns – the namespace of the function.
  • funcName – the function name.
Returns:

true if the given function is available.

See also: org.apache.xpath.ExtensionsProvider.functionAvailable(java.lang.String,java.lang.String)

regsiterFunction
public void regsiterFunction(String ns, String funcName, XPathFunction func)

Registers a function to this provider.

Parameters:
  • ns – the namespace of the function.
  • funcName – the function name.
  • func – the function implementation.

hk.hku.cecid.piazza.corvus.admin.handler

AdminModuleRegistrar

public class AdminModuleRegistrar extends ExtensionPointIteratedHandler

AdminModuleRegistrar handles the registration of an admin module with the default admin pagelet adaptor.

Author:Hugo Y. K. Lam

See also: hk.hku.cecid.piazza.corvus.admin.listener.AdminPageletAdaptor

Methods

processExtension
public void processExtension(Extension extension)

Adds an admin module to the default admin pagelet adaptor.

Parameters:
  • extension – the extension which represents the module to be added.
Throws:

See also: hk.hku.cecid.piazza.commons.spa.ExtensionPointHandler.processExtensions(java.util.Collection)

AdminPageletRegistrar

public class AdminPageletRegistrar extends ExtensionPointIteratedHandler

AdminPageletRegistrar handles the registration of a pagelet with the default admin pagelet adaptor.

Author:Hugo Y. K. Lam

See also: hk.hku.cecid.piazza.corvus.admin.listener.AdminPageletAdaptor

Methods

getPageletStore
protected PageletStore getPageletStore(Extension extension)

Gets the pagelet store this registrar manages.

Parameters:
  • extension – the extension being processed.
Returns:

the pagelet store of the default admin pagelet adaptor.

processExtension
public void processExtension(Extension extension)

Adds a pagelet to the pagelet store that this registrar manages.

Parameters:
  • extension – the extension which represents the pagelet to be added.
Throws:

See also: hk.hku.cecid.piazza.commons.spa.ExtensionPointHandler.processExtensions(java.util.Collection)

AdminPluginHandler

public class AdminPluginHandler implements PluginHandler

AdminPluginHandler is responsible for creating a new HTTP dispatcher context for the admin dispatcher.

Author:Hugo Y. K. Lam

See also: hk.hku.cecid.piazza.commons.servlet.http.HttpDispatcherContext

Fields

ADMIN_CONTEXT_ID
public static final String ADMIN_CONTEXT_ID

The ID of the admin dispatcher context.

API_CONTEXT_ID
public static final String API_CONTEXT_ID

Methods

processActivation
public void processActivation(Plugin plugin)

Processes the admin plugin activation and creates a new HTTP dispatcher context for the admin dispatcher.

Parameters:
  • plugin – the plugin this handler represents.
Throws:

See also: hk.hku.cecid.piazza.commons.spa.PluginHandler.processActivation(hk.hku.cecid.piazza.commons.spa.Plugin)

processDeactivation
public void processDeactivation(Plugin plugin)

Processes the admin plugin deactivation.

Parameters:
  • plugin – the plugin this handler represents.
Throws:

See also: hk.hku.cecid.piazza.commons.spa.PluginHandler.processDeactivation(hk.hku.cecid.piazza.commons.spa.Plugin)

AdminRequestFilterRegistrar

public class AdminRequestFilterRegistrar extends HttpdRequestFilterRegistrar

AdminRequestFilterRegistrar handles the registration of an HTTP request filter with the admin dispatcher context.

Author:Hugo Y. K. Lam

Methods

getHttpdContext
protected HttpDispatcherContext getHttpdContext(Extension extension)

Gets the admin dispatcher context.

See also: hk.hku.cecid.piazza.corvus.core.main.handler.HttpdContextRegistrar.getHttpdContext(hk.hku.cecid.piazza.commons.spa.Extension)

AdminRequestListenerRegistrar

public class AdminRequestListenerRegistrar extends HttpdRequestListenerRegistrar

AdminRequestListenerRegistrar handles the registration of an HTTP request listener with the admin dispatcher context.

Author:Hugo Y. K. Lam

Methods

getHttpdContext
protected HttpDispatcherContext getHttpdContext(Extension extension)

Gets the admin dispatcher context.

See also: hk.hku.cecid.piazza.corvus.core.main.handler.HttpdContextRegistrar.getHttpdContext(hk.hku.cecid.piazza.commons.spa.Extension)

ApiRequestListenerRegistrar

public class ApiRequestListenerRegistrar extends HttpdRequestListenerRegistrar

ApiRequestListenerRegistrar handles the registration of an HTTP request listener with the API dispatcher context.

Author:Patrick Yee

Methods

getHttpdContext
protected HttpDispatcherContext getHttpdContext(Extension extension)

Gets the admin dispatcher context.

See also: hk.hku.cecid.piazza.corvus.core.main.handler.HttpdContextRegistrar.getHttpdContext(hk.hku.cecid.piazza.commons.spa.Extension)

hk.hku.cecid.piazza.corvus.admin.listener

AdminPageletAdaptor

public class AdminPageletAdaptor extends BorderLayoutPageletAdaptor

AdminPageletAdaptor is an HTTP-XSLT pagelet adaptor. It generally serves as a main framework for the admin pages. Pages generated by this pagelet are in border layout format corresponding to the pre-defined template.

Subclasses are expected to override the getCenterSource() method and provide implementation for the generation of the transformation source which contributes to the center region of the page being rendered.

Author:Hugo Y. K. Lam

Fields

ATTR_MESSAGE
protected static final String ATTR_MESSAGE

The attribute name of the message attribute.

ATTR_PREFIX
protected static final String ATTR_PREFIX

The prefix of the attriute name used in this pagelet.

modules
public static final Set modules

The modules of this pagelet.

store
public static final PageletStore store

The pagelet store of this pagelet.

Methods

getCenterSource
protected Source getCenterSource(HttpServletRequest request)

Gets the transformation source of the main body. This method by default generates a transformation source of the system status. Sub-classes should override this method and provide its own implementation.

Parameters:
  • request – the servlet request.
Returns:

the transformation source of the system status.

See also: hk.hku.cecid.piazza.commons.pagelet.xslt.BorderLayoutPageletAdaptor.getCenterSource(javax.servlet.http.HttpServletRequest)

getErrorSource
protected Source getErrorSource(TemplateElement element, Throwable e, HttpServletRequest request)

Gets transformation source which represents the error generated by any of the pagelets composing the page being generated by this pagelet.

See also: hk.hku.cecid.piazza.commons.pagelet.xslt.HttpXsltPageletAdaptor.getErrorSource(TemplateElement,Throwable,HttpServletRequest)

getModuleId
protected String getModuleId(HttpServletRequest request)

Gets the module ID that this pagelet represents. This method will look up the listener parameter ‘module’.

Parameters:
  • request – the servlet request.
Returns:

the module ID.

getNorthSource
protected Source getNorthSource(HttpServletRequest request)

Gets the transformation source of the menu tabs.

See also: hk.hku.cecid.piazza.commons.pagelet.xslt.BorderLayoutPageletAdaptor.getNorthSource(javax.servlet.http.HttpServletRequest)

getPageletStore
protected PageletStore getPageletStore()

See also: hk.hku.cecid.piazza.commons.pagelet.PageletStore

getSouthSource
protected Source getSouthSource(HttpServletRequest request)

Gets the transformation source of the message area. The source will be generated according to the message attribute.

Parameters:
  • request – the servlet request.
Returns:

the transformation source of the message area.

See also: .ATTR_MESSAGE, hk.hku.cecid.piazza.commons.pagelet.xslt.BorderLayoutPageletAdaptor.getSouthSource(javax.servlet.http.HttpServletRequest)

getTabId
protected String getTabId(HttpServletRequest request)

Gets the tab ID that this pagelet represents. This method will look up the listener parameter ‘tab’.

Parameters:
  • request – the servlet request.
Returns:

the tab ID.

getWestSource
protected Source getWestSource(HttpServletRequest request)

Gets the transformation source of the menu modules.

See also: hk.hku.cecid.piazza.commons.pagelet.xslt.BorderLayoutPageletAdaptor.getWestSource(javax.servlet.http.HttpServletRequest)

hk.hku.cecid.piazza.corvus.admin.menu

hk.hku.cecid.piazza.corvus.core

Kernel

public class Kernel

Kernel is the nucleus of Piazza Corvus. It initializes the basic configuration and sets up the plugin registry. After setting up the plugin registry, it activates the plugins and extension points and then Corvus is started.

Author:Hugo Y. K. Lam

Methods

getInstance
public static Kernel getInstance()

Gets the single kernel instance.

Returns:the kernel instance.
getPluginRegistry
public PluginRegistry getPluginRegistry()

Retrieves the plugin registry managed by this kernel.

Returns:the plugin registry.
getStartupTime
public Date getStartupTime()

Retrieves the startup time of this kernel.

Returns:the startup time.
hasErrors
public boolean hasErrors()

Checks whether there were any errors in the start up process of this kernel.

Returns:true if there were any errors in the start up process.
shutdown
public void shutdown()

Shutdowns this kernel and deactivates all the plugin registry.

hk.hku.cecid.piazza.corvus.core.main.admin

AdminMainProcessor

public class AdminMainProcessor implements PluginHandler

The plugin handler for the Admin Main module plugin

Author:Joel Matsumoto

Fields

ACTIVE_MODULE_SCHEDULER
public static String ACTIVE_MODULE_SCHEDULER

Housecleaning Scheduler Active Task module id

core
public static SystemModule core

Methods

getModuleGroup
public static ModuleGroup getModuleGroup()
processActivation
public void processActivation(Plugin plugin)

Activate the module group from the conf files

processDeactivation
public void processDeactivation(Plugin plugin)

Deactivate the modules for this module group

hk.hku.cecid.piazza.corvus.core.main.admin.hc.module

NeoSchedulerTask

public class NeoSchedulerTask extends SchedulerTask

Methods

cleanAS2
protected Transaction cleanAS2(int months)

NeoSchedulerTaskList

public class NeoSchedulerTaskList extends SchedulerTaskList

Methods

getTaskList
public List getTaskList()

SchedulerTask

public class SchedulerTask implements ActiveTask

Fields

DATE_FORMAT
public static final String DATE_FORMAT

Formats

TIME_FORMAT
public static final String TIME_FORMAT

Methods

cleanAS2
protected Transaction cleanAS2(int months)

Attempt to clean out the AS2 database

Parameters:
  • months
Throws:
cleanEBMS
protected Transaction cleanEBMS(int months)

Attempt to clean the EBMS messages.

Parameters:
  • months
Throws:
execute
public void execute()
getMaxRetries
public int getMaxRetries()
getNextRunDateFromNow
public static Date getNextRunDateFromNow(int day_of_week, int hour, int min, int sec)
getRetryInterval
public long getRetryInterval()
isRetryEnabled
public boolean isRetryEnabled()
isSucceedFast
public boolean isSucceedFast()
onAwake
public void onAwake()
onFailure
public void onFailure(Throwable e)
setNextRunDateFromNow
public boolean setNextRunDateFromNow(AdminProperties properties)
setRetried
public void setRetried(int retried)

SchedulerTaskList

public class SchedulerTaskList extends ActiveTaskList

Methods

getTaskList
public List getTaskList()

hk.hku.cecid.piazza.corvus.core.main.admin.hc.util

AdminProperties

public class AdminProperties

A class to wrap the admin.main properties file for easier handling.

Author:Joel Matsumoto

Fields

ADMIN
public static final String ADMIN

The base element for the admin properties file.

CUTOFF_BEFORE
public static final String CUTOFF_BEFORE
DAY
public static final String DAY
EMAIL
public static final String EMAIL
HCPATH
public static final String HCPATH

Properties within the housecleaning element.

HOUSECLEANING
public static final String HOUSECLEANING

Properties within the admin element

LAST_RUN
public static final String LAST_RUN
NEXT_RUN
public static final String NEXT_RUN
ON
public static final String ON
PASSWORD
public static final String PASSWORD
PORT
public static final String PORT
REASON_FAILED
public static final String REASON_FAILED
SMTP
public static final String SMTP
STATUS
public static final String STATUS
TIME
public static final String TIME
USERNAME
public static final String USERNAME

Constructors

AdminProperties
public AdminProperties(PropertyTree tree)

Methods

getCutoff
public int getCutoff()

Return the ‘cutoff’ property if set, else if null or invalid, throw an exception.

Throws:
Returns:

int

getDay
public int getDay()

Return the ‘day’ property or throw an exception if an invalid integer

Throws:
Returns:

int

getElementHC
public String getElementHC(String name)
getEmail
public String getEmail()

Return the ‘email’ property if set or return an empty String. If null throw an exception.

Throws:
Returns:

String

getLastRun
public String getLastRun()

Return the ‘lastrun’ property if set, else return an empty String. If null, throw an exception.

Throws:
Returns:

String

getNextRun
public String getNextRun()

Return the ‘nextrun’ property if set, else return an empty String. If null, throw an exception.

Throws:
Returns:

String

getPassword
public String getPassword()
getPort
public int getPort()

Return the ‘port’ property if set or throw an exception if null/invalid. If the value is not set, will return the deafult, 25;

Throws:
Returns:

int

getReason
public String getReason()

Return the ‘reason’ property if set, else return an empty String. If null, throw an exception.

Throws:
Returns:

String

getSmtp
public String getSmtp()

Return the ‘smtp’ property if set or return an empty String. If null, throw an exception.

Throws:
Returns:

String

getStatus
public String getStatus()

Return the ‘status’ property if set, else return an empty String. If null, throw an exception.

Throws:
Returns:

String

getTime
public String getTime()

Return the ‘time’ property.

Throws:
Returns:

String

getUsername
public String getUsername()

Return the ‘username’ property if set, else return an empty String. If null, throw an exception.

Throws:
Returns:

String

isOn
public boolean isOn()

Return a boolean depending on if the value is set to ON/OFF or return false if none set/null/invalid.

Returns:boolean
setCutoff
public void setCutoff(int cutoff)

Set the property ‘cutoff’.

Parameters:
  • cutoff
setDay
public void setDay(int day)

Set the property ‘day’. 1-7 Sun-Sat

Parameters:
  • day
setElementHC
public void setElementHC(String name, String value)
setEmail
public void setEmail(String email)

Set the property ‘email’.

Parameters:
  • email
setLastRun
public void setLastRun(String lastrun)

Set the property ‘lastrun’.

Parameters:
  • lastrun
setNextRun
public void setNextRun(String nextrun)

Set the property ‘nextrun’.

Parameters:
  • nextrun
setOn
public void setOn(boolean b)

Set the property ‘on’.

Parameters:
  • b
setPassword
public void setPassword(String password)
setPort
public void setPort(int port)

Set the property ‘port’.

Parameters:
  • port
setReason
public void setReason(String reason)

Set the property ‘reason’.

Parameters:
  • reason
setSmtp
public void setSmtp(String smtp)

Set the property ‘smtp’.

Parameters:
  • smtp
setStatus
public void setStatus(String status)

Set the property ‘status’.

Parameters:
  • status
setTime
public void setTime(String time)

Set the property ‘time’.

Parameters:
  • time
setUsername
public void setUsername(String username)

Set the property ‘username’.

Parameters:
  • username
write
public void write()

Writes the property tree to url asscoaited with the component

Throws:
write
public void write(URL u)

Writes to the specified url.

Parameters:
  • u
Throws:

AdminPropertiesException

public class AdminPropertiesException extends Exception

Class to handle exceptions for the AdminProperties class.

Author:Joel Matsumoto

Constructors

AdminPropertiesException
public AdminPropertiesException()
AdminPropertiesException
public AdminPropertiesException(String msg)
AdminPropertiesException
public AdminPropertiesException(String msg, Exception cause)

hk.hku.cecid.piazza.corvus.core.main.admin.listener

CorePropertiesPageletAdaptor

public class CorePropertiesPageletAdaptor extends PropertiesPageletAdaptor

CorePropertiesPageletAdaptor is a properties pagelet adaptor which provides an admin function of the core system properties.

Author:Hugo Y. K. Lam

Methods

addHouseCleaning
protected PropertyTree addHouseCleaning(HttpServletRequest request, PropertyTree dom)

Add the housecleaning data to the XSL tranformation.

Parameters:
  • request
  • dom
Returns:

PropertyTree

getCenterSource
protected Source getCenterSource(HttpServletRequest request)
getProperties
protected PropertySheet getProperties()

Gets the core system properties.

Returns:the core system properties.

See also: hk.hku.cecid.piazza.corvus.core.main.admin.listener.PropertiesPageletAdaptor.getProperties()

HttpdPageletAdaptor

public class HttpdPageletAdaptor extends AdminPageletAdaptor

HttpdPageletAdaptor is an admin pagelet adaptor which provides an admin function of the default HTTP dispatcher.

Author:Hugo Y. K. Lam

Methods

getCenterSource
protected Source getCenterSource(HttpServletRequest request)

Generates the transformation source of the default HTTP dispatcher.

See also: hk.hku.cecid.piazza.corvus.admin.listener.AdminPageletAdaptor.getCenterSource(javax.servlet.http.HttpServletRequest)

ModuleInfoPageletAdaptor

public class ModuleInfoPageletAdaptor extends AdminPageletAdaptor

ModuleInfoPageletAdaptor is an admin pagelet adaptor which provides an admin function of the system modules.

Author:Hugo Y. K. Lam

Methods

getCenterSource
protected Source getCenterSource(HttpServletRequest request)

Generates the transformation source of the system modules.

See also: hk.hku.cecid.piazza.corvus.admin.listener.AdminPageletAdaptor.getCenterSource(javax.servlet.http.HttpServletRequest)

PluginRegistryPageletAdaptor

public class PluginRegistryPageletAdaptor extends AdminPageletAdaptor

PluginRegistryPageletAdaptor is an admin pagelet adaptor which provides an admin function of the plugin registry.

Author:Hugo Y. K. Lam

Methods

getCenterSource
protected Source getCenterSource(HttpServletRequest request)

Generates the transformation source of the plugin regsitry.

See also: hk.hku.cecid.piazza.corvus.admin.listener.AdminPageletAdaptor.getCenterSource(javax.servlet.http.HttpServletRequest)

PropertiesPageletAdaptor

public class PropertiesPageletAdaptor extends AdminPageletAdaptor

PropertiesPageletAdaptor is an admin pagelet adaptor which provides an admin function of the JVM properties. Subclasses can override the getProperties() method and return a compatible properties object for sharing the same admin function.

Author:Hugo Y. K. Lam

Methods

getCenterSource
protected Source getCenterSource(HttpServletRequest request)

Generates the transformation source of the properties.

See also: hk.hku.cecid.piazza.corvus.admin.listener.AdminPageletAdaptor.getCenterSource(javax.servlet.http.HttpServletRequest)

getProperties
protected PropertySheet getProperties()

Gets the properties that this adaptor administrates.

Returns:the JVM properties.
getPropertiesForDisplayAndUpdate
protected PropertyTree getPropertiesForDisplayAndUpdate(HttpServletRequest request, PropertyTree dom)

hk.hku.cecid.piazza.corvus.core.main.handler

HttpdContextListenerRegistrar

public class HttpdContextListenerRegistrar extends HttpdContextRegistrar

HttpdContextListenerRegistrar handles the registration of an HTTP dispatcher context listener with the default HTTP dispatcher context.

Author:Hugo Y. K. Lam

Methods

processExtension
public void processExtension(Extension extension)

Adds an HTTP dispatcher context listener to the default HTTP dispatcher context.

Parameters:
  • extension – the extension which represents the listener.
Throws:

See also: hk.hku.cecid.piazza.commons.spa.ExtensionPointHandler.processExtensions(java.util.Collection)

HttpdContextRegistrar

public abstract class HttpdContextRegistrar extends ExtensionPointIteratedHandler

HttpdContextRegistrar is a generic registrar for any extension point handler which handles reqistration, or alike, with an HTTP dispatcher context.

Author:Hugo Y. K. Lam

Methods

getHttpdContext
protected HttpDispatcherContext getHttpdContext(Extension extension)

Gets the HTTP dispatcher context this registrar manages.

Parameters:
  • extension – the extension being processed.
Returns:

the default HTTP dispatcher context.

HttpdRequestFilterRegistrar

public class HttpdRequestFilterRegistrar extends HttpdContextRegistrar

HttpdRequestFilterRegistrar handles the registration of an HTTP request filter with the default HTTP dispatcher context.

Author:Hugo Y. K. Lam

Methods

processExtension
public void processExtension(Extension extension)

Adds an HTTP request filter to the default HTTP dispatcher context.

Parameters:
  • extension – the extension which represents the filter.
Throws:

See also: hk.hku.cecid.piazza.commons.spa.ExtensionPointHandler.processExtensions(java.util.Collection)

HttpdRequestListenerRegistrar

public class HttpdRequestListenerRegistrar extends HttpdContextRegistrar

HttpdRequestListenerRegistrar handles the registration of an HTTP request listener with the default HTTP dispatcher context.

Author:Hugo Y. K. Lam

Methods

processExtension
public void processExtension(Extension extension)

Adds an HTTP request listener to the default HTTP dispatcher context.

Parameters:
  • extension – the extension which represents the listener.
Throws:

See also: hk.hku.cecid.piazza.commons.spa.ExtensionPointHandler.processExtensions(java.util.Collection)

RemoteCommandRegistrar

public class RemoteCommandRegistrar extends ExtensionPointIteratedHandler

RemoteCommandRegistrar handles the registration of any remote command with the central remote command handler.

Author:Hugo Y. K. Lam

Methods

processExtension
public void processExtension(Extension extension)

Adds a remote command to the central remote command handler.

Parameters:
  • extension – the extension which represents the remote command.
Throws:

See also: hk.hku.cecid.piazza.commons.spa.ExtensionPointHandler.processExtensions(java.util.Collection)

hk.hku.cecid.piazza.corvus.core.main.listener

HttpProxyListener

public class HttpProxyListener extends HttpRequestAdaptor

HttpProxyListener is an HTTP request listener which serves as a simple HTTP proxy handler. It does not support HTTPS nor caching.

Author:Hugo Y. K. Lam

Methods

processRequest
public String processRequest(HttpServletRequest request, HttpServletResponse response)

Perform a simple HTTP proxy operation. No caching will be provided.

See also: hk.hku.cecid.piazza.commons.servlet.http.HttpRequestListener.processRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)

WSPingService

public class WSPingService extends WebServicesAdaptor

WSPingService is a simple web service which provides a ping-pong function.

Author:Hugo Y. K. Lam

Methods

serviceRequested
public SOAPElement[] serviceRequested(SOAPElement[] bodies)

Processes the web service ping and replies with a pong message.

Throws:

hk.hku.cecid.piazza.corvus.core.servlet

StartupServlet

public class StartupServlet extends HttpServlet

StartupServlet is the main startup servlet of Corvus. It will initialize the Corvus kernel once the servlet is being initialized.

Author:Hugo Y. K. Lam

Methods

destroy
public void destroy()

Invoked when the servlet is out of service.

See also: javax.servlet.Servlet.destroy()

init
public void init(ServletConfig config)

Initializes the servlet.

See also: javax.servlet.Servlet.init(javax.servlet.ServletConfig)