1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 package complex.framework.recovery;
25 
26 import com.sun.star.accessibility.XAccessible;
27 import com.sun.star.accessibility.XAccessibleContext;
28 import com.sun.star.awt.Rectangle;
29 import com.sun.star.awt.Size;
30 import com.sun.star.awt.XDialog;
31 import com.sun.star.awt.XExtendedToolkit;
32 import com.sun.star.awt.XWindow;
33 import com.sun.star.beans.XPropertySet;
34 import com.sun.star.container.XEnumeration;
35 import com.sun.star.container.XIndexAccess;
36 import com.sun.star.container.XNameContainer;
37 import com.sun.star.drawing.XDrawPage;
38 import com.sun.star.drawing.XDrawPages;
39 import com.sun.star.drawing.XDrawPagesSupplier;
40 import com.sun.star.drawing.XShape;
41 import com.sun.star.drawing.XShapes;
42 import com.sun.star.frame.XController;
43 import com.sun.star.frame.XDesktop;
44 import com.sun.star.frame.XDispatch;
45 import com.sun.star.frame.XDispatchProvider;
46 import com.sun.star.frame.XFrame;
47 import com.sun.star.frame.XModel;
48 import com.sun.star.lang.XComponent;
49 import com.sun.star.lang.XMultiServiceFactory;
50 import com.sun.star.lang.XSingleServiceFactory;
51 import com.sun.star.presentation.XCustomPresentationSupplier;
52 import com.sun.star.presentation.XPresentationSupplier;
53 import com.sun.star.sheet.XSheetCellRange;
54 import com.sun.star.sheet.XSpreadsheet;
55 import com.sun.star.sheet.XSpreadsheetDocument;
56 import com.sun.star.sheet.XSpreadsheets;
57 import com.sun.star.style.XStyle;
58 import com.sun.star.table.XCellRange;
59 import com.sun.star.text.ControlCharacter;
60 import com.sun.star.text.XText;
61 import com.sun.star.text.XTextCursor;
62 import com.sun.star.text.XTextDocument;
63 import com.sun.star.uno.AnyConverter;
64 import com.sun.star.uno.Type;
65 import com.sun.star.uno.UnoRuntime;
66 import com.sun.star.uno.XInterface;
67 import com.sun.star.view.XSelectionSupplier;
68 import complexlib.ComplexTestCase;
69 import helper.OfficeProvider;
70 import helper.OfficeWatcher;
71 import java.awt.Dimension;
72 import java.awt.Point;
73 import java.awt.Toolkit;
74 import java.io.PrintWriter;
75 import java.util.Hashtable;
76 import java.util.Random;
77 import util.DesktopTools;
78 import util.PropertyName;
79 import util.SOfficeFactory;
80 import util.UITools;
81 import util.utils;
82 
83 // ---------- junit imports -----------------
84 import org.junit.After;
85 import org.junit.AfterClass;
86 import org.junit.Before;
87 import org.junit.BeforeClass;
88 import org.junit.Test;
89 import org.openoffice.test.OfficeConnection;
90 import static org.junit.Assert.*;
91 // ------------------------------------------
92 
93 public class RecoveryTest extends ComplexTestCase {
94 
95     static XMultiServiceFactory xMSF;
96     static SOfficeFactory SOF;
97     static RecoveryTools rt;
98     /**
99      * If you divide the screen in four parts in the first of them the office
100      * windows should be placed. The range of the first quarter is stored in the variable.
101      */
102     static Point windowMaxPosition;
103     /**
104      * The office windows starts in the first quarter of the screen. In this variable
105      * the maximum size for the windows was stored so the windows can be placed
106      * visible on the screen.
107      */
108     static Size windowMaxSize;
109 
110     /**
111      * All office windows will be placed by this test on randomized positions.
112      * This positions was stored in this Hashmap. The keys are the frame names
113      * and the values are com sun.star.awt.Rectangle.
114      * @see com.sun.star.awt.Rectangle
115      */
116     private Hashtable windowsPosSize = new Hashtable();
117 
118     /**
119      * A function to tell the framework, which test functions are available.
120      * @return All test methods.
121      *
122      * @todo: hidden documents
123      * @todo: running presentation
124      * @todo: modular dialogs like Hyperlink-Dialog
125      * @todo: second view of a document
126      * @todo: remove recovery data before start test
127      * @todo: after a second start after the crash there should no documents recovered anymore
128      * @todo: enable remove of recovery files
129      * @todo: modify makefile to check for parameters
130      */
getTestMethodNames()131     public String[] getTestMethodNames() {
132         return new String[]{"testCrash"};
133     }
134 
135     /** Create the environment for following tests.
136      * Use either a component loader from desktop or
137      * from frame
138      * @throws Exception Exception
139      */
140 
normalCrash()141     public void normalCrash(){
142         cleanRecoveryData();
143         startOffice();
144         generateDesktop();
145         makeCrash();
146         int expectedDocumentCount = windowsPosSize.size() + 1;
147         handleRecoveryDialogAfterCrash(expectedDocumentCount);
148         startOffice();
149         handleRecoveryDialog_QuickExit(expectedDocumentCount);
150         handleCrashReporterDialog(true, true);
151         checkDocumentCount(expectedDocumentCount);
152     }
153 
testCrash()154     public void testCrash(){
155         cleanRecoveryData();
156         restoreBackupRecoveryData();
157         startOffice();
158         int expectedDocumentCount = 3;
159 //		handleRecoveryDialog_QuickExit(expectedDocumentCount);
160         handleRecoveryDialog_QuickExitAndSave(expectedDocumentCount);
161         //handleCrashReporterDialog(true, true);
162         //checkDocumentCount(expectedDocumentCount);
163     }
164 
before()165     public void before() throws Exception {
166 
167         String msg ="\n\n\tPATH TO OFFICE BINARY MISSING!\n";
168         msg +="\tPlease run your command with the following parameter:\n\n";
169         msg +="\t-AppExecutionCommand=OFFICEBINARY CONNECTIONSTRING\n\n";
170         msg +="Example Windows:\n";
171         msg +="-AppExecutionCommand=C:\\office\\soffice.exe -accept=socket,host=localhost,port=8101;urp;\n\n";
172         msg +="Example UNIX:\n";
173         msg +="-AppExecutionCommand=/office/soffice \"-accept=socket,host=localhost,port=8101;urp;\"\n\n";
174         msg+="NOTE: on UNIX be sure to have the connection string inside quotation mark!\n";
175 
176         assure(msg, param.get("AppExecutionCommand") != null && ! param.get("AppExecutionCommand").equals(""));
177         System.out.println("HALLO" + param.get("AppExecutionCommand"));
178         msg = "\n\nONE PARAMETER IS MISSING!\n";
179         msg += "Please append to your command the following parameter:\n\n";
180         msg += "\t-NoOffice=true";
181         assure(msg, param.getBool("NoOffice"));
182 
183 
184         rt = new RecoveryTools(param ,log);
185 
186         rt.removeParametersFromAppExecutionCommand();
187 
188         log.println("start the office to test recovery feature...");
189 
190         // make window ranges
191         makeWindowPositionRage();
192 
193         //makeRecoveryData();
194     }
195 
makeRecoveryData()196     private void makeRecoveryData(){
197         cleanRecoveryData();
198         startOffice();
199         generateDesktop();
200         makeCrash();
201         int expectedDocumentCount = windowsPosSize.size() + 1;
202         handleRecoveryDialogAfterCrash(expectedDocumentCount);
203         backupRecoveryData();
204         cleanRecoveryData();
205     }
206 
startOffice()207     private void startOffice(){
208         assure("Could not connect to office", connect());
209         log.setWatcher(param.get("Watcher"));
210     }
211 
212 
checkDocumentCount(int expectedDocumentCount)213     private void checkDocumentCount(int expectedDocumentCount){
214         XEnumeration allComp = DesktopTools.getAllComponents(xMSF);
215         int documentCount = 0;
216 
217         try{
218             while (allComp.hasMoreElements()){
219                 allComp.nextElement();
220                 documentCount ++;
221             }
222         }
223         catch ( com.sun.star.container.NoSuchElementException e){}
224         catch ( com.sun.star.lang.WrappedTargetException e){}
225 
226         String msg ="The amount of documents to recover is different form the expected amount:\n";
227         msg += "\texpected:\t" + expectedDocumentCount + "\n";
228         msg += "\tto recover:\t" + documentCount;
229 
230         assure(msg, expectedDocumentCount == documentCount);
231     }
232 
233     /**
234      * This function starts an office instance. It uses the AppExecutionCommad parameter.
235      * @return TRUE if office is connected otherwise FALSE
236      */
connect()237     private boolean connect(){
238         try {
239 
240             OfficeProvider oProvider = new OfficeProvider();
241             xMSF = (XMultiServiceFactory)oProvider.getManager(param);
242 
243             SOF = SOfficeFactory.getFactory(xMSF);
244 
245         }
246         catch (java.lang.Exception e) {
247             log.println(e.getClass().getName());
248             log.println("Message: " + e.getMessage());
249             failed("Cannot connect the office.");
250             return false;
251         }
252         return true;
253     }
254 
255     /**
256      * While creating the test environment the positions and sizes of the frames
257      * was saved. After the office has recovered the documents, this functions
258      * compares the saved positions and sizes with the current frame.
259      */
compareWindowPositions()260     private void compareWindowPositions(){
261         System.out.println("all frames:########");
262         System.out.println(windowsPosSize.entrySet().toString());
263 
264         XEnumeration allComp = DesktopTools.getAllComponents(xMSF);
265 
266         String msg=null;
267 
268         while (allComp.hasMoreElements()){
269             try{
270                 // get all components from the desktop
271                 XComponent xComponent = (XComponent) UnoRuntime.queryInterface(
272                                        XComponent.class, allComp.nextElement());
273 
274                 XModel xModel = (XModel) UnoRuntime.queryInterface(XModel.class, xComponent);
275 
276                 String frameName = xModel.getCurrentController().getFrame().getName();
277 
278                 // check if this frame was used in creation of test environment
279                 if (windowsPosSize.containsKey(frameName)){
280 
281                     Rectangle oldRect = (Rectangle) windowsPosSize.get(frameName);
282 
283                     XWindow xWindow = xModel.getCurrentController().getFrame().getContainerWindow();
284                     Rectangle newRect = xWindow.getPosSize();
285 
286 
287                     boolean ok = oldRect.Height == newRect.Height;
288                     ok &= oldRect.Width == newRect.Width;
289                     ok &= oldRect.X == newRect.X;
290                     ok &= oldRect.Y == newRect.Y;
291 
292                     if (!ok){
293                         msg = "The frame '" + frameName + "' has a different position/size:\n";
294                         msg += "original value -> restored value:\n";
295                         msg += "X     : " + oldRect.X + " -> " + newRect.X + "\n";
296                         msg += "Y     : " + oldRect.Y + " -> " + newRect.Y + "\n";
297                         msg += "Height: " + oldRect.Height + " -> " + newRect.Height + "\n";
298                         msg += "Width : " + oldRect.Width + " -> " + newRect.Width + "\n";
299                     }
300 
301                     assure(msg, ok, CONTINUE);
302 
303                 }
304             } catch (com.sun.star.container.NoSuchElementException e) {
305             } catch ( com.sun.star.lang.WrappedTargetException e) {}
306         }
307 
308     }
309 
310     /**
311      * This function crashes the office
312      */
makeCrash()313     private void makeCrash(){
314         // get all documents
315         Object[] allDocs = DesktopTools.getAllOpenDocuments(xMSF);
316 
317         // get one of them for dispatching
318         XComponent xDoc = (XComponent) allDocs[0];
319         log.println("make the crash in second thread");
320 
321         CrashThread crash = new CrashThread(xDoc, xMSF);
322         crash.start();
323         rt.pause();
324         rt.pause();
325     }
326 
327     /**
328      *  This function uses accessibility to handle the dialog which appears while the
329      * office is crashed. It click the button "OK" to continue.
330      */
handleRecoveryDialogAfterCrash(int expectedDocumentCount)331     private void handleRecoveryDialogAfterCrash(int expectedDocumentCount){
332         try{
333 
334             // if the office crashes, the recovery feature needs some time
335             // to save all docs. Therefore the recovery dialog could need some
336             // time to pop up.
337             log.println("waiting for recovery dialog...");
338 
339             int counter = 0;
340             int maximum = param.getInt(PropertyName.THREAD_TIME_OUT) / param.getInt(PropertyName.SHORT_WAIT);
341 
342             XDialog oDialog = rt.getActiveDialog(xMSF);
343 
344             while ( oDialog == null && (counter < maximum))
345             {
346                 rt.pause();
347                 oDialog = rt.getActiveDialog(xMSF);
348                 counter ++;
349             }
350 
351             assure("could not get Recovery Window",(oDialog != null));
352 
353             XWindow xWindow = (XWindow) UnoRuntime.queryInterface(XWindow.class, oDialog);
354 
355             UITools oUITools = new UITools(xMSF, xWindow);
356 
357             oUITools.printAccessibleTree((PrintWriter) log, param.getBool(PropertyName.DEBUG_IS_ACTIVE));
358 
359             String[] documents = oUITools.getListBoxItems("The following files will be recovered");
360             log.println("there are " + documents.length + " documents to save");
361 
362             String msg ="The amount of documents to recover is different form the expected amount:\n";
363             msg += "\texpected:\t" + expectedDocumentCount + "\n";
364             msg += "\tto recover:\t" + documents.length;
365 
366             assure(msg, expectedDocumentCount == documents.length);
367 
368             log.println("disable automatically launch of Office");
369             oUITools.setCheckBoxValue("Launch OpenOffice automatically", new Integer(0));
370 
371             log.println("start saving...");
372             oUITools.clickButton("OK");
373 
374             rt.waitForClosedOffice();
375 
376         } catch (Exception e){
377             e.printStackTrace();
378             failed("Could not handle crash-dialog: " + e.toString());
379         }
380     }
381 
handleCrashReporterDialog(boolean cancel, boolean YesNo)382      private void handleCrashReporterDialog(boolean cancel, boolean YesNo){
383         try{
384 
385             log.println("try to get Crash Reporter Dialog...");
386 
387             XDialog oDialog = rt.getActiveDialog(xMSF);
388             assure("could not get CrashReporter Dialog", oDialog != null);
389 
390             XWindow xWindow = (XWindow) UnoRuntime.queryInterface(XWindow.class, oDialog);
391 
392             log.println(oDialog.getTitle());
393 
394             UITools oUITools = new UITools(xMSF, xWindow);
395 
396             if (cancel) {
397                 log.println("clicking 'Cancel' button...");
398 
399                 try{
400                     rt.clickThreadButton(xMSF, xWindow, "Cancel");
401                 } catch (com.sun.star.accessibility.IllegalAccessibleComponentStateException e){
402                     failed("Could not click 'Cancel' at CrashReporter Dialog");
403                 }
404 
405             }
406             else {
407                 log.println("clicking 'Next' button...");
408                 oUITools.clickButton("Next >");
409             }
410 
411         } catch (Exception e){
412             failed("Could not handle CrashReporter Dialog: " + e.toString());
413         }
414     }
415 
handleRecoveryDialog_QuickExit(int expectedDocumentCount)416     private void handleRecoveryDialog_QuickExit(int expectedDocumentCount){
417         log.println("handle Recovery Dialog at restart: quick exit");
418         handleRecoveryDialogAtRestart(expectedDocumentCount, false, true);
419         handleAreYouSureDialog(true);
420         handleSaveDocumentsDialog(false);
421 
422     }
handleRecoveryDialog_QuickExitAndSave(int expectedDocumentCount)423     private void handleRecoveryDialog_QuickExitAndSave(int expectedDocumentCount){
424         log.println("handle Recovery Dialog at restart: quick exit");
425         handleRecoveryDialogAtRestart(expectedDocumentCount, false, true);
426         handleAreYouSureDialog(true);
427         handleSaveDocumentsDialog(true);
428     }
handleRecoveryDialog_Recover(int expectedDocumentCount)429     private void handleRecoveryDialog_Recover(int expectedDocumentCount){
430 
431     }
handleRecoveryDialog_RecoverAndCrashreporter(int expectedDocumentCount)432     private void handleRecoveryDialog_RecoverAndCrashreporter(int expectedDocumentCount){
433 
434     }
435      /**
436       * This function uses accessibility to handle the dialog which appears while the
437       * office is started after a crash. It waits until the "Next" button is enabled
438       * and click it then to continue.
439       * @param expectedDocumentCount the amount of documents which must be displayed in the recovery dialog
440       * @param recover If the document should be recovered this variable must be true. If it is false
441       * the recovery process was stopped and the button cancel was clicked.
442       * @param cancel If the recovery is finished, this parameter decides to click the "Next" button
443       * or the click cancel. If the value is true, the cancel button was clicked.
444       */
handleRecoveryDialogAtRestart(int expectedDocumentCount, boolean recover, boolean cancel)445     private void handleRecoveryDialogAtRestart(int expectedDocumentCount, boolean recover, boolean cancel){
446         try{
447 
448             log.println("try to get Recovery Dialog...");
449 
450             XDialog oDialog = null;
451             oDialog = rt.getActiveDialogAfterStartup(xMSF);
452 
453             assure("could not get Recovery Dialog at start of office", (oDialog != null), CONTINUE);
454 
455             XWindow xWindow = (XWindow) UnoRuntime.queryInterface(XWindow.class, oDialog);
456             log.println("got the following dialog: '" +oDialog.getTitle() + "'");
457 
458             UITools oUITools = new UITools(xMSF, xWindow);
459 
460             String listBoxName = "Status of recovered documents";
461             String[] documents = oUITools.getListBoxItems(listBoxName);
462             log.println("there are " + documents.length + " documents to recover");
463             log.println("The following files will be recovered:");
464             for (int i=0;i<documents.length;i++){
465                 log.println(documents[i]);
466             }
467 
468             String msg ="The amount of documents to recover is different form the expected amount:\n";
469             msg += "\texpected:\t" + expectedDocumentCount + "\n";
470             msg += "\tto recover:\t" + documents.length;
471 
472             assure(msg, expectedDocumentCount ==documents.length);
473 
474             if (recover){
475 
476                 log.println("clicking 'Start Recovery' button...");
477                 oUITools.clickButton("Start Recovery >");
478 
479                 rt.pause();
480 
481                 //XAccessibleContext oButton = oUITools.getButton("Start Recovery >");
482                 int counter = 0;
483                 int maximum = param.getInt(PropertyName.THREAD_TIME_OUT) / param.getInt(PropertyName.SHORT_WAIT);
484                 //boolean enabeld = oButton.getAccessibleStateSet().contains(com.sun.star.accessibility.AccessibleStateType.ENABLED);
485 
486                 XAccessibleContext oButton = null;
487                 while ((oButton == null) && (counter < maximum)){
488                     log.println("recovering...");
489 
490                     try{
491                        oButton = oUITools.getButton("Next >");
492                     } catch (java.lang.NullPointerException e){
493                         // no fault: The title "Start Recovery" switches to "Next"
494                         // while all documents are recovered
495                     }
496                     rt.pause();
497                     counter++;
498                 }
499 
500                 if (cancel) {
501                     log.println("clicking 'Cancel' button...");
502 
503                     try{
504                         rt.clickThreadButton(xMSF, xWindow, "Cancel");
505                     } catch (com.sun.star.accessibility.IllegalAccessibleComponentStateException e){
506                         failed("Could not click 'Cancel' at recovery-dialog.");
507                     }
508 
509                 }
510                 else {
511                     log.println("clicking 'Next' button...");
512                     oUITools.clickButton("Next >");
513                 }
514 
515                 rt.pause();
516 
517             } else {
518                     log.println("do not recover: clicking 'Cancel' button...");
519 
520                     try{
521                         rt.clickThreadButton(xMSF, xWindow, "Cancel");
522                     } catch (com.sun.star.accessibility.IllegalAccessibleComponentStateException e){
523                         failed("Could not click 'Cancel' at recovery-dialog");
524                     }
525             }
526 
527         } catch (Exception e){
528             failed("Could not handle recovery-dialog at restart: " + e.toString());
529         }
530 
531     }
532 
533     /**
534      * This function uses accessibility to handle the dialog "Are you sure".
535      * It click "Yes" or "No", depending on the value of the parameter <CODE>Yes</CODE>
536      * @param yes If value is <CODE>TRUE</CODE> the button "Yes" was clicked, otherwise the button
537      * "No".
538      */
handleAreYouSureDialog(boolean yes)539     private void handleAreYouSureDialog(boolean yes)
540     {
541         try{
542             if (yes){
543                 rt.handleModalDialog(xMSF, "Yes");
544             } else{
545                 rt.handleModalDialog(xMSF, "Cancel");
546             }
547         } catch (com.sun.star.accessibility.IllegalAccessibleComponentStateException e){
548             failed("Could not handle 'Are you sure' dialog.");
549         }
550     }
551 
552     /**
553      * This function uses accessibility to handle the dialog "Are you sure".
554      * It click "Yes" or "No", depending on the value of the parameter <CODE>Yes</CODE>
555      * @param saveDocuments If value is <CODE>TRUE</CODE> the button "Yes" was clicked, otherwise the button
556      * "No".
557      */
handleSaveDocumentsDialog(boolean saveDocuments)558     private void handleSaveDocumentsDialog(boolean saveDocuments)
559     {
560         try{
561             if (!saveDocuments){
562                 rt.handleModalDialog(xMSF, "Cancel");
563             } else{
564                 XWindow oDialog = null;
565                 oDialog = rt.getActiveWindow(xMSF);
566 
567                 assure("could not get 'Save Documents' Dialog: ", (oDialog != null), CONTINUE);
568 
569                 UITools oUITools = new UITools(xMSF, oDialog);
570 
571                 oUITools.printAccessibleTree((PrintWriter) log, param.getBool(PropertyName.DEBUG_IS_ACTIVE));
572 
573                 String listBoxName = "Documents";
574                 String[] documents = null;
575                 try{
576                     documents = oUITools.getListBoxItems(listBoxName);
577                 } catch (java.lang.Exception e){
578                     failed("could not get the document names from the 'Save Documents' dialog", CONTINUE);
579                 }
580                 log.println("there are " + documents.length + " documents to save");
581                 log.println("The following documents will be saved:");
582                 for (int i=0;i<documents.length;i++){
583                     log.println(documents[i]);
584                 }
585                 String tempURL = utils.getOfficeTempDir(xMSF);
586 
587                 log.println("the destination for saving is: " + tempURL);
588                 try{
589                     oUITools.setTextEditFiledText("Save to", tempURL);
590                 } catch (java.lang.Exception e){
591                     failed("could not set target directory for saving documents at 'Save Documents' dialog", CONTINUE);
592                 }
593                 try{
594                     oUITools.clickButton("OK");
595                 } catch (java.lang.Exception e){
596                     failed("could not click 'OK' at 'Save Documents' dialog", CONTINUE);
597                 }
598             }
599         } catch (com.sun.star.accessibility.IllegalAccessibleComponentStateException e){
600             failed("Could not handle 'Are you sure' dialog.");
601         }
602     }
603 
604     /**
605      * This function gets the current screen size and calculate the first
606      * quarter of it. This quarter was used to position to office windows.
607      * Further this function calculates the maximum window size so the window
608      * is visible if it placed on extreme position.
609      */
makeWindowPositionRage()610     private void makeWindowPositionRage(){
611         Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
612         Point pos = new Point();
613         Size size = new Size();
614 
615         // get the max position of the first quarter of the screen
616         pos.x = screenDim.width / 2;
617         pos.y = screenDim.height / 2;
618         windowMaxPosition = pos;
619 
620         // get the max size of the windows while they placed in windowMaxPosition
621         // range and not outside the visibility
622         size.Height = screenDim.height;
623         size.Width = screenDim.width;
624         windowMaxSize = size;
625     }
626 
generateDesktop()627     private void generateDesktop(){
628 
629         // create some documents with content
630         makeWriterDoc("WriterDoc1", true);
631 //        makeCalcDoc("CalcDoc1", true);
632 //        makeDrawDoc("DrawDoc1", true);
633 //        makeImpressDoc("ImpressDoc1", true);
634 //        makeMathDoc("MathDoc1", true);
635 
636         // create some documents without content
637 //        makeMathDoc("_blank_math", false);
638 //        makeDrawDoc("_blank_draw", false);
639 //        makeCalcDoc("_blank_calc", false);
640 //        makeWriterDoc("_blank_writer", false);
641 //        makeImpressDoc("_blank_impress", false);
642 
643 //        makeMathDoc("MathDocEmpty", false);
644 //        makeDrawDoc("DrawDocEmpty", false);
645 //        makeCalcDoc("CalcDocEmpty", false);
646         makeWriterDoc("WriterDocEmpty", false);
647 //        makeImpressDoc("ImpressDocEmpty", false);
648 
649         log.println("Test object successfully created.");
650 
651     }
652 
makeImpressDoc(String frameName, boolean withContent)653     private void makeImpressDoc(String frameName, boolean withContent){
654         log.println("creating Impress document '" + frameName + "'");
655         XComponent xImpressDoc = createNewImpressDoc(frameName);
656         if (withContent) fillImpressDocWithContent(xImpressDoc);
657         positioningDocument((XModel) UnoRuntime.queryInterface(XModel.class,
658                                                                xImpressDoc));
659     }
660 
makeDrawDoc(String frameName, boolean withContent)661     private void makeDrawDoc(String frameName, boolean withContent){
662         log.println("creating Draw document '" + frameName + "'");
663         XComponent xDrawDoc = createNewDrawDoc(frameName);
664         if (withContent) fillDrawDocWithContent(xDrawDoc);
665         positioningDocument((XModel) UnoRuntime.queryInterface(XModel.class,
666                                                                  xDrawDoc));
667     }
668 
makeCalcDoc(String frameName, boolean withContent)669     private void makeCalcDoc(String frameName, boolean withContent){
670         log.println("creating Calc document '" + frameName + "'");
671         XSpreadsheetDocument xSpreadsheetDoc = createNewCalcDoc(frameName);
672         if (withContent) fillCalcDocWithContent(xSpreadsheetDoc);
673         positioningDocument((XModel) UnoRuntime.queryInterface(XModel.class,
674                                                            xSpreadsheetDoc));
675     }
676 
positioningDocument(XModel model)677     private void positioningDocument(XModel model){
678 
679         XWindow xWindow = model.getCurrentController().getFrame().getContainerWindow();
680         String frameName = model.getCurrentController().getFrame().getName();
681 
682         // get randomized position and size
683         Rectangle posSize = makePosZize();
684 
685         // save position and size
686         windowsPosSize.put(frameName, posSize);
687 
688         xWindow.setPosSize(posSize.X, posSize.Y, posSize.Width, posSize.Height,
689                            com.sun.star.awt.PosSize.POSSIZE);
690         Rectangle test = xWindow.getPosSize();
691         log.println("x: "+test.X+" y:"+test.Y+" width:"+test.Width+" height:"+test.Height);
692     }
693 
makePosZize()694     private Rectangle makePosZize(){
695 
696         Rectangle posSize = new Rectangle();
697         Random rand = new Random();
698 
699         // Random integers that range from from 0 to n
700         posSize.X = rand.nextInt(windowMaxPosition.x + 1);
701         posSize.Y = rand.nextInt(windowMaxPosition.y + 1);
702 
703         int maxHeight = windowMaxSize.Height-posSize.X;
704         int maxWidth = windowMaxSize.Width-posSize.Y;
705         int height = rand.nextInt(maxHeight + 1);
706         int width = rand.nextInt((windowMaxSize.Width-posSize.Y) + 1);
707 
708         // be sure that the new size is greater then the half of windowMaxSize
709         posSize.Height = (height < (maxHeight / 2)) ? height + (maxHeight / 2) : height;
710         posSize.Width =  (width < (maxWidth / 2)) ? width + (maxWidth / 2) : width;
711 
712         return posSize;
713     }
714 
makeMathDoc(String frameName, boolean withContent)715     private void makeMathDoc(String frameName, boolean withContent){
716         log.println("creating Math document '" + frameName + "'");
717         XComponent xMathDoc = createNewMathDoc(frameName);
718         if (withContent) fillMathDocWithContent(xMathDoc);
719         positioningDocument((XModel) UnoRuntime.queryInterface(XModel.class,
720                                                                xMathDoc));
721     }
722 
createNewMathDoc(String frameName)723     private XComponent createNewMathDoc(String frameName){
724         XComponent xMathDoc = null;
725         try{
726             xMathDoc = SOF.createMathDoc(frameName);
727         } catch (com.sun.star.uno.Exception e) {
728             log.println("Exception occurred while creating Math document '"+frameName+"':");
729             failed("Couldn't create test environment");
730         }
731         return xMathDoc;
732     }
733 
fillMathDocWithContent(XComponent xMathDoc)734     private void fillMathDocWithContent(XComponent xMathDoc){
735         // setting a formula in document
736         final String expFormula = "sum a cdot b";
737         final XPropertySet xPS = (XPropertySet) UnoRuntime.queryInterface
738             (XPropertySet.class, xMathDoc);
739         try {
740             xPS.setPropertyValue("Formula", expFormula);
741         } catch(com.sun.star.lang.WrappedTargetException e) {
742             log.println("Exception occurred while filling Math document with content.");
743             failed("Couldn't create test environment");
744         } catch(com.sun.star.lang.IllegalArgumentException e) {
745             log.println("Exception occurred while filling Math document with content.");
746             failed("Couldn't create test environment");
747         } catch(com.sun.star.beans.PropertyVetoException e) {
748             log.println("Exception occurred while filling Math document with content.");
749             failed("Couldn't create test environment");
750         } catch(com.sun.star.beans.UnknownPropertyException e) {
751             log.println("Exception occurred while filling Math document with content.");
752             failed("Couldn't create test environment");
753         }
754     }
755 
createNewImpressDoc(String frameName)756     private XComponent createNewImpressDoc(String frameName){
757         XComponent xImpressDoc = null;
758         try{
759             xImpressDoc = SOF.createImpressDoc(frameName);
760         } catch (com.sun.star.uno.Exception e) {
761             log.println("Exception occurred while creating Impress document '"+frameName+"':");
762             failed("Couldn't create test environment");
763         }
764         return xImpressDoc;
765     }
766 
767 
fillImpressDocWithContent(XComponent xImpressDoc)768     private void fillImpressDocWithContent(XComponent xImpressDoc){
769 
770         log.println( "get presentation" );
771         XPresentationSupplier oPS = (XPresentationSupplier)
772             UnoRuntime.queryInterface(XPresentationSupplier.class, xImpressDoc);
773         XInterface oObj = oPS.getPresentation();
774 
775         log.println( "get custom presentation" );
776         XCustomPresentationSupplier oCPS = (XCustomPresentationSupplier)
777             UnoRuntime.queryInterface(
778                 XCustomPresentationSupplier.class, xImpressDoc);
779         XNameContainer xCP = oCPS.getCustomPresentations();
780 
781         XInterface oInstance = null;
782 
783         XSingleServiceFactory oSingleMSF = (XSingleServiceFactory)
784             UnoRuntime.queryInterface(XSingleServiceFactory.class, xCP);
785 
786         try{
787             oInstance = (XInterface) oSingleMSF.createInstance();
788         } catch (com.sun.star.uno.Exception e) {
789             log.println("Could not create custom presentation while filling Impress document with content.");
790             failed("Couldn't create test environment");
791         }
792 
793         try {
794             xCP.insertByName("FirstPresentation",oInstance);
795         } catch (com.sun.star.lang.WrappedTargetException e) {
796             log.println("Could not insert custom presentation while filling Impress document with content.");
797             failed("Couldn't create test environment");
798         } catch (com.sun.star.container.ElementExistException e) {
799             log.println("Could not insert custom presentation while filling Impress document with content.");
800             failed("Couldn't create test environment");
801         } catch (com.sun.star.lang.IllegalArgumentException e) {
802             log.println("Could not insert custom presentation while filling Impress document with content.");
803             failed("Couldn't create test environment");
804         }
805     }
806 
createNewDrawDoc(String frameName)807     private XComponent createNewDrawDoc(String frameName){
808         XComponent xDrawDoc = null;
809         try{
810             xDrawDoc = SOF.createDrawDoc(frameName);
811         } catch (com.sun.star.uno.Exception e) {
812             log.println("Exception occurred while creating Draw document '"+frameName+"':");
813             failed("Couldn't create test environment");
814         }
815         return xDrawDoc;
816     }
817 
fillDrawDocWithContent(XComponent xDrawDoc)818     private void fillDrawDocWithContent(XComponent xDrawDoc){
819         XDrawPagesSupplier oDPS = (XDrawPagesSupplier)
820             UnoRuntime.queryInterface(XDrawPagesSupplier.class, xDrawDoc);
821         XDrawPages oDPn = oDPS.getDrawPages();
822         XIndexAccess oDPi = (XIndexAccess)
823             UnoRuntime.queryInterface(XIndexAccess.class, oDPn);
824         XDrawPage oDP = null;
825         try {
826             oDP = (XDrawPage) AnyConverter.toObject(
827                         new Type(XDrawPage.class),oDPi.getByIndex(0));
828         } catch (com.sun.star.lang.WrappedTargetException e) {
829             log.println("Could not get Draw pages while filling Draw document with content.");
830             failed("Couldn't create test environment");
831         } catch (com.sun.star.lang.IndexOutOfBoundsException e) {
832             log.println("Could not get Draw pages while filling Draw document with content.");
833             failed("Couldn't create test environment");
834         } catch (com.sun.star.lang.IllegalArgumentException e) {
835             log.println("Could not get Draw pages while filling Draw document with content.");
836             failed("Couldn't create test environment");
837         }
838 
839         // get a Shape
840         log.println( "getting Shape" );
841         XShapes oShapes = (XShapes) UnoRuntime.queryInterface
842             (XShapes.class, oDP);
843         XInterface oObj = SOF.createShape
844             (xDrawDoc, 5000, 3500, 7500, 5000, "Rectangle");
845         for (int i=0; i < 10; i++) {
846             oShapes.add(
847                 SOF.createShape(xDrawDoc,
848                     5000, 3500, 7510 + 10 * i, 5010 + 10 * i, "Rectangle"));
849         }
850         XShape oShape = SOF.createShape
851             (xDrawDoc, 3000, 4500, 15000, 1000, "Ellipse");
852         oShapes.add((XShape) oObj);
853         oShapes.add((XShape) oShape);
854 
855 
856         XPropertySet oShapeProps = (XPropertySet)
857             UnoRuntime.queryInterface(XPropertySet.class, oObj);
858         XStyle aStyle = null;
859         try {
860             aStyle = (XStyle) AnyConverter.toObject(
861                 new Type(XStyle.class),oShapeProps.getPropertyValue("Style"));
862             oShapeProps.setPropertyValue("ZOrder", new Integer(1));
863         } catch (com.sun.star.lang.WrappedTargetException e) {
864             log.println("Exception occurred while setting or getting property value while filling Draw document with content.");
865             failed("Couldn't create test environment");
866         } catch (com.sun.star.beans.UnknownPropertyException e) {
867             log.println("Exception occurred while setting or getting property value while filling Draw document with content.");
868             failed("Couldn't create test environment");
869         } catch (com.sun.star.lang.IllegalArgumentException e) {
870             log.println("Exception occurred while setting or getting property value while filling Draw document with content.");
871             failed("Couldn't create test environment");
872         } catch (com.sun.star.beans.PropertyVetoException e) {
873             log.println("Exception occurred while setting or getting property value while filling Draw document with content.");
874             failed("Couldn't create test environment");
875         }
876     }
877 
makeWriterDoc(String frameName, boolean withContent)878     private void makeWriterDoc(String frameName, boolean withContent){
879         log.println("creating Writer document '" + frameName + "'");
880         XTextDocument xTextDoc = createNewWriterDoc(frameName);
881         if (withContent) fillWriterDocWithContent(xTextDoc);
882         positioningDocument((XModel) UnoRuntime.queryInterface(XModel.class,
883                                                                  xTextDoc));
884     }
885 
createNewWriterDoc(String frameName)886     private XTextDocument createNewWriterDoc(String frameName){
887         XTextDocument xTextDoc = null;
888         try {
889             xTextDoc = SOF.createTextDoc(frameName);
890         } catch (com.sun.star.uno.Exception e) {
891             log.println("Exception occurred while creating text document '"+frameName+"':");
892             failed("Couldn't create test environment");
893         }
894         return xTextDoc;
895     }
896 
fillWriterDocWithContent(XTextDocument xTextDoc)897     private void fillWriterDocWithContent(XTextDocument xTextDoc){
898         try{
899             log.println( "inserting some lines" );
900             XText oText = xTextDoc.getText();
901             XTextCursor oCursor = oText.createTextCursor();
902             for (int i=0; i<5; i++){
903                 oText.insertString( oCursor,"Paragraph Number: " + i, false);
904                 oText.insertString( oCursor,
905                 " The quick brown fox jumps over the lazy Dog: SwXParagraph",
906                 false);
907                 oText.insertControlCharacter(
908                 oCursor, ControlCharacter.PARAGRAPH_BREAK, false );
909                 oText.insertString( oCursor,
910                 "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG: SwXParagraph",
911                 false);
912                 oText.insertControlCharacter(oCursor,
913                 ControlCharacter.PARAGRAPH_BREAK, false );
914                 oText.insertControlCharacter(
915                 oCursor, ControlCharacter.LINE_BREAK, false );
916             }
917         } catch ( com.sun.star.lang.IllegalArgumentException e ){
918             log.println("Exception occurred while filling text document with content.");
919             failed("Couldn't create test environment");
920         } catch (com.sun.star.uno.Exception e) {
921             log.println("Exception occurred while filling text document with content.");
922             failed("Couldn't create test environment");
923         }
924     }
925 
createNewCalcDoc(String frameName)926     private XSpreadsheetDocument createNewCalcDoc(String frameName){
927 
928         XSpreadsheetDocument xSheetDoc = null;
929 
930         try {
931             xSheetDoc = SOF.createCalcDoc(frameName);
932         } catch (com.sun.star.uno.Exception e) {
933             log.println("Exception occurred while creating Calc document '"+frameName+"':");
934             failed("Couldn't create test environment");
935         }
936         return xSheetDoc;
937     }
938 
fillCalcDocWithContent(XSpreadsheetDocument xSpreadsheetDoc)939     private void fillCalcDocWithContent(XSpreadsheetDocument xSpreadsheetDoc){
940 
941         try{
942             XSpreadsheets oSpreadsheets = xSpreadsheetDoc.getSheets();
943 
944             XSpreadsheet oSheet = (XSpreadsheet) AnyConverter.toObject(
945                              new Type(XSpreadsheet.class),
946                              oSpreadsheets.getByName(
947                                      oSpreadsheets.getElementNames()[0]));
948 
949             XCellRange testRange = oSheet.getCellRangeByName("$A$1:$D$4");
950 
951             XSheetCellRange testSheetRange = (XSheetCellRange) UnoRuntime.queryInterface(
952                                                      XSheetCellRange.class,
953                                                      testRange);
954             oSheet.getCellByPosition(1, 1).setValue(1);
955             oSheet.getCellByPosition(4, 5).setValue(1);
956             oSheet.getCellByPosition(3, 2).setFormula("xTextDoc");
957             oSheet.getCellByPosition(3, 3).setFormula("xTextDoc");
958         } catch (com.sun.star.lang.WrappedTargetException e) {
959             log.println("Exception occurred while filling Calc document with content.");
960             failed("Couldn't create test environment");
961         } catch (com.sun.star.container.NoSuchElementException e) {
962             log.println("Exception occurred while filling Calc document with content.");
963             failed("Couldn't create test environment");
964         } catch (com.sun.star.lang.IndexOutOfBoundsException e) {
965             log.println("Exception occurred while filling Calc document with content.");
966             failed("Couldn't create test environment");
967         } catch (com.sun.star.lang.IllegalArgumentException e) {
968             log.println("Exception occurred while filling Calc document with content.");
969             failed("Couldn't create test environment");
970         } catch (com.sun.star.uno.Exception e) {
971             log.println("Exception occurred while filling Calc document with content.");
972             failed("Couldn't create test environment");
973         }
974     }
975 
976     /**
977      * copies all files from the backup folder into a folder called backup.recoveryTest
978      * and copies the Recovery.xcu to recovery.xcu.recoveryTest
979      */
backupRecoveryData()980     private void backupRecoveryData()
981     {
982         log.println("backup recovery data...");
983         try{
984             rt.copyRecoveryData(true);
985         }catch (com.sun.star.io.IOException e){
986             failed("could not copy recovery data: " + e.toString());
987         }catch (java.io.IOException e){
988             failed("could not copy recovery data: " + e.toString());
989         }
990     }
991 
992     /**
993      * copies all files from the backup.recoveryTest folder into the backup folder
994      * and copies the Recovery.xcu.recoveryTest to recovery.xcu
995      */
restoreBackupRecoveryData()996     private void restoreBackupRecoveryData()
997     {
998         log.println("restore backup recovery data...");
999         try{
1000             rt.copyRecoveryData(false);
1001         }catch (com.sun.star.io.IOException e){
1002             failed("could not copy recovery data: " + e.toString());
1003         }catch (java.io.IOException e){
1004             failed("could not copy recovery data: " + e.toString());
1005         }
1006     }
1007 
cleanRecoveryData()1008     private void cleanRecoveryData(){
1009         try{
1010             log.println("bootstrapping the office to get user path to remove old recovery data...");
1011 
1012             rt.cleanRecoveryData();
1013 
1014         } catch (com.sun.star.io.IOException e){
1015             failed("could not clean recovery data: " + e.toString());
1016         }
1017     }
1018 }
1019