summaryrefslogtreecommitdiff
path: root/xmerge/source/xmerge/java/org/openoffice/xmerge/test/Driver.java
blob: 9a4816b03536fc8d337c9066bf4d84e5030d98be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

package org.openoffice.xmerge.test;

import java.util.Vector;
import java.util.Enumeration;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.File;

import org.openoffice.xmerge.Convert;
import org.openoffice.xmerge.Document;
import org.openoffice.xmerge.ConvertData;
import org.openoffice.xmerge.ConverterFactory;
import org.openoffice.xmerge.test.ConverterInfoList;
import org.openoffice.xmerge.util.registry.ConverterInfoMgr;
import org.openoffice.xmerge.util.registry.ConverterInfoReader;
import org.openoffice.xmerge.DocumentMerger;

/**
 *  This class is a command-line driver for the converter framework.
 *  It is expected that this code will be later called by the device
 *  server. It does some basic validation of the command-line
 *  parameters.
 */
public final class Driver {

    /**  Command-line parameter. */
    private String fromMime = null;

    /**  Command-line parameter. */
    private String toMime = null;

    /**  mergeFile name. */
    private String mergeFile = null;

    /**  Command-line parmeter. */
    private Vector deviceFiles = new Vector();

    /**  Command-line parmeter shortcuts. */
    private String mimeTypes[] = {
                                    "sxc", "staroffice/sxc",
                                    "sxw","staroffice/sxw"
    };


    /**
     *  Main.
     *
     *  @param  args  The argument passed on the command line.
     */
    public static void main(String args[]) {

        // Register jarfiles
        //
        String propFile       = "ConverterInfoList.properties";
        ConverterInfoList cil = null;
        try {
            cil = new ConverterInfoList(propFile);
        } catch (Exception e) {
            System.out.println("\nCannot not load " + propFile +
                " property file");
        }

        Enumeration jarInfoEnumeration;
        ConverterInfoReader cir;

        Enumeration jarFileEnum = cil.getJarFileEnum();
        while (jarFileEnum.hasMoreElements()) {
            String jarName = (String) jarFileEnum.nextElement();
            try {
                cir = new ConverterInfoReader(jarName, false);
                jarInfoEnumeration = cir.getConverterInfoEnumeration();
                ConverterInfoMgr.addPlugIn(jarInfoEnumeration);
            } catch (Exception e) {
                System.out.println("\nCannot not load <" + jarName +
                    "> from the <" + propFile + "> property file");
            }
        }

        try {

            Driver app = new Driver();
            app.parseCommandLine(args);
            app.doConversion();
        } catch (IllegalArgumentException ex) {

            String msg = ex.getMessage();
            if (msg != null) System.out.println("\n" + msg);
            showUsage();

        } catch (Exception ex) {

            String msg = ex.getMessage();
            if (msg != null) System.out.println("\n" + msg);
            ex.printStackTrace();
        }
    }


    /**
     *  Gets a <code>Convert</code> object using the
     *  <code>ConverterFactory</code> and  does the conversion using
     *  this object.
     *
     *  @throws  IllegalArgumentException  If an argument is invalid.
     */
    private void doConversion() throws IllegalArgumentException {

        ConverterFactory cf = new ConverterFactory();
        Convert myConvert   = cf.getConverter(fromMime, toMime);
        String processFile  = null;

        if (myConvert == null) {
            System.out.println("\nNo plug-in exists to convert from <" +
                fromMime + "> to <" + toMime + ">");
            throw new IllegalArgumentException();
        }

        try {
            Enumeration dfEnum = deviceFiles.elements();
            while (dfEnum.hasMoreElements()) {
                processFile = (String)dfEnum.nextElement();
                File f = new File(processFile);

                // Make sure the input file actually exists before using it
                if (!f.exists()) {
                    System.out.println(processFile + " does not exist!");
                    System.exit(0);
                }
                FileInputStream fis = new FileInputStream(f);
                myConvert.addInputStream(f.getName(), fis);
            }
        } catch (Exception addExcept) {
            System.out.println("\nFile <" + processFile + "> is not in <" +
                fromMime + "> format");
            throw new IllegalArgumentException();
        }

        ConvertData dataOut = null;

        try {
            dataOut = myConvert.convert();
        } catch (Exception convertExcept) {
            System.out.println("\nThere was an error in the conversion");
            convertExcept.printStackTrace();
        }

        if (dataOut != null ) {

            if (mergeFile == null) {
                Enumeration docEnum = dataOut.getDocumentEnumeration();
                while (docEnum.hasMoreElements()) {
                    Document docOut      = (Document)docEnum.nextElement();
                    String fileName      = docOut.getFileName();
                    try {
                        FileOutputStream fos = new FileOutputStream(fileName);
                        docOut.write(fos);
                        fos.flush();
                        fos.close();
                    } catch (Exception writeExcept) {
                        System.out.println("\nThere was an writing out file <" +
                            fileName + ">");
                        writeExcept.printStackTrace();
                    }
                }
            } else {
                try {
                    FileInputStream mergeIS = new FileInputStream(mergeFile);
                    Document mergeDoc = myConvert.getOfficeDocument(mergeFile, mergeIS);
                    DocumentMerger merger = myConvert.getDocumentMerger(mergeDoc);
                    Enumeration mergeDocEnum = dataOut.getDocumentEnumeration();
                    Document convertedFile = (Document)mergeDocEnum.nextElement();

                    merger.merge(convertedFile);
              mergeIS.close();

                    FileOutputStream fos = new FileOutputStream(mergeFile);
                    mergeDoc.write(fos);
                    fos.flush();
                    fos.close();
                } catch (Exception mergeExcept) {
                    System.out.println("\nThere was an error in the merge");
                    mergeExcept.printStackTrace();
                }
            }
        }
    }


    /**
     *  Display usage.
     */
    private static void showUsage() {

        System.out.println("\nUsage:");
        System.out.println("\n   java org.openoffice.xmerge.test.Driver <args>");
        System.out.println("\n   where <args> is as follows:");
        System.out.println("   -from <MIMETYPE> -to <MIMETYPE> [ -merge <OrigDoc ] <document>\n");
    }


    /**
     *  Parse command-line arguments.
     *
     *  @param  args  Array of command line arguments.
     *
     *  @throws  IllegalArgumentException  If an argument is invalid.
     */
    private void parseCommandLine(String args[])
        throws IllegalArgumentException {

        if (args.length == 0) {
            throw new IllegalArgumentException();
        }

        for (int i = 0; i < args.length; i++) {
            String arg = args[i];

            if ("-to".equals(arg)) {
                toMime = extractArg(i, args);
                for (int j = 0; j < mimeTypes.length; j+=2) {
                    if(mimeTypes[j].equals(extractArg(i, args)))
                        toMime = mimeTypes[j+1];
                }
                i++;
            } else if ("-from".equals(arg)) {
                fromMime = extractArg(i, args);
                for (int j = 0; j < mimeTypes.length; j+=2) {
                    if(mimeTypes[j].equals(extractArg(i, args)))
                        fromMime = mimeTypes[j+1];
                }
                i++;
            } else if ("-merge".equals(arg)) {
                mergeFile = extractArg(i, args);
                if (!isZip(mergeFile)) {
                    throw new
                        IllegalArgumentException("Arg " + i +
                                                 ": expected zip, got " +
                                                 mergeFile);
                }
                i++;
            } else {
                deviceFiles.add(arg);
            }
        }

        System.out.println("\nConverting from " + fromMime + " to " + toMime +
                           ((mergeFile != null) ? " with merge " : " "));
    }


    /**
     *  Extract the next argument from the array, while checking to see
     *  that the array size is not exceeded.  Throw a friendly error
     *  message in case the arg is missing.
     *
     *  @param  i     Argument index.
     *  @param  args  Array of command line arguments.
     *
     *  @return  The argument with the specified index.
     *
     *  @throws  IllegalArgumentException  If an argument is invalid.
     */
    private String extractArg(int i, String args[])
        throws IllegalArgumentException {

        if (i+1 < args.length)
            return args[i+1];
        else throw new
            IllegalArgumentException("Arg " + i +
                                     ": expected arg for " + args[i]);
    }


    /**
     *  Simple validation for Office ZIP files.
     *
     *  @param  zipName  The name of the ZIP file.
     *
     *  @return  true if zipName is valid, false otherwise.
     */
    private boolean isZip(String zipName) {

        String str = zipName.toLowerCase();
        if (str.endsWith("sxw") || zipName.endsWith("sxc")) {
            return true;
        }

        return false;
    }
}