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