1 /*************************************************************************
3 * The Contents of this file are made available subject to the terms of
6 * Copyright 2000, 2010 Oracle and/or its affiliates.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of Sun Microsystems, Inc. nor the names of its
18 * contributors may be used to endorse or promote products derived
19 * from this software without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
28 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
29 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
30 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
31 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 *************************************************************************/
35 // Import everything we use
37 import com
.sun
.star
.beans
.XPropertySet
;
38 import com
.sun
.star
.beans
.XMultiPropertySet
;
39 import com
.sun
.star
.beans
.XHierarchicalPropertySet
;
40 import com
.sun
.star
.beans
.XMultiHierarchicalPropertySet
;
41 import com
.sun
.star
.beans
.XPropertyState
;
42 import com
.sun
.star
.beans
.XMultiPropertyStates
;
44 import com
.sun
.star
.configuration
.XTemplateInstance
;
46 import com
.sun
.star
.container
.XNameAccess
;
47 import com
.sun
.star
.container
.XNameReplace
;
48 import com
.sun
.star
.container
.XNameContainer
;
49 import com
.sun
.star
.container
.XNamed
;
50 import com
.sun
.star
.container
.XChild
;
51 import com
.sun
.star
.container
.XHierarchicalNameAccess
;
52 import com
.sun
.star
.container
.XHierarchicalName
;
54 import com
.sun
.star
.lang
.XComponent
;
55 import com
.sun
.star
.lang
.XMultiComponentFactory
;
56 import com
.sun
.star
.lang
.XSingleServiceFactory
;
57 import com
.sun
.star
.lang
.XMultiServiceFactory
;
58 import com
.sun
.star
.lang
.XServiceInfo
;
59 import com
.sun
.star
.lang
.EventObject
;
61 import com
.sun
.star
.uno
.UnoRuntime
;
62 import com
.sun
.star
.uno
.XComponentContext
;
63 import com
.sun
.star
.uno
.XInterface
;
64 import com
.sun
.star
.uno
.AnyConverter
;
66 import com
.sun
.star
.util
.XChangesBatch
;
67 import com
.sun
.star
.util
.XChangesNotifier
;
68 import com
.sun
.star
.util
.XChangesListener
;
69 import com
.sun
.star
.util
.ChangesEvent
;
72 /* These examples show how to use the following features of the Config API:
76 o Updating properties in groups
77 o Adding and removing items in sets
78 o Resetting data to their defaults
80 Each example is in a separate method call.
82 public class ConfigExamples
84 // The ComponentContext interface of the remote component context
85 private final XComponentContext mxContext
;
87 // The MultiComponentFactory interface of the ServiceManager
88 private final XMultiComponentFactory mxServiceManager
;
90 // The MultiServiceFactory interface of the ConfigurationProvider
91 private XMultiServiceFactory mxProvider
= null;
93 public static void main( String args
[] )
96 // get the remote office component context
97 com
.sun
.star
.uno
.XComponentContext xContext
=
98 com
.sun
.star
.comp
.helper
.Bootstrap
.bootstrap();
100 if( xContext
!= null )
101 System
.out
.println("Connected to a running office ...");
103 System
.out
.println( "ERROR: Cannot connect - no remote component context available." );
105 // Create an instance of the class and call its run method
106 ConfigExamples aExample
= new ConfigExamples(xContext
);
109 // if you own the service manager dispose it here
110 // to ensure that the default provider is properly disposed and flushed
120 /** Create a ConfigExamples instance supplying a service factory
122 public ConfigExamples(XComponentContext xContext
)
124 mxContext
= xContext
;
125 mxServiceManager
= xContext
.getServiceManager();
128 /** Run the examples with a default ConfigurationProvider
131 throws com
.sun
.star
.uno
.Exception
133 mxProvider
= createProvider();
137 // we are using the default ConfigurationProvider, so we must not dispose it
141 /** Run the examples with a given ConfigurationProvider
143 public void runExamples( )
145 if (checkProvider(mxProvider
))
147 System
.out
.println("\nStarting examples.");
153 updateGroupExample();
159 System
.out
.println("\nAll Examples completed.");
162 System
.out
.println("ERROR: Cannot run examples without ConfigurationProvider.");
166 /** Do some simple checks, if there is a valid ConfigurationProvider
168 public static boolean checkProvider(XMultiServiceFactory xProvider
)
170 // check the provider we have
171 if (xProvider
== null)
173 System
.out
.println("No provider available. Cannot access configuration data.");
180 // check the provider implementation
181 XServiceInfo xProviderServices
=
182 UnoRuntime
.queryInterface( XServiceInfo
.class, xProvider
);
184 if (xProviderServices
== null ||
185 !xProviderServices
.supportsService("com.sun.star.configuration.ConfigurationProvider"))
187 System
.out
.println("WARNING: The provider is not a com.sun.star.configuration.ConfigurationProvider");
190 if (xProviderServices
!= null)
192 System
.out
.println("Using provider implementation: " + xProviderServices
.getImplementationName());
197 catch (com
.sun
.star
.uno
.RuntimeException e
)
199 System
.err
.println("ERROR: Failure while checking the provider services.");
205 /** Get the provider we have
207 public XMultiServiceFactory
getProvider( )
212 /** Create a default configuration provider
214 public XMultiServiceFactory
createProvider( )
215 throws com
.sun
.star
.uno
.Exception
217 final String sProviderService
= "com.sun.star.configuration.ConfigurationProvider";
219 // create the provider and return it as a XMultiServiceFactory
220 XMultiServiceFactory xProvider
= UnoRuntime
.queryInterface(XMultiServiceFactory
.class,
221 mxServiceManager
.createInstanceWithContext(sProviderService
,
227 /** Create a specified read-only configuration view
229 public Object
createConfigurationView( String sPath
)
230 throws com
.sun
.star
.uno
.Exception
232 XMultiServiceFactory xProvider
= getProvider();
234 // The service name: Need only read access:
235 final String sReadOnlyView
= "com.sun.star.configuration.ConfigurationAccess";
237 // creation arguments: nodepath
238 com
.sun
.star
.beans
.PropertyValue aPathArgument
= new com
.sun
.star
.beans
.PropertyValue();
239 aPathArgument
.Name
= "nodepath";
240 aPathArgument
.Value
= sPath
;
242 Object
[] aArguments
= new Object
[1];
243 aArguments
[0] = aPathArgument
;
246 Object xViewRoot
= xProvider
.createInstanceWithArguments(sReadOnlyView
, aArguments
);
251 /** Create a specified updatable configuration view
253 Object
createUpdatableView( String sPath
)
254 throws com
.sun
.star
.uno
.Exception
256 XMultiServiceFactory xProvider
= getProvider();
258 // The service name: Need update access:
259 final String cUpdatableView
= "com.sun.star.configuration.ConfigurationUpdateAccess";
261 // creation arguments: nodepath
262 com
.sun
.star
.beans
.PropertyValue aPathArgument
= new com
.sun
.star
.beans
.PropertyValue();
263 aPathArgument
.Name
= "nodepath";
264 aPathArgument
.Value
= sPath
;
266 Object
[] aArguments
= new Object
[1];
267 aArguments
[0] = aPathArgument
;
270 Object xViewRoot
= xProvider
.createInstanceWithArguments(cUpdatableView
, aArguments
);
275 /** This method demonstrates read access to data
277 protected void readDataExample ()
281 System
.out
.println("\n--- starting example: read grid option settings --------------------");
282 Object aData
= readGridConfiguration( );
283 System
.out
.println("Read grid options: " + aData
);
286 catch ( Exception e
)
292 /** This method demonstrates browsing access to data
294 protected void browseDataExample ()
298 System
.out
.println("\n--- starting example: browse filter configuration ------------------");
299 printRegisteredFilters( );
301 catch ( Exception e
)
307 /** This method demonstrates update access to group data
309 protected void updateGroupExample ()
313 System
.out
.println("\n--- starting example: update group data --------------");
316 catch ( Exception e
)
322 /** This method demonstrates resetting data to its default state
324 protected void resetGroupExample ()
328 System
.out
.println("\n--- starting example: reset group data -----------------------------");
329 Object aOldData
= readGridConfiguration( );
330 resetGridConfiguration( );
331 Object aNewData
= readGridConfiguration( );
332 System
.out
.println("Before reset: user grid options: " + aOldData
);
333 System
.out
.println("After reset: default grid options: " + aNewData
);
335 catch ( Exception e
)
341 /** This method demonstrates update access to set data
343 protected void updateSetExample ()
347 System
.out
.println("\n--- starting example: update set data ---------------");
348 storeSampleDataSource( );
350 catch ( Exception e
)
357 /// class to hold information about grid settings
358 private static class GridOptions
360 private boolean visible
;
361 private int resolution_x
;
362 private int resolution_y
;
363 private int subdivision_x
;
364 private int subdivision_y
;
367 public String
toString() {
368 StringBuffer aBuffer
= new StringBuffer();
369 aBuffer
.append("[ Grid is "); aBuffer
.append(visible ?
"VISIBLE" : "HIDDEN");
370 aBuffer
.append("; resolution = (" + resolution_x
+ "," + resolution_y
+ ")");
371 aBuffer
.append("; subdivision = (" + subdivision_x
+ "," + subdivision_y
+ ")");
372 aBuffer
.append(" ]");
373 return aBuffer
.toString();
377 /// This method reads information about grid settings
378 protected GridOptions
readGridConfiguration()
379 throws com
.sun
.star
.uno
.Exception
381 // The path to the root element
382 final String cGridOptionsPath
= "/org.openoffice.Office.Calc/Grid";
385 Object xViewRoot
= createConfigurationView(cGridOptionsPath
);
387 // the result structure
388 GridOptions options
= new GridOptions();
390 // accessing a single nested value
391 XHierarchicalPropertySet xProperties
=
392 UnoRuntime
.queryInterface(XHierarchicalPropertySet
.class, xViewRoot
);
394 Object aVisible
= xProperties
.getHierarchicalPropertyValue("Option/VisibleGrid");
395 options
.visible
= ((Boolean
) aVisible
).booleanValue();
397 // accessing a nested object and its subproperties
398 Object xSubdivision
= xProperties
.getHierarchicalPropertyValue("Subdivision");
400 XMultiPropertySet xSubdivProperties
=
401 UnoRuntime
.queryInterface(XMultiPropertySet
.class, xSubdivision
);
403 // variables for multi-element access
404 String
[] aElementNames
= new String
[] { "XAxis", "YAxis" };
406 Object
[] aElementValues
= xSubdivProperties
.getPropertyValues(aElementNames
);
408 options
.subdivision_x
= ((Integer
) aElementValues
[0]).intValue();
409 options
.subdivision_y
= ((Integer
) aElementValues
[1]).intValue();
411 // accessing deeply nested subproperties
412 Object xResolution
= xProperties
.getHierarchicalPropertyValue("Resolution");
414 XMultiHierarchicalPropertySet xResolutionProperties
=
415 UnoRuntime
.queryInterface(XMultiHierarchicalPropertySet
.class, xResolution
);
417 aElementNames
[0] = "XAxis/Metric";
418 aElementNames
[1] = "YAxis/Metric";
420 aElementValues
= xResolutionProperties
.getHierarchicalPropertyValues(aElementNames
);
422 options
.resolution_x
= ((Integer
) aElementValues
[0]).intValue();
423 options
.resolution_y
= ((Integer
) aElementValues
[1]).intValue();
425 // all options have been retrieved - clean up and return
426 // we are done with the view - dispose it
428 UnoRuntime
.queryInterface(XComponent
.class, xViewRoot
).dispose();
434 /// Interface to procees information when browsing the configuration tree
435 public interface IConfigurationProcessor
437 /// process a value item
438 void processValueElement( String sPath_
, Object aValue_
);
439 /// process a structural item
440 void processStructuralElement( String sPath_
, XInterface xElement_
);
443 /// Internal method to recursively browse a structural element in preorder
444 public void browseElementRecursively( XInterface xElement
, IConfigurationProcessor aProcessor
)
445 throws com
.sun
.star
.uno
.Exception
447 // First process this as an element (preorder traversal)
448 XHierarchicalName xElementPath
=
449 UnoRuntime
.queryInterface(XHierarchicalName
.class, xElement
);
451 String sPath
= xElementPath
.getHierarchicalName();
453 aProcessor
.processStructuralElement( sPath
, xElement
);
455 // now process this as a container
456 XNameAccess xChildAccess
=
457 UnoRuntime
.queryInterface(XNameAccess
.class, xElement
);
459 // get a list of child elements
460 String
[] aElementNames
= xChildAccess
.getElementNames();
462 // and process them one by one
463 for(int i
=0; i
< aElementNames
.length
; ++i
)
465 Object aChild
= xChildAccess
.getByName( aElementNames
[i
] );
466 // is it a structural element (object) ...
467 if ( AnyConverter
.isObject(aChild
) && !AnyConverter
.isArray(aChild
) )
469 // then get an interface
470 XInterface xChildElement
= UnoRuntime
.queryInterface(XInterface
.class, aChild
);
472 // and continue processing child elements recursively
473 browseElementRecursively( xChildElement
, aProcessor
);
475 // ... or is it a simple value
478 // Build the path to it from the path of
479 // the element and the name of the child
482 xElementPath
.composeHierarchicalName(aElementNames
[i
]);
484 // and process the value
485 aProcessor
.processValueElement( sChildPath
, aChild
);
490 /** Method to browse the part rooted at sRootPath
491 of the configuration that the Provider provides.
493 All nodes will be processed by the IConfigurationProcessor passed.
495 public void browseConfiguration( String sRootPath
, IConfigurationProcessor aProcessor
)
496 throws com
.sun
.star
.uno
.Exception
498 // create the root element
499 XInterface xViewRoot
= (XInterface
)createConfigurationView( sRootPath
);
501 // now do the processing
502 browseElementRecursively( xViewRoot
, aProcessor
);
504 // we are done with the view - dispose it
505 // This assumes that the processor
506 // does not keep a reference to the elements in processStructuralElement
508 UnoRuntime
.queryInterface(XComponent
.class,xViewRoot
).dispose();
512 /** Method to browse the filter configuration.
514 Information about installed filters will be printed.
516 public void printRegisteredFilters()
517 throws com
.sun
.star
.uno
.Exception
519 final String sFilterKey
= "/org.openoffice.TypeDetection.Filter/Filters";
521 // browse the configuration, dumping filter information
522 browseConfiguration( sFilterKey
,
523 new IConfigurationProcessor () {
524 /// prints Path and Value of properties
525 public void processValueElement( String sPath_
, Object aValue_
) {
526 if (AnyConverter
.isArray(aValue_
))
528 final Object
[] aArray
= (Object
[])aValue_
;
530 System
.out
.print("\tValue: " + sPath_
+ " = { ");
531 for (int i
=0; i
<aArray
.length
; ++i
)
533 if (i
!= 0) System
.out
.print(", ");
534 System
.out
.print(aArray
[i
]);
536 System
.out
.println(" }");
539 System
.out
.println("\tValue: " + sPath_
+ " = " + aValue_
);
542 /// prints the Filter entries
543 public void processStructuralElement( String sPath_
, XInterface xElement_
) {
544 // get template information, to detect instances of the 'Filter' template
545 XTemplateInstance xInstance
=
546 UnoRuntime
.queryInterface( XTemplateInstance
.class,xElement_
);
548 // only select the Filter entries
549 if (xInstance
!= null && xInstance
.getTemplateName().endsWith("Filter")) {
550 XNamed xNamed
= UnoRuntime
.queryInterface(XNamed
.class,xElement_
);
551 System
.out
.println("Filter " + xNamed
.getName() + " (" + sPath_
+ ")");
557 // GROUP UPDATE example
559 /** This method simulates editing configuration data using a GridEditor dialog class
561 public void editGridOptions( )
562 throws com
.sun
.star
.uno
.Exception
564 // The path to the root element
565 final String cGridOptionsPath
= "/org.openoffice.Office.Calc/Grid";
568 Object xViewRoot
= createUpdatableView( cGridOptionsPath
);
571 GridOptionsEditor dialog
= new GridOptionsEditor();
573 // set up the initial values and register listeners
574 // get a data access interface, to supply the view with a model
575 XMultiHierarchicalPropertySet xProperties
=
576 UnoRuntime
.queryInterface(XMultiHierarchicalPropertySet
.class, xViewRoot
);
578 dialog
.setModel( xProperties
);
580 // get a listener object (probably an adapter) that notifies
581 // the dialog of external changes to its model
582 XChangesListener xListener
= dialog
.createChangesListener( );
584 XChangesNotifier xNotifier
=
585 UnoRuntime
.queryInterface(XChangesNotifier
.class, xViewRoot
);
587 xNotifier
.addChangesListener( xListener
);
589 // trigger the listener
590 changeSomeData( cGridOptionsPath
+ "/Subdivision" );
592 if (dialog
.execute() == GridOptionsEditor
.SAVE_SETTINGS
)
594 // changes have been applied to the view here
595 XChangesBatch xUpdateControl
=
596 UnoRuntime
.queryInterface(XChangesBatch
.class,xViewRoot
);
600 xUpdateControl
.commitChanges();
604 dialog
.informUserOfError( e
);
608 // all changes have been handled - clean up and return
609 // listener is done now
610 xNotifier
.removeChangesListener( xListener
);
612 // we are done with the view - dispose it
613 UnoRuntime
.queryInterface(XComponent
.class, xViewRoot
).dispose();
616 /** A class that changes some grid options settings
618 The interface of this class is chose to resemble a possible UI dialog class
620 private class GridOptionsEditor
{
621 /// the data this editor edits
622 XMultiHierarchicalPropertySet mxModel
;
624 public static final int CANCELED
= 0;
625 public static final int SAVE_SETTINGS
= 1;
627 // sets a model and updates the display
628 public void setModel(XMultiHierarchicalPropertySet xModel
) {
633 // this method 'runs' the 'dialog'
634 public int execute() {
637 System
.out
.println("-- GridEditor executing --");
638 // simulate a user action changing some data
640 System
.out
.println("-- GridEditor done --");
641 return SAVE_SETTINGS
;
645 informUserOfError(e
);
650 /// this method is called to report an error during dialog execution to the zuser
651 public void informUserOfError(Exception e
) {
652 System
.err
.println("ERROR in GridEditor:");
656 /// this method is called to allow the dialog to get feedback about changes occurring elsewhere
657 public XChangesListener
createChangesListener() {
658 if (mxModel
== null) return null;
660 return (new XChangesListener () {
661 public void changesOccurred( ChangesEvent event
) {
662 System
.out
.println("GridEditor - Listener received changes event containing " +
663 event
.Changes
.length
+ " change(s).");
667 public void disposing(EventObject event
) {
668 System
.out
.println("GridEditor - Listener received disposed event: releasing model");
673 /// this method is called when data has changed to display the updated data
674 private void updateDisplay() {
676 System
.out
.println("Grid options editor: data=" + readModel());
678 System
.out
.println("Grid options editor: no model set");
681 // this method is used to read all relevant data from the model
682 private GridOptions
readModel()
686 String
[] aOptionNames
= new String
[5];
687 aOptionNames
[0] = "Option/VisibleGrid";
688 aOptionNames
[1] = "Subdivision/XAxis";
689 aOptionNames
[2] = "Subdivision/YAxis";
690 aOptionNames
[3] = "Resolution/XAxis/Metric";
691 aOptionNames
[4] = "Resolution/YAxis/Metric";
693 Object
[] aValues
= mxModel
.getHierarchicalPropertyValues(aOptionNames
);
695 GridOptions result
= new GridOptions();
696 result
.visible
= ((Boolean
)aValues
[0]).booleanValue();
697 result
.subdivision_x
= ((Integer
)aValues
[1]).intValue();
698 result
.subdivision_y
= ((Integer
)aValues
[2]).intValue();
699 result
.resolution_x
= ((Integer
)aValues
[3]).intValue();
700 result
.resolution_y
= ((Integer
)aValues
[4]).intValue();
706 informUserOfError(e
);
711 // this method executes an edit
712 private void toggleVisibility()
716 XHierarchicalPropertySet xHPS
=
717 UnoRuntime
.queryInterface(XHierarchicalPropertySet
.class, mxModel
);
719 final String sSetting
= "Option/VisibleGrid";
721 System
.out
.println("GridEditor: toggling Visibility");
723 Boolean bOldValue
= (Boolean
)xHPS
.getHierarchicalPropertyValue(sSetting
);
725 Boolean bNewValue
= Boolean
.valueOf( ! bOldValue
.booleanValue() );
727 xHPS
.setHierarchicalPropertyValue(sSetting
,bNewValue
);
731 informUserOfError(e
);
736 /** This method creates an extra updatable view to change some data
737 and trigger the listener of the GridEditor
739 void changeSomeData(String xKey
)
743 Object xOtherViewRoot
= createUpdatableView(xKey
);
745 XNameReplace aReplace
= UnoRuntime
.queryInterface(XNameReplace
.class, xOtherViewRoot
);
747 String aItemNames
[] = aReplace
.getElementNames();
748 for (int i
=0; i
< aItemNames
.length
; ++i
) {
749 Object aItem
= aReplace
.getByName( aItemNames
[i
] );
750 // replace integers by a 'complement' value
751 if ( AnyConverter
.isInt(aItem
) )
753 int nOld
= AnyConverter
.toInt(aItem
);
754 int nNew
= 9999 - nOld
;
756 System
.out
.println("Replacing integer value: " + aItemNames
[i
]);
757 aReplace
.replaceByName( aItemNames
[i
], Integer
.valueOf( nNew
) );
760 // and booleans by their negated value
761 else if ( AnyConverter
.isBoolean(aItem
) )
763 boolean bOld
= AnyConverter
.toBoolean(aItem
);
764 boolean bNew
= ! bOld
;
766 System
.out
.println("Replacing boolean value: " + aItemNames
[i
]);
767 aReplace
.replaceByName( aItemNames
[i
], Boolean
.valueOf( bNew
) );
771 // commit the changes
772 XChangesBatch xUpdateControl
=
773 UnoRuntime
.queryInterface(XChangesBatch
.class,xOtherViewRoot
);
775 xUpdateControl
.commitChanges();
777 // we are done with the view - dispose it
778 UnoRuntime
.queryInterface(XComponent
.class, xOtherViewRoot
).dispose();
782 System
.err
.println("Could not change some data in a different view. An exception occurred:");
787 // GROUP RESET EXAMPLE
788 /// This method resets the grid settings to their default values
789 protected void resetGridConfiguration()
790 throws com
.sun
.star
.uno
.Exception
792 // The path to the root element
793 final String cGridOptionsPath
= "/org.openoffice.Office.Calc/Grid";
796 Object xViewRoot
= createUpdatableView(cGridOptionsPath
);
798 // resetting a single nested value
799 XHierarchicalNameAccess xHierarchicalAccess
=
800 UnoRuntime
.queryInterface(XHierarchicalNameAccess
.class, xViewRoot
);
802 // get using absolute name
803 Object xOptions
= xHierarchicalAccess
.getByHierarchicalName(cGridOptionsPath
+ "/Option");
805 XPropertyState xOptionState
=
806 UnoRuntime
.queryInterface(XPropertyState
.class, xOptions
);
808 xOptionState
.setPropertyToDefault("VisibleGrid");
810 // resetting more deeply nested values
811 Object xResolutionX
= xHierarchicalAccess
.getByHierarchicalName("Resolution/XAxis");
812 Object xResolutionY
= xHierarchicalAccess
.getByHierarchicalName("Resolution/YAxis");
814 XPropertyState xResolutionStateX
=
815 UnoRuntime
.queryInterface(XPropertyState
.class, xResolutionX
);
816 XPropertyState xResolutionStateY
=
817 UnoRuntime
.queryInterface(XPropertyState
.class, xResolutionY
);
819 xResolutionStateX
.setPropertyToDefault("Metric");
820 xResolutionStateY
.setPropertyToDefault("Metric");
822 // resetting multiple sibling values
823 Object xSubdivision
= xHierarchicalAccess
.getByHierarchicalName("Subdivision");
825 XMultiPropertyStates xSubdivisionStates
=
826 UnoRuntime
.queryInterface(XMultiPropertyStates
.class, xSubdivision
);
828 xSubdivisionStates
.setAllPropertiesToDefault();
830 // commit the changes
831 XChangesBatch xUpdateControl
=
832 UnoRuntime
.queryInterface(XChangesBatch
.class,xViewRoot
);
834 xUpdateControl
.commitChanges();
836 // we are done with the view - dispose it
837 UnoRuntime
.queryInterface(XComponent
.class, xViewRoot
).dispose();
841 // SET UPDATE EXAMPLE
842 private static boolean SET_EXAMPLE_BROKEN_IN_THIS_RELEASE
= true;
844 /** This method stores a sample data source given some connection data.
846 ATTENTION: This example requires an older version of the
847 org.openoffice.Office.DataAccess schema.
848 It does not work with the current schema.
849 Because of this, the method currenty does nothing.
850 You can still use the techniques shown in the example code.
852 void storeSampleDataSource()
853 throws com
.sun
.star
.uno
.Exception
855 if (SET_EXAMPLE_BROKEN_IN_THIS_RELEASE
)
857 System
.out
.println("- DISABLED: (the existing example does not work with this version) -");
858 return; // this function does not work
861 String sSampleDataSourceName
= "SampleTextDatabase";
863 String sSampleDataSourceURL
= "sdbc:flat:$(userurl)/database/SampleTextDatabase";
865 com
.sun
.star
.beans
.NamedValue
[] aSettings
= new com
.sun
.star
.beans
.NamedValue
[2];
866 aSettings
[0] = new com
.sun
.star
.beans
.NamedValue("HeaderLine",Boolean
.TRUE
);
867 aSettings
[1] = new com
.sun
.star
.beans
.NamedValue("FieldDelimiter",";");
869 String
[] aTableFilter
= new String
[] { "table.txt", "othertable.txt" };
871 storeDataSource(sSampleDataSourceName
,sSampleDataSourceURL
,"",false,0,aSettings
,aTableFilter
);
874 /// This method stores a data source given some connection data
875 void storeDataSource(
876 String sDataSourceName
,
877 String sDataSourceURL
,
879 boolean bNeedsPassword
,
881 com
.sun
.star
.beans
.NamedValue
[] aDriverSettings
,
882 String
[] aTableFilter
884 throws com
.sun
.star
.uno
.Exception
886 // create the view and get the data source element
887 Object xDataSource
= createDataSourceDescription(getProvider(),sDataSourceName
);
890 XPropertySet xDataSourceProperties
=
891 UnoRuntime
.queryInterface(XPropertySet
.class, xDataSource
);
893 xDataSourceProperties
.setPropertyValue("URL", sDataSourceURL
);
894 xDataSourceProperties
.setPropertyValue("User", sUser
);
895 xDataSourceProperties
.setPropertyValue("IsPasswordRequired", Boolean
.valueOf( bNeedsPassword
) );
896 xDataSourceProperties
.setPropertyValue("LoginTimeout", Integer
.valueOf( nTimeout
) );
898 if ( aTableFilter
!= null )
899 xDataSourceProperties
.setPropertyValue("TableFilter", aTableFilter
);
901 // store the driver-specific settings
902 if (aDriverSettings
!= null)
904 Object xSettingsSet
= xDataSourceProperties
.getPropertyValue("DataSourceSettings");
905 storeSettings( xSettingsSet
, aDriverSettings
);
908 // save the data and dispose the view
909 // recover the view root
910 Object xViewRoot
= getViewRoot(xDataSource
);
912 // commit the changes
913 XChangesBatch xUpdateControl
=
914 UnoRuntime
.queryInterface(XChangesBatch
.class,xViewRoot
);
916 xUpdateControl
.commitChanges();
919 UnoRuntime
.queryInterface(XComponent
.class, xViewRoot
).dispose();
922 /** This method gets the DataSourceDescription for a data source.
923 It either gets the existing entry or creates a new instance.
925 Object
createDataSourceDescription(XMultiServiceFactory xProvider
, String sDataSourceName
)
926 throws com
.sun
.star
.uno
.Exception
928 // The service name: Need an update access:
929 final String cUpdatableView
= "com.sun.star.configuration.ConfigurationUpdateAccess";
931 // The path to the DataSources set node
932 final String cDataSourcesPath
= "/org.openoffice.Office.DataAccess/DataSources";
934 // creation arguments: nodepath
935 com
.sun
.star
.beans
.PropertyValue aPathArgument
= new com
.sun
.star
.beans
.PropertyValue();
936 aPathArgument
.Name
= "nodepath";
937 aPathArgument
.Value
= cDataSourcesPath
;
939 Object
[] aArguments
= new Object
[1];
940 aArguments
[0] = aPathArgument
;
944 xProvider
.createInstanceWithArguments(cUpdatableView
, aArguments
);
946 XNameAccess xSetOfDataSources
=
947 UnoRuntime
.queryInterface(XNameAccess
.class,xViewRoot
);
949 Object xDataSourceDescriptor
= null; // the result
950 if ( xSetOfDataSources
.hasByName( sDataSourceName
))
952 // the element is there
955 // the view should point to the element directly, so we need to extend the path
956 XHierarchicalName xComposePath
= UnoRuntime
.queryInterface(XHierarchicalName
.class, xSetOfDataSources
);
958 String sElementPath
= xComposePath
.composeHierarchicalName( sDataSourceName
);
960 // use the name of the element now
961 aPathArgument
.Value
= sElementPath
;
963 // create another view now
964 Object
[] aDeepArguments
= new Object
[1];
965 aDeepArguments
[0] = aPathArgument
;
968 xDataSourceDescriptor
=
969 xProvider
.createInstanceWithArguments(cUpdatableView
, aDeepArguments
);
971 if ( xDataSourceDescriptor
!= null) // all went fine
973 // dispose the other view
974 UnoRuntime
.queryInterface(XComponent
.class, xViewRoot
).dispose();
980 // something went wrong, we retry with a new element
981 System
.err
.println("WARNING: An exception occurred while creating a view for an existing data source: " + e
);
982 xDataSourceDescriptor
= null;
986 // do we have a result element yet ?
987 if ( xDataSourceDescriptor
== null)
990 XNameContainer xSetUpdate
=
991 UnoRuntime
.queryInterface(XNameContainer
.class, xViewRoot
);
993 // create a new detached set element (instance of DataSourceDescription)
994 XSingleServiceFactory xElementFactory
=
995 UnoRuntime
.queryInterface(XSingleServiceFactory
.class, xSetUpdate
);
997 // the new element is the result !
998 xDataSourceDescriptor
= xElementFactory
.createInstance();
1000 // insert it - this also names the element
1001 xSetUpdate
.insertByName( sDataSourceName
, xDataSourceDescriptor
);
1004 return xDataSourceDescriptor
;
1007 /// this method stores a number of settings in a set node containing DataSourceSetting objects
1008 void storeSettings(Object xSettingsSet
, com
.sun
.star
.beans
.NamedValue
[] aSettings
)
1009 throws com
.sun
.star
.uno
.Exception
1011 if (aSettings
== null)
1014 // get the settings set as a container
1015 XNameContainer xSettingsContainer
=
1016 UnoRuntime
.queryInterface( XNameContainer
.class, xSettingsSet
);
1018 // and get a factory interface for creating the entries
1019 XSingleServiceFactory xSettingsFactory
=
1020 UnoRuntime
.queryInterface(XSingleServiceFactory
.class, xSettingsSet
);
1022 // now insert the individual settings
1023 for (int i
= 0; i
< aSettings
.length
; ++i
) {
1024 // create a DataSourceSetting object
1025 XPropertySet xSetting
= UnoRuntime
.queryInterface( XPropertySet
.class, xSettingsFactory
.createInstance() );
1027 // can set the value before inserting
1028 xSetting
.setPropertyValue( "Value", aSettings
[i
].Value
);
1030 // and now insert or replace as appropriate
1031 if (xSettingsContainer
.hasByName( aSettings
[i
].Name
))
1032 xSettingsContainer
.replaceByName( aSettings
[i
].Name
, xSetting
);
1034 xSettingsContainer
.insertByName( aSettings
[i
].Name
, xSetting
);
1040 /// This method get the view root node given an interface to any node in the view
1041 public static Object
getViewRoot(Object xElement
)
1043 Object xResult
= xElement
;
1045 // set the result to its parent until that would be null
1049 XChild xParentAccess
=
1050 UnoRuntime
.queryInterface(XChild
.class,xResult
);
1052 if (xParentAccess
!= null)
1053 xParent
= xParentAccess
.getParent();
1057 if (xParent
!= null)
1060 while (xParent
!= null);
1065 // workaround methods for unimplemented functionality
1067 /// WORKAROUND: does the same as xNamedItem.setName(sNewName) should do
1068 void renameSetItem(XNamed xNamedItem
, String sNewName
)
1069 throws com
.sun
.star
.uno
.Exception
1071 XChild xChildItem
= UnoRuntime
.queryInterface(XChild
.class, xNamedItem
);
1073 XNameContainer xParentSet
= UnoRuntime
.queryInterface( XNameContainer
.class, xChildItem
.getParent() );
1075 String sOldName
= xNamedItem
.getName();
1077 // now rename the item
1078 xParentSet
.removeByName(sOldName
);
1079 xParentSet
.insertByName(sNewName
,xNamedItem
);
1082 /// WORKAROUND: does the same as xChildItem.setParent( xNewParent ) should do
1083 void moveSetItem(XChild xChildItem
, XNameContainer xNewParent
)
1084 throws com
.sun
.star
.uno
.Exception
1086 XNamed xNamedItem
= UnoRuntime
.queryInterface(XNamed
.class, xChildItem
);
1088 XNameContainer xOldParent
= UnoRuntime
.queryInterface( XNameContainer
.class, xChildItem
.getParent() );
1090 String sItemName
= xNamedItem
.getName();
1092 // now rename the item
1093 xOldParent
.removeByName(sItemName
);
1094 xNewParent
.insertByName(sItemName
,xChildItem
);
1098 // ------- the end -----------