You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@synapse.apache.org by hi...@apache.org on 2011/12/07 13:17:12 UTC
svn commit: r1211407 [2/7] - in /synapse/trunk/java/modules/integration: ./
src/ src/test/ src/test/java/ src/test/java/org/ src/test/java/org/apache/
src/test/java/org/apache/synapse/ src/test/java/org/apache/synapse/samples/
src/test/java/org/apache/...
Added: synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/SynapseTestCase.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/SynapseTestCase.java?rev=1211407&view=auto
==============================================================================
--- synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/SynapseTestCase.java (added)
+++ synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/SynapseTestCase.java Wed Dec 7 12:17:10 2011
@@ -0,0 +1,485 @@
+/*
+ * 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.synapse.samples.framework;
+
+import junit.framework.TestCase;
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.samples.framework.clients.EventSampleClient;
+import org.apache.synapse.samples.framework.clients.MTOMSwASampleClient;
+import org.apache.synapse.samples.framework.clients.StockQuoteSampleClient;
+
+import javax.xml.namespace.QName;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.Properties;
+
+/**
+ * This is the class from which all sample tests are derived. Loads and stores necessary
+ * configuration information. Starts the mediation engine and backend server(s) before each test.
+ * Shuts down running servers after a test is complete.
+ */
+public abstract class SynapseTestCase extends TestCase {
+
+ private static final Log log = LogFactory.getLog(SynapseTestCase.class);
+
+ private SampleConfiguration configuration;
+ private String sampleDescriptor;
+ private int sampleId;
+ private ProcessController pc;
+ private ArrayList<BackEndServerController> backendServerControllers;
+ private OMElement sampleConfigElement;
+
+ private String currentLocation;
+
+ protected SynapseTestCase(int sampleId) {
+ this.sampleId = sampleId;
+ log.info("Creating Synapse TestCase for test " + sampleId);
+ currentLocation = System.getProperty("user.dir") + "/";
+ sampleDescriptor = "/sample" + sampleId + ".xml";
+ configuration = new SampleConfiguration();
+ backendServerControllers = new ArrayList<BackEndServerController>();
+ System.setProperty("java.io.tmpdir", currentLocation + "modules/integration/target/temp");
+ }
+
+ /**
+ * Executed before this test case. That means, this will be executed before each test.
+ * Loads all configuration info. and starts the servers.
+ */
+ public void setUp() {
+ log.info("SynapseTestCase: Performing necessary steps to run test " + sampleId);
+
+ assertTrue("Could not load the global descriptor file for sample " + sampleId,
+ loadDescriptorInfoFile());
+ assertTrue("There are errors in global descriptor file for sample " + sampleId,
+ processDescriptorFile());
+ assertTrue("Could not load synapse configuration settings for the sample " + sampleId,
+ initSynapseConfigInfo());
+ assertTrue("Could not load axis2 configuration settings for the sample " + sampleId,
+ initBackEndServersConfigInfo());
+ assertTrue("Could not load client configuration settings for the sample " + sampleId,
+ initClientConfigInfo());
+
+ if (configuration.getSynapseConfig().isClusteringEnabled()) {
+ assertTrue("Could not properly configure clustering", configureClustering());
+ }
+
+ for (BackEndServerController bsc : backendServerControllers) {
+ if (!bsc.start()) {
+ doCleanup();
+ fail("There was an error starting the server: " + bsc.getServerName());
+ }
+ }
+
+ if (!pc.startProcess()) {
+ doCleanup();
+ fail("There was an error starting synapse server");
+ }
+ }
+
+ /**
+ * Executed after this test case. That means, This will be executed after each test
+ */
+ public void tearDown() {
+ log.info("Test " + sampleId + " is finished");
+ doCleanup();
+ }
+
+ /**
+ * shutting down servers, cleaning temp files
+ */
+ private void doCleanup() {
+ if (pc != null) {
+ log.info("Stopping Synapse");
+ pc.stopProcess();
+ }
+
+ ArrayList<BackEndServerController> clonedControllers = (ArrayList<BackEndServerController>)
+ backendServerControllers.clone();
+ for (BackEndServerController bsc : clonedControllers) {
+ if (bsc instanceof Axis2BackEndServerController) {
+ log.info("Stopping Server: " + bsc.getServerName());
+ bsc.stop();
+ backendServerControllers.remove(bsc);
+ }
+ }
+
+ for (BackEndServerController bsc : backendServerControllers) {
+ log.info("Stopping Server: " + bsc.getServerName());
+ bsc.stop();
+ }
+
+ //cleaning up temp dir
+ try {
+ FileUtils.cleanDirectory(new File(System.getProperty("java.io.tmpdir")));
+ } catch (IOException e) {
+ log.warn("Error while cleaning temp directory", e);
+ }
+ }
+
+ /**
+ * Reads the specific descriptor file for the particular sample
+ * from resource directory
+ *
+ * @return true if the configuration was loaded successfully
+ */
+ private boolean loadDescriptorInfoFile() {
+ log.info("Reading sample descriptor file from " + sampleDescriptor);
+ sampleConfigElement = null;
+ try {
+ InputStream in = this.getClass().getResourceAsStream(sampleDescriptor);
+ if (in == null) {
+ fail("Cannot read sample descriptor file. Verify that it exists in the resource dir");
+ }
+ StAXOMBuilder builder = new StAXOMBuilder(in);
+ sampleConfigElement = builder.getDocumentElement();
+ } catch (Exception e) {
+ log.error("Error loading test descriptor", e);
+ return false;
+ }
+ return sampleConfigElement != null;
+ }
+
+ /**
+ * Checks if sample id is matched
+ *
+ * @return true If the sample ID matches
+ */
+ private boolean processDescriptorFile() {
+ int fileID = -1;
+ Iterator itr = sampleConfigElement.getChildrenWithLocalName(SampleConfigConstants.TAG_SAMPLE_ID);
+ while (itr.hasNext()) {
+ fileID = Integer.parseInt(((OMElement) itr.next()).getText());
+ }
+ itr = sampleConfigElement.getChildrenWithLocalName(SampleConfigConstants.TAG_SAMPLE_NAME);
+ while (itr.hasNext()) {
+ String sampleName = ((OMElement) itr.next()).getText();
+ configuration.setSampleName(sampleName);
+ }
+
+ return sampleId == fileID;
+ }
+
+ /**
+ * Reads and stores synapse specific configuration information from descriptor
+ *
+ * @return true If the initialization is successful
+ */
+ private boolean initSynapseConfigInfo() {
+ Properties synapseProperties = new Properties();
+ OMElement synEle = null;
+ Iterator itr = sampleConfigElement.getChildrenWithLocalName(SampleConfigConstants.TAG_SYNAPSE_CONF);
+ while (itr.hasNext()) {
+ synEle = (OMElement) itr.next();
+ }
+ if (synEle == null) {
+ log.error("Cannot find synapse configuration information in sample descriptor file");
+ return false;
+ } else {
+ itr = synEle.getChildElements();
+ }
+ while (itr.hasNext()) {
+ OMElement ele = (OMElement) itr.next();
+ synapseProperties.setProperty(ele.getLocalName(), ele.getText());
+ }
+ log.info("Initializing Configuration information for synapse server...");
+ String synapseHome = currentLocation;
+
+ String synapseXml = synapseProperties.getProperty(SampleConfigConstants.TAG_SYNAPSE_CONF_XML);
+ String axis2Repo = synapseProperties.getProperty(SampleConfigConstants.TAG_SYNAPSE_CONF_AXIS2_REPO);
+ String axis2Xml = synapseProperties.getProperty(SampleConfigConstants.TAG_SYNAPSE_CONF_AXIS2_XML);
+ Boolean clusteringEnabled = Boolean.parseBoolean(
+ (String) synapseProperties.get(SampleConfigConstants.TAG_ENABLE_CLUSTERING));
+
+ configuration.getSynapseConfig().setServerName("SynapseServerForSample" + sampleId);
+
+ if (synapseXml == null) {
+ log.error("synapse config file must be specified for the sample");
+ return false;
+ } else {
+ configuration.getSynapseConfig().setSynapseXml(synapseHome + synapseXml);
+ }
+ if (axis2Repo == null) {
+ log.info("synapse repository is not specified in the descriptor. using default value...");
+ configuration.getSynapseConfig().setAxis2Repo(synapseHome +
+ SampleConfigConstants.DEFAULT_SYNAPSE_CONF_AXIS2_REPO);
+ } else {
+ configuration.getSynapseConfig().setAxis2Repo(synapseHome + axis2Repo);
+ }
+ if (axis2Xml == null) {
+ log.info("synapse axis2.xml is not specified in the descriptor. using default value...");
+ configuration.getSynapseConfig().setAxis2Xml(synapseHome +
+ SampleConfigConstants.DEFAULT_SYNAPSE_CONF_AXIS2_XML);
+ } else {
+ configuration.getSynapseConfig().setAxis2Xml(synapseHome + axis2Xml);
+ }
+
+ configuration.getSynapseConfig().setSynapseHome(synapseHome);
+ configuration.getSynapseConfig().setClusteringEnabled(clusteringEnabled);
+
+ pc = new SynapseProcessController(configuration.getSynapseConfig());
+ return true;
+ }
+
+ /**
+ * Reads and stores backend server specific configuration information from descriptor
+ *
+ * @return true If the initialization is successful
+ */
+ private boolean initBackEndServersConfigInfo() {
+ OMElement bESConfigEle = null;
+ Iterator itr_BEEle = sampleConfigElement.getChildrenWithLocalName(
+ SampleConfigConstants.TAG_BE_SERVER_CONF);
+ while (itr_BEEle.hasNext()) {
+ bESConfigEle = (OMElement) itr_BEEle.next();
+ }
+ if (bESConfigEle == null) {
+ log.warn("No backend servers are defined");
+ return false;
+ }
+ log.info("Initializing Configuration information for backend servers...");
+
+ // Processing JMS servers
+ Properties jmsProperties = new Properties();
+ Iterator itr_JMS_Servers = bESConfigEle.getChildrenWithLocalName(
+ SampleConfigConstants.TAG_BE_SERVER_CONF_JMS_BROKER);
+ while (itr_JMS_Servers.hasNext()) {
+ OMElement jmsServer = (OMElement) itr_JMS_Servers.next();
+ String serverID = jmsServer.getAttributeValue(new QName("id"));
+ String serverName = "SampleJMSServer" + serverID;
+ configuration.addNewJMSBroker(serverName);
+
+ Iterator serverConfig = jmsServer.getChildElements();
+ while (serverConfig.hasNext()) {
+ OMElement ele = (OMElement) serverConfig.next();
+ jmsProperties.setProperty(ele.getLocalName(), ele.getText());
+ }
+
+ String providerURL = jmsProperties.getProperty(
+ SampleConfigConstants.TAG_BE_SERVER_CONF_JMS_PROVIDER_URL);
+ String initialNF = jmsProperties.getProperty(
+ SampleConfigConstants.TAG_BE_SERVER_CONF_JMS_INITIAL_NAMING_FACTORY);
+
+ if (providerURL == null) {
+ log.info("Using default provider url");
+ configuration.getJMSConfig(serverName).setProviderURL(
+ SampleConfigConstants.DEFAULT_BE_SERVER_CONF_JMS_PROVIDER_URL);
+ } else {
+ configuration.getJMSConfig(serverName).setProviderURL(providerURL);
+ }
+ if (initialNF == null) {
+ log.info("Using default initial naming factory");
+ configuration.getJMSConfig(serverName).setInitialNamingFactory(
+ SampleConfigConstants.DEFAULT_BE_SERVER_CONF_JMS_INITIAL_NAMING_FACTORY);
+ } else {
+ configuration.getJMSConfig(serverName).setInitialNamingFactory(initialNF);
+ }
+
+ configuration.getJMSConfig(serverName).setServerName(serverName);
+
+ backendServerControllers.add(new JMSBrokerController(serverName,
+ configuration.getJMSConfig(serverName)));
+ }
+
+
+ // Processing derby servers
+ Properties derbyProperties = new Properties();
+ Iterator itrDerbyServers = bESConfigEle.getChildrenWithLocalName(
+ SampleConfigConstants.TAG_BE_SERVER_CONF_DERBY_SERVER);
+ while (itrDerbyServers.hasNext()) {
+ OMElement derbyServer = (OMElement) itrDerbyServers.next();
+ String serverID = derbyServer.getAttributeValue(new QName("id"));
+ String serverName = "SampleDerbyServer" + serverID;
+ configuration.addNewDerbyServer(serverName);
+
+ Iterator serverConfig = derbyServer.getChildElements();
+ while (serverConfig.hasNext()) {
+ OMElement ele = (OMElement) serverConfig.next();
+ derbyProperties.setProperty(ele.getLocalName(), ele.getText());
+ }
+
+ configuration.getDerbyConfig(serverName).setServerName(serverName);
+ backendServerControllers.add(new DerbyServerController(serverName,
+ configuration.getDerbyConfig(serverName)));
+ }
+
+ // Processing axis2 servers
+ Properties axis2Properties = new Properties();
+ Iterator itr_Axis2_Servers = bESConfigEle.getChildrenWithLocalName(
+ SampleConfigConstants.TAG_BE_SERVER_CONF_AXIS2_SERVER);
+ while (itr_Axis2_Servers.hasNext()) {
+ OMElement axis2Server = (OMElement) itr_Axis2_Servers.next();
+ String serverID = axis2Server.getAttributeValue(new QName("id"));
+ String serverName = "SampleAxis2Server" + serverID;
+ configuration.addNewAxis2Server(serverName);
+
+ Iterator serverConfig = axis2Server.getChildElements();
+ while (serverConfig.hasNext()) {
+ OMElement ele = (OMElement) serverConfig.next();
+ axis2Properties.setProperty(ele.getLocalName(), ele.getText());
+ }
+ String axis2Home = currentLocation;
+ String relAxis2Repo = axis2Properties.getProperty(
+ SampleConfigConstants.TAG_BE_SERVER_CONF_AXIS2_REPO);
+ String relAxis2Xml = axis2Properties.getProperty(
+ SampleConfigConstants.TAG_BE_SERVER_CONF_AXIS2_XML);
+ String axis2HttpPort = axis2Properties.getProperty(
+ SampleConfigConstants.TAG_BE_SERVER_CONF_AXIS2_HTTP_PORT);
+ String axis2HttpsPort = axis2Properties.getProperty(
+ SampleConfigConstants.TAG_BE_SERVER_CONF_AXIS2_HTTPS_PORT);
+
+ configuration.getAxis2Config(serverName).setServerName(serverName);
+
+ if (relAxis2Repo == null) {
+ log.info("axis2 repository is not specified in the descriptor. using default value...");
+ configuration.getAxis2Config(serverName).setAxis2Repo(axis2Home +
+ SampleConfigConstants.DEFAULT_BE_SERVER_CONF_AXIS2_REPO);
+ } else {
+ configuration.getAxis2Config(serverName).setAxis2Repo(axis2Home + relAxis2Repo);
+ }
+ if (relAxis2Xml == null) {
+ log.info("axis2.xml is not specified in the descriptor. using default value...");
+ configuration.getAxis2Config(serverName).setAxis2Xml(axis2Home +
+ SampleConfigConstants.DEFAULT_BE_SERVER_CONF_AXIS2_XML);
+ } else {
+ configuration.getAxis2Config(serverName).setAxis2Xml(axis2Home + relAxis2Xml);
+ }
+
+ configuration.getAxis2Config(serverName).setHttpPort(axis2HttpPort);
+ configuration.getAxis2Config(serverName).setHttpsPort(axis2HttpsPort);
+
+ backendServerControllers.add(new Axis2BackEndServerController(serverName,
+ configuration.getAxis2Config(serverName)));
+ }
+
+ return true;
+ }
+
+ /*
+ * reads and stores client specific configuration information from descriptor
+ */
+ private boolean initClientConfigInfo() {
+ Properties clientProperties = new Properties();
+ OMElement cliEle = null;
+ Iterator itr = sampleConfigElement.getChildrenWithLocalName(
+ SampleConfigConstants.TAG_CLIENT_CONF);
+ while (itr.hasNext()) {
+ cliEle = (OMElement) itr.next();
+ }
+ if (cliEle == null) {
+ return false;
+ } else {
+ itr = cliEle.getChildElements();
+ }
+ while (itr.hasNext()) {
+ OMElement ele = (OMElement) itr.next();
+ clientProperties.setProperty(ele.getLocalName(), ele.getText());
+ }
+
+ log.info("Initializing Configuration information for clients...");
+ String clientRepo = clientProperties.getProperty(
+ SampleConfigConstants.TAG_CLIENT_CONF_REPO);
+ String clientAxis2Xml = clientProperties.getProperty(
+ SampleConfigConstants.TAG_CLIENT_CONF_AXIS2_XML);
+
+ if (clientRepo == null) {
+ log.info("client repository location is not specified in the descriptor. using default value...");
+ configuration.getClientConfig().setClientRepo(currentLocation +
+ SampleConfigConstants.DEFAULT_CLIENT_CONF_REPO);
+
+ } else {
+ configuration.getClientConfig().setClientRepo(currentLocation + clientRepo);
+ }
+
+ if (clientAxis2Xml == null) {
+ log.info("client axis2.xml is not specified in the descriptor. using default value...");
+ configuration.getClientConfig().setAxis2Xml(currentLocation +
+ SampleConfigConstants.DEFAULT_CLIENT_CONF_AXIS2_XML);
+
+ } else {
+ configuration.getClientConfig().setAxis2Xml(currentLocation + clientAxis2Xml);
+ }
+ return true;
+
+ }
+
+ private boolean configureClustering() {
+ try {
+ String ip = SynapseTestUtils.getIPAddress();
+ if (ip == null || ip.isEmpty()) {
+ log.fatal("Could not detect an active IP address");
+ return false;
+ }
+ log.info(" Using the IP :" + ip);
+
+ String synapseAxis2Xml = configuration.getSynapseConfig().getAxis2Xml();
+ String axis2Config = FileUtils.readFileToString(new File(synapseAxis2Xml));
+ String modifiedSynapseAxis2 = SynapseTestUtils.replace(axis2Config, "${replace.me}", ip);
+ File tempSynapseAxis2 = File.createTempFile("axis2Syn-", "xml");
+ tempSynapseAxis2.deleteOnExit();
+ FileUtils.writeStringToFile(tempSynapseAxis2, modifiedSynapseAxis2);
+ configuration.getSynapseConfig().setAxis2Xml(tempSynapseAxis2.getAbsolutePath());
+
+ for (BackEndServerController besc : backendServerControllers) {
+ String serverName = besc.getServerName();
+ String beAxis2Xml = configuration.getAxis2Config(serverName).getAxis2Xml();
+ String beAxis2Config = FileUtils.readFileToString(new File(beAxis2Xml));
+ String modifiedBEAxis2 = SynapseTestUtils.replace(beAxis2Config, "${replace.me}", ip);
+ File tempBEAxis2 = File.createTempFile("axis2BE-", "xml");
+ tempBEAxis2.deleteOnExit();
+ FileUtils.writeStringToFile(tempBEAxis2, modifiedBEAxis2);
+ configuration.getAxis2Config(serverName).setAxis2Xml(tempBEAxis2.getAbsolutePath());
+ }
+ return true;
+
+ } catch (Exception e) {
+ log.error("Error configuring clustering", e);
+ return false;
+ }
+
+
+ }
+
+ protected SampleConfiguration getConfiguration() {
+ return configuration;
+ }
+
+ protected ArrayList<BackEndServerController> getBackendServerControllers() {
+ return backendServerControllers;
+ }
+
+ public StockQuoteSampleClient getStockQuoteClient() {
+ return new StockQuoteSampleClient(configuration.getClientConfig());
+ }
+
+ public EventSampleClient getEventSubscriberSampleClient() {
+ return new EventSampleClient(configuration.getClientConfig());
+ }
+
+ public MTOMSwASampleClient getMTOMSwASampleClient() {
+ return new MTOMSwASampleClient(configuration.getClientConfig());
+ }
+}
\ No newline at end of file
Added: synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/SynapseTestUtils.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/SynapseTestUtils.java?rev=1211407&view=auto
==============================================================================
--- synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/SynapseTestUtils.java (added)
+++ synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/SynapseTestUtils.java Wed Dec 7 12:17:10 2011
@@ -0,0 +1,81 @@
+/*
+ * 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.synapse.samples.framework;
+
+import java.net.Inet4Address;
+import java.net.InetAddress;
+import java.net.NetworkInterface;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.List;
+
+public class SynapseTestUtils {
+
+ static String replace(String str, String pattern, String replace) {
+ int s = 0;
+ int e;
+ StringBuilder result = new StringBuilder();
+
+ while ((e = str.indexOf(pattern, s)) >= 0) {
+ result.append(str.substring(s, e));
+ result.append(replace);
+ s = e + pattern.length();
+ }
+ result.append(str.substring(s));
+ return result.toString();
+ }
+
+ static String getIPAddress() throws Exception {
+ List<InetAddress> ipAddresses = new ArrayList<InetAddress>();
+ String ipAddress = null;
+
+ Enumeration e = NetworkInterface.getNetworkInterfaces();
+ while (e.hasMoreElements()) {
+ NetworkInterface ni = (NetworkInterface) e.nextElement();
+ // Clustering doesn't work for loop-back addresses, so we are not interested
+ // we are not interested in inactive interfaces either
+ if (ni.isLoopback() || !ni.isUp()) continue;
+
+ Enumeration e2 = ni.getInetAddresses();
+ while (e2.hasMoreElements()) {
+ InetAddress ip = (InetAddress) e2.nextElement();
+ ipAddresses.add(ip);
+ }
+ }
+
+ if (ipAddresses.isEmpty()) {
+ return null;
+ } else {
+ for (InetAddress ip : ipAddresses) {
+ if (ip instanceof Inet4Address) {
+ ipAddress = ip.getHostAddress();
+ break;
+ }
+ }
+ }
+
+ if (ipAddress == null) {
+ ipAddress = ipAddresses.get(0).getHostAddress();
+ }
+
+ return ipAddress;
+ }
+
+}
\ No newline at end of file
Added: synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/TestSamplesHandlerSuite.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/TestSamplesHandlerSuite.java?rev=1211407&view=auto
==============================================================================
--- synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/TestSamplesHandlerSuite.java (added)
+++ synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/TestSamplesHandlerSuite.java Wed Dec 7 12:17:10 2011
@@ -0,0 +1,173 @@
+/*
+ * 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.synapse.samples.framework;
+
+import junit.framework.TestSuite;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.samples.framework.tests.message.*;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+
+/*
+ * This is executed by maven and handles which samples to run
+ */
+public class TestSamplesHandlerSuite extends TestSuite {
+
+ private static final Log log = LogFactory.getLog(TestSamplesHandlerSuite.class);
+ private static HashMap<String, Object> sampleClassRepo
+ = new HashMap<String, Object>();
+
+ public static TestSuite suite() {
+
+ //Adding all samples available
+ populateSamplesMap();
+
+ ArrayList<Class> suiteClassesList = new ArrayList<Class>();
+ TestSuite suite = new TestSuite();
+
+ String inputSuiteName = System.getProperty("suite");
+ String tests = System.getProperty("tests");
+ String suiteName = "SamplesSuite";
+
+ //preparing suites, if specified
+ if (inputSuiteName != null) {
+ if (inputSuiteName.equalsIgnoreCase("message")) {
+ suiteName = "MessageMediationSamplesSuite";
+ for (int i = 0; i <= 15; i++) {
+ Class testClass = (Class) sampleClassRepo.get(Integer.toString(i));
+ if (testClass != null) {
+ suiteClassesList.add(testClass);
+ }
+ }
+ }
+ if (inputSuiteName.equalsIgnoreCase("endpoint")) {
+ suiteName = "EndpointSamplesSuite";
+ for (int i = 50; i <= 60; i++) {
+ Class testClass = (Class) sampleClassRepo.get(Integer.toString(i));
+ if (testClass != null) {
+ suiteClassesList.add(testClass);
+ }
+ }
+ }
+ if (inputSuiteName.equalsIgnoreCase("qos")) {
+ suiteName = "QoSSamplesSuite";
+ for (int i = 100; i <= 110; i++) {
+ Class testClass = (Class) sampleClassRepo.get(Integer.toString(i));
+ if (testClass != null) {
+ suiteClassesList.add(testClass);
+ }
+ }
+ }
+ if (inputSuiteName.equalsIgnoreCase("proxy")) {
+ suiteName = "ProxySamplesSuite";
+ for (int i = 150; i <= 170; i++) {
+ Class testClass = (Class) sampleClassRepo.get(Integer.toString(i));
+ if (testClass != null) {
+ suiteClassesList.add(testClass);
+ }
+ }
+ }
+ if (inputSuiteName.equalsIgnoreCase("transport")) {
+ suiteName = "TransportSamplesSuite";
+ for (int i = 250; i <= 280; i++) {
+ Class testClass = (Class) sampleClassRepo.get(Integer.toString(i));
+ if (testClass != null) {
+ suiteClassesList.add(testClass);
+ }
+ }
+ }
+ if (inputSuiteName.equalsIgnoreCase("tasks")) {
+ suiteName = "TasksSamplesSuite";
+ for (int i = 300; i <= 310; i++) {
+ Class testClass = (Class) sampleClassRepo.get(Integer.toString(i));
+ if (testClass != null) {
+ suiteClassesList.add(testClass);
+ }
+ }
+ }
+ if (inputSuiteName.equalsIgnoreCase("advanced")) {
+ suiteName = "AdvancedSamplesSuite";
+ for (int i = 350; i <= 490; i++) {
+ Class testClass = (Class) sampleClassRepo.get(Integer.toString(i));
+ if (testClass != null) {
+ suiteClassesList.add(testClass);
+ }
+ }
+ }
+ if (inputSuiteName.equalsIgnoreCase("eventing")) {
+ suiteName = "EventingSamplesSuite";
+ for (int i = 500; i <= 510; i++) {
+ Class testClass = (Class) sampleClassRepo.get(Integer.toString(i));
+ if (testClass != null) {
+ suiteClassesList.add(testClass);
+ }
+ }
+ }
+ } else if (tests != null) {
+ String[] testArray = tests.split(",");
+ suiteName = "SelectedSamplesSuite";
+ for (String testNum : testArray) {
+ Class testClass = (Class) sampleClassRepo.get(testNum);
+ if (testClass != null) {
+ suiteClassesList.add(testClass);
+ }
+ }
+ } else {
+ suiteName = "AllSamplesSuite";
+ for (int i = 0; i <= 600; i++) {
+ Class testClass = (Class) sampleClassRepo.get(Integer.toString(i));
+ if (testClass != null) {
+ suiteClassesList.add(testClass);
+ }
+ }
+ }
+
+ for (Class testClass : suiteClassesList) {
+ suite.addTestSuite(testClass);
+ log.info("Adding Sample:" + testClass);
+ }
+ suite.setName(suiteName);
+
+ return suite;
+ }
+
+ private static void populateSamplesMap() {
+
+ //Message Mediation
+ sampleClassRepo.put("0", Sample0.class);
+ sampleClassRepo.put("1", Sample1.class);
+ sampleClassRepo.put("2", Sample2.class);
+ sampleClassRepo.put("3", Sample3.class);
+ sampleClassRepo.put("4", Sample4.class);
+ sampleClassRepo.put("5", Sample5.class);
+ sampleClassRepo.put("6", Sample6.class);
+ sampleClassRepo.put("7", Sample7.class);
+ sampleClassRepo.put("8", Sample8.class);
+ sampleClassRepo.put("9", Sample9.class);
+ sampleClassRepo.put("10", Sample10.class);
+ sampleClassRepo.put("11", Sample11.class);
+ sampleClassRepo.put("12", Sample12.class);
+ sampleClassRepo.put("13", Sample13.class);
+ sampleClassRepo.put("15", Sample15.class);
+ sampleClassRepo.put("16", Sample16.class);
+ }
+}
\ No newline at end of file
Added: synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/clients/EventSampleClient.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/clients/EventSampleClient.java?rev=1211407&view=auto
==============================================================================
--- synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/clients/EventSampleClient.java (added)
+++ synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/clients/EventSampleClient.java Wed Dec 7 12:17:10 2011
@@ -0,0 +1,363 @@
+/*
+* 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.synapse.samples.framework.clients;
+
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.OMFactory;
+import org.apache.axiom.om.OMNamespace;
+import org.apache.axiom.om.util.AXIOMUtil;
+import org.apache.axis2.addressing.EndpointReference;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.ConfigurationContextFactory;
+import org.apache.axis2.context.MessageContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.samples.framework.SampleClientResult;
+import org.apache.synapse.samples.framework.SampleConfiguration;
+
+import javax.xml.namespace.QName;
+
+
+public class EventSampleClient {
+
+ private static final Log log = LogFactory.getLog(EventSampleClient.class);
+
+ private Options options;
+ private ServiceClient serviceClient;
+ private SampleClientResult clientResult;
+ private SampleConfiguration.ClientSampleConfiguration configuration;
+ private OMFactory factory;
+ private OMElement message;
+ private OMNamespace schemaNamespace;
+ private OMNamespace nss11;
+ private OMNamespace addressingNamespace;
+ private OMNamespace eventingNamespace;
+
+ public EventSampleClient(SampleConfiguration.ClientSampleConfiguration configuration) {
+ this.configuration = configuration;
+ factory = OMAbstractFactory.getOMFactory();
+ schemaNamespace = factory.createOMNamespace("http://www.w3.org/2001/XMLSchema", "xmlns");
+ nss11 =
+ factory.createOMNamespace("http://schemas.xmlsoap.org/soap/envelope", "s11");
+ addressingNamespace = factory.createOMNamespace(
+ "http://schemas.xmlsoap.org/ws/2004/08/addressing", "wsa");
+ eventingNamespace =
+ factory.createOMNamespace("http://schemas.xmlsoap.org/ws/2004/08/eventing", "wse");
+ }
+
+ private void initializeClient(String addUrl) throws Exception {
+ options = new Options();
+ clientResult = new SampleClientResult();
+ clientResult.setGotResponse(false);
+
+ ConfigurationContext configContext;
+ configContext = ConfigurationContextFactory.
+ createConfigurationContextFromFileSystem(configuration.getClientRepo(),
+ configuration.getAxis2Xml());
+ serviceClient = new ServiceClient(configContext, null);
+
+ if (addUrl != null && !"null".equals(addUrl)) {
+ serviceClient.engageModule("addressing");
+ options.setTo(new EndpointReference(addUrl));
+ }
+ serviceClient.setOptions(options);
+
+ message = factory.createOMElement("message", null);
+ }
+
+ private void deInitializeClient() {
+ try {
+ if (serviceClient != null) {
+ serviceClient.cleanup();
+ }
+ } catch (Exception ignore) {
+ }
+ }
+
+ public SampleClientResult subscribe(String addUrl, String address, String expires, String topic) {
+ OMElement subscribeOm = factory.createOMElement("Subscribe", eventingNamespace);
+ OMElement deliveryOm = factory.createOMElement("Delivery", eventingNamespace);
+ deliveryOm.addAttribute(factory.createOMAttribute("Mode", null,
+ "http://schemas.xmlsoap.org/ws/2004/08/eventing/DeliveryModes/Push"));
+ OMElement notifyToOm = factory.createOMElement("NotifyTo", eventingNamespace);
+ OMElement addressOm = factory.createOMElement("Address", addressingNamespace);
+ factory.createOMText(addressOm, address);
+ OMElement expiresOm = factory.createOMElement("Expires", eventingNamespace);
+ factory.createOMText(expiresOm, expires);
+ OMElement filterOm = factory.createOMElement("Filter", eventingNamespace);
+ filterOm.addAttribute(factory.createOMAttribute("Dialect", null,
+ "http://synapse.apache.org/eventing/dialect/topicFilter"));
+ factory.createOMText(filterOm, topic);
+
+
+ notifyToOm.addChild(addressOm);
+ deliveryOm.addChild(notifyToOm);
+ subscribeOm.addChild(deliveryOm);
+ if (!(expires.equals("*"))) {
+ subscribeOm.addChild(expiresOm); // Add only if the value provided
+ }
+ subscribeOm.addChild(filterOm);
+
+
+ log.info("Subscribing: " + subscribeOm.toString());
+ try {
+ initializeClient(addUrl);
+ options.setAction("http://schemas.xmlsoap.org/ws/2004/08/eventing/Subscribe");
+
+ OMElement response = serviceClient.sendReceive(subscribeOm);
+ log.info("Subscribed to topic " + topic);
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+
+ }
+ log.info("Response Received: " + response.toString());
+ String subId =
+ response.getFirstChildWithName(
+ new QName(eventingNamespace.getNamespaceURI(), "SubscriptionManager"))
+ .getFirstChildWithName(
+ new QName(addressingNamespace.getNamespaceURI(), "ReferenceParameters"))
+ .getFirstChildWithName(
+ new QName(eventingNamespace.getNamespaceURI(), "Identifier")).getText();
+ log.info("Subscription identifier: " + subId);
+ clientResult.addProperty("subId", subId);
+ clientResult.setGotResponse(true);
+ } catch (Exception e) {
+ log.error("Fault Received : " + e.toString(), e);
+ clientResult.setGotResponse(false);
+ clientResult.setException(e);
+ }
+ deInitializeClient();
+ return clientResult;
+
+ }
+
+
+ public SampleClientResult unsubscribe(String addUrl, String identifier) {
+ /** Send unsubscribe message
+ (01) <s12:Envelope
+ (02) xmlns:s12="http://www.w3.org/2003/05/soap-envelope"
+ (03) xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"
+ (04) xmlns:wse="http://schemas.xmlsoap.org/ws/2004/08/eventing"
+ (05) xmlns:ow="http://www.example.org/oceanwatch" >
+ (06) <s12:Header>
+ (07) <wsa:Action>
+ (08) http://schemas.xmlsoap.org/ws/2004/08/eventing/Unsubscribe
+ (09) </wsa:Action>
+ (10) <wsa:MessageID>
+ (11) uuid:2653f89f-25bc-4c2a-a7c4-620504f6b216
+ (12) </wsa:MessageID>
+ (13) <wsa:ReplyTo>
+ (14) <wsa:Address>http://www.example.com/MyEventSink</wsa:Address>
+ (15) </wsa:ReplyTo>
+ (16) <wsa:To>
+ (17) http://www.example.org/oceanwatch/SubscriptionManager
+ (18) </wsa:To>
+ (19) <wse:Identifier>
+ (20) uuid:22e8a584-0d18-4228-b2a8-3716fa2097fa
+ (21) </wse:Identifier>
+ (22) </s12:Header>
+ (23) <s12:Body>
+ (24) <wse:Unsubscribe />
+ (25) </s12:Body>
+ (26) </s12:Envelope>*/
+ OMElement subscribeOm = factory.createOMElement("Unsubscribe", eventingNamespace);
+
+ log.info("UnSubscribing: " + subscribeOm.toString());
+ try {
+ initializeClient(addUrl);
+ options.setAction("http://schemas.xmlsoap.org/ws/2004/08/eventing/Unsubscribe");
+
+ OMElement identifierOm = factory.createOMElement("Identifier", eventingNamespace);
+ factory.createOMText(identifierOm, identifier);
+ serviceClient.addHeader(identifierOm);
+ OMElement response = serviceClient.sendReceive(subscribeOm);
+ log.info("UnSubscribed to ID " + identifier);
+ Thread.sleep(1000);
+ log.info("UnSubscribe Response Received: " + response.toString());
+ clientResult.setGotResponse(true);
+ } catch (Exception e) {
+ log.error("Fault Received : " + e.toString(), e);
+ clientResult.setGotResponse(false);
+ clientResult.setException(e);
+ }
+ deInitializeClient();
+ return clientResult;
+ }
+
+ public SampleClientResult renew(String addUrl, String expires, String identifier) {
+ /**
+ * (01) <s12:Envelope
+ (02) xmlns:s12="http://www.w3.org/2003/05/soap-envelope"
+ (03) xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"
+ (04) xmlns:wse="http://schemas.xmlsoap.org/ws/2004/08/eventing"
+ (05) xmlns:ow="http://www.example.org/oceanwatch" >
+ (06) <s12:Header>
+ (07) <wsa:Action>
+ (08) http://schemas.xmlsoap.org/ws/2004/08/eventing/Renew
+ (09) </wsa:Action>
+ (10) <wsa:MessageID>
+ (11) uuid:bd88b3df-5db4-4392-9621-aee9160721f6
+ (12) </wsa:MessageID>
+ (13) <wsa:ReplyTo>
+ (14) <wsa:Address>http://www.example.com/MyEventSink</wsa:Address>
+ (15) </wsa:ReplyTo>
+ (16) <wsa:To>
+ (17) http://www.example.org/oceanwatch/SubscriptionManager
+ (18) </wsa:To>
+ (19) <wse:Identifier>
+ (20) uuid:22e8a584-0d18-4228-b2a8-3716fa2097fa
+ (21) </wse:Identifier>
+ (22) </s12:Header>
+ (23) <s12:Body>
+ (24) <wse:Renew>
+ (25) <wse:Expires>2004-06-26T21:07:00.000-08:00</wse:Expires>
+ (26) </wse:Renew>
+ (27) </s12:Body>
+ (28) </s12:Envelope>
+ */
+
+ OMElement subscribeOm = factory.createOMElement("Renew", eventingNamespace);
+ OMElement expiresOm = factory.createOMElement("Expires", eventingNamespace);
+ factory.createOMText(expiresOm, expires);
+ subscribeOm.addChild(expiresOm);
+
+
+ log.info("SynapseSubscription Renew \n" + subscribeOm.toString());
+ try {
+ initializeClient(addUrl);
+ OMElement identifierOm = factory.createOMElement("Identifier", eventingNamespace);
+ factory.createOMText(identifierOm, identifier);
+ serviceClient.addHeader(identifierOm);
+ options.setAction("http://schemas.xmlsoap.org/ws/2004/08/eventing/Renew");
+ OMElement response = serviceClient.sendReceive(subscribeOm);
+ log.info("SynapseSubscription Renew to ID " + identifier);
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+
+ }
+ log.info("SynapseSubscription Renew Response Received: " + response.toString());
+ clientResult.setGotResponse(true);
+ } catch (Exception e) {
+ log.error("Fault Received : " + e.toString(), e);
+ clientResult.setGotResponse(false);
+ clientResult.setException(e);
+ }
+ deInitializeClient();
+ return clientResult;
+ }
+
+ public SampleClientResult getStatus(String addUrl, String identifier) {
+ /**
+ * (01) <s12:Envelope
+ (02) xmlns:s12="http://www.w3.org/2003/05/soap-envelope"
+ (03) xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"
+ (04) xmlns:wse="http://schemas.xmlsoap.org/ws/2004/08/eventing"
+ (05) xmlns:ow="http://www.example.org/oceanwatch" >
+ (06) <s12:Header>
+ (07) <wsa:Action>
+ (08) http://schemas.xmlsoap.org/ws/2004/08/eventing/GetStatus
+ (09) </wsa:Action>
+ (10) <wsa:MessageID>
+ (11) uuid:bd88b3df-5db4-4392-9621-aee9160721f6
+ (12) </wsa:MessageID>
+ (13) <wsa:ReplyTo>
+ (14) <wsa:Address>http://www.example.com/MyEventSink</wsa:Address>
+ (15) </wsa:ReplyTo>
+ (16) <wsa:To>
+ (17) http://www.example.org/oceanwatch/SubscriptionManager
+ (18) </wsa:To>
+ (19) <wse:Identifier>
+ (20) uuid:22e8a584-0d18-4228-b2a8-3716fa2097fa
+ (21) </wse:Identifier>
+ (22) </s12:Header>
+ (23) <s12:Body>
+ (24) <wse:GetStatus />
+ (25) </s12:Body>
+ (26) </s12:Envelope>
+ */
+ OMElement subscribeOm = factory.createOMElement("GetStatus", eventingNamespace);
+
+ log.info("GetStatus using: " + subscribeOm.toString());
+ try {
+ initializeClient(addUrl);
+ options.setAction("http://schemas.xmlsoap.org/ws/2004/08/eventing/GetStatus");
+
+ OMElement identifierOm = factory.createOMElement("Identifier", eventingNamespace);
+ factory.createOMText(identifierOm, identifier);
+ serviceClient.addHeader(identifierOm);
+ OMElement response = serviceClient.sendReceive(subscribeOm);
+ log.info("GetStatus to ID " + identifier);
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+
+ }
+ log.info("GetStatus Response Received: " + response.toString());
+ clientResult.setGotResponse(true);
+ } catch (Exception e) {
+ log.error("Fault Received : " + e.toString(), e);
+ clientResult.setGotResponse(false);
+ clientResult.setException(e);
+ }
+ deInitializeClient();
+ return clientResult;
+ }
+
+ public SampleClientResult sendEvent(String addUrl, String symbol, String price, String qty,
+ String topic, String topicns) {
+ try {
+ initializeClient(addUrl);
+
+ OMNamespace aipNamespace = factory.createOMNamespace(topicns, "aip");
+ // set the target topic
+ OMElement topicOm = factory.createOMElement("Topic", aipNamespace);
+ factory.createOMText(topicOm, topic);
+ serviceClient.addHeader(topicOm);
+ // set for fire and forget
+ options.setProperty(MessageContext.CLIENT_API_NON_BLOCKING, Boolean.FALSE);
+
+ OMElement payload =
+ AXIOMUtil.stringToOM("<m:placeOrder xmlns:m=\"http://services.samples\">\n" +
+ " <m:order>\n" +
+ " <m:price>" + price + "</m:price>\n" +
+ " <m:quantity>" + qty + "</m:quantity>\n" +
+ " <m:symbol>" + symbol + "</m:symbol>\n" +
+ " </m:order>\n" +
+ "</m:placeOrder>");
+
+ log.info("Sending Event : \n" + payload.toString());
+ serviceClient.fireAndForget(payload);
+ log.info("Event sent to topic " + topic);
+ Thread.sleep(1000);
+ clientResult.setGotResponse(true);
+ } catch (Exception e) {
+ log.error("Fault Received : " + e.toString(), e);
+ clientResult.setGotResponse(false);
+ clientResult.setException(e);
+ }
+ deInitializeClient();
+ return clientResult;
+ }
+}
\ No newline at end of file
Added: synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/clients/JMSSampleClient.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/clients/JMSSampleClient.java?rev=1211407&view=auto
==============================================================================
--- synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/clients/JMSSampleClient.java (added)
+++ synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/clients/JMSSampleClient.java Wed Dec 7 12:17:10 2011
@@ -0,0 +1,118 @@
+/*
+ * 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.synapse.samples.framework.clients;
+
+import javax.jms.*;
+import javax.naming.InitialContext;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+
+public class JMSSampleClient {
+
+ private QueueConnection connection;
+ private QueueSession session;
+ private QueueSender sender;
+
+ public void connect(String destName) throws Exception {
+
+ Properties env = new Properties();
+ //String factoryURL = System.getProperty("java.naming.factory.url.pkgs");
+ String connectionFactoryName = "ConnectionFactory";
+
+ if (System.getProperty("java.naming.provider.url") == null) {
+ env.put("java.naming.provider.url", "tcp://localhost:61616");
+ }
+ if (System.getProperty("java.naming.factory.initial") == null) {
+ env.put("java.naming.factory.initial",
+ "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
+ }
+ if (connectionFactoryName != null) {
+ env.put("transport.jms.ConnectionFactoryJNDIName", connectionFactoryName);
+ }
+
+ InitialContext ic = new InitialContext(env);
+ QueueConnectionFactory confac = (QueueConnectionFactory) ic.lookup("ConnectionFactory");
+ connection = confac.createQueueConnection();
+ session = connection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
+ sender = session.createSender((Queue)ic.lookup(destName));
+ }
+
+ public void shutdown() throws Exception {
+ sender.close();
+ session.close();
+ connection.close();
+ }
+
+ private void sendBytesMessage(byte[] payload) throws Exception {
+ BytesMessage bm = session.createBytesMessage();
+ bm.writeBytes(payload);
+ sender.send(bm);
+ }
+
+ public void sendTextMessage(String payload) throws Exception {
+ TextMessage tm = session.createTextMessage(payload);
+ sender.send(tm);
+ }
+
+ public static byte[] getBytesFromFile(String fileName) throws IOException {
+
+ File file = new File(fileName);
+ InputStream is = new FileInputStream(file);
+ long length = file.length();
+
+ byte[] bytes = new byte[(int) length];
+
+ int offset = 0;
+ int numRead = 0;
+ while (offset < bytes.length
+ && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
+ offset += numRead;
+ }
+
+ // Ensure all the bytes have been read in
+ if (offset < bytes.length) {
+ throw new IOException("Could not completely read file " + file.getName());
+ }
+
+ is.close();
+ return bytes;
+ }
+
+ public static double getRandom(double base, double variance, boolean positiveOnly) {
+ double rand = Math.random();
+ return (base + ((rand > 0.5 ? 1 : -1) * variance * base * rand))
+ * (positiveOnly ? 1 : (rand > 0.5 ? 1 : -1));
+ }
+
+ public void sendAsPox(String param) throws Exception{
+ sendTextMessage(
+ "<m:placeOrder xmlns:m=\"http://services.samples\">\n" +
+ " <m:order>\n" +
+ " <m:price>" + getRandom(100, 0.9, true) + "</m:price>\n" +
+ " <m:quantity>" + (int) getRandom(10000, 1.0, true) + "</m:quantity>\n" +
+ " <m:symbol>" + param + "</m:symbol>\n" +
+ " </m:order>\n" +
+ "</m:placeOrder>");
+ }
+
+}
Added: synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/clients/MTOMSwASampleClient.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/clients/MTOMSwASampleClient.java?rev=1211407&view=auto
==============================================================================
--- synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/clients/MTOMSwASampleClient.java (added)
+++ synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/clients/MTOMSwASampleClient.java Wed Dec 7 12:17:10 2011
@@ -0,0 +1,197 @@
+/*
+ * 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.synapse.samples.framework.clients;
+
+import org.apache.axiom.attachments.Attachments;
+import org.apache.axiom.om.*;
+import org.apache.axiom.soap.SOAPBody;
+import org.apache.axiom.soap.SOAPEnvelope;
+import org.apache.axiom.soap.SOAPFactory;
+import org.apache.axis2.Constants;
+import org.apache.axis2.addressing.EndpointReference;
+import org.apache.axis2.client.OperationClient;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.ConfigurationContextFactory;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.wsdl.WSDLConstants;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.samples.framework.SampleClientResult;
+import org.apache.synapse.samples.framework.SampleConfiguration;
+
+import javax.activation.DataHandler;
+import javax.activation.FileDataSource;
+import javax.xml.namespace.QName;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+
+public class MTOMSwASampleClient {
+ private static final Log log = LogFactory.getLog(StockQuoteSampleClient.class);
+ ConfigurationContext configContext = null;
+
+ Options options;
+ SampleClientResult clientResult;
+ OMElement payload;
+ OMElement response;
+ ServiceClient serviceClient;
+ boolean completed;
+ SampleConfiguration.ClientSampleConfiguration configuration;
+
+ public MTOMSwASampleClient(SampleConfiguration.ClientSampleConfiguration configuration) {
+ this.configuration = configuration;
+ }
+
+ public SampleClientResult sendUsingMTOM(String fileName, String targetEPR) {
+ clientResult = new SampleClientResult();
+ try {
+ OMFactory factory = OMAbstractFactory.getOMFactory();
+ OMNamespace ns = factory.createOMNamespace("http://services.samples", "m0");
+ payload = factory.createOMElement("uploadFileUsingMTOM", ns);
+ OMElement request = factory.createOMElement("request", ns);
+ OMElement image = factory.createOMElement("image", ns);
+
+ log.info("Sending file : " + fileName + " as MTOM");
+ FileDataSource fileDataSource = new FileDataSource(new File(fileName));
+ DataHandler dataHandler = new DataHandler(fileDataSource);
+ OMText textData = factory.createOMText(dataHandler, true);
+ image.addChild(textData);
+ request.addChild(image);
+ payload.addChild(request);
+
+ ConfigurationContext configContext =
+ ConfigurationContextFactory.
+ createConfigurationContextFromFileSystem(configuration.getClientRepo(),
+ configuration.getAxis2Xml());
+
+ serviceClient = new ServiceClient(configContext, null);
+
+ Options options = new Options();
+ options.setTo(new EndpointReference(targetEPR));
+ options.setAction("urn:uploadFileUsingMTOM");
+ options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
+
+ serviceClient.setOptions(options);
+ OMElement response = serviceClient.sendReceive(payload);
+
+ OMText binaryNode = (OMText) response.
+ getFirstChildWithName(new QName("http://services.samples", "response")).
+ getFirstChildWithName(new QName("http://services.samples", "image")).
+ getFirstOMChild();
+ dataHandler = (DataHandler) binaryNode.getDataHandler();
+ InputStream is = dataHandler.getInputStream();
+ log.info("temp.dir: " + System.getProperty("java.io.tmpdir"));
+ File tempFile = File.createTempFile("mtom-", ".gif");
+ FileOutputStream fos = new FileOutputStream(tempFile);
+ BufferedOutputStream dest = new BufferedOutputStream(fos, 2048);
+
+ byte data[] = new byte[2048];
+ int count;
+ while ((count = is.read(data, 0, 2048)) != -1) {
+ dest.write(data, 0, count);
+ }
+
+ dest.flush();
+ dest.close();
+ log.info("Saved response to file : " + tempFile.getAbsolutePath());
+
+ clientResult.setGotResponse(true);
+ } catch (Exception e) {
+ log.error("Error invoking service", e);
+ clientResult.setGotResponse(false);
+ clientResult.setException(e);
+ }
+
+ return clientResult;
+
+ }
+
+ public SampleClientResult sendUsingSWA(String fileName, String targetEPR) {
+ clientResult = new SampleClientResult();
+ try {
+ Options options = new Options();
+ options.setTo(new EndpointReference(targetEPR));
+ options.setAction("urn:uploadFileUsingSwA");
+ options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE);
+
+ ConfigurationContext configContext =
+ ConfigurationContextFactory.
+ createConfigurationContextFromFileSystem(configuration.getClientRepo(),
+ configuration.getAxis2Xml());
+
+ ServiceClient sender = new ServiceClient(configContext, null);
+
+ sender.setOptions(options);
+ OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP);
+
+ MessageContext mc = new MessageContext();
+
+ log.info("Sending file : " + fileName + " as SwA");
+ FileDataSource fileDataSource = new FileDataSource(new File(fileName));
+ DataHandler dataHandler = new DataHandler(fileDataSource);
+ String attachmentID = mc.addAttachment(dataHandler);
+
+
+ SOAPFactory factory = OMAbstractFactory.getSOAP11Factory();
+ SOAPEnvelope env = factory.getDefaultEnvelope();
+ OMNamespace ns = factory.createOMNamespace("http://services.samples", "m0");
+ OMElement payload = factory.createOMElement("uploadFileUsingSwA", ns);
+ OMElement request = factory.createOMElement("request", ns);
+ OMElement imageId = factory.createOMElement("imageId", ns);
+ imageId.setText(attachmentID);
+ request.addChild(imageId);
+ payload.addChild(request);
+ env.getBody().addChild(payload);
+ mc.setEnvelope(env);
+
+ mepClient.addMessageContext(mc);
+ mepClient.execute(true);
+ MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
+
+ SOAPBody body = response.getEnvelope().getBody();
+ String imageContentId = body.
+ getFirstChildWithName(new QName("http://services.samples", "uploadFileUsingSwAResponse")).
+ getFirstChildWithName(new QName("http://services.samples", "response")).
+ getFirstChildWithName(new QName("http://services.samples", "imageId")).
+ getText();
+
+ Attachments attachment = response.getAttachmentMap();
+ dataHandler = attachment.getDataHandler(imageContentId);
+ File tempFile = File.createTempFile("swa-", ".gif");
+ FileOutputStream fos = new FileOutputStream(tempFile);
+ dataHandler.writeTo(fos);
+ fos.flush();
+ fos.close();
+
+ log.info("Saved response to file : " + tempFile.getAbsolutePath());
+
+ clientResult.setGotResponse(true);
+ } catch (Exception e) {
+ log.error("Error invoking service", e);
+ clientResult.setGotResponse(false);
+ clientResult.setException(e);
+ }
+
+ return clientResult;
+
+ }
+}
Added: synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/clients/StockQuoteCallback.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/clients/StockQuoteCallback.java?rev=1211407&view=auto
==============================================================================
--- synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/clients/StockQuoteCallback.java (added)
+++ synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/clients/StockQuoteCallback.java Wed Dec 7 12:17:10 2011
@@ -0,0 +1,43 @@
+package org.apache.synapse.samples.framework.clients;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axis2.client.async.AxisCallback;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ *
+ */
+public class StockQuoteCallback implements AxisCallback {
+
+ private static final Log log = LogFactory.getLog(StockQuoteCallback.class);
+
+ StockQuoteSampleClient client;
+
+ public StockQuoteCallback(StockQuoteSampleClient client) {
+ this.client=client;
+ }
+
+ public void onMessage(org.apache.axis2.context.MessageContext messageContext) {
+ log.info("Response received to the callback");
+ OMElement result
+ = messageContext.getEnvelope().getBody().getFirstElement();
+ // Detach the result to make sure that the element we return to the sample client
+ // is completely built
+ result.detach();
+ client.setResponse(result);
+ }
+
+ public void onFault(org.apache.axis2.context.MessageContext messageContext) {
+ log.warn("Fault received to the callback : " + messageContext.getEnvelope().
+ getBody().getFault());
+ }
+
+ public void onError(Exception e) {
+ log.warn("Error inside callback : " + e);
+ }
+
+ public void onComplete() {
+ client.setCompleted(true);
+ }
+}
Added: synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/clients/StockQuoteHandler.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/clients/StockQuoteHandler.java?rev=1211407&view=auto
==============================================================================
--- synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/clients/StockQuoteHandler.java (added)
+++ synapse/trunk/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/clients/StockQuoteHandler.java Wed Dec 7 12:17:10 2011
@@ -0,0 +1,364 @@
+/*
+ * 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.synapse.samples.framework.clients;
+
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.OMFactory;
+import org.apache.axiom.om.OMNamespace;
+import org.apache.axiom.om.xpath.AXIOMXPath;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Random;
+
+/**
+ * A class that can create messages to, and parse replies from our sample StockQuote service
+ */
+public class StockQuoteHandler {
+
+ private static final Random RANDOM = new Random();
+
+ /**
+ * Create a new custom quote request with a body as follows
+ * <m0:CheckPriceRequest xmlns:m0="http://services.samples">
+ * <m0:Code>symbol</m0:Code>
+ * </m0:CheckPriceRequest>
+ * @param symbol the stock symbol
+ * @return OMElement for SOAP body
+ */
+ public static OMElement createCustomQuoteRequest(String symbol) {
+ OMFactory factory = OMAbstractFactory.getOMFactory();
+ OMNamespace ns = factory.createOMNamespace(
+ "http://services.samples", "m0");
+ OMElement chkPrice = factory.createOMElement("CheckPriceRequest", ns);
+ OMElement code = factory.createOMElement("Code", ns);
+ chkPrice.addChild(code);
+ code.setText(symbol);
+ return chkPrice;
+ }
+
+ /**
+ * Create a new quote request with a body as follows
+ * <m:GetQuote xmlns:m="http://services.samples">
+ * <m:request>
+ * <m:symbol>IBM</m:symbol>
+ * </m:request>
+ * </m:GetQuote>
+ * @param symbol the stock symbol
+ * @return OMElement for SOAP body
+ */
+ public static OMElement createStandardQuoteRequest(String symbol, int itrCount) {
+ OMFactory factory = OMAbstractFactory.getOMFactory();
+ OMNamespace ns = factory.createOMNamespace("http://services.samples", "m0");
+ OMElement getQuote = factory.createOMElement("getQuote", ns);
+ for (int i =0; i<itrCount; i++) {
+ OMElement request = factory.createOMElement("request", ns);
+ OMElement symb = factory.createOMElement("symbol", ns);
+ request.addChild(symb);
+ getQuote.addChild(request);
+ symb.setText(symbol);
+ }
+ return getQuote;
+ }
+
+ /**
+ * Create a new full quote request with a body as follows
+ * <m:GetFullQuote xmlns:m="http://services.samples">
+ * <m:request>
+ * <m:symbol>IBM</m:symbol>
+ * </m:request>
+ * </m:GetFullQuote>
+ * @param symbol the stock symbol
+ * @return OMElement for SOAP body
+ */
+ public static OMElement createFullQuoteRequest(String symbol) {
+ OMFactory factory = OMAbstractFactory.getOMFactory();
+ OMNamespace ns = factory.createOMNamespace("http://services.samples", "m0");
+ OMElement getQuote = factory.createOMElement("getFullQuote", ns);
+ OMElement request = factory.createOMElement("request", ns);
+ OMElement symb = factory.createOMElement("symbol", ns);
+ request.addChild(symb);
+ getQuote.addChild(request);
+ symb.setText(symbol);
+ return getQuote;
+ }
+
+ /**
+ * Create a new market activity request with a body as follows
+ * <m:getMarketActivity xmlns:m="http://services.samples">
+ * <m:request>
+ * <m:symbol>IBM</m:symbol>
+ * ...
+ * <m:symbol>MSFT</m:symbol>
+ * </m:request>
+ * </m:getMarketActivity>
+ * @return OMElement for SOAP body
+ */
+ public static OMElement createMarketActivityRequest() {
+ OMFactory factory = OMAbstractFactory.getOMFactory();
+ OMNamespace ns = factory.createOMNamespace("http://services.samples", "m0");
+ OMElement getQuote = factory.createOMElement("getMarketActivity", ns);
+ OMElement request = factory.createOMElement("request", ns);
+
+ OMElement symb = null;
+ for (int i=0; i<100; i++) {
+ symb = factory.createOMElement("symbols", ns);
+ symb.setText(randomString(3));
+ request.addChild(symb);
+ }
+
+ getQuote.addChild(request);
+ return getQuote;
+ }
+
+ /**
+ * Create a new order for a quantiry of a stock at a given price
+ * <m:placeOrder xmlns:m="http://services.samples">
+ * <m:order>
+ * <m:price>3.141593E0</m:price>
+ * <m:quantity>4</m:quantity>
+ * <m:symbol>IBM</m:symbol>
+ * </m:order>
+ * </m:placeOrder>
+ *
+ * @param purchPrice the purchase price
+ * @param qty the quantiry
+ * @param symbol the stock
+ * @return an OMElement payload for the order
+ */
+ public static OMElement createPlaceOrderRequest(double purchPrice, int qty, String symbol) {
+ OMFactory factory = OMAbstractFactory.getOMFactory();
+ OMNamespace ns = factory.createOMNamespace("http://services.samples", "m0");
+ OMElement placeOrder= factory.createOMElement("placeOrder", ns);
+ OMElement order = factory.createOMElement("order", ns);
+ OMElement price = factory.createOMElement("price", ns);
+ OMElement quantity = factory.createOMElement("quantity", ns);
+ OMElement symb = factory.createOMElement("symbol", ns);
+ price.setText(Double.toString(purchPrice));
+ quantity.setText(Integer.toString(qty));
+ symb.setText(symbol);
+ order.addChild(price);
+ order.addChild(quantity);
+ order.addChild(symb);
+ placeOrder.addChild(order);
+ return placeOrder;
+ }
+
+ /**
+ * Digests the standard StockQuote response and extracts the last trade price
+ * @param result
+ * @return
+ * @throws javax.xml.stream.XMLStreamException
+ *
+ * <ns:getQuoteResponse xmlns:ns="http://services.samples">
+ * <ns:return>
+ * <ns:change>-2.3238706829151026</ns:change>
+ * ...
+ * <ns:symbol>IBM</ns:symbol>
+ * <ns:volume>17949</ns:volume>
+ * </ns:return>
+ * </ns:getQuoteResponse>
+ */
+ public static String parseStandardQuoteResponse(OMElement result) throws Exception {
+
+ AXIOMXPath xPath = new AXIOMXPath("//ns:last");
+ xPath.addNamespace("ns","http://services.samples/xsd");
+ OMElement last = (OMElement) xPath.selectSingleNode(result);
+ if (last != null) {
+ return last.getText();
+ } else {
+ throw new Exception("Unexpected response : " + result);
+ }
+ }
+
+ /**
+ * <ns:getFullQuoteResponse xmlns:ns="http://services.samples">
+ <ns:return>
+ <tradeHistory xmlns="http://services.samples">
+ <day>0</day>
+ <quote>
+ <change>-2.367492989603466</change>
+ <earnings>13.14956711287784</earnings>
+ <high>-155.58844623078153</high>
+ <last>157.47582716569198</last>
+ <lastTradeTimestamp>Mon Apr 16 23:29:58 LKT 2007</lastTradeTimestamp>
+ <low>-155.31924118819015</low>
+ <marketCap>6373750.467022192</marketCap>
+ <name>IBM Company</name>
+ <open>-154.84071720443495</open>
+ <peRatio>-17.353258031353164</peRatio>
+ <percentageChange>-1.3910235348298898</percentageChange>
+ <prevClose>170.1979104108393</prevClose>
+ <symbol>IBM</symbol>
+ <volume>8935</volume>
+ </quote>
+ </tradeHistory>
+ <tradeHistory xmlns="http://services.samples">
+ <day>1</day>
+ <quote>
+ <change>3.794122022240518</change>
+ <earnings>-8.656536789776045</earnings>
+ <high>176.77136802352928</high>
+ <last>170.28677783945102</last>
+ <lastTradeTimestamp>Mon Apr 16 23:29:58 LKT 2007</lastTradeTimestamp>
+ <low>-166.64126635049223</low>
+ <marketCap>-6112014.916847887</marketCap>
+ <name>IBM Company</name>
+ <open>-168.30884678174925</open>
+ <peRatio>-18.644628475049693</peRatio>
+ <percentageChange>-2.29678289479374</percentageChange>
+ <prevClose>-165.19288918603885</prevClose>
+ <symbol>IBM</symbol>
+ <volume>5825</volume>
+ </quote>
+ </tradeHistory>
+ ...
+ </ns:return>
+ </ns:getFullQuoteResponse>
+ *
+ * @param result
+ * @return
+ * @throws Exception
+ */
+ public static String parseFullQuoteResponse(OMElement result) throws Exception {
+
+ AXIOMXPath xPath = new AXIOMXPath("//ns:last");
+ xPath.addNamespace("ns","http://services.samples/xsd");
+ List lastNodes = xPath.selectNodes(result);
+
+ if (lastNodes == null) {
+ throw new Exception("Unexpected response : " + result);
+ }
+
+ double total = 0;
+ int count = 0;
+
+ Iterator iter = lastNodes.iterator();
+ while (iter.hasNext()) {
+ OMElement last = (OMElement) iter.next();
+ total += Double.parseDouble(last.getText());
+ count++;
+ }
+
+ return Double.toString(total/count);
+ }
+
+ /**
+ * <ns:getMarketActivityResponse xmlns:ns="http://services.samples">
+ <ns:return>
+ <quotes xmlns="http://services.samples">
+ <change>4.183958555301184</change>
+ <earnings>-8.585281368244686</earnings>
+ <high>-158.70528805517333</high>
+ <last>160.83784480071603</last>
+ <lastTradeTimestamp>Tue Apr 17 02:21:30 LKT 2007</lastTradeTimestamp>
+ <low>-157.4950051860593</low>
+ <marketCap>5.9907588733164035E7</marketCap>
+ <name>EHM Company</name>
+ <open>-160.18368223376558</open>
+ <peRatio>24.0926205053427</peRatio>
+ <percentageChange>-2.6141745708181374</percentageChange>
+ <prevClose>-160.04893483420904</prevClose>
+ <symbol>EHM</symbol>
+ <volume>6319</volume>
+ </quotes>
+ <quotes xmlns="http://services.samples">
+ ....
+ <volume>7613</volume>
+ </quotes>
+ ...
+ </ns:return>
+ <ns:getMarketActivityResponse>
+ * @param result
+ * @return the average last price for each stock symbol
+ * @throws Exception
+ */
+ public static String parseMarketActivityResponse(OMElement result) throws Exception {
+
+ AXIOMXPath xPath = new AXIOMXPath("//ns:last");
+ xPath.addNamespace("ns","http://services.samples/xsd");
+ List lastNodes = xPath.selectNodes(result);
+
+ if (lastNodes == null) {
+ throw new Exception("Unexpected response : " + result);
+ }
+
+ double total = 0;
+ int count = 0;
+
+ Iterator iter = lastNodes.iterator();
+ while (iter.hasNext()) {
+ OMElement last = (OMElement) iter.next();
+ total += Double.parseDouble(last.getText());
+ count++;
+ }
+
+ return Double.toString(total/count);
+ }
+
+ /**
+ * Digests the custom quote response and extracts the last trade price
+ * @param result
+ * @return
+ * @throws javax.xml.stream.XMLStreamException
+ *
+ * <CheckPriceResponse xmlns="http://ws.invesbot.com/" >
+ * <Code>IBM</Code>
+ * <Price>82.90</Price>
+ * </CheckPriceResponse>
+ */
+ public static String parseCustomQuoteResponse(OMElement result) throws Exception {
+
+ AXIOMXPath xPath = new AXIOMXPath("//ns:Price");
+ xPath.addNamespace("ns","http://services.samples/xsd");
+ OMElement price = (OMElement) xPath.selectSingleNode(result);
+ if (price != null) {
+ return price.getText();
+ } else {
+ throw new Exception("Unexpected response : " + result);
+ }
+ }
+
+ /**
+ * Return a random String of letters
+ * @param count number of letters
+ * @return the random string
+ */
+ public static String randomString(int count) {
+ int end = 'Z' + 1;
+ int start = 'A';
+
+ StringBuffer buffer = new StringBuffer();
+ int gap = end - start;
+
+ while (count-- != 0) {
+ char ch;
+ ch = (char) (RANDOM.nextInt(gap) + start);
+ if (Character.isLetter(ch)) {
+ buffer.append(ch);
+ } else {
+ count++;
+ }
+ }
+ return buffer.toString();
+ }
+
+}