merged tag ooo/DEV300_m102
[LibreOffice.git] / qadevOOo / runner / convwatch / OfficePrint.java
blobc9a656ac84b4fc5be37bf2bc9884860bfb8de04e
1 /*************************************************************************
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 * Copyright 2000, 2010 Oracle and/or its affiliates.
7 * OpenOffice.org - a multi-platform office productivity suite
9 * This file is part of OpenOffice.org.
11 * OpenOffice.org is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License version 3
13 * only, as published by the Free Software Foundation.
15 * OpenOffice.org is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License version 3 for more details
19 * (a copy is included in the LICENSE file that accompanied this code).
21 * You should have received a copy of the GNU Lesser General Public License
22 * version 3 along with OpenOffice.org. If not, see
23 * <http://www.openoffice.org/license.html>
24 * for a copy of the LGPLv3 License.
26 ************************************************************************/
28 package convwatch;
30 import java.io.File;
31 import java.util.ArrayList;
32 import java.io.FileWriter;
34 import com.sun.star.uno.UnoRuntime;
35 import com.sun.star.lang.XMultiServiceFactory;
36 import com.sun.star.document.XTypeDetection;
37 import com.sun.star.container.XNameAccess;
38 import com.sun.star.frame.XDesktop;
39 import com.sun.star.beans.XPropertySet;
40 import com.sun.star.beans.PropertyValue;
41 import com.sun.star.frame.XComponentLoader;
42 import com.sun.star.lang.XComponent;
43 import com.sun.star.frame.XStorable;
44 import com.sun.star.view.XPrintable;
45 import com.sun.star.lang.XServiceInfo;
46 import com.sun.star.frame.XModel;
47 import com.sun.star.uno.AnyConverter;
49 import helper.URLHelper;
50 import helper.PropertyHelper;
51 import helper.OSHelper;
52 // import convwatch.FileHelper;
53 // import convwatch.MSOfficePrint;
54 // import convwatch.GraphicalTestArguments;
55 // import convwatch.ConvWatchCancelException;
57 // import helper.Parameter;
59 /**
60 * This Object is to print a given document with OpenOffice.org / StarOffice
61 * over the normal printer driver
62 * or over it's pdf exporter
64 public class OfficePrint {
67 // static long m_nStartTime;
68 // // static Date m_aDateCache = null;
70 // /*
71 // simple helper functions to start/stop a timer, to know how long a process need in milliseconds
72 // */
73 // public static void startTimer()
74 // {
75 // // if (m_aDateCache == null)
76 // // {
77 // // m_aDateCache = new Date();
78 // // }
79 // // m_nStartTime = m_aDateCache.getTime();
80 // m_nStartTime = System.currentTimeMillis();
81 // }
82 // public static long stopTimer()
83 // {
84 // // if (m_aDateCache == null)
85 // // {
86 // // System.out.println("Forgotten to initialise start timer.");
87 // // return 0;
88 // // }
89 // // long m_nStopTime = m_aDateCache.getTime();
90 // if (m_nStartTime == 0)
91 // {
92 // System.out.println("Forgotten to initialise start timer.");
93 // return 0;
94 // }
95 // long m_nStopTime = System.currentTimeMillis();
96 // return m_nStopTime - m_nStartTime;
97 // }
100 private static void showProperty(PropertyValue _aValue)
102 String sName = _aValue.Name;
103 String sValue;
106 sValue = AnyConverter.toString(_aValue.Value);
107 GlobalLogWriter.get().println("Property " + sName + ":=" + sValue);
109 catch (com.sun.star.lang.IllegalArgumentException e)
111 // GlobalLogWriter.get().println("showProperty: can't convert a object to string.");
112 GlobalLogWriter.get().println("Property " + sName + ":= a Object which can't convert by AnyConverter()");
117 * shows the FilterName and MediaType from the given XComponent
119 static String getDocumentType( XComponent _aDoc )
121 XModel xModel = UnoRuntime.queryInterface( XModel.class, _aDoc);
122 PropertyValue[] aArgs = xModel.getArgs();
123 for (int i=0;i<aArgs.length;i++)
125 PropertyValue aValue = aArgs[i];
126 // System.out.print("Property: '" + aValue.Name);
127 // System.out.println("' := '" + aValue.Value + "'");
128 if (aValue.Name.equals("FilterName") ||
129 aValue.Name.equals("MediaType"))
131 String sNameValue = "'" + aValue.Name + "' := '" + aValue.Value + "'";
132 return sNameValue;
135 return "";
138 static void showDocumentType( XComponent _aDoc )
140 String sNameValue = getDocumentType(_aDoc);
141 GlobalLogWriter.get().println(" Property: '" + sNameValue);
144 * load a OpenOffice.org document from a given URL (_sInputURL)
145 * the GraphicalTestArguments must contain a living MultiServiceFactory object
146 * or we crash here.
147 * Be aware, the ownership of the document gets to you, you have to close it.
148 * @param _aGTA
149 * @param _sInputURL
150 * @return
152 public static XComponent loadFromURL(GraphicalTestArguments _aGTA,
153 String _sInputURL)
155 XComponent aDoc = null;
158 if (_aGTA.getMultiServiceFactory() == null)
160 GlobalLogWriter.get().println("MultiServiceFactory in GraphicalTestArgument not set.");
161 return null;
163 Object oDsk = _aGTA.getMultiServiceFactory().createInstance("com.sun.star.frame.Desktop");
164 XDesktop aDesktop = UnoRuntime.queryInterface(XDesktop.class, oDsk);
166 if (aDesktop != null)
168 GlobalLogWriter.get().println("com.sun.star.frame.Desktop created.");
169 // String sInputURL = aCurrentParameter.sInputURL;
170 // String sOutputURL = aCurrentParameter.sOutputURL;
171 // String sPrintFileURL = aCurrentParameter.sPrintToFileURL;
172 // System.out.println(_sInputURL);
175 // set here the loadComponentFromURL() properties
176 // at the moment only 'Hidden' is set, so no window is opened at work
178 ArrayList<PropertyValue> aPropertyList = new ArrayList<PropertyValue>();
180 // check which properties should set and count it.
181 // if (_aGTA.isHidden())
182 // {
183 // nPropertyCount ++;
184 // }
185 // if (_aGTA.getImportFilterName() != null && _aGTA.getImportFilterName().length() > 0)
186 // {
187 // nPropertyCount ++;
188 // }
190 // initialize the propertyvalue
191 // int nPropertyIndex = 0;
192 // aProps = new PropertyValue[ nPropertyCount ];
194 // set all property values
195 if (_aGTA.isHidden())
197 PropertyValue Arg = new PropertyValue();
198 Arg.Name = "Hidden";
199 Arg.Value = Boolean.TRUE;
200 aPropertyList.add(Arg);
201 showProperty(Arg);
203 if (_aGTA.getImportFilterName() != null && _aGTA.getImportFilterName().length() > 0)
205 PropertyValue Arg = new PropertyValue();
206 Arg.Name = "FilterName";
207 Arg.Value = _aGTA.getImportFilterName();
208 aPropertyList.add(Arg);
209 showProperty(Arg);
212 GlobalLogWriter.get().println(DateHelper.getDateTimeForHumanreadableLog() + " Load document");
213 // GlobalLogWriter.get().flush();
215 XComponentLoader aCompLoader = UnoRuntime.queryInterface( XComponentLoader.class, aDesktop);
217 // XComponent aDoc = null;
219 _aGTA.getPerformance().startTime(PerformanceContainer.Load);
220 aDoc = aCompLoader.loadComponentFromURL(_sInputURL, "_blank", 0, PropertyHelper.createPropertyValueArrayFormArrayList(aPropertyList) );
221 _aGTA.getPerformance().stopTime(PerformanceContainer.Load);
222 if (aDoc != null)
224 GlobalLogWriter.get().println(DateHelper.getDateTimeForHumanreadableLog() + " Load document done.");
225 showDocumentType(aDoc);
226 _aGTA.setDocumentType(getDocumentType(aDoc));
228 else
230 GlobalLogWriter.get().println(" Load document failed.");
231 if (_aGTA.getImportFilterName() != null && _aGTA.getImportFilterName().length() > 0)
233 GlobalLogWriter.get().println(" Please check FilterName := '" + _aGTA.getImportFilterName() + "'");
235 GlobalLogWriter.get().println("");
238 else
240 GlobalLogWriter.get().println("com.sun.star.frame.Desktop failed.");
243 catch ( com.sun.star.uno.Exception e )
245 // Some exception occures.FAILED
246 GlobalLogWriter.get().println("UNO Exception caught.");
247 GlobalLogWriter.get().println("Message: " + e.getMessage());
248 e.printStackTrace();
249 aDoc = null;
251 return aDoc;
254 static boolean exportToPDF(XComponent _xComponent, String _sDestinationName)
256 XServiceInfo xServiceInfo =
257 UnoRuntime.queryInterface(
258 XServiceInfo.class, _xComponent
261 ArrayList<PropertyValue> aPropertyList = new ArrayList<PropertyValue>();
262 PropertyValue aFiltername = new PropertyValue();
263 aFiltername.Name = "FilterName";
264 aFiltername.Value = getFilterName_forPDF(xServiceInfo);
265 aPropertyList.add(aFiltername);
266 showProperty(aFiltername);
267 boolean bWorked = true;
271 XStorable store =
272 UnoRuntime.queryInterface(
273 XStorable.class, _xComponent
275 store.storeToURL(_sDestinationName, PropertyHelper.createPropertyValueArrayFormArrayList(aPropertyList));
277 catch (com.sun.star.io.IOException e)
279 GlobalLogWriter.get().println("IO Exception caught.");
280 GlobalLogWriter.get().println("Message: " + e.getMessage());
281 bWorked = false;
284 return bWorked;
287 static String getFilterName_forPDF(XServiceInfo xServiceInfo)
289 String filterName = "";
291 if (xServiceInfo.supportsService("com.sun.star.text.TextDocument"))
293 //writer
294 filterName = "writer_pdf_Export";
296 else if ( xServiceInfo.supportsService( "com.sun.star.sheet.SpreadsheetDocument" ) )
298 //calc
299 filterName = "calc_pdf_Export";
301 else if ( xServiceInfo.supportsService( "com.sun.star.drawing.DrawingDocument" ) )
303 //draw
304 filterName = "draw_pdf_Export";
306 else if ( xServiceInfo.supportsService( "com.sun.star.presentation.PresentationDocument" ) )
308 //impress
309 filterName = "impress_pdf_Export";
311 else if (xServiceInfo.supportsService("com.sun.star.text.WebDocument"))
313 //html document
314 filterName = "writer_web_pdf_Export";
316 else if ( xServiceInfo.supportsService("com.sun.star.text.GlobalDocument") )
318 //master document
319 filterName = "writer_globaldocument_pdf_Export";
321 else if ( xServiceInfo.supportsService( "com.sun.star.formulaFormulaProperties" ) )
323 //math document
324 filterName = "math_pdf_Export";
327 return filterName;
330 // -----------------------------------------------------------------------------
332 public static boolean storeAsPDF(GraphicalTestArguments _aGTA,
333 String _sInputURL,
334 String _sOutputURL)
336 boolean bBack = false;
337 XComponent aDoc = loadFromURL(_aGTA, _sInputURL);
339 if (aDoc == null)
341 GlobalLogWriter.get().println("Can't load document.");
342 return bBack;
344 bBack = storeAsPDF(_aGTA, aDoc, _sOutputURL);
345 createInfoFile(_sOutputURL, _aGTA, "as pdf");
347 GlobalLogWriter.get().println("Close document.");
348 aDoc.dispose();
349 return bBack;
352 public static boolean storeAsPDF(GraphicalTestArguments _aGTA,
353 XComponent _aDoc,
354 String _sOutputURL)
356 // try {
357 boolean bBack = true;
358 _aGTA.getPerformance().startTime(PerformanceContainer.StoreAsPDF);
359 bBack = exportToPDF(_aDoc, _sOutputURL);
360 _aGTA.getPerformance().stopTime(PerformanceContainer.StoreAsPDF);
362 if (!bBack)
364 GlobalLogWriter.get().println("Can't store document as PDF.");
365 bBack = false;
367 return bBack;
370 // -----------------------------------------------------------------------------
373 * print the document found in file (_sInputURL) to as postscript to file (_sPrintFileURL)
374 * Due to the fact we use a printer to convert the file to postscript, the default printer
375 * to create such postscript format must be installed, this is not tested here.
377 * @param _aGTA
378 * @param _sInputURL
379 * @param _sOutputURL
380 * @param _sPrintFileURL
381 * @return true, if print has been done.
382 * Be careful, true means only print returns with no errors, to be sure print is really done
383 * check existance of _sPrintFileURL
386 public static boolean printToFileWithOOo(GraphicalTestArguments _aGTA,
387 String _sInputURL,
388 String _sOutputURL,
389 String _sPrintFileURL)
391 // waitInSeconds(1);
392 boolean bBack = false;
394 XComponent aDoc = loadFromURL(_aGTA, _sInputURL);
395 if (aDoc != null)
397 if ( _sInputURL.equals(_sOutputURL) )
399 // don't store document
400 // input and output are equal OR
401 GlobalLogWriter.get().println("Warning: Inputpath and Outputpath are equal. Document will not stored again.");
402 _aGTA.disallowStore();
404 bBack = impl_printToFileWithOOo(_aGTA, aDoc, _sOutputURL, _sPrintFileURL);
406 GlobalLogWriter.get().println("Close document.");
407 aDoc.dispose();
409 else
411 GlobalLogWriter.get().println("loadDocumentFromURL() failed with document: " + _sInputURL);
413 return bBack;
416 // -----------------------------------------------------------------------------
417 public static void createInfoFile(String _sFile, GraphicalTestArguments _aGTA)
419 createInfoFile(_sFile, _aGTA, "");
422 public static void createInfoFile(String _sFile, GraphicalTestArguments _aGTA, String _sSpecial)
424 String sFilename;
425 if (_sFile.startsWith("file://"))
427 sFilename = FileHelper.getSystemPathFromFileURL(_sFile);
428 GlobalLogWriter.get().println("CreateInfoFile: '" + sFilename + "'" );
430 else
432 sFilename = _sFile;
434 String sFileDir = FileHelper.getPath(sFilename);
435 String sBasename = FileHelper.getBasename(sFilename);
436 String sNameNoSuffix = FileHelper.getNameNoSuffix(sBasename);
438 String fs = System.getProperty("file.separator");
439 String ls = System.getProperty("line.separator");
440 String sInfoFilename = sFileDir + fs + sNameNoSuffix + ".info";
441 File aInfoFile = new File(sInfoFilename);
443 String sBuildID = "";
447 FileWriter out = new FileWriter(aInfoFile.toString());
448 out.write("# automatically created file by graphical compare" + ls);
449 if (_aGTA != null)
451 if (_sSpecial != null && _sSpecial.equals("msoffice"))
453 out.write("# buildid from wordloadfile" + ls);
454 sBuildID = _aGTA.getPerformance().getMSOfficeVersion();
455 out.write("buildid=" + sBuildID + ls);
457 else
459 out.write("# buildid is read out of the bootstrap file" + ls);
460 sBuildID = _aGTA.getBuildID();
461 out.write("buildid=" + sBuildID + ls);
463 // if (_sSpecial != null && _sSpecial.length() > 0)
464 // {
465 // out.write("special=" + _sSpecial + ls);
466 // }
467 out.write(ls);
468 out.write("# resolution given in DPI" + ls);
469 out.write("resolution=" + _aGTA.getResolutionInDPI() + ls);
471 else
473 out.write("buildid=" + _sSpecial + ls);
475 // long nTime = stopTimer();
476 // if (nTime != 0)
477 // {
478 // out.write("# time is given in milli seconds" + ls);
479 // out.write("time=" + nTime + ls);
480 // }
482 out.write(ls);
483 out.write("# Values out of System.getProperty(...)" + ls);
484 out.write("os.name=" + System.getProperty("os.name") + ls);
485 out.write("os.arch=" + System.getProperty("os.arch") + ls);
486 out.write("os.version=" + System.getProperty("os.version") + ls);
488 if (_aGTA != null)
490 out.write(ls);
491 out.write("# Performance output, values are given in milli sec." + ls);
492 _aGTA.getPerformance().print(out);
495 out.flush();
496 out.close();
498 catch (java.io.IOException e)
500 GlobalLogWriter.get().println("can't create Info file.");
501 e.printStackTrace();
504 String sExtension = FileHelper.getSuffix(_aGTA.getInputFile());
505 if (sExtension.startsWith("."))
507 sExtension = sExtension.substring(1);
510 DB.writeToDB(_aGTA.getInputFile(),
511 sNameNoSuffix,
512 sExtension,
513 sBuildID,
514 _aGTA.getReferenceType(),
515 _aGTA.getResolutionInDPI()
521 // -----------------------------------------------------------------------------
522 private static boolean impl_printToFileWithOOo(GraphicalTestArguments _aGTA,
523 XComponent _aDoc,
524 String _sOutputURL,
525 String _sPrintFileURL)
527 boolean bBack = false;
528 boolean bFailed = true; // always be a pessimist,
529 if (_aDoc == null)
531 GlobalLogWriter.get().println("No document is given.");
532 return bBack;
537 if (_sOutputURL != null)
539 if (_aGTA.isStoreAllowed())
541 // store the document in an other directory
542 XStorable aStorable = UnoRuntime.queryInterface( XStorable.class, _aDoc);
543 if (aStorable != null)
545 PropertyValue [] szEmptyArgs = new PropertyValue [0];
547 GlobalLogWriter.get().println(DateHelper.getDateTimeForHumanreadableLog() + " Store document.");
548 _aGTA.getPerformance().startTime(PerformanceContainer.Store);
549 aStorable.storeAsURL(_sOutputURL, szEmptyArgs);
550 _aGTA.getPerformance().stopTime(PerformanceContainer.Store);
552 GlobalLogWriter.get().println(DateHelper.getDateTimeForHumanreadableLog() + " Store document done.");
553 TimeHelper.waitInSeconds(2, "After store as URL to:" + _sOutputURL);
554 GlobalLogWriter.get().println("Reload stored file test.");
555 XComponent aDoc = loadFromURL(_aGTA, _sOutputURL);
556 if (aDoc == null)
558 GlobalLogWriter.get().println("Reload stored file test failed, can't reload file: " + _sOutputURL);
564 catch ( com.sun.star.uno.Exception e )
566 // Some exception occures.FAILED
567 GlobalLogWriter.get().println("UNO Exception caught.");
568 GlobalLogWriter.get().println("Message: " + e.getMessage());
570 e.printStackTrace();
571 bBack = false;
577 // System.out.println("Document loaded.");
578 // Change Pagesettings to DIN A4
580 GlobalLogWriter.get().println(DateHelper.getDateTimeForHumanreadableLog() + " Print document.");
581 XPrintable aPrintable = UnoRuntime.queryInterface( XPrintable.class, _aDoc);
582 if (aPrintable != null)
584 // System.out.println(" Set PaperFormat to DIN A4");
585 // {
586 // PropertyValue[] aPrinterProps = aPrintable.getPrinter();
587 // System.out.println("PrinterProps size: " + String.valueOf(aPrinterProps.length));
588 // int nPropIndex = 0;
589 // while (!"PaperFormat".equals(aPrinterProps[nPropIndex].Name))
590 // {
591 // // System.out.println(aPrinterProps[nPropIndex].Name);
592 // nPropIndex++;
593 // }
594 // aPrinterProps[nPropIndex].Value = com.sun.star.view.PaperFormat.A4;
595 // aPrintable.setPrinter(aPrinterProps);
596 // }
598 // configure Office to allow to execute macos
600 // TODO: We need a possiblity to set the printer name also for StarOffice/OpenOffice
601 if (OSHelper.isWindows())
603 if (_aGTA.getPrinterName() != null)
605 ArrayList<PropertyValue> aPropertyList = new ArrayList<PropertyValue>();
606 // PropertyValue [] aPrintProps = new PropertyValue[1];
607 PropertyValue Arg = new PropertyValue();
608 Arg.Name = "Name";
609 Arg.Value = _aGTA.getPrinterName();
610 aPropertyList.add(Arg);
611 showProperty(Arg);
612 // GlobalLogWriter.get().println("Printername is not null, so set to " + _aGTA.getPrinterName());
613 aPrintable.setPrinter(PropertyHelper.createPropertyValueArrayFormArrayList(aPropertyList));
617 // set property values for XPrintable.print()
618 // more can be found at "http://api.openoffice.org/docs/common/ref/com/sun/star/view/PrintOptions.html"
620 // int nProperties = 1; // default for 'FileName' property
621 // if (_aGTA.printAllPages() == false)
622 // {
623 // // we don't want to print all pages, build Pages string by ourself
624 // nProperties ++;
625 // }
626 // int nPropsCount = 0;
628 // If we are a SpreadSheet (calc), we need to set PrintAllSheets property to 'true'
629 XServiceInfo xServiceInfo = UnoRuntime.queryInterface( XServiceInfo.class, _aDoc );
630 if ( xServiceInfo.supportsService( "com.sun.star.sheet.SpreadsheetDocument" ) )
632 XMultiServiceFactory xMSF = _aGTA.getMultiServiceFactory();
633 Object aSettings = xMSF.createInstance( "com.sun.star.sheet.GlobalSheetSettings" );
634 if (aSettings != null)
636 XPropertySet xPropSet = UnoRuntime.queryInterface( XPropertySet.class, aSettings );
637 xPropSet.setPropertyValue( "PrintAllSheets", new Boolean( true ) );
638 GlobalLogWriter.get().println("PrintAllSheets := true");
642 ArrayList<PropertyValue> aPrintProps = new ArrayList<PropertyValue>();
643 // GlobalLogWriter.get().println("Property FileName:=" + _sPrintFileURL);
645 // PropertyValue [] aPrintProps = new PropertyValue[nProperties];
646 PropertyValue Arg = new PropertyValue();
647 Arg.Name = "FileName";
648 Arg.Value = _sPrintFileURL;
649 // aPrintProps[nPropsCount ++] = Arg;
650 aPrintProps.add(Arg);
651 showProperty(Arg);
653 if (_aGTA.printAllPages() == false)
655 String sPages = "";
656 if (_aGTA.getMaxPages() > 0)
658 sPages = "1-" + String.valueOf(_aGTA.getMaxPages());
660 if (_aGTA.getOnlyPages().length() != 0)
662 if (sPages.length() != 0)
664 sPages += ";";
666 sPages += String.valueOf(_aGTA.getOnlyPages());
669 Arg = new PropertyValue();
670 Arg.Name = "Pages";
671 Arg.Value = sPages;
672 aPrintProps.add(Arg);
673 showProperty(Arg);
676 // GlobalLogWriter.get().println("Start printing.");
678 _aGTA.getPerformance().startTime(PerformanceContainer.Print);
679 aPrintable.print(PropertyHelper.createPropertyValueArrayFormArrayList(aPrintProps));
680 TimeHelper.waitInSeconds(1, "Start waiting for print ready.");
682 GlobalLogWriter.get().println("Wait until document is printed.");
683 boolean isBusy = true;
684 int nPrintCount = 0;
685 while (isBusy)
687 PropertyValue[] aPrinterProps = aPrintable.getPrinter();
688 int nPropIndex = 0;
689 while (!"IsBusy".equals(aPrinterProps[nPropIndex].Name))
691 // System.out.println(aPrinterProps[nPropIndex].Name);
692 nPropIndex++;
694 isBusy = (aPrinterProps[nPropIndex].Value == Boolean.TRUE) ? true : false;
695 TimeHelper.waitInSeconds(1, "is print ready?");
696 nPrintCount++;
697 if (nPrintCount > 3600)
699 // we will never wait >1h until print is ready!
700 GlobalLogWriter.get().println("ERROR: Cancel print due to too long wait.");
701 throw new com.sun.star.uno.Exception("Convwatch exception, wait too long for printing.");
704 _aGTA.getPerformance().stopTime(PerformanceContainer.Print);
705 GlobalLogWriter.get().println(DateHelper.getDateTimeForHumanreadableLog() + " Print document done.");
707 // Create a .info file near the printed '.ps' or '.prn' file.
708 createInfoFile(_sPrintFileURL, _aGTA);
710 else
712 GlobalLogWriter.get().println("Can't get XPrintable interface.");
714 bFailed = false;
715 bBack = true;
717 catch ( com.sun.star.uno.Exception e )
719 // Some exception occures.FAILED
720 GlobalLogWriter.get().println("UNO Exception caught.");
721 GlobalLogWriter.get().println("Message: " + e.getMessage());
723 e.printStackTrace();
724 bBack = false;
727 if (bFailed == true)
729 GlobalLogWriter.get().println("convwatch.OfficePrint: FAILED");
731 else
733 GlobalLogWriter.get().println("convwatch.OfficePrint: OK");
735 return bBack;
740 * @param _aGTA
741 * @param _sAbsoluteOutputPath
742 * @param _sAbsoluteInputFile
743 * @return true, if the reference (*.prrn file) based on given output path and given input path exist.
744 * If OVERWRITE_REFERENCE is set, always return false.
746 public static boolean isReferenceExists(GraphicalTestArguments _aGTA,
747 String _sAbsoluteOutputPath,
748 String _sAbsoluteInputFile)
750 if (! FileHelper.exists(_sAbsoluteInputFile))
752 // throw new ConvWatchCancelException("Input file: " + _sAbsoluteInputFile + " does not exist.");
753 return false;
756 String fs = System.getProperty("file.separator");
758 // String sInputFileURL = URLHelper.getFileURLFromSystemPath(_sAbsoluteInputFile);
760 String sInputFileBasename = FileHelper.getBasename(_sAbsoluteInputFile);
761 // String sOutputFileURL = null;
762 String sOutputPath;
763 if (_sAbsoluteOutputPath != null)
765 sOutputPath = _sAbsoluteOutputPath;
766 // FileHelper.makeDirectories("", sOutputPath);
768 else
770 String sInputPath = FileHelper.getPath(_sAbsoluteInputFile);
771 sOutputPath = sInputPath;
773 // sOutputFileURL = URLHelper.getFileURLFromSystemPath(sOutputPath + fs + sInputFileBasename);
774 // sOutputFileURL = null;
776 String sPrintFilename = FileHelper.getNameNoSuffix(sInputFileBasename);
777 // String sPrintFileURL;
779 String sAbsolutePrintFilename = sOutputPath + fs + sPrintFilename + ".prn";
780 if (FileHelper.exists(sAbsolutePrintFilename) && _aGTA.getOverwrite() == false)
782 GlobalLogWriter.get().println("Reference already exist, don't overwrite. Set " + PropertyName.DOC_COMPARATOR_OVERWRITE_REFERENCE + "=true to force overwrite.");
783 return true;
785 return false;
788 // -----------------------------------------------------------------------------
790 * create a reference file
791 * _sAbsoluteInputPath contains the source file, if not exists, return with failure.
792 * _sAbsoluteOutputPath contains the destination, where the file will store after load with StarOffice/OpenOffice.org
793 * if is null, print only near the Input file path
794 * _sPrintType ".prn" Print input file with StarOffice/OpenOffice.org and the default printer as PostScript
796 * @param _aGTA
797 * @param _sAbsoluteOutputPath
798 * @param _sAbsoluteInputFile
799 * @return
800 * @throws ConvWatchCancelException
802 public static boolean buildReference(GraphicalTestArguments _aGTA,
803 String _sAbsoluteOutputPath,
804 String _sAbsoluteInputFile)
805 throws ConvWatchCancelException
807 if (! FileHelper.exists(_sAbsoluteInputFile))
809 throw new ConvWatchCancelException("buildReference(): Input file: " + _sAbsoluteInputFile + " does not exist.");
812 String fs = System.getProperty("file.separator");
814 String sInputFileURL = URLHelper.getFileURLFromSystemPath(_sAbsoluteInputFile);
816 String sInputFileBasename = FileHelper.getBasename(_sAbsoluteInputFile);
817 String sOutputFileURL = null;
818 String sOutputPath;
819 if (_sAbsoluteOutputPath != null)
821 sOutputPath = _sAbsoluteOutputPath;
822 FileHelper.makeDirectories("", sOutputPath);
824 else
826 String sInputPath = FileHelper.getPath(_sAbsoluteInputFile);
827 sOutputPath = sInputPath;
829 // sOutputFileURL = URLHelper.getFileURLFromSystemPath(sOutputPath + fs + sInputFileBasename);
830 sOutputFileURL = null;
832 String sPrintFilename = FileHelper.getNameNoSuffix(sInputFileBasename);
833 String sPrintFileURL;
835 String sAbsolutePrintFilename = sOutputPath + fs + sPrintFilename + ".prn";
836 if (FileHelper.exists(sAbsolutePrintFilename) && _aGTA.getOverwrite() == false)
838 GlobalLogWriter.get().println("Reference already exist, don't overwrite. Set " + PropertyName.DOC_COMPARATOR_OVERWRITE_REFERENCE + "=true to force overwrite.");
839 return true;
842 if (_aGTA.getReferenceType().toLowerCase().equals("msoffice"))
844 sPrintFileURL = URLHelper.getFileURLFromSystemPath(sAbsolutePrintFilename);
846 else if (_aGTA.getReferenceType().toLowerCase().equals("pdf"))
848 // TODO: If we rename the stored file to *.pdf, we have to be sure that we use *.pdf also as a available reference
849 sPrintFileURL = URLHelper.getFileURLFromSystemPath(sAbsolutePrintFilename );
851 else if (_aGTA.getReferenceType().toLowerCase().equals("ooo"))
853 sPrintFileURL = URLHelper.getFileURLFromSystemPath(sAbsolutePrintFilename );
855 else
857 GlobalLogWriter.get().println("OfficePrint.buildreference(): Unknown print type.");
858 return false;
860 return printToFile(_aGTA, sInputFileURL, sOutputFileURL, sPrintFileURL);
863 public static boolean printToFile(GraphicalTestArguments _aGTA,
864 String _sInputFileURL,
865 String _sOutputFileURL,
866 String _sPrintFileURL) throws ConvWatchCancelException
868 boolean bBack = false;
869 String sPrintFileURL = null;
871 // check if given file is a picture, then do nothing
872 String sDocumentSuffix = FileHelper.getSuffix(_sInputFileURL);
873 if (sDocumentSuffix.toLowerCase().endsWith(".png") ||
874 sDocumentSuffix.toLowerCase().endsWith(".gif") ||
875 sDocumentSuffix.toLowerCase().endsWith(".jpg") ||
876 sDocumentSuffix.toLowerCase().endsWith(".bmp"))
878 return false;
882 // remember the current timer, to know how long a print process need.
883 // startTimer();
885 if (_aGTA.getReferenceType().toLowerCase().equals("ooo"))
887 bBack = printToFileWithOOo(_aGTA, _sInputFileURL, _sOutputFileURL, _sPrintFileURL);
889 else if (_aGTA.getReferenceType().toLowerCase().equals("pdf"))
891 GlobalLogWriter.get().println("USE PDF AS EXPORT FORMAT.");
892 bBack = storeAsPDF(_aGTA, _sInputFileURL, _sPrintFileURL);
894 else if (_aGTA.getReferenceType().toLowerCase().equals("msoffice"))
896 if (MSOfficePrint.isMSOfficeDocumentFormat(_sInputFileURL))
898 GlobalLogWriter.get().println("USE MSOFFICE AS EXPORT FORMAT.");
899 MSOfficePrint a = new MSOfficePrint();
902 a.printToFileWithMSOffice(_aGTA, FileHelper.getSystemPathFromFileURL(_sInputFileURL),
903 FileHelper.getSystemPathFromFileURL(_sPrintFileURL));
905 catch(ConvWatchCancelException e)
907 e.printStackTrace();
908 GlobalLogWriter.get().println(e.getMessage());
909 throw new ConvWatchCancelException("Exception caught. Problem with MSOffice printer methods.");
911 catch(java.io.IOException e)
913 GlobalLogWriter.get().println(e.getMessage());
914 throw new ConvWatchCancelException("IOException caught. Problem with MSOffice printer methods.");
916 bBack = true;
918 else
920 GlobalLogWriter.get().println("This document type is not recognized as MSOffice format, as default fallback StarOffice/OpenOffice.org instead is used.");
921 bBack = printToFileWithOOo(_aGTA, _sInputFileURL, _sOutputFileURL, _sPrintFileURL);
924 else
926 // System.out.println("");
927 throw new ConvWatchCancelException("OfficePrint.printToFile(): Unknown print type.");
929 return bBack;
932 // -----------------------------------------------------------------------------
933 // TODO: move this away!
934 // -----------------------------------------------------------------------------
935 static void showType(String _sInputURL, XMultiServiceFactory _xMSF)
937 if (_sInputURL.length() == 0)
939 return;
942 if (_xMSF == null)
944 GlobalLogWriter.get().println("MultiServiceFactory not set.");
945 return;
947 XTypeDetection aTypeDetection = null;
950 Object oObj = _xMSF.createInstance("com.sun.star.document.TypeDetection");
951 aTypeDetection = UnoRuntime.queryInterface(XTypeDetection.class, oObj);
953 catch(com.sun.star.uno.Exception e)
955 GlobalLogWriter.get().println("Can't get com.sun.star.document.TypeDetection.");
956 return;
958 if (aTypeDetection != null)
960 String sType = aTypeDetection.queryTypeByURL(_sInputURL);
961 GlobalLogWriter.get().println("Type is: " + sType);
966 // -----------------------------------------------------------------------------
967 public static String getInternalFilterName(String _sFilterName, XMultiServiceFactory _xMSF)
969 if (_sFilterName.length() == 0)
971 // System.out.println("No FilterName set.");
972 return null;
975 if (_xMSF == null)
977 GlobalLogWriter.get().println("MultiServiceFactory not set.");
978 return null;
980 // XFilterFactory aFilterFactory = null;
981 Object aObj = null;
984 aObj = _xMSF.createInstance("com.sun.star.document.FilterFactory");
986 catch(com.sun.star.uno.Exception e)
988 GlobalLogWriter.get().println("Can't get com.sun.star.document.FilterFactory.");
989 return null;
991 if (aObj != null)
993 XNameAccess aNameAccess = UnoRuntime.queryInterface(XNameAccess.class, aObj);
994 if (aNameAccess != null)
997 // if (_sFilterName.toLowerCase().equals("help"))
998 // {
999 // System.out.println("Show all possible ElementNames from current version." );
1000 // String[] aElementNames = aNameAccess.getElementNames();
1001 // for (int i = 0; i<aElementNames.length; i++)
1002 // {
1003 // System.out.println(aElementNames[i]);
1004 // }
1005 // System.out.println("Must quit.");
1006 // System.out.exit(1);
1007 // }
1009 if (! aNameAccess.hasByName(_sFilterName))
1011 GlobalLogWriter.get().println("FilterFactory.hasByName() says there exist no '" + _sFilterName + "'" );
1012 return null;
1015 Object[] aElements = null;
1016 String[] aExtensions;
1019 aElements = (Object[]) aNameAccess.getByName(_sFilterName);
1020 if (aElements != null)
1022 String sInternalFilterName = null;
1023 // System.out.println("getByName().length: " + String.valueOf(aElements.length));
1024 for (int i=0;i<aElements.length; i++)
1026 PropertyValue aPropertyValue = (PropertyValue)aElements[i];
1027 // System.out.println("PropertyValue.Name: " + aPropertyValue.Name);
1028 if (aPropertyValue.Name.equals("Type"))
1030 String sValue = (String)aPropertyValue.Value;
1031 // System.out.println("Type: " + sValue);
1032 sInternalFilterName = sValue;
1035 return sInternalFilterName;
1037 else
1039 GlobalLogWriter.get().println("There are no elements for FilterName '" + _sFilterName + "'");
1040 return null;
1043 catch (com.sun.star.container.NoSuchElementException e)
1045 GlobalLogWriter.get().println("NoSuchElementException caught. " + e.getMessage());
1047 catch (com.sun.star.lang.WrappedTargetException e)
1049 GlobalLogWriter.get().println("WrappedTargetException caught. " + e.getMessage());
1053 return null;
1056 // -----------------------------------------------------------------------------
1058 static String getServiceNameFromFilterName(String _sFilterName, XMultiServiceFactory _xMSF)
1060 if (_sFilterName.length() == 0)
1062 // System.out.println("No FilterName set.");
1063 return null;
1066 if (_xMSF == null)
1068 GlobalLogWriter.get().println("MultiServiceFactory not set.");
1069 return null;
1071 // XFilterFactory aFilterFactory = null;
1072 Object aObj = null;
1075 aObj = _xMSF.createInstance("com.sun.star.document.FilterFactory");
1077 catch(com.sun.star.uno.Exception e)
1079 GlobalLogWriter.get().println("Can't get com.sun.star.document.FilterFactory.");
1080 return null;
1082 if (aObj != null)
1084 XNameAccess aNameAccess = UnoRuntime.queryInterface(XNameAccess.class, aObj);
1085 if (aNameAccess != null)
1087 if (! aNameAccess.hasByName(_sFilterName))
1089 GlobalLogWriter.get().println("FilterFactory.hasByName() says there exist no '" + _sFilterName + "'" );
1090 return null;
1093 Object[] aElements = null;
1094 String[] aExtensions;
1097 aElements = (Object[]) aNameAccess.getByName(_sFilterName);
1098 if (aElements != null)
1100 String sServiceName = null;
1101 // System.out.println("getByName().length: " + String.valueOf(aElements.length));
1102 for (int i=0;i<aElements.length; i++)
1104 PropertyValue aPropertyValue = (PropertyValue)aElements[i];
1105 if (aPropertyValue.Name.equals("DocumentService"))
1107 String sValue = (String)aPropertyValue.Value;
1108 // System.out.println("DocumentService: " + sValue);
1109 sServiceName = sValue;
1110 break;
1113 return sServiceName;
1115 else
1117 GlobalLogWriter.get().println("There are no elements for FilterName '" + _sFilterName + "'");
1118 return null;
1121 catch (com.sun.star.container.NoSuchElementException e)
1123 GlobalLogWriter.get().println("NoSuchElementException caught. " + e.getMessage());
1125 catch (com.sun.star.lang.WrappedTargetException e)
1127 GlobalLogWriter.get().println("WrappedTargetException caught. " + e.getMessage());
1131 return null;
1133 // -----------------------------------------------------------------------------
1135 public static String getFileExtension(String _sInternalFilterName, XMultiServiceFactory _xMSF)
1137 if (_sInternalFilterName.length() == 0)
1139 // System.out.println("No FilterName set.");
1140 return null;
1143 if (_xMSF == null)
1145 GlobalLogWriter.get().println("MultiServiceFactory not set.");
1146 return null;
1148 XTypeDetection aTypeDetection = null;
1151 Object oObj = _xMSF.createInstance("com.sun.star.document.TypeDetection");
1152 aTypeDetection =UnoRuntime.queryInterface(XTypeDetection.class, oObj);
1154 catch(com.sun.star.uno.Exception e)
1156 GlobalLogWriter.get().println("Can't get com.sun.star.document.TypeDetection.");
1157 return null;
1159 if (aTypeDetection != null)
1161 XNameAccess aNameAccess = UnoRuntime.queryInterface(XNameAccess.class, aTypeDetection);
1162 if (aNameAccess != null)
1165 // System.out.println("Show ElementNames" );
1166 // String[] aElementNames = aNameAccess.getElementNames();
1167 // for (int i = 0; i<aElementNames.length; i++)
1168 // {
1169 // System.out.println(aElementNames[i]);
1170 // }
1172 if (! aNameAccess.hasByName(_sInternalFilterName))
1174 GlobalLogWriter.get().println("TypeDetection.hasByName() says there exist no '" + _sInternalFilterName + "'" );
1175 return null;
1178 Object[] aElements = null;
1179 String[] aExtensions;
1182 aElements = (Object[]) aNameAccess.getByName(_sInternalFilterName);
1183 if (aElements != null)
1185 String sExtension = null;
1186 // System.out.println("getByName().length: " + String.valueOf(aElements.length));
1187 for (int i=0;i<aElements.length; i++)
1189 PropertyValue aPropertyValue = (PropertyValue)aElements[i];
1190 // System.out.println("PropertyValue.Name: " + aPropertyValue.Name);
1191 if (aPropertyValue.Name.equals("Extensions"))
1193 aExtensions = (String[])aPropertyValue.Value;
1194 GlobalLogWriter.get().println(" Possible extensions are: " + String.valueOf(aExtensions.length));
1195 if (aExtensions.length > 0)
1197 for (int j=0;j<aExtensions.length;j++)
1199 GlobalLogWriter.get().println(" " + aExtensions[j]);
1201 sExtension = aExtensions[0];
1202 GlobalLogWriter.get().println("");
1206 return sExtension;
1208 else
1210 GlobalLogWriter.get().println("There are no elements for FilterName '" + _sInternalFilterName + "'");
1211 return null;
1214 catch (com.sun.star.container.NoSuchElementException e)
1216 GlobalLogWriter.get().println("NoSuchElementException caught. " + e.getMessage());
1218 catch (com.sun.star.lang.WrappedTargetException e)
1220 GlobalLogWriter.get().println("WrappedTargetException caught. " + e.getMessage());
1224 return null;
1227 // -----------------------------------------------------------------------------
1228 public static void convertDocument(String _sInputFile, String _sOutputPath, GraphicalTestArguments _aGTA) throws ConvWatchCancelException
1230 XMultiServiceFactory xMSF = _aGTA.getMultiServiceFactory();
1231 if (xMSF == null)
1233 GlobalLogWriter.get().println("MultiServiceFactory in GraphicalTestArgument not set.");
1234 return;
1237 String sInputURL = URLHelper.getFileURLFromSystemPath(_sInputFile);
1238 // showType(sInputURL, xMSF);
1239 XComponent aDoc = loadFromURL( _aGTA, sInputURL);
1240 if (aDoc == null)
1242 GlobalLogWriter.get().println("Can't load document '"+ sInputURL + "'");
1243 return;
1246 if (_sOutputPath == null)
1248 GlobalLogWriter.get().println("Outputpath not set.");
1249 return;
1252 if (! _aGTA.isStoreAllowed())
1254 GlobalLogWriter.get().println("It's not allowed to store, check Input/Output path.");
1255 return;
1257 // TODO: Do we need to wait?
1258 TimeHelper.waitInSeconds(1, "wait after loadFromURL.");
1260 XServiceInfo xServiceInfo = UnoRuntime.queryInterface( XServiceInfo.class, aDoc );
1261 // String sFilter = getFilterName_forExcel(xServiceInfo);
1262 // System.out.println("Filter is " + sFilter);
1264 // store the document in an other directory
1265 XStorable xStorable = UnoRuntime.queryInterface( XStorable.class, aDoc);
1266 if (xStorable == null)
1268 GlobalLogWriter.get().println("com.sun.star.frame.XStorable is null");
1269 return;
1272 String sFilterName = _aGTA.getExportFilterName();
1274 // check how many Properties should initialize
1275 int nPropertyCount = 0;
1276 // if (sFilterName != null && sFilterName.length() > 0)
1277 // {
1278 // nPropertyCount ++;
1279 // }
1281 // initialize PropertyArray
1282 // PropertyValue [] aStoreProps = new PropertyValue[ nPropertyCount ];
1283 // int nPropertyIndex = 0;
1284 ArrayList<PropertyValue> aPropertyList = new ArrayList<PropertyValue>();
1286 String sExtension = "";
1288 if (sFilterName != null && sFilterName.length() > 0)
1290 String sInternalFilterName = getInternalFilterName(sFilterName, xMSF);
1291 String sServiceName = getServiceNameFromFilterName(sFilterName, xMSF);
1293 GlobalLogWriter.get().println("Filter detection:");
1294 // check if service name from file filter is the same as from the loaded document
1295 boolean bServiceFailed = false;
1296 if (sServiceName == null || sInternalFilterName == null)
1298 GlobalLogWriter.get().println("Given FilterName '" + sFilterName + "' seems to be unknown.");
1299 bServiceFailed = true;
1301 if (! xServiceInfo.supportsService(sServiceName))
1303 GlobalLogWriter.get().println("Service from FilterName '" + sServiceName + "' is not supported by loaded document.");
1304 bServiceFailed = true;
1306 if (bServiceFailed == true)
1308 GlobalLogWriter.get().println("Please check '" + PropertyName.DOC_CONVERTER_EXPORT_FILTER_NAME + "' in the property file.");
1309 return;
1312 if (sInternalFilterName != null && sInternalFilterName.length() > 0)
1314 // get the FileExtension, by the filter name, if we don't get a file extension
1315 // we assume the is also no right filter name.
1316 sExtension = getFileExtension(sInternalFilterName, xMSF);
1317 if (sExtension == null)
1319 GlobalLogWriter.get().println("Can't found an extension for filtername, take it from the source.");
1323 PropertyValue Arg = new PropertyValue();
1324 Arg.Name = "FilterName";
1325 Arg.Value = sFilterName;
1326 // aStoreProps[nPropertyIndex ++] = Arg;
1327 aPropertyList.add(Arg);
1328 showProperty(Arg);
1329 GlobalLogWriter.get().println("FilterName is set to: " + sFilterName);
1332 String sOutputURL = "";
1335 // create the new filename with the extension, which is ok to the file format
1336 String sInputFileBasename = FileHelper.getBasename(_sInputFile);
1337 // System.out.println("InputFileBasename " + sInputFileBasename);
1338 String sInputFileNameNoSuffix = FileHelper.getNameNoSuffix(sInputFileBasename);
1339 // System.out.println("InputFilename no suffix " + sInputFileNameNoSuffix);
1340 String fs = System.getProperty("file.separator");
1341 String sOutputFile = _sOutputPath;
1342 if (! sOutputFile.endsWith(fs))
1344 sOutputFile += fs;
1346 if (sExtension != null && sExtension.length() > 0)
1348 sOutputFile += sInputFileNameNoSuffix + "." + sExtension;
1350 else
1352 sOutputFile += sInputFileBasename;
1355 if (FileHelper.exists(sOutputFile) && _aGTA.getOverwrite() == false)
1357 GlobalLogWriter.get().println("File already exist, don't overwrite. Set " + PropertyName.DOC_COMPARATOR_OVERWRITE_REFERENCE + "=true to force overwrite.");
1358 return;
1361 sOutputURL = URLHelper.getFileURLFromSystemPath(sOutputFile);
1363 GlobalLogWriter.get().println("Store document as '" + sOutputURL + "'");
1364 xStorable.storeAsURL(sOutputURL, PropertyHelper.createPropertyValueArrayFormArrayList(aPropertyList));
1365 GlobalLogWriter.get().println("Document stored.");
1367 catch (com.sun.star.io.IOException e)
1369 GlobalLogWriter.get().println("Can't store document '" + sOutputURL + "'. Message is :'" + e.getMessage() + "'");
1371 // TODO: Do we need to wait?
1372 TimeHelper.waitInSeconds(1, "unknown in OfficePrint.convertDocument()");