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.loadAllDocuments;
25 
26 import com.sun.star.beans.PropertyValue;
27 import com.sun.star.frame.FrameSearchFlag;
28 import com.sun.star.frame.XComponentLoader;
29 import com.sun.star.frame.XFrame;
30 import com.sun.star.frame.XStorable;
31 import com.sun.star.io.XInputStream;
32 import com.sun.star.lang.XComponent;
33 import com.sun.star.lang.XMultiServiceFactory;
34 import com.sun.star.uno.UnoRuntime;
35 import com.sun.star.util.XCloseable;
36 import com.sun.star.ucb.XSimpleFileAccess;
37 
38 
39 import helper.URLHelper;
40 
41 import java.io.File;
42 import java.io.InputStreamReader;
43 
44 import java.util.Enumeration;
45 import java.util.Vector;
46 
47 // ---------- junit imports -----------------
48 import org.junit.After;
49 import org.junit.AfterClass;
50 import org.junit.Before;
51 import org.junit.BeforeClass;
52 import org.junit.Test;
53 import org.openoffice.test.OfficeConnection;
54 import org.openoffice.test.OfficeFileUrl;
55 import static org.junit.Assert.*;
56 // ------------------------------------------
57 
58 //-----------------------------------------------
59 /** @short  Check the interface method XComponentLoader.loadComponentFromURL()
60 
61     @descr  A prerequisite for this test is a server which allows access to files
62             that will be loaded via three different access methods:
63             <ul>
64                 <li>1. nfs (mounted directory / mapped network drive)</li>
65                 <li>2. ftp</li>
66                 <li>3. http</li>
67             </ul>
68             <p>
69             The test will look for a list of files from the <i>TestDocumentPath</i>
70             on and load these files from the mounted directory, via ftp and http.
71             The parameters for this have to be "ftp_access" and "http_access".
72             If they are not given, tests for ftp and http will fail.
73 
74     @todo   We need a further test for accessing UNC paths on windows!
75  */
76 public class CheckXComponentLoader
77 {
78     //-------------------------------------------
79     // some const
80 
81     /** used to classify the result of a loadComponentFromURL() request. */
82     private static final int RESULT_UNKNOWN                  = 0;
83     private static final int RESULT_VALID_DOC                = 1;
84     private static final int RESULT_EMPTY_DOC                = 2;
85     private static final int RESULT_ILLEGALARGUMENTEXCEPTION = 3;
86     private static final int RESULT_IOEXCEPTION              = 4;
87     private static final int RESULT_RUNTIMEEXCEPTION         = 5;
88     private static final int RESULT_EXCEPTION                = 6;
89 
90     /** File/URL separators. */
91     private static final String fs_url = "/";
92     // private static final String fs_sys = System.getProperty("file.separator");
93 
94     /** used for testing password protected files. */
95     private static final String SUFFIX_PASSWORD_TEMPFILE = "password_";
96     private static final String PREFIX_PASSWORD_TEMPFILE = ".sxw";
97     private static final String DEFAULT_PASSWORD         = "DefaultPasswordForComponentLoaderTest";
98 
99     //-------------------------------------------
100     // member
101 
102     /** points to the global uno service manager. */
103     private XMultiServiceFactory m_xMSF = null;
104 
105     /** provides XComponentLoader interface. */
106     private XFrame m_xDesktop = null;
107 
108     /** provides XComponentLoader interface too. */
109     private XFrame m_xFrame = null;
110 
111     /** will be set to xDesktop OR xFrame. */
112     private XComponentLoader m_xLoader = null;
113 
114     /** can be used to open local files as stream. */
115     private XSimpleFileAccess m_xStreamProvider = null;
116 
117     /** directory for creating temp. files. */
118     private String m_sTempPath = null;
119 
120     /** directory for searching files to load */
121     private String m_sTestDocPath = null;
122 
123     /** files of m_sTestDocPath to test. */
124     private static Vector m_lTestFiles = null;
125 
126     //-------------------------------------------
127     // test environment
128 
129     //-------------------------------------------
130     /** @short  A function to tell the framework,
131                 which test functions are available.
132 
133         @return All test methods.
134         @todo   Think about selection of tests from outside ...
135      */
136 //    public String[] getTestMethodNames()
137 //    {
138 //        // TODO think about trigger of sub-tests from outside
139 //        return new String[]
140 //        {
141 //            "checkURLEncoding"           ,
142 //            "checkURLHandling"           ,
143 //            "checkUsingOfMediaDescriptor",
144 //            "checkStreamLoading"         ,
145 //            "checkLoadingWithPassword"
146 //        };
147 //    }
148 
149     //-------------------------------------------
150     /** @short  Create the environment for following tests.
151 
152         @descr  Use either a component loader from desktop or
153                 from frame
154      */
before()155     @Before public void before()
156     {
157         // get uno service manager from global test environment
158         m_xMSF = getMSF();
159 
160         // create stream provider
161         try
162         {
163             m_xStreamProvider = UnoRuntime.queryInterface(XSimpleFileAccess.class, m_xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess"));
164         }
165         catch(java.lang.Throwable ex)
166         {
167             fail("Could not create a stream provider instance.");
168         }
169 
170         // create desktop instance
171         try
172         {
173             m_xDesktop = UnoRuntime.queryInterface(XFrame.class, m_xMSF.createInstance("com.sun.star.frame.Desktop"));
174         }
175         catch(java.lang.Throwable ex)
176         {
177             fail("Could not create the desktop instance.");
178         }
179 
180         // create frame instance
181         m_xFrame = m_xDesktop.findFrame("testFrame_componentLoader",
182                                         FrameSearchFlag.TASKS | FrameSearchFlag.CREATE);
183         assertNotNull("Couldn't create test frame.", m_xFrame);
184 
185         // define default loader for testing
186         // TODO think about using of bot loader instances!
187         m_xLoader = UnoRuntime.queryInterface(XComponentLoader.class, m_xDesktop);
188         assertNotNull("Desktop service doesn't support needed component loader interface.", m_xLoader);
189 
190         // get temp path for this environment
191         final String tempDirURL = util.utils.getOfficeTemp/*Dir*/(getMSF());
192         m_sTempPath = graphical.FileHelper.getSystemPathFromFileURL(tempDirURL);
193         // m_sTempPath = "."+fs_sys;
194 
195         // get all files from the given directory
196         // TODO URLHelper should ignore directories!
197         m_lTestFiles = new Vector();
198         final String sTestDocURL = OfficeFileUrl.getAbsolute(new File("testdocuments"));
199         m_sTestDocPath = graphical.FileHelper.getSystemPathFromFileURL(sTestDocURL);
200         try
201         {
202             File        aBaseDir        = new File(m_sTestDocPath);
203             Vector      lDirContent     = URLHelper.getSystemFilesFromDir(aBaseDir.getPath());
204             Enumeration lList           = lDirContent.elements();
205             int         nBasePathLength = m_sTestDocPath.length();
206             while(lList.hasMoreElements())
207             {
208                 File aFile = (File)lList.nextElement();
209 
210                 // ignore broken links and directories at all
211                 if (
212                     (!aFile.exists()) ||
213                     (!aFile.isFile())
214                    )
215                 {
216                     continue;
217                 }
218 
219                 String sCompletePath = aFile.getAbsolutePath();
220                 String sSubPath      = sCompletePath.substring(nBasePathLength);
221 
222                 // Some test files are checked into CVS. ignore CVS  helper files!
223 //                if (sSubPath.indexOf("CVS") > -1)
224 //                {
225 //                    continue;
226 //                }
227 
228                 m_lTestFiles.add(sSubPath);
229             }
230         }
231         catch(java.lang.Throwable ex)
232         {
233             fail("Couldn't find test documents.");
234         }
235     }
236 
237     //-------------------------------------------
238     /** @short  close the environment.
239      */
after()240     @After public void after()
241     {
242         XCloseable xClose = UnoRuntime.queryInterface(XCloseable.class, m_xFrame);
243         try
244         {
245             xClose.close(false);
246         }
247         catch(com.sun.star.util.CloseVetoException exVeto)
248             { fail("Test frame couldn't be closed successfully."); }
249 
250         m_xFrame  = null;
251         m_xLoader = null;
252     }
253 
254     //-------------------------------------------
255     /** @short  Look for files in the given directory for loading.
256      */
checkUsingOfMediaDescriptor()257     @Test public void checkUsingOfMediaDescriptor()
258     {
259         InteractionHandler xHandler   = new InteractionHandler();
260         StatusIndicator    xIndicator = new StatusIndicator(StatusIndicator.SHOWSTATUS_LOG);
261 
262         PropertyValue[] lProps = new PropertyValue[3];
263 
264         lProps[0] = new PropertyValue();
265         lProps[0].Name  = "Hidden";
266         lProps[0].Value = Boolean.TRUE;
267 
268         lProps[1] = new PropertyValue();
269         lProps[1].Name  = "InteractionHandler";
270         lProps[1].Value = xHandler;
271 
272         lProps[2] = new PropertyValue();
273         lProps[2].Name  = "StatusIndicator";
274         lProps[2].Value = xIndicator;
275 
276         Enumeration aSnapshot = m_lTestFiles.elements();
277         while (aSnapshot.hasMoreElements())
278         {
279             File   aSysFile = new File(m_sTestDocPath, (String)aSnapshot.nextElement());
280             String sURL     = URLHelper.getFileURLFromSystemPath(aSysFile);
281 
282             if (/*! (sURL.endsWith(".jpg") ||
283                    sURL.endsWith(".gif"))*/
284                     true
285                   )
286             {
287                 loadURL(m_xLoader, RESULT_VALID_DOC, sURL, "_blank", 0, lProps);
288                 // It's not needed to reset this using states!
289                 // It's done internally ...
290                 if (!xIndicator.wasUsed())
291                 {
292                     System.out.println("External progress was not used for loading.");
293                 }
294                 if (xHandler.wasUsed())
295                 {
296                     System.out.println("External interaction handler was not used for loading.");
297                 }
298             }
299         }
300     }
301 
302     //-------------------------------------------
303     /** TODO document me and move this method to a more global helper! */
impl_getTempFileName(String sTempPath, String sSuffix , String sPrefix )304     private String impl_getTempFileName(String sTempPath,
305                                         String sSuffix  ,
306                                         String sPrefix  )
307     {
308         File aDir = new File(sTempPath);
309         aDir.mkdirs();
310 //        if (!aDir.exists())
311 //        {
312 //            fail("Could not access temp directory \"" + sTempPath + "\".");
313 //        }
314 
315     // TODO: create a temp file which not exist!
316         for (int i=0; i<999999; ++i)
317         {
318             File aTempFile = new File(aDir, sSuffix+i+sPrefix);
319             if (!aTempFile.exists())
320             {
321                 return aTempFile.getAbsolutePath();
322             }
323         }
324 
325         fail("Seems that all temp file names are currently in use!");
326         return null;
327     }
328 
329     //-------------------------------------------
330     /** TODO document me and move this method to a more global helper! */
impl_createTempOfficeDocument(XComponentLoader xLoader , String sSourceURL, String sTargetURL, String sFilter , String sPassword )331     private void impl_createTempOfficeDocument(XComponentLoader xLoader   ,
332                                                String           sSourceURL,
333                                                String           sTargetURL,
334                                                String           sFilter   ,
335                                                String           sPassword )
336     {
337         PropertyValue[] lLoadProps = new PropertyValue[1];
338 
339         lLoadProps[0] = new PropertyValue();
340         lLoadProps[0].Name = "Hidden";
341         lLoadProps[0].Value = Boolean.TRUE;
342 
343         PropertyValue[] lSaveProps = new PropertyValue[3];
344 
345         lSaveProps[0] = new PropertyValue();
346         lSaveProps[0].Name = "FilterName";
347         lSaveProps[0].Value = sFilter;
348 
349         lSaveProps[1] = new PropertyValue();
350         lSaveProps[1].Name = "PassWord";
351         lSaveProps[1].Value = sPassword;
352 
353         lSaveProps[2] = new PropertyValue();
354         lSaveProps[2].Name = "Overwrite";
355         lSaveProps[2].Value = Boolean.TRUE;
356 
357         XComponent xDoc = null;
358         try
359         {
360             // load it
361             xDoc = xLoader.loadComponentFromURL(sSourceURL, "_blank", 0, lLoadProps);
362             assertNotNull("Could create office document, which should be saved as temp one.", xDoc);
363 
364             // save it as temp file
365             XStorable xStore = UnoRuntime.queryInterface(XStorable.class, xDoc);
366             xStore.storeAsURL(sTargetURL, lSaveProps);
367 
368             // Dont forget to close this file. Otherwise the temp file is locked!
369             XCloseable xClose = UnoRuntime.queryInterface(XCloseable.class, xDoc);
370             xClose.close(false);
371         }
372         catch(java.lang.Throwable ex)
373         {
374             fail("Could not create temp office document.");
375         }
376     }
377 
378     //-------------------------------------------
379     /** @short  Check the password handling.
380 
381         @descr  The used password is the one given
382                 as password for the ftp connection,
383                 or - if none given a default one.
384      */
checkLoadingWithPassword()385     @Test public void checkLoadingWithPassword()
386     {
387         String sTempFile = impl_getTempFileName(m_sTempPath, SUFFIX_PASSWORD_TEMPFILE, PREFIX_PASSWORD_TEMPFILE);
388         File   aTestFile = new File(sTempFile);
389         String sTestURL  = URLHelper.getFileURLFromSystemPath(aTestFile);
390 
391         impl_createTempOfficeDocument(m_xLoader, "private:factory/swriter", sTestURL, "StarOffice XML (Writer)", DEFAULT_PASSWORD);
392 
393         PropertyValue[] lArgs1 = new PropertyValue[2];
394 
395         lArgs1[0] = new PropertyValue();
396         lArgs1[0].Name  = "Hidden";
397         lArgs1[0].Value = Boolean.TRUE;
398 
399         lArgs1[1] = new PropertyValue();
400         lArgs1[1].Name  = "Password";
401         lArgs1[1].Value = DEFAULT_PASSWORD;
402 
403         PropertyValue[] lArgs2 = new PropertyValue[1];
404 
405         lArgs2[0] = new PropertyValue();
406         lArgs2[0].Name  = "Hidden";
407         lArgs2[0].Value = Boolean.TRUE;
408 
409         loadURL(m_xLoader, RESULT_VALID_DOC, sTestURL, "_blank", 0, lArgs1);
410 // TODO: wrong?        loadURL(m_xLoader, RESULT_EMPTY_DOC, sTestURL, "_blank", 0, lArgs2);
411     }
412 
413     /**
414      * Check URL encoding. The first filename that matches "*.sxw"
415      * is used as source for several encodings.
416      */
checkURLEncoding()417     @Test public void checkURLEncoding() {
418         PropertyValue[] lProps = new PropertyValue[1];
419 
420         lProps[0] = new PropertyValue();
421         lProps[0].Name = "Hidden";
422         lProps[0].Value = Boolean.TRUE;
423 
424         // first get encoding of this system
425         InputStreamReader in = new InputStreamReader(System.in);
426         String sSystemEncoding = in.getEncoding();
427 
428         System.out.println("This system's encoding: " + sSystemEncoding);
429 
430         assertNotNull("Found an empty directory. There are no files for testing.", m_lTestFiles);
431 
432 
433         // get a file name as byte array
434         Enumeration aSnapshot = m_lTestFiles.elements();
435         byte[] baURL = null;
436 
437         while (aSnapshot.hasMoreElements()) {
438             File aFile = new File(m_sTestDocPath, (String)aSnapshot.nextElement());
439             String sFile = URLHelper.getFileURLFromSystemPath(aFile);
440 
441             // take the first sxw file as stream
442             if (sFile.endsWith(".sxw")) {
443                 baURL = sFile.getBytes();
444 
445                 break;
446             }
447         }
448 
449         assertNotNull("Found no file to load. Cannot test.", baURL);
450 
451         //construct several different encoded strings
452         String[] sEncoding = new String[] {
453             "US-ASCII", "TRUE", // us ascii encoding
454             "ISO-8859-1", "TRUE", // iso encoding
455             "UTF-8", "TRUE", // 8 bit utf encoding
456             "UTF-16BE", "FALSE", // 16 bit big endian utf
457             "UTF-16LE", "FALSE", // 16 bit little endian utf
458             "UTF-16", "FALSE" // 16 bit, order specified by byte order mark
459 
460         };
461 
462         for (int i = 0; i < sEncoding.length; i = i + 2) {
463             try {
464                 String encURL = new String(baURL, sEncoding[i]);
465                 System.out.println("ENC[" + sEncoding[i] + "]");
466 
467                 if (sEncoding[i + 1].equals("TRUE")) {
468                     loadURL(m_xLoader, RESULT_VALID_DOC, encURL, "_blank", 0,
469                             lProps);
470                 } else {
471                     //with cws_loadenv01 changed to IllegalArgumentException
472                     loadURL(m_xLoader, RESULT_ILLEGALARGUMENTEXCEPTION, encURL, "_blank", 0,
473                             lProps);
474                 }
475             } catch (java.io.UnsupportedEncodingException e) {
476                 fail("Unsopported Encoding: " + sEncoding[i] +
477                        "\n Not able to test encoding on this platform.");
478             }
479         }
480     }
481 
482     /**
483      * Check url handling with a load of URLs.
484      * 1. unsupported URLs.
485      * 2. "stupid" URLs
486      * 3. case sensitive URLs
487      * 4. FTP URLs
488      * 5. HTTP URLs
489      */
490 //    public void checkURLHandling() {
491 //        PropertyValue[] lProps = new PropertyValue[1];
492 //
493 //        lProps[0] = new PropertyValue();
494 //        lProps[0].Name = "Hidden";
495 //        lProps[0].Value = Boolean.TRUE;
496 //
497 //        System.out.println("check possible but unsupported URLs");
498 //
499 //        String[] sIllegalArgs = new String[] {
500 //            "slot:5000", "slot:10909", ".uno:SaveAs", ".uno:Open",
501 //        };
502 //        loadURL(m_xLoader, RESULT_ILLEGALARGUMENTEXCEPTION, sIllegalArgs,
503 //                "_blank", 0, lProps);
504 //
505 //        System.out.println("check stupid URLs");
506 //
507 //        sIllegalArgs = new String[] {
508 //            "slot:xxx", "slot:111111111", ".uno:save_as", ".uno:open_this",
509 //            ".UnO:*",
510 //        };
511 //        loadURL(m_xLoader, RESULT_ILLEGALARGUMENTEXCEPTION, sIllegalArgs,
512 //                "_blank", 0, lProps);
513 //
514 //        String[] sEmptyDocs = new String[] {
515 //            "mailo:hansi.meier@germany.sun.com", "file:/c:\\test/file.cxx",
516 //            "file:///c|:\\test/file.cxx", "http_server://staroffice-doc\\",
517 //            "c:\\\\test///\\test.sxw", "news_:staroffice-doc",
518 //            "newsletter@blubber", "private_factory/swriter",
519 //            "private:factory//swriter", "private:factory/swriter/___",
520 //            "c:\\test\\test.sxw", "macro:///ImportWizard.Main.Main",
521 //            "macro:///Euro.AutoPilotRun.StartAutoPilot",
522 //            "service:com.sun.star.frame.Frame",
523 //            "mailto:steffen.grund@germany.sun.com", "news:staroffice-doc",
524 //            "macro:/ExportWizard", "macro://Euro.AutoPilotRun.StartAutoPilot",
525 //            "service:com.sun.star.frame."
526 //        };
527 //
528 //        //with cws_loadenv01 changed to IllegalArgumentException
529 //        loadURL(m_xLoader, RESULT_ILLEGALARGUMENTEXCEPTION, sEmptyDocs, "_blank", 0,
530 //                lProps);
531 //
532 //        System.out.println("check case sensitive URLs");
533 //
534 //        sIllegalArgs = new String[] {
535 //            "sLot:5000", "sloT:10909", ".unO:SaveAs", ".uno:OPEN",
536 //        };
537 //        loadURL(m_xLoader, RESULT_ILLEGALARGUMENTEXCEPTION, sIllegalArgs,
538 //                "_blank", 0, lProps);
539 //
540 //        sEmptyDocs = new String[] {
541 //            "private:factory/SWRITER", "private:factory/SWRITER/WEB",
542 //            "macro:///importwizard.main.main",
543 //            "Macro:///euro.autopilotrun.startautopilot",
544 //            "Service:Com.Sun.Star.Frame.Frame",
545 //            "Mailto:andreas.schluens@germany.sun.com", "neWs:staroffice-doc",
546 //            "News:Staroffice-doc"
547 //        };
548 //
549 //        //with cws_loadenv01 changed to IllegalArgumentException
550 //        loadURL(m_xLoader, RESULT_ILLEGALARGUMENTEXCEPTION, sEmptyDocs, "_blank", 0,
551 //                lProps);
552 //
553 //        System.out.println("check FTP URLs");
554 //
555 //        String sFTPURL = (String) param.get("FtpAccess");
556 //        Enumeration aSnapshot = m_lTestFiles.elements();
557 //
558 //        while (aSnapshot.hasMoreElements()) {
559 //            String doc = (String) aSnapshot.nextElement();
560 //
561 //
562 //            // if os is windows
563 //            doc = doc.replace('\\', '/');
564 //	    if (doc.indexOf("CVS")<0) {
565 //		    loadURL(m_xLoader, RESULT_VALID_DOC, sFTPURL + "/" + doc,
566 //                    "_blank", 0, lProps);
567 //	    }
568 //        }
569 //
570 //        System.out.println("check HTTP URLs");
571 //
572 //        String sHTTPURL = (String) param.get("HttpAccess");
573 //        aSnapshot = m_lTestFiles.elements();
574 //
575 //        while (aSnapshot.hasMoreElements()) {
576 //            String doc = (String) aSnapshot.nextElement();
577 //
578 //
579 //            // if os is windows
580 //            doc = doc.replace('\\', '/');
581 //	    if (doc.indexOf("CVS")<0) {
582 //		    loadURL(m_xLoader, RESULT_VALID_DOC, sHTTPURL + "/" + doc,
583 //                    "_blank", 0, lProps);
584 //	    }
585 //        }
586 //    }
587 
588     /** TODo document me
589      */
checkStreamLoading()590     @Test public void checkStreamLoading()
591     {
592         PropertyValue[] lProps = new PropertyValue[2];
593 
594         lProps[0] = new PropertyValue();
595         lProps[0].Name = "Hidden";
596         lProps[0].Value = Boolean.TRUE;
597 
598         lProps[1] = new PropertyValue();
599         lProps[1].Name = "InputStream";
600 
601         Enumeration aSnapshot = m_lTestFiles.elements();
602         while (aSnapshot.hasMoreElements())
603         {
604             File   aFile = new File(m_sTestDocPath, (String) aSnapshot.nextElement());
605             String sURL  = URLHelper.getFileURLFromSystemPath(aFile);
606 
607 //            if (sURL.indexOf("CVS") > -1)
608 //            {
609 //                continue;
610 //            }
611 
612             try
613             {
614                 XInputStream xStream = m_xStreamProvider.openFileRead(sURL);
615                 lProps[1].Value = xStream;
616             }
617             catch(com.sun.star.uno.Exception e)
618             {
619                 fail("Could not open test file \""+sURL+"\" for stream test.");
620             }
621 
622             // check different version of "private:stream" URL!
623             loadURL(m_xLoader, RESULT_VALID_DOC, "private:stream" , "_blank", 0, lProps);
624             // loadURL(m_xLoader, RESULT_VALID_DOC, "private:stream" , "_blank", 0, lProps);
625             // loadURL(m_xLoader, RESULT_VALID_DOC, "private:stream/", "_blank", 0, lProps);
626 	}
627     }
628 
629     /**
630      * Loads one URL with the given parameters using the method
631      * loadComponentFromURL(). Further it's possible to specify, whch result is
632      * required and we check internally if it was reached. Logging of errors
633      * and success stories is done inside this method too. Of course we catch
634      * all possible exceptions and try to leave the office without any forgotten
635      * but opened documents.
636      */
loadURL(XComponentLoader m_xLoader, int nRequiredResult, String sURL, String sTarget, int nFlags, PropertyValue[] lProps)637     private void loadURL(XComponentLoader m_xLoader, int nRequiredResult,
638                          String sURL, String sTarget, int nFlags,
639                          PropertyValue[] lProps) {
640         int nResult = RESULT_EMPTY_DOC;
641         XComponent xDoc = null;
642 
643         try {
644             xDoc = m_xLoader.loadComponentFromURL(sURL, sTarget, nFlags,
645                                                      lProps);
646 
647             if (xDoc != null) {
648                 nResult = RESULT_VALID_DOC;
649             } else {
650                 nResult = RESULT_EMPTY_DOC;
651             }
652         } catch (com.sun.star.lang.IllegalArgumentException exArgument) {
653             nResult = RESULT_ILLEGALARGUMENTEXCEPTION;
654         } catch (com.sun.star.io.IOException exIO) {
655             nResult = RESULT_IOEXCEPTION;
656         } catch (com.sun.star.uno.RuntimeException exRuntime) {
657             nResult = RESULT_RUNTIMEEXCEPTION;
658         } catch (Exception e) {
659             nResult = RESULT_EXCEPTION;
660         }
661 
662         try {
663             if (xDoc != null) {
664                 xDoc.dispose();
665                 xDoc = null;
666             }
667         } catch (com.sun.star.uno.RuntimeException exClosing) {
668             System.out.println("exception during disposing of a document found!" +
669                         " Doesn't influence test - but should be checked.");
670         }
671 
672         String sMessage = "URL[\"" + sURL + "\"]";
673 
674         if (nResult == nRequiredResult) {
675             System.out.println(sMessage + " expected result [" +
676                         convertResult2String(nResult) + "] ");
677         } else {
678             fail(sMessage + " unexpected result [" +
679                    convertResult2String(nResult) + "] " +
680                    "\nrequired was [" +
681                    convertResult2String(nRequiredResult) + "]" +
682                    "\nwe got       [" + convertResult2String(nResult) + "]"
683                    );
684         }
685     }
686 
loadURL(XComponentLoader m_xLoader, int nRequiredResult, String[] sURL, String sTarget, int nFlags, PropertyValue[] lProps)687     private void loadURL(XComponentLoader m_xLoader, int nRequiredResult,
688                          String[] sURL, String sTarget, int nFlags,
689                          PropertyValue[] lProps) {
690         for (int i = 0; i < sURL.length; i++)
691         {
692             loadURL(m_xLoader, nRequiredResult, sURL[i], sTarget, nFlags, lProps);
693         }
694     }
695 
696     /**
697      * it match the int result value to a string, which can be used for logging
698      */
convertResult2String(int nResult)699     private static String convertResult2String(int nResult) {
700         switch (nResult) {
701         case RESULT_VALID_DOC:
702             return "VALID_DOC";
703 
704         case RESULT_EMPTY_DOC:
705             return "EMPTY_DOC";
706 
707         case RESULT_ILLEGALARGUMENTEXCEPTION:
708             return "ILLEGALARGUMENTEXCEPTION";
709 
710         case RESULT_IOEXCEPTION:
711             return "IOEXCEPTION";
712 
713         case RESULT_RUNTIMEEXCEPTION:
714             return "RUNTIMEEXCEPTION";
715 
716         case RESULT_EXCEPTION:
717             return "ALLOTHEREXCEPTION";
718         }
719 
720         return "unknown!";
721     }
722 
getMSF()723     private XMultiServiceFactory getMSF()
724     {
725         final XMultiServiceFactory xMSF1 = UnoRuntime.queryInterface(XMultiServiceFactory.class, connection.getComponentContext().getServiceManager());
726         return xMSF1;
727     }
728 
729     // setup and close connections
730     @BeforeClass
setUpConnection()731     public static void setUpConnection() throws Exception
732     {
733         System.out.println("setUpConnection()");
734         connection.setUp();
735     }
736 
737     @AfterClass
tearDownConnection()738     public static void tearDownConnection()
739             throws InterruptedException, com.sun.star.uno.Exception
740     {
741         System.out.println("tearDownConnection()");
742         connection.tearDown();
743     }
744     private static final OfficeConnection connection = new OfficeConnection();
745 
746 }
747