1 /*************************************************************************
2  *
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * Copyright 2000, 2010 Oracle and/or its affiliates.
6  *
7  * OpenOffice.org - a multi-platform office productivity suite
8  *
9  * This file is part of OpenOffice.org.
10  *
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.
14  *
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).
20  *
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.
25  *
26  ************************************************************************/
27 
28 package graphical;
29 
30 import java.io.File;
31 import java.io.FileWriter;
32 import java.io.RandomAccessFile;
33 import helper.ProcessHandler;
34 import java.util.ArrayList;
35 import helper.OSHelper;
36 import javax.xml.parsers.DocumentBuilder;
37 import javax.xml.parsers.DocumentBuilderFactory;
38 import org.w3c.dom.Document;
39 import org.w3c.dom.Node;
40 
41 /**
42  * This object gives all functionallity to print msoffice documents.
43  * It also offers functions to check what type of document it is.
44  * It handles *.doc as word documents and use word to print
45  * *.xls as excel
46  * *.ppt as powerpoint
47  */
48 
49 //class ProcessHelper
50 //{
51 //    ArrayList m_aArray;
52 //}
53 
54 public class MSOfficePostscriptCreator implements IOffice
55 {
56     private String m_sPrinterName;               // within Windows the tools need a printer name;
57 
58     public void setPrinterName(String _s)
59     {
60         m_sPrinterName = _s;
61     }
62 
63     private ParameterHelper m_aParameterHelper;
64     private String m_sDocumentName;
65     private String m_sResult;
66 
67     // CTor
68     public MSOfficePostscriptCreator(ParameterHelper _aParam, String _sResult)
69     {
70         m_aParameterHelper = _aParam;
71         m_sResult = _sResult;
72 //        String sKillCommand = (String)_aParam.getTestParameters().get(util.PropertyName.APP_KILL_COMMAND);
73 //        if (sKillCommand == null)
74 //        {
75 //            sKillCommand = "";
76 //        }
77 //        if (sKillCommand.length() > 0)
78 //        {
79 //            sKillCommand += ";";
80 //        }
81         String sKillCommand = "C:/bin/kill.exe -9 winword;C:/bin/kill.exe -9 excel";
82         _aParam.getTestParameters().put(util.PropertyName.APP_KILL_COMMAND, sKillCommand);
83     }
84 
85     public void load(String _sDocumentName) throws OfficeException
86     {
87         m_sDocumentName = _sDocumentName;
88 
89         if (! isMSOfficeDocumentFormat(m_sDocumentName))
90         {
91             GlobalLogWriter.println("This document type is not recognized as MSOffice format, as default fallback StarOffice/OpenOffice.org instead is used.");
92             throw new OfficeException("This document type is not recognized as MSOffice format, as default fallback StarOffice/OpenOffice.org instead is used.");
93         }
94     }
95 
96     public void storeAsPostscript() throws OfficeException
97     {
98         GlobalLogWriter.println("USE MSOFFICE AS EXPORT FORMAT.");
99         try
100         {
101             String sDocumentName = m_sDocumentName + ".ps";
102             printToFileWithMSOffice(m_aParameterHelper,
103                                     m_sDocumentName,
104                                     m_sResult);
105             File aFile = new File(sDocumentName);
106             if (aFile.exists())
107             {
108                 String sBasename = FileHelper.getBasename(sDocumentName);
109                 FileHelper.addBasenameToIndex(m_sResult, sBasename, "msoffice", "postscript", m_sDocumentName);
110             }
111         }
112         catch(OfficeException e)
113         {
114             e.printStackTrace();
115             GlobalLogWriter.println(e.getMessage());
116             throw new OfficeException("Exception caught. Problem with MSOffice printer methods.");
117         }
118         catch(java.io.IOException e)
119         {
120             GlobalLogWriter.println(e.getMessage());
121             throw new OfficeException("IOException caught. Problem with MSOffice printer methods.");
122         }
123     }
124 
125     public void start() throws OfficeException
126     {
127         // we don't have an office to start
128     }
129 
130     public void close() throws OfficeException
131     {
132         // we don't have an office to stop
133     }
134 
135     // -----------------------------------------------------------------------------
136     private boolean isWordDocument(String _sSuffix)
137         {
138             if (_sSuffix.toLowerCase().endsWith(".doc") ||
139                 _sSuffix.toLowerCase().endsWith(".rtf") ||
140                 _sSuffix.toLowerCase().endsWith(".dot"))
141             {
142                 return true;
143             }
144             return false;
145         }
146 
147     private boolean isExcelDocument(String _sSuffix)
148         {
149             // xlt templates
150             // xlw
151             // xla addin
152             if (_sSuffix.toLowerCase().endsWith(".xls"))
153             {
154                 return true;
155             }
156             /* temporal insertion by SUS
157             if (_sSuffix.endsWith(".xml"))
158             {
159                 return true;
160             }*/
161             return false;
162         }
163 
164     private boolean isPowerPointDocument(String _sSuffix)
165         {
166             if (_sSuffix.toLowerCase().endsWith(".pps") ||
167                 _sSuffix.toLowerCase().endsWith(".ppt"))
168             {
169                 return true;
170             }
171             return false;
172         }
173 
174     /**
175      * returns true, if the given filename has a MS Office suffix.
176      */
177     private boolean isMSOfficeDocumentFormat(String _sFile)
178     {
179         String sDocumentSuffix = FileHelper.getSuffix(_sFile);
180         if (isWordDocument(sDocumentSuffix)) {return true;}
181         if (isExcelDocument(sDocumentSuffix)) {return true;}
182         if (isPowerPointDocument(sDocumentSuffix)) {return true;}
183         // if suffix is xml, return also true, but we can't decide if word or excel
184         if (sDocumentSuffix.toLowerCase().endsWith(".xml")) {return true;}
185         return false;
186     }
187 
188     public void storeToFileWithMSOffice( ParameterHelper _aGTA,
189                                          String _sInputFile,
190                                          String _sOutputFile) throws OfficeException, java.io.IOException
191         {
192             String sDocumentSuffix = FileHelper.getSuffix(_sInputFile);
193             String sFilterName = _aGTA.getExportFilterName();
194             ArrayList<String> aStartCommand = new ArrayList<String>();
195             if (isWordDocument(sDocumentSuffix))
196             {
197                 aStartCommand = createWordStoreHelper();
198             }
199             else if (isExcelDocument(sDocumentSuffix))
200             {
201                 aStartCommand = createExcelStoreHelper();
202             }
203             else if (isPowerPointDocument(sDocumentSuffix))
204             {
205             }
206             else if (sDocumentSuffix.toLowerCase().equals(".xml"))
207             {
208                 // special case, if xml we prefer word, but with DEFAULT_XML_FORMAT_APP=excel it's changeable.
209                 String sDocFormat = getXMLDocumentFormat(_sInputFile);
210                 // if (_aGTA.getDefaultXMLFormatApp().toLowerCase().equals("excel"))
211                 if (sDocFormat.equals("excel"))
212                 {
213                     aStartCommand = createExcelStoreHelper();
214                 }
215                 else
216                 {
217                     aStartCommand = createWordStoreHelper();
218                 }
219                 // else
220                 // {
221                 // }
222             }
223             else
224             {
225                 GlobalLogWriter.println("No Microsoft Office document format found.");
226 
227                 throw new WrongSuffixException("No MS office document format found.");
228             }
229             if (aStartCommand != null)
230             {
231                 if (sFilterName == null)
232                 {
233 // TODO: hardcoded FilterName in perl script
234                     sFilterName = ""; // xlXMLSpreadsheet";
235                 }
236 
237                 // String sCommand = sStartCommand + " " +
238                 //     _sInputFile + " " +
239                 //     StringHelper.doubleQuote(sFilterName) + " " +
240                 //     _sOutputFile;
241 
242                 aStartCommand.add(_sInputFile);
243                 aStartCommand.add(sFilterName);
244                 aStartCommand.add(_sOutputFile);
245                 realStartCommand(aStartCommand);
246             }
247         }
248 
249     // -----------------------------------------------------------------------------
250     /**
251      * print the given file (_sInputFile) to the file name (_sPrintFile)
252      * @param _aGTA
253      * @param _sInputFile
254      * @param _sPrintFilename
255      * @throws OfficeException
256      * @throws java.io.IOException
257      */
258     public void printToFileWithMSOffice( ParameterHelper _aGTA,
259                                          String _sInputFile,
260                                          String _sPrintFilename) throws OfficeException, java.io.IOException
261         {
262             String sDocumentSuffix = FileHelper.getSuffix(_sInputFile);
263 
264             setPrinterName(_aGTA.getPrinterName());
265 
266             ArrayList<String> aStartCommand = new ArrayList<String>();
267             if (isWordDocument(sDocumentSuffix))
268             {
269                 aStartCommand = createWordPrintHelper();
270             }
271             else if (isExcelDocument(sDocumentSuffix))
272             {
273                 aStartCommand = createExcelPrintHelper();
274             }
275             else if (isPowerPointDocument(sDocumentSuffix))
276             {
277                 aStartCommand = createPowerPointPrintHelper();
278             }
279             else if (sDocumentSuffix.toLowerCase().equals(".xml"))
280             {
281 // TODO: Open XML File and check if we need excel or word
282                 String sOfficeType = getOfficeType(_sInputFile);
283 
284                 // special case, if xml we prefer word, but with DEFAULT_XML_FORMAT_APP=excel it's changeable.
285                 // if (_aGTA.getDefaultXMLFormatApp().toLowerCase().equals("excel"))
286                 if (sOfficeType.equals("excel"))
287                 {
288                     aStartCommand = createExcelPrintHelper();
289                 }
290                 else if (sOfficeType.equals("word"))
291                 {
292                     aStartCommand = createWordPrintHelper();
293                 }
294                 else
295                 {
296                     return;
297                 }
298             }
299             else
300             {
301                 GlobalLogWriter.println("No Microsoft Office document format found.");
302 // TODO: use a better Exception!!!
303                 throw new WrongSuffixException("No Mircosoft Office document format found.");
304             }
305 
306             if (aStartCommand.isEmpty() == false)
307             {
308                 String sPrinterName = m_sPrinterName;
309                 if (sPrinterName == null)
310                 {
311                     sPrinterName = "";
312                 }
313 
314                 // String sCommand = sStartCommand + " " +
315                 //     _sInputFile + " " +
316                 //     StringHelper.doubleQuote(m_sPrinterName) + " " +
317                 //     _sPrintFilename;
318                 aStartCommand.add(_sInputFile);
319                 aStartCommand.add(m_sPrinterName);
320                 aStartCommand.add(_sPrintFilename);
321 
322                 realStartCommand(aStartCommand);
323             }
324             String sUserDir = System.getProperty("user.home");
325             _aGTA.getPerformance().readWordValuesFromFile(FileHelper.appendPath(sUserDir, "msofficeloadtimes.txt"));
326             FileHelper.createInfoFile(_sPrintFilename, _aGTA, "msoffice");
327             TimeHelper.waitInSeconds(2, "Give Microsoft Office some time to print.");
328         }
329 
330     public void realStartCommand(ArrayList _aStartCommand) throws OfficeException
331         {
332             if (_aStartCommand.isEmpty())
333             {
334                 throw new OfficeException/*WrongEnvironmentException*/("Given list is empty.");
335             }
336 
337             try
338             {
339                 // Convert the StartCommand ArrayList to a String List
340                 int nValues = _aStartCommand.size();
341                 String[] aList = new String[nValues];
342                 for (int i=0;i<nValues;i++)
343                 {
344                     String aStr = (String) _aStartCommand.get(i);
345                     if (aStr == null)
346                     {
347                         aStr = "";
348                     }
349                     if (aStr.length() == 0)
350                     {
351                         aStr = "\"\"";
352                     }
353                     aList[i] = new String(aStr);
354                 }
355 
356                 // This is really the latest point where we can check if we are running within windows environment
357                 if (! OSHelper.isWindows())
358                 {
359                     // TODO: use a better Exception!!!
360                     throw new WrongEnvironmentException("We doesn't work within windows environment.");
361                 }
362 
363 
364                 ProcessHandler aHandler = new ProcessHandler(aList);
365                 boolean bBackValue = aHandler.executeSynchronously();
366             }
367             catch (IndexOutOfBoundsException e)
368             {
369                 throw new WrongEnvironmentException("Given list is too short.");
370             }
371 
372             // return aHandler.getExitCode();
373         }
374 
375 
376     private String getPerlExe()
377     {
378         final String sPerlExe = System.getProperty("perl.exe", "perl");
379         return sPerlExe;
380     }
381 
382     ArrayList<String> createWordPrintHelper() throws java.io.IOException
383         {
384             // create a program in tmp file
385             String sTmpPath = util.utils.getUsersTempDir();
386             String ls = System.getProperty("line.separator");
387 
388             String sPrintViaWord = "printViaWord.pl";
389 
390             ArrayList<String> aList = searchLocalFile(sPrintViaWord);
391             if (aList.isEmpty() == false)
392             {
393                 return aList;
394             }
395 
396             String sFileName = FileHelper.appendPath(sTmpPath, sPrintViaWord);
397             File aFile = new File(sFileName);
398             FileWriter out = new FileWriter(aFile);
399 
400 
401             out.write( "eval 'exec perl -wS $0 ${1+\"$@\"}'                                                          " + ls );
402             out.write( "   if 0;                                                                                     " + ls );
403             out.write( "use strict;                                                                                  " + ls );
404             out.write( "use Time::HiRes;                                                                             " + ls );
405             out.write( "if ( $^O ne \"MSWin32\")                                                                     " + ls );
406             out.write( "{                                                                                            " + ls );
407             out.write( "   print 'Windows only.\\n';                                                                  " + ls );
408             out.write( "   print_usage();                                                                            " + ls );
409             out.write( "   exit(1);                                                                                  " + ls );
410             out.write( "}                                                                                            " + ls );
411             out.write( "                                                                                             " + ls );
412             out.write( "use Win32::OLE;                                                                              " + ls );
413             out.write( "use Win32::OLE::Const 'Microsoft Word';                                                      " + ls );
414             out.write( "                                                                                             " + ls );
415             out.write( "# ------ usage ------                                                                        " + ls );
416             out.write( "sub print_usage()                                                                            " + ls );
417             out.write( "{                                                                                            " + ls );
418             out.write( "    print STDERR \"Usage: word_print.pl  <Word file> <name of printer> <output file> .\\n     " + ls );
419             out.write( "                  Please use the same string for the name of the printer as you can find \\n  " + ls );
420             out.write( "                  under Start-Control Panel-Printer and Faxes  \\n                        " + ls );
421             out.write( "                  The name could look like the the following line: \\n                        " + ls );
422             out.write( "                  Apple LaserWriter II NT v47.0 \\n                                           " + ls );
423             out.write( "                  Sample command line: \\n                                                    " + ls );
424             out.write( "                  execl_print.pl  c:\\book1.doc Apple LaserWriter II NT v47.0 c:\\output\\book1.ps \\n\";  " + ls );
425             out.write( "}                                                                                            " + ls );
426             out.write( "                                                                                             " + ls );
427             out.write( "                                                                                             " + ls );
428             out.write( "if ($#ARGV != 2)                                                                             " + ls );
429             out.write( "{                                                                                            " + ls );
430             out.write( "   print 'Too less arguments.\\n';                                                            " + ls );
431             out.write( "   print_usage();                                                                            " + ls );
432             out.write( "   exit(1);                                                                                  " + ls );
433             out.write( "}                                                                                            " + ls );
434             out.write( "                                                                                             " + ls );
435             out.write( "my $startWordTime = Time::HiRes::time(); " + ls );
436             out.write( "my $Word = Win32::OLE->new('Word.Application');                                              " + ls );
437             out.write( "my $stopWordTime = Time::HiRes::time() - $startWordTime; " + ls );
438             out.write( "# $Word->{'Visible'} = 1;         # if you want to see what's going on                       " + ls );
439             out.write( "# , ReadOnly => 1})" + ls );
440             out.write(ls);
441             out.write( "my $startLoadWordTime = Time::HiRes::time(); " + ls );
442             out.write( "$Word->Documents->Open({Filename => $ARGV[0]})                                               " + ls );
443             out.write( "    || die('Unable to open document ', Win32::OLE->LastError());                             " + ls );
444             out.write( "my $stopLoadWordTime = Time::HiRes::time() - $startLoadWordTime; " + ls );
445             out.write(ls);
446             out.write( "my $startPrintWordTime = Time::HiRes::time(); " + ls);
447             out.write( "my $oldActivePrinte = $Word->{ActivePrinter} ;                                               " + ls );
448             out.write( "$Word->{ActivePrinter} = $ARGV[1];                                                           " + ls );
449             out.write( "$Word->ActiveDocument->PrintOut({                                                            " + ls );
450             out.write( "                                 Background => 0,                                            " + ls );
451             out.write( "                                 Append     => 0,                                            " + ls );
452             out.write( "                                 Range      => wdPrintAllDocument,                           " + ls );
453             out.write( "                                 Item       => wdPrintDocumentContent,                       " + ls );
454             out.write( "                                 Copies     => 1,                                            " + ls );
455             out.write( "                                 PageType   => wdPrintAllPages,                              " + ls );
456             out.write( "                                 PrintToFile => 1,                                           " + ls );
457             out.write( "                                 OutputFileName => $ARGV[2]                                  " + ls );
458             out.write( "  });                                                                                        " + ls );
459             out.write( "$Word->{ActivePrinter} = $oldActivePrinte;                                                   " + ls );
460             out.write( "my $stopPrintWordTime = Time::HiRes::time() - $startPrintWordTime;" + ls);
461 
462             out.write( "# ActiveDocument.Close(SaveChanges:=WdSaveOptions.wdDoNotSaveChanges)" + ls );
463             out.write( "my $sVersion = $Word->Application->Version();"+ls);
464             out.write( "$Word->ActiveDocument->Close({SaveChanges => 0});                                                           " + ls );
465             out.write( "$Word->Quit();                                                                               " + ls );
466 
467             out.write( "local *FILE;" + ls);
468             out.write( "if (open(FILE, \">$ENV{HOME}/msofficeloadtimes.txt\"))" + ls);
469             out.write( "{" + ls);
470             out.write( "   print FILE \"name=$ARGV[0]\\n\";" + ls);
471             out.write( "   print FILE \"WordVersion=$sVersion\\n\";" + ls);
472             out.write( "   print FILE \"WordStartTime=$stopWordTime\\n\";" + ls);
473             out.write( "   print FILE \"WordLoadTime=$stopLoadWordTime\\n\";" + ls);
474             out.write( "   print FILE \"WordPrintTime=$stopPrintWordTime\\n\";" + ls);
475             out.write( "   close(FILE);" + ls);
476             out.write( "}" + ls);
477             out.close();
478 
479             aList.add(getPerlExe());
480             aList.add(sFileName);
481             return aList;
482         }
483 
484     // TODO: Maybe give a possibility to say where search the script from outside
485 
486     ArrayList<String> searchLocalFile(String _sScriptName)
487         {
488             String userdir = System.getProperty("user.dir");
489 
490             ArrayList<String> aList = new ArrayList<String>();
491             String sFileName = FileHelper.appendPath(userdir, _sScriptName);
492             File aPerlScript = new File(sFileName);
493             if (FileHelper.isDebugEnabled())
494             {
495                 GlobalLogWriter.println("Search for local existance of " + aPerlScript.getAbsolutePath());
496             }
497 
498             if (aPerlScript.exists())
499             {
500                 if (FileHelper.isDebugEnabled())
501                 {
502                     GlobalLogWriter.println("OK, found it, use this instead the internal one.");
503                 }
504 
505                 String sName = aPerlScript.getAbsolutePath();
506                 // String sCommand = "perl " + sName;
507                 // System.out.println(sCommand);
508                 aList.add("perl");
509                 aList.add(sName);
510                 return aList;
511             }
512             return aList;
513         }
514 
515     ArrayList<String> createWordStoreHelper() throws java.io.IOException
516         {
517             // create a program in tmp file
518             String sTmpPath = util.utils.getUsersTempDir();
519             String ls = System.getProperty("line.separator");
520 
521             // ArrayList aList = new ArrayList();
522             String sSaveViaWord = "saveViaWord.pl";
523 
524             ArrayList<String> aList = searchLocalFile(sSaveViaWord);
525             if (aList.isEmpty() == false)
526             {
527                 return aList;
528             }
529 
530             String sName = FileHelper.appendPath(sTmpPath, sSaveViaWord);
531             if (FileHelper.isDebugEnabled())
532             {
533                 GlobalLogWriter.println("No local found, create a perl script: " + sName);
534             }
535 
536             File aFile = new File(sName);
537             FileWriter out = new FileWriter(aFile);
538 
539             out.write( "eval 'exec perl -wS $0 ${1+\"$@\"}'                                                          " + ls );
540             out.write( "   if 0;                                                                                     " + ls );
541             out.write( "use strict;                                                                                  " + ls );
542             out.write( "                                                                                             " + ls );
543             out.write( "if ( $^O ne \"MSWin32\")                                                                     " + ls );
544             out.write( "{                                                                                            " + ls );
545             out.write( "   print 'Windows only.\\n';                                                                  " + ls );
546             out.write( "   print_usage();                                                                            " + ls );
547             out.write( "   exit(1);                                                                                  " + ls );
548             out.write( "}                                                                                            " + ls );
549             out.write( "                                                                                             " + ls );
550             out.write( "use Win32::OLE;                                                                              " + ls );
551             out.write( "use Win32::OLE::Const 'Microsoft Word';                                                      " + ls );
552             out.write( "                                                                                             " + ls );
553             out.write( "# ------ usage ------                                                                        " + ls );
554             out.write( "sub print_usage()                                                                            " + ls );
555             out.write( "{                                                                                            " + ls );
556             out.write( "    print STDERR \"Usage: storeViaWord.pl  <Word file> <output filer> <output file> \\n\"     " + ls );
557             out.write( "}                                                                                            " + ls );
558             out.write( "                                                                                             " + ls );
559             out.write( "                                                                                             " + ls );
560             out.write( "if ($#ARGV != 2)                                                                             " + ls );
561             out.write( "{                                                                                            " + ls );
562             out.write( "   print 'Too less arguments.\\n';                                                            " + ls );
563             out.write( "   print_usage();                                                                            " + ls );
564             out.write( "   exit(1);                                                                                  " + ls );
565             out.write( "}                                                                                            " + ls );
566             out.write( "                                                                                             " + ls );
567             out.write( "                                                                                             " + ls );
568             out.write( "my $Word = Win32::OLE->new('Word.Application');                                              " + ls );
569             out.write( "# $Word->{'Visible'} = 1;         # if you want to see what's going on                       " + ls );
570             out.write( "my $Book = $Word->Documents->Open($ARGV[0])                                                             " + ls );
571             out.write( "    || die('Unable to open document ', Win32::OLE->LastError());                             " + ls );
572             out.write( "# my $oldActivePrinte = $Word->{ActivePrinter} ;                                               " + ls );
573             out.write( "# $Word->{ActivePrinter} = $ARGV[1];                                                           " + ls );
574             out.write( "# $Word->ActiveDocument->PrintOut({                                                            " + ls );
575             out.write( "#                                  Background => 0,                                            " + ls );
576             out.write( "#                                  Append     => 0,                                            " + ls );
577             out.write( "#                                  Range      => wdPrintAllDocument,                           " + ls );
578             out.write( "#                                  Item       => wdPrintDocumentContent,                       " + ls );
579             out.write( "#                                  Copies     => 1,                                            " + ls );
580             out.write( "#                                  PageType   => wdPrintAllPages,                              " + ls );
581             out.write( "#                                  PrintToFile => 1,                                           " + ls );
582             out.write( "#                                  OutputFileName => $ARGV[2]                                  " + ls );
583             out.write( "#   });                                                                                        " + ls );
584             out.write( "# $Word->{ActivePrinter} = $oldActivePrinte;                                                   " + ls );
585             out.write( "$Book->savaAs($ARGV[2], $ARGV[1]);                                                             " + ls );
586             out.write( "# ActiveDocument.Close(SaveChanges:=WdSaveOptions.wdDoNotSaveChanges)" + ls );
587             out.write( "$Book->Close({SaveChanges => 0});                                                           " + ls );
588             out.write( "$Word->Quit();                                                                               " + ls );
589             out.close();
590 
591             aList.add(getPerlExe());
592             aList.add(sName);
593             return aList;
594         }
595 
596 
597     ArrayList<String> createExcelPrintHelper() throws java.io.IOException
598         {
599             // create a program in tmp file
600             String sTmpPath = util.utils.getUsersTempDir();
601             String ls = System.getProperty("line.separator");
602 
603             String sPrintViaExcel = "printViaExcel.pl";
604 
605             ArrayList<String> aList = searchLocalFile(sPrintViaExcel);
606             if (aList.isEmpty() == false)
607             {
608                 return aList;
609             }
610             String sName = FileHelper.appendPath(sTmpPath, sPrintViaExcel);
611             if (FileHelper.isDebugEnabled())
612             {
613                 GlobalLogWriter.println("No local found, create a perl script: " + sName);
614             }
615 
616             File aFile = new File(sName);
617             FileWriter out = new FileWriter(aFile);
618 
619             // out.write( "eval 'exec perl -wS $0 ${1+\"$@\"}'                                                                                " + ls );
620             // out.write( "   if 0;                                                                                                         " + ls );
621             out.write("#BEGIN" + ls);
622             out.write("#{" + ls);
623             out.write("#" + ls);
624             out.write("#    # insert HACK" + ls);
625             out.write("#    unshift(@INC, '');" + ls);
626             out.write("#}" + ls);
627             out.write( "use strict;                                                                                                      " + ls );
628             out.write( "                                                                                                                 " + ls );
629             out.write( "if ( $^O ne \"MSWin32\")                                                                                         " + ls );
630             out.write( "{                                                                                                                " + ls );
631             out.write( "   print \"Windows only.\\n\";                                                                                    " + ls );
632             out.write( "   print_usage();                                                                                                " + ls );
633             out.write( "   exit(1);                                                                                                      " + ls );
634             out.write( "}                                                                                                                " + ls );
635             out.write( "                                                                                                                 " + ls );
636             out.write( "                                                                                                                 " + ls );
637             out.write( "use Win32::OLE qw(in with);                                                                                      " + ls );
638             out.write( "use Win32::OLE::Const 'Microsoft Excel';                                                                         " + ls );
639             out.write( "                                                                                                                 " + ls );
640             out.write( "# ------ usage ------                                                                                            " + ls );
641             out.write( "sub print_usage()                                                                                                " + ls );
642             out.write( "{                                                                                                                " + ls );
643             out.write( "    print STDERR \"Usage: printViaExcel.pl  <Excel file> <name of printer> <output file> .\\n                       " + ls );
644             out.write( "                  Please use the same string for the name of the printer as you can find \\n                      " + ls );
645             out.write( "                  under Start-Control Panel-Printer and Faxes  \\n                                            " + ls );
646             out.write( "                  The name could look like the the following line: \\n                                            " + ls );
647             out.write( "                  Apple LaserWriter II NT v47.0 \\n                                                               " + ls );
648             out.write( "                  Sample command line: \\n                                                                        " + ls );
649             out.write( "                  execl_print.pl  c:\\book1.xls Apple LaserWriter II NT v47.0 c:\\output\\book1.ps \\n\";     " + ls );
650             out.write( "}                                                                                                                " + ls );
651             out.write( "                                                                                                                 " + ls );
652             out.write( "                                                                                                                 " + ls );
653             out.write( "                                                                                                                 " + ls );
654             out.write( "$Win32::OLE::Warn = 3;                                # die on errors...                                         " + ls );
655             out.write( "                                                                                                                 " + ls );
656             out.write( "                                                                                                                 " + ls );
657             out.write( "if ($#ARGV != 2)                                                                                                 " + ls );
658             out.write( "{                                                                                                                " + ls );
659             out.write( "   print STDERR \"Too less arguments.\\n\";                                                                      " + ls );
660             out.write( "   print STDERR \"ARGV[0] $ARGV[0]\\n\";                                                                         " + ls );
661             out.write( "   print STDERR \"ARGV[1] $ARGV[1]\\n\";                                                                         " + ls );
662             out.write( "   print STDERR \"ARGV[2] $ARGV[2]\\n\";                                                                         " + ls );
663             out.write( "   print_usage();                                                                                                " + ls );
664             out.write( "   exit(1);                                                                                                      " + ls );
665             out.write( "}                                                                                                                " + ls );
666             out.write( "                                                                                                                 " + ls );
667             out.write( "my $Excel = Win32::OLE->GetActiveObject('Excel.Application')                                                     " + ls );
668             out.write( "    || Win32::OLE->new('Excel.Application', 'Quit');  # get already active Excel                                 " + ls );
669             out.write( "                                                      # application or open new                                  " + ls );
670             out.write( "                                                                                                                 " + ls );
671             out.write( "                                                                                                                 " + ls );
672             out.write( "                                                                                                                 " + ls );
673             out.write( "my $Book = $Excel->Workbooks->Open( $ARGV[0] );                                                                  " + ls );
674             out.write( "   $Book->PrintOut({Copies => 1,                                                                                 " + ls );
675             out.write( "                    ActivePrinter => $ARGV[1],                                                                   " + ls );
676             out.write( "                    PrToFileName => $ARGV[2],                                                                    " + ls );
677             out.write( "                    Collate => 1                                                                                 " + ls );
678             out.write( "                    });                                                                                          " + ls );
679             out.write( "# Close worksheets without store changes" + ls );
680             out.write( "# $Book->Close({SaveChanges => 0});                                                           " + ls );
681             out.write( "my $sVersion = $Excel->Application->Version();"+ls);
682             out.write( "$Excel->Quit();                                                                                                     " + ls );
683             out.write( "local *FILE;" + ls);
684             out.write( "if (open(FILE, \">$ENV{HOME}/msofficeloadtimes.txt\"))" + ls);
685             out.write( "{" + ls);
686             out.write( "   print FILE \"name=$ARGV[0]\\n\";" + ls);
687             out.write( "   print FILE \"ExcelVersion=$sVersion\\n\";" + ls);
688 //            out.write( "   print FILE \"WordStartTime=$stopWordTime\\n\";" + ls);
689 //            out.write( "   print FILE \"WordLoadTime=$stopLoadWordTime\\n\";" + ls);
690 //            out.write( "   print FILE \"WordPrintTime=$stopPrintWordTime\\n\";" + ls);
691             out.write( "   close(FILE);" + ls);
692             out.write( "}" + ls);
693             out.close();
694 
695             aList.add(getPerlExe());
696             aList.add(sName);
697             return aList;
698         }
699 
700     ArrayList<String> createExcelStoreHelper() throws java.io.IOException
701         {
702             // create a program in tmp file
703             String sTmpPath = util.utils.getUsersTempDir();
704             String ls = System.getProperty("line.separator");
705 
706             String sSaveViaExcel = "saveViaExcel.pl";
707 
708             ArrayList<String> aList = searchLocalFile(sSaveViaExcel);
709             if (aList.isEmpty() == false)
710             {
711                 return aList;
712             }
713             String sName = FileHelper.appendPath(sTmpPath, sSaveViaExcel);
714             if (FileHelper.isDebugEnabled())
715             {
716                 GlobalLogWriter.println("No local found, create a script: " + sName);
717             }
718 
719             File aFile = new File(sName);
720             FileWriter out = new FileWriter(aFile);
721 
722             out.write( "eval 'exec perl -wS $0 ${1+\"$@\"}'                                                                                " + ls );
723             out.write( "   if 0;                                                                                                         " + ls );
724             out.write( "use strict;                                                                                                      " + ls );
725             out.write( "# This script is automatically created.                                                                          " + ls );
726             out.write( "                                                                                                                 " + ls );
727             out.write( "use Win32::OLE qw(in with);                                                                                      " + ls );
728             out.write( "use Win32::OLE::Const 'Microsoft Excel';                                                                         " + ls );
729             out.write( "                                                                                                                 " + ls );
730             out.write( "# ------ usage ------                                                                                            " + ls );
731             out.write( "sub print_usage()                                                                                                " + ls );
732             out.write( "{                                                                                                                " + ls );
733             out.write( "    print STDERR \"Usage: savaViaExcel.pl  <Excel file> <filefilter> <output file> .\\n                       " + ls );
734             out.write( "                  execl_print.pl  c:\\book1.xls Apple LaserWriter II NT v47.0 c:\\output\\book1.ps \\n\";     " + ls );
735             out.write( "}                                                                                                                " + ls );
736             out.write( "                                                                                                                 " + ls );
737             out.write( "                                                                                                                 " + ls );
738             out.write( "                                                                                                                 " + ls );
739             out.write( "$Win32::OLE::Warn = 3;                                # die on errors...                                         " + ls );
740             out.write( "                                                                                                                 " + ls );
741             out.write( "                                                                                                                 " + ls );
742             out.write( "if ($#ARGV != 2)                                                                                                 " + ls );
743             out.write( "{                                                                                                                " + ls );
744             out.write( "   print \"Too less arguments.\\n\";                                                                              " + ls );
745             out.write( "   print_usage();                                                                                                " + ls );
746             out.write( "   exit(1);                                                                                                      " + ls );
747             out.write( "}                                                                                                                " + ls );
748             out.write( "                                                                                                                 " + ls );
749             out.write( "my $Excel = Win32::OLE->GetActiveObject('Excel.Application')                                                     " + ls );
750             out.write( "    || Win32::OLE->new('Excel.Application', 'Quit');  # get already active Excel                                 " + ls );
751             out.write( "                                                      # application or open new                                  " + ls );
752             out.write( "my $sFilterParameter = $ARGV[1];                                                                                                                 " + ls );
753             out.write( "my $sFilterName = xlHTML;                                                                                                                 " + ls );
754             out.write( "if ($sFilterParameter eq 'xlXMLSpreadsheet')                                                                                                                 " + ls );
755             out.write( "{                                                                                                                 " + ls );
756             out.write( "    $sFilterName = xlXMLSpreadsheet;                                                                                                                " + ls );
757             out.write( "}                                                                                                                 " + ls );
758             out.write( "elsif ($sFilterParameter eq 'xlHTML')                                                                                                                 " + ls );
759             out.write( "{                                                                                                                 " + ls );
760             out.write( "    $sFilterName = xlHTML;                                                                                                                 " + ls );
761             out.write( "}                                                                                                                 " + ls );
762             out.write( "else                                                                                                                 " + ls );
763             out.write( "{                                                                                                                 " + ls );
764             out.write( "    my $undefined;                                                                                                " + ls);
765             out.write( "    $sFilterName = $undefined;                                                                                                              " + ls );
766             out.write( "}                                                                                                                 " + ls );
767             out.write( "                                                                                                                 " + ls );
768             out.write( "my $Book = $Excel->Workbooks->Open( $ARGV[0] );                                                                  " + ls );
769             out.write( "$Excel->{DisplayAlerts} = 0;                                                                                     " + ls );
770             out.write( "$Book->saveAs($ARGV[2],                                                                                          " + ls );
771             out.write( "              $sFilterName,                                                                                   " + ls );
772             out.write( "              '',                                                                                                " + ls );
773             out.write( "              '',                                                                                                " + ls );
774             out.write( "              0,                                                                                                 " + ls );
775             out.write( "              0,                                                                                                 " + ls );
776             out.write( "              xlNoChange,                                                                                        " + ls );
777             out.write( "              xlLocalSessionChanges,                                                                             " + ls );
778             out.write( "              1);                                                                                                " + ls );
779             out.write( "# Close worksheets without store changes" + ls );
780             out.write( "# $Book->Close({SaveChanges => 0}); " + ls );
781             out.write( "$Excel->Quit();                                                                                                     " + ls );
782             out.close();
783 
784             aList.add(getPerlExe());
785             aList.add(sName);
786             return aList;
787         }
788 
789     ArrayList<String> createPowerPointPrintHelper() throws java.io.IOException
790         {
791             // create a program in tmp file
792             String sTmpPath = util.utils.getUsersTempDir();
793             String ls = System.getProperty("line.separator");
794 
795             String sPrintViaPowerPoint = "printViaPowerPoint.pl";
796 
797             ArrayList<String> aList = searchLocalFile(sPrintViaPowerPoint);
798             if (aList.isEmpty() == false)
799             {
800                 return aList;
801             }
802             String sName = FileHelper.appendPath(sTmpPath, sPrintViaPowerPoint);
803             if (FileHelper.isDebugEnabled())
804             {
805                 GlobalLogWriter.println("No local found, create a script: " + sName);
806             }
807 
808             File aFile = new File(sName);
809             FileWriter out = new FileWriter(aFile);
810 
811 
812             out.write( "eval 'exec perl -wS $0 $1 $2 '                                                                                         " + ls );
813             out.write( "   if 0;                                                                                                               " + ls );
814             out.write( "use strict;                                                                                                            " + ls );
815             out.write( "                                                                                                                       " + ls );
816             out.write( "if ( $^O ne \"MSWin32\")                                                                                                 " + ls );
817             out.write( "{                                                                                                                      " + ls );
818             out.write( "   print \"Windows only.\\n\";                                                                                            " + ls );
819             out.write( "   print_usage();                                                                                                      " + ls );
820             out.write( "   exit(1);                                                                                                            " + ls );
821             out.write( "}                                                                                                                      " + ls );
822             out.write( "                                                                                                                       " + ls );
823             out.write( "                                                                                                                       " + ls );
824             out.write( "use Win32::OLE qw(in with);                                                                                            " + ls );
825             out.write( "use Win32::OLE::Const 'Microsoft PowerPoint';                                                                          " + ls );
826             out.write( "                                                                                                                       " + ls );
827             out.write( "# ------ usage ------                                                                                                  " + ls );
828             out.write( "sub print_usage()                                                                                                      " + ls );
829             out.write( "{                                                                                                                      " + ls );
830             out.write( "    print STDERR \"Usage: powerpoint_print.pl  <PowerPoint file> <name of printer> <output file> .\\n                    " + ls );
831             out.write( "                  Please use the same string for the name of the printer as you can find \\n                            " + ls );
832             out.write( "                  under Start-Control Panel-Printer and Faxes  \\n                                                  " + ls );
833             out.write( "                  The name could look like the the following line: \\n                                                  " + ls );
834             out.write( "                  Apple LaserWriter II NT v47.0 \\n                                                                     " + ls );
835             out.write( "                  Sample command line: \\n                                                                              " + ls );
836             out.write( "                  powerpoint_print.pl  c:\\book.ppt Apple LaserWriter II NT v47.0 c:\\output\\book.ps \\n\";         " + ls );
837             out.write( "}                                                                                                                      " + ls );
838             out.write( "                                                                                                                       " + ls );
839             out.write( "                                                                                                                       " + ls );
840             out.write( "                                                                                                                       " + ls );
841             out.write( "$Win32::OLE::Warn = 3;                                # die on errors...                                               " + ls );
842             out.write( "                                                                                                                       " + ls );
843             out.write( "                                                                                                                       " + ls );
844             out.write( "if ($#ARGV < 2)                                                                                                        " + ls );
845             out.write( "{                                                                                                                      " + ls );
846             out.write( "   print \"Too less arguments.\\n\";                                                                                      " + ls );
847             out.write( "   print_usage();                                                                                                      " + ls );
848             out.write( "   exit(1);                                                                                                            " + ls );
849             out.write( "}                                                                                                                      " + ls );
850             out.write( "                                                                                                                       " + ls );
851             out.write( "my $PowerPoint = Win32::OLE->GetActiveObject('PowerPoint.Application')                                                 " + ls );
852             out.write( "    || Win32::OLE->new('PowerPoint.Application', 'Quit');  # get already active Excel                                  " + ls );
853             out.write( "                                                      # application or open new                                        " + ls );
854             out.write( "                                                                                                                       " + ls );
855             out.write( "                                                                                                                       " + ls );
856             out.write( "                                                                                                                       " + ls );
857             out.write( "   $PowerPoint->{'Visible'} = 1;                                                                                       " + ls );
858             out.write( "   my $Presentation = $PowerPoint->Presentations->Add;                                                                 " + ls );
859             out.write( "   my $Presentation = $PowerPoint->Presentations->Open( $ARGV[0] );                                                    " + ls );
860             out.write( "# we can't change active printer in powerpoint                                                            " + ls );
861             out.write( "#   $Presentation->PrintOptions->{ActivePrinter} = $ARGV[1]; " + ls );
862             out.write( "   print \"Active printer is: \" . $Presentation->PrintOptions->{ActivePrinter} . \"\\n\"; " + ls );
863             out.write( "   $Presentation->PrintOptions->{PrintInBackground} = 0;                                                               " + ls );
864             out.write( "   # PrintColorType = 1 means print in color and PrintColorType = 2 means print in gray                                " + ls );
865             out.write( "   $Presentation->PrintOptions->{PrintColorType} = 1;                                                                  " + ls );
866             out.write( "                                                                                                                       " + ls );
867             out.write( "   $Presentation->PrintOut({PrintToFile => $ARGV[2]});                                                                 " + ls );
868             out.write( "   sleep 5;                                                                                                            " + ls );
869             out.write( "   print \"Presentation has been printed\\n\";                                                                            " + ls );
870             out.write( "my $sVersion = $Presentation->Application->Version();"+ls);
871             out.write( "   $PowerPoint->Quit(); " + ls );
872 
873             out.write( "local *FILE;" + ls);
874             out.write( "if (open(FILE, \">$ENV{HOME}/msofficeloadtimes.txt\"))" + ls);
875             out.write( "{" + ls);
876             out.write( "   print FILE \"name=$ARGV[0]\\n\";" + ls);
877             out.write( "   print FILE \"PowerPointVersion=$sVersion\\n\";" + ls);
878 //            out.write( "   print FILE \"WordStartTime=$stopWordTime\\n\";" + ls);
879 //            out.write( "   print FILE \"WordLoadTime=$stopLoadWordTime\\n\";" + ls);
880 //            out.write( "   print FILE \"WordPrintTime=$stopPrintWordTime\\n\";" + ls);
881             out.write( "   close(FILE);" + ls);
882             out.write( "}" + ls);
883             out.close();
884 
885             aList.add(getPerlExe());
886             aList.add(sName);
887             return aList;
888         }
889 
890     /**
891        @param _sFilename a name to a ms office xml file
892        @return 'word' or 'excel' or '' if type not known
893     */
894     public String getOfficeType(String _sFilename)
895         {
896             File aFile = new File(_sFilename);
897             if (! aFile.exists())
898             {
899                 GlobalLogWriter.println("couldn't find file " + _sFilename);
900                 return "";
901             }
902             RandomAccessFile aReader = null;
903             String sOfficeType = "";
904             try
905             {
906                 aReader = new RandomAccessFile(aFile,"r");
907                 String aLine = "";
908                 while (aLine != null)
909                 {
910                     aLine = aReader.readLine();
911                     if (aLine != null)
912                     {
913                         aLine = aLine.trim();
914                         if ( (! (aLine.length() < 2) ) &&
915                              (! aLine.startsWith("#")) &&
916                              (! aLine.startsWith(";")) )
917                         {
918                             int nIdx = aLine.indexOf("mso-application");
919                             if (nIdx > 0)
920                             {
921                                 if (aLine.indexOf("Word.Document") > 0)
922                                 {
923                                     sOfficeType = "word";
924                                 }
925                                 else if (aLine.indexOf("Excel") > 0)
926                                 {
927                                     sOfficeType = "excel";
928                                 }
929                                 else
930                                 {
931                                     GlobalLogWriter.println("Unknown/unsupported data file: " + aLine);
932                                 }
933                             }
934                         }
935                     }
936                 }
937             }
938             catch (java.io.FileNotFoundException fne)
939             {
940                 System.out.println("couldn't open file " + _sFilename);
941                 System.out.println("Message: " + fne.getMessage());
942             }
943             catch (java.io.IOException ie)
944             {
945                 System.out.println("Exception while reading file " + _sFilename);
946                 System.out.println("Message: " + ie.getMessage());
947             }
948             try
949             {
950                 aReader.close();
951             }
952             catch (java.io.IOException ie)
953             {
954                 System.out.println("Couldn't close file " + _sFilename);
955                 System.out.println("Message: " + ie.getMessage());
956             }
957             return sOfficeType;
958         }
959 
960     private static String getXMLDocumentFormat(String _sInputFile)
961     {
962         String sType = "word"; // default
963         try
964         {
965             // ---- Parse XML file ----
966             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
967             // factory.setNamespaceAware( true );
968             // factory.setValidating( true );
969             DocumentBuilder builder  = factory.newDocumentBuilder();
970             Document        document = builder.parse( new File (_sInputFile) );
971             Node            rootNode = document.getDocumentElement();
972 
973             // ---- Get list of nodes to given tag ----
974             // document.
975             // NodeList ndList = document.getElementsByTagName( sToSearch /* argv[2] */ );
976             // System.out.println( "\nNode list at the beginning:" );
977             String sRootNodeName = rootNode.getNodeName();
978             if (sRootNodeName.equals("w:wordDocument"))
979             {
980                 sType = "word";
981             }
982             else if (sRootNodeName.equals("WorkBook"))
983             {
984                 sType = "excel";
985             }
986             // there exists no powerpoint xml representation in MSOffice 2003
987             else
988             {
989                 GlobalLogWriter.println("Error: unknown root node: '" + sRootNodeName + "' please check the document. Try to use Word as default.");
990                 sType = "word"; // default
991             }
992             // printNodesFromList( ndList );
993         }
994         catch (java.lang.Exception e)
995         {
996         }
997         return sType;
998     }
999 
1000 //    public static void main(String [] _args)
1001 //    {
1002 //        String sTest = getXMLDocumentFormat("c:/cws/temp/input/Blah Fasel.xml");
1003 //    }
1004 }
1005