Branch libreoffice-5-0-4
[LibreOffice.git] / framework / qa / complex / loadAllDocuments / CheckXComponentLoader.java
blobda3b57a1c0962de934a19d71d91c2b0ad3f90588
1 /*
2 * This file is part of the LibreOffice project.
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 * This file incorporates work covered by the following license notice:
10 * Licensed to the Apache Software Foundation (ASF) under one or more
11 * contributor license agreements. See the NOTICE file distributed
12 * with this work for additional information regarding copyright
13 * ownership. The ASF licenses this file to you under the Apache
14 * License, Version 2.0 (the "License"); you may not use this file
15 * except in compliance with the License. You may obtain a copy of
16 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
19 package complex.loadAllDocuments;
21 import static org.junit.Assert.assertNotNull;
22 import static org.junit.Assert.fail;
23 import helper.URLHelper;
25 import java.io.File;
26 import java.io.InputStreamReader;
27 import java.util.ArrayList;
28 import java.util.Iterator;
29 import java.util.List;
31 import org.junit.After;
32 import org.junit.AfterClass;
33 import org.junit.Before;
34 import org.junit.BeforeClass;
35 import org.junit.Test;
36 import org.openoffice.test.OfficeConnection;
37 import org.openoffice.test.OfficeFileUrl;
39 import com.sun.star.beans.PropertyValue;
40 import com.sun.star.frame.FrameSearchFlag;
41 import com.sun.star.frame.XComponentLoader;
42 import com.sun.star.frame.XFrame;
43 import com.sun.star.frame.XStorable;
44 import com.sun.star.io.XInputStream;
45 import com.sun.star.lang.XComponent;
46 import com.sun.star.lang.XMultiServiceFactory;
47 import com.sun.star.ucb.XSimpleFileAccess;
48 import com.sun.star.uno.UnoRuntime;
49 import com.sun.star.util.XCloseable;
52 /** @short Check the interface method XComponentLoader.loadComponentFromURL()
54 @descr A prerequisite for this test is a server which allows access to files
55 that will be loaded via three different access methods:
56 <ul>
57 <li>1. nfs (mounted directory / mapped network drive)</li>
58 <li>2. ftp</li>
59 <li>3. http</li>
60 </ul>
61 <p>
62 The test will look for a list of files from the <i>TestDocumentPath</i>
63 on and load these files from the mounted directory, via ftp and http.
64 The parameters for this have to be "ftp_access" and "http_access".
65 If they are not given, tests for ftp and http will fail.
67 @todo We need a further test for accessing UNC paths on windows!
69 public class CheckXComponentLoader
72 // some const
74 /** used to classify the result of a loadComponentFromURL() request. */
75 private static final int RESULT_VALID_DOC = 1;
76 private static final int RESULT_EMPTY_DOC = 2;
77 private static final int RESULT_ILLEGALARGUMENTEXCEPTION = 3;
78 private static final int RESULT_IOEXCEPTION = 4;
79 private static final int RESULT_RUNTIMEEXCEPTION = 5;
80 private static final int RESULT_EXCEPTION = 6;
82 /** used for testing password protected files. */
83 private static final String SUFFIX_PASSWORD_TEMPFILE = "password_";
84 private static final String PREFIX_PASSWORD_TEMPFILE = ".sxw";
85 private static final String DEFAULT_PASSWORD = "DefaultPasswordForComponentLoaderTest";
88 // member
90 /** provides XComponentLoader interface too. */
91 private XFrame m_xFrame = null;
93 /** will be set to xDesktop OR xFrame. */
94 private XComponentLoader m_xLoader = null;
96 /** can be used to open local files as stream. */
97 private XSimpleFileAccess m_xStreamProvider = null;
99 /** directory for creating temp. files. */
100 private String m_sTempPath = null;
102 /** directory for searching files to load */
103 private String m_sTestDocPath = null;
105 /** files of m_sTestDocPath to test. */
106 private static ArrayList<String> m_lTestFiles = null;
109 // test environment
112 /** @short Create the environment for following tests.
114 @descr Use either a component loader from desktop or
115 from frame
117 @Before public void before()
119 // get uno service manager from global test environment
120 /* points to the global uno service manager. */
121 XMultiServiceFactory xMSF = getMSF();
123 // create stream provider
126 m_xStreamProvider = UnoRuntime.queryInterface(XSimpleFileAccess.class, xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess"));
128 catch(java.lang.Throwable ex)
130 fail("Could not create a stream provider instance.");
133 // create desktop instance
134 /* provides XComponentLoader interface. */
135 XFrame xDesktop = null;
138 xDesktop = UnoRuntime.queryInterface(XFrame.class, xMSF.createInstance("com.sun.star.frame.Desktop"));
140 catch(java.lang.Throwable ex)
142 fail("Could not create the desktop instance.");
145 // create frame instance
146 m_xFrame = xDesktop.findFrame("testFrame_componentLoader",
147 FrameSearchFlag.TASKS | FrameSearchFlag.CREATE);
148 assertNotNull("Couldn't create test frame.", m_xFrame);
150 // define default loader for testing
151 // TODO think about using of bot loader instances!
152 m_xLoader = UnoRuntime.queryInterface(XComponentLoader.class, xDesktop);
153 assertNotNull("Desktop service doesn't support needed component loader interface.", m_xLoader);
155 // get temp path for this environment
156 final String tempDirURL = util.utils.getOfficeTemp/*Dir*/(getMSF());
157 m_sTempPath = graphical.FileHelper.getSystemPathFromFileURL(tempDirURL);
158 // m_sTempPath = "."+fs_sys;
160 // get all files from the given directory
161 // TODO URLHelper should ignore directories!
162 m_lTestFiles = new ArrayList<String>();
163 final String sTestDocURL = OfficeFileUrl.getAbsolute(new File("testdocuments"));
164 m_sTestDocPath = graphical.FileHelper.getSystemPathFromFileURL(sTestDocURL);
167 File aBaseDir = new File(m_sTestDocPath);
168 List<File> lDirContent = URLHelper.getSystemFilesFromDir(aBaseDir.getPath());
169 Iterator<File> lList = lDirContent.iterator();
170 int nBasePathLength = m_sTestDocPath.length();
171 while(lList.hasNext())
173 File aFile = lList.next();
175 // ignore broken links and directories at all
176 if (
177 (!aFile.exists()) ||
178 (!aFile.isFile())
181 continue;
184 String sCompletePath = aFile.getAbsolutePath();
185 String sSubPath = sCompletePath.substring(nBasePathLength);
187 m_lTestFiles.add(sSubPath);
190 catch(java.lang.Throwable ex)
192 fail("Couldn't find test documents.");
197 /** @short close the environment.
199 @After public void after()
201 XCloseable xClose = UnoRuntime.queryInterface(XCloseable.class, m_xFrame);
204 xClose.close(false);
206 catch(com.sun.star.util.CloseVetoException exVeto)
207 { fail("Test frame couldn't be closed successfully."); }
209 m_xFrame = null;
210 m_xLoader = null;
214 /** @short Look for files in the given directory for loading.
216 @Test public void checkUsingOfMediaDescriptor()
218 InteractionHandler xHandler = new InteractionHandler();
219 StatusIndicator xIndicator = new StatusIndicator();
221 PropertyValue[] lProps = new PropertyValue[3];
223 lProps[0] = new PropertyValue();
224 lProps[0].Name = "Hidden";
225 lProps[0].Value = Boolean.TRUE;
227 lProps[1] = new PropertyValue();
228 lProps[1].Name = "InteractionHandler";
229 lProps[1].Value = xHandler;
231 lProps[2] = new PropertyValue();
232 lProps[2].Name = "StatusIndicator";
233 lProps[2].Value = xIndicator;
235 Iterator<String> aSnapshot = m_lTestFiles.iterator();
236 while (aSnapshot.hasNext())
238 File aSysFile = new File(m_sTestDocPath, aSnapshot.next());
239 String sURL = URLHelper.getFileURLFromSystemPath(aSysFile);
241 loadURL(m_xLoader, RESULT_VALID_DOC, sURL, "_blank", 0, lProps);
242 // Its not needed to reset this using states!
243 // Its done internally ...
244 if (!xIndicator.wasUsed())
246 System.out.println("External progress was not used for loading.");
248 if (xHandler.wasUsed())
250 System.out.println("External interaction handler was not used for loading.");
256 /** TODO document me and move this method to a more global helper! */
257 private String impl_getTempFileName(String sTempPath,
258 String sSuffix ,
259 String sPrefix )
261 File aDir = new File(sTempPath);
262 aDir.mkdirs();
264 // TODO: create a temp file which not exist!
265 for (int i=0; i<999999; ++i)
267 File aTempFile = new File(aDir, sSuffix+i+sPrefix);
268 if (!aTempFile.exists())
270 return aTempFile.getAbsolutePath();
274 fail("Seems that all temp file names are currently in use!");
275 return null;
279 /** TODO document me and move this method to a more global helper! */
280 private void impl_createTempOfficeDocument(XComponentLoader xLoader ,
281 String sSourceURL,
282 String sTargetURL,
283 String sFilter ,
284 String sPassword )
286 PropertyValue[] lLoadProps = new PropertyValue[1];
288 lLoadProps[0] = new PropertyValue();
289 lLoadProps[0].Name = "Hidden";
290 lLoadProps[0].Value = Boolean.TRUE;
292 PropertyValue[] lSaveProps = new PropertyValue[3];
294 lSaveProps[0] = new PropertyValue();
295 lSaveProps[0].Name = "FilterName";
296 lSaveProps[0].Value = sFilter;
298 lSaveProps[1] = new PropertyValue();
299 lSaveProps[1].Name = "PassWord";
300 lSaveProps[1].Value = sPassword;
302 lSaveProps[2] = new PropertyValue();
303 lSaveProps[2].Name = "Overwrite";
304 lSaveProps[2].Value = Boolean.TRUE;
306 XComponent xDoc = null;
309 // load it
310 xDoc = xLoader.loadComponentFromURL(sSourceURL, "_blank", 0, lLoadProps);
311 assertNotNull("Could create office document, which should be saved as temp one.", xDoc);
313 // save it as temp file
314 XStorable xStore = UnoRuntime.queryInterface(XStorable.class, xDoc);
315 xStore.storeAsURL(sTargetURL, lSaveProps);
317 // Dont forget to close this file. Otherwise the temp file is locked!
318 XCloseable xClose = UnoRuntime.queryInterface(XCloseable.class, xDoc);
319 xClose.close(false);
321 catch(java.lang.Throwable ex)
323 fail("Could not create temp office document.");
328 /** @short Check the password handling.
330 @descr The used password is the one given
331 as password for the ftp connection,
332 or - if none given a default one.
334 @Test public void checkLoadingWithPassword()
336 String sTempFile = impl_getTempFileName(m_sTempPath, SUFFIX_PASSWORD_TEMPFILE, PREFIX_PASSWORD_TEMPFILE);
337 File aTestFile = new File(sTempFile);
338 String sTestURL = URLHelper.getFileURLFromSystemPath(aTestFile);
340 impl_createTempOfficeDocument(m_xLoader, "private:factory/swriter", sTestURL, "StarOffice XML (Writer)", DEFAULT_PASSWORD);
342 PropertyValue[] lArgs1 = new PropertyValue[2];
344 lArgs1[0] = new PropertyValue();
345 lArgs1[0].Name = "Hidden";
346 lArgs1[0].Value = Boolean.TRUE;
348 lArgs1[1] = new PropertyValue();
349 lArgs1[1].Name = "Password";
350 lArgs1[1].Value = DEFAULT_PASSWORD;
352 PropertyValue[] lArgs2 = new PropertyValue[1];
354 lArgs2[0] = new PropertyValue();
355 lArgs2[0].Name = "Hidden";
356 lArgs2[0].Value = Boolean.TRUE;
358 loadURL(m_xLoader, RESULT_VALID_DOC, sTestURL, "_blank", 0, lArgs1);
359 // TODO: wrong? loadURL(m_xLoader, RESULT_EMPTY_DOC, sTestURL, "_blank", 0, lArgs2);
363 * Check URL encoding. The first filename that matches "*.sxw"
364 * is used as source for several encodings.
366 @Test public void checkURLEncoding() {
367 PropertyValue[] lProps = new PropertyValue[1];
369 lProps[0] = new PropertyValue();
370 lProps[0].Name = "Hidden";
371 lProps[0].Value = Boolean.TRUE;
373 // first get encoding of this system
374 InputStreamReader in = new InputStreamReader(System.in);
375 String sSystemEncoding = in.getEncoding();
377 System.out.println("This system's encoding: " + sSystemEncoding);
379 assertNotNull("Found an empty directory. There are no files for testing.", m_lTestFiles);
382 // get a file name as byte array
383 Iterator<String> aSnapshot = m_lTestFiles.iterator();
384 byte[] baURL = null;
386 while (aSnapshot.hasNext()) {
387 File aFile = new File(m_sTestDocPath, aSnapshot.next());
388 String sFile = URLHelper.getFileURLFromSystemPath(aFile);
390 // take the first sxw file as stream
391 if (sFile.endsWith(".sxw")) {
392 baURL = sFile.getBytes();
394 break;
398 assertNotNull("Found no file to load. Cannot test.", baURL);
400 //construct several different encoded strings
401 String[] sEncoding = new String[] {
402 "US-ASCII", "TRUE", // us ascii encoding
403 "ISO-8859-1", "TRUE", // iso encoding
404 "UTF-8", "TRUE", // 8 bit utf encoding
405 "UTF-16BE", "FALSE", // 16 bit big endian utf
406 "UTF-16LE", "FALSE", // 16 bit little endian utf
407 "UTF-16", "FALSE" // 16 bit, order specified by byte order mark
411 for (int i = 0; i < sEncoding.length; i = i + 2) {
412 try {
413 String encURL = new String(baURL, sEncoding[i]);
414 System.out.println("ENC[" + sEncoding[i] + "]");
416 if (sEncoding[i + 1].equals("TRUE")) {
417 loadURL(m_xLoader, RESULT_VALID_DOC, encURL, "_blank", 0,
418 lProps);
419 } else {
420 //with cws_loadenv01 changed to IllegalArgumentException
421 loadURL(m_xLoader, RESULT_ILLEGALARGUMENTEXCEPTION, encURL, "_blank", 0,
422 lProps);
424 } catch (java.io.UnsupportedEncodingException e) {
425 fail("Unsopported Encoding: " + sEncoding[i] +
426 "\n Not able to test encoding on this platform.");
431 /** TODo document me
433 @Test public void checkStreamLoading()
435 PropertyValue[] lProps = new PropertyValue[2];
437 lProps[0] = new PropertyValue();
438 lProps[0].Name = "Hidden";
439 lProps[0].Value = Boolean.TRUE;
441 lProps[1] = new PropertyValue();
442 lProps[1].Name = "InputStream";
444 Iterator<String> aSnapshot = m_lTestFiles.iterator();
445 while (aSnapshot.hasNext())
447 File aFile = new File(m_sTestDocPath, aSnapshot.next());
448 String sURL = URLHelper.getFileURLFromSystemPath(aFile);
452 XInputStream xStream = m_xStreamProvider.openFileRead(sURL);
453 lProps[1].Value = xStream;
455 catch(com.sun.star.uno.Exception e)
457 fail("Could not open test file \""+sURL+"\" for stream test.");
460 // check different version of "private:stream" URL!
461 loadURL(m_xLoader, RESULT_VALID_DOC, "private:stream" , "_blank", 0, lProps);
466 * Loads one URL with the given parameters using the method
467 * loadComponentFromURL(). Further it's possible to specify, whch result is
468 * required and we check internally if it was reached. Logging of errors
469 * and success stories is done inside this method too. Of course we catch
470 * all possible exceptions and try to leave the office without any forgotten
471 * but opened documents.
473 private void loadURL(XComponentLoader xLoader, int nRequiredResult,
474 String sURL, String sTarget, int nFlags,
475 PropertyValue[] lProps) {
476 int nResult = RESULT_EMPTY_DOC;
477 XComponent xDoc = null;
479 try {
480 xDoc = xLoader.loadComponentFromURL(sURL, sTarget, nFlags,
481 lProps);
483 if (xDoc != null) {
484 nResult = RESULT_VALID_DOC;
485 } else {
486 nResult = RESULT_EMPTY_DOC;
488 } catch (com.sun.star.lang.IllegalArgumentException exArgument) {
489 nResult = RESULT_ILLEGALARGUMENTEXCEPTION;
490 } catch (com.sun.star.io.IOException exIO) {
491 nResult = RESULT_IOEXCEPTION;
492 } catch (com.sun.star.uno.RuntimeException exRuntime) {
493 nResult = RESULT_RUNTIMEEXCEPTION;
494 } catch (Exception e) {
495 nResult = RESULT_EXCEPTION;
498 try {
499 if (xDoc != null) {
500 xDoc.dispose();
501 xDoc = null;
503 } catch (com.sun.star.uno.RuntimeException exClosing) {
504 System.out.println("exception during disposing of a document found!" +
505 " Doesn't influence test - but should be checked.");
508 String sMessage = "URL[\"" + sURL + "\"]";
510 if (nResult == nRequiredResult) {
511 System.out.println(sMessage + " expected result [" +
512 convertResult2String(nResult) + "] ");
513 } else {
514 fail(sMessage + " unexpected result [" +
515 convertResult2String(nResult) + "] " +
516 "\nrequired was [" +
517 convertResult2String(nRequiredResult) + "]" +
518 "\nwe got [" + convertResult2String(nResult) + "]"
524 * it match the int result value to a string, which can be used for logging
526 private static String convertResult2String(int nResult) {
527 switch (nResult) {
528 case RESULT_VALID_DOC:
529 return "VALID_DOC";
531 case RESULT_EMPTY_DOC:
532 return "EMPTY_DOC";
534 case RESULT_ILLEGALARGUMENTEXCEPTION:
535 return "ILLEGALARGUMENTEXCEPTION";
537 case RESULT_IOEXCEPTION:
538 return "IOEXCEPTION";
540 case RESULT_RUNTIMEEXCEPTION:
541 return "RUNTIMEEXCEPTION";
543 case RESULT_EXCEPTION:
544 return "ALLOTHEREXCEPTION";
547 return "unknown!";
550 private XMultiServiceFactory getMSF()
552 return UnoRuntime.queryInterface(XMultiServiceFactory.class, connection.getComponentContext().getServiceManager());
555 // setup and close connections
556 @BeforeClass
557 public static void setUpConnection() throws Exception
559 System.out.println("setUpConnection()");
560 connection.setUp();
563 @AfterClass
564 public static void tearDownConnection()
565 throws InterruptedException, com.sun.star.uno.Exception
567 System.out.println("tearDownConnection()");
568 connection.tearDown();
570 private static final OfficeConnection connection = new OfficeConnection();