Debian Codegraph @

scripting/java/com/sun/star/script/framework/provider/ScriptProvider.java

raw
1 /*
2 * This file is part of the LibreOffice project.
3 *
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7 *
8 * This file incorporates work covered by the following license notice:
9 *
10 * Licensed to the Apache Software Foundation (ASF) under one or more
11 * contributor license agreements. See the NOTICE file distributed
12 * with this work for additional information regarding copyright
13 * ownership. The ASF licenses this file to you under the Apache
14 * License, Version 2.0 (the "License"); you may not use this file
15 * except in compliance with the License. You may obtain a copy of
16 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
17 */
18 package com.sun.star.script.framework.provider;
19
20 import com.sun.star.beans.Property;
21 import com.sun.star.beans.XIntrospectionAccess;
22 import com.sun.star.beans.XPropertyChangeListener;
23 import com.sun.star.beans.XPropertySet;
24 import com.sun.star.beans.XPropertySetInfo;
25 import com.sun.star.beans.XVetoableChangeListener;
26
27 import com.sun.star.container.XNameContainer;
28
29 import com.sun.star.deployment.XPackage;
30
31 import com.sun.star.document.XScriptInvocationContext;
32
33 import com.sun.star.frame.XModel;
34 import com.sun.star.frame.XTransientDocumentsDocumentContentFactory;
35
36 import com.sun.star.lang.XInitialization;
37 import com.sun.star.lang.XMultiComponentFactory;
38 import com.sun.star.lang.XServiceInfo;
39 import com.sun.star.lang.XTypeProvider;
40
41 import com.sun.star.script.XInvocation;
42 import com.sun.star.script.browse.BrowseNodeTypes;
43 import com.sun.star.script.browse.XBrowseNode;
44 import com.sun.star.script.framework.browse.DialogFactory;
45 import com.sun.star.script.framework.browse.ProviderBrowseNode;
46 import com.sun.star.script.framework.container.ParcelContainer;
47 import com.sun.star.script.framework.container.ParsedScriptUri;
48 import com.sun.star.script.framework.container.ScriptMetaData;
49 import com.sun.star.script.framework.container.UnoPkgContainer;
50 import com.sun.star.script.framework.container.XMLParserFactory;
51 import com.sun.star.script.framework.log.LogUtils;
52 import com.sun.star.script.provider.ScriptFrameworkErrorException;
53 import com.sun.star.script.provider.ScriptFrameworkErrorType;
54 import com.sun.star.script.provider.XScript;
55 import com.sun.star.script.provider.XScriptContext;
56 import com.sun.star.script.provider.XScriptProvider;
57
58 import com.sun.star.sdbc.XRow;
59
60 import com.sun.star.ucb.Command;
61 import com.sun.star.ucb.UniversalContentBroker;
62 import com.sun.star.ucb.XCommandProcessor;
63 import com.sun.star.ucb.XContent;
64 import com.sun.star.ucb.XContentIdentifier;
65 import com.sun.star.ucb.XUniversalContentBroker;
66
67 import com.sun.star.uno.AnyConverter;
68 import com.sun.star.uno.Exception;
69 import com.sun.star.uno.Type;
70 import com.sun.star.uno.TypeClass;
71 import com.sun.star.uno.UnoRuntime;
72 import com.sun.star.uno.XComponentContext;
73
74 import com.sun.star.util.XMacroExpander;
75
76 public abstract class ScriptProvider implements
77 XScriptProvider, XBrowseNode, XPropertySet, XInvocation, XInitialization,
78 XTypeProvider, XServiceInfo, XNameContainer {
79
80 private final String[] __serviceNames = {
81 "com.sun.star.script.provider.ScriptProviderFor",
82 "com.sun.star.script.provider.LanguageScriptProvider",
83 "com.sun.star.script.browse.BrowseNode",
84 "com.sun.star.script.provider.ScriptProvider"
85 };
86
87 protected String language;
88
89 protected XComponentContext m_xContext;
90 private XMultiComponentFactory m_xMultiComponentFactory;
91 protected XModel m_xModel;
92 protected XScriptInvocationContext m_xInvocContext;
93 private ParcelContainer m_container;
94
95 // proxies to helper objects which implement interfaces
96 private XPropertySet m_xPropertySetProxy;
97 private XInvocation m_xInvocationProxy;
98
99 // TODO should this be implemented in this class
100 private XBrowseNode m_xBrowseNodeProxy;
101 private XScriptContext m_xScriptContext;
102
103 public ScriptProvider(XComponentContext ctx, String language) {
104 this.language = language;
105 __serviceNames[0] += language;
106
107 LogUtils.DEBUG("ScriptProvider: constructor - start. " + language);
108
109 m_xContext = ctx;
110
111 // Initialize DialogFactory class in case dialogs are required
112 DialogFactory.createDialogFactory(m_xContext);
113
114 try {
115 m_xMultiComponentFactory = m_xContext.getServiceManager();
116
117 if (m_xMultiComponentFactory == null) {
118 throw new Exception("Error could not obtain a " +
119 "multicomponent factory - rethrowing Exception.");
120 }
121
122 Object serviceObj =
123 m_xContext.getValueByName(
124 "/singletons/com.sun.star.util.theMacroExpander");
125
126 XMacroExpander me =
127 (XMacroExpander) AnyConverter.toObject(
128 new Type(XMacroExpander.class), serviceObj);
129
130 XMLParserFactory.setOfficeDTDURL(
131 me.expandMacros(
132 "$BRAND_BASE_DIR/$BRAND_SHARE_SUBDIR/dtd/officedocument/1_0/"));
133
134 } catch (Exception e) {
135 LogUtils.DEBUG(LogUtils.getTrace(e));
136 throw new com.sun.star.uno.RuntimeException(
137 e, "Error constructing ScriptProvider: " + e);
138 }
139
140 LogUtils.DEBUG("ScriptProvider: constructor - finished.");
141 }
142
143 synchronized public XScriptContext getScriptingContext() {
144 if (m_xScriptContext == null) {
145 m_xScriptContext = ScriptContext.createContext(m_xModel, m_xInvocContext,
146 m_xContext, m_xMultiComponentFactory);
147 }
148
149 return m_xScriptContext;
150 }
151
152 public void initialize(Object[] aArguments)
153 throws com.sun.star.uno.Exception {
154 LogUtils.DEBUG("entering XInit for language " + language);
155 boolean isPkgProvider = false;
156
157 if (aArguments.length == 1) {
158 String contextUrl = null;
159
160 if (AnyConverter.getType(aArguments[0]).getTypeClass().equals(
161 TypeClass.INTERFACE)) {
162 // try whether it denotes a XScriptInvocationContext
163 m_xInvocContext =
164 UnoRuntime.queryInterface(XScriptInvocationContext.class, aArguments[0]);
165
166 if (m_xInvocContext != null) {
167 // if so, obtain the document - by definition, this must be
168 // the ScriptContainer
169 m_xModel =
170 UnoRuntime.queryInterface(XModel.class, m_xInvocContext.getScriptContainer());
171 } else {
172 // otherwise, check whether it's an XModel
173 m_xModel =
174 UnoRuntime.queryInterface(XModel.class, aArguments[0]);
175 }
176
177 if (m_xModel == null) {
178 throw new com.sun.star.uno.Exception(
179 "ScriptProvider argument must be either a string, a valid XScriptInvocationContext, "
180 + "or an XModel", this);
181 }
182
183 contextUrl = getDocUrlFromModel(m_xModel);
184 m_container = new ParcelContainer(m_xContext, contextUrl, language);
185
186 } else if (AnyConverter.isString(aArguments[0])) {
187
188 String originalContextURL = AnyConverter.toString(aArguments[0]);
189 LogUtils.DEBUG("creating Application, path: " + originalContextURL);
190 contextUrl = originalContextURL;
191
192 // TODO no support for packages in documents yet
193 if (originalContextURL.startsWith("vnd.sun.star.tdoc")) {
194 m_container = new ParcelContainer(m_xContext, contextUrl, language);
195 m_xModel = getModelFromDocUrl(originalContextURL);
196 } else {
197 String extensionDb = "vnd.sun.star.expand:${$BRAND_INI_DIR/"
198 + PathUtils.BOOTSTRAP_NAME + "::UserInstallation}/user";
199
200 String extensionRepository = null;
201
202 if (originalContextURL.startsWith("bundled")) {
203 contextUrl = "vnd.sun.star.expand:$BUNDLED_EXTENSIONS";
204 extensionRepository = "bundled";
205 } else if (originalContextURL.startsWith("share")) {
206 contextUrl = "vnd.sun.star.expand:$BRAND_BASE_DIR/$BRAND_SHARE_SUBDIR";
207 extensionRepository = "shared";
208 } else if (originalContextURL.startsWith("user")) {
209 contextUrl = "vnd.sun.star.expand:${$BRAND_INI_DIR/"
210 + PathUtils.BOOTSTRAP_NAME + "::UserInstallation}/user";
211 extensionRepository = "user";
212 }
213
214 if (originalContextURL.endsWith("uno_packages")) {
215 isPkgProvider = true;
216
217 if (!originalContextURL.equals(contextUrl)
218 && extensionRepository != null
219 && !extensionRepository.equals("bundled")) {
220
221 contextUrl = PathUtils.make_url(contextUrl, "uno_packages");
222 }
223 }
224
225 if (isPkgProvider) {
226 m_container =
227 new UnoPkgContainer(m_xContext, contextUrl, extensionDb, extensionRepository,
228 language);
229 } else {
230 m_container =
231 new ParcelContainer(m_xContext, contextUrl, language);
232 }
233 }
234 } else {
235 throw new com.sun.star.uno.RuntimeException(
236 "ScriptProvider created with invalid argument");
237 }
238
239 LogUtils.DEBUG("Modified Application path is: " + contextUrl);
240 LogUtils.DEBUG("isPkgProvider is: " + isPkgProvider);
241
242 // TODO should all be done in this class instead of
243 // delegation????
244 m_xBrowseNodeProxy =
245 new ProviderBrowseNode(this, m_container, m_xContext);
246
247 m_xInvocationProxy =
248 UnoRuntime.queryInterface(XInvocation.class, m_xBrowseNodeProxy);
249 m_xPropertySetProxy =
250 UnoRuntime.queryInterface(XPropertySet.class, m_xBrowseNodeProxy);
251 } else {
252 // this is ok, for example when executing a script from the
253 // command line
254 LogUtils.DEBUG("ScriptProviderFor" + language +
255 " initialized without a context");
256 }
257
258 LogUtils.DEBUG("leaving XInit");
259 }
260
261 /**
262 * Gets the types attribute of the ScriptProvider object
263 *
264 * @return The types value
265 */
266 public com.sun.star.uno.Type[] getTypes() {
267 Type[] retValue = new Type[ 8 ];
268 retValue[ 0 ] = new Type(XScriptProvider.class);
269 retValue[ 1 ] = new Type(XBrowseNode.class);
270 retValue[ 2 ] = new Type(XInitialization.class);
271 retValue[ 3 ] = new Type(XTypeProvider.class);
272 retValue[ 4 ] = new Type(XServiceInfo.class);
273 retValue[ 5 ] = new Type(XPropertySet.class);
274 retValue[ 6 ] = new Type(XInvocation.class);
275 retValue[ 7 ] = new Type(com.sun.star.container.XNameContainer.class);
276
277 return retValue;
278 }
279
280 /**
281 * Gets the implementationId attribute of the ScriptProvider object
282 *
283 * @return The implementationId value
284 */
285 public byte[] getImplementationId() {
286 return new byte[0];
287 }
288
289 /**
290 * Gets the implementationName attribute of the ScriptProvider object
291 *
292 * @return The implementationName value
293 */
294 public String getImplementationName() {
295 return getClass().getName();
296 }
297
298 /**
299 * Description of the Method
300 *
301 * @param serviceName Description of the Parameter
302 * @return Description of the Return Value
303 */
304 public boolean supportsService(String serviceName) {
305 for (int index = __serviceNames.length; index-- > 0;) {
306 if (serviceName.equals(__serviceNames[ index ])) {
307 return true;
308 }
309 }
310
311 return false;
312 }
313
314 /**
315 * Gets the supportedServiceNames attribute of the ScriptProvider object
316 *
317 * @return The supportedServiceNames value
318 */
319 public String[] getSupportedServiceNames() {
320 return __serviceNames;
321 }
322
323 public abstract XScript getScript(/*IN*/String scriptURI) throws
324 com.sun.star.uno.RuntimeException, ScriptFrameworkErrorException;
325
326 // TODO need to encapsulate this better,
327 // Some factory concept for creating/accessing Editor
328 // How this is passed down or how it is accessible by BrowseNode
329 // implementations needs thinking about
330 // This method is used to determine whether the ScriptProvider
331 // has a ScriptEditor
332 public abstract boolean hasScriptEditor();
333
334 // TODO see above
335 // This method is used to get the ScriptEditor for this ScriptProvider
336 public abstract ScriptEditor getScriptEditor();
337
338 public ScriptMetaData getScriptData(/*IN*/String scriptURI) throws
339 ScriptFrameworkErrorException {
340
341 try {
342 ParsedScriptUri details = m_container.parseScriptUri(scriptURI);
343
344 try {
345 ScriptMetaData scriptData = m_container.findScript(details);
346
347 if (scriptData == null) {
348 throw new ScriptFrameworkErrorException(
349 details.function + " does not exist", null, details.function, language,
350 ScriptFrameworkErrorType.NO_SUCH_SCRIPT);
351 }
352
353 return scriptData;
354 } catch (com.sun.star.container.NoSuchElementException nse) {
355 ScriptFrameworkErrorException e2 =
356 new ScriptFrameworkErrorException(nse.getMessage(), null, details.function,
357 language, ScriptFrameworkErrorType.NO_SUCH_SCRIPT);
358 e2.initCause(nse);
359 throw e2;
360 } catch (com.sun.star.lang.WrappedTargetException wta) {
361 // TODO specify the correct error Type
362 java.lang.Exception wrapped = (java.lang.Exception) wta.TargetException;
363 String message = wta.getMessage();
364
365 if (wrapped != null) {
366 message = wrapped.getMessage();
367 }
368
369 ScriptFrameworkErrorException e2 =
370 new ScriptFrameworkErrorException(message, null, details.function, language,
371 ScriptFrameworkErrorType.UNKNOWN);
372 e2.initCause(wta);
373 throw e2;
374 }
375 } catch (com.sun.star.lang.IllegalArgumentException ila) {
376 // TODO specify the correct error Type
377 ScriptFrameworkErrorException e2
378 = new ScriptFrameworkErrorException(
379 ila.getMessage(), null, scriptURI, language,
380 ScriptFrameworkErrorType.UNKNOWN);
381 e2.initCause(ila);
382 throw e2;
383 }
384 }
385
386 // Implementation of XBrowseNode interface
387 public String getName() {
388 return language;
389 }
390
391 public XBrowseNode[] getChildNodes() {
392 if (m_xBrowseNodeProxy == null) {
393 LogUtils.DEBUG("No Nodes available ");
394 return new XBrowseNode[0];
395 }
396
397 return m_xBrowseNodeProxy .getChildNodes();
398 }
399
400 public boolean hasChildNodes() {
401 if (m_xBrowseNodeProxy == null) {
402 LogUtils.DEBUG("No Nodes available ");
403 return false;
404 }
405
406 return m_xBrowseNodeProxy.hasChildNodes();
407 }
408
409 public short getType() {
410 return BrowseNodeTypes.CONTAINER;
411 }
412
413 @Override
414 public String toString() {
415 return getName();
416 }
417
418 // implementation of XInvocation interface
419 public XIntrospectionAccess getIntrospection() {
420 return m_xInvocationProxy.getIntrospection();
421 }
422
423 public Object invoke(String aFunctionName, Object[] aParams,
424 short[][] aOutParamIndex, Object[][] aOutParam) throws
425 com.sun.star.lang.IllegalArgumentException,
426 com.sun.star.script.CannotConvertException,
427 com.sun.star.reflection.InvocationTargetException {
428
429 return m_xInvocationProxy.invoke(
430 aFunctionName, aParams, aOutParamIndex, aOutParam);
431 }
432
433 public void setValue(String aPropertyName, Object aValue) throws
434 com.sun.star.beans.UnknownPropertyException,
435 com.sun.star.script.CannotConvertException,
436 com.sun.star.reflection.InvocationTargetException {
437
438 m_xInvocationProxy.setValue(aPropertyName, aValue);
439 }
440
441 public Object getValue(String aPropertyName) throws
442 com.sun.star.beans.UnknownPropertyException {
443 return m_xInvocationProxy.getValue(aPropertyName);
444 }
445
446 public boolean hasMethod(String aName) {
447 return m_xInvocationProxy.hasMethod(aName);
448 }
449
450 public boolean hasProperty(String aName) {
451 return m_xInvocationProxy.hasProperty(aName);
452 }
453
454 public XPropertySetInfo getPropertySetInfo() {
455 return m_xPropertySetProxy.getPropertySetInfo();
456 }
457
458 public void setPropertyValue(String aPropertyName, Object aValue) throws
459 com.sun.star.beans.UnknownPropertyException,
460 com.sun.star.beans.PropertyVetoException,
461 com.sun.star.lang.IllegalArgumentException,
462 com.sun.star.lang.WrappedTargetException {
463
464 m_xPropertySetProxy.setPropertyValue(aPropertyName, aValue);
465 }
466
467 public Object getPropertyValue(String PropertyName) throws
468 com.sun.star.beans.UnknownPropertyException,
469 com.sun.star.lang.WrappedTargetException {
470
471 return m_xPropertySetProxy.getPropertyValue(PropertyName);
472 }
473
474 public void addPropertyChangeListener(String aPropertyName,
475 XPropertyChangeListener xListener) throws
476 com.sun.star.beans.UnknownPropertyException,
477 com.sun.star.lang.WrappedTargetException {
478
479 m_xPropertySetProxy.addPropertyChangeListener(aPropertyName, xListener);
480 }
481
482 public void removePropertyChangeListener(
483 String aPropertyName, XPropertyChangeListener aListener) throws
484 com.sun.star.beans.UnknownPropertyException,
485 com.sun.star.lang.WrappedTargetException {
486
487 m_xPropertySetProxy.removePropertyChangeListener(
488 aPropertyName, aListener);
489 }
490
491 public void addVetoableChangeListener(
492 String PropertyName, XVetoableChangeListener aListener) throws
493 com.sun.star.beans.UnknownPropertyException,
494 com.sun.star.lang.WrappedTargetException {
495
496 m_xPropertySetProxy.addVetoableChangeListener(PropertyName, aListener);
497 }
498
499 public void removeVetoableChangeListener(String PropertyName,
500 XVetoableChangeListener aListener) throws
501 com.sun.star.beans.UnknownPropertyException,
502 com.sun.star.lang.WrappedTargetException {
503
504 m_xPropertySetProxy.removeVetoableChangeListener(
505 PropertyName, aListener);
506
507 }
508 public java.lang.Object getByName(String aName) throws
509 com.sun.star.container.NoSuchElementException,
510 com.sun.star.lang.WrappedTargetException {
511
512 // TODO needs implementing?
513 throw new com.sun.star.uno.RuntimeException("getByName not implemented");
514 }
515
516 public String[] getElementNames() {
517 // TODO needs implementing?
518 throw new com.sun.star.uno.RuntimeException("getElementNames not implemented");
519 }
520
521 // Performs the getRegStatus functionality for the PkgMgr
522 public boolean hasByName(String aName) {
523 return ((UnoPkgContainer)m_container).hasRegisteredUnoPkgContainer(aName);
524 }
525
526 public com.sun.star.uno.Type getElementType() {
527 // TODO at the moment this returns void indicating
528 // type is unknown should indicate XPackage ? do we implement XPackage
529 return new Type();
530 }
531
532 public boolean hasElements() {
533 // TODO needs implementing?
534 throw new com.sun.star.uno.RuntimeException("hasElements not implemented");
535 }
536 public void replaceByName(String aName, java.lang.Object aElement) throws
537 com.sun.star.lang.IllegalArgumentException,
538 com.sun.star.container.NoSuchElementException,
539 com.sun.star.lang.WrappedTargetException {
540
541 // TODO needs implementing
542 throw new com.sun.star.uno.RuntimeException("replaceByName not implemented");
543 }
544
545 public void insertByName(String aName, java.lang.Object aElement) throws
546 com.sun.star.lang.IllegalArgumentException,
547 com.sun.star.container.ElementExistException,
548 com.sun.star.lang.WrappedTargetException {
549
550 LogUtils.DEBUG("Provider for " + language + " received register for package "
551 + aName);
552
553 XPackage newPackage = UnoRuntime.queryInterface(XPackage.class, aElement);
554
555 if (aName == null || aName.length() == 0) {
556 throw new com.sun.star.lang.IllegalArgumentException("Empty name");
557 }
558
559 if (newPackage == null) {
560 throw new com.sun.star.lang.IllegalArgumentException("No package supplied");
561 }
562
563 ((UnoPkgContainer)m_container).processUnoPackage(newPackage, language);
564 }
565
566 // de-register for library only !!
567 public void removeByName(String Name) throws
568 com.sun.star.container.NoSuchElementException,
569 com.sun.star.lang.WrappedTargetException {
570
571 LogUtils.DEBUG("In ScriptProvider.removeByName() for " + Name
572 + " this provider = " + language);
573
574 ParcelContainer c =
575 ((UnoPkgContainer)m_container).getRegisteredUnoPkgContainer(
576 Name);
577
578 if (c != null) {
579 String libName;
580
581 if (Name.endsWith("/")) {
582 String tmp = Name.substring(0, Name.lastIndexOf('/'));
583 libName = tmp.substring(tmp.lastIndexOf('/') + 1);
584 } else {
585 libName = Name.substring(Name.lastIndexOf('/') + 1);
586 }
587
588 LogUtils.DEBUG("Deregistering library " + libName);
589
590 if (c.removeParcel(libName)) {
591 ((UnoPkgContainer)m_container).deRegisterPackageContainer(Name);
592 } else {
593 throw new com.sun.star.container.NoSuchElementException(
594 libName + " cannot be removed from container.");
595 }
596 } else {
597 throw new com.sun.star.container.NoSuchElementException(
598 Name + " doesn't exist for " + language);
599 }
600
601 // TODO see if we want to remove the ParcelContainer is no Parcels/Libraries left
602 }
603
604 private String getDocUrlFromModel(XModel document) {
605 XTransientDocumentsDocumentContentFactory factory = null;
606
607 try {
608
609 factory = UnoRuntime.queryInterface(
610 XTransientDocumentsDocumentContentFactory.class,
611 m_xMultiComponentFactory.createInstanceWithContext(
612 "com.sun.star.frame.TransientDocumentsDocumentContentFactory",
613 m_xContext));
614
615 } catch (Exception ex) {
616 }
617
618 if (factory == null)
619 throw new com.sun.star.uno.RuntimeException(
620 "ScriptProvider: unable to create a TDOC context factory.", this);
621
622 try {
623 XContent content = factory.createDocumentContent(document);
624 return content.getIdentifier().getContentIdentifier();
625 } catch (com.sun.star.lang.IllegalArgumentException ex) {
626 }
627
628 LogUtils.DEBUG("unable to determine the model's TDOC URL");
629 return "";
630 }
631
632 private XModel getModelFromDocUrl(String docUrl) {
633
634 LogUtils.DEBUG("getModelFromDocUrl - searching for match for ->"
635 + docUrl + "<-");
636
637 XModel xModel = null;
638
639 try {
640 XUniversalContentBroker ucb = UniversalContentBroker.create(m_xContext);
641
642 XContentIdentifier xCntId = ucb.createContentIdentifier(docUrl);
643
644 XContent xCnt = ucb.queryContent(xCntId);
645
646 XCommandProcessor xCmd =
647 UnoRuntime.queryInterface(XCommandProcessor.class, xCnt);
648
649 Property[] pArgs = new Property[ ] { new Property() };
650 pArgs[ 0 ].Name = "DocumentModel";
651 pArgs[ 0 ].Handle = -1;
652
653 Command command = new Command();
654
655 command.Handle = -1;
656 command.Name = "getPropertyValues";
657 command.Argument = pArgs;
658
659 com.sun.star.ucb.XCommandEnvironment env = null ;
660 Object result = xCmd.execute(command, 0, env) ;
661
662 XRow values = UnoRuntime.queryInterface(XRow.class, result);
663
664 xModel = UnoRuntime.queryInterface(XModel.class,
665 values.getObject(1, null));
666
667 } catch (Exception ignore) {
668 LogUtils.DEBUG("Failed to get model exception " + ignore);
669 }
670
671 return xModel;
672 }
673 }