xref: /trunk/test/testuno/source/fvt/uno/ffc/FFCTest.java (revision eba4d44a)
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 		app.start();
199 	}
200 	@After
201 	public void tearDown() throws Exception {
202 		if (!isSucceed) {
203 			FileUtil.copyFile(operateFilePath, Testspace.getFile(failedFilesDir).getAbsolutePath());
204 			FileUtil.appendStringToFile( Testspace.getFile(failedFilesDir + File.separator + "failedFiles.files").getAbsolutePath(), fileURL +"\r\n");
205 			app.close();
206 			SystemUtil.killProcess("WerFault.*");
207 			SystemUtil.sleep(2);
208 			SystemUtil.killProcess("EQNEDT32.*");
209 			//WerFault.exe
210 			//EQNEDT32.EXE
211 		}
212 	}
213 
214 
215 
216 	@Test(timeout=1000*60*5)
217 	public void exportTest() throws Exception {
218 		//MS Office Format ->ODF
219 		boolean flag = false;
220 
221 		String saveAsODF = exportAsODF(operateFilePath);
222 		System.out.println("MS ->ODF finished");
223 		//ODF->MS
224 		String savedMSFilePath = exportAsODF(saveAsODF);
225 		File savedMSFile = new File(savedMSFilePath);
226 		Assert.assertTrue("FFC Test for file : "+ savedMSFilePath, savedMSFile.exists());
227 		System.out.println("ODF->MS Finished");
228 
229 
230 		//Export ODF->PDF
231 		exportAsPDF(saveAsODF);
232 		System.out.println("ODF->PDF Finished");
233 		flag = true;
234 		Assert.assertTrue("FFC Test for file : "+ operateFilePath, flag);
235 		isSucceed = true;
236 	}
237 	private String getSuffix(String file) {
238 		String lowerCaseName = file.toLowerCase();
239 		String suffix = lowerCaseName.substring(lowerCaseName.lastIndexOf("."));
240 		return suffix;
241 	}
242 	/**
243 	 * return the Export ODF file path
244 	 * @throws IOException
245 	 * @throws IllegalArgumentException
246 	 */
247 	private String exportAsODF(String testFile) throws IOException, IllegalArgumentException {
248 		XComponent document = loadSampleFile(testFile);
249 		String suffix = getSuffix(testFile);
250 		String filterName = filterMap.get(suffix);
251 		PropertyValue[] lProperties = null;
252 		lProperties = new PropertyValue[3];
253 		lProperties[0] = new PropertyValue();
254 		lProperties[0].Name = "FilterName";
255 		lProperties[0].Value = filterName;
256 		lProperties[1] = new PropertyValue();
257 		lProperties[1].Name = "Overwrite";
258 		lProperties[1].Value = Boolean.TRUE;
259 		lProperties[2] = new PropertyValue();
260 		lProperties[2].Name = "AsyncMode";
261 		lProperties[2].Value = new Boolean(false);
262 
263 		XStorable store = (XStorable) UnoRuntime.queryInterface(XStorable.class, document);
264 		File file = new File(testFile);
265 		String fileName = file.getName();
266 		String saveAsFilePath = file.getParentFile().getAbsolutePath() + File.separator + fileName + "." + formatMap.get(suffix);//TODO
267 		store.storeAsURL(Testspace.getUrl(saveAsFilePath), lProperties);
268 		app.closeDocument(document);
269 		return saveAsFilePath;
270 	}
271 
272 	private void exportAsPDF(String testFilePath) throws Exception {
273 		XComponent xComponent = loadSampleFile(testFilePath);
274 		XStorable xStorable = (XStorable) UnoRuntime.queryInterface(
275 				XStorable.class, xComponent);
276 
277 		PropertyValue[] aMediaDescriptor = new PropertyValue[1];
278 		aMediaDescriptor[0] = new PropertyValue();
279 		aMediaDescriptor[0].Name = "FilterName";
280 		aMediaDescriptor[0].Value = "writer_pdf_Export";
281 		File file = new File(testFilePath);
282 		String fileName = file.getName();
283 		String saveAsFilePath =  file.getParentFile().getAbsolutePath() + File.separator + fileName + ".pdf" ;
284 		// export to pdf
285 		xStorable.storeToURL(Testspace.getUrl(saveAsFilePath), aMediaDescriptor);
286 
287 		// close this document
288 		app.closeDocument(xComponent);
289 		File pdfFile = new File(saveAsFilePath);
290 		Assert.assertTrue("Verify sampe file " + testFilePath + " exprot to pdf!", pdfFile.exists());
291 	}
292 
293 	public static void initMap() {
294 		filterMap.put(".doc", "writer8");
295 		filterMap.put(".docx", "writer8");
296 		filterMap.put(".odt", "MS Word 97");
297 		filterMap.put(".ppt", "impress8");
298 		filterMap.put(".pptx", "impress8");
299 		filterMap.put(".odp", "MS PowerPoint 97");
300 		filterMap.put(".xls", "calc8");
301 		filterMap.put(".xlsx", "calc8");
302 		filterMap.put(".ods", "MS Excel 97");
303 
304 		formatMap.put(".doc", "odt");
305 		formatMap.put(".docx", "odt");
306 		formatMap.put(".odt", "doc");
307 
308 		formatMap.put(".ppt", "odp");
309 		formatMap.put(".pptx", "odp");
310 		formatMap.put(".odp", "ppt");
311 
312 		formatMap.put(".xls", "ods");
313 		formatMap.put(".xlsx", "ods");
314 		formatMap.put(".ods", "xls");
315 	}
316 	private XComponent loadSampleFile(String filePath) throws IOException, IllegalArgumentException {
317 		if (!"".equals(filePath)) {
318 			PropertyValue[] loadProps = null;
319 			if (filePath.endsWith("x")) {//ooxml sample file
320 				loadProps = new PropertyValue[4];
321 				loadProps[0] = new PropertyValue();
322 				loadProps[0].Name = "Hidden";
323 				loadProps[0].Value = Boolean.TRUE;
324 				loadProps[1] = new PropertyValue();
325 				loadProps[1].Name = "FilterName";
326 				String filePathLowCase = filePath.toLowerCase();
327 				if(filePathLowCase.endsWith("docx")) {
328 					loadProps[1].Value = "MS Word 2007 XML";
329 				}
330 				if(filePathLowCase.endsWith("pptx")){
331 					loadProps[1].Value = "MS PowerPoint 2007 XML";
332 				}
333 				if(filePathLowCase.endsWith("xlsx")) {
334 					loadProps[1].Value = "MS Excel 2007 XML";
335 				}
336 				loadProps[2] = new PropertyValue();
337 				loadProps[2].Name = "ReadOnly";
338 				loadProps[2].Value = true;
339 				loadProps[3] = new PropertyValue();
340 				loadProps[3].Name = "MacroExecutionMode";
341 				loadProps[3].Value = MacroExecMode.NEVER_EXECUTE;
342 			} else {
343 				loadProps = new PropertyValue[3];
344 				loadProps[0] = new PropertyValue();
345 				loadProps[0].Name = "Hidden";
346 				loadProps[0].Value = Boolean.TRUE;
347 				loadProps[1] = new PropertyValue();
348 				loadProps[1].Name = "ReadOnly";
349 				loadProps[1].Value = Boolean.TRUE;
350 				loadProps[2] = new PropertyValue();
351 				loadProps[2].Name = "AsyncMode";
352 				loadProps[2].Value = new Boolean(false);
353 			}
354 
355 			String urlPath = Testspace.getUrl(filePath);
356 			XComponentLoader componentLoader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class, app.getDesktop());
357 			return componentLoader.loadComponentFromURL(urlPath, "_blank", 0, loadProps);
358 		}
359 		return null;
360 	}
361 	/**
362 	 * the url is like this format:
363 	 * ftp://user:password@192.168.0.1/public/sample/testsample.doc
364 	 * @param url
365 	 * @return
366 	 */
367 	public String downloadFile(String url) {
368 		File urlFile = new File( new File(url.replaceAll("%20", " ")).getName());
369 
370 		File tempFolderFile = new File(tempFolder);
371 		if (!tempFolderFile.exists()) {
372 			tempFolderFile.mkdir();
373 		}
374 		String testFile = testSpaceFile.getAbsolutePath() + File.separator + "temp" + File.separator + urlFile.getName();
375 		FileUtil.download(url, new File(testFile));
376 		return testFile;
377 	}
378 
379 
380 
381 }
382