summaryrefslogtreecommitdiffstats
path: root/java
diff options
context:
space:
mode:
authorantelder <antelder@13f79535-47bb-0310-9956-ffa450edef68>2009-11-16 07:58:46 +0000
committerantelder <antelder@13f79535-47bb-0310-9956-ffa450edef68>2009-11-16 07:58:46 +0000
commit825f3fa980c343cd85e67b8add68949724980feb (patch)
tree4d1efd76d7f4ccc371caeb98ecba5210fe446be9 /java
parentfa1d7440cb4bc2b257aee612dc1c5b866fb4bbf9 (diff)
Resurrect the JavaSCript client contributed in TUSCANY-417 and start getting it working with the 2.x runtime. Work in progress, but it does now work for listing/getting/invoking services in remote nodes using the tribes endpoint registry
git-svn-id: http://svn.us.apache.org/repos/asf/tuscany@880648 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'java')
-rw-r--r--java/sca/modules/sca-client-javascript/LICENSE205
-rw-r--r--java/sca/modules/sca-client-javascript/META-INF/MANIFEST.MF20
-rw-r--r--java/sca/modules/sca-client-javascript/NOTICE6
-rw-r--r--java/sca/modules/sca-client-javascript/pom.xml46
-rw-r--r--java/sca/modules/sca-client-javascript/src/main/java/org/apache/tuscany/sca/client/javascript/ScriptEngine.java662
-rw-r--r--java/sca/modules/sca-client-javascript/src/main/java/org/apache/tuscany/sca/client/javascript/TuscanyShell.java44
6 files changed, 983 insertions, 0 deletions
diff --git a/java/sca/modules/sca-client-javascript/LICENSE b/java/sca/modules/sca-client-javascript/LICENSE
new file mode 100644
index 0000000000..6e529a25c4
--- /dev/null
+++ b/java/sca/modules/sca-client-javascript/LICENSE
@@ -0,0 +1,205 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed 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.
+
+
+
diff --git a/java/sca/modules/sca-client-javascript/META-INF/MANIFEST.MF b/java/sca/modules/sca-client-javascript/META-INF/MANIFEST.MF
new file mode 100644
index 0000000000..db748f5b37
--- /dev/null
+++ b/java/sca/modules/sca-client-javascript/META-INF/MANIFEST.MF
@@ -0,0 +1,20 @@
+Manifest-Version: 1.0
+Tool: Bnd-0.0.255
+Bundle-Name: Apache Tuscany SCA Client JavaScript
+Created-By: 1.6.0_07 (Sun Microsystems Inc.)
+Bundle-Vendor: The Apache Software Foundation
+Bundle-Version: 2.0.0
+Bnd-LastModified: 1225397189093
+Bundle-ManifestVersion: 2
+Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt
+Bundle-Description: Apache Tuscany SCA Client JavaScript
+Import-Package: org.apache.tuscany.sca.assembly;version="2.0.0",
+ org.apache.tuscany.sca.client.rmi;version="2.0.0",
+ org.apache.tuscany.sca.core;version="2.0.0",
+ org.apache.tuscany.sca.interfacedef.java;version="2.0.0",
+ org.apache.tuscany.sca.runtime;version="2.0.0",
+ org.oasisopen.sca;version="2.0.0",
+ org.oasisopen.sca.client;version="2.0.0"
+Bundle-SymbolicName: org.apache.tuscany.sca.client.javascript
+Bundle-DocURL: http://www.apache.org/
+
diff --git a/java/sca/modules/sca-client-javascript/NOTICE b/java/sca/modules/sca-client-javascript/NOTICE
new file mode 100644
index 0000000000..51042eab05
--- /dev/null
+++ b/java/sca/modules/sca-client-javascript/NOTICE
@@ -0,0 +1,6 @@
+${pom.name}
+Copyright (c) 2005 - 2009 The Apache Software Foundation
+
+This product includes software developed by
+The Apache Software Foundation (http://www.apache.org/).
+
diff --git a/java/sca/modules/sca-client-javascript/pom.xml b/java/sca/modules/sca-client-javascript/pom.xml
new file mode 100644
index 0000000000..cb4278c0c7
--- /dev/null
+++ b/java/sca/modules/sca-client-javascript/pom.xml
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ * 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.
+-->
+<project>
+
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.tuscany.sca</groupId>
+ <artifactId>tuscany-modules</artifactId>
+ <version>2.0-SNAPSHOT</version>
+ <relativePath>../pom.xml</relativePath>
+ </parent>
+
+ <artifactId>tuscany-sca-client-javascript</artifactId>
+ <name>Apache Tuscany SCA Client JavaScript</name>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.tuscany.sca</groupId>
+ <artifactId>tuscany-sca-client-rmi</artifactId>
+ <version>2.0-SNAPSHOT</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.tuscany.sca</groupId>
+ <artifactId>tuscany-implementation-java-runtime</artifactId>
+ <version>2.0-SNAPSHOT</version>
+ </dependency>
+ </dependencies>
+
+</project>
diff --git a/java/sca/modules/sca-client-javascript/src/main/java/org/apache/tuscany/sca/client/javascript/ScriptEngine.java b/java/sca/modules/sca-client-javascript/src/main/java/org/apache/tuscany/sca/client/javascript/ScriptEngine.java
new file mode 100644
index 0000000000..3db6a6d08c
--- /dev/null
+++ b/java/sca/modules/sca-client-javascript/src/main/java/org/apache/tuscany/sca/client/javascript/ScriptEngine.java
@@ -0,0 +1,662 @@
+/**
+ *
+ * Copyright 2005 The Apache Software Foundation or its licensors, as applicable.
+ *
+ * Licensed 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.tuscany.sca.client.javascript;
+
+import java.io.BufferedReader;
+import java.io.CharArrayWriter;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.PrintStream;
+import java.io.PrintWriter;
+import java.lang.reflect.Method;
+import java.net.URI;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.List;
+
+import org.apache.tuscany.sca.assembly.AssemblyFactory;
+import org.apache.tuscany.sca.assembly.Endpoint;
+import org.apache.tuscany.sca.assembly.EndpointReference;
+import org.apache.tuscany.sca.client.rmi.SCAClientFactoryImpl;
+import org.apache.tuscany.sca.core.ExtensionPointRegistry;
+import org.apache.tuscany.sca.core.FactoryExtensionPoint;
+import org.apache.tuscany.sca.interfacedef.java.JavaInterface;
+import org.apache.tuscany.sca.runtime.EndpointRegistry;
+
+import sun.org.mozilla.javascript.internal.Context;
+import sun.org.mozilla.javascript.internal.Function;
+import sun.org.mozilla.javascript.internal.Scriptable;
+import sun.org.mozilla.javascript.internal.ScriptableObject;
+import sun.org.mozilla.javascript.internal.WrappedException;
+/**
+ *
+ * This class implements a Scripting Engine for the Tuscany runitme. This engine
+ * uses the Rhino javaScript Engine.
+ *
+ * <p> The default script functions supported by this engine are the following:
+ * <ul>
+ * <li>echo</li>
+ * <li>version</li>
+ * <li>load</li>
+ * <li>help</li>
+ * <li>exit</li>
+ * <li>printStackTrace</li>
+ * <li>loadModule</li>
+ * <li>listComponents</li>
+ * <li>getComponent</li>
+ * <li>listServices</li>
+ * <li>getService</li>
+ * </ul>
+ */
+public class ScriptEngine extends ScriptableObject implements Runnable{
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * The context with which this script engine will be run
+ */
+ private Context jsContext = null;
+
+ /**
+ * Set of parameters passes to the script engine
+ */
+ private String[] params = null;
+
+ /**
+ * instance of Tuscany runtime
+ */
+ private SCAClientFactoryImpl tuscany;
+
+ /**
+ * A reference to the old class loader
+ */
+ private ClassLoader oldClassLoader = null;
+
+ /**
+ * Flag to indicate, if the shoutdown has requested by the user
+ */
+ private boolean shutdown;
+
+ /**
+ * The current output stream
+ */
+ private static PrintStream out = System.out;
+
+ /**
+ * The current error output stream
+ */
+ private PrintStream err = System.err;
+
+ /**
+ * The current input stream
+ */
+ private InputStream in = System.in;
+
+ /**
+ * The prompt used
+ */
+ private String prompt = "js> ";
+
+ /**
+ * The last exception that occured, used for debugging
+ */
+ private Throwable lastException = null;
+
+ /**
+ * Names of the global functions particular to the shell. Note that these functions
+ * are not part of ECMA.
+ */
+ public static final String[] SCRIPT_FUNCTIONS = {
+ "echo",
+ "version",
+ "load",
+ "help",
+ "exit",
+ "printStackTrace",
+ "loadModule",
+ "listComponents",
+ "getComponent",
+ "listServices",
+ "getService", };
+
+ /**
+ * get the class name
+ * @return "global"
+ */
+ @Override
+ public String getClassName() {
+ return "global";
+ }
+
+ /**
+ * Construct a script engine
+ *
+ * @param command line arguments
+ */
+ public ScriptEngine(String[] params) {
+ this.params = params;
+ }
+
+ /**
+ * Run the script engine. Invoking this method will initialize the script engine,
+ * Tuscany Runtime and load any SCA modules if found in the classpath.
+ *
+ */
+ public void run() {
+ // Associate a new Context with this thread
+ jsContext = Context.enter();
+ try {
+ // initialize standard objects
+ jsContext.initStandardObjects(this);
+ // define supported script functions
+ this.defineFunctionProperties(SCRIPT_FUNCTIONS,
+ ScriptEngine.class,
+ ScriptableObject.DONTENUM);
+
+ // init the tuscany runtime
+ this.initTuscanyRuntime();
+ // initialize the script engine
+ this.startScriptEngine();
+ }
+ finally {
+ tuscany.stop();
+ Thread.currentThread().setContextClassLoader(oldClassLoader);
+ Context.exit();
+ }
+ }
+
+ /**
+ * Print the help message.
+ *
+ * This method is defined as a script function.
+ */
+ public void help() {
+ final String helpMsg =
+ "Command Description \n" +
+ "======= =========== \n" +
+ "help() Display this message. \n" +
+ "load(['f1.js', ...]) Load and execute javaScript source files named f1.js, etc. \n" +
+ "echo([expr ...]) Evaluate and print a variable or an expressions. \n" +
+ "exit() Exit this shell. \n" +
+ "version([number]) Get or set the javaScript version. \n" +
+ "printStackTrace() Print the stacktrace of the last exception \n" +
+ "loadModule(jar|war) Not yet implemented. \n" +
+ "listComponents() Not yet implemented. \n" +
+ "getComponent('name') Get an instance of the component with the given name. \n" +
+ "listServices() Not yet implemented. \n" +
+ "getService('name') Not yet implemented. \n";
+
+ out.println();
+ out.println(helpMsg);
+ }
+
+ /**
+ * Load a given module with the tuscany runtime
+ *
+ * This method is defined as a script function.
+ *
+ * @param moduleName absolute path of the module
+ */
+ public void loadModule(final String moduleName) {
+ try {
+ File file = new File(moduleName);
+ URL[] urls = new URL[] {file.toURL()};
+ final ClassLoader newCL = new URLClassLoader(urls);
+ Thread.currentThread().setContextClassLoader(newCL);
+ } catch (Exception e) {
+ err.println(e.getMessage());
+ lastException = e;
+ }
+ // TODO complete this method
+ /*
+ ModuleContext context = CurrentModuleContext.getContext();
+ out.println(context.toString());
+ tuscany.stop();
+
+ try {
+ File file = new File(moduleName);
+ URL[] urls = new URL[] {file.toURL(), };
+ final ClassLoader newCL = new URLClassLoader(urls);
+ Thread.currentThread().setContextClassLoader(newCL);
+
+ //Class c = Class.forName("customerinfo.CustomerInfoClient", true, newCL);
+ //out.println("c = " + c);
+
+ tuscany = new TuscanyRuntime(moduleName, null);
+ tuscany.start();
+
+ context = CurrentModuleContext.getContext();
+ out.println(context.toString());
+
+ //Object component = context.locateService("CustomerInfoServiceComponent");
+ //out.println(component);
+ }
+ catch (Exception e) {
+ err.println(e.getMessage());
+ lastException = e;
+ }
+ */
+ }
+
+ /**
+ * List the components available within the current module
+ *
+ * This method is defined as a script function.
+ */
+ public void listComponents() {
+ // TODO complete this method
+ }
+
+ /**
+ * Get the component available within the current module with a
+ * given name
+ *
+ * This method is defined as a script function.
+ *
+ * @param name name of the component
+ * @return service component object represented by the given name
+ */
+ public Object getComponent(String name) {
+// ModuleContext tuscanyContext = CurrentModuleContext.getContext();
+// Object component = tuscanyContext.locateService(name);
+
+// return component;
+ return null;
+ }
+
+ /**
+ * List the external services available within the current module
+ *
+ * This method is defined as a script function.
+ */
+ public void listServices() {
+ EndpointRegistry epr = tuscany.getEndpointRegistry();
+ for (Endpoint e : epr.getEndpoints()) {
+ out.println(e.getURI());
+ }
+ }
+
+ public Object getService(String serviceName) {
+ ExtensionPointRegistry extensionsRegistry = tuscany.getExtensionsRegistry();
+ FactoryExtensionPoint factories = extensionsRegistry.getExtensionPoint(FactoryExtensionPoint.class);
+ AssemblyFactory assemblyFactory = factories.getFactory(AssemblyFactory.class);
+
+ EndpointReference endpointReference = assemblyFactory.createEndpointReference();
+ endpointReference.setReference(assemblyFactory.createComponentReference());
+ Endpoint targetEndpoint = assemblyFactory.createEndpoint();
+ targetEndpoint.setURI(serviceName);
+ endpointReference.setTargetEndpoint(targetEndpoint);
+ EndpointRegistry epr = tuscany.getEndpointRegistry();
+ List<Endpoint> er = epr.findEndpoint(endpointReference);
+ if (er.size() < 1) {
+ err.println("service not found " + serviceName);
+ return null;
+ }
+ JavaInterface ifac = ((JavaInterface)er.get(0).getInterfaceContract().getInterface());
+ return getService(serviceName, ifac.getName());
+ }
+
+ /**
+ * Get an external service defined within the current module with a given name
+ *
+ * This method is defined as a script function.
+ *
+ * @param name name of the service
+ * @return service object represented by the given name
+ */
+ protected Object getService(String serviceName, String type) {
+ try {
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
+ Class<?> serviceInterface = cl.loadClass(type);
+ Object service = tuscany.getService(serviceInterface, serviceName);
+ printService(serviceInterface);
+ return service;
+ } catch (Exception e) {
+ err.println(e.getClass().getSimpleName() + ": " + e.getMessage());
+ lastException = e;
+ return null;
+ }
+ }
+
+ private void printService(Class<?> serviceInterface) {
+ out.println(serviceInterface.getName());
+ for (Method m : serviceInterface.getMethods()) {
+ out.print(" " + m.getReturnType().getName() + " " + m.getName() + "(");
+ boolean one = false;
+ for (Class arg : m.getParameterTypes()) {
+ if (one) {
+ out.print(", ");
+ }
+ out.print(arg.getName());
+ one = true;
+ }
+ out.println(")");
+ }
+ }
+
+ /**
+ * Echo a variable or a message.
+ *
+ * This method is defined as a script function.
+ *
+ * @param jsContext
+ * @param thisObj
+ * @param args
+ * @param function
+ */
+ public static void echo(Context jsContext, Scriptable thisObj, Object[] args, Function function)
+ {
+ if (args.length > 0) {
+ out.println(args[0]);
+ for (int i=1; i < args.length; i++) {
+ out.print(" " + Context.toString(args[i]));
+ }
+ }
+ out.println();
+ }
+
+ /**
+ * print the stacktrace of the last exception
+ *
+ * This method is defined as a script function.
+ */
+ public void printStackTrace() {
+ if (lastException == null) {
+ out.println("No stacktrace available");
+ }
+ else {
+ err.println(getStackTrace(lastException));
+ }
+ }
+
+ /**
+ * Exit the shell when it is in the interactive mode.
+ *
+ * This method is defined as a script function.
+ */
+ public void exit(){
+ shutdown = true;
+ }
+
+ /**
+ * Get and set the language version.
+ *
+ * This method is defined as a JavaScript function.
+ *
+ * @param jsContext
+ * @param thisObj
+ * @param args
+ * @param function
+ */
+ public static double version(Context jsContext, Scriptable thisObj, Object[] args, Function function)
+ {
+ if (args.length > 0) {
+ int i = (int)Context.toNumber(args[0]);
+ jsContext.setLanguageVersion(i);
+ }
+ return (double) jsContext.getLanguageVersion();
+ }
+
+ /**
+ * Load and execute a set of JavaScript source files.
+ *
+ * This method is defined as a JavaScript function.
+ *
+ * @param jsContext
+ * @param thisObj
+ * @param args
+ * @param function
+ */
+ public static void load(Context jsContext, Scriptable thisObj, Object[] args, Function function)
+ {
+ ScriptEngine engine = (ScriptEngine)getTopLevelScope(thisObj);
+ for (int i = 0; i < args.length; i++) {
+ engine.processFile(Context.toString(args[i]));
+ }
+ }
+
+ /**
+ * Get the current output stream
+ *
+ * @return current output stream
+ */
+ public PrintStream getOut() {
+ return out;
+ }
+
+ /**
+ * Set the current output stream
+ * @param out the new output stream
+ */
+ public void setOut(PrintStream out) {
+ ScriptEngine.out = out;
+ }
+
+ /**
+ * Get the current error output stream
+ *
+ * @return Returns the current error output stream.
+ */
+ public PrintStream getErr() {
+ return err;
+ }
+
+ /**
+ * Set the current error output stream
+ * @param err The new error output stream to set.
+ */
+ public void setErr(PrintStream err) {
+ this.err = err;
+ }
+
+ /**
+ * Get the current input stream
+ *
+ * @return Returns the current input stream.
+ */
+ public InputStream getIn() {
+ return in;
+ }
+
+ /**
+ * Set the current input stream
+ * @param in The new input stream to set.
+ */
+ public void setIn(InputStream in) {
+ this.in = in;
+ }
+
+ /**
+ * initialize the Tuscany runtime
+ *
+ */
+ protected void initTuscanyRuntime() {
+
+ // Required to allow the SDO runtime to use the correct classloader
+ oldClassLoader = Thread.currentThread().getContextClassLoader();
+// Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
+
+ tuscany = new SCAClientFactoryImpl(URI.create("tribes:foo"));
+
+// // Obtain and start the Tuscany runtime
+// try {
+// tuscany = new TuscanyRuntime("TuscanyClient", null);
+// tuscany.start();
+//
+// // this will get the module name; either specified by user or from the classpath
+// String moduleName = getCurrentModuleName();
+// // TODO how do we get all the components, services exposed by this module ?
+//
+// }
+// catch (ConfigurationException ce) {
+// err.println("Failed to start Tuscany runtime: " + ce.getMessage());
+// //ce.printStackTrace(err);
+// lastException = ce;
+// }
+ }
+
+
+ /**
+ * start the script engine
+ *
+ */
+ protected void startScriptEngine() {
+
+ out.println("Tuscany SCA Shell 0.1, type help() for a list of supported functions.");
+
+ // set up "arguments" in the global scope
+ if (params.length > 1) {
+ int length = params.length - 1;
+ Object obj[] = new Object[length];
+ System.arraycopy(params, 1, obj, 0, length);
+
+ Scriptable argsObj = jsContext.newArray(this, obj);
+ this.defineProperty("arguments", argsObj, ScriptableObject.DONTENUM);
+ }
+
+ if (params.length == 0) {
+ // no file name specified, go to interactive mode
+ this.startInteractiveMode();
+ }
+ else {
+ // TODO this could be a jar file or a script file
+ // process the specified file
+ this.processFile(params[0]);
+ }
+ System.gc();
+ }
+
+
+
+ /**
+ * Evaluate JavaScript source in the interactive mode.
+ *
+ */
+ private void startInteractiveMode()
+ {
+ // see if org.mozilla.javascript.tools.shell.Main.processSource() can handle this
+ //Main.setErr(this.getErr());
+ //Main.setOut(this.getOut());
+ //Main.setIn(this.getIn());
+ //Main.processSource(jsContext, filename);
+
+ BufferedReader reader = new BufferedReader(new InputStreamReader(in));
+ int currentLine = 1;
+ boolean done = false;
+ while (!shutdown && !done) {
+ out.print(prompt);
+ out.flush();
+ int lineToCompile = currentLine;
+ try {
+ StringBuffer source = new StringBuffer();
+ // read the next line entered by user
+ boolean compilable = false;
+ while(!compilable) {
+ String nextLine = reader.readLine();
+ if (nextLine != null) {
+ currentLine += 1;
+ source.append(nextLine).append("\n");
+ compilable = jsContext.stringIsCompilableUnit(source.toString());
+ }
+ else {
+ // TODO check if this can handle Ctrl+C
+ System.out.println("=== Ctrl+C pressed ==");
+ // break both the loops
+ done = true;
+ compilable = true;
+ }
+ }
+ Object result = jsContext.evaluateString(this, source.toString(), "<stdin>", lineToCompile, null);
+ if (result != Context.getUndefinedValue()) {
+ out.println(Context.toString(result));
+ }
+ }
+ catch (Exception e) {
+ if (e instanceof WrappedException) {
+ WrappedException we = (WrappedException)e;
+ err.println(we.getWrappedException().getMessage());
+ }
+ err.println(e.getMessage());
+ //e.printStackTrace(err);
+ lastException = e;
+ }
+ }
+ out.println();
+ }
+
+ /**
+ * Read the contents from a script file and execute it.
+ *
+ * @param filename the name of the file to compile
+ */
+ private void processFile(String fileName) {
+ BufferedReader reader = null;
+ try {
+ reader = new BufferedReader(new FileReader(fileName));
+ jsContext.evaluateReader(this, reader, fileName, 1, null);
+ }
+ catch (Exception e) {
+ if (e instanceof WrappedException) {
+ WrappedException we = (WrappedException)e;
+ err.println(we.getWrappedException().getMessage());
+ }
+ err.println(e.getLocalizedMessage());
+ //e.printStackTrace(err);
+ lastException = e;
+ }
+ finally {
+ try {
+ reader.close();
+ }
+ catch (IOException ioe) {
+ err.println(ioe.getLocalizedMessage());
+ //ioe.printStackTrace(err);
+ lastException = ioe;
+ }
+ }
+ }
+
+ /**
+ * Find the SCA module name. If the user have specified one, use that,
+ * otherwise, if there is a module definition in the path, pick it up.
+ *
+ * @return name of the module
+ */
+ private String getCurrentModuleName() {
+ String moduleName = "";
+
+ // TODO parse the arguments to see if there is an SCA module name
+ return moduleName;
+ }
+
+ /**
+ * Get the stacktrace for a give exception
+ *
+ * @param t Throwable from which the stacktrace need to be obtained
+ * @return char array containing the stack trace
+ */
+ private char[] getStackTrace(Throwable t) {
+ CharArrayWriter charWriter = new CharArrayWriter(2048);
+ PrintWriter writer = new PrintWriter(charWriter);
+ t.printStackTrace(writer);
+
+ return charWriter.toCharArray();
+ }
+}
diff --git a/java/sca/modules/sca-client-javascript/src/main/java/org/apache/tuscany/sca/client/javascript/TuscanyShell.java b/java/sca/modules/sca-client-javascript/src/main/java/org/apache/tuscany/sca/client/javascript/TuscanyShell.java
new file mode 100644
index 0000000000..abdbb2c677
--- /dev/null
+++ b/java/sca/modules/sca-client-javascript/src/main/java/org/apache/tuscany/sca/client/javascript/TuscanyShell.java
@@ -0,0 +1,44 @@
+/**
+ *
+ * Copyright 2005 The Apache Software Foundation or its licensors, as applicable.
+ *
+ * Licensed 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.tuscany.sca.client.javascript;
+
+/**
+ *
+ * This class provides a scripting shell that can be used as a Tuscany client. This shell
+ * extends from the Rhino JavaScript Engine's shell and provides capablities for working
+ * with the Tuscany Runtime.
+ *
+ * <p> This shell initializt the Tuscany Engine, using the input parameters that point to
+ * an SCA jar or war or a directory with an sca.module file. The Shell will load that module
+ * and then all the components and external services in the sca.module become available in the
+ * Shell, so that you can invoke them dynamically
+ *
+ */
+public class TuscanyShell {
+
+ /**
+ * Main entry point into the shell. This method invokes the
+ * <code>ScriptEngine</code>.
+ *
+ */
+ public static void main(String args[]) {
+ ScriptEngine engine = new ScriptEngine(args);
+ new Thread(engine).start();
+ }
+
+}