1 /*
2  * ************************************************************************
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * Copyright 2000, 2010 Oracle and/or its affiliates.
7  *
8  * OpenOffice.org - a multi-platform office productivity suite
9  *
10  * This file is part of OpenOffice.org.
11  *
12  * OpenOffice.org is free software: you can redistribute it and/or modify
13  * it under the terms of the GNU Lesser General Public License version 3
14  * only, as published by the Free Software Foundation.
15  *
16  * OpenOffice.org is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU Lesser General Public License version 3 for more details
20  * (a copy is included in the LICENSE file that accompanied this code).
21  *
22  * You should have received a copy of the GNU Lesser General Public License
23  * version 3 along with OpenOffice.org.  If not, see
24  * <http://www.openoffice.org/license.html>
25  * for a copy of the LGPLv3 License.
26  *
27  * ***********************************************************************
28  */
29 
30 package graphical;
31 
32 import com.sun.star.beans.PropertyValue;
33 import com.sun.star.beans.XPropertySet;
34 import com.sun.star.container.XNameAccess;
35 import com.sun.star.frame.FrameSearchFlag;
36 import com.sun.star.frame.XComponentLoader;
37 import com.sun.star.frame.XDesktop;
38 import com.sun.star.frame.XModel;
39 import com.sun.star.frame.XStorable;
40 import com.sun.star.lang.XComponent;
41 import com.sun.star.lang.XMultiServiceFactory;
42 import com.sun.star.lang.XServiceInfo;
43 import com.sun.star.sdb.XOfficeDatabaseDocument;
44 import com.sun.star.sdb.XReportDocumentsSupplier;
45 import com.sun.star.sdb.application.XDatabaseDocumentUI;
46 import com.sun.star.uno.UnoRuntime;
47 import com.sun.star.uno.XInterface;
48 import com.sun.star.util.XCloseable;
49 import complexlib.Assurance;
50 // import complexlib.ComplexTestCase.AssureException;
51 import helper.OfficeProvider;
52 import helper.PropertyHelper;
53 import helper.URLHelper;
54 import java.io.File;
55 import java.util.ArrayList;
56 
57 /**
58  *
59  * @author ll93751
60  */
61 
62 class PropertySetHelper
63 {
64     XPropertySet m_xPropertySet;
65     public PropertySetHelper(Object _aObj)
66         {
67             m_xPropertySet = UnoRuntime.queryInterface(XPropertySet.class, _aObj);
68         }
69 
70     /**
71        get a property and don't convert it
72        @param _sName the string name of the property
73        @return the object value of the property without any conversion
74     */
75     public Object getPropertyValueAsObject(String _sName)
76         {
77             Object aObject = null;
78 
79             if (m_xPropertySet != null)
80             {
81                 try
82                 {
83                     aObject = m_xPropertySet.getPropertyValue(_sName);
84                 }
85                 catch (com.sun.star.beans.UnknownPropertyException e)
86                 {
87                     System.out.println("ERROR: UnknownPropertyException caught. '" + _sName + "'");
88                     System.out.println("Message: " + e.getMessage());
89                 }
90                 catch (com.sun.star.lang.WrappedTargetException e)
91                 {
92                     System.out.println("ERROR: WrappedTargetException caught.");
93                     System.out.println("Message: " + e.getMessage());
94                 }
95             }
96             return aObject;
97         }
98 }
99 
100 public class OpenOfficeDatabaseReportExtractor extends Assurance
101 {
102     private ParameterHelper m_aParameterHelper;
103 
104     public OpenOfficeDatabaseReportExtractor(ParameterHelper _aParameter)
105     {
106         m_aParameterHelper = _aParameter;
107     }
108 
109     private XDesktop m_xDesktop = null;
110     private XDesktop getXDesktop()
111         {
112 
113             if (m_xDesktop == null)
114             {
115                 try
116                 {
117                     XInterface xInterface = (XInterface) getMultiServiceFactory().createInstance( "com.sun.star.frame.Desktop" );
118                     m_xDesktop =  UnoRuntime.queryInterface(XDesktop.class, xInterface);
119                 }
120                 catch (com.sun.star.uno.Exception e)
121                 {
122                     GlobalLogWriter.println("ERROR: uno.Exception caught");
123                     GlobalLogWriter.println("Message: " + e.getMessage());
124                 }
125             }
126             return m_xDesktop;
127         }
128 
129     private void showElements(XNameAccess _xNameAccess)
130         {
131             if (_xNameAccess != null)
132             {
133                 String[] sElementNames = _xNameAccess.getElementNames();
134                 for(int i=0;i<sElementNames.length; i++)
135                 {
136                     System.out.println("Value: [" + i + "] := " + sElementNames[i]);
137                 }
138             }
139             else
140             {
141                 System.out.println("Warning: Given object is null.");
142             }
143         }
144 
145 
146     private OfficeProvider m_aProvider = null;
147     private XMultiServiceFactory m_xMultiServiceFactory = null;
148     private XMultiServiceFactory getMultiServiceFactory()
149     {
150         if (m_xMultiServiceFactory == null)
151         {
152             m_xMultiServiceFactory = m_aParameterHelper.getMultiServiceFactory();
153         }
154         return m_xMultiServiceFactory;
155     }
156 //    private void startOffice()
157 //        {
158 //            // int tempTime = m_aParameterHelper.getTestParameters().getInt("SingleTimeOut");
159 //            param.put("TimeOut", new Integer(300000));
160 //            System.out.println("TimeOut: " + param.getInt("TimeOut"));
161 //            System.out.println("ThreadTimeOut: " + param.getInt("ThreadTimeOut"));
162 //
163 //            // OfficeProvider aProvider = null;
164 //            m_aProvider = new OfficeProvider();
165 //            m_xXMultiServiceFactory = (XMultiServiceFactory) m_aProvider.getManager(param);
166 //            param.put("ServiceFactory", m_xXMultiServiceFactory);
167 //        }
168 //
169 //    private void stopOffice()
170 //        {
171 //            if (m_aProvider != null)
172 //            {
173 //                m_aProvider.closeExistingOffice(param, true);
174 //                m_aProvider = null;
175 //            }
176 //            TimeHelper.waitInSeconds(2, "Give close Office some time.");
177 //        }
178 
179     private String m_sMailAddress = null;
180     private String m_sParentDistinct = null;
181 
182     // private String m_sUPDMinor;
183     // private String m_sCWS_WORK_STAMP;
184 
185     private static String m_sSourceVersion;
186     private static String m_sDestinationVersion;
187     private static String m_sSourceName;
188     private static String m_sDestinationName;
189 
190     private static final int WRITER = 1;
191     private static final int CALC = 2;
192 
193     /**
194      * This is the main test Function of current ReportDesignerTest
195      * @param _sDocument
196      * @return
197      */
198 
199     public ArrayList<String> load(String _sDocument /*, int _nType*/)
200         {
201             // We need to copy the database file to a place where we have write access, NEVER use the docpool for this
202             String sOutputPath = m_aParameterHelper.getOutputPath();
203             File aOutputPath = new File(sOutputPath);
204             aOutputPath.mkdirs();
205 
206             String sFilename = FileHelper.getBasename(_sDocument);
207             String sDestinationFile = FileHelper.appendPath(sOutputPath, sFilename);
208             FileHelper.copy(_sDocument, sDestinationFile);
209 
210             // now the fix reference of the AbsoluteReferenceFile should exist.
211             assure("There exists no file: " + sDestinationFile, FileHelper.exists(sDestinationFile));
212 
213             String sFileURL = URLHelper.getFileURLFromSystemPath(sDestinationFile);
214             GlobalLogWriter.println("File URL: " + sFileURL);
215 
216             ArrayList<PropertyValue> aPropertyList = new ArrayList<PropertyValue>();
217 
218             // FYI: it is not allowed to open the document read only
219 //            PropertyValue aReadOnly = new PropertyValue(); // always overwrite already exist files
220 //            aReadOnly.Name = "ReadOnly";
221 //            aReadOnly.Value = Boolean.TRUE;
222 //            aPropertyList.add(aReadOnly);
223 
224             XComponent xDocComponent = loadComponent(sFileURL, getXDesktop(), aPropertyList);
225 
226             GlobalLogWriter.println("Load done");
227 // 	context = createUnoService("com.sun.star.sdb.DatabaseContext")
228 //     oDataBase = context.getByName("hh")
229 //     oDBDoc = oDataBase.DatabaseDocument
230 //
231 // 	dim args(1) as new com.sun.star.beans.PropertyValue
232 // 	args(0).Name = "ActiveConnection"
233 // 	args(0).Value = oDBDoc.getCurrentController().getPropertyValue("ActiveConnection")
234 // 	reportContainer = oDBDoc.getReportDocuments()
235 //     report = reportContainer.loadComponentFromURL("Report40","",0,args)
236 
237             ArrayList<String> aList = null;
238             try
239             {
240 //                XInterface x = (XInterface)getMultiServiceFactory().createInstance("com.sun.star.sdb.DatabaseContext");
241 //                assure("can't create instance of com.sun.star.sdb.DatabaseContext", x != null);
242 //                GlobalLogWriter.println("createInstance com.sun.star.sdb.DatabaseContext done");
243 
244 //                XNameAccess xNameAccess = (XNameAccess) UnoRuntime.queryInterface(XNameAccess.class, x);
245 //                showElements(xNameAccess);
246 //                Object aObj = xNameAccess.getByName(sFileURL);
247 //                    GlobalLogWriter.println("1");
248 
249 //                PropertySetHelper aHelper = new PropertySetHelper(aObj);
250 //                XDocumentDataSource xDataSource = (XDocumentDataSource)UnoRuntime.queryInterface(XDocumentDataSource.class, aObj);
251 //                Object aDatabaseDocument = aHelper.getPropertyValueAsObject("DatabaseDocument");
252 //                XOfficeDatabaseDocument xOfficeDBDoc = xDataSource.getDatabaseDocument();
253 
254                 XOfficeDatabaseDocument xOfficeDBDoc = UnoRuntime.queryInterface(XOfficeDatabaseDocument.class, xDocComponent);
255 
256 //                XOfficeDatabaseDocument xOfficeDBDoc = (XOfficeDatabaseDocument)UnoRuntime.queryInterface(XOfficeDatabaseDocument.class, xDataSource);
257                 assure("can't access DatabaseDocument", xOfficeDBDoc != null);
258 //                GlobalLogWriter.println("2");
259 
260                 XModel xDBSource = UnoRuntime.queryInterface(XModel.class, xOfficeDBDoc);
261                 Object aController = xDBSource.getCurrentController();
262                 assure("Controller of xOfficeDatabaseDocument is empty!", aController != null);
263 //                GlobalLogWriter.println("3");
264 
265                 XDatabaseDocumentUI aDBDocUI = UnoRuntime.queryInterface(XDatabaseDocumentUI.class, aController);
266                 aDBDocUI.connect();
267                 boolean isConnect = aDBDocUI.isConnected();
268                 if (isConnect)
269                 {
270                     GlobalLogWriter.println("Connection is true");
271                 }
272                 else
273                 {
274                     GlobalLogWriter.println("Connection is false");
275                 }
276 
277                 // aHelper = new PropertySetHelper(aController);
278 
279                 XReportDocumentsSupplier xSupplier = UnoRuntime.queryInterface(XReportDocumentsSupplier.class, xOfficeDBDoc);
280                 XNameAccess xNameAccess = xSupplier.getReportDocuments();
281                 assure("xOfficeDatabaseDocument returns no Report Document", xNameAccess != null);
282 //                     GlobalLogWriter.println("5");
283 
284                 showElements(xNameAccess);
285 
286                 // Object aActiveConnectionObj = aHelper.getPropertyValueAsObject("ActiveConnection");
287                 Object aActiveConnectionObj = aDBDocUI.getActiveConnection();
288                 assure("ActiveConnection is empty", aActiveConnectionObj != null);
289 //                     GlobalLogWriter.println("5");
290 
291                 ArrayList<PropertyValue> aPropertyList2 = new ArrayList<PropertyValue>();
292 
293                 PropertyValue aActiveConnection = new PropertyValue();
294                 aActiveConnection.Name = "ActiveConnection";
295                 aActiveConnection.Value = aActiveConnectionObj;
296                 aPropertyList2.add(aActiveConnection);
297 
298                 aList = loadAndStoreReports(xNameAccess, aPropertyList2 /*, _nType*/ );
299                 createDBEntry(/*_nType*/);
300             }
301             catch(Exception/*com.sun.star.uno.Exception*/ e)
302             {
303                 GlobalLogWriter.println("ERROR: Exception caught");
304                 GlobalLogWriter.println("Message: " + e.getMessage());
305             }
306 
307             // String mTestDocumentPath = (String) param.get("TestDocumentPath");
308             // System.out.println("mTestDocumentPath: '" + mTestDocumentPath + "'");
309             // // workaround for issue using deprecated "DOCPTH" prop
310             // System.setProperty("DOCPTH", mTestDocumentPath);
311 
312             // Close the document
313             // util.utils.shortWait(2000);
314 
315             closeComponent(xDocComponent);
316             return aList;
317         }
318 
319     private String getDocumentPoolName(/*int _nType*/)
320         {
321             return "AutogenReportDesignTest";
322             // return getFileFormat(_nType);
323         }
324 
325 // -----------------------------------------------------------------------------
326     private void createDBEntry(/*int _nType*/)
327         {
328             // try to connect the database
329             String sDBConnection = (String)m_aParameterHelper.getTestParameters().get( convwatch.PropertyName.DB_CONNECTION_STRING );
330             if (sDBConnection != null && sDBConnection.length() > 0)
331             {
332                 GlobalLogWriter.println("DBConnection: " + sDBConnection);
333 // TODO: DB
334 //                DB.init(sDBConnection);
335 
336                 // String sFixRefSubDirectory = "ReportDesign_qa_complex_" + getFileFormat(_nType);
337                 String sFixRefSubDirectory = "ReportDesignFixRef";
338 
339                 String sSourceVersion = m_sSourceVersion;
340                 // String sSourceVersion = sFixRefSubDirectory;
341                 String sSourceName = m_sSourceName;
342                 // String sSourceCreatorType = "fixref";
343                 String sSourceCreatorType = "";
344                 String sDestinationVersion = m_sDestinationVersion;
345                 // if (sDestinationVersion.length() == 0)
346                 // {
347                 //     sDestinationVersion = m_sUPDMinor;
348                 // }
349                 String sDestinationName = m_sDestinationName;
350                 String sDestinationCreatorType = "";
351                 String sDocumentPoolDir = getOutputPath(/*_nType*/);
352                 String sDocumentPoolName = getDocumentPoolName(/*_nType*/);
353                 String sSpecial = "";
354 
355 // TODO: DB
356 //                DB.insertinto_documentcompare(sSourceVersion, sSourceName, sSourceCreatorType,
357 //                                              m_sDestinationVersion, sDestinationName, sDestinationCreatorType,
358 //                                              sDocumentPoolDir, sDocumentPoolName, m_sMailAddress,
359 //                                              sSpecial, m_sParentDistinct);
360                 TimeHelper.waitInSeconds(1, "wait for DB.");
361                 // DB.test();
362                 // System.exit(1);
363             }
364         }
365 
366     private ArrayList<String> loadAndStoreReports(XNameAccess _xNameAccess, ArrayList<PropertyValue> _aPropertyList /*, int _nType*/ )
367         {
368             ArrayList<String> aList = new ArrayList<String>();
369             if (_xNameAccess != null)
370             {
371                 String[] sElementNames = _xNameAccess.getElementNames();
372                 for(int i=0;i<sElementNames.length; i++)
373                 {
374                     String sReportName = sElementNames[i];
375                     XComponent xDoc = loadComponent(sReportName, _xNameAccess, _aPropertyList);
376                     if (xDoc != null)
377                     {
378                         // util.utils.shortWait(1000);
379                         // print? or store?
380                         String sDocumentPathName = storeComponent(sReportName, xDoc /*, _nType*/);
381                         aList.add(sDocumentPathName);
382     //                    util.utils.shortWait(1000);
383                         closeComponent(xDoc);
384     //                    util.utils.shortWait(1000);
385                     }
386                     else
387                     {
388                         System.out.println("Leave out maybe due to errors.");
389                     }
390                     // sBackPath contains the path where to find the extracted ODB Document
391                 }
392             }
393             return aList;
394         }
395 
396     private String getFormatExtension(Object _xComponent /* int _nType*/ )
397          {
398              String sExtension;
399              XServiceInfo xServiceInfo =  UnoRuntime.queryInterface( XServiceInfo.class, _xComponent );
400              if ( xServiceInfo.supportsService( "com.sun.star.sheet.SpreadsheetDocument" ) )
401              {
402                  // calc
403                  sExtension = ".ods";
404              }
405              else if (xServiceInfo.supportsService("com.sun.star.text.TextDocument"))
406              {
407                  //writer
408                  sExtension = ".odt";
409              }
410              else
411              {
412                  sExtension = ".UNKNOWN";
413              }
414              return sExtension;
415          }
416 
417     //         switch(_nType)
418     //         {
419     //         case WRITER:
420     //             sExtension = ".odt";
421     //             break;
422     //         case CALC:
423     //             sExtension = ".ods";
424     //             break;
425     //         default:
426     //             sExtension = ".UNKNOWN";
427     //         }
428     //         return sExtension;
429     //     }
430     // private String getFileFormat(int _nType)
431     //     {
432     //         String sFileType;
433     //         switch(_nType)
434     //         {
435     //         case WRITER:
436     //             sFileType = "writer8";
437     //             break;
438     //         case CALC:
439     //             sFileType = "calc8";
440     //             break;
441     //         default:
442     //             sFileType = "UNKNOWN";
443     //         }
444     //         return sFileType;
445     //     }
446 
447     private String m_sOutputPath = null;
448 
449     private String getOutputPath(/*int _nType*/)
450         {
451             if (m_sOutputPath == null)
452             {
453                 String sOutputPath = (String)m_aParameterHelper.getTestParameters().get( convwatch.PropertyName.DOC_COMPARATOR_OUTPUT_PATH );
454                 sOutputPath = helper.StringHelper.removeQuoteIfExists(sOutputPath);
455 
456                 // sOutputPath += "tmp_123";
457                 sOutputPath = FileHelper.appendPath(sOutputPath, DateHelper.getDateTimeForFilename());
458                 // sOutputPath += System.getProperty("file.separator");
459 
460                 // sOutputPath += getFileFormat(_nType);
461                 // sOutputPath += System.getProperty("file.separator");
462 
463                 File aOutputFile = new File(sOutputPath); // create the directory of the given output path
464                 aOutputFile.mkdirs();
465                 m_sOutputPath = sOutputPath;
466             }
467             return m_sOutputPath;
468         }
469 
470     /*
471       store given _xComponent under the given Name in DOC_COMPARATOR_INPUTPATH
472      */
473     private String storeComponent(String _sName, Object _xComponent /*, int _nType*/ )
474         {
475             String sOutputPath = getOutputPath(/*_nType*/);
476 
477 //            // add DocumentPoolName
478 //            sOutputPath = FileHelper.appendPath(sOutputPath, getDocumentPoolName(/*_nType*/));
479 //            // sOutputPath += System.getProperty("file.separator");
480 //
481 //            File aOutputFile = new File(sOutputPath); // create the directory of the given output path
482 //            aOutputFile.mkdirs();
483 
484 
485             String sName = _sName + getFormatExtension(_xComponent /*_nType*/);
486             sOutputPath = FileHelper.appendPath(sOutputPath, sName);
487 
488             // we need the name and path
489             String sBackPathName = sOutputPath;
490 
491             String sOutputURL = URLHelper.getFileURLFromSystemPath(sOutputPath);
492 
493             ArrayList<PropertyValue> aPropertyList = new ArrayList<PropertyValue>(); // set some properties for storeAsURL
494 
495             // PropertyValue aFileFormat = new PropertyValue();
496             // aFileFormat.Name = "FilterName";
497             // aFileFormat.Value = getFileFormat(_nType);
498             // aPropertyList.add(aFileFormat);
499 
500             PropertyValue aOverwrite = new PropertyValue(); // always overwrite already exist files
501             aOverwrite.Name = "Overwrite";
502             aOverwrite.Value = Boolean.TRUE;
503             aPropertyList.add(aOverwrite);
504 
505             // store the document in an other directory
506             XStorable aStorable = UnoRuntime.queryInterface( XStorable.class, _xComponent);
507             if (aStorable != null)
508             {
509                 GlobalLogWriter.println("store document as URL: '" + sOutputURL + "'");
510                 try
511                 {
512                     aStorable.storeAsURL(sOutputURL, PropertyHelper.createPropertyValueArrayFormArrayList(aPropertyList));
513                 }
514                 catch (com.sun.star.io.IOException e)
515                 {
516                     GlobalLogWriter.println("ERROR: Exception caught");
517                     GlobalLogWriter.println("Can't write document URL: '" + sOutputURL + "'");
518                     GlobalLogWriter.println("Message: " + e.getMessage());
519                 }
520             }
521             return sBackPathName;
522         }
523 
524     private XComponent loadComponent(String _sName, Object _xComponent, ArrayList _aPropertyList)
525         {
526             XComponent xDocComponent = null;
527             XComponentLoader xComponentLoader =  UnoRuntime.queryInterface( XComponentLoader.class, _xComponent );
528 
529             try
530             {
531                 PropertyValue[] aLoadProperties = PropertyHelper.createPropertyValueArrayFormArrayList(_aPropertyList);
532                 GlobalLogWriter.println("Load component: '" + _sName + "'");
533                 xDocComponent = xComponentLoader.loadComponentFromURL(_sName, "_blank", FrameSearchFlag.ALL, aLoadProperties);
534                 GlobalLogWriter.println("Load component: '" + _sName + "' done");
535             }
536             catch (com.sun.star.io.IOException e)
537             {
538                 GlobalLogWriter.println("ERROR: Exception caught");
539                 GlobalLogWriter.println("Can't load document '" + _sName + "'");
540                 GlobalLogWriter.println("Message: " + e.getMessage());
541             }
542             catch (com.sun.star.lang.IllegalArgumentException e)
543             {
544                 GlobalLogWriter.println("ERROR: Exception caught");
545                 GlobalLogWriter.println("Illegal Arguments given to loadComponentFromURL.");
546                 GlobalLogWriter.println("Message: " + e.getMessage());
547             }
548             return xDocComponent;
549         }
550 
551     private void closeComponent(XComponent _xDoc)
552         {
553             // Close the document
554             XCloseable xCloseable =  UnoRuntime.queryInterface(XCloseable.class, _xDoc);
555             try
556             {
557                 xCloseable.close(true);
558             }
559             catch (com.sun.star.util.CloseVetoException e)
560             {
561                 GlobalLogWriter.println("ERROR: CloseVetoException caught");
562                 GlobalLogWriter.println("CloseVetoException occured Can't close document.");
563                 GlobalLogWriter.println("Message: " + e.getMessage());
564             }
565         }
566 
567 }
568