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 import com.sun.star.uno.UnoRuntime;
25 
26 import java.io.File;
27 import java.io.FileFilter;
28 
29 
30 /** The class <CODE>DocumentConverter</CODE> allows you to convert all documents
31  * in a given directory and in its subdirectories to a given type. A converted
32  * document will be created in the same directory as the origin document.
33  *
34  */
35 public class DocumentConverter {
36     /** Containing the loaded documents
37      */
38     static com.sun.star.frame.XComponentLoader xCompLoader = null;
39     /** Containing the given type to convert to
40      */
41     static String sConvertType = "";
42     /** Containing the given extension
43      */
44     static String sExtension = "";
45     /** Containing the current file or directory
46      */
47     static String sIndent = "";
48     /** Containing the directory where the converted files are saved
49      */
50     static String sOutputDir = "";
51 
52     /** Traversing the given directory recursively and converting their files to
53      * the favoured type if possible
54      * @param fileDirectory Containing the directory
55      */
traverse( File fileDirectory )56     static void traverse( File fileDirectory ) {
57         // Testing, if the file is a directory, and if so, it throws an exception
58         if ( !fileDirectory.isDirectory() ) {
59             throw new IllegalArgumentException(
60                 "not a directory: " + fileDirectory.getName()
61                 );
62         }
63 
64         // Prepare Url for the output directory
65         File outdir = new File(DocumentConverter.sOutputDir);
66         String sOutUrl = "file:///" + outdir.getAbsolutePath().replace( '\\', '/' );
67 
68         System.out.println("\nThe converted documents will stored in \""
69                            + outdir.getPath() + "!");
70 
71         System.out.println(sIndent + "[" + fileDirectory.getName() + "]");
72         sIndent += "  ";
73 
74         // Getting all files and directories in the current directory
75         File[] entries = fileDirectory.listFiles();
76 
77 
78         // Iterating for each file and directory
79         for ( int i = 0; i < entries.length; ++i ) {
80             // Testing, if the entry in the list is a directory
81             if ( entries[ i ].isDirectory() ) {
82                 // Recursive call for the new directory
83                 traverse( entries[ i ] );
84             } else {
85                 // Converting the document to the favoured type
86                 try {
87                     // Composing the URL by replacing all backslashs
88                     String sUrl = "file:///"
89                         + entries[ i ].getAbsolutePath().replace( '\\', '/' );
90 
91                     // Loading the wanted document
92                     com.sun.star.beans.PropertyValue propertyValues[] =
93                         new com.sun.star.beans.PropertyValue[1];
94                     propertyValues[0] = new com.sun.star.beans.PropertyValue();
95                     propertyValues[0].Name = "Hidden";
96                     propertyValues[0].Value = new Boolean(true);
97 
98                     Object oDocToStore =
99                         DocumentConverter.xCompLoader.loadComponentFromURL(
100                             sUrl, "_blank", 0, propertyValues);
101 
102                     // Getting an object that will offer a simple way to store
103                     // a document to a URL.
104                     com.sun.star.frame.XStorable xStorable =
105                         (com.sun.star.frame.XStorable)UnoRuntime.queryInterface(
106                             com.sun.star.frame.XStorable.class, oDocToStore );
107 
108                     // Preparing properties for converting the document
109                     propertyValues = new com.sun.star.beans.PropertyValue[2];
110                     // Setting the flag for overwriting
111                     propertyValues[0] = new com.sun.star.beans.PropertyValue();
112                     propertyValues[0].Name = "Overwrite";
113                     propertyValues[0].Value = new Boolean(true);
114                     // Setting the filter name
115                     propertyValues[1] = new com.sun.star.beans.PropertyValue();
116                     propertyValues[1].Name = "FilterName";
117                     propertyValues[1].Value = DocumentConverter.sConvertType;
118 
119                     // Appending the favoured extension to the origin document name
120                     int index1 = sUrl.lastIndexOf('/');
121                     int index2 = sUrl.lastIndexOf('.');
122                     String sStoreUrl = sOutUrl + sUrl.substring(index1, index2 + 1)
123                         + DocumentConverter.sExtension;
124 
125                     // Storing and converting the document
126                     xStorable.storeAsURL(sStoreUrl, propertyValues);
127 
128                     // Closing the converted document. Use XCloseable.clsoe if the
129                     // interface is supported, otherwise use XComponent.dispose
130                     com.sun.star.util.XCloseable xCloseable =
131                         (com.sun.star.util.XCloseable)UnoRuntime.queryInterface(
132                             com.sun.star.util.XCloseable.class, xStorable);
133 
134                     if ( xCloseable != null ) {
135                         xCloseable.close(false);
136                     } else {
137                         com.sun.star.lang.XComponent xComp =
138                             (com.sun.star.lang.XComponent)UnoRuntime.queryInterface(
139                                 com.sun.star.lang.XComponent.class, xStorable);
140 
141                         xComp.dispose();
142                     }
143                 }
144                 catch( Exception e ) {
145                     e.printStackTrace(System.err);
146                 }
147 
148                 System.out.println(sIndent + entries[ i ].getName());
149             }
150         }
151 
152         sIndent = sIndent.substring(2);
153     }
154 
155     /** Bootstrap UNO, getting the remote component context, getting a new instance
156      * of the desktop (used interface XComponentLoader) and calling the
157      * static method traverse
158      * @param args The array of the type String contains the directory, in which
159      *             all files should be converted, the favoured converting type
160      *             and the wanted extension
161      */
main( String args[] )162     public static void main( String args[] ) {
163         if ( args.length < 3 ) {
164             System.out.println("usage: java -jar DocumentConverter.jar " +
165                 "\"<directory to convert>\" \"<type to convert to>\" " +
166                 "\"<extension>\" \"<output_directory>\"");
167             System.out.println("\ne.g.:");
168             System.out.println("usage: java -jar DocumentConverter.jar " +
169                 "\"c:/myoffice\" \"swriter: MS Word 97\" \"doc\"");
170             System.exit(1);
171         }
172 
173         com.sun.star.uno.XComponentContext xContext = null;
174 
175         try {
176             // get the remote office component context
177             xContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
178             System.out.println("Connected to a running office ...");
179 
180             // get the remote office service manager
181             com.sun.star.lang.XMultiComponentFactory xMCF =
182                 xContext.getServiceManager();
183 
184             Object oDesktop = xMCF.createInstanceWithContext(
185                 "com.sun.star.frame.Desktop", xContext);
186 
187             xCompLoader = (com.sun.star.frame.XComponentLoader)
188                 UnoRuntime.queryInterface(com.sun.star.frame.XComponentLoader.class,
189                                           oDesktop);
190 
191             // Getting the given starting directory
192             File file = new File(args[0]);
193 
194             // Getting the given type to convert to
195             sConvertType = args[1];
196 
197             // Getting the given extension that should be appended to the
198             // origin document
199             sExtension = args[2];
200 
201             // Getting the given type to convert to
202             sOutputDir = args[3];
203 
204             // Starting the conversion of documents in the given directory
205             // and subdirectories
206             traverse(file);
207 
208             System.exit(0);
209         } catch( Exception e ) {
210             e.printStackTrace(System.err);
211             System.exit(1);
212         }
213     }
214 }
215