Update ooo320-m1
[ooovba.git] / qadevOOo / runner / convwatch / OfficePrint.java
blob13aaee136730fbfced1a31e35cc78552748c55e8
1 /*************************************************************************
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * Copyright 2008 by Sun Microsystems, Inc.
7 * OpenOffice.org - a multi-platform office productivity suite
9 * $RCSfile: OfficePrint.java,v $
10 * $Revision: 1.10.8.1 $
12 * This file is part of OpenOffice.org.
14 * OpenOffice.org is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU Lesser General Public License version 3
16 * only, as published by the Free Software Foundation.
18 * OpenOffice.org is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU Lesser General Public License version 3 for more details
22 * (a copy is included in the LICENSE file that accompanied this code).
24 * You should have received a copy of the GNU Lesser General Public License
25 * version 3 along with OpenOffice.org. If not, see
26 * <http://www.openoffice.org/license.html>
27 * for a copy of the LGPLv3 License.
29 ************************************************************************/
31 package convwatch;
33 import java.io.File;
34 import java.util.ArrayList;
35 import java.io.FileWriter;
37 import com.sun.star.uno.UnoRuntime;
38 import com.sun.star.lang.XMultiServiceFactory;
39 import com.sun.star.document.XTypeDetection;
40 import com.sun.star.container.XNameAccess;
41 import com.sun.star.frame.XDesktop;
42 import com.sun.star.beans.XPropertySet;
43 import com.sun.star.beans.PropertyValue;
44 import com.sun.star.frame.XComponentLoader;
45 import com.sun.star.lang.XComponent;
46 import com.sun.star.frame.XStorable;
47 import com.sun.star.view.XPrintable;
48 import com.sun.star.lang.XServiceInfo;
49 import com.sun.star.frame.XModel;
50 import com.sun.star.uno.AnyConverter;
52 import helper.URLHelper;
53 import helper.PropertyHelper;
54 import helper.OSHelper;
55 import convwatch.FileHelper;
56 import convwatch.MSOfficePrint;
57 import convwatch.GraphicalTestArguments;
58 import convwatch.ConvWatchCancelException;
60 // import helper.Parameter;
62 /**
63 * This Object is to print a given document with OpenOffice.org / StarOffice
64 * over the normal printer driver
65 * or over it's pdf exporter
67 public class OfficePrint {
70 // static long m_nStartTime;
71 // // static Date m_aDateCache = null;
72 //
73 // /*
74 // simple helper functions to start/stop a timer, to know how long a process need in milliseconds
75 // */
76 // public static void startTimer()
77 // {
78 // // if (m_aDateCache == null)
79 // // {
80 // // m_aDateCache = new Date();
81 // // }
82 // // m_nStartTime = m_aDateCache.getTime();
83 // m_nStartTime = System.currentTimeMillis();
84 // }
85 // public static long stopTimer()
86 // {
87 // // if (m_aDateCache == null)
88 // // {
89 // // System.out.println("Forgotten to initialise start timer.");
90 // // return 0;
91 // // }
92 // // long m_nStopTime = m_aDateCache.getTime();
93 // if (m_nStartTime == 0)
94 // {
95 // System.out.println("Forgotten to initialise start timer.");
96 // return 0;
97 // }
98 // long m_nStopTime = System.currentTimeMillis();
99 // return m_nStopTime - m_nStartTime;
100 // }
103 private static void showProperty(PropertyValue _aValue)
105 String sName = _aValue.Name;
106 String sValue;
109 sValue = AnyConverter.toString(_aValue.Value);
110 GlobalLogWriter.get().println("Property " + sName + ":=" + sValue);
112 catch (com.sun.star.lang.IllegalArgumentException e)
114 GlobalLogWriter.get().println("showProperty: can't convert a object to string.");
118 /**
119 * shows the FilterName and MediaType from the given XComponent
121 static String getDocumentType( XComponent _aDoc )
123 XModel xModel = (XModel) UnoRuntime.queryInterface( XModel.class, _aDoc);
124 PropertyValue[] aArgs = xModel.getArgs();
125 for (int i=0;i<aArgs.length;i++)
127 PropertyValue aValue = aArgs[i];
128 // System.out.print("Property: '" + aValue.Name);
129 // System.out.println("' := '" + aValue.Value + "'");
130 if (aValue.Name.equals("FilterName") ||
131 aValue.Name.equals("MediaType"))
133 String sNameValue = "'" + aValue.Name + "' := '" + aValue.Value + "'";
134 return sNameValue;
137 return "";
140 static void showDocumentType( XComponent _aDoc )
142 String sNameValue = getDocumentType(_aDoc);
143 GlobalLogWriter.get().println(" Property: '" + sNameValue);
146 * load a OpenOffice.org document from a given URL (_sInputURL)
147 * the GraphicalTestArguments must contain a living MultiServiceFactory object
148 * or we crash here.
149 * Be aware, the ownership of the document gets to you, you have to close it.
151 public static XComponent loadFromURL(GraphicalTestArguments _aGTA,
152 String _sInputURL)
154 XComponent aDoc = null;
155 try
157 if (_aGTA.getMultiServiceFactory() == null)
159 GlobalLogWriter.get().println("MultiServiceFactory in GraphicalTestArgument not set.");
160 return null;
162 Object oDsk = _aGTA.getMultiServiceFactory().createInstance("com.sun.star.frame.Desktop");
163 XDesktop aDesktop = (XDesktop)UnoRuntime.queryInterface(XDesktop.class, oDsk);
165 if (aDesktop != null)
167 GlobalLogWriter.get().println("com.sun.star.frame.Desktop created.");
168 // String sInputURL = aCurrentParameter.sInputURL;
169 // String sOutputURL = aCurrentParameter.sOutputURL;
170 // String sPrintFileURL = aCurrentParameter.sPrintToFileURL;
171 // System.out.println(_sInputURL);
174 // set here the loadComponentFromURL() properties
175 // at the moment only 'Hidden' is set, so no window is opened at work
177 ArrayList aPropertyList = new ArrayList();
179 // check which properties should set and count it.
180 // if (_aGTA.isHidden())
181 // {
182 // nPropertyCount ++;
183 // }
184 // if (_aGTA.getImportFilterName() != null && _aGTA.getImportFilterName().length() > 0)
185 // {
186 // nPropertyCount ++;
187 // }
189 // initialize the propertyvalue
190 // int nPropertyIndex = 0;
191 // aProps = new PropertyValue[ nPropertyCount ];
193 // set all property values
194 if (_aGTA.isHidden())
196 PropertyValue Arg = new PropertyValue();
197 Arg.Name = "Hidden";
198 Arg.Value = Boolean.TRUE;
199 aPropertyList.add(Arg);
200 showProperty(Arg);
202 if (_aGTA.getImportFilterName() != null && _aGTA.getImportFilterName().length() > 0)
204 PropertyValue Arg = new PropertyValue();
205 Arg.Name = "FilterName";
206 Arg.Value = _aGTA.getImportFilterName();
207 aPropertyList.add(Arg);
208 showProperty(Arg);
211 GlobalLogWriter.get().println(DateHelper.getDateTimeForHumanreadableLog() + " Load document");
212 // GlobalLogWriter.get().flush();
214 XComponentLoader aCompLoader = (XComponentLoader) UnoRuntime.queryInterface( XComponentLoader.class, aDesktop);
216 // XComponent aDoc = null;
218 _aGTA.getPerformance().startTime(PerformanceContainer.Load);
219 aDoc = aCompLoader.loadComponentFromURL(_sInputURL, "_blank", 0, PropertyHelper.createPropertyValueArrayFormArrayList(aPropertyList) );
220 _aGTA.getPerformance().stopTime(PerformanceContainer.Load);
221 if (aDoc != null)
223 GlobalLogWriter.get().println(DateHelper.getDateTimeForHumanreadableLog() + " Load document done.");
224 showDocumentType(aDoc);
225 _aGTA.setDocumentType(getDocumentType(aDoc));
227 else
229 GlobalLogWriter.get().println(" Load document failed.");
230 if (_aGTA.getImportFilterName() != null && _aGTA.getImportFilterName().length() > 0)
232 GlobalLogWriter.get().println(" Please check FilterName := '" + _aGTA.getImportFilterName() + "'");
234 GlobalLogWriter.get().println("");
237 else
239 GlobalLogWriter.get().println("com.sun.star.frame.Desktop failed.");
242 catch ( com.sun.star.uno.Exception e )
244 // Some exception occures.FAILED
245 GlobalLogWriter.get().println("UNO Exception caught.");
246 GlobalLogWriter.get().println("Message: " + e.getMessage());
247 e.printStackTrace();
248 aDoc = null;
250 return aDoc;
253 static boolean exportToPDF(XComponent _xComponent, String _sDestinationName)
255 XServiceInfo xServiceInfo =
256 (XServiceInfo) UnoRuntime.queryInterface(
257 XServiceInfo.class, _xComponent
260 ArrayList aPropertyList = new ArrayList();
261 PropertyValue aFiltername = new PropertyValue();
262 aFiltername.Name = "FilterName";
263 aFiltername.Value = getFilterName_forPDF(xServiceInfo);
264 aPropertyList.add(aFiltername);
265 showProperty(aFiltername);
266 boolean bWorked = true;
270 XStorable store =
271 (XStorable) UnoRuntime.queryInterface(
272 XStorable.class, _xComponent
274 store.storeToURL(_sDestinationName, PropertyHelper.createPropertyValueArrayFormArrayList(aPropertyList));
276 catch (com.sun.star.io.IOException e)
278 GlobalLogWriter.get().println("IO Exception caught.");
279 GlobalLogWriter.get().println("Message: " + e.getMessage());
280 bWorked = false;
283 return bWorked;
286 static String getFilterName_forPDF(XServiceInfo xServiceInfo)
288 String filterName = "";
290 if (xServiceInfo.supportsService("com.sun.star.text.TextDocument"))
292 //writer
293 filterName = "writer_pdf_Export";
295 else if ( xServiceInfo.supportsService( "com.sun.star.sheet.SpreadsheetDocument" ) )
297 //calc
298 filterName = "calc_pdf_Export";
300 else if ( xServiceInfo.supportsService( "com.sun.star.drawing.DrawingDocument" ) )
302 //draw
303 filterName = "draw_pdf_Export";
305 else if ( xServiceInfo.supportsService( "com.sun.star.presentation.PresentationDocument" ) )
307 //impress
308 filterName = "impress_pdf_Export";
310 else if (xServiceInfo.supportsService("com.sun.star.text.WebDocument"))
312 //html document
313 filterName = "writer_web_pdf_Export";
315 else if ( xServiceInfo.supportsService("com.sun.star.text.GlobalDocument") )
317 //master document
318 filterName = "writer_globaldocument_pdf_Export";
320 else if ( xServiceInfo.supportsService( "com.sun.star.formulaFormulaProperties" ) )
322 //math document
323 filterName = "math_pdf_Export";
326 return filterName;
329 // -----------------------------------------------------------------------------
331 public static boolean storeAsPDF(GraphicalTestArguments _aGTA,
332 String _sInputURL,
333 String _sOutputURL)
335 boolean bBack = false;
336 XComponent aDoc = loadFromURL(_aGTA, _sInputURL);
338 if (aDoc == null)
340 GlobalLogWriter.get().println("Can't load document.");
341 return bBack;
343 bBack = storeAsPDF(_aGTA, aDoc, _sOutputURL);
344 createInfoFile(_sOutputURL, _aGTA, "as pdf");
346 GlobalLogWriter.get().println("Close document.");
347 aDoc.dispose();
348 return bBack;
351 public static boolean storeAsPDF(GraphicalTestArguments _aGTA,
352 XComponent _aDoc,
353 String _sOutputURL)
355 // try {
356 boolean bBack = true;
357 _aGTA.getPerformance().startTime(PerformanceContainer.StoreAsPDF);
358 bBack = exportToPDF(_aDoc, _sOutputURL);
359 _aGTA.getPerformance().stopTime(PerformanceContainer.StoreAsPDF);
361 if (!bBack)
363 GlobalLogWriter.get().println("Can't store document as PDF.");
364 bBack = false;
366 return bBack;
369 // -----------------------------------------------------------------------------
372 * print the document found in file (_sInputURL) to as postscript to file (_sPrintFileURL)
373 * Due to the fact we use a printer to convert the file to postscript, the default printer
374 * to create such postscript format must be installed, this is not tested here.
376 * @return true, if print has been done.
377 * Be careful, true means only print returns with no errors, to be sure print is really done
378 * check existance of _sPrintFileURL
381 public static boolean printToFileWithOOo(GraphicalTestArguments _aGTA,
382 String _sInputURL,
383 String _sOutputURL,
384 String _sPrintFileURL)
386 // waitInSeconds(1);
387 boolean bBack = false;
389 XComponent aDoc = loadFromURL(_aGTA, _sInputURL);
390 if (aDoc != null)
392 if ( _sInputURL.equals(_sOutputURL) )
394 // don't store document
395 // input and output are equal OR
396 GlobalLogWriter.get().println("Warning: Inputpath and Outputpath are equal. Document will not stored again.");
397 _aGTA.disallowStore();
399 bBack = impl_printToFileWithOOo(_aGTA, aDoc, _sOutputURL, _sPrintFileURL);
401 GlobalLogWriter.get().println("Close document.");
402 aDoc.dispose();
404 else
406 GlobalLogWriter.get().println("loadDocumentFromURL() failed with document: " + _sInputURL);
408 return bBack;
411 // -----------------------------------------------------------------------------
412 public static void createInfoFile(String _sFile, GraphicalTestArguments _aGTA)
414 createInfoFile(_sFile, _aGTA, "");
417 public static void createInfoFile(String _sFile, GraphicalTestArguments _aGTA, String _sSpecial)
419 String sFilename;
420 if (_sFile.startsWith("file://"))
422 sFilename = FileHelper.getSystemPathFromFileURL(_sFile);
423 GlobalLogWriter.get().println("CreateInfoFile: '" + sFilename + "'" );
425 else
427 sFilename = _sFile;
429 String sFileDir = FileHelper.getPath(sFilename);
430 String sBasename = FileHelper.getBasename(sFilename);
431 String sNameNoSuffix = FileHelper.getNameNoSuffix(sBasename);
433 String fs = System.getProperty("file.separator");
434 String ls = System.getProperty("line.separator");
435 String sInfoFilename = sFileDir + fs + sNameNoSuffix + ".info";
436 File aInfoFile = new File(sInfoFilename);
438 String sBuildID = "";
442 FileWriter out = new FileWriter(aInfoFile.toString());
443 out.write("# automatically created file by graphical compare" + ls);
444 if (_aGTA != null)
446 if (_sSpecial != null && _sSpecial.equals("msoffice"))
448 out.write("# buildid from wordloadfile" + ls);
449 sBuildID = _aGTA.getPerformance().getMSOfficeVersion();
450 out.write("buildid=" + sBuildID + ls);
452 else
454 out.write("# buildid is read out of the bootstrap file" + ls);
455 sBuildID = _aGTA.getBuildID();
456 out.write("buildid=" + sBuildID + ls);
458 // if (_sSpecial != null && _sSpecial.length() > 0)
459 // {
460 // out.write("special=" + _sSpecial + ls);
461 // }
462 out.write(ls);
463 out.write("# resolution given in DPI" + ls);
464 out.write("resolution=" + _aGTA.getResolutionInDPI() + ls);
466 else
468 out.write("buildid=" + _sSpecial + ls);
470 // long nTime = stopTimer();
471 // if (nTime != 0)
472 // {
473 // out.write("# time is given in milli seconds" + ls);
474 // out.write("time=" + nTime + ls);
475 // }
477 out.write(ls);
478 out.write("# Values out of System.getProperty(...)" + ls);
479 out.write("os.name=" + System.getProperty("os.name") + ls);
480 out.write("os.arch=" + System.getProperty("os.arch") + ls);
481 out.write("os.version=" + System.getProperty("os.version") + ls);
483 if (_aGTA != null)
485 out.write(ls);
486 out.write("# Performance output, values are given in milli sec." + ls);
487 _aGTA.getPerformance().print(out);
490 out.flush();
491 out.close();
493 catch (java.io.IOException e)
495 GlobalLogWriter.get().println("can't create Info file.");
496 e.printStackTrace();
499 String sExtension = FileHelper.getSuffix(_aGTA.getInputFile());
500 if (sExtension.startsWith("."))
502 sExtension = sExtension.substring(1);
505 DB.writeToDB(_aGTA.getInputFile(),
506 sNameNoSuffix,
507 sExtension,
508 sBuildID,
509 _aGTA.getReferenceType(),
510 _aGTA.getResolutionInDPI()
516 // -----------------------------------------------------------------------------
517 private static boolean impl_printToFileWithOOo(GraphicalTestArguments _aGTA,
518 XComponent _aDoc,
519 String _sOutputURL,
520 String _sPrintFileURL)
522 boolean bBack = false;
523 boolean bFailed = true; // always be a pessimist,
524 if (_aDoc == null)
526 GlobalLogWriter.get().println("No document is given.");
527 return bBack;
530 try
532 if (_sOutputURL != null)
534 if (_aGTA.isStoreAllowed())
536 // store the document in an other directory
537 XStorable aStorable = (XStorable) UnoRuntime.queryInterface( XStorable.class, _aDoc);
538 if (aStorable != null)
540 PropertyValue [] szEmptyArgs = new PropertyValue [0];
542 GlobalLogWriter.get().println(DateHelper.getDateTimeForHumanreadableLog() + " Store document.");
543 _aGTA.getPerformance().startTime(PerformanceContainer.Store);
544 aStorable.storeAsURL(_sOutputURL, szEmptyArgs);
545 _aGTA.getPerformance().stopTime(PerformanceContainer.Store);
547 GlobalLogWriter.get().println(DateHelper.getDateTimeForHumanreadableLog() + " Store document done.");
548 TimeHelper.waitInSeconds(2, "After store as URL to:" + _sOutputURL);
549 GlobalLogWriter.get().println("Reload stored file test.");
550 XComponent aDoc = loadFromURL(_aGTA, _sOutputURL);
551 if (aDoc == null)
553 GlobalLogWriter.get().println("Reload stored file test failed, can't reload file: " + _sOutputURL);
559 catch ( com.sun.star.uno.Exception e )
561 // Some exception occures.FAILED
562 GlobalLogWriter.get().println("UNO Exception caught.");
563 GlobalLogWriter.get().println("Message: " + e.getMessage());
565 e.printStackTrace();
566 bBack = false;
569 try
572 // System.out.println("Document loaded.");
573 // Change Pagesettings to DIN A4
575 GlobalLogWriter.get().println(DateHelper.getDateTimeForHumanreadableLog() + " Print document.");
576 XPrintable aPrintable = (XPrintable) UnoRuntime.queryInterface( XPrintable.class, _aDoc);
577 if (aPrintable != null)
579 // System.out.println(" Set PaperFormat to DIN A4");
580 // {
581 // PropertyValue[] aPrinterProps = aPrintable.getPrinter();
582 // System.out.println("PrinterProps size: " + String.valueOf(aPrinterProps.length));
583 // int nPropIndex = 0;
584 // while (!"PaperFormat".equals(aPrinterProps[nPropIndex].Name))
585 // {
586 // // System.out.println(aPrinterProps[nPropIndex].Name);
587 // nPropIndex++;
588 // }
589 // aPrinterProps[nPropIndex].Value = com.sun.star.view.PaperFormat.A4;
590 // aPrintable.setPrinter(aPrinterProps);
591 // }
593 // configure Office to allow to execute macos
595 // TODO: We need a possiblity to set the printer name also for StarOffice/OpenOffice
596 if (OSHelper.isWindows())
598 if (_aGTA.getPrinterName() != null)
600 ArrayList aPropertyList = new ArrayList();
601 // PropertyValue [] aPrintProps = new PropertyValue[1];
602 PropertyValue Arg = new PropertyValue();
603 Arg.Name = "Name";
604 Arg.Value = _aGTA.getPrinterName();
605 aPropertyList.add(Arg);
606 showProperty(Arg);
607 // GlobalLogWriter.get().println("Printername is not null, so set to " + _aGTA.getPrinterName());
608 aPrintable.setPrinter(PropertyHelper.createPropertyValueArrayFormArrayList(aPropertyList));
612 // set property values for XPrintable.print()
613 // more can be found at "http://api.openoffice.org/docs/common/ref/com/sun/star/view/PrintOptions.html"
615 // int nProperties = 1; // default for 'FileName' property
616 // if (_aGTA.printAllPages() == false)
617 // {
618 // // we don't want to print all pages, build Pages string by ourself
619 // nProperties ++;
620 // }
621 // int nPropsCount = 0;
623 // If we are a SpreadSheet (calc), we need to set PrintAllSheets property to 'true'
624 XServiceInfo xServiceInfo = (XServiceInfo) UnoRuntime.queryInterface( XServiceInfo.class, _aDoc );
625 if ( xServiceInfo.supportsService( "com.sun.star.sheet.SpreadsheetDocument" ) )
627 XMultiServiceFactory xMSF = _aGTA.getMultiServiceFactory();
628 Object aSettings = xMSF.createInstance( "com.sun.star.sheet.GlobalSheetSettings" );
629 if (aSettings != null)
631 XPropertySet xPropSet = (XPropertySet) UnoRuntime.queryInterface( XPropertySet.class, aSettings );
632 xPropSet.setPropertyValue( "PrintAllSheets", new Boolean( true ) );
636 ArrayList aPrintProps = new ArrayList();
637 GlobalLogWriter.get().println("Property FileName:=" + _sPrintFileURL);
639 // PropertyValue [] aPrintProps = new PropertyValue[nProperties];
640 PropertyValue Arg = new PropertyValue();
641 Arg.Name = "FileName";
642 Arg.Value = _sPrintFileURL;
643 // aPrintProps[nPropsCount ++] = Arg;
644 aPrintProps.add(Arg);
645 // showProperty(Arg);
647 if (_aGTA.printAllPages() == false)
649 String sPages = "";
650 if (_aGTA.getMaxPages() > 0)
652 sPages = "1-" + String.valueOf(_aGTA.getMaxPages());
654 if (_aGTA.getOnlyPages().length() != 0)
656 if (sPages.length() != 0)
658 sPages += ";";
660 sPages += String.valueOf(_aGTA.getOnlyPages());
663 Arg = new PropertyValue();
664 Arg.Name = "Pages";
665 Arg.Value = sPages;
666 aPrintProps.add(Arg);
668 showProperty(Arg);
670 // GlobalLogWriter.get().println("Start printing.");
672 _aGTA.getPerformance().startTime(PerformanceContainer.Print);
673 aPrintable.print(PropertyHelper.createPropertyValueArrayFormArrayList(aPrintProps));
674 TimeHelper.waitInSeconds(1, "Start waiting for print ready.");
676 GlobalLogWriter.get().println("Wait until document is printed.");
677 boolean isBusy = true;
678 int nPrintCount = 0;
679 while (isBusy)
681 PropertyValue[] aPrinterProps = aPrintable.getPrinter();
682 int nPropIndex = 0;
683 while (!"IsBusy".equals(aPrinterProps[nPropIndex].Name))
685 // System.out.println(aPrinterProps[nPropIndex].Name);
686 nPropIndex++;
688 isBusy = (aPrinterProps[nPropIndex].Value == Boolean.TRUE) ? true : false;
689 TimeHelper.waitInSeconds(1, "is print ready?");
690 nPrintCount++;
691 if (nPrintCount > 3600)
693 // we will never wait >1h until print is ready!
694 GlobalLogWriter.get().println("ERROR: Cancel print due to too long wait.");
695 throw new com.sun.star.uno.Exception("Convwatch exception, wait too long for printing.");
698 _aGTA.getPerformance().stopTime(PerformanceContainer.Print);
699 GlobalLogWriter.get().println(DateHelper.getDateTimeForHumanreadableLog() + " Print document done.");
701 // Create a .info file near the printed '.ps' or '.prn' file.
702 createInfoFile(_sPrintFileURL, _aGTA);
704 else
706 GlobalLogWriter.get().println("Can't get XPrintable interface.");
708 bFailed = false;
709 bBack = true;
711 catch ( com.sun.star.uno.Exception e )
713 // Some exception occures.FAILED
714 GlobalLogWriter.get().println("UNO Exception caught.");
715 GlobalLogWriter.get().println("Message: " + e.getMessage());
717 e.printStackTrace();
718 bBack = false;
721 if (bFailed == true)
723 GlobalLogWriter.get().println("convwatch.OfficePrint: FAILED");
725 else
727 GlobalLogWriter.get().println("convwatch.OfficePrint: OK");
729 return bBack;
734 * @return true, if the reference (*.prrn file) based on given output path and given input path exist.
735 * If OVERWRITE_REFERENCE is set, always return false.
737 public static boolean isReferenceExists(GraphicalTestArguments _aGTA,
738 String _sAbsoluteOutputPath,
739 String _sAbsoluteInputFile)
741 if (! FileHelper.exists(_sAbsoluteInputFile))
743 // throw new ConvWatchCancelException("Input file: " + _sAbsoluteInputFile + " does not exist.");
744 return false;
747 String fs = System.getProperty("file.separator");
749 // String sInputFileURL = URLHelper.getFileURLFromSystemPath(_sAbsoluteInputFile);
751 String sInputFileBasename = FileHelper.getBasename(_sAbsoluteInputFile);
752 // String sOutputFileURL = null;
753 String sOutputPath;
754 if (_sAbsoluteOutputPath != null)
756 sOutputPath = _sAbsoluteOutputPath;
757 // FileHelper.makeDirectories("", sOutputPath);
759 else
761 String sInputPath = FileHelper.getPath(_sAbsoluteInputFile);
762 sOutputPath = sInputPath;
764 // sOutputFileURL = URLHelper.getFileURLFromSystemPath(sOutputPath + fs + sInputFileBasename);
765 // sOutputFileURL = null;
767 String sPrintFilename = FileHelper.getNameNoSuffix(sInputFileBasename);
768 // String sPrintFileURL;
770 String sAbsolutePrintFilename = sOutputPath + fs + sPrintFilename + ".prn";
771 if (FileHelper.exists(sAbsolutePrintFilename) && _aGTA.getOverwrite() == false)
773 GlobalLogWriter.get().println("Reference already exist, don't overwrite. Set " + PropertyName.DOC_COMPARATOR_OVERWRITE_REFERENCE + "=true to force overwrite.");
774 return true;
776 return false;
779 // -----------------------------------------------------------------------------
781 * create a reference file
782 * _sAbsoluteInputPath contains the source file, if not exists, return with failure.
783 * _sAbsoluteOutputPath contains the destination, where the file will store after load with StarOffice/OpenOffice.org
784 * if is null, print only near the Input file path
785 * _sPrintType ".prn" Print input file with StarOffice/OpenOffice.org and the default printer as PostScript
788 public static boolean buildReference(GraphicalTestArguments _aGTA,
789 String _sAbsoluteOutputPath,
790 String _sAbsoluteInputFile)
791 throws ConvWatchCancelException
793 if (! FileHelper.exists(_sAbsoluteInputFile))
795 throw new ConvWatchCancelException("buildReference(): Input file: " + _sAbsoluteInputFile + " does not exist.");
798 String fs = System.getProperty("file.separator");
800 String sInputFileURL = URLHelper.getFileURLFromSystemPath(_sAbsoluteInputFile);
802 String sInputFileBasename = FileHelper.getBasename(_sAbsoluteInputFile);
803 String sOutputFileURL = null;
804 String sOutputPath;
805 if (_sAbsoluteOutputPath != null)
807 sOutputPath = _sAbsoluteOutputPath;
808 FileHelper.makeDirectories("", sOutputPath);
810 else
812 String sInputPath = FileHelper.getPath(_sAbsoluteInputFile);
813 sOutputPath = sInputPath;
815 // sOutputFileURL = URLHelper.getFileURLFromSystemPath(sOutputPath + fs + sInputFileBasename);
816 sOutputFileURL = null;
818 String sPrintFilename = FileHelper.getNameNoSuffix(sInputFileBasename);
819 String sPrintFileURL;
821 String sAbsolutePrintFilename = sOutputPath + fs + sPrintFilename + ".prn";
822 if (FileHelper.exists(sAbsolutePrintFilename) && _aGTA.getOverwrite() == false)
824 GlobalLogWriter.get().println("Reference already exist, don't overwrite. Set " + PropertyName.DOC_COMPARATOR_OVERWRITE_REFERENCE + "=true to force overwrite.");
825 return true;
828 if (_aGTA.getReferenceType().toLowerCase().equals("msoffice"))
830 sPrintFileURL = URLHelper.getFileURLFromSystemPath(sAbsolutePrintFilename);
832 else if (_aGTA.getReferenceType().toLowerCase().equals("pdf"))
834 // TODO: If we rename the stored file to *.pdf, we have to be sure that we use *.pdf also as a available reference
835 sPrintFileURL = URLHelper.getFileURLFromSystemPath(sAbsolutePrintFilename );
837 else if (_aGTA.getReferenceType().toLowerCase().equals("ooo"))
839 sPrintFileURL = URLHelper.getFileURLFromSystemPath(sAbsolutePrintFilename );
841 else
843 GlobalLogWriter.get().println("OfficePrint.buildreference(): Unknown print type.");
844 return false;
846 return printToFile(_aGTA, sInputFileURL, sOutputFileURL, sPrintFileURL);
849 public static boolean printToFile(GraphicalTestArguments _aGTA,
850 String _sInputFileURL,
851 String _sOutputFileURL,
852 String _sPrintFileURL) throws ConvWatchCancelException
854 boolean bBack = false;
855 String sPrintFileURL = null;
857 // check if given file is a picture, then do nothing
858 String sDocumentSuffix = FileHelper.getSuffix(_sInputFileURL);
859 if (sDocumentSuffix.toLowerCase().endsWith(".png") ||
860 sDocumentSuffix.toLowerCase().endsWith(".gif") ||
861 sDocumentSuffix.toLowerCase().endsWith(".jpg") ||
862 sDocumentSuffix.toLowerCase().endsWith(".bmp"))
864 return false;
868 // remember the current timer, to know how long a print process need.
869 // startTimer();
871 if (_aGTA.getReferenceType().toLowerCase().equals("ooo"))
873 bBack = printToFileWithOOo(_aGTA, _sInputFileURL, _sOutputFileURL, _sPrintFileURL);
875 else if (_aGTA.getReferenceType().toLowerCase().equals("pdf"))
877 GlobalLogWriter.get().println("USE PDF AS EXPORT FORMAT.");
878 bBack = storeAsPDF(_aGTA, _sInputFileURL, _sPrintFileURL);
880 else if (_aGTA.getReferenceType().toLowerCase().equals("msoffice"))
882 if (MSOfficePrint.isMSOfficeDocumentFormat(_sInputFileURL))
884 GlobalLogWriter.get().println("USE MSOFFICE AS EXPORT FORMAT.");
885 MSOfficePrint a = new MSOfficePrint();
888 a.printToFileWithMSOffice(_aGTA, FileHelper.getSystemPathFromFileURL(_sInputFileURL),
889 FileHelper.getSystemPathFromFileURL(_sPrintFileURL));
891 catch(ConvWatchCancelException e)
893 e.printStackTrace();
894 GlobalLogWriter.get().println(e.getMessage());
895 throw new ConvWatchCancelException("Exception caught. Problem with MSOffice printer methods.");
897 catch(java.io.IOException e)
899 GlobalLogWriter.get().println(e.getMessage());
900 throw new ConvWatchCancelException("IOException caught. Problem with MSOffice printer methods.");
902 bBack = true;
904 else
906 GlobalLogWriter.get().println("This document type is not recognized as MSOffice format, as default fallback StarOffice/OpenOffice.org instead is used.");
907 bBack = printToFileWithOOo(_aGTA, _sInputFileURL, _sOutputFileURL, _sPrintFileURL);
910 else
912 // System.out.println("");
913 throw new ConvWatchCancelException("OfficePrint.printToFile(): Unknown print type.");
915 return bBack;
918 // -----------------------------------------------------------------------------
919 // TODO: move this away!
920 // -----------------------------------------------------------------------------
921 static void showType(String _sInputURL, XMultiServiceFactory _xMSF)
923 if (_sInputURL.length() == 0)
925 return;
928 if (_xMSF == null)
930 GlobalLogWriter.get().println("MultiServiceFactory not set.");
931 return;
933 XTypeDetection aTypeDetection = null;
936 Object oObj = _xMSF.createInstance("com.sun.star.document.TypeDetection");
937 aTypeDetection = (XTypeDetection)UnoRuntime.queryInterface(XTypeDetection.class, oObj);
939 catch(com.sun.star.uno.Exception e)
941 GlobalLogWriter.get().println("Can't get com.sun.star.document.TypeDetection.");
942 return;
944 if (aTypeDetection != null)
946 String sType = aTypeDetection.queryTypeByURL(_sInputURL);
947 GlobalLogWriter.get().println("Type is: " + sType);
952 // -----------------------------------------------------------------------------
953 public static String getInternalFilterName(String _sFilterName, XMultiServiceFactory _xMSF)
955 if (_sFilterName.length() == 0)
957 // System.out.println("No FilterName set.");
958 return null;
961 if (_xMSF == null)
963 GlobalLogWriter.get().println("MultiServiceFactory not set.");
964 return null;
966 // XFilterFactory aFilterFactory = null;
967 Object aObj = null;
970 aObj = _xMSF.createInstance("com.sun.star.document.FilterFactory");
972 catch(com.sun.star.uno.Exception e)
974 GlobalLogWriter.get().println("Can't get com.sun.star.document.FilterFactory.");
975 return null;
977 if (aObj != null)
979 XNameAccess aNameAccess = (XNameAccess)UnoRuntime.queryInterface(XNameAccess.class, aObj);
980 if (aNameAccess != null)
983 // if (_sFilterName.toLowerCase().equals("help"))
984 // {
985 // System.out.println("Show all possible ElementNames from current version." );
986 // String[] aElementNames = aNameAccess.getElementNames();
987 // for (int i = 0; i<aElementNames.length; i++)
988 // {
989 // System.out.println(aElementNames[i]);
990 // }
991 // System.out.println("Must quit.");
992 // System.out.exit(1);
993 // }
995 if (! aNameAccess.hasByName(_sFilterName))
997 GlobalLogWriter.get().println("FilterFactory.hasByName() says there exist no '" + _sFilterName + "'" );
998 return null;
1001 Object[] aElements = null;
1002 String[] aExtensions;
1005 aElements = (Object[]) aNameAccess.getByName(_sFilterName);
1006 if (aElements != null)
1008 String sInternalFilterName = null;
1009 // System.out.println("getByName().length: " + String.valueOf(aElements.length));
1010 for (int i=0;i<aElements.length; i++)
1012 PropertyValue aPropertyValue = (PropertyValue)aElements[i];
1013 // System.out.println("PropertyValue.Name: " + aPropertyValue.Name);
1014 if (aPropertyValue.Name.equals("Type"))
1016 String sValue = (String)aPropertyValue.Value;
1017 // System.out.println("Type: " + sValue);
1018 sInternalFilterName = sValue;
1021 return sInternalFilterName;
1023 else
1025 GlobalLogWriter.get().println("There are no elements for FilterName '" + _sFilterName + "'");
1026 return null;
1029 catch (com.sun.star.container.NoSuchElementException e)
1031 GlobalLogWriter.get().println("NoSuchElementException caught. " + e.getMessage());
1033 catch (com.sun.star.lang.WrappedTargetException e)
1035 GlobalLogWriter.get().println("WrappedTargetException caught. " + e.getMessage());
1039 return null;
1042 // -----------------------------------------------------------------------------
1044 static String getServiceNameFromFilterName(String _sFilterName, XMultiServiceFactory _xMSF)
1046 if (_sFilterName.length() == 0)
1048 // System.out.println("No FilterName set.");
1049 return null;
1052 if (_xMSF == null)
1054 GlobalLogWriter.get().println("MultiServiceFactory not set.");
1055 return null;
1057 // XFilterFactory aFilterFactory = null;
1058 Object aObj = null;
1061 aObj = _xMSF.createInstance("com.sun.star.document.FilterFactory");
1063 catch(com.sun.star.uno.Exception e)
1065 GlobalLogWriter.get().println("Can't get com.sun.star.document.FilterFactory.");
1066 return null;
1068 if (aObj != null)
1070 XNameAccess aNameAccess = (XNameAccess)UnoRuntime.queryInterface(XNameAccess.class, aObj);
1071 if (aNameAccess != null)
1073 if (! aNameAccess.hasByName(_sFilterName))
1075 GlobalLogWriter.get().println("FilterFactory.hasByName() says there exist no '" + _sFilterName + "'" );
1076 return null;
1079 Object[] aElements = null;
1080 String[] aExtensions;
1083 aElements = (Object[]) aNameAccess.getByName(_sFilterName);
1084 if (aElements != null)
1086 String sServiceName = null;
1087 // System.out.println("getByName().length: " + String.valueOf(aElements.length));
1088 for (int i=0;i<aElements.length; i++)
1090 PropertyValue aPropertyValue = (PropertyValue)aElements[i];
1091 if (aPropertyValue.Name.equals("DocumentService"))
1093 String sValue = (String)aPropertyValue.Value;
1094 // System.out.println("DocumentService: " + sValue);
1095 sServiceName = sValue;
1096 break;
1099 return sServiceName;
1101 else
1103 GlobalLogWriter.get().println("There are no elements for FilterName '" + _sFilterName + "'");
1104 return null;
1107 catch (com.sun.star.container.NoSuchElementException e)
1109 GlobalLogWriter.get().println("NoSuchElementException caught. " + e.getMessage());
1111 catch (com.sun.star.lang.WrappedTargetException e)
1113 GlobalLogWriter.get().println("WrappedTargetException caught. " + e.getMessage());
1117 return null;
1119 // -----------------------------------------------------------------------------
1121 public static String getFileExtension(String _sInternalFilterName, XMultiServiceFactory _xMSF)
1123 if (_sInternalFilterName.length() == 0)
1125 // System.out.println("No FilterName set.");
1126 return null;
1129 if (_xMSF == null)
1131 GlobalLogWriter.get().println("MultiServiceFactory not set.");
1132 return null;
1134 XTypeDetection aTypeDetection = null;
1137 Object oObj = _xMSF.createInstance("com.sun.star.document.TypeDetection");
1138 aTypeDetection = (XTypeDetection)UnoRuntime.queryInterface(XTypeDetection.class, oObj);
1140 catch(com.sun.star.uno.Exception e)
1142 GlobalLogWriter.get().println("Can't get com.sun.star.document.TypeDetection.");
1143 return null;
1145 if (aTypeDetection != null)
1147 XNameAccess aNameAccess = (XNameAccess)UnoRuntime.queryInterface(XNameAccess.class, aTypeDetection);
1148 if (aNameAccess != null)
1151 // System.out.println("Show ElementNames" );
1152 // String[] aElementNames = aNameAccess.getElementNames();
1153 // for (int i = 0; i<aElementNames.length; i++)
1154 // {
1155 // System.out.println(aElementNames[i]);
1156 // }
1158 if (! aNameAccess.hasByName(_sInternalFilterName))
1160 GlobalLogWriter.get().println("TypeDetection.hasByName() says there exist no '" + _sInternalFilterName + "'" );
1161 return null;
1164 Object[] aElements = null;
1165 String[] aExtensions;
1168 aElements = (Object[]) aNameAccess.getByName(_sInternalFilterName);
1169 if (aElements != null)
1171 String sExtension = null;
1172 // System.out.println("getByName().length: " + String.valueOf(aElements.length));
1173 for (int i=0;i<aElements.length; i++)
1175 PropertyValue aPropertyValue = (PropertyValue)aElements[i];
1176 // System.out.println("PropertyValue.Name: " + aPropertyValue.Name);
1177 if (aPropertyValue.Name.equals("Extensions"))
1179 aExtensions = (String[])aPropertyValue.Value;
1180 GlobalLogWriter.get().println(" Possible extensions are: " + String.valueOf(aExtensions.length));
1181 if (aExtensions.length > 0)
1183 for (int j=0;j<aExtensions.length;j++)
1185 GlobalLogWriter.get().println(" " + aExtensions[j]);
1187 sExtension = aExtensions[0];
1188 GlobalLogWriter.get().println("");
1192 return sExtension;
1194 else
1196 GlobalLogWriter.get().println("There are no elements for FilterName '" + _sInternalFilterName + "'");
1197 return null;
1200 catch (com.sun.star.container.NoSuchElementException e)
1202 GlobalLogWriter.get().println("NoSuchElementException caught. " + e.getMessage());
1204 catch (com.sun.star.lang.WrappedTargetException e)
1206 GlobalLogWriter.get().println("WrappedTargetException caught. " + e.getMessage());
1210 return null;
1213 // -----------------------------------------------------------------------------
1214 public static void convertDocument(String _sInputFile, String _sOutputPath, GraphicalTestArguments _aGTA) throws ConvWatchCancelException
1216 XMultiServiceFactory xMSF = _aGTA.getMultiServiceFactory();
1217 if (xMSF == null)
1219 GlobalLogWriter.get().println("MultiServiceFactory in GraphicalTestArgument not set.");
1220 return;
1223 String sInputURL = URLHelper.getFileURLFromSystemPath(_sInputFile);
1224 // showType(sInputURL, xMSF);
1225 XComponent aDoc = loadFromURL( _aGTA, sInputURL);
1226 if (aDoc == null)
1228 GlobalLogWriter.get().println("Can't load document '"+ sInputURL + "'");
1229 return;
1232 if (_sOutputPath == null)
1234 GlobalLogWriter.get().println("Outputpath not set.");
1235 return;
1238 if (! _aGTA.isStoreAllowed())
1240 GlobalLogWriter.get().println("It's not allowed to store, check Input/Output path.");
1241 return;
1243 // TODO: Do we need to wait?
1244 TimeHelper.waitInSeconds(1, "wait after loadFromURL.");
1246 XServiceInfo xServiceInfo = (XServiceInfo) UnoRuntime.queryInterface( XServiceInfo.class, aDoc );
1247 // String sFilter = getFilterName_forExcel(xServiceInfo);
1248 // System.out.println("Filter is " + sFilter);
1250 // store the document in an other directory
1251 XStorable xStorable = (XStorable) UnoRuntime.queryInterface( XStorable.class, aDoc);
1252 if (xStorable == null)
1254 GlobalLogWriter.get().println("com.sun.star.frame.XStorable is null");
1255 return;
1258 String sFilterName = _aGTA.getExportFilterName();
1260 // check how many Properties should initialize
1261 int nPropertyCount = 0;
1262 // if (sFilterName != null && sFilterName.length() > 0)
1263 // {
1264 // nPropertyCount ++;
1265 // }
1267 // initialize PropertyArray
1268 // PropertyValue [] aStoreProps = new PropertyValue[ nPropertyCount ];
1269 // int nPropertyIndex = 0;
1270 ArrayList aPropertyList = new ArrayList();
1272 String sExtension = "";
1274 if (sFilterName != null && sFilterName.length() > 0)
1276 String sInternalFilterName = getInternalFilterName(sFilterName, xMSF);
1277 String sServiceName = getServiceNameFromFilterName(sFilterName, xMSF);
1279 GlobalLogWriter.get().println("Filter detection:");
1280 // check if service name from file filter is the same as from the loaded document
1281 boolean bServiceFailed = false;
1282 if (sServiceName == null || sInternalFilterName == null)
1284 GlobalLogWriter.get().println("Given FilterName '" + sFilterName + "' seems to be unknown.");
1285 bServiceFailed = true;
1287 if (! xServiceInfo.supportsService(sServiceName))
1289 GlobalLogWriter.get().println("Service from FilterName '" + sServiceName + "' is not supported by loaded document.");
1290 bServiceFailed = true;
1292 if (bServiceFailed == true)
1294 GlobalLogWriter.get().println("Please check '" + PropertyName.DOC_CONVERTER_EXPORT_FILTER_NAME + "' in the property file.");
1295 return;
1298 if (sInternalFilterName != null && sInternalFilterName.length() > 0)
1300 // get the FileExtension, by the filter name, if we don't get a file extension
1301 // we assume the is also no right filter name.
1302 sExtension = getFileExtension(sInternalFilterName, xMSF);
1303 if (sExtension == null)
1305 GlobalLogWriter.get().println("Can't found an extension for filtername, take it from the source.");
1309 PropertyValue Arg = new PropertyValue();
1310 Arg.Name = "FilterName";
1311 Arg.Value = sFilterName;
1312 // aStoreProps[nPropertyIndex ++] = Arg;
1313 aPropertyList.add(Arg);
1314 showProperty(Arg);
1315 GlobalLogWriter.get().println("FilterName is set to: " + sFilterName);
1318 String sOutputURL = "";
1321 // create the new filename with the extension, which is ok to the file format
1322 String sInputFileBasename = FileHelper.getBasename(_sInputFile);
1323 // System.out.println("InputFileBasename " + sInputFileBasename);
1324 String sInputFileNameNoSuffix = FileHelper.getNameNoSuffix(sInputFileBasename);
1325 // System.out.println("InputFilename no suffix " + sInputFileNameNoSuffix);
1326 String fs = System.getProperty("file.separator");
1327 String sOutputFile = _sOutputPath;
1328 if (! sOutputFile.endsWith(fs))
1330 sOutputFile += fs;
1332 if (sExtension != null && sExtension.length() > 0)
1334 sOutputFile += sInputFileNameNoSuffix + "." + sExtension;
1336 else
1338 sOutputFile += sInputFileBasename;
1341 if (FileHelper.exists(sOutputFile) && _aGTA.getOverwrite() == false)
1343 GlobalLogWriter.get().println("File already exist, don't overwrite. Set " + PropertyName.DOC_COMPARATOR_OVERWRITE_REFERENCE + "=true to force overwrite.");
1344 return;
1347 sOutputURL = URLHelper.getFileURLFromSystemPath(sOutputFile);
1349 GlobalLogWriter.get().println("Store document as '" + sOutputURL + "'");
1350 xStorable.storeAsURL(sOutputURL, PropertyHelper.createPropertyValueArrayFormArrayList(aPropertyList));
1351 GlobalLogWriter.get().println("Document stored.");
1353 catch (com.sun.star.io.IOException e)
1355 GlobalLogWriter.get().println("Can't store document '" + sOutputURL + "'. Message is :'" + e.getMessage() + "'");
1357 // TODO: Do we need to wait?
1358 TimeHelper.waitInSeconds(1, "unknown in OfficePrint.convertDocument()");