xref: /trunk/test/testuno/source/fvt/uno/ffc/FFCTest.java (revision 45e2f390c041b30a26ca2aee1e99e305783ca105)
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 package fvt.uno.ffc;
21 
22 import java.io.File;
23 import java.io.FilenameFilter;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 
28 import junit.framework.Assert;
29 
30 import org.junit.After;
31 import org.junit.Before;
32 import org.junit.BeforeClass;
33 import org.junit.Rule;
34 import org.junit.Test;
35 import org.junit.runner.RunWith;
36 import org.openoffice.test.OpenOffice;
37 import org.openoffice.test.common.FileProvider;
38 import org.openoffice.test.common.FileProvider.FileRepos;
39 import org.openoffice.test.common.FileUtil;
40 import org.openoffice.test.common.Logger;
41 import org.openoffice.test.common.SystemUtil;
42 import org.openoffice.test.common.Testspace;
43 import org.openoffice.test.uno.UnoApp;
44 
45 import com.sun.star.beans.PropertyValue;
46 import com.sun.star.document.MacroExecMode;
47 import com.sun.star.frame.XComponentLoader;
48 import com.sun.star.frame.XStorable;
49 import com.sun.star.io.IOException;
50 import com.sun.star.lang.IllegalArgumentException;
51 import com.sun.star.lang.XComponent;
52 import com.sun.star.uno.UnoRuntime;
53 /**
54  * Pls place a suite file in directory "suite" which is same level with test uno. like bewlow
55  * -suite
56  * -testuno
57  * The suite file content is like this format
58  * ftp://user:password@192.168.0.1/public/sample/testsample.doc
59  * ..
60  * ..
61  * ftp://user:password@192.168.0.1/public/sample/testsample2.doc
62  *This script is used to test FFC by UNO API
63  *It cover below scenario:
64  *MS2003/2010 format->ODF format
65  *New Saved ODF Format file -> MS 2003 Format
66  *New Saved ODF Format file -> PDF
67  *
68  */
69 @RunWith(FileProvider.class)
70 public class FFCTest {
71     @Rule
72     public Logger log = Logger.getLogger(this, false);
73 
74     private static final UnoApp app = new UnoApp();
75     private static Map<String, String> filterMap = new HashMap<String, String>();
76     @FileRepos
77     public static String suiteDir = "../suite/";
78     private String fileURL = "";
79     private String operateFilePath = "";
80     private static Map<String, String> formatMap = new HashMap<String, String>();
81     private static File testSpaceFile = Testspace.getFile();
82     private boolean isSucceed = false;
83     private static String  tempFolder = testSpaceFile.getAbsolutePath() + File.separator + "temp";
84 
85     private static String failedFilesDir  = "output/failedSampleFiles/";;
86 //  @Parameters
87 //  public static Collection<String[]>  data() throws Exception{
88 //      initMap();
89 //      ArrayList<String[]> list = new ArrayList<String[]>();
90 //      List<String> suitePathList = new ArrayList<String>();
91 //      FileReader fileReader = null;
92 //      BufferedReader reader = null;
93 //      File suites = new File(suiteDir);
94 //      if (suites.exists() && suites.list().length > 0) {
95 //          isSuiteFileExist = true;
96 //          for(File file: suites.listFiles()){
97 //              if(FileUtil.getFileExtName(file.getName()).toLowerCase().equals("suite")){
98 //                  suitePathList.add(file.getAbsolutePath());
99 //              }
100 //          }
101 //          try{
102 //              for (String suitePath : suitePathList) {
103 //                  fileReader = new FileReader(suitePath);
104 //                  reader = new BufferedReader(fileReader);
105 //                  String line = null;
106 //                  while((line = reader.readLine()) != null){
107 //                      if (!"".equals(line)) {
108 //                          list.add(new String[]{line});
109 //                      }
110 //                  }
111 //                  if(reader != null){
112 //                      reader.close();
113 //                      reader = null;
114 //                  }
115 //                  if(fileReader != null){
116 //                      fileReader.close();
117 //                      fileReader = null;
118 //                  }
119 //              }
120 //
121 //          }catch(Exception e){
122 //              throw new Exception("throw exception when read suite file. " + e.getMessage());
123 //          }finally{
124 //              try{
125 //                  if(reader != null){
126 //                      reader.close();
127 //                      reader = null;
128 //                  }
129 //                  if(fileReader != null){
130 //                      fileReader.close();
131 //                      fileReader = null;
132 //                  }
133 //              }catch(Exception io){
134 //              }
135 //          }
136 //      } else {// run files from ffc data directory
137 //          File ffcDataHome = new File("data\\ffc");
138 //          getFileList(ffcDataHome, list);
139 //      }
140 //
141 //      return list;
142 //  }
143 //
144     public static void getFileList(File dir, List<String[]> list) {
145         File[] files = dir.listFiles(new FilenameFilter() {
146             @Override
147             public boolean accept(File dir, String name) {
148                 File file =  new File(dir.getAbsolutePath() + File.separator + name);
149                 String filename = new File(name).getName().toLowerCase();
150                 boolean accept;
151                 if (file.isDirectory()) {
152                     accept = true;
153                 } else {
154                     accept =  filename.endsWith(".docx")
155                     || filename.endsWith(".pptx")
156                     || filename.endsWith(".xlsx")
157                     || filename.endsWith(".ppt")
158                     || filename.endsWith(".xls")
159                     ||  filename.endsWith(".doc") ;
160                 }
161 
162                 return accept;
163             }
164 
165         });
166         if (files == null)
167             return;
168 
169         for (File file : files) {
170             if (file.isDirectory()) {
171                 getFileList(file, list);
172             } else {
173                 list.add(new String[] {file.getAbsolutePath().replace(dir.getParentFile().getAbsolutePath(), "").replace("\\", "/")});
174 
175             }
176         }
177     }
178 
179     public FFCTest(String url) {
180         this.fileURL = url;
181     }
182 
183     @BeforeClass
184     public static void init() {
185         initMap();
186         //Disable automation
187         OpenOffice.getDefault().setAutomationPort(-1);
188         OpenOffice.getDefault().addArgs("-invisible", "-conversionmode", "-headless", "-hidemenu");
189 
190         File failedDirec = Testspace.getFile(failedFilesDir);
191         failedDirec.mkdirs();
192     }
193 
194     @Before
195     public void setUp() throws Exception {
196         operateFilePath =  Testspace.prepareData(fileURL);
197 
198 
199         app.start();
200     }
201     @After
202     public void tearDown() throws Exception {
203         if (!isSucceed) {
204             FileUtil.copyFile(operateFilePath, Testspace.getFile(failedFilesDir).getAbsolutePath());
205             FileUtil.appendStringToFile( Testspace.getFile(failedFilesDir + File.separator + "failedFiles.files").getAbsolutePath(), fileURL +"\r\n");
206             app.close();
207             SystemUtil.killProcess("WerFault.*");
208             SystemUtil.sleep(2);
209             SystemUtil.killProcess("EQNEDT32.*");
210             //WerFault.exe
211             //EQNEDT32.EXE
212         }
213     }
214 
215 
216 
217     @Test(timeout=1000*60*10)
218     public void exportTest() throws Exception {
219         //MS Office Format ->ODF
220         boolean flag = false;
221 
222         String saveAsODF = exportAsODF(operateFilePath);
223         System.out.println("MS ->ODF finished");
224         //ODF->MS
225         String savedMSFilePath = exportAsODF(saveAsODF);
226         File savedMSFile = new File(savedMSFilePath);
227         Assert.assertTrue("FFC Test for file : "+ savedMSFilePath, savedMSFile.exists());
228         System.out.println("ODF->MS Finished");
229 
230 
231         //Export ODF->PDF
232         exportAsPDF(saveAsODF);
233         System.out.println("ODF->PDF Finished");
234         flag = true;
235         Assert.assertTrue("FFC Test for file : "+ operateFilePath, flag);
236         isSucceed = true;
237     }
238     private String getSuffix(String file) {
239         String lowerCaseName = file.toLowerCase();
240         String suffix = lowerCaseName.substring(lowerCaseName.lastIndexOf("."));
241         return suffix;
242     }
243     /**
244      * return the Export ODF file path
245      * @throws IOException
246      * @throws IllegalArgumentException
247      */
248     private String exportAsODF(String testFile) throws IOException, IllegalArgumentException {
249         XComponent document = loadSampleFile(testFile);
250         try {
251             Thread.sleep(2000);
252         } catch (InterruptedException e) {
253             e.printStackTrace();
254         }
255         String suffix = getSuffix(testFile);
256         String filterName = filterMap.get(suffix);
257         PropertyValue[] lProperties = null;
258         lProperties = new PropertyValue[3];
259         lProperties[0] = new PropertyValue();
260         lProperties[0].Name = "FilterName";
261         lProperties[0].Value = filterName;
262         lProperties[1] = new PropertyValue();
263         lProperties[1].Name = "Overwrite";
264         lProperties[1].Value = Boolean.TRUE;
265         lProperties[2] = new PropertyValue();
266         lProperties[2].Name = "AsyncMode";
267         lProperties[2].Value = new Boolean(false);
268 
269         XStorable store = (XStorable) UnoRuntime.queryInterface(XStorable.class, document);
270         File file = new File(testFile);
271         String fileName = file.getName();
272         String saveAsFilePath = file.getParentFile().getAbsolutePath() + File.separator + fileName + "." + formatMap.get(suffix);//TODO
273         store.storeAsURL(Testspace.getUrl(saveAsFilePath), lProperties);
274         try {
275             Thread.sleep(3000);
276         } catch (InterruptedException e) {
277             e.printStackTrace();
278         }
279         app.closeDocument(document);
280         try {
281             Thread.sleep(2000);
282         } catch (InterruptedException e) {
283             e.printStackTrace();
284         }
285         return saveAsFilePath;
286     }
287 
288     private void exportAsPDF(String testFilePath) throws Exception {
289         XComponent xComponent = loadSampleFile(testFilePath);
290         XStorable xStorable = (XStorable) UnoRuntime.queryInterface(
291                 XStorable.class, xComponent);
292 
293         PropertyValue[] aMediaDescriptor = new PropertyValue[1];
294         aMediaDescriptor[0] = new PropertyValue();
295         aMediaDescriptor[0].Name = "FilterName";
296         aMediaDescriptor[0].Value = "writer_pdf_Export";
297         File file = new File(testFilePath);
298         String fileName = file.getName();
299         String saveAsFilePath =  file.getParentFile().getAbsolutePath() + File.separator + fileName + ".pdf" ;
300         // export to pdf
301         xStorable.storeToURL(Testspace.getUrl(saveAsFilePath), aMediaDescriptor);
302         try {
303             Thread.sleep(5000);
304         } catch (InterruptedException e) {
305             e.printStackTrace();
306         }
307         // close this document
308         app.closeDocument(xComponent);
309         File pdfFile = new File(saveAsFilePath);
310         Assert.assertTrue("Verify sampe file " + testFilePath + " exprot to pdf!", pdfFile.exists());
311     }
312 
313     public static void initMap() {
314         filterMap.put(".doc", "writer8");
315         filterMap.put(".docx", "writer8");
316         filterMap.put(".odt", "MS Word 97");
317         filterMap.put(".ppt", "impress8");
318         filterMap.put(".pptx", "impress8");
319         filterMap.put(".odp", "MS PowerPoint 97");
320         filterMap.put(".xls", "calc8");
321         filterMap.put(".xlsx", "calc8");
322         filterMap.put(".ods", "MS Excel 97");
323 
324         formatMap.put(".doc", "odt");
325         formatMap.put(".docx", "odt");
326         formatMap.put(".odt", "doc");
327 
328         formatMap.put(".ppt", "odp");
329         formatMap.put(".pptx", "odp");
330         formatMap.put(".odp", "ppt");
331 
332         formatMap.put(".xls", "ods");
333         formatMap.put(".xlsx", "ods");
334         formatMap.put(".ods", "xls");
335     }
336     private XComponent loadSampleFile(String filePath) throws IOException, IllegalArgumentException {
337         if (!"".equals(filePath)) {
338             PropertyValue[] loadProps = null;
339             if (filePath.endsWith("x")) {//ooxml sample file
340                 loadProps = new PropertyValue[4];
341                 loadProps[0] = new PropertyValue();
342                 loadProps[0].Name = "Hidden";
343                 loadProps[0].Value = Boolean.TRUE;
344                 loadProps[1] = new PropertyValue();
345                 loadProps[1].Name = "FilterName";
346                 String filePathLowCase = filePath.toLowerCase();
347                 if(filePathLowCase.endsWith("docx")) {
348                     loadProps[1].Value = "MS Word 2007 XML";
349                 }
350                 if(filePathLowCase.endsWith("pptx")){
351                     loadProps[1].Value = "MS PowerPoint 2007 XML";
352                 }
353                 if(filePathLowCase.endsWith("xlsx")) {
354                     loadProps[1].Value = "MS Excel 2007 XML";
355                 }
356                 loadProps[2] = new PropertyValue();
357                 loadProps[2].Name = "ReadOnly";
358                 loadProps[2].Value = true;
359                 loadProps[3] = new PropertyValue();
360                 loadProps[3].Name = "MacroExecutionMode";
361                 loadProps[3].Value = MacroExecMode.NEVER_EXECUTE;
362             } else {
363                 loadProps = new PropertyValue[3];
364                 loadProps[0] = new PropertyValue();
365                 loadProps[0].Name = "Hidden";
366                 loadProps[0].Value = Boolean.TRUE;
367                 loadProps[1] = new PropertyValue();
368                 loadProps[1].Name = "ReadOnly";
369                 loadProps[1].Value = Boolean.TRUE;
370                 loadProps[2] = new PropertyValue();
371                 loadProps[2].Name = "AsyncMode";
372                 loadProps[2].Value = new Boolean(false);
373             }
374 
375             String urlPath = Testspace.getUrl(filePath);
376             XComponentLoader componentLoader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class, app.getDesktop());
377             return componentLoader.loadComponentFromURL(urlPath, "_blank", 0, loadProps);
378         }
379         return null;
380     }
381     /**
382      * the url is like this format:
383      * ftp://user:password@192.168.0.1/public/sample/testsample.doc
384      * @param url
385      * @return
386      */
387     public String downloadFile(String url) {
388         File urlFile = new File( new File(url.replaceAll("%20", " ")).getName());
389 
390         File tempFolderFile = new File(tempFolder);
391         if (!tempFolderFile.exists()) {
392             tempFolderFile.mkdir();
393         }
394         String testFile = testSpaceFile.getAbsolutePath() + File.separator + "temp" + File.separator + urlFile.getName();
395         FileUtil.download(url, new File(testFile));
396         return testFile;
397     }
398 
399 
400 
401 }
402