xref: /AOO41X/main/odk/examples/DevelopersGuide/Database/sdbcx.java (revision cdf0e10c4e3984b49a9502b011690b615761d4a3)
1 /*************************************************************************
2  *
3  *  The Contents of this file are made available subject to the terms of
4  *  the BSD license.
5  *
6  *  Copyright 2000, 2010 Oracle and/or its affiliates.
7  *  All rights reserved.
8  *
9  *  Redistribution and use in source and binary forms, with or without
10  *  modification, are permitted provided that the following conditions
11  *  are met:
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.
20  *
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.
32  *
33  *************************************************************************/
34 
35 import java.io.*;
36 
37 import com.sun.star.lang.XComponent;
38 import com.sun.star.uno.*;
39 import com.sun.star.bridge.XUnoUrlResolver;
40 import com.sun.star.beans.XPropertySet;
41 import com.sun.star.container.XNameAccess;
42 import com.sun.star.container.XIndexAccess;
43 import com.sun.star.sdbc.*;
44 import com.sun.star.sdbcx.*;
45 import com.sun.star.lang.XMultiServiceFactory;
46 
47 public class sdbcx
48 {
49 	private XMultiServiceFactory xORB;
50 	private static XConnection con;
51 	private XTablesSupplier xTabSup;
52 
53         public static XMultiServiceFactory rSmgr;
54 	public static void main(String argv[]) throws java.lang.Exception
55 	{
56 		try{
57 			rSmgr = connect("socket,host=localhost,port=8100");
58                         sdbcx test = new sdbcx(rSmgr);
59                         test.createConnection();
60                         test.displayTableProperties();
61                         // now we dispose the connection to close it
62                         XComponent xComponent = (XComponent)UnoRuntime.queryInterface(XComponent.class,con);
63                         if(xComponent != null)
64                         {
65                                 xComponent.dispose();
66                                 System.out.println("Connection disposed!");
67                         }
68                 }
69 		catch(com.sun.star.uno.Exception e)
70 		{
71 			System.out.println(e);
72 			e.printStackTrace();
73 		}
74 		System.exit(0);
75         }
76         public static XMultiServiceFactory connect( String connectStr )
77 		throws com.sun.star.uno.Exception,
78 		com.sun.star.uno.RuntimeException, java.lang.Exception
79 	{
80 		// initial serviceManager
81 		XMultiServiceFactory xLocalServiceManager =
82 			com.sun.star.comp.helper.Bootstrap.createSimpleServiceManager();
83 
84 		// create a connector, so that it can contact the office
85 		Object  xUrlResolver  = xLocalServiceManager.createInstance( "com.sun.star.bridge.UnoUrlResolver" );
86 		XUnoUrlResolver urlResolver = (XUnoUrlResolver)UnoRuntime.queryInterface(
87             XUnoUrlResolver.class, xUrlResolver );
88 
89 		Object rInitialObject = urlResolver.resolve( "uno:" + connectStr + ";urp;StarOffice.NamingService" );
90 
91 		XNamingService rName = (XNamingService)UnoRuntime.queryInterface(
92             XNamingService.class, rInitialObject );
93 
94 		XMultiServiceFactory xMSF = null;
95 		if( rName != null ) {
96 			System.err.println( "got the remote naming service !" );
97 			Object rXsmgr = rName.getRegisteredObject("StarOffice.ServiceManager" );
98 
99 			xMSF = (XMultiServiceFactory)
100 				UnoRuntime.queryInterface( XMultiServiceFactory.class, rXsmgr );
101 		}
102 
103 		return ( xMSF );
104 	}
105 
106 
107 	public sdbcx(XMultiServiceFactory rSmgr )
108 	{
109 		xORB = rSmgr;
110 	}
111 
112 	public void createConnection() throws com.sun.star.uno.Exception
113 	{
114 		// create the Driver with the implementation name
115 		Object aDriver = xORB.createInstance("com.sun.star.comp.sdbcx.adabas.ODriver");
116 		// query for the interface
117 		com.sun.star.sdbc.XDriver xDriver;
118 		xDriver = (XDriver)UnoRuntime.queryInterface(XDriver.class,aDriver);
119 		if(xDriver != null)
120 		{
121 			// first create the needed url
122 			String adabasURL = "sdbc:adabas::MYDB0";
123 			// second create the necessary properties
124 			com.sun.star.beans.PropertyValue [] adabasProps = new com.sun.star.beans.PropertyValue[]
125 			{
126 				new com.sun.star.beans.PropertyValue("user",0,"test1",com.sun.star.beans.PropertyState.DIRECT_VALUE),
127 				new com.sun.star.beans.PropertyValue("password",0,"test1",com.sun.star.beans.PropertyState.DIRECT_VALUE)
128 			};
129 			//
130 
131 			// now create a connection to adabas
132 			con = xDriver.connect(adabasURL,adabasProps);
133 			if(con != null)
134 			{
135 				System.out.println("Connection could be created!");
136 				// we the XDatabaseDefinitionSupplier interface from the driver to get the XTablesSupplier
137 				XDataDefinitionSupplier xDDSup = (XDataDefinitionSupplier)UnoRuntime.queryInterface(
138 						XDataDefinitionSupplier.class,xDriver);
139 				if(xDDSup != null)
140 				{
141 					xTabSup = xDDSup.getDataDefinitionByConnection(con);
142 					if(xTabSup != null)
143 					{
144 						XNameAccess xTables = xTabSup.getTables();
145 						// now print all table names
146 						System.out.println("Tables available:");
147 						String [] aTableNames = xTables.getElementNames();
148 						for ( int i =0; i<= aTableNames.length-1; i++)
149 							System.out.println(aTableNames[i]);
150 					}
151 				}
152 				else
153 					System.out.println("The driver is not a SDBCX capable!");
154 			}
155 			else
156 				System.out.println("Connection could not be created!");
157 		}
158 	}
159 
160 	public void displayTableProperties() throws com.sun.star.uno.Exception
161 	{
162 		XNameAccess xTables = xTabSup.getTables();
163 		String [] aTableNames = xTables.getElementNames();
164 		if(0 != aTableNames.length)
165 		{
166 			Object table = xTables.getByName(aTableNames[0]);
167 			XPropertySet xProp = (XPropertySet)UnoRuntime.queryInterface(XPropertySet.class,table);
168 			System.out.println("Name:          " + xProp.getPropertyValue("Name"));
169 			System.out.println("CatalogName:   " + xProp.getPropertyValue("CatalogName"));
170 			System.out.println("SchemaName:    " + xProp.getPropertyValue("SchemaName"));
171 			System.out.println("Description:   " + xProp.getPropertyValue("Description"));
172 			// the following property is optional so we first must check if it exists
173 			if(xProp.getPropertySetInfo().hasPropertyByName("Type"))
174 				System.out.println("Type:          " + xProp.getPropertyValue("Type"));
175 		}
176 	}
177 
178 	//###########################################################
179 	// 15. example
180 	// print all columns of a XColumnsSupplier
181 	//###########################################################
182 	public static void printColumns(XColumnsSupplier xColumnsSup) throws com.sun.star.uno.Exception,SQLException
183 	{
184 		System.out.println("Example printColumns");
185 		// the table must be at least support a XColumnsSupplier interface
186 		System.out.println("--- Columns ---");
187 		XNameAccess xColumns = xColumnsSup.getColumns();
188 		String [] aColumnNames = xColumns.getElementNames();
189 		for ( int i =0; i<= aColumnNames.length-1; i++)
190 			System.out.println("    " + aColumnNames[i]);
191 	}
192 	//###########################################################
193 	// 16. example
194 	// print all keys inclusive the columns of a key
195 	//###########################################################
196 	public static void printKeys(XColumnsSupplier xColumnsSup) throws com.sun.star.uno.Exception,SQLException
197 	{
198 		System.out.println("Example printKeys");
199 		XKeysSupplier xKeysSup = (XKeysSupplier)UnoRuntime.queryInterface(XKeysSupplier.class,xColumnsSup);
200 		if(xKeysSup != null)
201 		{
202 			System.out.println("--- Keys ---");
203 			XIndexAccess xKeys = xKeysSup.getKeys();
204 			for ( int i =0; i < xKeys.getCount(); i++)
205 			{
206 				Object key = xKeys.getByIndex(i);
207 				XPropertySet xProp = (XPropertySet)UnoRuntime.queryInterface(XPropertySet.class,key);
208 				System.out.println("    " + xProp.getPropertyValue("Name"));
209 				XColumnsSupplier xKeyColumnsSup = ( XColumnsSupplier ) UnoRuntime.queryInterface(XColumnsSupplier.class,xProp);
210 				printColumns(xKeyColumnsSup);
211 			}
212 		}
213 	}
214 	//###########################################################
215 	// 17. example
216 	// print all keys inclusive the columns of a key
217 	//###########################################################
218 	public static void printIndexes(XColumnsSupplier xColumnsSup) throws com.sun.star.uno.Exception,SQLException
219 	{
220 		System.out.println("Example printIndexes");
221 		XIndexesSupplier xIndexesSup = (XIndexesSupplier)UnoRuntime.queryInterface(XIndexesSupplier.class,xColumnsSup);
222 		if(xIndexesSup != null)
223 		{
224 			System.out.println("--- Indexes ---");
225 			XNameAccess xIndexs = xIndexesSup.getIndexes();
226 			String [] aIndexNames = xIndexs.getElementNames();
227 			for ( int i =0; i<= aIndexNames.length-1; i++)
228 			{
229 				System.out.println("    " + aIndexNames[i]);
230 				Object index = xIndexs.getByName(aIndexNames[i]);
231 				XColumnsSupplier xIndexColumnsSup = (XColumnsSupplier)UnoRuntime.queryInterface(XColumnsSupplier.class,index);
232 				printColumns(xIndexColumnsSup);
233 			}
234 		}
235 	}
236 
237 	//###########################################################
238 	// 18. example
239 	// column properties
240 	//###########################################################
241     public static void printColumnProperties(Object column) throws com.sun.star.uno.Exception,SQLException
242 	{
243 		System.out.println("Example printColumnProperties");
244 		XPropertySet xProp = (XPropertySet)UnoRuntime.queryInterface(XPropertySet.class,column);
245 		System.out.println("Name:            " + xProp.getPropertyValue("Name"));
246 		System.out.println("Type:            " + xProp.getPropertyValue("Type"));
247 		System.out.println("TypeName:        " + xProp.getPropertyValue("TypeName"));
248 		System.out.println("Precision:       " + xProp.getPropertyValue("Precision"));
249 		System.out.println("Scale:           " + xProp.getPropertyValue("Scale"));
250 		System.out.println("IsNullable:      " + xProp.getPropertyValue("IsNullable"));
251 		System.out.println("IsAutoIncrement: " + xProp.getPropertyValue("IsAutoIncrement"));
252 		System.out.println("IsCurrency:      " + xProp.getPropertyValue("IsCurrency"));
253 		// the following property is optional so we first must check if it exists
254 		if(xProp.getPropertySetInfo().hasPropertyByName("IsRowVersion"))
255 			System.out.println("IsRowVersion:    " + xProp.getPropertyValue("IsRowVersion"));
256 		if(xProp.getPropertySetInfo().hasPropertyByName("Description"))
257 			System.out.println("Description:     " + xProp.getPropertyValue("Description"));
258 		if(xProp.getPropertySetInfo().hasPropertyByName("DefaultValue"))
259 			System.out.println("DefaultValue:    " + xProp.getPropertyValue("DefaultValue"));
260 	}
261 
262 	//###########################################################
263 	// 19. example
264 	// index properties
265 	//###########################################################
266 	public static void printIndexProperties(Object index) throws com.sun.star.uno.Exception,SQLException
267 	{
268 		System.out.println("Example printIndexProperties");
269 		XPropertySet xProp = (XPropertySet)UnoRuntime.queryInterface(XPropertySet.class,index);
270 		System.out.println("Name:              " + xProp.getPropertyValue("Name"));
271 		System.out.println("Catalog:           " + xProp.getPropertyValue("Catalog"));
272 		System.out.println("IsUnique:          " + xProp.getPropertyValue("IsUnique"));
273 		System.out.println("IsPrimaryKeyIndex: " + xProp.getPropertyValue("IsPrimaryKeyIndex"));
274 		System.out.println("IsClustered:       " + xProp.getPropertyValue("IsClustered"));
275 	}
276 
277 	//###########################################################
278 	// 20. example
279 	// key properties
280 	//###########################################################
281 	public static void printKeyProperties(Object key) throws com.sun.star.uno.Exception,SQLException
282 	{
283 		System.out.println("Example printKeyProperties");
284 		XPropertySet xProp = (XPropertySet)UnoRuntime.queryInterface(XPropertySet.class,key);
285 		System.out.println("Name:            " + xProp.getPropertyValue("Name"));
286 		System.out.println("Type:            " + xProp.getPropertyValue("Type"));
287 		System.out.println("ReferencedTable: " + xProp.getPropertyValue("ReferencedTable"));
288 		System.out.println("UpdateRule:      " + xProp.getPropertyValue("UpdateRule"));
289 		System.out.println("DeleteRule:      " + xProp.getPropertyValue("DeleteRule"));
290 	}
291 
292 	//###########################################################
293 	// 21. example
294 	// print all groups and the users with their privileges who belong to this group
295 	//###########################################################
296 	public static void printGroups(XTablesSupplier xTabSup) throws com.sun.star.uno.Exception,SQLException
297 	{
298 		System.out.println("Example printGroups");
299 		XGroupsSupplier xGroupsSup = (XGroupsSupplier)UnoRuntime.queryInterface(XGroupsSupplier.class,xTabSup);
300 		if(xGroupsSup != null)
301 		{
302 			// the table must be at least support a XColumnsSupplier interface
303 			System.out.println("--- Groups ---");
304 			XNameAccess xGroups = xGroupsSup.getGroups();
305 			String [] aGroupNames = xGroups.getElementNames();
306 			for ( int i =0; i < aGroupNames.length; i++)
307 			{
308 				System.out.println("    " + aGroupNames[i]);
309 				XUsersSupplier xUsersSup = (XUsersSupplier)UnoRuntime.queryInterface(XUsersSupplier.class,xGroups.getByName(aGroupNames[i]));
310 				if(xUsersSup != null)
311 				{
312 					XAuthorizable xAuth = (XAuthorizable)UnoRuntime.queryInterface(XAuthorizable.class,xUsersSup);
313 					// the table must be at least support a XColumnsSupplier interface
314 					System.out.println("\t--- Users ---");
315 					XNameAccess xUsers = xUsersSup.getUsers();
316 					String [] aUserNames = xUsers.getElementNames();
317 					for ( int j =0; j < aUserNames.length; j++)
318 					{
319 						System.out.println("\t    " + aUserNames[j] + " Privileges: " + xAuth.getPrivileges(aUserNames[j],PrivilegeObject.TABLE));
320 					}
321 				}
322 			}
323 		}
324 	}
325 
326 	//###########################################################
327 	// 22. example
328 	// create the table salesmen
329 	//###########################################################
330 	public static void createTableSalesMen(XNameAccess xTables) throws com.sun.star.uno.Exception,SQLException
331 	{
332 		System.out.println("Example createTableSalesMen");
333 		XDataDescriptorFactory xTabFac = (XDataDescriptorFactory)UnoRuntime.queryInterface(XDataDescriptorFactory.class,xTables);
334 		if(xTabFac != null)
335 		{
336 			// create the new table
337 			XPropertySet xTable = xTabFac.createDataDescriptor();
338 			// set the name of the new table
339 			xTable.setPropertyValue("Name","SALESMAN");
340 			// append the columns
341 			XColumnsSupplier xColumSup = (XColumnsSupplier)UnoRuntime.queryInterface(XColumnsSupplier.class,xTable);
342 			XDataDescriptorFactory xColFac = (XDataDescriptorFactory)UnoRuntime.queryInterface(XDataDescriptorFactory.class,xColumSup.getColumns());
343 			XAppend xAppend = (XAppend)UnoRuntime.queryInterface(XAppend.class,xColFac);
344 			// we only need one descriptor
345 			XPropertySet xCol = xColFac.createDataDescriptor();
346 			// create first column and append
347 			xCol.setPropertyValue("Name","SNR");
348 			xCol.setPropertyValue("Type",new Integer(DataType.INTEGER));
349 			xCol.setPropertyValue("IsNullable",new Integer(ColumnValue.NO_NULLS));
350 			xAppend.appendByDescriptor(xCol);
351 			// 2nd only set the properties which differs
352 			xCol.setPropertyValue("Name","FIRSTNAME");
353 			xCol.setPropertyValue("Type",new Integer(DataType.VARCHAR));
354 			xCol.setPropertyValue("IsNullable",new Integer(ColumnValue.NULLABLE));
355 			xCol.setPropertyValue("Precision",new Integer(50));
356 			xAppend.appendByDescriptor(xCol);
357 			// 3nd only set the properties which differs
358 			xCol.setPropertyValue("Name","LASTNAME");
359 			xCol.setPropertyValue("Precision",new Integer(100));
360 			xAppend.appendByDescriptor(xCol);
361 			// 4nd only set the properties which differs
362 			xCol.setPropertyValue("Name","STREET");
363 			xCol.setPropertyValue("Precision",new Integer(50));
364 			xAppend.appendByDescriptor(xCol);
365 			// 5nd only set the properties which differs
366 			xCol.setPropertyValue("Name","STATE");
367 			xAppend.appendByDescriptor(xCol);
368 			// 6nd only set the properties which differs
369 			xCol.setPropertyValue("Name","ZIP");
370 			xCol.setPropertyValue("Type",new Integer(DataType.INTEGER));
371 			xCol.setPropertyValue("Precision",new Integer(10)); // default value integer
372 			xAppend.appendByDescriptor(xCol);
373 			// 7nd only set the properties which differs
374 			xCol.setPropertyValue("Name","BIRTHDATE");
375 			xCol.setPropertyValue("Type",new Integer(DataType.DATE));
376 			xCol.setPropertyValue("Precision",new Integer(10)); // default value integer
377 			xAppend.appendByDescriptor(xCol);
378 			// now we create the primary key
379 			XKeysSupplier xKeySup = (XKeysSupplier)UnoRuntime.queryInterface(XKeysSupplier.class,xTable);
380 			XDataDescriptorFactory xKeyFac = (XDataDescriptorFactory)UnoRuntime.queryInterface(XDataDescriptorFactory.class,xKeySup.getKeys());
381 			XAppend xKeyAppend = (XAppend)UnoRuntime.queryInterface(XAppend.class,xKeyFac);
382 			XPropertySet xKey = xKeyFac.createDataDescriptor();
383 			xKey.setPropertyValue("Type",new Integer(KeyType.PRIMARY));
384 			// now append the columns to key
385 			XColumnsSupplier xKeyColumSup = (XColumnsSupplier)UnoRuntime.queryInterface(XColumnsSupplier.class,xKey);
386 			XDataDescriptorFactory xKeyColFac = (XDataDescriptorFactory)UnoRuntime.queryInterface(XDataDescriptorFactory.class,xKeyColumSup.getColumns());
387 			XAppend xKeyColAppend = (XAppend)UnoRuntime.queryInterface(XAppend.class,xKeyColFac);
388 			// we only need one descriptor
389 			XPropertySet xKeyCol = xKeyColFac.createDataDescriptor();
390 			xKeyCol.setPropertyValue("Name","SNR");
391 			// append the key column
392 			xKeyColAppend.appendByDescriptor(xKeyCol);
393 			// apend the key
394 			xKeyAppend.appendByDescriptor(xKey);
395 			// the last step is to append the new table to the tables collection
396 			 XAppend xTableAppend = (XAppend)UnoRuntime.queryInterface(XAppend.class,xTabFac);
397 			 xTableAppend.appendByDescriptor(xTable);
398 		}
399 	}
400 
401 	//###########################################################
402 	// 23. example
403 	// create a user
404 	//###########################################################
405 	public static void createUser(XNameAccess xUsers) throws com.sun.star.uno.Exception,SQLException
406 	{
407 		System.out.println("Example createUser");
408 		XDataDescriptorFactory xUserFac = (XDataDescriptorFactory)UnoRuntime.queryInterface(XDataDescriptorFactory.class,xUsers);
409 		if(xUserFac != null)
410 		{
411 			// create the new table
412 			XPropertySet xUser = xUserFac.createDataDescriptor();
413 			// set the name of the new table
414 			xUser.setPropertyValue("Name","BOSS");
415 			xUser.setPropertyValue("Password","BOSSWIFENAME");
416 			XAppend xAppend = (XAppend)UnoRuntime.queryInterface(XAppend.class,xUserFac);
417 			xAppend.appendByDescriptor(xUser);
418 		}
419 	}
420 }
421