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