summaryrefslogtreecommitdiff
path: root/scripting/java/com/sun/star/script/framework/provider
diff options
context:
space:
mode:
Diffstat (limited to 'scripting/java/com/sun/star/script/framework/provider')
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/ClassLoaderFactory.java77
-rw-r--r--scripting/java/com/sun/star/script/framework/provider/EditorScriptContext.java103
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/NoSuitableClassLoaderException.java56
-rw-r--r--scripting/java/com/sun/star/script/framework/provider/PathUtils.java90
-rw-r--r--scripting/java/com/sun/star/script/framework/provider/ScriptContext.java168
-rw-r--r--scripting/java/com/sun/star/script/framework/provider/ScriptEditor.java13
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/ScriptProvider.java734
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/beanshell/PlainSourceView.java250
-rw-r--r--scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptEditorForBeanShell.java415
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/beanshell/ScriptProviderForBeanShell.java421
-rw-r--r--scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptSourceModel.java144
-rw-r--r--scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptSourceView.java38
-rw-r--r--scripting/java/com/sun/star/script/framework/provider/beanshell/template.bsh48
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/java/Resolver.java53
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/java/ScriptDescriptor.java215
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/java/ScriptProviderForJava.java402
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/java/ScriptProxy.java95
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/java/StrictResolver.java131
-rw-r--r--scripting/java/com/sun/star/script/framework/provider/javascript/ScriptEditorForJavaScript.java379
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/javascript/ScriptProviderForJavaScript.java395
-rw-r--r--scripting/java/com/sun/star/script/framework/provider/javascript/template.js37
21 files changed, 4264 insertions, 0 deletions
diff --git a/scripting/java/com/sun/star/script/framework/provider/ClassLoaderFactory.java b/scripting/java/com/sun/star/script/framework/provider/ClassLoaderFactory.java
new file mode 100755
index 000000000000..e3b4989657da
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/ClassLoaderFactory.java
@@ -0,0 +1,77 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ClassLoaderFactory.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+
+package com.sun.star.script.framework.provider;
+
+import java.net.*;
+
+import com.sun.star.script.framework.log.LogUtils;
+import com.sun.star.script.framework.container.ScriptMetaData;
+
+/**
+ * Class Loader Factory
+ *
+ * @author Noel Power
+ * @created August 2, 2002
+ */
+public class ClassLoaderFactory
+{
+ private ClassLoaderFactory() {}
+
+ public static ClassLoader getURLClassLoader( ScriptMetaData scriptData )
+ throws NoSuitableClassLoaderException, MalformedURLException
+ {
+ ClassLoader parent = scriptData.getClass().getClassLoader();
+ URL[] classPath = scriptData.getClassPath();
+ LogUtils.DEBUG("Classpath has length " + classPath.length );
+ for ( int i=0; i < classPath.length; i++ )
+ {
+ LogUtils.DEBUG("ClassPath " + i + "} is " + classPath[ i ].toString() );
+ }
+ return getURLClassLoader( parent, classPath );
+ }
+ public static ClassLoader getURLClassLoader( ClassLoader parent, URL[] classpath)
+ throws NoSuitableClassLoaderException
+ {
+ ClassLoader loader =
+ new URLClassLoader( classpath, parent);
+
+ if (loader != null)
+ {
+ return loader;
+ }
+ else
+ {
+ throw new NoSuitableClassLoaderException(
+ "Unable to create URLClassLoader");
+ }
+ }
+
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/EditorScriptContext.java b/scripting/java/com/sun/star/script/framework/provider/EditorScriptContext.java
new file mode 100644
index 000000000000..5a8b16ff2850
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/EditorScriptContext.java
@@ -0,0 +1,103 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: EditorScriptContext.java,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package com.sun.star.script.framework.provider;
+
+import com.sun.star.frame.XModel;
+import com.sun.star.frame.XDesktop;
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.document.XScriptInvocationContext;
+
+import com.sun.star.script.provider.XScriptContext;
+
+
+/**
+ * Description of the Class
+ *
+ * @author Noel Power
+ * @created August 2, 2002
+ */
+public class EditorScriptContext implements XScriptContext
+{
+ private XDesktop m_xDeskTop;
+ private XComponentContext m_xComponentContext;
+ private XDesktop m_xCtx;
+ public EditorScriptContext( XComponentContext xmComponentContext,
+ XDesktop xDesktop )
+ {
+ this.m_xComponentContext = xmComponentContext;
+ this.m_xDeskTop = xDesktop;
+ }
+
+ //----------------------------------------------------------------------
+ /**
+ Obtain the document reference on which the script can operate
+
+ @returns
+ XModel interface
+ */
+ public XModel getDocument()
+ {
+ XModel xModel = ( XModel ) UnoRuntime.queryInterface( XModel.class,
+ m_xDeskTop.getCurrentComponent() );
+
+ return xModel;
+ }
+
+ public XScriptInvocationContext getInvocationContext()
+ {
+ XScriptInvocationContext xContext = ( XScriptInvocationContext ) UnoRuntime.queryInterface(
+ XScriptInvocationContext.class, getDocument() );
+ return xContext;
+ }
+
+ /**
+ Obtain the desktop reference on which the script can operate
+
+ @returns
+ XDesktop interface
+ */
+ public XDesktop getDesktop()
+ {
+ return m_xDeskTop;
+ }
+
+ /**
+ Obtain the component context which the script can use to create other uno components
+
+ @returns
+ XComponentContext interface
+ */
+ public XComponentContext getComponentContext()
+ {
+ return m_xComponentContext;
+ }
+
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/NoSuitableClassLoaderException.java b/scripting/java/com/sun/star/script/framework/provider/NoSuitableClassLoaderException.java
new file mode 100755
index 000000000000..f37f12e239d4
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/NoSuitableClassLoaderException.java
@@ -0,0 +1,56 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: NoSuitableClassLoaderException.java,v $
+ * $Revision: 1.3 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package com.sun.star.script.framework.provider;
+
+public class NoSuitableClassLoaderException extends Exception
+{
+ /**
+ * Constructs an <code>NoSuitableClassLoaderException</code> with <code>null</code>
+ * as its error detail message.
+ */
+ public NoSuitableClassLoaderException()
+ {
+ super();
+ }
+ /**
+ * Constructs an <code>NoSuitBaleClassLoaderException</code> with the specified detail
+ * message. The error message string <code>s</code> can later be
+ * retrieved by the <code>{@link java.lang.Throwable#getMessage}</code>
+ * method of class <code>java.lang.Throwable</code>.
+ *
+ * @param s the detail message.
+ */
+ public NoSuitableClassLoaderException(String s)
+ {
+ super(s);
+ }
+
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/PathUtils.java b/scripting/java/com/sun/star/script/framework/provider/PathUtils.java
new file mode 100644
index 000000000000..cc45040e3c5c
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/PathUtils.java
@@ -0,0 +1,90 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: PathUtils.java,v $
+ * $Revision: 1.8.6.1 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package com.sun.star.script.framework.provider;
+
+import java.util.StringTokenizer;
+
+import java.lang.reflect.Method;
+
+import com.sun.star.frame.XModel;
+import com.sun.star.uno.IQueryInterface;
+
+public class PathUtils {
+
+ public static String FILE_URL_PREFIX;
+ public static String BOOTSTRAP_NAME;
+ private static boolean m_windows = false;
+
+ static {
+ // detect if windows platform
+ if (System.getProperty("os.name").startsWith("Windows"))
+ m_windows = true;
+
+ FILE_URL_PREFIX = m_windows ? "file:///" : "file://";
+ BOOTSTRAP_NAME = m_windows ? "bootstrap.ini" : "bootstraprc";
+ }
+ public static String getOidForModel( XModel xModel )
+ {
+ String oid = new String("");
+ if ( xModel != null )
+ {
+ try
+ {
+ Method getOid = IQueryInterface.class.getMethod("getOid", (java.lang.Class[])null);
+ if ( getOid != null )
+ {
+ oid = (String)getOid.invoke( xModel, new Object[0] );
+ }
+
+ }
+ catch ( Exception ignore )
+ {
+ }
+ }
+ return oid;
+ }
+ static public String make_url( String baseUrl, String url )
+ {
+ StringBuffer buff = new StringBuffer( baseUrl.length() + url.length() ); buff.append( baseUrl );
+ StringTokenizer t = new StringTokenizer( url, "/");
+ while ( t.hasMoreElements() )
+ {
+ if ( buff.charAt( buff.length() - 1 ) != '/' )
+ {
+ buff.append('/');
+ }
+ buff.append( java.net.URLEncoder.encode( (String)t.nextElement() ) ); }
+ return buff.toString();
+ }
+
+ private PathUtils() {
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/ScriptContext.java b/scripting/java/com/sun/star/script/framework/provider/ScriptContext.java
new file mode 100644
index 000000000000..a821ab6b393b
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/ScriptContext.java
@@ -0,0 +1,168 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptContext.java,v $
+ * $Revision: 1.11 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package com.sun.star.script.framework.provider;
+
+import com.sun.star.document.XScriptInvocationContext;
+import com.sun.star.frame.XModel;
+import com.sun.star.frame.XDesktop;
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.lang.XMultiComponentFactory;
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.beans.PropertyAttribute;
+import com.sun.star.lib.uno.helper.PropertySet;
+import com.sun.star.uno.Type;
+
+import com.sun.star.script.provider.XScriptContext;
+
+import com.sun.star.script.framework.log.LogUtils;
+
+
+/**
+ * Description of the Class
+ *
+ * @author Noel Power
+ * @created August 2, 2002
+ */
+public class ScriptContext extends PropertySet implements XScriptContext
+{
+ /**
+ * Description of the Class
+ *
+ * @author John Rice
+ * @created 18/09/02
+ */
+
+ public final static String HM_DOC_REF = "DocumentReference";
+ public final static String HM_DESKTOP = "Desktop";
+ public final static String HM_COMPONENT_CONTEXT = "ComponentContext";
+
+ private final static String DOC_REF = "SCRIPTING_DOC_REF";
+ private final static String DOC_URI = "SCRIPTING_DOC_URI";
+
+
+ public XModel m_xModel = null;
+ public XScriptInvocationContext m_xInvocationContext = null;
+ public String m_sDocURI = null;
+ public XDesktop m_xDeskTop = null;
+ public Integer m_iStorageID = null;
+ public XComponentContext m_xComponentContext = null;
+
+ public ScriptContext( XComponentContext xmComponentContext,
+ XDesktop xDesktop, XModel xModel, XScriptInvocationContext xInvocContext)
+ {
+ this.m_xDeskTop = xDesktop;
+ this.m_xComponentContext = xmComponentContext;
+ this.m_xModel = xModel;
+ this.m_xInvocationContext = xInvocContext;
+
+ if ( m_xModel != null )
+ {
+ registerProperty( DOC_URI, new Type(String.class),
+ (short)(PropertyAttribute.MAYBEVOID | PropertyAttribute.TRANSIENT), "m_sDocURI");
+ }
+
+ registerProperty( HM_DOC_REF, new Type(XModel.class),
+ (short)(PropertyAttribute.MAYBEVOID | PropertyAttribute.TRANSIENT), "m_xModel");
+ registerProperty( HM_DESKTOP, new Type(XDesktop.class),
+ (short)(PropertyAttribute.MAYBEVOID | PropertyAttribute.TRANSIENT), "m_xDeskTop");
+ registerProperty( HM_COMPONENT_CONTEXT, new Type(XDesktop.class),
+ (short)(PropertyAttribute.MAYBEVOID | PropertyAttribute.TRANSIENT), "m_xComponentContext");
+ }
+
+ public static XScriptContext createContext( XModel xModel, XScriptInvocationContext xInvocContext,
+ XComponentContext xCtxt, XMultiComponentFactory xMCF)
+ {
+ XScriptContext sc = null;
+
+ try {
+
+ Object xInterface = null;
+ XDesktop xDesktop = null;
+
+ xInterface = xMCF.createInstanceWithContext(
+ "com.sun.star.frame.Desktop", xCtxt);
+ xDesktop = (XDesktop)
+ UnoRuntime.queryInterface(XDesktop.class, xInterface);
+ if ( xModel != null )
+ {
+ sc = new ScriptContext(xCtxt, xDesktop, xModel, xInvocContext);
+ }
+ else
+ {
+ sc = new EditorScriptContext(xCtxt, xDesktop );
+ }
+
+ }
+ catch ( Exception e ) {
+ LogUtils.DEBUG( LogUtils.getTrace( e ) );
+ }
+ return sc;
+ }
+
+ //----------------------------------------------------------------------
+ /**
+ Obtain the document reference on which the script can operate
+
+ @returns
+ XModel interface
+ */
+ public XModel getDocument()
+ {
+ return m_xModel;
+ }
+
+ public XScriptInvocationContext getInvocationContext()
+ {
+ return m_xInvocationContext;
+ }
+
+ /**
+ Obtain the desktop reference on which the script can operate
+
+ @returns
+ XDesktop interface
+ */
+ public XDesktop getDesktop()
+ {
+ return m_xDeskTop;
+ }
+
+ /**
+ Obtain the component context which the script can use to create other uno components
+
+ @returns
+ XComponentContext interface
+ */
+ public XComponentContext getComponentContext()
+ {
+ return m_xComponentContext;
+ }
+
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/ScriptEditor.java b/scripting/java/com/sun/star/script/framework/provider/ScriptEditor.java
new file mode 100644
index 000000000000..e6654d2bd83f
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/ScriptEditor.java
@@ -0,0 +1,13 @@
+package com.sun.star.script.framework.provider;
+
+import com.sun.star.script.provider.XScriptContext;
+import com.sun.star.script.framework.container.ScriptMetaData;
+
+public interface ScriptEditor
+{
+ public Object execute() throws Exception;
+ public void indicateErrorLine( int lineNum );
+ public void edit(XScriptContext context, ScriptMetaData entry);
+ public String getTemplate();
+ public String getExtension();
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/ScriptProvider.java b/scripting/java/com/sun/star/script/framework/provider/ScriptProvider.java
new file mode 100755
index 000000000000..65c07349d740
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/ScriptProvider.java
@@ -0,0 +1,734 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptProvider.java,v $
+ * $Revision: 1.13.6.1 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package com.sun.star.script.framework.provider;
+
+import com.sun.star.container.XNameContainer;
+
+import com.sun.star.uno.Exception;
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.lang.XMultiComponentFactory;
+import com.sun.star.lang.XInitialization;
+import com.sun.star.lang.XTypeProvider;
+import com.sun.star.lang.XServiceInfo;
+import com.sun.star.frame.XModel;
+
+import com.sun.star.util.XMacroExpander;
+
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.uno.AnyConverter;
+import com.sun.star.uno.Type;
+
+import com.sun.star.beans.XPropertySet;
+import com.sun.star.beans.XVetoableChangeListener;
+import com.sun.star.beans.XPropertyChangeListener;
+import com.sun.star.beans.XPropertySetInfo;
+import com.sun.star.beans.Property;
+
+import com.sun.star.beans.XIntrospectionAccess;
+import com.sun.star.script.XInvocation;
+
+import com.sun.star.script.provider.XScriptContext;
+import com.sun.star.script.provider.XScriptProvider;
+import com.sun.star.script.provider.XScript;
+import com.sun.star.script.provider.ScriptFrameworkErrorException;
+import com.sun.star.script.provider.ScriptFrameworkErrorType;
+
+import com.sun.star.script.browse.XBrowseNode;
+import com.sun.star.script.browse.BrowseNodeTypes;
+
+import com.sun.star.script.framework.log.LogUtils;
+
+import com.sun.star.script.framework.container.ScriptMetaData;
+import com.sun.star.script.framework.container.XMLParserFactory;
+import com.sun.star.script.framework.container.ParcelContainer;
+import com.sun.star.script.framework.container.ParsedScriptUri;
+import com.sun.star.script.framework.container.UnoPkgContainer;
+
+import com.sun.star.ucb.Command;
+import com.sun.star.ucb.XContentProvider;
+import com.sun.star.ucb.XContent;
+import com.sun.star.ucb.XCommandProcessor;
+import com.sun.star.ucb.XContentIdentifier;
+import com.sun.star.ucb.XContentIdentifierFactory;
+
+import com.sun.star.sdbc.XRow;
+
+import com.sun.star.script.framework.browse.ProviderBrowseNode;
+import com.sun.star.script.framework.browse.DialogFactory;
+
+import com.sun.star.deployment.XPackage;
+
+
+import com.sun.star.document.XScriptInvocationContext;
+import com.sun.star.frame.XTransientDocumentsDocumentContentFactory;
+import com.sun.star.uno.TypeClass;
+
+public abstract class ScriptProvider
+ implements XScriptProvider, XBrowseNode, XPropertySet, XInvocation,
+ XInitialization, XTypeProvider, XServiceInfo, XNameContainer
+{
+ private final String[] __serviceNames = {
+ "com.sun.star.script.provider.ScriptProviderFor",
+ "com.sun.star.script.provider.LanguageScriptProvider"
+ };
+
+ public final static String CLASSPATH = "classpath";
+
+ protected String language;
+
+ protected XComponentContext m_xContext;
+ protected XMultiComponentFactory m_xMultiComponentFactory;
+ protected XModel m_xModel;
+ protected XScriptInvocationContext m_xInvocContext;
+ protected ParcelContainer m_container;
+
+ // proxies to helper objects which implement interfaces
+ private XPropertySet m_xPropertySetProxy;
+ private XInvocation m_xInvocationProxy;
+ // TODO should this be implemented in this class
+ private XBrowseNode m_xBrowseNodeProxy;
+ private XScriptContext m_xScriptContext;
+
+ public ScriptProvider( XComponentContext ctx, String language )
+ {
+ this.language = language;
+ __serviceNames[0] += language;
+
+ LogUtils.DEBUG( "ScriptProvider: constructor - start. " + language );
+
+ m_xContext = ctx;
+
+ // Initialize DialogFactory class in case dialogs are required
+ DialogFactory.createDialogFactory(m_xContext);
+
+ try
+ {
+ m_xMultiComponentFactory = m_xContext.getServiceManager();
+
+ if ( m_xMultiComponentFactory == null )
+ {
+ throw new Exception( "Error could not obtain a " +
+ "multicomponent factory - rethrowing Exception." );
+ }
+
+ Object serviceObj = m_xContext.getValueByName(
+ "/singletons/com.sun.star.util.theMacroExpander");
+
+ XMacroExpander me = (XMacroExpander) AnyConverter.toObject(
+ new Type(XMacroExpander.class), serviceObj);
+
+ XMLParserFactory.setOfficeDTDURL(me.expandMacros(
+ "${$BRAND_BASE_DIR/program/bootstraprc::BaseInstallation}/share/dtd/officedocument/1_0/"));
+
+ }
+ catch ( Exception e )
+ {
+ LogUtils.DEBUG( LogUtils.getTrace( e ) );
+ throw new com.sun.star.uno.RuntimeException(
+ "Error constructing ScriptProvider: "
+ + e.getMessage() );
+ }
+
+ LogUtils.DEBUG( "ScriptProvider: constructor - finished." );
+ }
+
+ synchronized public XScriptContext getScriptingContext()
+ {
+ if ( m_xScriptContext == null )
+ {
+ m_xScriptContext = ScriptContext.createContext( m_xModel, m_xInvocContext, m_xContext, m_xMultiComponentFactory );
+ }
+ return m_xScriptContext;
+ }
+ public void initialize( Object[] aArguments )
+ throws com.sun.star.uno.Exception
+ {
+ LogUtils.DEBUG( "entering XInit for language " + language);
+ boolean isPkgProvider = false;
+ if( aArguments.length == 1 )
+ {
+ String contextUrl = null;
+ if ( AnyConverter.getType(aArguments[0]).getTypeClass().equals(TypeClass.INTERFACE) )
+ {
+ // try whether it denotes a XScriptInvocationContext
+ m_xInvocContext = (XScriptInvocationContext)UnoRuntime.queryInterface(
+ XScriptInvocationContext.class, aArguments[0]);
+ if ( m_xInvocContext != null )
+ {
+ // if so, obtain the document - by definition, this must be
+ // the ScriptContainer
+ m_xModel = (XModel)UnoRuntime.queryInterface( XModel.class,
+ m_xInvocContext.getScriptContainer() );
+ }
+ else
+ {
+ // otherwise, check whether it's an XModel
+ m_xModel = (XModel)UnoRuntime.queryInterface( XModel.class,
+ m_xInvocContext.getScriptContainer() );
+ }
+ if ( m_xModel == null )
+ {
+ throw new com.sun.star.uno.Exception(
+ "ScriptProvider argument must be either a string, a valid XScriptInvocationContext, " +
+ "or an XModel", this);
+ }
+
+ contextUrl = getDocUrlFromModel( m_xModel );
+ m_container = new ParcelContainer( m_xContext, contextUrl, language );
+ }
+ else if (AnyConverter.isString(aArguments[0]) == true)
+ {
+ String originalContextURL = AnyConverter.toString(aArguments[0]);
+ LogUtils.DEBUG("creating Application, path: " + originalContextURL );
+ contextUrl = originalContextURL;
+ // TODO no support for packages in documents yet
+ if ( originalContextURL.startsWith( "vnd.sun.star.tdoc" ) )
+ {
+ m_container = new ParcelContainer( m_xContext, contextUrl, language );
+ m_xModel = getModelFromDocUrl( originalContextURL );
+ }
+ else
+ {
+ if ( originalContextURL.startsWith( "share" ) )
+ {
+ contextUrl = "vnd.sun.star.expand:${$BRAND_BASE_DIR/program/" + PathUtils.BOOTSTRAP_NAME + "::BaseInstallation}/share";
+ }
+ else if ( originalContextURL.startsWith( "user" ) )
+ {
+ contextUrl = "vnd.sun.star.expand:${$BRAND_BASE_DIR/program/" + PathUtils.BOOTSTRAP_NAME + "::UserInstallation}/user";
+ }
+
+ if ( originalContextURL.endsWith( "uno_packages") )
+ {
+ isPkgProvider = true;
+ }
+ if ( originalContextURL.endsWith( "uno_packages") && !originalContextURL.equals( contextUrl ) )
+ {
+ contextUrl = PathUtils.make_url( contextUrl, "uno_packages" );
+ }
+ if ( isPkgProvider )
+ {
+ m_container = new UnoPkgContainer( m_xContext, contextUrl, language );
+ }
+ else
+ {
+ m_container = new ParcelContainer( m_xContext, contextUrl, language );
+ }
+ }
+ }
+ else
+ {
+ throw new com.sun.star.uno.RuntimeException(
+ "ScriptProvider created with invalid argument");
+ }
+
+ LogUtils.DEBUG("Modified Application path is: " + contextUrl );
+ LogUtils.DEBUG("isPkgProvider is: " + isPkgProvider );
+
+ // TODO should all be done in this class instead of
+ // deleagation????
+ m_xBrowseNodeProxy = new ProviderBrowseNode( this,
+ m_container, m_xContext );
+
+ m_xInvocationProxy = (XInvocation)UnoRuntime.queryInterface(XInvocation.class, m_xBrowseNodeProxy);
+ m_xPropertySetProxy = (XPropertySet)UnoRuntime.queryInterface(XPropertySet.class, m_xBrowseNodeProxy);
+ }
+ else
+ {
+ // this is ok, for example when executing a script from the
+ // command line
+ LogUtils.DEBUG( "ScriptProviderFor" + language +
+ " initialized without a context");
+ }
+ LogUtils.DEBUG( "leaving XInit" );
+ }
+
+ /**
+ * Gets the types attribute of the ScriptProvider object
+ *
+ * @return The types value
+ */
+ public com.sun.star.uno.Type[] getTypes()
+ {
+ Type[] retValue = new Type[ 8 ];
+ retValue[ 0 ] = new Type( XScriptProvider.class );
+ retValue[ 1 ] = new Type( XBrowseNode.class );
+ retValue[ 2 ] = new Type( XInitialization.class );
+ retValue[ 3 ] = new Type( XTypeProvider.class );
+ retValue[ 4 ] = new Type( XServiceInfo.class );
+ retValue[ 5 ] = new Type( XPropertySet.class );
+ retValue[ 6 ] = new Type( XInvocation.class );
+ retValue[ 7 ] = new Type( com.sun.star.container.XNameContainer.class );
+ return retValue;
+ }
+
+ /**
+ * Gets the implementationId attribute of the ScriptProvider object
+ *
+ * @return The implementationId value
+ */
+ public byte[] getImplementationId()
+ {
+ return this.getClass().getName().getBytes();
+ }
+
+ /**
+ * Gets the implementationName attribute of the ScriptProvider object
+ *
+ * @return The implementationName value
+ */
+ public String getImplementationName()
+ {
+ return getClass().getName();
+ }
+
+ /**
+ * Description of the Method
+ *
+ * @param serviceName Description of the Parameter
+ * @return Description of the Return Value
+ */
+ public boolean supportsService( String serviceName )
+ {
+ for ( int index = __serviceNames.length; index-- > 0; )
+ {
+ if ( serviceName.equals( __serviceNames[ index ] ) )
+ {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Gets the supportedServiceNames attribute of the ScriptProvider object
+ *
+ * @return The supportedServiceNames value
+ */
+ public String[] getSupportedServiceNames()
+ {
+ return __serviceNames;
+ }
+
+
+
+ public abstract XScript getScript( /*IN*/String scriptURI )
+ throws com.sun.star.uno.RuntimeException,
+ ScriptFrameworkErrorException;
+
+ // TODO need to encapsulate this better,
+ // Some factory concept for creating/accessing Editor
+ // How this is passed down or how it is accessable by BrowseNode
+ // implementations needs thinking about
+ // This method is used to determine whether the ScriptProvider
+ // has a ScriptEditor
+ public abstract boolean hasScriptEditor();
+ // TODO see above
+ // This method is used to get the ScriptEditor for this ScriptProvider
+ public abstract ScriptEditor getScriptEditor();
+
+ public ScriptMetaData getScriptData( /*IN*/String scriptURI ) throws ScriptFrameworkErrorException
+
+ {
+ ParsedScriptUri details = null;
+ try
+ {
+ details = m_container.parseScriptUri( scriptURI );
+ ScriptMetaData scriptData = m_container.findScript( details );
+ if ( scriptData == null )
+ {
+ throw new ScriptFrameworkErrorException( details.function + " does not exist",
+ null, details.function, language, ScriptFrameworkErrorType.NO_SUCH_SCRIPT );
+ }
+ return scriptData;
+ }
+ catch ( com.sun.star.lang.IllegalArgumentException ila )
+ {
+ // TODO specify the correct error Type
+ throw new ScriptFrameworkErrorException( ila.getMessage(),
+ null, scriptURI, language, ScriptFrameworkErrorType.UNKNOWN );
+ }
+ catch ( com.sun.star.container.NoSuchElementException nse )
+ {
+ throw new ScriptFrameworkErrorException( nse.getMessage(),
+ null, details.function, language, ScriptFrameworkErrorType.NO_SUCH_SCRIPT );
+ }
+ catch ( com.sun.star.lang.WrappedTargetException wta )
+ {
+ // TODO specify the correct error Type
+ Exception wrapped = (Exception)wta.TargetException;
+ String message = wta.getMessage();
+ if ( wrapped != null )
+ {
+ message = wrapped.getMessage();
+ }
+ throw new ScriptFrameworkErrorException( message,
+ null, details.function, language, ScriptFrameworkErrorType.UNKNOWN );
+ }
+
+ }
+
+
+ // Implementation of XBrowseNode interface
+ public String getName()
+ {
+ return language;
+ }
+
+ public XBrowseNode[] getChildNodes()
+ {
+ if ( m_xBrowseNodeProxy == null )
+ {
+ LogUtils.DEBUG("No Nodes available ");
+ return new XBrowseNode[0];
+ }
+ return m_xBrowseNodeProxy .getChildNodes();
+ }
+
+ public boolean hasChildNodes()
+ {
+ if ( m_xBrowseNodeProxy == null )
+ {
+ LogUtils.DEBUG("No Nodes available ");
+ return false;
+ }
+ return m_xBrowseNodeProxy.hasChildNodes();
+ }
+
+ public short getType()
+ {
+ return BrowseNodeTypes.CONTAINER;
+ }
+
+ public String toString()
+ {
+ return getName();
+ }
+
+ // implementation of XInvocation interface
+ public XIntrospectionAccess getIntrospection() {
+ return m_xInvocationProxy.getIntrospection();
+ }
+
+ public Object invoke(String aFunctionName, Object[] aParams,
+ short[][] aOutParamIndex, Object[][] aOutParam)
+ throws com.sun.star.lang.IllegalArgumentException,
+ com.sun.star.script.CannotConvertException,
+ com.sun.star.reflection.InvocationTargetException
+ {
+ return m_xInvocationProxy.invoke(
+ aFunctionName, aParams, aOutParamIndex, aOutParam);
+ }
+
+ public void setValue(String aPropertyName, Object aValue)
+ throws com.sun.star.beans.UnknownPropertyException,
+ com.sun.star.script.CannotConvertException,
+ com.sun.star.reflection.InvocationTargetException
+ {
+ m_xInvocationProxy.setValue(aPropertyName, aValue);
+ }
+
+ public Object getValue(String aPropertyName)
+ throws com.sun.star.beans.UnknownPropertyException
+ {
+ return m_xInvocationProxy.getValue(aPropertyName);
+ }
+
+ public boolean hasMethod(String aName) {
+ return m_xInvocationProxy.hasMethod(aName);
+ }
+
+ public boolean hasProperty(String aName) {
+ return m_xInvocationProxy.hasProperty(aName);
+ }
+
+ public XPropertySetInfo getPropertySetInfo()
+ {
+ return m_xPropertySetProxy.getPropertySetInfo();
+ }
+
+ public void setPropertyValue(String aPropertyName, Object aValue)
+ throws com.sun.star.beans.UnknownPropertyException,
+ com.sun.star.beans.PropertyVetoException,
+ com.sun.star.lang.IllegalArgumentException,
+ com.sun.star.lang.WrappedTargetException
+ {
+ m_xPropertySetProxy.setPropertyValue(aPropertyName, aValue);
+ }
+
+ public Object getPropertyValue(String PropertyName)
+ throws com.sun.star.beans.UnknownPropertyException,
+ com.sun.star.lang.WrappedTargetException
+ {
+ return m_xPropertySetProxy.getPropertyValue(PropertyName);
+ }
+
+ public void addPropertyChangeListener(
+ String aPropertyName, XPropertyChangeListener xListener)
+ throws com.sun.star.beans.UnknownPropertyException,
+ com.sun.star.lang.WrappedTargetException
+ {
+ m_xPropertySetProxy.addPropertyChangeListener(aPropertyName, xListener);
+ }
+
+ public void removePropertyChangeListener(
+ String aPropertyName, XPropertyChangeListener aListener)
+ throws com.sun.star.beans.UnknownPropertyException,
+ com.sun.star.lang.WrappedTargetException
+ {
+ m_xPropertySetProxy.removePropertyChangeListener(
+ aPropertyName, aListener);
+ }
+
+ public void addVetoableChangeListener(
+ String PropertyName, XVetoableChangeListener aListener)
+ throws com.sun.star.beans.UnknownPropertyException,
+ com.sun.star.lang.WrappedTargetException
+ {
+ m_xPropertySetProxy.addVetoableChangeListener(PropertyName, aListener);
+ }
+
+ public void removeVetoableChangeListener(
+ String PropertyName, XVetoableChangeListener aListener)
+ throws com.sun.star.beans.UnknownPropertyException,
+ com.sun.star.lang.WrappedTargetException
+ {
+ m_xPropertySetProxy.removeVetoableChangeListener(
+ PropertyName, aListener);
+ }
+ public java.lang.Object getByName( String aName ) throws com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException
+ {
+ // TODO needs implementing?
+ if ( true )
+ {
+ throw new com.sun.star.uno.RuntimeException(
+ "getByName not implemented" );
+ }
+ return new Object();
+ }
+
+ public String[] getElementNames()
+ {
+ // TODO needs implementing?
+ String[] result = new String[0];
+ if ( true )
+ {
+ throw new com.sun.star.uno.RuntimeException(
+ "getElementNames not implemented" );
+
+ }
+ return result;
+ }
+
+
+ // Performs the getRegStatus functionality for the PkgMgr
+ public boolean hasByName( String aName )
+ {
+ boolean result = false;
+ if ( ((UnoPkgContainer)m_container).hasRegisteredUnoPkgContainer( aName ) )
+ {
+ result = true;
+ }
+ return result;
+ }
+
+ public com.sun.star.uno.Type getElementType()
+ {
+ // TODO at the moment this returns void indicating
+ // type is unknown should indicate XPackage ? do we implement XPackage
+ return new Type();
+ }
+
+ public boolean hasElements()
+ {
+ // TODO needs implementing?
+ boolean result = false;
+ if ( true )
+ {
+ throw new com.sun.star.uno.RuntimeException(
+ "hasElements not implemented" );
+
+ }
+ return result;
+ }
+ public void replaceByName( String aName, java.lang.Object aElement ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException
+ {
+ // TODO needs implementing
+ if ( true )
+ {
+ throw new com.sun.star.uno.RuntimeException(
+ "replaceByName not implemented" );
+
+ }
+ }
+
+ public void insertByName( String aName, java.lang.Object aElement ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.container.ElementExistException, com.sun.star.lang.WrappedTargetException
+ {
+ LogUtils.DEBUG("Provider for " + language + " received register for package " + aName );
+ XPackage newPackage = ( XPackage ) UnoRuntime.queryInterface( XPackage.class, aElement );
+ if ( aName.length() == 0 )
+ {
+ throw new com.sun.star.lang.IllegalArgumentException( "Empty name" );
+ }
+ if ( newPackage == null )
+ {
+ throw new com.sun.star.lang.IllegalArgumentException( "No package supplied" );
+ }
+
+ ((UnoPkgContainer)m_container).processUnoPackage( newPackage, language );
+ }
+
+ // de-register for library only !!
+ public void removeByName( String Name ) throws com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException
+ {
+ LogUtils.DEBUG("In ScriptProvider.removeByName() for " + Name + " this provider = " + language );
+ ParcelContainer c = ((UnoPkgContainer)m_container).getRegisteredUnoPkgContainer( Name );
+ if ( c != null )
+ {
+ String libName;
+ if (Name.endsWith("/"))
+ {
+ String tmp = Name.substring( 0, Name.lastIndexOf( "/" ) );
+ libName = tmp.substring( tmp.lastIndexOf( "/" ) + 1 );
+ }
+ else
+ {
+ libName = Name.substring( Name.lastIndexOf( "/" ) + 1 );
+ }
+ LogUtils.DEBUG("Deregistering library " + libName );
+ if ( c.removeParcel( libName ) )
+ {
+ ((UnoPkgContainer)m_container).deRegisterPackageContainer( Name );
+ }
+ else
+ {
+ throw new com.sun.star.container.NoSuchElementException( libName + " cannot be removed from container." );
+ }
+ }
+ else
+ {
+ throw new com.sun.star.container.NoSuchElementException( Name + " doesn't exist for " + language );
+ }
+ // TODO see if we want to remove the ParcelContainer is no Parcels/Libraries left
+ }
+
+ private String getDocUrlFromModel( XModel document )
+ {
+ XTransientDocumentsDocumentContentFactory factory = null;
+ try
+ {
+ factory = (XTransientDocumentsDocumentContentFactory)UnoRuntime.queryInterface(
+ XTransientDocumentsDocumentContentFactory.class,
+ m_xMultiComponentFactory.createInstanceWithContext(
+ "com.sun.star.frame.TransientDocumentsDocumentContentFactory",
+ m_xContext
+ )
+ );
+ }
+ catch (Exception ex)
+ {
+ }
+
+ if ( factory == null )
+ throw new com.sun.star.uno.RuntimeException( "ScriptProvider: unable to create a TDOC context factory.", this );
+
+ try
+ {
+ XContent content = factory.createDocumentContent( document );
+ return content.getIdentifier().getContentIdentifier();
+ }
+ catch( Exception ex )
+ {
+ }
+
+ LogUtils.DEBUG("unable to determine the model's TDOC URL");
+ return "";
+ }
+
+ private XModel getModelFromDocUrl( String docUrl )
+ {
+ LogUtils.DEBUG("getModelFromDocUrl - searching for match for ->" + docUrl + "<-" );
+ XModel xModel = null;
+ try
+ {
+ Object[] args = new String[] {"Local", "Office" };
+
+ Object ucb = m_xMultiComponentFactory.createInstanceWithArgumentsAndContext( "com.sun.star.ucb.UniversalContentBroker", args, m_xContext );
+
+
+ XContentIdentifierFactory xFac = ( XContentIdentifierFactory )
+ UnoRuntime.queryInterface( XContentIdentifierFactory.class,
+ ucb );
+
+
+ XContentIdentifier xCntId = xFac.createContentIdentifier( docUrl );
+
+
+ XContentProvider xCntAccess = ( XContentProvider )
+ UnoRuntime.queryInterface( XContentProvider.class,
+ ucb );
+
+
+ XContent xCnt = xCntAccess.queryContent( xCntId );
+
+
+ XCommandProcessor xCmd = ( XCommandProcessor )
+ UnoRuntime.queryInterface( XCommandProcessor.class, xCnt );
+
+
+ Property[] pArgs = new Property[ ] { new Property() };
+ pArgs[ 0 ].Name = "DocumentModel";
+ pArgs[ 0 ].Handle = -1;
+
+ Command command = new Command();
+
+ command.Handle = -1;
+ command.Name = "getPropertyValues";
+ command.Argument = pArgs;
+
+ com.sun.star.ucb.XCommandEnvironment env = null ;
+ Object result = xCmd.execute( command, 0, env ) ;
+
+ XRow values = ( XRow ) UnoRuntime.queryInterface( XRow.class,
+ result );
+
+ xModel = ( XModel ) UnoRuntime.queryInterface( XModel.class,
+ values.getObject( 1, null ) );
+ }
+ catch ( Exception ignore )
+ {
+ LogUtils.DEBUG("Failed to get model exception " + ignore );
+
+ }
+ return xModel;
+ }
+
+
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/beanshell/PlainSourceView.java b/scripting/java/com/sun/star/script/framework/provider/beanshell/PlainSourceView.java
new file mode 100755
index 000000000000..617c99051250
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/beanshell/PlainSourceView.java
@@ -0,0 +1,250 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: PlainSourceView.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package com.sun.star.script.framework.provider.beanshell;
+
+import javax.swing.JTextArea;
+import javax.swing.JScrollPane;
+import javax.swing.JComponent;
+import javax.swing.event.DocumentListener;
+import javax.swing.event.DocumentEvent;
+
+import java.awt.Graphics;
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.Polygon;
+import java.awt.Rectangle;
+import java.awt.Dimension;
+
+public class PlainSourceView extends JScrollPane
+ implements ScriptSourceView, DocumentListener {
+
+ private ScriptSourceModel model;
+ private JTextArea ta;
+ private GlyphGutter gg;
+ private int linecount;
+ private boolean isModified = false;
+
+ public PlainSourceView(ScriptSourceModel model) {
+ this.model = model;
+ initUI();
+ model.setView(this);
+ }
+
+ public void clear() {
+ ta.setText("");
+ }
+
+ public void update() {
+ /* Remove ourselves as a DocumentListener while loading the source
+ so we don't get a storm of DocumentEvents during loading */
+ ta.getDocument().removeDocumentListener(this);
+
+ if (isModified == false)
+ {
+ int pos = ta.getCaretPosition();
+ ta.setText(model.getText());
+ try {
+ ta.setCaretPosition(pos);
+ }
+ catch (IllegalArgumentException iae) {
+ // do nothing and allow JTextArea to set it's own position
+ }
+ }
+
+ // scroll to currentPosition of the model
+ try {
+ int line = ta.getLineStartOffset(model.getCurrentPosition());
+ Rectangle rect = ta.modelToView(line);
+ ta.scrollRectToVisible(rect);
+ }
+ catch (Exception e) {
+ // couldn't scroll to line, do nothing
+ }
+
+ gg.repaint();
+
+ // Add back the listener
+ ta.getDocument().addDocumentListener(this);
+ }
+
+ public boolean isModified() {
+ return isModified;
+ }
+
+ public void setModified(boolean value) {
+ isModified = value;
+ }
+
+ private void initUI() {
+ ta = new JTextArea();
+ ta.setRows(15);
+ ta.setColumns(40);
+ ta.setLineWrap(false);
+ ta.insert(model.getText(), 0);
+ linecount = ta.getLineCount();
+
+ gg = new GlyphGutter(this);
+
+ setViewportView(ta);
+ setRowHeaderView(gg);
+
+ ta.getDocument().addDocumentListener(this);
+ }
+
+ /* Implementation of DocumentListener interface */
+ public void insertUpdate(DocumentEvent e) {
+ doChanged(e);
+ }
+
+ public void removeUpdate(DocumentEvent e) {
+ doChanged(e);
+ }
+
+ public void changedUpdate(DocumentEvent e) {
+ doChanged(e);
+ }
+
+ /* If the number of lines in the JTextArea has changed then update the
+ GlyphGutter */
+ public void doChanged(DocumentEvent e) {
+ isModified = true;
+
+ if (linecount != ta.getLineCount()) {
+ gg.update();
+ linecount = ta.getLineCount();
+ }
+ }
+
+ public String getText() {
+ return ta.getText();
+ }
+
+ public JTextArea getTextArea() {
+ return ta;
+ }
+
+ public int getCurrentPosition() {
+ return model.getCurrentPosition();
+ }
+}
+
+class GlyphGutter extends JComponent {
+
+ private PlainSourceView view;
+ private final String DUMMY_STRING = "99";
+
+ GlyphGutter(PlainSourceView view) {
+ this.view = view;
+ update();
+ }
+
+ public void update() {
+ JTextArea textArea = view.getTextArea();
+ Font font = textArea.getFont();
+ setFont(font);
+
+ FontMetrics metrics = getFontMetrics(font);
+ int h = metrics.getHeight();
+ int lineCount = textArea.getLineCount() + 1;
+
+ String dummy = Integer.toString(lineCount);
+ if (dummy.length() < 2) {
+ dummy = DUMMY_STRING;
+ }
+
+ Dimension d = new Dimension();
+ d.width = metrics.stringWidth(dummy) + 16;
+ d.height = lineCount * h + 100;
+ setPreferredSize(d);
+ setSize(d);
+ }
+
+ public void paintComponent(Graphics g) {
+ JTextArea textArea = view.getTextArea();
+
+ Font font = textArea.getFont();
+ g.setFont(font);
+
+ FontMetrics metrics = getFontMetrics(font);
+ Rectangle clip = g.getClipBounds();
+
+ g.setColor(getBackground());
+ g.fillRect(clip.x, clip.y, clip.width, clip.height);
+
+ int ascent = metrics.getMaxAscent();
+ int h = metrics.getHeight();
+ int lineCount = textArea.getLineCount() + 1;
+
+ int startLine = clip.y / h;
+ int endLine = (clip.y + clip.height) / h + 1;
+ int width = getWidth();
+ if (endLine > lineCount) {
+ endLine = lineCount;
+ }
+
+ for (int i = startLine; i < endLine; i++) {
+ String text;
+ text = Integer.toString(i + 1) + " ";
+ int w = metrics.stringWidth(text);
+ int y = i * h;
+ g.setColor(Color.blue);
+ g.drawString(text, 0, y + ascent);
+ int x = width - ascent;
+
+ // if currentPosition is not -1 then a red arrow will be drawn
+ if (i == view.getCurrentPosition()) {
+ drawArrow(g, ascent, x, y);
+ }
+ }
+ }
+
+ private void drawArrow(Graphics g, int ascent, int x, int y) {
+ Polygon arrow = new Polygon();
+ int dx = x;
+ y += ascent - 10;
+ int dy = y;
+ arrow.addPoint(dx, dy + 3);
+ arrow.addPoint(dx + 5, dy + 3);
+ for (x = dx + 5; x <= dx + 10; x++, y++) {
+ arrow.addPoint(x, y);
+ }
+ for (x = dx + 9; x >= dx + 5; x--, y++) {
+ arrow.addPoint(x, y);
+ }
+ arrow.addPoint(dx + 5, dy + 7);
+ arrow.addPoint(dx, dy + 7);
+
+ g.setColor(Color.red);
+ g.fillPolygon(arrow);
+ g.setColor(Color.black);
+ g.drawPolygon(arrow);
+ }
+};
diff --git a/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptEditorForBeanShell.java b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptEditorForBeanShell.java
new file mode 100644
index 000000000000..c7286ccb2a0a
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptEditorForBeanShell.java
@@ -0,0 +1,415 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptEditorForBeanShell.java,v $
+ * $Revision: 1.9 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package com.sun.star.script.framework.provider.beanshell;
+
+import javax.swing.JComponent;
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+import javax.swing.JButton;
+import javax.swing.JOptionPane;
+
+import java.awt.FlowLayout;
+import java.awt.event.ActionListener;
+import java.awt.event.ActionEvent;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.IOException;
+import java.net.URL;
+import java.util.Map;
+import java.util.HashMap;
+
+import com.sun.star.script.provider.XScriptContext;
+import com.sun.star.script.framework.provider.ScriptEditor;
+import com.sun.star.script.framework.container.ScriptMetaData;
+import com.sun.star.script.framework.provider.ClassLoaderFactory;
+
+public class ScriptEditorForBeanShell
+ implements ScriptEditor, ActionListener
+{
+ private JFrame frame;
+ private String filename;
+
+ private ScriptSourceModel model;
+ private ScriptSourceView view;
+
+ private XScriptContext context;
+ private URL scriptURL = null;
+ private ClassLoader cl = null;
+
+ // global ScriptEditorForBeanShell returned for getEditor() calls
+ private static ScriptEditorForBeanShell theScriptEditorForBeanShell;
+
+ // global list of ScriptEditors, key is URL of file being edited
+ private static Map BEING_EDITED = new HashMap();
+
+ // template for new BeanShell scripts
+ private static String BSHTEMPLATE;
+
+ // try to load the template for BeanShell scripts
+ static {
+ try {
+ URL url =
+ ScriptEditorForBeanShell.class.getResource("template.bsh");
+
+ InputStream in = url.openStream();
+ StringBuffer buf = new StringBuffer();
+ byte[] b = new byte[1024];
+ int len = 0;
+
+ while ((len = in.read(b)) != -1) {
+ buf.append(new String(b, 0, len));
+ }
+
+ in.close();
+
+ BSHTEMPLATE = buf.toString();
+ }
+ catch (IOException ioe) {
+ BSHTEMPLATE = "// BeanShell script";
+ }
+ catch (Exception e) {
+ BSHTEMPLATE = "// BeanShell script";
+ }
+ }
+
+ /**
+ * Returns the global ScriptEditorForBeanShell instance.
+ */
+ public static ScriptEditorForBeanShell getEditor()
+ {
+ if (theScriptEditorForBeanShell == null)
+ {
+ synchronized(ScriptEditorForBeanShell.class)
+ {
+ if (theScriptEditorForBeanShell == null)
+ {
+ theScriptEditorForBeanShell =
+ new ScriptEditorForBeanShell();
+ }
+ }
+ }
+ return theScriptEditorForBeanShell;
+ }
+
+ /**
+ * Get the ScriptEditorForBeanShell instance for this URL
+ *
+ * @param url The URL of the script source file
+ *
+ * @return The ScriptEditorForBeanShell associated with
+ * the given URL if one exists, otherwise null.
+ */
+ public static ScriptEditorForBeanShell getEditor(URL url)
+ {
+ return (ScriptEditorForBeanShell)BEING_EDITED.get(url);
+ }
+
+ /**
+ * Returns whether or not the script source being edited in this
+ * ScriptEditorForBeanShell has been modified
+ */
+ public boolean isModified()
+ {
+ return view.isModified();
+ }
+
+ /**
+ * Returns the text being displayed in this ScriptEditorForBeanShell
+ *
+ * @return The text displayed in this ScriptEditorForBeanShell
+ */
+ public String getText()
+ {
+ return view.getText();
+ }
+
+ /**
+ * Returns the template text for BeanShell scripts
+ *
+ * @return The template text for BeanShell scripts
+ */
+ public String getTemplate() {
+ return BSHTEMPLATE;
+ }
+
+ /**
+ * Returns the default extension for BeanShell scripts
+ *
+ * @return The default extension for BeanShell scripts
+ */
+ public String getExtension() {
+ return "bsh";
+ }
+
+
+ /**
+ * Indicates the line where error occured
+ *
+ */
+ public void indicateErrorLine( int lineNum )
+ {
+ model.indicateErrorLine( lineNum );
+ }
+ /**
+ * Executes the script edited by the editor
+ *
+ */
+ public Object execute() throws Exception {
+ frame.toFront();
+ return model.execute( context, cl );
+ }
+ /**
+ * Opens an editor window for the specified ScriptMetaData.
+ * If an editor window is already open for that data it will be
+ * moved to the front.
+ *
+ * @param metadata The metadata describing the script
+ * @param context The context in which to execute the script
+ *
+ */
+ public void edit(XScriptContext context, ScriptMetaData entry) {
+
+ if (entry != null ) {
+ try {
+ ClassLoader cl = null;
+ try {
+ cl = ClassLoaderFactory.getURLClassLoader( entry );
+ }
+ catch (Exception ignore) // TODO re-examine error handling
+ {
+ }
+ String sUrl = entry.getParcelLocation();
+ if ( !sUrl.endsWith( "/" ) )
+ {
+ sUrl += "/";
+ }
+ sUrl += entry.getLanguageName();
+ URL url = entry.getSourceURL();
+
+ // check if there is already an editing session for this script
+ if (BEING_EDITED.containsKey(url))
+ {
+ ScriptEditorForBeanShell editor =
+ (ScriptEditorForBeanShell) BEING_EDITED.get(url);
+
+ editor.frame.toFront();
+ }
+ else
+ {
+ new ScriptEditorForBeanShell(context, cl, url);
+ }
+ }
+ catch (IOException ioe) {
+ showErrorMessage( "Error loading file: " + ioe.getMessage() );
+ }
+ }
+ }
+
+ private ScriptEditorForBeanShell() {
+ }
+
+ private ScriptEditorForBeanShell(XScriptContext context, ClassLoader cl,
+ URL url)
+ {
+ this.context = context;
+ this.scriptURL = url;
+ this.model = new ScriptSourceModel(url);
+ this.filename = url.getFile();
+ this.cl = cl;
+ try {
+ Class c = Class.forName(
+ "org.openoffice.netbeans.editor.NetBeansSourceView");
+
+ Class[] types = new Class[] { ScriptSourceModel.class };
+
+ java.lang.reflect.Constructor ctor = c.getConstructor(types);
+
+ if (ctor != null) {
+ Object[] args = new Object[] { this.model };
+ this.view = (ScriptSourceView) ctor.newInstance(args);
+ }
+ else {
+ this.view = new PlainSourceView(model);
+ }
+ }
+ catch (java.lang.Error err) {
+ this.view = new PlainSourceView(model);
+ }
+ catch (Exception e) {
+ this.view = new PlainSourceView(model);
+ }
+
+ this.model.setView(this.view);
+ initUI();
+ frame.show();
+
+ BEING_EDITED.put(url, this);
+ }
+
+ private void showErrorMessage(String message) {
+ JOptionPane.showMessageDialog(frame, message,
+ "Error", JOptionPane.ERROR_MESSAGE);
+ }
+
+ private void initUI() {
+ frame = new JFrame("BeanShell Debug Window: " + filename);
+ frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
+
+ frame.addWindowListener(
+ new WindowAdapter()
+ {
+ public void windowClosing(WindowEvent e) {
+ doClose();
+ }
+ }
+ );
+
+ String[] labels = {"Run", "Clear", "Save", "Close"};
+ JPanel p = new JPanel();
+ p.setLayout(new FlowLayout());
+
+ for (int i = 0; i < labels.length; i++) {
+ JButton b = new JButton(labels[i]);
+ b.addActionListener(this);
+ p.add(b);
+
+ if (labels[i].equals("Save") && filename == null) {
+ b.setEnabled(false);
+ }
+ }
+
+ frame.getContentPane().add((JComponent)view, "Center");
+ frame.getContentPane().add(p, "South");
+ frame.pack();
+ frame.setSize(590, 480);
+ frame.setLocation(300, 200);
+ }
+
+ private void doClose() {
+ if (view.isModified()) {
+ int result = JOptionPane.showConfirmDialog(frame,
+ "The script has been modified. " +
+ "Do you want to save the changes?");
+
+ if (result == JOptionPane.CANCEL_OPTION)
+ {
+ // don't close the window, just return
+ return;
+ }
+ else if (result == JOptionPane.YES_OPTION)
+ {
+ boolean saveSuccess = saveTextArea();
+ if (saveSuccess == false)
+ {
+ return;
+ }
+ }
+ }
+ frame.dispose();
+ shutdown();
+ }
+
+ private boolean saveTextArea() {
+ boolean result = true;
+
+ if (!view.isModified()) {
+ return true;
+ }
+
+ OutputStream fos = null;
+ try {
+ String s = view.getText();
+ fos = scriptURL.openConnection().getOutputStream();
+ if ( fos != null) {
+ fos.write(s.getBytes());
+ }
+ else
+ {
+ showErrorMessage(
+ "Error saving script: Could not open stream for file" );
+ result = false;
+ }
+ view.setModified(false);
+ }
+ catch (IOException ioe) {
+ showErrorMessage( "Error saving script: " + ioe.getMessage() );
+ result = false;
+ }
+ catch (Exception e) {
+ showErrorMessage( "Error saving script: " + e.getMessage() );
+ result = false;
+ }
+ finally {
+ if (fos != null) {
+ try {
+ fos.flush();
+ if ( fos != null )
+ {
+ fos.close();
+ }
+ }
+ catch (IOException ignore) {
+ }
+ }
+ }
+ return result;
+ }
+
+ private void shutdown()
+ {
+ if (BEING_EDITED.containsKey(scriptURL)) {
+ BEING_EDITED.remove(scriptURL);
+ }
+ }
+
+ public void actionPerformed(ActionEvent e) {
+ if (e.getActionCommand().equals("Run")) {
+ try
+ {
+ execute();
+ }
+ catch (Exception invokeException ) {
+ showErrorMessage(invokeException.getMessage());
+ }
+ }
+ else if (e.getActionCommand().equals("Close")) {
+ doClose();
+ }
+ else if (e.getActionCommand().equals("Save")) {
+ saveTextArea();
+ }
+ else if (e.getActionCommand().equals("Clear")) {
+ view.clear();
+ }
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptProviderForBeanShell.java b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptProviderForBeanShell.java
new file mode 100755
index 000000000000..732013601c76
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptProviderForBeanShell.java
@@ -0,0 +1,421 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptProviderForBeanShell.java,v $
+ * $Revision: 1.11.6.1 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package com.sun.star.script.framework.provider.beanshell;
+
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.lang.XMultiComponentFactory;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.lang.XSingleServiceFactory;
+import com.sun.star.registry.XRegistryKey;
+import com.sun.star.comp.loader.FactoryHelper;
+import com.sun.star.frame.XModel;
+import com.sun.star.uno.Type;
+import com.sun.star.uno.Any;
+
+import com.sun.star.reflection.InvocationTargetException;
+
+import java.util.StringTokenizer;
+
+import java.net.URL;
+
+import bsh.Interpreter;
+
+import com.sun.star.document.XScriptInvocationContext;
+import com.sun.star.script.provider.XScript;
+import com.sun.star.script.provider.ScriptErrorRaisedException;
+import com.sun.star.script.provider.ScriptExceptionRaisedException;
+import com.sun.star.script.provider.ScriptFrameworkErrorException;
+import com.sun.star.script.provider.ScriptFrameworkErrorType;
+
+
+import com.sun.star.script.framework.provider.*;
+import com.sun.star.script.framework.log.*;
+import com.sun.star.script.framework.container.ScriptMetaData;
+
+public class ScriptProviderForBeanShell
+{
+ public static class _ScriptProviderForBeanShell extends ScriptProvider
+ {
+ public _ScriptProviderForBeanShell(XComponentContext ctx)
+ {
+ super (ctx, "BeanShell");
+ }
+
+ public XScript getScript( /*IN*/String scriptURI )
+ throws com.sun.star.uno.RuntimeException,
+ ScriptFrameworkErrorException
+ {
+ ScriptMetaData scriptData = null;
+ try
+ {
+ scriptData = getScriptData( scriptURI );
+ ScriptImpl script = new ScriptImpl( m_xContext, scriptData, m_xModel, m_xInvocContext );
+ return script;
+ }
+ catch ( com.sun.star.uno.RuntimeException re )
+ {
+ throw new ScriptFrameworkErrorException( "Failed to create script object: " + re.getMessage(),
+ null, scriptData.getLanguageName(), language, ScriptFrameworkErrorType.UNKNOWN );
+ }
+ }
+
+ public boolean hasScriptEditor()
+ {
+ return true;
+ }
+
+ public ScriptEditor getScriptEditor()
+ {
+ return ScriptEditorForBeanShell.getEditor();
+ }
+ }
+
+ /**
+ * Returns a factory for creating the service.
+ * This method is called by the <code>JavaLoader</code>
+ * <p>
+ *
+ * @param implName the name of the implementation for which a service is desired
+ * @param multiFactory the service manager to be used if needed
+ * @param regKey the registryKey
+ * @return returns a <code>XSingleServiceFactory</code> for creating
+ * the component
+ * @see com.sun.star.comp.loader.JavaLoader
+ */
+ public static XSingleServiceFactory __getServiceFactory( String implName,
+ XMultiServiceFactory multiFactory,
+ XRegistryKey regKey )
+ {
+ XSingleServiceFactory xSingleServiceFactory = null;
+
+ if ( implName.equals( ScriptProviderForBeanShell._ScriptProviderForBeanShell.class.getName() ) )
+ {
+ xSingleServiceFactory = FactoryHelper.getServiceFactory(
+ ScriptProviderForBeanShell._ScriptProviderForBeanShell.class,
+ "com.sun.star.script.ScriptProviderForBeanShell",
+ multiFactory,
+ regKey );
+ }
+
+ return xSingleServiceFactory;
+ }
+
+
+ /**
+ * Writes the service information into the given registry key.
+ * This method is called by the <code>JavaLoader</code>
+ * <p>
+ *
+ * @param regKey the registryKey
+ * @return returns true if the operation succeeded
+ * @see com.sun.star.comp.loader.JavaLoader
+ */
+ public static boolean __writeRegistryServiceInfo( XRegistryKey regKey )
+ {
+ String impl = "com.sun.star.script.framework.provider.beanshell." +
+ "ScriptProviderForBeanShell$_ScriptProviderForBeanShell";
+
+ String service1 = "com.sun.star.script.provider." +
+ "ScriptProvider";
+ String service2 = "com.sun.star.script.provider." +
+ "LanguageScriptProvider";
+ String service3 = "com.sun.star.script.provider." +
+ "ScriptProviderForBeanShell";
+ String service4 = "com.sun.star.script.browse." +
+ "BrowseNode";
+
+ if ( FactoryHelper.writeRegistryServiceInfo(impl, service1, regKey) &&
+ FactoryHelper.writeRegistryServiceInfo(impl, service2, regKey) &&
+ FactoryHelper.writeRegistryServiceInfo(impl, service3, regKey) &&
+ FactoryHelper.writeRegistryServiceInfo(impl, service4, regKey) )
+ {
+ return true;
+ }
+ return false;
+ }
+
+}
+
+class ScriptImpl implements XScript
+{
+ private ScriptMetaData metaData;
+ private XComponentContext m_xContext;
+ private XMultiComponentFactory m_xMultiComponentFactory;
+ private XModel m_xModel;
+ private XScriptInvocationContext m_xInvocContext;
+
+ ScriptImpl( XComponentContext ctx, ScriptMetaData metaData, XModel xModel,
+ XScriptInvocationContext xContext ) throws com.sun.star.uno.RuntimeException
+ {
+ this.metaData = metaData;
+ this.m_xContext = ctx;
+ this.m_xModel = xModel;
+ this.m_xInvocContext = xContext;
+
+ try
+ {
+ this.m_xMultiComponentFactory = m_xContext.getServiceManager();
+ }
+ catch ( Exception e )
+ {
+ LogUtils.DEBUG( LogUtils.getTrace( e ) );
+ throw new com.sun.star.uno.RuntimeException(
+ "Error constructing ScriptImpl [beanshell]: "
+ + e.getMessage() );
+ }
+
+ LogUtils.DEBUG("ScriptImpl [beanshell] script data = " + metaData );
+ }
+ /**
+ * documentStorageID and document reference
+ * for use in script name resolving
+ *
+ * @param aParams All parameters; pure, out params are
+ * undefined in sequence, i.e., the value
+ * has to be ignored by the callee
+ *
+ * @param aOutParamIndex Out indices
+ *
+ * @param aOutParam Out parameters
+ *
+ * @returns The value returned from the function
+ * being invoked
+ *
+ * @throws IllegalArgumentException If there is no matching script name
+ *
+ * @throws CannotConvertException If args do not match or cannot
+ * be converted the those of the
+ * invokee
+ *
+ * @throws InvocationTargetException If the running script throws
+ * an exception this information
+ * is captured and rethrown as
+ * this exception type.
+ */
+
+ public Object invoke( /*IN*/Object[] aParams,
+ /*OUT*/short[][] aOutParamIndex,
+ /*OUT*/Object[][] aOutParam )
+ throws ScriptFrameworkErrorException,
+ InvocationTargetException
+ {
+ // Initialise the out paramters - not used at the moment
+ aOutParamIndex[0] = new short[0];
+ aOutParam[0] = new Object[0];
+
+
+ ClassLoader cl = null;
+ URL sourceUrl = null;
+ try {
+ cl = ClassLoaderFactory.getURLClassLoader( metaData );
+ sourceUrl = metaData.getSourceURL();
+ }
+ catch ( java.net.MalformedURLException mfu )
+ {
+ // Framework error
+ throw new ScriptFrameworkErrorException(
+ mfu.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.MALFORMED_URL );
+ }
+ catch ( NoSuitableClassLoaderException nsc )
+ {
+ // Framework error
+ throw new ScriptFrameworkErrorException(
+ nsc.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.UNKNOWN );
+ }
+ // Set class loader to be used for class files
+ // and jar files
+ Thread.currentThread().setContextClassLoader(cl);
+ Interpreter interpreter = new Interpreter();
+
+ interpreter.getNameSpace().clear();
+ // Set class loader to be used by interpreter
+ // to look for classes by source e.g. interpreter
+ // will use this classloader to search classpath
+ // for source file ( bla.java ) on import or reference
+ interpreter.setClassLoader(cl);
+ try {
+ interpreter.set("XSCRIPTCONTEXT",
+ ScriptContext.createContext(m_xModel, m_xInvocContext,
+ m_xContext, m_xMultiComponentFactory));
+
+ interpreter.set("ARGUMENTS", aParams);
+ }
+ catch (bsh.EvalError e) {
+ // Framework error setting up context
+ throw new ScriptFrameworkErrorException(
+ e.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.UNKNOWN );
+ }
+
+ try {
+ String source = null;
+ Object result = null;
+
+ ScriptEditorForBeanShell editor =
+ ScriptEditorForBeanShell.getEditor(
+ sourceUrl );
+
+ if ( editor != null )
+ {
+ result = editor.execute();
+
+ if (result == null)
+ {
+ return new Any(new Type(), null);
+ }
+ return result;
+ }
+
+ metaData.loadSource();
+ source = metaData.getSource();
+
+ if ( source == null || source.length() == 0 )
+ {
+ throw new ScriptFrameworkErrorException(
+ "Failed to read script", null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.NO_SUCH_SCRIPT );
+ }
+ result = interpreter.eval( source );
+
+ if (result == null)
+ {
+ return new Any(new Type(), null);
+ }
+ return result;
+ }
+ catch ( bsh.ParseException pe )
+ {
+ throw new InvocationTargetException( "Beanshell failed to parse " + metaData.getLanguageName(), null, processBshException( pe, metaData.getLanguageName() ) );
+ }
+ catch ( bsh.TargetError te )
+ {
+ throw new InvocationTargetException( "Beanshell uncaught exception for " + metaData.getLanguageName(), null, processBshException( te, metaData.getLanguageName() ) );
+ }
+ catch ( bsh.EvalError ex )
+ {
+ throw new InvocationTargetException( "Beanshell error for " + metaData.getLanguageName(), null, processBshException( ex, metaData.getLanguageName() ) );
+ }
+ catch ( Exception e )
+ {
+ throw new ScriptFrameworkErrorException(
+ "Failed to read script", null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.UNKNOWN );
+ }
+ }
+ private void raiseEditor( int lineNum )
+ {
+ ScriptEditorForBeanShell editor = null;
+ try
+ {
+ URL sourceUrl = metaData.getSourceURL();
+ editor = ScriptEditorForBeanShell.getEditor( sourceUrl );
+ if ( editor == null )
+ {
+ editor = ScriptEditorForBeanShell.getEditor();
+ editor.edit(
+ ScriptContext.createContext(m_xModel, m_xInvocContext,
+ m_xContext, m_xMultiComponentFactory), metaData );
+ editor = ScriptEditorForBeanShell.getEditor( sourceUrl );
+ }
+ if ( editor != null )
+ {
+ editor.indicateErrorLine( lineNum );
+ }
+ }
+ catch( Exception ignore )
+ {
+ }
+ }
+
+ private ScriptErrorRaisedException processBshException( bsh.EvalError e, String script )
+ {
+ LogUtils.DEBUG("Beanshell error RAW message " + e.getMessage());
+ String message = e.getMessage();
+ int usefullInfoIndex = message.lastIndexOf("\' :" );
+ int lineNum = e.getErrorLineNumber();
+
+ raiseEditor( lineNum );
+
+ //String stackTrace = te.getScriptStackTrace(); // never seems to have any info??
+ if ( usefullInfoIndex > -1 )
+ {
+ message = message.substring( usefullInfoIndex + 2 );
+ }
+ if ( e instanceof bsh.TargetError )
+ {
+ LogUtils.DEBUG("got instance of TargetError");
+ if ( usefullInfoIndex == -1 )
+ {
+ message = ( ( bsh.TargetError)e ).getTarget().getMessage();
+ }
+ String wrappedException = "";
+ String full = e.toString();
+ int index = full.indexOf( "Target exception:" );
+ if ( index > -1 )
+ {
+ String toParse = full.substring( index );
+ LogUtils.DEBUG("About to parse " + toParse );
+ StringTokenizer tokenizer = new StringTokenizer( full.substring( index ),":" );
+ if ( tokenizer.countTokens() > 2 )
+ {
+ LogUtils.DEBUG("First token = " + (String)tokenizer.nextElement());
+ wrappedException = (String)tokenizer.nextElement();
+ LogUtils.DEBUG("wrapped exception = = " + wrappedException );
+ }
+ }
+ ScriptExceptionRaisedException se = new ScriptExceptionRaisedException( message);
+ se.lineNum = lineNum;
+ se.scriptName = script;
+ se.exceptionType = wrappedException;
+ se.language = "BeanShell";
+ LogUtils.DEBUG("UnCaught Exception error: " );
+ LogUtils.DEBUG("\tscript: " + script );
+ LogUtils.DEBUG("\tline: " + lineNum );
+ LogUtils.DEBUG("\twrapped exception: " + wrappedException );
+ LogUtils.DEBUG("\tmessage: " + message );
+ return se;
+ }
+ else
+ {
+ LogUtils.DEBUG("Error or ParseError Exception error: " );
+ LogUtils.DEBUG("\tscript: " + script );
+ LogUtils.DEBUG("\tline: " + lineNum );
+ LogUtils.DEBUG("\tmessage: " + message );
+ return new ScriptErrorRaisedException( message, null, script, "BeanShell", lineNum );
+ }
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptSourceModel.java b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptSourceModel.java
new file mode 100644
index 000000000000..186fed25a6e4
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptSourceModel.java
@@ -0,0 +1,144 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptSourceModel.java,v $
+ * $Revision: 1.9 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package com.sun.star.script.framework.provider.beanshell;
+
+import java.io.InputStream;
+import java.io.IOException;
+
+import java.net.URL;
+
+import com.sun.star.script.provider.XScriptContext;
+
+public class ScriptSourceModel {
+
+ private int currentPosition = -1;
+ private URL file = null;
+ private ScriptSourceView view = null;
+
+ public ScriptSourceModel(URL file ) {
+ this.file = file;
+ }
+
+ private String load() throws IOException {
+ StringBuffer buf = new StringBuffer();
+ InputStream in = file.openStream();
+
+ byte[] contents = new byte[1024];
+ int len = 0;
+
+ while ((len = in.read(contents, 0, 1024)) != -1) {
+ buf.append(new String(contents, 0, len));
+ }
+
+ try {
+ in.close();
+ }
+ catch (IOException ignore) {
+ }
+
+ return buf.toString();
+ }
+
+ public String getText() {
+ String result = "";
+
+ try {
+ result = load();
+ }
+ catch (IOException ioe) {
+ // do nothing, empty string will be returned
+ }
+
+ return result;
+ }
+
+ public int getCurrentPosition() {
+ return this.currentPosition;
+ }
+
+ public void setView(ScriptSourceView view) {
+ this.view = view;
+ }
+
+ public Object execute(final XScriptContext context, ClassLoader cl )
+ throws Exception
+ {
+ Object result = null;
+ // Thread execThread = new Thread() {
+ // public void run() {
+ if ( cl != null )
+ {
+ // sets this threads class loader
+ // hopefully any threads spawned by this
+ // will inherit this cl
+ // this enables any class files imported
+ // from the interpreter to be loaded
+ // note: setting the classloader on the
+ // interpreter has a slightly different
+ // meaning in that the classloader for
+ // the interpreter seems only to look for
+ // source files ( bla.java ) in the classpath
+ Thread.currentThread().setContextClassLoader(cl);
+ }
+ bsh.Interpreter interpreter = new bsh.Interpreter();
+ if ( cl != null )
+ {
+ // additionally set class loader on the interpreter
+ // to allow it to load java classes defined in source
+ // files e.g. bla.java
+ interpreter.getNameSpace().clear();
+ }
+
+
+ // reset position
+ currentPosition = -1;
+ view.update();
+
+ interpreter.set("XSCRIPTCONTEXT", context);
+ interpreter.set("ARGUMENTS", new Object[0]);
+
+ if (view.isModified()) {
+ result = interpreter.eval(view.getText());
+ }
+ else {
+ result = interpreter.eval(getText());
+ }
+ // }
+ // };
+ // execThread.start();
+ return result;
+ }
+ public void indicateErrorLine( int lineNum )
+ {
+ System.out.println("Beanshell indicateErrorLine " + lineNum );
+ currentPosition = lineNum - 1;
+ view.update();
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptSourceView.java b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptSourceView.java
new file mode 100644
index 000000000000..98d5214d4a78
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptSourceView.java
@@ -0,0 +1,38 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptSourceView.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package com.sun.star.script.framework.provider.beanshell;
+
+public interface ScriptSourceView {
+ public void clear();
+ public void update();
+ public boolean isModified();
+ public void setModified(boolean value);
+ public String getText();
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/beanshell/template.bsh b/scripting/java/com/sun/star/script/framework/provider/beanshell/template.bsh
new file mode 100644
index 000000000000..03cb114d79b7
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/beanshell/template.bsh
@@ -0,0 +1,48 @@
+/*
+ Import standard OpenOffice.org API classes. For more information on
+ these classes and the OpenOffice.org API, see the OpenOffice.org
+ Developers Guide at:
+
+ http://api.openoffice.org/
+*/
+
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.frame.XDesktop;
+import com.sun.star.frame.XModel;
+
+/*
+ Import XScriptContext class. An instance of this class is available
+ to all BeanShell scripts in the global variable "XSCRIPTCONTEXT". This
+ variable can be used to access the document for which this script
+ was invoked.
+
+ Methods available are:
+
+ XSCRIPTCONTEXT.getDocument() returns XModel
+ XSCRIPTCONTEXT.getInvocationContext() returns XScriptInvocationContext or NULL
+ XSCRIPTCONTEXT.getDesktop() returns XDesktop
+ XSCRIPTCONTEXT.getComponentContext() returns XComponentContext
+
+ For more information on using this class see the scripting
+ developer guides at:
+
+ http://api.openoffice.org/docs/DevelopersGuide/ScriptingFramework/ScriptingFramework.xhtml
+*/
+
+// Hello World in BeanShell
+import com.sun.star.text.XTextDocument;
+import com.sun.star.text.XText;
+import com.sun.star.text.XTextRange;
+
+oDoc = UnoRuntime.queryInterface(XModel.class,XSCRIPTCONTEXT.getInvocationContext());
+if ( oDoc == null )
+ oDoc = XSCRIPTCONTEXT.getDocument();
+
+xTextDoc = (XTextDocument) UnoRuntime.queryInterface(XTextDocument.class,oDoc);
+xText = xTextDoc.getText();
+xTextRange = xText.getEnd();
+xTextRange.setString( "Hello World (in BeanShell)" );
+
+// BeanShell OpenOffice.org scripts should always return 0
+return 0;
diff --git a/scripting/java/com/sun/star/script/framework/provider/java/Resolver.java b/scripting/java/com/sun/star/script/framework/provider/java/Resolver.java
new file mode 100755
index 000000000000..addea113390a
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/java/Resolver.java
@@ -0,0 +1,53 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: Resolver.java,v $
+ * $Revision: 1.3 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package com.sun.star.script.framework.provider.java;
+
+/**
+ * The Resolver interface is an interface common to all classes which
+ * want to implement an algorithm for obtaining a ScriptProxy object
+ * for a particular ScriptDescriptor and Class
+ *
+ * @author Tomas O'Connor
+ * @created August 2, 2002
+ */
+
+public interface Resolver {
+ /**
+ * Returns a ScriptProxy object for the given ScriptDescriptor and Class
+ *
+ * @param sd A script Descriptor
+ * @param c A Class
+ * @return The ScriptProxy value
+ */
+ public ScriptProxy getProxy( ScriptDescriptor sd, Class c )
+ throws NoSuchMethodException;
+}
+
diff --git a/scripting/java/com/sun/star/script/framework/provider/java/ScriptDescriptor.java b/scripting/java/com/sun/star/script/framework/provider/java/ScriptDescriptor.java
new file mode 100755
index 000000000000..35bdf76f9ae9
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/java/ScriptDescriptor.java
@@ -0,0 +1,215 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptDescriptor.java,v $
+ * $Revision: 1.3 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+
+package com.sun.star.script.framework.provider.java;
+
+import java.util.Vector;
+import java.util.StringTokenizer;
+
+/**
+ * The <code>ScriptDescriptor</code> object is used to store the search
+ * criteria that should be used for finding a particular script
+ *
+ * @author Tomas O'Connor
+ * @created August 2, 2002
+ */
+public class ScriptDescriptor
+{
+ private String m_name;
+ private String m_methodName;
+ private String m_className;
+ private Vector m_classpath;
+ private Vector m_argumentTypes = new Vector( 11 );
+
+
+ /**
+ * Constructs a ScriptDescriptor for the given name
+ *
+ * @param name Script Name
+ * @exception IllegalArgumentException if the given name does not contain a "."
+ */
+ public ScriptDescriptor( String name )
+ throws IllegalArgumentException
+ {
+ int idx = name.lastIndexOf( '.' );
+
+ if ( idx == -1 )
+ {
+ throw new IllegalArgumentException( "Invalid method name" );
+ }
+
+ this.m_name = name;
+ this.m_methodName = name.substring( idx + 1 );
+ this.m_className = name.substring( 0, idx );
+ }
+
+
+ /**
+ * Gets the fully qualified name of this <code>ScriptDescriptor</code>
+ *
+ * @return The Script Name value
+ */
+ public String getName()
+ {
+ return m_name;
+ }
+
+ /**
+ * Gets the fully qualified name of this <code>ScriptDescriptor</code>
+ *
+ * @return The Script Name value
+ */
+ public String getClassName()
+ {
+ return m_className;
+ }
+
+
+ /**
+ * Gets the method name of this <code>ScriptDescriptor</code>
+ *
+ * @return The methodName value
+ */
+ public String getMethodName()
+ {
+ return m_methodName;
+ }
+
+
+ /**
+ * Sets the classpath value stored by this <code>ScriptDescriptor</code>
+ *
+ * @param classpath The new classpath value
+ */
+ public void setClasspath( String classpath )
+ {
+ StringTokenizer stk = new StringTokenizer( classpath, ":" );
+ while( stk.hasMoreElements() )
+ {
+ this.m_classpath.add( (String) stk.nextElement() );
+ }
+ }
+
+ /**
+ * Sets the classpath value stored by this <code>ScriptDescriptor</code>
+ *
+ * @param classpath The new classpath value
+ */
+ public void setClasspath( Vector classpath )
+ {
+ this.m_classpath = classpath;
+ }
+
+
+ /**
+ * Gets the classpath value stored by this <code>ScriptDescriptor</code>
+ *
+ * @return The classpath value
+ */
+ public Vector getClasspath()
+ {
+ return m_classpath;
+ }
+
+
+ /**
+ * Adds the given <code>Class</code> to the list of argument types stored in
+ * this ScriptDescriptor
+ *
+ * @param clazz The feature to be added to the ArgumentType attribute
+ */
+ public synchronized void addArgumentType( Class clazz )
+ {
+ m_argumentTypes.addElement( clazz );
+ }
+
+
+ /**
+ * Adds the given array of <code>Class</code> to the list of argument types
+ * stored in this ScriptDescriptor
+ *
+ * @param classes The feature to be added to the ArgumentTypes attribute
+ */
+ public synchronized void addArgumentTypes( Class[] classes )
+ {
+ for ( int i = 0; i < classes.length; i++ )
+ {
+ addArgumentType( classes[ i ] );
+ }
+ }
+
+
+ /**
+ * Gets a list of the types of the arguments stored in this
+ * <code>ScriptDescriptor</code>
+ *
+ * return the argument types as an array of Class
+ *
+ * @return The argumentTypes value
+ */
+ public synchronized Class[]
+ getArgumentTypes()
+ {
+ if ( m_argumentTypes.size() > 0 )
+ return ( Class[] ) m_argumentTypes.toArray( new Class[ 0 ] );
+ else
+ return null;
+ }
+
+
+ /**
+ * Returns a <code>String</code> representation of this
+ * <code>ScriptDescriptor</code>
+ *
+ * @return The scriptName including the parameters.
+ */
+ public String toString()
+ {
+ StringBuffer description = new StringBuffer( m_name );
+ Class[] types = getArgumentTypes();
+
+ description.append( " (" );
+
+ if ( types != null )
+ {
+ for ( int i = 0; i < types.length - 1; i++ )
+ {
+ description.append( types[ i ].getName() );
+ description.append( ", " );
+ }
+
+ description.append( types[ types.length - 1 ].getName() );
+ }
+ description.append( ")" );
+
+ return description.toString();
+ }
+}
+
diff --git a/scripting/java/com/sun/star/script/framework/provider/java/ScriptProviderForJava.java b/scripting/java/com/sun/star/script/framework/provider/java/ScriptProviderForJava.java
new file mode 100755
index 000000000000..14fcfa348137
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/java/ScriptProviderForJava.java
@@ -0,0 +1,402 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptProviderForJava.java,v $
+ * $Revision: 1.10.6.1 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package com.sun.star.script.framework.provider.java;
+
+import com.sun.star.frame.XModel;
+import com.sun.star.comp.loader.FactoryHelper;
+import com.sun.star.document.XScriptInvocationContext;
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.lang.XMultiComponentFactory;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.lang.XSingleServiceFactory;
+import com.sun.star.registry.XRegistryKey;
+import com.sun.star.uno.Type;
+import com.sun.star.uno.Any;
+
+import java.util.ArrayList;
+import java.util.Map;
+import java.net.MalformedURLException;
+
+import com.sun.star.script.provider.XScriptContext;
+import com.sun.star.script.provider.XScript;
+import com.sun.star.script.provider.ScriptExceptionRaisedException;
+import com.sun.star.script.provider.ScriptFrameworkErrorException;
+import com.sun.star.script.provider.ScriptFrameworkErrorType;
+
+import com.sun.star.script.framework.container.ScriptMetaData;
+
+import com.sun.star.script.framework.provider.*;
+import com.sun.star.script.framework.log.LogUtils;
+/**
+ * Description of the Class
+ *
+ * @author Noel Power
+ * @created August 2, 2002
+ */
+public class ScriptProviderForJava
+{
+ /**
+ * Description of the Class
+ *
+ * @author Noel Power
+ * @created August 2, 2002
+ */
+ public static class _ScriptProviderForJava extends ScriptProvider
+ {
+ private Resolver m_resolutionPolicy = new StrictResolver();
+
+ public _ScriptProviderForJava( XComponentContext ctx )
+ {
+ super (ctx, "Java");
+ }
+
+ public XScript getScript( /*IN*/String scriptURI )
+ throws com.sun.star.uno.RuntimeException,
+ ScriptFrameworkErrorException
+ {
+ ScriptMetaData scriptData = null;
+ scriptData = getScriptData( scriptURI );
+ ScriptImpl script = null;
+ try
+ {
+ script = new ScriptImpl( m_xContext, m_resolutionPolicy, scriptData, m_xModel, m_xInvocContext );
+ return script;
+ }
+ catch ( com.sun.star.uno.RuntimeException re )
+ {
+ throw new ScriptFrameworkErrorException( "Failed to create script object: " + re.getMessage(),
+ null, scriptData.getLanguageName(), language, ScriptFrameworkErrorType.UNKNOWN );
+ }
+
+ }
+
+ public boolean hasScriptEditor()
+ {
+ return false;
+ }
+
+ public ScriptEditor getScriptEditor()
+ {
+ return null;
+ }
+ }
+
+ /**
+ * Returns a factory for creating the service.
+ * This method is called by the <code>JavaLoader</code>
+ * <p>
+ *
+ * @param implName the name of the implementation for which a service is desired
+ * @param multiFactory the service manager to be used if needed
+ * @param regKey the registryKey
+ * @return returns a <code>XSingleServiceFactory</code> for creating
+ * the component
+ * @see com.sun.star.comp.loader.JavaLoader
+ */
+ public static XSingleServiceFactory __getServiceFactory( String implName,
+ XMultiServiceFactory multiFactory,
+ XRegistryKey regKey )
+ {
+ XSingleServiceFactory xSingleServiceFactory = null;
+
+ if ( implName.equals( ScriptProviderForJava._ScriptProviderForJava.class.getName() ) )
+ {
+ xSingleServiceFactory = FactoryHelper.getServiceFactory(
+ ScriptProviderForJava._ScriptProviderForJava.class,
+ "com.sun.star.script.provider.ScriptProviderForJava",
+ multiFactory,
+ regKey );
+ }
+
+ return xSingleServiceFactory;
+ }
+
+
+ /**
+ * Writes the service information into the given registry key.
+ * This method is called by the <code>JavaLoader</code>
+ * <p>
+ *
+ * @param regKey the registryKey
+ * @return returns true if the operation succeeded
+ * @see com.sun.star.comp.loader.JavaLoader
+ */
+ public static boolean __writeRegistryServiceInfo( XRegistryKey regKey )
+ {
+ String impl = "com.sun.star.script.framework.provider.java." +
+ "ScriptProviderForJava$_ScriptProviderForJava";
+
+ String service1 = "com.sun.star.script.provider." +
+ "ScriptProvider";
+ String service2 = "com.sun.star.script.provider." +
+ "LanguageScriptProvider";
+ String service3 = "com.sun.star.script.provider." +
+ "ScriptProviderForJava";
+ String service4 = "com.sun.star.script.browse." +
+ "BrowseNode";
+
+ if ( FactoryHelper.writeRegistryServiceInfo(impl, service1, regKey) &&
+ FactoryHelper.writeRegistryServiceInfo(impl, service2, regKey) &&
+ FactoryHelper.writeRegistryServiceInfo(impl, service3, regKey) &&
+ FactoryHelper.writeRegistryServiceInfo(impl, service4, regKey) )
+ {
+ return true;
+ }
+ return false;
+ }
+
+}
+
+class ScriptImpl implements XScript
+{
+ private ScriptMetaData metaData;
+ private XComponentContext m_xContext;
+ private XModel m_xModel;
+ private XScriptInvocationContext m_xInvocContext;
+ private XMultiComponentFactory m_xMultiComponentFactory;
+ private Resolver m_resolutionPolicy;
+ ScriptImpl( XComponentContext ctx, Resolver resolver, ScriptMetaData metaData, XModel xModel, XScriptInvocationContext xInvocContext ) throws com.sun.star.uno.RuntimeException
+ {
+ this.metaData = metaData;
+ this.m_xContext = ctx;
+ this.m_xModel = xModel;
+ this.m_xInvocContext = xInvocContext;
+ this.m_resolutionPolicy = resolver;
+ try
+ {
+ this.m_xMultiComponentFactory = m_xContext.getServiceManager();
+ }
+ catch ( Exception e )
+ {
+ LogUtils.DEBUG( LogUtils.getTrace( e ) );
+ throw new com.sun.star.uno.RuntimeException(
+ "Error constructing ScriptProvider: "
+ + e.getMessage() );
+ }
+
+ LogUtils.DEBUG("ScriptImpl [java] script data = " + metaData );
+ }
+ /**
+ * Invoke
+ *
+ *
+ * @param aParams All parameters; pure, out params are undefined in
+ * sequence, i.e., the value has to be ignored by the callee
+ * @param aOutParamIndex Out indices
+ * @param aOutParam Out parameters
+ * @returns The value returned from the function being invoked
+ * @throws IllegalArgumentException If there is no matching script name
+ * @throws CannotConvertException If args do not match or cannot be converted
+ * the those of the invokee
+ * @throws InvocationTargetException If the running script throws an exception
+ * this information is captured and rethrown as this exception type.
+ */
+
+ public Object invoke(
+ /*IN*/Object[] params,
+ /*OUT*/short[][] aOutParamIndex,
+ /*OUT*/Object[][] aOutParam )
+
+ throws ScriptFrameworkErrorException, com.sun.star.reflection.InvocationTargetException
+ {
+ LogUtils.DEBUG( "** ScriptProviderForJava::invoke: Starting..." );
+
+ // Initialise the out paramters - not used at the moment
+ aOutParamIndex[0] = new short[0];
+ aOutParam[0] = new Object[0];
+
+
+ Map languageProps = metaData.getLanguageProperties();
+
+ ScriptDescriptor scriptDesc =
+ new ScriptDescriptor( metaData.getLanguageName() );
+
+ ClassLoader scriptLoader = null;
+
+ try {
+ LogUtils.DEBUG( "Classloader starting..." );
+ scriptLoader = ClassLoaderFactory.getURLClassLoader(
+ metaData );
+ LogUtils.DEBUG( "Classloader finished..." );
+ }
+ catch (MalformedURLException mfe )
+ {
+ // Framework error
+ throw new ScriptFrameworkErrorException(
+ mfe.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.MALFORMED_URL );
+ }
+ catch (NoSuitableClassLoaderException ncl )
+ {
+ // Framework error
+ throw new ScriptFrameworkErrorException(
+ ncl.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.UNKNOWN );
+ }
+ catch (ArrayStoreException e )
+ {
+ // Framework error
+ throw new ScriptFrameworkErrorException(
+ e.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.UNKNOWN );
+ }
+
+ ArrayList invocationArgList = new ArrayList();
+ Object[] invocationArgs = null;
+
+ LogUtils.DEBUG( "Parameter Mapping..." );
+
+ // Setup Context Object
+ XScriptContext xSc = ScriptContext.createContext(m_xModel, m_xInvocContext,
+ m_xContext, m_xMultiComponentFactory);
+ scriptDesc.addArgumentType( XScriptContext.class );
+ invocationArgList.add( xSc );
+
+ for ( int i = 0; i < params.length; i++ )
+ {
+ scriptDesc.addArgumentType( params[ i ].getClass() );
+ invocationArgList.add( params[ i ] );
+ }
+
+ if ( !invocationArgList.isEmpty() )
+ {
+ invocationArgs = invocationArgList.toArray();
+ }
+
+
+
+ LogUtils.DEBUG( "ScriptProxy starting... " );
+ ScriptProxy script = null;
+ try
+ {
+ String className = metaData.getLanguageName().substring( 0,
+ metaData.getLanguageName().lastIndexOf( '.' ) );
+ LogUtils.DEBUG( "About to load Class " + className + " starting... " );
+
+ long start = new java.util.Date().getTime();
+ Class c = scriptLoader.loadClass( className );
+ long end = new java.util.Date().getTime();
+
+ LogUtils.DEBUG("loadClass took: " + String.valueOf(end - start) +
+ "milliseconds");
+
+ try
+ {
+ LogUtils.DEBUG( "class loaded ... " );
+ script = m_resolutionPolicy.getProxy( scriptDesc, c );
+ LogUtils.DEBUG( "script resolved ... " );
+ }
+ catch( NoSuchMethodException e )
+ {
+ // Framework error
+ throw new ScriptFrameworkErrorException(
+ e.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.NO_SUCH_SCRIPT );
+ }
+ }
+ catch ( ClassNotFoundException e )
+ {
+ // Framework error
+ throw new ScriptFrameworkErrorException(
+ e.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.NO_SUCH_SCRIPT );
+ }
+
+ LogUtils.DEBUG( "Starting Invoke on Proxy ..." );
+ Object result = null;
+
+ try
+ {
+ long start = new java.util.Date().getTime();
+ result = script.invoke( invocationArgs );
+ long end = new java.util.Date().getTime();
+
+ LogUtils.DEBUG("invoke took: " +
+ String.valueOf(end - start) + "milliseconds");
+ }
+ catch ( java.lang.IllegalArgumentException iae )
+ {
+ throw new ScriptFrameworkErrorException(
+ iae.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.UNKNOWN );
+
+ }
+ catch ( java.lang.IllegalAccessException ia )
+ {
+ throw new ScriptFrameworkErrorException(
+ ia.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.UNKNOWN );
+ }
+ catch ( java.lang.reflect.InvocationTargetException ite )
+ {
+ Throwable targetException = ite.getTargetException();
+ ScriptExceptionRaisedException se =
+ new ScriptExceptionRaisedException(
+ targetException.toString() );
+ se.lineNum = -1;
+ se.scriptName = metaData.getLanguageName();
+ se.language = "Java";
+ se.exceptionType = targetException.getClass().getName();
+ throw new com.sun.star.reflection.InvocationTargetException(
+ "Scripting Framework error executing script ", null, se );
+ }
+ catch ( Exception unknown )
+ {
+ ScriptExceptionRaisedException se =
+ new ScriptExceptionRaisedException(
+ unknown.toString() );
+ se.lineNum = -1;
+ se.scriptName = metaData.getLanguageName();
+ se.language = "Java";
+ se.exceptionType = unknown.getClass().getName();
+ throw new com.sun.star.reflection.InvocationTargetException(
+ "Scripting Framework error executing script ", null, se );
+ }
+ if ( result == null )
+ {
+ LogUtils.DEBUG( "Got Nothing Back" );
+ // in the case where there is no return type
+ Any voidAny = new Any(new Type(), null);
+ result = voidAny;
+ }
+ else
+ {
+ LogUtils.DEBUG( "Got object " + result );
+ }
+ return result;
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/java/ScriptProxy.java b/scripting/java/com/sun/star/script/framework/provider/java/ScriptProxy.java
new file mode 100755
index 000000000000..3b78a6bc2c5b
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/java/ScriptProxy.java
@@ -0,0 +1,95 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptProxy.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+
+package com.sun.star.script.framework.provider.java;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.InvocationTargetException;
+
+/**
+ * A ScriptProxy object acts as a proxy for a Java <code>Method</code>
+ *
+ * @author Tomas O'Connor
+ * @created August 2, 2002
+ * @see java.lang.reflect.Method
+ */
+public class ScriptProxy
+{
+ private Object m_targetObject;
+ private Method m_method;
+
+
+ /**
+ * Constructs a <code>ScriptProxy</code> object for the given
+ * <code>Method</code>
+ *
+ * @param method Description of the Parameter
+ */
+ public ScriptProxy( Method method )
+ {
+ this.m_method = method;
+ }
+
+
+ /**
+ * Sets the <code>Object</code> on which the ScriptProxy should invoke
+ * the method
+ *
+ * @param obj The new targetObject value
+ */
+ public void setTargetObject( Object obj )
+ {
+ m_targetObject = obj;
+ }
+
+
+ /**
+ * Invokes the method contained in this <code>ScriptProxy</code>,
+ * any exceptions resulting from the invocation will be thrown
+ *
+ * @param args the arguments to be passed when invoking
+ * the method
+ * @return the Object returned from the method
+ * invocation, may be null
+ * @exception IllegalAccessException Description of the Exception
+ * @exception InvocationTargetException Description of the Exception
+ * @exception IllegalArgumentException Description of the Exception
+ * @exception Exception Description of the Exception
+ * @see java.lang.reflect.Method for the exceptions
+ * that may be thrown
+ */
+ public Object invoke( Object[] args )
+ throws IllegalAccessException, InvocationTargetException,
+ IllegalArgumentException
+ {
+ return m_method.invoke( m_targetObject, args );
+ }
+}
+
diff --git a/scripting/java/com/sun/star/script/framework/provider/java/StrictResolver.java b/scripting/java/com/sun/star/script/framework/provider/java/StrictResolver.java
new file mode 100755
index 000000000000..87a6f994e174
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/java/StrictResolver.java
@@ -0,0 +1,131 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: StrictResolver.java,v $
+ * $Revision: 1.3 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+
+package com.sun.star.script.framework.provider.java;
+
+import java.lang.reflect.*;
+import com.sun.star.script.framework.log.LogUtils;
+
+/**
+ * A StrictResolver can be used to get a ScriptProxy object for a given
+ * ScriptDescriptor and Class. The StrictResolver is an implementation of
+ * the Resolver strategy. It will only return a ScriptProxy object if a
+ * method accepting all of the arguments specified in the ScriptDescriptor
+ * can be found in the Class.
+ *
+ * @author Tomas O'Connor
+ * @created August 2, 2002
+ */
+public class StrictResolver implements Resolver
+{
+ /**
+ *Constructor for the StrictResolver object
+ */
+ public StrictResolver()
+ {
+ LogUtils.DEBUG( this.getClass().getName() + " created" );
+ }
+
+
+ /**
+ * Returns a ScriptProxy object for the given ScriptDescriptor and Class.
+ * Only a strict match will be returned ie. where all of the arguments in
+ * the given ScriptDescriptor match the types of the
+ *
+ * @param sd the ScriptDescriptor for which a ScriptProxy is required
+ * @param c the Class file in which to search for the method
+ * @return the ScriptProxy matching the criteria, or null if no match is found
+ */
+ public ScriptProxy getProxy( ScriptDescriptor sd, Class c )
+ throws NoSuchMethodException
+ {
+ Method m = null;
+ ScriptProxy sp = null;
+
+ LogUtils.DEBUG( "StrictResolver.getProxy() for: " + sd.toString() );
+
+ try
+ {
+ m = resolveArguments( sd, c );
+ }
+ catch ( ClassNotFoundException e )
+ {
+ throw new NoSuchMethodException( "StrictResolver.getProxy: Cant find method: "
+ + sd.getMethodName() + ":" + e.getMessage() );
+ }
+ catch ( NoSuchMethodException e )
+ {
+ throw new NoSuchMethodException( "StrictResolver.getProxy: Cant find method: "
+ + sd.getMethodName() + ":" + e.getMessage() );
+ }
+
+ sp = new ScriptProxy( m );
+
+ int modifiers = m.getModifiers();
+ if ( !Modifier.isStatic( modifiers ) )
+ {
+ Object o;
+ try
+ {
+ o = c.newInstance();
+ }
+ catch ( InstantiationException ie )
+ {
+ throw new NoSuchMethodException( "getScriptProxy: Cant instantiate: " +
+ c.getName() );
+ }
+ catch ( IllegalAccessException iae )
+ {
+ throw new NoSuchMethodException( "getScriptProxy: Cant access: "
+ + c.getName() );
+ }
+ sp.setTargetObject( o );
+ }
+
+ return sp;
+ }
+
+
+ /**
+ * Description of the Method
+ *
+ * @param sd Description of the Parameter
+ * @param c Description of the Parameter
+ * @return Description of the Return Value
+ * @exception ClassNotFoundException
+ * @exception NoSuchMethodException
+ */
+ private Method resolveArguments( ScriptDescriptor sd, Class c )
+ throws ClassNotFoundException, NoSuchMethodException
+ {
+ return c.getMethod( sd.getMethodName(), sd.getArgumentTypes() );
+ }
+}
+
diff --git a/scripting/java/com/sun/star/script/framework/provider/javascript/ScriptEditorForJavaScript.java b/scripting/java/com/sun/star/script/framework/provider/javascript/ScriptEditorForJavaScript.java
new file mode 100644
index 000000000000..45e99c8c324d
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/javascript/ScriptEditorForJavaScript.java
@@ -0,0 +1,379 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptEditorForJavaScript.java,v $
+ * $Revision: 1.8 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package com.sun.star.script.framework.provider.javascript;
+
+import org.mozilla.javascript.Context;
+import org.mozilla.javascript.Scriptable;
+import org.mozilla.javascript.ImporterTopLevel;
+import org.mozilla.javascript.tools.debugger.Main;
+import org.mozilla.javascript.tools.debugger.ScopeProvider;
+
+import com.sun.star.script.provider.XScriptContext;
+import com.sun.star.script.framework.container.ScriptMetaData;
+import com.sun.star.script.framework.provider.ScriptEditor;
+import com.sun.star.script.framework.log.LogUtils;
+
+import java.io.InputStream;
+import java.io.IOException;
+import java.net.URL;
+
+import java.util.Map;
+import java.util.HashMap;
+
+import javax.swing.SwingUtilities;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+
+public class ScriptEditorForJavaScript implements ScriptEditor
+{
+ // global ScriptEditorForJavaScript instance
+ private static ScriptEditorForJavaScript theScriptEditorForJavaScript;
+
+ // template for JavaScript scripts
+ private static String JSTEMPLATE;
+
+ static private Main rhinoWindow;
+ private URL scriptURL;
+ // global list of ScriptEditors, key is URL of file being edited
+ private static Map BEING_EDITED = new HashMap();
+
+ static {
+ try {
+ URL url =
+ ScriptEditorForJavaScript.class.getResource("template.js");
+
+ InputStream in = url.openStream();
+ StringBuffer buf = new StringBuffer();
+ byte[] b = new byte[1024];
+ int len = 0;
+
+ while ((len = in.read(b)) != -1) {
+ buf.append(new String(b, 0, len));
+ }
+
+ in.close();
+
+ JSTEMPLATE = buf.toString();
+ }
+ catch (IOException ioe) {
+ JSTEMPLATE = "// JavaScript script";
+ }
+ catch (Exception e) {
+ JSTEMPLATE = "// JavaScript script";
+ }
+ }
+
+ /**
+ * Returns the global ScriptEditorForJavaScript instance.
+ */
+ public static ScriptEditorForJavaScript getEditor()
+ {
+ if (theScriptEditorForJavaScript == null)
+ {
+ synchronized(ScriptEditorForJavaScript.class)
+ {
+ if (theScriptEditorForJavaScript == null)
+ {
+ theScriptEditorForJavaScript =
+ new ScriptEditorForJavaScript();
+ }
+ }
+ }
+ return theScriptEditorForJavaScript;
+ }
+
+ /**
+ * Get the ScriptEditorForJavaScript instance for this URL
+ *
+ * @param url The URL of the script source file
+ *
+ * @return The ScriptEditorForJavaScript associated with
+ * the given URL if one exists, otherwise null.
+ */
+ public static ScriptEditorForJavaScript getEditor(URL url)
+ {
+ return (ScriptEditorForJavaScript)BEING_EDITED.get(url);
+ }
+
+ /**
+ * Returns whether or not the script source being edited in this
+ * ScriptEditorForJavaScript has been modified
+ */
+ public boolean isModified()
+ {
+ return rhinoWindow.isModified( scriptURL );
+ }
+
+ /**
+ * Returns the text being displayed in this ScriptEditorForJavaScript
+ *
+ * @return The text displayed in this ScriptEditorForJavaScript
+ */
+ public String getText()
+ {
+ return rhinoWindow.getText( scriptURL );
+ }
+
+ /**
+ * Returns the Rhino Debugger url of this ScriptEditorForJavaScript
+ *
+ * @return The url of this ScriptEditorForJavaScript
+ */
+ public String getURL()
+ {
+ return scriptURL.toString();
+ }
+
+ /**
+ * Returns the template text for JavaScript scripts
+ *
+ * @return The template text for JavaScript scripts
+ */
+ public String getTemplate()
+ {
+ return JSTEMPLATE;
+ }
+
+ /**
+ * Returns the default extension for JavaScript scripts
+ *
+ * @return The default extension for JavaScript scripts
+ */
+ public String getExtension()
+ {
+ return "js";
+ }
+
+ /**
+ * Opens an editor window for the specified ScriptMetaData.
+ * If an editor window is already open for that data it will be
+ * moved to the front.
+ *
+ * @param metadata The metadata describing the script
+ * @param context The context in which to execute the script
+ *
+ */
+ public void edit(final XScriptContext context, ScriptMetaData entry)
+ {
+ try {
+ String sUrl = entry.getParcelLocation();
+ if ( !sUrl.endsWith( "/" ) )
+ {
+ sUrl += "/";
+ }
+ sUrl += entry.getLanguageName();
+ URL url = entry.getSourceURL();
+
+ // check if there is already an editing session for this script
+ //if (BEING_EDITED.containsKey(url))
+ if ( rhinoWindow != null )
+ {
+ ScriptEditorForJavaScript editor =
+ (ScriptEditorForJavaScript) BEING_EDITED.get(url);
+ if ( editor == null )
+ {
+ editor = new ScriptEditorForJavaScript( context, url );
+ editor.edit( context, entry );
+ }
+ else
+ {
+ rhinoWindow.showScriptWindow( url );
+ }
+ }
+ else
+ {
+ ScriptEditorForJavaScript editor =
+ new ScriptEditorForJavaScript( context, url );
+
+ }
+ rhinoWindow.toFront();
+ }
+ catch ( IOException e )
+ {
+ LogUtils.DEBUG("Caught exception: " + e);
+ LogUtils.DEBUG(LogUtils.getTrace(e));
+ }
+ }
+
+ // Ensures that new instances of this class can only be created using
+ // the factory methods
+ private ScriptEditorForJavaScript()
+ {
+ }
+
+ private ScriptEditorForJavaScript(XScriptContext context, URL url)
+ {
+ initUI();
+ Scriptable scope = getScope( context );
+ this.rhinoWindow.openFile(url, scope, new closeHandler( url ) );
+
+
+ this.scriptURL = url;
+ synchronized( ScriptEditorForJavaScript.class )
+ {
+ BEING_EDITED.put(url, this);
+ }
+
+ }
+
+ /**
+ * Executes the script edited by the editor
+ *
+ */
+
+ public Object execute() throws Exception
+ {
+ rhinoWindow.toFront();
+
+ return this.rhinoWindow.runScriptWindow( scriptURL );
+ }
+
+ /**
+ * Indicates the line where error occured
+ *
+ */
+ public void indicateErrorLine( int lineNum )
+ {
+ this.rhinoWindow.toFront();
+ this.rhinoWindow.highlighLineInScriptWindow( scriptURL, lineNum );
+ }
+ // This code is based on the main method of the Rhino Debugger Main class
+ // We pass in the XScriptContext in the global scope for script execution
+ private void initUI() {
+ try {
+ synchronized ( ScriptEditorForJavaScript.class )
+ {
+ if ( this.rhinoWindow != null )
+ {
+ return;
+ }
+
+ final Main sdb = new Main("Rhino JavaScript Debugger");
+ swingInvoke(new Runnable() {
+ public void run() {
+ sdb.pack();
+ sdb.setSize(640, 640);
+ sdb.setVisible(true);
+ }
+ });
+ sdb.setExitAction(new Runnable() {
+ public void run() {
+ sdb.clearAllBreakpoints();
+ sdb.dispose();
+ shutdown();
+ }
+ });
+ Context.addContextListener(sdb);
+ sdb.setScopeProvider(new ScopeProvider() {
+ public Scriptable getScope() {
+ return org.mozilla.javascript.tools.shell.Main.getScope();
+ }
+ });
+ sdb.addWindowListener( new WindowAdapter() {
+ public void windowClosing(WindowEvent e) {
+ shutdown();
+ }
+ });
+ this.rhinoWindow = sdb;
+ }
+ } catch (Exception exc) {
+ LogUtils.DEBUG( LogUtils.getTrace( exc ) );
+ }
+ }
+
+ private static void swingInvoke(Runnable f) {
+ if (SwingUtilities.isEventDispatchThread()) {
+ f.run();
+ return;
+ }
+ try {
+ SwingUtilities.invokeAndWait(f);
+ } catch (Exception exc) {
+ LogUtils.DEBUG( LogUtils.getTrace( exc ) );
+ }
+ }
+
+ private void shutdown()
+ {
+ // dereference Rhino Debugger window
+ this.rhinoWindow = null;
+ this.scriptURL = null;
+ // remove all scripts from BEING_EDITED
+ synchronized( BEING_EDITED )
+ {
+ java.util.Iterator iter = BEING_EDITED.keySet().iterator();
+ java.util.Vector keysToRemove = new java.util.Vector();
+ while ( iter.hasNext() )
+ {
+
+ URL key = (URL)iter.next();
+ keysToRemove.add( key );
+ }
+ for ( int i=0; i<keysToRemove.size(); i++ )
+ {
+ BEING_EDITED.remove( keysToRemove.elementAt( i ) );
+ }
+ keysToRemove = null;
+ }
+
+ }
+ private Scriptable getScope(XScriptContext xsctxt )
+ {
+ Context ctxt = Context.enter();
+ ImporterTopLevel scope = new ImporterTopLevel(ctxt);
+
+ Scriptable jsCtxt = Context.toObject(xsctxt, scope);
+ scope.put("XSCRIPTCONTEXT", scope, jsCtxt);
+
+ Scriptable jsArgs = Context.toObject(
+ new Object[0], scope);
+ scope.put("ARGUMENTS", scope, jsArgs);
+
+ Context.exit();
+ return scope;
+ }
+
+ class closeHandler implements Runnable
+ {
+ URL url;
+ closeHandler( URL url )
+ {
+ this.url = url;
+ }
+ public void run()
+ {
+ synchronized( BEING_EDITED )
+ {
+ Object o = BEING_EDITED.remove( this.url );
+ }
+ }
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/javascript/ScriptProviderForJavaScript.java b/scripting/java/com/sun/star/script/framework/provider/javascript/ScriptProviderForJavaScript.java
new file mode 100755
index 000000000000..d913129c5f87
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/javascript/ScriptProviderForJavaScript.java
@@ -0,0 +1,395 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptProviderForJavaScript.java,v $
+ * $Revision: 1.10.6.1 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package com.sun.star.script.framework.provider.javascript;
+
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.lang.XMultiComponentFactory;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.lang.XSingleServiceFactory;
+import com.sun.star.frame.XModel;
+import com.sun.star.registry.XRegistryKey;
+import com.sun.star.comp.loader.FactoryHelper;
+
+import com.sun.star.document.XScriptInvocationContext;
+import com.sun.star.reflection.InvocationTargetException;
+
+import java.net.URL;
+
+import com.sun.star.script.provider.XScript;
+
+import com.sun.star.script.provider.ScriptExceptionRaisedException;
+import com.sun.star.script.provider.ScriptFrameworkErrorException;
+import com.sun.star.script.provider.ScriptFrameworkErrorType;
+
+import com.sun.star.script.framework.log.LogUtils;
+import com.sun.star.script.framework.provider.ScriptContext;
+import com.sun.star.script.framework.provider.ClassLoaderFactory;
+import com.sun.star.script.framework.provider.ScriptProvider;
+import com.sun.star.script.framework.provider.ScriptEditor;
+import com.sun.star.script.framework.container.ScriptMetaData;
+
+import org.mozilla.javascript.Context;
+import org.mozilla.javascript.ImporterTopLevel;
+import org.mozilla.javascript.Scriptable;
+import org.mozilla.javascript.JavaScriptException;
+
+public class ScriptProviderForJavaScript
+{
+ public static class _ScriptProviderForJavaScript extends ScriptProvider
+ {
+ public _ScriptProviderForJavaScript(XComponentContext ctx)
+ {
+ super(ctx, "JavaScript");
+ }
+
+ public XScript getScript( /*IN*/String scriptURI )
+ throws com.sun.star.uno.RuntimeException,
+ ScriptFrameworkErrorException
+ {
+ ScriptMetaData scriptData = null;
+ try
+ {
+ scriptData = getScriptData( scriptURI );
+ ScriptImpl script = new ScriptImpl( m_xContext, scriptData, m_xModel, m_xInvocContext );
+ return script;
+ }
+ catch ( com.sun.star.uno.RuntimeException re )
+ {
+ throw new ScriptFrameworkErrorException( "Failed to create script object: " + re.getMessage(),
+ null, scriptData.getLanguageName(), language, ScriptFrameworkErrorType.UNKNOWN );
+ }
+ }
+
+ public boolean hasScriptEditor()
+ {
+ return true;
+ }
+
+ public ScriptEditor getScriptEditor()
+ {
+ return ScriptEditorForJavaScript.getEditor();
+ }
+ }
+
+ /**
+ * Returns a factory for creating the service.
+ * This method is called by the <code>JavaLoader</code>
+ * <p>
+ *
+ * @param implName the name of the implementation for which a service is desired
+ * @param multiFactory the service manager to be used if needed
+ * @param regKey the registryKey
+ * @return returns a <code>XSingleServiceFactory</code> for creating
+ * the component
+ * @see com.sun.star.comp.loader.JavaLoader
+ */
+ public static XSingleServiceFactory __getServiceFactory( String implName,
+ XMultiServiceFactory multiFactory,
+ XRegistryKey regKey )
+ {
+ XSingleServiceFactory xSingleServiceFactory = null;
+
+ if ( implName.equals( ScriptProviderForJavaScript._ScriptProviderForJavaScript.class.getName() ) )
+ {
+ xSingleServiceFactory = FactoryHelper.getServiceFactory(
+ ScriptProviderForJavaScript._ScriptProviderForJavaScript.class,
+ "com.sun.star.script.provider.ScriptProviderForJavaScript",
+ multiFactory,
+ regKey );
+ }
+
+ return xSingleServiceFactory;
+ }
+
+
+ /**
+ * Writes the service information into the given registry key.
+ * This method is called by the <code>JavaLoader</code>
+ * <p>
+ *
+ * @param regKey the registryKey
+ * @return returns true if the operation succeeded
+ * @see com.sun.star.comp.loader.JavaLoader
+ */
+ public static boolean __writeRegistryServiceInfo( XRegistryKey regKey )
+ {
+ String impl = "com.sun.star.script.framework.provider.javascript." +
+ "ScriptProviderForJavaScript$_ScriptProviderForJavaScript";
+
+ String service1 = "com.sun.star.script.provider." +
+ "ScriptProvider";
+ String service2 = "com.sun.star.script.provider." +
+ "LanguageScriptProvider";
+ String service3 = "com.sun.star.script.provider." +
+ "ScriptProviderForJavaScript";
+ String service4 = "com.sun.star.script.browse." +
+ "BrowseNode";
+
+ if ( FactoryHelper.writeRegistryServiceInfo(impl, service1, regKey) &&
+ FactoryHelper.writeRegistryServiceInfo(impl, service2, regKey) &&
+ FactoryHelper.writeRegistryServiceInfo(impl, service3, regKey) &&
+ FactoryHelper.writeRegistryServiceInfo(impl, service4, regKey) )
+ {
+ return true;
+ }
+ return false;
+ }
+}
+class ScriptImpl implements XScript
+{
+ private ScriptMetaData metaData;
+ private XComponentContext m_xContext;
+ private XMultiComponentFactory m_xMultiComponentFactory;
+ private XModel m_xModel;
+ private XScriptInvocationContext m_xInvocContext;
+
+ ScriptImpl( XComponentContext ctx, ScriptMetaData metaData, XModel xModel, XScriptInvocationContext xInvocContext ) throws com.sun.star.uno.RuntimeException
+ {
+ this.metaData = metaData;
+ this.m_xContext = ctx;
+ this.m_xModel = xModel;
+ this.m_xInvocContext = xInvocContext;
+ try
+ {
+ this.m_xMultiComponentFactory = m_xContext.getServiceManager();
+ }
+ catch ( Exception e )
+ {
+ LogUtils.DEBUG( LogUtils.getTrace( e ) );
+ throw new com.sun.star.uno.RuntimeException(
+ "Error constructing ScriptImpl: [javascript]");
+ }
+ LogUtils.DEBUG("ScriptImpl [javascript] script data = " + metaData );
+ }
+
+ /**
+ * The invoke method of the ScriptProviderForJavaScript runs the
+ * JavaScript script specified in the URI
+ *
+ *
+ *
+ * @param aParams All parameters; pure, out params are
+ * undefined in sequence, i.e., the value
+ * has to be ignored by the callee
+ *
+ * @param aOutParamIndex Out indices
+ *
+ * @param aOutParam Out parameters
+ *
+ * @returns The value returned from the function
+ * being invoked
+ *
+ * @throws ScriptFrameworkErrorException If there is no matching script name
+ *
+ *
+ * @throws InvocationTargetException If the running script throws
+ * an exception this information
+ * is captured and rethrown as
+ * ScriptErrorRaisedException or
+ * ScriptExceptionRaisedException
+ */
+
+ public Object invoke(
+ /*IN*/Object[] params,
+ /*OUT*/short[][] aOutParamIndex,
+ /*OUT*/Object[][] aOutParam )
+
+ throws ScriptFrameworkErrorException, InvocationTargetException
+ {
+ // Initialise the out paramters - not used at the moment
+ aOutParamIndex[0] = new short[0];
+ aOutParam[0] = new Object[0];
+
+
+
+ ClassLoader cl = null;
+ URL sourceUrl = null;
+ try {
+ cl = ClassLoaderFactory.getURLClassLoader( metaData );
+ sourceUrl = metaData.getSourceURL();
+ }
+ catch ( java.net.MalformedURLException mfu )
+ {
+ throw new ScriptFrameworkErrorException(
+ mfu.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.MALFORMED_URL );
+ }
+ catch ( com.sun.star.script.framework.provider.NoSuitableClassLoaderException nsc )
+ {
+ // Framework error
+ throw new ScriptFrameworkErrorException(
+ nsc.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.UNKNOWN );
+ }
+ Context ctxt = null;
+
+ try
+ {
+ String editorURL = sourceUrl.toString();
+ Object result = null;
+ String source = null;
+ ScriptEditorForJavaScript editor =
+ ScriptEditorForJavaScript.getEditor(
+ metaData.getSourceURL() );
+
+ if (editor != null)
+ {
+ editorURL = editor.getURL();
+ result = editor.execute();
+ if ( result != null &&
+ result.getClass().getName().equals( "org.mozilla.javascript.Undefined" ) )
+ {
+ // Always return a string
+ // TODO revisit
+ return Context.toString( result );
+ }
+
+ }
+
+ if (editor != null && editor.isModified() == true)
+ {
+ LogUtils.DEBUG("GOT A MODIFIED SOURCE");
+ source = editor.getText();
+ }
+ else
+ {
+ metaData.loadSource();
+ source = metaData.getSource();
+
+ }
+
+ if ( source == null || source.length() == 0 ) {
+ throw new ScriptFrameworkErrorException(
+ "Failed to read source data for script", null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.UNKNOWN );
+ }
+
+ /* Set the context ClassLoader on the current thread to
+ be our custom ClassLoader. This is the suggested method
+ for setting up a ClassLoader to be used by the Rhino
+ interpreter
+ */
+ if (cl != null) {
+ Thread.currentThread().setContextClassLoader(cl);
+ }
+
+ // Initialize a Rhino Context object
+ ctxt = Context.enter();
+
+ /* The ImporterTopLevel ensures that importClass and
+ importPackage statements work in Javascript scripts
+ Make the XScriptContext available as a global variable
+ to the script
+ */
+ ImporterTopLevel scope = new ImporterTopLevel(ctxt);
+
+ Scriptable jsCtxt = Context.toObject(
+ ScriptContext.createContext(
+ m_xModel, m_xInvocContext, m_xContext,
+ m_xMultiComponentFactory), scope);
+ scope.put("XSCRIPTCONTEXT", scope, jsCtxt);
+
+ Scriptable jsArgs = Context.toObject(params, scope);
+ scope.put("ARGUMENTS", scope, jsArgs);
+
+ result = ctxt.evaluateString(scope,
+ source, "<stdin>", 1, null);
+ result = ctxt.toString(result);
+ return result;
+ }
+ catch (JavaScriptException jse) {
+ LogUtils.DEBUG( "Caught JavaScriptException exception for JavaScript type = " + jse.getClass() );
+ String message = jse.getMessage();
+ //int lineNo = jse.getLineNumber();
+ Object wrap = jse.getValue();
+ LogUtils.DEBUG( "\t message " + message );
+ LogUtils.DEBUG( "\t wrapped type " + wrap.getClass() );
+ LogUtils.DEBUG( "\t wrapped toString " + wrap.toString() );
+ ScriptExceptionRaisedException se = new
+ ScriptExceptionRaisedException( message );
+ se.lineNum = -1;
+ se.language = "JavaScript";
+ se.scriptName = metaData.getLanguageName();
+ se.exceptionType = wrap.getClass().getName();
+ se.language = metaData.getLanguage();
+ LogUtils.DEBUG( "ExceptionRaised exception " );
+ LogUtils.DEBUG( "\t message " + se.getMessage() );
+ LogUtils.DEBUG( "\t lineNum " + se.lineNum );
+ LogUtils.DEBUG( "\t language " + se.language );
+ LogUtils.DEBUG( "\t scriptName " + se.scriptName );
+ raiseEditor( se.lineNum );
+ throw new InvocationTargetException( "JavaScript uncaught exception" + metaData.getLanguageName(), null, se );
+ }
+ catch (Exception ex) {
+ LogUtils.DEBUG("Caught Exception " + ex );
+ LogUtils.DEBUG("rethrowing as ScriptFramework error" );
+ throw new ScriptFrameworkErrorException(
+ ex.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.UNKNOWN );
+ }
+ finally {
+ if ( ctxt != null )
+ {
+ Context.exit();
+ }
+ }
+ }
+
+ private void raiseEditor( int lineNum )
+ {
+ ScriptEditorForJavaScript editor = null;
+ try
+ {
+ URL sourceUrl = metaData.getSourceURL();
+ editor = ScriptEditorForJavaScript.getEditor( sourceUrl );
+ if ( editor == null )
+ {
+ editor = ScriptEditorForJavaScript.getEditor();
+ editor.edit(
+ ScriptContext.createContext(m_xModel, m_xInvocContext,
+ m_xContext, m_xMultiComponentFactory), metaData );
+ editor = ScriptEditorForJavaScript.getEditor( sourceUrl );
+ }
+ if ( editor != null )
+ {
+ System.out.println("** Have raised IDE for JavaScript, calling indicateErrorLine for line " + lineNum );
+ editor.indicateErrorLine( lineNum );
+ }
+ }
+ catch( Exception ignore )
+ {
+ }
+ }
+}
+
diff --git a/scripting/java/com/sun/star/script/framework/provider/javascript/template.js b/scripting/java/com/sun/star/script/framework/provider/javascript/template.js
new file mode 100644
index 000000000000..d992791e647c
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/javascript/template.js
@@ -0,0 +1,37 @@
+// Hello World in JavaScript
+// Import standard OpenOffice.org API classes. For more information on
+// these classes and the OpenOffice.org API, see the OpenOffice.org
+// Developers Guide at:
+// http://api.openoffice.org/
+
+importClass(Packages.com.sun.star.uno.UnoRuntime);
+importClass(Packages.com.sun.star.text.XTextDocument);
+importClass(Packages.com.sun.star.text.XText);
+importClass(Packages.com.sun.star.text.XTextRange);
+importClass(Packages.com.sun.star.frame.XModel);
+
+// Import XScriptContext class. An instance of this class is available
+// to all JavaScript scripts in the global variable "XSCRIPTCONTEXT". This
+// variable can be used to access the document for which this script
+// was invoked.
+//
+// Methods available are:
+//
+// XSCRIPTCONTEXT.getDocument() returns XModel
+// XSCRIPTCONTEXT.getInvocationContext() returns XScriptInvocationContext or NULL
+// XSCRIPTCONTEXT.getDesktop() returns XDesktop
+// XSCRIPTCONTEXT.getComponentContext() returns XComponentContext
+//
+// For more information on using this class see the scripting
+// developer guides at:
+//
+// http://api.openoffice.org/docs/DevelopersGuide/ScriptingFramework/ScriptingFramework.xhtml
+//
+
+oDoc = UnoRuntime.queryInterface(XModel,XSCRIPTCONTEXT.getInvocationContext());
+if ( !oDoc )
+ oDoc = XSCRIPTCONTEXT.getDocument();
+xTextDoc = UnoRuntime.queryInterface(XTextDocument,oDoc);
+xText = xTextDoc.getText();
+xTextRange = xText.getEnd();
+xTextRange.setString( "Hello World (in JavaScript)" );