airavata-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From patanac...@apache.org
Subject svn commit: r1170897 - in /incubator/airavata/trunk/modules/ws-messenger/common: ./ src/ src/main/ src/main/java/ src/main/java/org/ src/main/java/org/apache/ src/main/java/org/apache/airavata/ src/main/java/org/apache/airavata/wsmg/ src/main/java/org/...
Date Wed, 14 Sep 2011 23:14:16 GMT
Author: patanachai
Date: Wed Sep 14 23:14:15 2011
New Revision: 1170897

URL: http://svn.apache.org/viewvc?rev=1170897&view=rev
Log:
Add Ws-messenger Common

Added:
    incubator/airavata/trunk/modules/ws-messenger/common/
    incubator/airavata/trunk/modules/ws-messenger/common/pom.xml
    incubator/airavata/trunk/modules/ws-messenger/common/src/
    incubator/airavata/trunk/modules/ws-messenger/common/src/main/
    incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/
    incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/
    incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/
    incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/
    incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/
    incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/
    incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/CommonRoutines.java
    incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/MsgBoxNameSpConsts.java
    incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/NotificationProducer.java
    incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/WsmgCommonConstants.java
    incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/WsmgNameSpaceConstants.java
    incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/WsmgVersion.java
    incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/storage/
    incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/storage/ConnectionPool.java
    incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/storage/DatabaseCreator.java
    incubator/airavata/trunk/modules/ws-messenger/common/src/test/
    incubator/airavata/trunk/modules/ws-messenger/common/src/test/java/

Added: incubator/airavata/trunk/modules/ws-messenger/common/pom.xml
URL: http://svn.apache.org/viewvc/incubator/airavata/trunk/modules/ws-messenger/common/pom.xml?rev=1170897&view=auto
==============================================================================
--- incubator/airavata/trunk/modules/ws-messenger/common/pom.xml (added)
+++ incubator/airavata/trunk/modules/ws-messenger/common/pom.xml Wed Sep 14 23:14:15 2011
@@ -0,0 +1,55 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+
+    <parent>
+        <artifactId>airavata-ws-messenger</artifactId>
+        <groupId>airavata</groupId>
+        <version>0.0.1-SNAPSHOT</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+    <name>Messenger Commons</name>
+    <groupId>airavata</groupId>
+    <artifactId>airavata-messenger-commons</artifactId>
+    <url>http://incubator.apache.org/airavata/</url>
+    <packaging>jar</packaging>
+
+    <dependencies>
+        <!-- Logging -->
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-api</artifactId>
+        </dependency>
+        
+        <!-- Axis2 -->
+        <dependency>
+            <groupId>org.apache.axis2</groupId>
+            <artifactId>axis2-kernel</artifactId>
+            <version>${axis2.version}</version>
+        </dependency>
+
+        <!-- Testing -->
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+        </dependency>
+
+    </dependencies>
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-surefire-plugin</artifactId>
+                <version>2.9</version>
+                <configuration>
+                    <systemPropertyVariables>
+                        <propertyName>propertyValue</propertyName>
+                        <buildDirectory>${project.build.directory}</buildDirectory>
+                    </systemPropertyVariables>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+</project>

Added: incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/CommonRoutines.java
URL: http://svn.apache.org/viewvc/incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/CommonRoutines.java?rev=1170897&view=auto
==============================================================================
--- incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/CommonRoutines.java (added)
+++ incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/CommonRoutines.java Wed Sep 14 23:14:15 2011
@@ -0,0 +1,222 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+package org.apache.airavata.wsmg.commons;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Reader;
+import java.io.StringWriter;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.net.SocketAddress;
+import java.net.SocketTimeoutException;
+import java.net.URI;
+import java.net.UnknownHostException;
+import java.text.DateFormat;
+import java.text.DecimalFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.TimeZone;
+
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.stream.XMLStreamWriter;
+
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.axiom.om.util.UUIDGenerator;
+import org.apache.axiom.soap.SOAPEnvelope;
+import org.apache.axiom.soap.SOAPFactory;
+import org.apache.axiom.soap.SOAPHeaderBlock;
+import org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.addressing.EndpointReference;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+
+public class CommonRoutines {
+
+    private static XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
+    private static XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
+
+    // Format date to string like "2004-06-26T21:07:00.000-08:00"
+    public static String getXsdDateTime(Date time) {
+        Date now = time;
+        DateFormat ISO8601Local = new SimpleDateFormat("yyyy-MM-dd'TestNotificationHandler'HH:mm:ss.SSS");
+        TimeZone timeZone = TimeZone.getDefault();
+        ISO8601Local.setTimeZone(timeZone);
+        int offset = timeZone.getOffset(now.getTime());
+        String sign = "+";
+        if (offset < 0) {
+            offset = -offset;
+            sign = "-";
+        }
+        int hours = offset / 3600000;
+        int minutes = (offset - hours * 3600000) / 60000;
+        if (offset != hours * 3600000 + minutes * 60000) {
+            // E.g. TZ=Asia/Riyadh87
+            throw new RuntimeException("TimeZone offset (" + sign + offset + " ms) is not an exact number of minutes");
+        }
+        DecimalFormat twoDigits = new DecimalFormat("00");
+        String ISO8601Now = ISO8601Local.format(now) + sign + twoDigits.format(hours) + ":" + twoDigits.format(minutes);
+        return ISO8601Now;
+    }
+
+    public static SOAPEnvelope reader2SOAPEnvelope(Reader reader) throws XMLStreamException {
+
+        XMLStreamReader inflow = getXMLInputFactory().createXMLStreamReader(reader);
+
+        StAXSOAPModelBuilder builder = new StAXSOAPModelBuilder(inflow);
+        SOAPEnvelope omEnvelope = builder.getSOAPEnvelope();
+        return omEnvelope;
+    }
+
+    private static XMLInputFactory getXMLInputFactory() {
+        return xmlInputFactory;
+    }
+
+    private static XMLOutputFactory getXMLOutputFactory() {
+        return xmlOutputFactory;
+    }
+
+    public static OMElement reader2OMElement(Reader reader) throws XMLStreamException {
+
+        XMLStreamReader inflow = getXMLInputFactory().createXMLStreamReader(reader);
+
+        StAXOMBuilder builder = new StAXOMBuilder(inflow);
+        OMElement omElement = builder.getDocumentElement();
+        return omElement;
+    }
+
+    public static String omToString(OMElement element) {
+
+        StringWriter writer = new StringWriter();
+
+        String ret = null;
+        try {
+            XMLStreamWriter streamWriter = getXMLOutputFactory().createXMLStreamWriter(writer);
+
+            element.serializeAndConsume(streamWriter);
+            streamWriter.flush();
+            ret = writer.toString();
+
+        } catch (Exception e) {
+            throw new RuntimeException("unable to serialize the OMElement", e);
+        }
+        return ret;
+    }
+
+    public static boolean isAvailable(URI address) {
+        // Create a socket with a timeout
+        try {
+            // exclude message box URL from availability check.
+            // if(addressString.indexOf("MsgBox")>0) return true;
+            // How to parse the address to port
+            InetAddress addr = InetAddress.getByName(address.getHost());
+            int port = address.getPort();
+            if (port == -1) { // URI has no port, invalid URI. Here I choose not
+                // to try port 80.
+                return false;
+            }
+            SocketAddress sockaddr = new InetSocketAddress(addr, port);
+
+            // Create an unbound socket
+            Socket sock = new Socket();
+
+            // This method will block no more than timeoutMs.
+            // If the timeout occurs, SocketTimeoutException is thrown.
+            int timeoutMs = 1000; // 2 seconds
+            sock.connect(sockaddr, timeoutMs);
+            sock.close();
+            // System.out.println("Still
+            // availabe:"+address.getHost()+":"+address.getPort());
+        } catch (UnknownHostException e) {
+            // e.printStackTrace();
+            return false;
+        } catch (SocketTimeoutException e) {
+            // e.printStackTrace();
+            return false;
+        } catch (IOException e) {
+            // e.printStackTrace();
+            return false;
+        }
+
+        return true;
+    }
+
+    public static String readFromStream(InputStream in) throws IOException {
+        StringBuffer wsdlStr = new StringBuffer();
+
+        int read;
+
+        byte[] buf = new byte[1024];
+        while ((read = in.read(buf)) > 0) {
+            wsdlStr.append(new String(buf, 0, read));
+        }
+        in.close();
+        return wsdlStr.toString();
+    }
+
+    public static Options getOptions(String soapAction, long timeout, EndpointReference destination) {
+        Options opts = new Options();
+        opts.setProperty(org.apache.axis2.transport.http.HTTPConstants.CHUNKED, Boolean.FALSE);
+        opts.setAction(soapAction);
+
+        opts.setTimeOutInMilliSeconds(timeout);
+        opts.setMessageId(UUIDGenerator.getUUID());
+        opts.setTo(destination);
+
+        return opts;
+    }
+
+    public static void setHeaders(String soapAction, String destination, ServiceClient client,
+            OMElement... customHeaders) throws AxisFault {
+
+        SOAPFactory soapfactory = OMAbstractFactory.getSOAP11Factory();
+
+        SOAPHeaderBlock msgId = soapfactory.createSOAPHeaderBlock("MessageID", WsmgNameSpaceConstants.WSA_NS);
+        msgId.setText(UUIDGenerator.getUUID());
+
+        SOAPHeaderBlock to = soapfactory.createSOAPHeaderBlock("To", WsmgNameSpaceConstants.WSA_NS);
+        to.setText(destination);
+
+        SOAPHeaderBlock action = soapfactory.createSOAPHeaderBlock("Action", WsmgNameSpaceConstants.WSA_NS);
+        action.setText(soapAction);
+
+        client.addHeader(action);
+        client.addHeader(msgId);
+        client.addHeader(to);
+
+        for (OMElement h : customHeaders) {
+            try {
+                client.addHeader(org.apache.axiom.om.util.ElementHelper.toSOAPHeaderBlock(h, soapfactory));
+            } catch (Exception e) {
+                throw AxisFault.makeFault(e);
+            }
+        }
+
+    }
+}

Added: incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/MsgBoxNameSpConsts.java
URL: http://svn.apache.org/viewvc/incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/MsgBoxNameSpConsts.java?rev=1170897&view=auto
==============================================================================
--- incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/MsgBoxNameSpConsts.java (added)
+++ incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/MsgBoxNameSpConsts.java Wed Sep 14 23:14:15 2011
@@ -0,0 +1,34 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+package org.apache.airavata.wsmg.commons;
+
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.OMFactory;
+import org.apache.axiom.om.OMNamespace;
+
+public class MsgBoxNameSpConsts {
+
+    private final static OMFactory factory = OMAbstractFactory.getOMFactory();
+
+    public final static OMNamespace MSG_BOX = factory.createOMNamespace(
+            "http://org.apache.airavata/xgws/msgbox/2004", "msg");
+}

Added: incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/NotificationProducer.java
URL: http://svn.apache.org/viewvc/incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/NotificationProducer.java?rev=1170897&view=auto
==============================================================================
--- incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/NotificationProducer.java (added)
+++ incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/NotificationProducer.java Wed Sep 14 23:14:15 2011
@@ -0,0 +1,132 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+package org.apache.airavata.wsmg.commons;
+
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.OMFactory;
+import org.apache.axiom.om.util.UUIDGenerator;
+import org.apache.axiom.soap.SOAPFactory;
+import org.apache.axiom.soap.SOAPHeaderBlock;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.addressing.EndpointReference;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+
+//import org.apache.airavata.wsmg.WsmgConstants;
+
+//import org.apache.airavata.wsmg.WsmgConstants;
+
+public class NotificationProducer {
+
+    private final OMFactory factory = OMAbstractFactory.getOMFactory();
+    private final SOAPFactory soapfactory = OMAbstractFactory.getSOAP11Factory();
+
+    public NotificationProducer() {
+
+    }
+
+    public synchronized OMElement deliverMessage(OMElement notificationMessage, String type,
+            EndpointReference brokerLocationEPR, long timeout) throws AxisFault {
+
+        ServiceClient client = createServiceClient(type, notificationMessage, brokerLocationEPR, timeout, null);
+
+        OMElement ret = client.sendReceive(notificationMessage);
+        client.cleanupTransport();
+        return ret;
+
+    }
+
+    public synchronized OMElement deliverMessage(OMElement notificationMessage, String type,
+            EndpointReference brokerLocationEPR, long timeout, OMElement topicExpressionEl) throws AxisFault {
+
+        ServiceClient client = createServiceClient(type, notificationMessage, brokerLocationEPR, timeout,
+                topicExpressionEl);
+
+        OMElement ret = client.sendReceive(notificationMessage);
+        client.cleanupTransport();
+        return ret;
+
+    }
+
+    private ServiceClient createServiceClient(String type, OMElement notificationMessage,
+            EndpointReference brokerLocationEPR, long timeout, OMElement topicExpressionEl) throws AxisFault {
+
+        ServiceClient client = new ServiceClient();
+
+        if (client.getAxisConfiguration().getModule(WsmgCommonConstants.AXIS_MODULE_NAME_ADDRESSING) != null) {
+            brokerLocationEPR.addReferenceParameter(topicExpressionEl);
+            client.engageModule(WsmgCommonConstants.AXIS_MODULE_NAME_ADDRESSING);
+        } else {
+            // OMElement msgId = factory.createOMElement("MessageID",
+            // WsmgNameSpaceConstants.WSA_NS);
+            // msgId.setText(UUIDGenerator.getUUID());
+            //
+            // OMElement to = factory.createOMElement("To",
+            // WsmgNameSpaceConstants.WSA_NS);
+            // to.setText(brokerLocationEPR.getAddress());
+            //
+            // OMElement action = factory.createOMElement("Action",
+            // WsmgNameSpaceConstants.WSA_NS);
+            // action.setText("wsnt".equals(type) ?
+            // WsmgNameSpaceConstants.WSNT_NS
+            // .getNamespaceURI()
+            // + "/Notify" : WsmgCommonConstants.WSMG_PUBLISH_SOAP_ACTION);
+
+            SOAPHeaderBlock msgId = soapfactory.createSOAPHeaderBlock("MessageID", WsmgNameSpaceConstants.WSA_NS);
+            msgId.setText(UUIDGenerator.getUUID());
+
+            SOAPHeaderBlock to = soapfactory.createSOAPHeaderBlock("To", WsmgNameSpaceConstants.WSA_NS);
+            to.setText(brokerLocationEPR.getAddress());
+
+            SOAPHeaderBlock action = soapfactory.createSOAPHeaderBlock("Action", WsmgNameSpaceConstants.WSA_NS);
+            action.setText("wsnt".equals(type) ? WsmgNameSpaceConstants.WSNT_NS.getNamespaceURI() + "/Notify"
+                    : WsmgCommonConstants.WSMG_PUBLISH_SOAP_ACTION);
+            if (topicExpressionEl != null) {
+                try {
+                    client.addHeader(org.apache.axiom.om.util.ElementHelper.toSOAPHeaderBlock(topicExpressionEl,
+                            soapfactory));
+                } catch (Exception e) {
+                    throw AxisFault.makeFault(e);
+                }
+            }
+            client.addHeader(action);
+            client.addHeader(msgId);
+            client.addHeader(to);
+
+        }
+
+        Options opts = new Options();
+
+        opts.setAction("wsnt".equals(type) ? WsmgNameSpaceConstants.WSNT_NS.getNamespaceURI() + "/Notify"
+                : WsmgCommonConstants.WSMG_PUBLISH_SOAP_ACTION);
+
+        opts.setTo(brokerLocationEPR);
+        opts.setTimeOutInMilliSeconds(timeout);
+
+        client.setOptions(opts);
+
+        return client;
+
+    }
+
+}

Added: incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/WsmgCommonConstants.java
URL: http://svn.apache.org/viewvc/incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/WsmgCommonConstants.java?rev=1170897&view=auto
==============================================================================
--- incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/WsmgCommonConstants.java (added)
+++ incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/WsmgCommonConstants.java Wed Sep 14 23:14:15 2011
@@ -0,0 +1,108 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+package org.apache.airavata.wsmg.commons;
+
+public class WsmgCommonConstants {
+
+    public static final String AXIS_MODULE_NAME_ADDRESSING = "addressing";
+
+    public final static String VERSION = WsmgVersion.getSpecVersion(); // "0.14";
+
+    public final static String UTF8 = "UTF-8";
+
+    public final static String TOPIC_PREFIX = "topic/";
+
+    public final static String PREFIX = "" + System.currentTimeMillis();
+
+    public final static String SUBSCRIPTION_POLICY = "SubscriptionPolicy";
+
+    public final static String SUBSCRIPTION_ID = "Identifier";
+
+    public final static String WILDCARD_TOPIC = ">";
+
+    public final static String TOPIC_EXPRESSION_SIMPLE_DIALECT = "http://www.ibm.com/xmlns/stdwip/web-services/WS-Topics/TopicExpression/simple";
+    public final static String XPATH_DIALECT = "http://www.w3.org/TR/1999/REC-xpath-19991116";
+    public final static String TOPIC_AND_XPATH_DIALECT = "http://docs.oasis-open.org/wsn";
+
+    public static final String WSMG_PLAIN_TEXT_WRAPPER = "plainTextWrapper";
+
+    public static final int WSRM_POLICY_TRUE = 1;
+
+    public static final int WSRM_POLICY_FALSE = 0;
+
+    public static final String BROKER_SERVICE_LOCATION = "broker.service.location";
+
+    public static final String BROKER_WSMGCONFIG = "broker.wsmgconfig";
+
+    public static final String BROKER_INITED = "broker.inited";
+
+    public static final String EPR_SOURCE_HELPER_TO_OM_GET_EPR_PROPERTIES = "http://www.w3.org/2005/08/addressing";
+
+    public final static String WSN1_0_ActionPrefix = "http://www.ibm.com/xmlns/stdwip";
+
+    public final static String WSN1_2_ActionPrefix = "http://docs.oasis-open.org/wsn";
+
+    public final static String WSN_ActionPrefix = WSN1_2_ActionPrefix;
+
+    public final static String WSMG_PUBLISH_SOAP_ACTION = "http://org.apache.airavata/WseNotification";
+    /**
+     * Constants to switch between different web service Stacks and Transports
+     * 
+     */
+    public static final int BROKER_WEB_SERVICE_STACK_STANDALONE_AXIS2 = 2;
+    public static final int BROKER_WEB_SERVICE_STACK_TOMCAT_AXIS2 = 4;
+
+    public static final String STORAGE_TYPE_IN_MEMORY = "memory";
+    public static final String STORAGE_TYPE_PERSISTANT = "persistent";
+
+    public static final String DELIVERY_METHOD_THREAD_CREW = "pcrew";
+    public static final String DELIVERY_METHOD_PARALLEL = "parallel";
+    public static final String DELIVERY_METHOD_SERIAL = "serial";
+
+    public static final int DEFAULT_SENDING_BATCH_SIZE = 10;
+    public static final int DEFAULT_SENDING_THREAD_POOL_SIZE = 4;
+
+    public static final long DEFAULT_CLIENT_SOCKET_TIME_OUT_MILLIES = 300000L;
+    public static final int DEFAULT_SUBSCRIPTION_EXPIRATION_TIME = 1000 * 60 * 60 * 72; // 72 hours
+
+    public static final String CONFIGURATION_FILE_NAME = "configuration.file.name";
+    public static final String CONFIG_JDBC_URL = "broker.jdbc.url";
+    public static final String CONFIG_JDBC_DRIVER = "broker.jdbc.driver";
+    public static final String CONFIG_START_DELIVERY_THREADS = "broker.start.delivery.thread";
+    public static final String CONFIG_DELIVERY_METHOD = "broker.delivery.method";
+    public static final String CONFIG_STORAGE_TYPE = "broker.storage.type";
+    public static final String CONFIG_SOCKET_TIME_OUT = "broker.socket.timeout";
+    public static final String CONFIG_MAX_MESSAGE_DELIVER_RETRIES = "broker.msg.delivery.retries";
+    public static final String CONFIG_AXIS2_REPO = "axis2.repository";
+    public static final String CONFIG_CONSUMER_URL_EXPIRATION_TIME_GAP = "consumer.expiration.time.gap";
+
+    public static final String CONFIG_SENDING_BATCH_SIZE = "sending.batch.size";
+    public static final String CONFIG_SENDING_THREAD_POOL_SIZE = "sending.thread.pool.size";
+
+    public static final String TABLE_NAME_EXPIRABLE_SUBCRIPTIONS = "subscription";
+    public static final String TABLE_NAME_NON_EXPIRABLE_SUBCRIPTIONS = "specialSubscription";
+
+    public static final String BROKER_CONFIGURATION_FILE_NAME = "msgBroker.properties";
+
+    public static final String DELIVERY_PROTOCOL = "broker.delivery.protocol";
+
+}

Added: incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/WsmgNameSpaceConstants.java
URL: http://svn.apache.org/viewvc/incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/WsmgNameSpaceConstants.java?rev=1170897&view=auto
==============================================================================
--- incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/WsmgNameSpaceConstants.java (added)
+++ incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/WsmgNameSpaceConstants.java Wed Sep 14 23:14:15 2011
@@ -0,0 +1,74 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+package org.apache.airavata.wsmg.commons;
+
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.OMFactory;
+import org.apache.axiom.om.OMNamespace;
+
+public abstract class WsmgNameSpaceConstants {
+
+    public final static String XHTML_NS = null;
+
+    public final static String RESOURCE_ID = "ResourceID";
+
+    public final static OMFactory factory = OMAbstractFactory.getOMFactory();
+
+    public final static OMNamespace WSMG_NS = factory.createOMNamespace(
+            "http://www.collab-ogce.org/ogce/index.php/Messaging", "org.apache.airavata.wsmg");
+
+    public final static OMNamespace WIDGET_NS = factory.createOMNamespace("http://widgets.com", "widget");
+
+    public final static OMNamespace NS_2004_08 = factory.createOMNamespace(
+            "http://schemas.xmlsoap.org/ws/2004/08/addressing", "wa48");
+
+    public final static OMNamespace WSRL_NS = factory.createOMNamespace(
+            "http://www.ibm.com/xmlns/stdwip/web-services/WS-ResourceLifetime", "wsrl");
+
+    public final static OMNamespace WSRP_NS = factory.createOMNamespace(
+            "http://www.ibm.com/xmlns/stdwip/web-services/WS-ResourceProperties", "wsrp");
+    // "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ResourceProperties-1.2-draft-01.xsd");
+
+    public final static OMNamespace WSNT_NS = factory.createOMNamespace(
+            "http://www.ibm.com/xmlns/stdwip/web-services/WS-BaseNotification", "wsnt");
+    // "http://docs.oasis-open.org/wsn/2004/06/wsn-WS-BaseNotification-1.2-draft-01.xsd");
+
+    public final static OMNamespace WSBR_NS = factory.createOMNamespace(
+            "http://www.ibm.com/xmlns/stdwip/web-services/WS-BrokeredNotification", "wsbn");
+
+    public final static OMNamespace WSA_NS = factory.createOMNamespace("http://www.w3.org/2005/08/addressing", "wsa");
+    // "http://schemas.xmlsoap.org/ws/2003/03/addressing");
+    // "http://schemas.xmlsoap.org/ws/2004/03/addressing");
+
+    public final static OMNamespace WSE_NS = factory.createOMNamespace(
+            "http://schemas.xmlsoap.org/ws/2004/08/eventing", "wse");
+
+    public final static OMNamespace SOAP_NS = factory.createOMNamespace("http://schemas.xmlsoap.org/soap/envelope/",
+            "s");
+
+    public final static OMNamespace WSE = factory.createOMNamespace("http://schemas.xmlsoap.org/ws/2004/08/eventing",
+            "wse");
+
+    public final static OMNamespace WSA_2004_NS = factory.createOMNamespace(
+            "http://schemas.xmlsoap.org/ws/2004/08/addressing", "wsa");
+
+}

Added: incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/WsmgVersion.java
URL: http://svn.apache.org/viewvc/incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/WsmgVersion.java?rev=1170897&view=auto
==============================================================================
--- incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/WsmgVersion.java (added)
+++ incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/WsmgVersion.java Wed Sep 14 23:14:15 2011
@@ -0,0 +1,180 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+package org.apache.airavata.wsmg.commons;
+
+public class WsmgVersion {
+
+    public final static String SPEC_VERSION = "1.0.0";
+
+    private final static String BUILD = "";
+
+    private final static String PROJECT_NAME = "WSMG";
+
+    private final static String IMPL_VERSION = SPEC_VERSION + BUILD;
+
+    private final static String USER_AGENT = PROJECT_NAME + "/" + IMPL_VERSION;
+
+    private static int VERSION_MAJOR = -1;
+
+    private static int VERSION_MINOR = -1;
+
+    private static int VERSION_INCREMENT = -1;
+
+    public static String getUserAgent() {
+        return USER_AGENT;
+    }
+
+    public static String getVersion() {
+        return SPEC_VERSION;
+    }
+    
+    public static String getSpecVersion() {
+        return SPEC_VERSION;
+    }
+
+    public static String getImplementationVersion() {
+        return IMPL_VERSION;
+    }
+
+    /**
+     * Print version when exxecuted from command line.
+     */
+    public static void main(String[] args) {
+        String SPEC_OPT = "-spec";
+        String IMPL_OPT = "-impl";
+        if (SPEC_OPT.equals(args[0])) {
+            System.out.println(SPEC_VERSION);
+        } else if (IMPL_OPT.equals(args[0])) {
+            System.out.println(IMPL_VERSION);
+        } else {
+            System.err
+                    .println(WsmgVersion.class.getName() + " Error: " + SPEC_OPT + " or " + IMPL_OPT + " is required");
+            System.exit(1);
+        }
+
+    }
+
+    public static void requireVersionOrExit(String version) {
+        try {
+            requireVersion(version);
+        } catch (Exception ex) {
+            ex.printStackTrace(System.err);
+            System.err.println("Error: could not find required version " + version + " of " + PROJECT_NAME + ": "
+                    + ex.getMessage());
+            System.err.println("Please make sure that JAR file with " + PROJECT_NAME + " with version " + version
+                    + " (or higher) is available.");
+            System.err.println("Please make sure there is no more than one JAR file with " + PROJECT_NAME);
+            System.err.println("Exiting");
+            System.exit(1);
+        }
+    }
+
+    /**
+     * Version mut be of form M.N[.K] where M is major version, N is minor version and K is icrement. This method
+     * returns true if current major version is the same and minor is bigger or equal to current minor verion. If
+     * provided major and minor verisons are equals to current version then increment is also checked and check is
+     * passed when increment is bigger or equal to current increment version.
+     */
+    public static void requireVersion(String version) throws IllegalStateException {
+        // check dependencies
+
+        // NOTE: this is safe as int operations are atomic ...
+        if (VERSION_MAJOR < 0)
+            extractCurrentVersion();
+        int[] parsed;
+        try {
+            parsed = parseVersion(version);
+        } catch (NumberFormatException ex) {
+            throw new IllegalStateException("could not parse " + PROJECT_NAME + " version string " + version);
+        }
+        int major = parsed[0];
+        int minor = parsed[1];
+        int increment = parsed[2];
+
+        if (major != VERSION_MAJOR) {
+            throw new IllegalStateException("required " + PROJECT_NAME + " " + version + " has different major version"
+                    + " from current " + SPEC_VERSION);
+        }
+        if (minor > VERSION_MINOR) {
+            throw new IllegalStateException("required " + PROJECT_NAME + " " + version + " has too big minor version"
+                    + " when compared to current " + SPEC_VERSION);
+        }
+        if (minor == VERSION_MINOR) {
+            if (increment > VERSION_INCREMENT) {
+                throw new IllegalStateException("required " + PROJECT_NAME + " " + version
+                        + " has too big increment version" + " when compared to current " + SPEC_VERSION);
+            }
+        }
+    }
+
+    /**
+     * Parse verion string N.M[.K] into thre subcomponents (M=major,N=minor,K=increment) that are returned in array with
+     * three elements. M and N must be non negative, and K if present must be positive integer. Increment K is optional
+     * and if not present in verion strig it is returned as zero.
+     */
+    public static int[] parseVersion(String version) throws NumberFormatException {
+        int[] parsed = new int[3];
+        int firstDot = version.indexOf('.');
+        if (firstDot == -1) {
+            throw new NumberFormatException("expected version string N.M but there is no dot in " + version);
+        }
+        String majorVersion = version.substring(0, firstDot);
+        parsed[0] = Integer.parseInt(majorVersion);
+        if (parsed[0] < 0) {
+            throw new NumberFormatException("major N version number in N.M can not be negative in " + version);
+        }
+        int secondDot = version.indexOf('.', firstDot + 1);
+        String minorVersion;
+        if (secondDot >= 0) {
+            minorVersion = version.substring(firstDot + 1, secondDot);
+        } else {
+            minorVersion = version.substring(firstDot + 1);
+        }
+        parsed[1] = Integer.parseInt(minorVersion);
+        if (parsed[1] < 0) {
+            throw new NumberFormatException("minor M version number in N.M can not be negative in " + version);
+        }
+        if (secondDot >= 0) {
+            String incrementVersion = version.substring(secondDot + 1);
+            parsed[2] = Integer.parseInt(incrementVersion);
+            if (parsed[2] < 0) {
+                throw new NumberFormatException("increment K version number in N.M.K must be positive number in "
+                        + version);
+            }
+        }
+        return parsed;
+    }
+
+    private static synchronized void extractCurrentVersion() throws IllegalStateException {
+        int[] parsed;
+        try {
+            parsed = parseVersion(SPEC_VERSION);
+        } catch (NumberFormatException ex) {
+            throw new IllegalStateException("internal problem: could not parse current " + PROJECT_NAME
+                    + " version string " + SPEC_VERSION);
+        }
+        VERSION_MAJOR = parsed[0];
+        VERSION_MINOR = parsed[1];
+        VERSION_INCREMENT = parsed[2];
+    }
+
+}

Added: incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/storage/ConnectionPool.java
URL: http://svn.apache.org/viewvc/incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/storage/ConnectionPool.java?rev=1170897&view=auto
==============================================================================
--- incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/storage/ConnectionPool.java (added)
+++ incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/storage/ConnectionPool.java Wed Sep 14 23:14:15 2011
@@ -0,0 +1,343 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+package org.apache.airavata.wsmg.commons.storage;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Vector;
+
+import javax.sql.DataSource;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A class for preallocating, recycling, and managing JDBC connections.
+ */
+public class ConnectionPool implements Runnable {
+    private long MAX_IDLE_TIME = 5 * 60 * 1000; // 5 minutes
+    private String driver, url, username, password, jdbcUrl;
+
+    private int initialConnections, maxConnections;
+
+    private boolean waitIfBusy;
+
+    private Vector availableConnections, busyConnections;
+
+    private boolean connectionPending = false;
+
+    private HashMap lastAccessTimeRecord = new HashMap();
+
+    private String urlType = "";
+
+    private DataSource datasource;
+
+    private boolean autoCommit = true;
+
+    private int transactionIsolation = Connection.TRANSACTION_NONE;
+    static Logger logger = LoggerFactory.getLogger(ConnectionPool.class);
+
+    public ConnectionPool(String driver, String url, String username, String password, int initialConnections,
+            int maxConnections, boolean waitIfBusy) throws SQLException {
+        this(initialConnections, maxConnections, waitIfBusy);
+        this.driver = driver;
+        this.url = url;
+        this.username = username;
+        this.password = password;
+        urlType = "speratedURL";
+        createConnectionPool();
+    }
+
+    public ConnectionPool(String driver, String jdbcUrl, int initialConnections, int maxConnections,
+            boolean waitIfBusy, boolean autoCommit, int transactionIsolation) throws SQLException {
+        this(initialConnections, maxConnections, waitIfBusy);
+        this.driver = driver;
+        this.jdbcUrl = jdbcUrl;
+        urlType = "simpleURL";
+        this.autoCommit = autoCommit;
+        this.transactionIsolation = transactionIsolation;
+        createConnectionPool();
+    }
+
+    public ConnectionPool(String driver, String jdbcUrl, int initialConnections, int maxConnections, boolean waitIfBusy)
+            throws SQLException {
+        this(initialConnections, maxConnections, waitIfBusy);
+        this.driver = driver;
+        this.jdbcUrl = jdbcUrl;
+        urlType = "simpleURL";
+        createConnectionPool();
+    }
+
+    public ConnectionPool(DataSource dataSource, int initialConnections, int maxConnections, boolean waitIfBusy)
+            throws SQLException {
+        this(initialConnections, maxConnections, waitIfBusy);
+        urlType = "dataSource";
+        this.datasource = dataSource;
+        createConnectionPool();
+    }
+
+    protected ConnectionPool(int initialConnections, int maxConnections, boolean waitIfBusy) throws SQLException {
+        this.initialConnections = initialConnections;
+        this.maxConnections = maxConnections;
+        this.waitIfBusy = waitIfBusy;
+        if (initialConnections > maxConnections) {
+            initialConnections = maxConnections;
+        }
+        availableConnections = new Vector(initialConnections);
+        busyConnections = new Vector();
+        CleanUpThread cleanUpThread = new CleanUpThread();
+        new Thread(cleanUpThread).start();
+    }
+
+    private void createConnectionPool() throws SQLException {
+        for (int i = 0; i < initialConnections; i++) {
+            availableConnections.addElement(makeNewConnection());
+        }
+    }
+
+    public synchronized Connection getConnection() throws SQLException {
+        if (!availableConnections.isEmpty()) {
+            Connection existingConnection = (Connection) availableConnections.lastElement();
+            int lastIndex = availableConnections.size() - 1;
+            // System.out.println("ConnectionNo="+lastIndex);
+            availableConnections.removeElementAt(lastIndex);
+
+            ((Long) lastAccessTimeRecord.get(existingConnection)).longValue();
+            // If connection on available list is closed (e.g.,
+            // it timed out), then remove it from available list
+            // and repeat the process of obtaining a connection.
+            // Also wake up threads that were waiting for a
+            // connection because maxConnection limit was reached.
+            if (existingConnection.isClosed()) {
+                notifyAll(); // Freed up a spot for anybody waiting
+                Connection connection = getConnection();
+                setTimeStamp(connection);
+                return (connection);
+            } else {
+                busyConnections.addElement(existingConnection);
+                setTimeStamp(existingConnection);
+                return existingConnection;
+            }
+        } else {
+            // Three possible cases:
+            // 1) You haven't reached maxConnections limit. So
+            // establish one in the background if there isn't
+            // already one pending, then wait for
+            // the next available connection (whether or not
+            // it was the newly established one).
+            // 2) You reached maxConnections limit and waitIfBusy
+            // flag is false. Throw SQLException in such a case.
+            // 3) You reached maxConnections limit and waitIfBusy
+            // flag is true. Then do the same thing as in second
+            // part of step 1: wait for next available connection.
+            if ((totalConnections() < maxConnections) && !connectionPending) {
+                makeBackgroundConnection();
+            } else if (!waitIfBusy) {
+                throw new SQLException("Connection limit reached");
+            }
+            // Wait for either a new connection to be established
+            // (if you called makeBackgroundConnection) or for
+            // an existing connection to be freed up.
+            try {
+                wait();
+            } catch (InterruptedException ie) {
+            }
+            // Someone freed up a connection, so try again.
+            Connection connection = getConnection();
+            setTimeStamp(connection);
+            return connection;
+        }
+    }
+
+    // You can't just make a new connection in the foreground
+    // when none are available, since this can take several
+    // seconds with a slow network connection. Instead,
+    // start a thread that establishes a new connection,
+    // then wait. You get woken up either when the new connection
+    // is established or if someone finishes with an existing
+    // connection.
+    private void makeBackgroundConnection() {
+        connectionPending = true;
+        try {
+            Thread connectThread = new Thread(this);
+            connectThread.start();
+        } catch (OutOfMemoryError oome) {
+            // Give up on new connection
+        }
+    }
+
+    public void run() {
+        try {
+            Connection connection = makeNewConnection();
+            synchronized (this) {
+                availableConnections.addElement(connection);
+                connectionPending = false;
+                notifyAll();
+            }
+        } catch (Exception e) { // SQLException or OutOfMemory
+            // Give up on new connection and wait for existing one
+            // to free up.
+        }
+    }
+
+    // This explicitly makes a new connection. Called in
+    // the foreground when initializing the ConnectionPool,
+    // and called in the background when running.
+    private Connection makeNewConnection() throws SQLException {
+        try {
+            // Load database driver if not already loaded
+            Class.forName(driver);
+            Connection connection;
+            // Establish network connection to database
+            if (urlType.equals("speratedURL")) {
+                connection = DriverManager.getConnection(url, username, password);
+            } else if (urlType.equals("simpleURL")) {
+                connection = DriverManager.getConnection(jdbcUrl);
+            } else { // if(urlType.equals("dataSource")){
+                connection = datasource.getConnection();
+
+            }
+            connection.setTransactionIsolation(this.transactionIsolation);
+            connection.setAutoCommit(this.autoCommit);
+            setTimeStamp(connection);
+            return connection;
+        } catch (ClassNotFoundException cnfe) {
+            // Simplify try/catch blocks of people using this by
+            // throwing only one exception type.
+            throw new SQLException("Can't find class for driver: " + driver);
+        }
+    }
+
+    private void setTimeStamp(Connection connection) {
+        lastAccessTimeRecord.put(connection, Long.valueOf(System.currentTimeMillis()));
+    }
+
+    // The database connection cannot be left idle for too long, otherwise TCP connection will be broken.
+    /**
+     * From http://forums.mysql.com/read.php?39,28450,57460#msg-57460 Okay, then it looks like wait_timeout on the
+     * server is killing your connection (it is set to 8 hours of idle time by default). Either set that value higher on
+     * your server, or configure your connection pool to not hold connections idle that long (I prefer the latter). Most
+     * folks I know that run MySQL with a connection pool in high-load production environments only let connections sit
+     * idle for a matter of minutes, since it only takes a few milliseconds to open a connection, and the longer one
+     * sits idle the more chance it will go "bad" because of a network hiccup or the MySQL server being restarted.
+     * 
+     * @throws SQLException
+     */
+    private boolean isConnectionStale(Connection connection) throws SQLException {
+        long currentTime = System.currentTimeMillis();
+        long lastAccess = ((Long) lastAccessTimeRecord.get(connection)).longValue();
+        if (currentTime - lastAccess > MAX_IDLE_TIME) {
+            // connection.close();
+            // System.out.println("*************JDBC Connection Stale!");
+            return true;
+        } else
+            return false;
+    }
+
+    private void closeStaleConnections() throws SQLException {
+        // close idle connections
+        Iterator iter = availableConnections.iterator();
+        while (iter.hasNext()) {
+            Connection existingConnection = (Connection) iter.next();
+            if (isConnectionStale(existingConnection)) {
+                existingConnection.close();
+                iter.remove();
+            }
+        }
+        // close busy connections that have been checked out for too long.
+        // This should not happen sinc ethis means program has bug for not releasing connections .
+        iter = busyConnections.iterator();
+        while (iter.hasNext()) {
+            Connection busyConnection = (Connection) iter.next();
+            if (isConnectionStale(busyConnection)) {
+                iter.remove();
+                busyConnection.close();
+                logger.warn("****Connection has checked out too long. Forced release. Check the program for unReleased connection.");
+            }
+        }
+    }
+
+    public synchronized void free(Connection connection) {
+        busyConnections.removeElement(connection);
+        availableConnections.addElement(connection);
+        // Wake up threads that are waiting for a connection
+        notifyAll();
+    }
+
+    public synchronized int totalConnections() {
+        return (availableConnections.size() + busyConnections.size());
+    }
+
+    /**
+     * Close all the connections. Use with caution: be sure no connections are in use before calling. Note that you are
+     * not <I>required</I> to call this when done with a ConnectionPool, since connections are guaranteed to be closed
+     * when garbage collected. But this method gives more control regarding when the connections are closed.
+     */
+    public synchronized void closeAllConnections() {
+        closeConnections(availableConnections);
+        availableConnections = new Vector();
+        closeConnections(busyConnections);
+        busyConnections = new Vector();
+        lastAccessTimeRecord.clear();
+    }
+
+    private void closeConnections(Vector connections) {
+        try {
+            for (int i = 0; i < connections.size(); i++) {
+                Connection connection = (Connection) connections.elementAt(i);
+                if (!connection.isClosed()) {
+                    connection.close();
+                }
+            }
+        } catch (SQLException sqle) {
+            // Ignore errors; garbage collect anyhow
+        }
+    }
+
+    public synchronized String toString() {
+        String info = "ConnectionPool(" + url + "," + username + ")" + ", available=" + availableConnections.size()
+                + ", busy=" + busyConnections.size() + ", max=" + maxConnections;
+        return (info);
+    }
+
+    class CleanUpThread implements Runnable {
+        public void run() {
+            while (true) {
+                try {
+                    Thread.sleep(MAX_IDLE_TIME);
+                } catch (InterruptedException e) {
+                    logger.warn(e.getMessage(), e);
+                }
+                try {
+                    closeStaleConnections();
+                } catch (SQLException e) {
+                    logger.warn(e.getMessage(), e);
+                    // e.printStackTrace();
+                }
+            }
+        }
+    }
+
+}

Added: incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/storage/DatabaseCreator.java
URL: http://svn.apache.org/viewvc/incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/storage/DatabaseCreator.java?rev=1170897&view=auto
==============================================================================
--- incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/storage/DatabaseCreator.java (added)
+++ incubator/airavata/trunk/modules/ws-messenger/common/src/main/java/org/apache/airavata/wsmg/commons/storage/DatabaseCreator.java Wed Sep 14 23:14:15 2011
@@ -0,0 +1,466 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.airavata.wsmg.commons.storage;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.io.*;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.SQLWarning;
+import java.sql.Statement;
+import java.util.StringTokenizer;
+
+/**
+ * This class creates the database tables required for messagebox and messagebroker with default configuration
+ * this class creates embedded derby database in local file system. User can specify required database in appropriate
+ * properties files.
+ */
+public class DatabaseCreator {
+
+    private static Log log = LogFactory.getLog(DatabaseCreator.class);
+    private ConnectionPool connectionPool;
+    private String delimiter = ";";
+    Connection conn = null;
+    Statement statement;
+
+    public DatabaseCreator(ConnectionPool dataSource) {
+        this.connectionPool = dataSource;
+    }
+
+    /**
+     * Creates database
+     *
+     * @throws Exception
+     */
+    public void createMsgBoxDatabase() throws Exception {
+        try {
+            conn = connectionPool.getConnection();
+            conn.setAutoCommit(false);
+            statement = conn.createStatement();
+            executeMsgBoxSQLScript();
+            conn.commit();
+            if (log.isTraceEnabled()) {
+                log.trace("Airavatatables are created successfully.");
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to create database tables for Airavataresource store. " + e.getMessage();
+            log.fatal(msg, e);
+            throw new Exception(msg, e);
+        } finally {
+            try {
+                if (conn != null) {
+                    conn.close();
+                }
+            } catch (SQLException e) {
+                log.error("Failed to close database connection.", e);
+            }
+        }
+    }
+
+    /**
+     * Creates database
+     *
+     * @throws Exception
+     */
+    public void createMsgBrokerDatabase() throws Exception {
+        try {
+            conn = connectionPool.getConnection();
+            conn.setAutoCommit(false);
+            statement = conn.createStatement();
+            executeMsgBrokerSQLScript();
+            conn.commit();
+            if (log.isTraceEnabled()) {
+                log.trace("Airavatatables are created successfully.");
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to create database tables for Airavataresource store. " + e.getMessage();
+            log.fatal(msg, e);
+            throw new Exception(msg, e);
+        } finally {
+            try {
+                if (conn != null) {
+                    conn.close();
+                }
+            } catch (SQLException e) {
+                log.error("Failed to close database connection.", e);
+            }
+        }
+    }
+
+    /**
+     * Checks whether database tables are created.
+     * @param checkSQL SQL execute during check.
+     * @return <code>true</core> if checkSQL is success, else <code>false</code>.
+     */
+    public boolean isDatabaseStructureCreated(String checkSQL) {
+        try {
+            if (log.isTraceEnabled()) {
+                log.trace("Running a query to test the database tables existence.");
+            }
+            // check whether the tables are already created with a query
+            Connection conn = connectionPool.getConnection();
+            Statement statement = null;
+            try {
+                statement = conn.createStatement();
+                ResultSet rs = statement.executeQuery(checkSQL);
+                if (rs != null) {
+                    rs.close();
+                }
+            } finally {
+                try {
+                    if (statement != null) {
+                        statement.close();
+                    }
+                } catch(SQLException e) {
+                    return false;
+                }
+            }
+        } catch (SQLException e) {
+            return false;
+        }
+
+        return true;
+    }
+
+
+    /**
+     * executes given sql
+     *
+     * @param sql
+     * @throws Exception
+     */
+    private void executeSQL(String sql) throws Exception {
+        // Check and ignore empty statements
+        if ("".equals(sql.trim())) {
+            return;
+        }
+
+        ResultSet resultSet = null;
+        try {
+            if (log.isDebugEnabled()) {
+                log.debug("SQL : " + sql);
+            }
+
+            boolean ret;
+            int updateCount = 0, updateCountTotal = 0;
+            ret = statement.execute(sql);
+            updateCount = statement.getUpdateCount();
+            resultSet = statement.getResultSet();
+            do {
+                if (!ret) {
+                    if (updateCount != -1) {
+                        updateCountTotal += updateCount;
+                    }
+                }
+                ret = statement.getMoreResults();
+                if (ret) {
+                    updateCount = statement.getUpdateCount();
+                    resultSet = statement.getResultSet();
+                }
+            } while (ret);
+
+            if (log.isDebugEnabled()) {
+                log.debug(sql + " : " + updateCountTotal + " rows affected");
+            }
+            SQLWarning warning = conn.getWarnings();
+            while (warning != null) {
+                log.info(warning + " sql warning");
+                warning = warning.getNextWarning();
+            }
+            conn.clearWarnings();
+        } catch (SQLException e) {
+            if (e.getSQLState().equals("X0Y32")) {
+                // eliminating the table already exception for the derby database
+                log.info("Table Already Exists", e);
+            } else {
+                throw new Exception("Error occurred while executing : " + sql, e);
+            }
+        } finally {
+            if (resultSet != null) {
+                try {
+                    resultSet.close();
+                } catch (SQLException e) {
+                    log.error("Error occurred while closing result set.", e);
+                }
+            }
+        }
+    }
+
+    /**
+     * computes relatational database type using database name
+     *
+     * @return String
+     * @throws Exception*
+     */
+    public static String getDatabaseType(Connection conn) throws Exception {
+        String type = null;
+        try {
+            if (conn != null && (!conn.isClosed())) {
+                DatabaseMetaData metaData = conn.getMetaData();
+                String databaseProductName = metaData.getDatabaseProductName();
+                if (databaseProductName.matches("(?i).*derby.*")) {
+                    type = "derby";
+                } else if (databaseProductName.matches("(?i).*mysql.*")) {
+                    type = "mysql";
+                }else {
+                    String msg = "Unsupported database: " + databaseProductName +
+                            ". Database will not be created automatically by the Airavata . " +
+                            "Please create the database using appropriate database scripts for " +
+                            "the database.";
+                    throw new Exception(msg);
+                }
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to create Airavatadatabase." + e.getMessage();
+            log.fatal(msg, e);
+            throw new Exception(msg, e);
+        }
+        return type;
+    }
+    /**
+     * Overloaded method with String input
+     * @return String
+     * @throws Exception*
+     */
+    public static String getDatabaseType(String dbUrl) throws Exception {
+        String type = null;
+        try {
+            if (dbUrl != null) {
+                if (dbUrl.matches("(?i).*derby.*")) {
+                    type = "derby";
+                } else if (dbUrl.matches("(?i).*mysql.*")) {
+                    type = "mysql";
+                }else {
+                    String msg = "Unsupported database: " + dbUrl +
+                            ". Database will not be created automatically by the Airavata. " +
+                            "Please create the database using appropriate database scripts for " +
+                            "the database.";
+                    throw new Exception(msg);
+                }
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to create Airavatadatabase." + e.getMessage();
+            log.fatal(msg, e);
+            throw new Exception(msg, e);
+        }
+        return type;
+    }
+    /**
+     * executes content in SQL script
+     *
+     * @return StringBuffer
+     * @throws Exception
+     */
+    private void executeMsgBoxSQLScript() throws Exception {
+        String databaseType = DatabaseCreator.getDatabaseType(this.conn);
+        boolean keepFormat = false;
+        if ("oracle".equals(databaseType)) {
+            delimiter = "/";
+        } else if ("db2".equals(databaseType)) {
+            delimiter = "/";
+        } else if ("openedge".equals(databaseType)) {
+            delimiter = "/";
+            keepFormat = true;
+        }
+
+        String dbscriptName = getMessageBoxDbScriptLocation(databaseType);
+
+        StringBuffer sql = new StringBuffer();
+        BufferedReader reader = null;
+
+        try {
+            InputStream is = this.getClass().getClassLoader().getResourceAsStream(dbscriptName);
+            reader = new BufferedReader(new InputStreamReader(is));
+            String line;
+            while ((line = reader.readLine()) != null) {
+                line = line.trim();
+                if (!keepFormat) {
+                    if (line.startsWith("//")) {
+                        continue;
+                    }
+                    if (line.startsWith("--")) {
+                        continue;
+                    }
+                    StringTokenizer st = new StringTokenizer(line);
+                    if (st.hasMoreTokens()) {
+                        String token = st.nextToken();
+                        if ("REM".equalsIgnoreCase(token)) {
+                            continue;
+                        }
+                    }
+                }
+                sql.append(keepFormat ? "\n" : " ").append(line);
+
+                // SQL defines "--" as a comment to EOL
+                // and in Oracle it may contain a hint
+                // so we cannot just remove it, instead we must end it
+                if (!keepFormat && line.indexOf("--") >= 0) {
+                    sql.append("\n");
+                }
+                if ((checkStringBufferEndsWith(sql, delimiter))) {
+                    executeSQL(sql.substring(0, sql.length() - delimiter.length()));
+                    sql.replace(0, sql.length(), "");
+                }
+            }
+            // Catch any statements not followed by ;
+            if (sql.length() > 0) {
+                executeSQL(sql.toString());
+            }
+        } catch (IOException e) {
+            log.error("Error occurred while executing SQL script for creating Airavatadatabase", e);
+            throw new Exception("Error occurred while executing SQL script for creating Airavatadatabase", e);
+
+        } finally {
+            if(reader != null){
+                reader.close();
+            }
+        }
+    }
+
+    /**
+     * executes content in SQL script
+     *
+     * @return StringBuffer
+     * @throws Exception
+     */
+    private void executeMsgBrokerSQLScript() throws Exception {
+        String databaseType = DatabaseCreator.getDatabaseType(this.conn);
+        boolean keepFormat = false;
+        if ("oracle".equals(databaseType)) {
+            delimiter = "/";
+        } else if ("db2".equals(databaseType)) {
+            delimiter = "/";
+        } else if ("openedge".equals(databaseType)) {
+            delimiter = "/";
+            keepFormat = true;
+        }
+
+        String dbscriptName = getMessageBrokerDbScriptLocation(databaseType);
+
+        StringBuffer sql = new StringBuffer();
+        BufferedReader reader = null;
+
+        try {
+            InputStream is = this.getClass().getClassLoader().getResourceAsStream(dbscriptName);
+            reader = new BufferedReader(new InputStreamReader(is));
+            String line;
+            while ((line = reader.readLine()) != null) {
+                line = line.trim();
+                if (!keepFormat) {
+                    if (line.startsWith("//")) {
+                        continue;
+                    }
+                    if (line.startsWith("--")) {
+                        continue;
+                    }
+                    StringTokenizer st = new StringTokenizer(line);
+                    if (st.hasMoreTokens()) {
+                        String token = st.nextToken();
+                        if ("REM".equalsIgnoreCase(token)) {
+                            continue;
+                        }
+                    }
+                }
+                sql.append(keepFormat ? "\n" : " ").append(line);
+
+                // SQL defines "--" as a comment to EOL
+                // and in Oracle it may contain a hint
+                // so we cannot just remove it, instead we must end it
+                if (!keepFormat && line.indexOf("--") >= 0) {
+                    sql.append("\n");
+                }
+                if ((checkStringBufferEndsWith(sql, delimiter))) {
+                    executeSQL(sql.substring(0, sql.length() - delimiter.length()));
+                    sql.replace(0, sql.length(), "");
+                }
+            }
+            // Catch any statements not followed by ;
+            if (sql.length() > 0) {
+                executeSQL(sql.toString());
+            }
+        } catch (IOException e) {
+            log.error("Error occurred while executing SQL script for creating Airavatadatabase", e);
+            throw new Exception("Error occurred while executing SQL script for creating Airavatadatabase", e);
+
+        } finally {
+            if(reader != null){
+                reader.close();
+            }
+        }
+    }
+    protected String getMessageBoxDbScriptLocation(String databaseType) {
+        String scriptName = "msgBox-" + databaseType + ".sql";
+        if (log.isDebugEnabled()) {
+            log.debug("Loading database script from :" + scriptName);
+        }
+        return "database_scripts" + File.separator + scriptName;
+    }
+
+    protected String getMessageBrokerDbScriptLocation(String databaseType) {
+        String scriptName = "msgBroker-" + databaseType + ".sql";
+        if (log.isDebugEnabled()) {
+            log.debug("Loading database script from :" + scriptName);
+        }
+        return "database_scripts" + File.separator + scriptName;
+    }
+
+    /**
+     * Checks that a string buffer ends up with a given string. It may sound
+     * trivial with the existing
+     * JDK API but the various implementation among JDKs can make those
+     * methods extremely resource intensive
+     * and perform poorly due to massive memory allocation and copying. See
+     *
+     * @param buffer the buffer to perform the check on
+     * @param suffix the suffix
+     * @return <code>true</code> if the character sequence represented by the
+     *         argument is a suffix of the character sequence represented by
+     *         the StringBuffer object; <code>false</code> otherwise. Note that the
+     *         result will be <code>true</code> if the argument is the
+     *         empty string.
+     */
+    public static boolean checkStringBufferEndsWith(StringBuffer buffer, String suffix) {
+        if (suffix.length() > buffer.length()) {
+            return false;
+        }
+        // this loop is done on purpose to avoid memory allocation performance
+        // problems on various JDKs
+        // StringBuffer.lastIndexOf() was introduced in jdk 1.4 and
+        // implementation is ok though does allocation/copying
+        // StringBuffer.toString().endsWith() does massive memory
+        // allocation/copying on JDK 1.5
+        // See http://issues.apache.org/bugzilla/show_bug.cgi?id=37169
+        int endIndex = suffix.length() - 1;
+        int bufferIndex = buffer.length() - 1;
+        while (endIndex >= 0) {
+            if (buffer.charAt(bufferIndex) != suffix.charAt(endIndex)) {
+                return false;
+            }
+            bufferIndex--;
+            endIndex--;
+        }
+        return true;
+    }
+}



Mime
View raw message