summaryrefslogtreecommitdiff
path: root/scripting/java/org/openoffice/idesupport/zip/ParcelZipper.java
blob: 30cf598a706af6f63cd4b8c7dfea4998ae37c963 (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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
/*
 * 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.idesupport.zip;

import java.io.*;
import java.util.Enumeration;
import java.util.zip.*;
import org.openoffice.idesupport.filter.FileFilter;
import org.openoffice.idesupport.filter.BinaryOnlyFilter;
import com.sun.star.script.framework.container.ParcelDescriptor;
import org.openoffice.idesupport.xml.Manifest;

public class ParcelZipper
{
    public static final String PARCEL_PREFIX_DIR = "Scripts/";
    private static final String PARCEL_EXTENSION = "sxp";
    public static final String CONTENTS_DIRNAME = "Contents";
    public static final String PARCEL_DESCRIPTOR_XML = "parcel-descriptor.xml";

    private static ParcelZipper zipper = null;

    private static final FileFilter DEFAULT_FILTER =
        BinaryOnlyFilter.getInstance();

    private ParcelZipper() {
    }

    public static ParcelZipper getParcelZipper() {
        if (zipper == null) {
            synchronized(ParcelZipper.class) {
                if (zipper == null)
                    zipper = new ParcelZipper();
            }
        }
        return zipper;
    }







    private String zipParcel(File basedir, File targetfile, FileFilter filter)
        throws IOException {
        String realpath, tmppath;

        realpath = targetfile.getPath();
        tmppath = realpath + ".tmp";

        File tmpfile = new File(tmppath);
        ZipOutputStream out = null;
        try {
            if (tmpfile.exists() == true)
                tmpfile.delete();

            out = new ZipOutputStream(new FileOutputStream(tmpfile));

            File[] children = basedir.listFiles();
            for (int i = 0; i < children.length; i++)
                addFileToParcel(children[i], "", out, filter);
        }
        catch (IOException ioe) {
            out.close();
            tmpfile.delete();
            throw ioe;
        }
        finally {
            if (out != null)
                out.close();
        }

        if (targetfile.exists() == true)
            targetfile.delete();
        tmpfile.renameTo(targetfile);

        return targetfile.getAbsolutePath();
    }

    private void addFileToParcel(File root, String path, ZipOutputStream out, FileFilter filter)
        throws IOException {
        ZipEntry ze;

        if (root.isDirectory() == true) {
            ze = new ZipEntry(/* PARCEL_PREFIX_DIR + */ path + root.getName() + "/");
            out.putNextEntry(ze);
            out.closeEntry();
            File[] children = root.listFiles();

            for (int i = 0; i < children.length; i++)
                addFileToParcel(children[i], path + root.getName() + "/", out, filter);
        }
        else {
            if (filter.validate(root.getName()) == false &&
                root.getName().equals("parcel-descriptor.xml") == false)
                return;

            ze = new ZipEntry(/* PARCEL_PREFIX_DIR + */ path + root.getName());
            out.putNextEntry(ze);

            byte[] bytes = new byte[1024];
            int len;

            FileInputStream fis = null;
            try {
                fis = new FileInputStream(root);

                while ((len = fis.read(bytes)) != -1)
                    out.write(bytes, 0, len);
            }
            finally {
                if (fis != null) fis.close();
            }
            out.closeEntry();
        }
    }



    private boolean isDirectoryOverwriteNeeded(File parcel, File target) {
        String parcelDir = getParcelDirFromParcelZip(parcel.getName());

        File langdir;
        try {
            langdir = new File(target, getParcelLanguage(parcel));
        }
        catch (IOException ioe) {
            return false;
        }

        if (langdir.exists() == false)
            return false;

        File[] children = langdir.listFiles();

        for (int i = 0; i < children.length; i++)
            if (children[i].getName().equals(parcelDir))
                return true;

        return false;
    }

    private boolean isDocumentOverwriteNeeded(File parcel, File document)
        throws IOException
    {
        ZipFile documentZip = null;
        boolean result = false;

        try {
            documentZip = new ZipFile(document);

            String name =
                PARCEL_PREFIX_DIR + getParcelLanguage(parcel) +
                    "/" + getParcelDirFromParcelZip(parcel.getName()) +
                    "/" + PARCEL_DESCRIPTOR_XML;

            if (documentZip.getEntry(name) != null)
                result = true;
        }
        catch (IOException ioe) {
            return false;
        }
        finally {
            if (documentZip != null) documentZip.close();
        }

        return result;
    }



    private String getParcelDirFromParcelZip(String zipname) {
        String result = zipname.substring(0, zipname.lastIndexOf("."));
        return result;
    }

    private String unzipToDirectory(File parcel, File targetDirectory)
        throws IOException {

        ZipInputStream in = null;
        File parcelDir = new File(targetDirectory,
            getParcelLanguage(parcel) + File.separator +
            getParcelDirFromParcelZip(parcel.getName()));

        if (isDirectoryOverwriteNeeded(parcel, targetDirectory)) {
            if (deleteDir(parcelDir) == false) {
                throw new IOException("Could not overwrite: " +
                    parcelDir.getAbsolutePath());
            }
        }

        try {
            in = new ZipInputStream(new FileInputStream(parcel));

            File outFile;
            ZipEntry inEntry = in.getNextEntry();
            byte[] bytes = new byte[1024];
            int len;

            while (inEntry != null) {
                outFile = new File(parcelDir, inEntry.getName());
                if (inEntry.isDirectory()) {
                    outFile.mkdir();
                }
                else {
                    if (outFile.getParentFile().exists() != true)
                        outFile.getParentFile().mkdirs();

                    FileOutputStream out = null;
                    try {
                        out = new FileOutputStream(outFile);

                        while ((len = in.read(bytes)) != -1)
                            out.write(bytes, 0, len);
                    }
                    finally {
                        if (out != null) out.close();
                    }
                }
                inEntry = in.getNextEntry();
            }
        }
        finally {
            if (in != null) in.close();
        }

        return parcelDir.getAbsolutePath();
    }

    private boolean deleteDir(File basedir) {
        if (basedir.isDirectory()) {
            String[] children = basedir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(basedir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return basedir.delete();
    }

    private String unzipToZip(File parcel, File targetDocument)
        throws IOException {

        ZipInputStream documentStream = null;
        ZipInputStream parcelStream = null;
        ZipOutputStream outStream = null;
        Manifest manifest;

        String language = getParcelLanguage(parcel);

        if (isDocumentOverwriteNeeded(parcel, targetDocument)) {
            String parcelName = language + "/" +
                getParcelDirFromParcelZip(parcel.getName());
            removeParcel(targetDocument, parcelName);
        }

        // first write contents of document to tmpfile
        File tmpfile = new File(targetDocument.getAbsolutePath() + ".tmp");

        manifest = addParcelToManifest(targetDocument, parcel);

        try {
            documentStream =
                new ZipInputStream(new FileInputStream(targetDocument));
            parcelStream = new ZipInputStream(new FileInputStream(parcel));
            outStream = new ZipOutputStream(new FileOutputStream(tmpfile));

            copyParcelToZip(parcelStream, outStream, PARCEL_PREFIX_DIR +
                language + "/" + getParcelDirFromParcelZip(parcel.getName()));
            copyDocumentToZip(documentStream, outStream, manifest);
        }
        catch (IOException ioe) {
            tmpfile.delete();
            throw ioe;
        }
        finally {
            if (documentStream != null) documentStream.close();
            if (parcelStream != null) parcelStream.close();
            if (outStream != null) outStream.close();
        }

        if (targetDocument.delete() == false) {
            tmpfile.delete();
            throw new IOException("Could not overwrite " + targetDocument);
        }
        else
            tmpfile.renameTo(targetDocument);

        return targetDocument.getAbsolutePath();
    }

    private void copyParcelToZip(ZipInputStream in, ZipOutputStream out,
        String parcelName) throws IOException {

        ZipEntry outEntry;
        ZipEntry inEntry = in.getNextEntry();
        byte[] bytes = new byte[1024];
        int len;

        while (inEntry != null) {
            if(parcelName!=null)
                outEntry = new ZipEntry(parcelName + "/" + inEntry.getName());
            else
                outEntry = new ZipEntry(inEntry);
            out.putNextEntry(outEntry);

            if (inEntry.isDirectory() == false)
                while ((len = in.read(bytes)) != -1)
                    out.write(bytes, 0, len);

            out.closeEntry();
            inEntry = in.getNextEntry();
        }
    }

    private void copyDocumentToZip(ZipInputStream in, ZipOutputStream out,
        Manifest manifest) throws IOException {

        ZipEntry outEntry;
        ZipEntry inEntry;
        byte[] bytes = new byte[1024];
        int len;

        while ((inEntry = in.getNextEntry()) != null) {

            outEntry = new ZipEntry(inEntry);
            out.putNextEntry(outEntry);

            if(inEntry.getName().equals("META-INF/manifest.xml") &&
               manifest != null) {
                InputStream manifestStream = null;
                try {
                    manifestStream = manifest.getInputStream();
                    while ((len = manifestStream.read(bytes)) != -1)
                        out.write(bytes, 0, len);
                }
                finally {
                    if (manifestStream != null)
                        manifestStream.close();
                }
            }
            else if (inEntry.isDirectory() == false) {
                while ((len = in.read(bytes)) != -1)
                    out.write(bytes, 0, len);
            }

            out.closeEntry();
        }
    }

    public String removeParcel(File document, String parcelName)
        throws IOException {

        ZipInputStream documentStream = null;
        ZipOutputStream outStream = null;
        Manifest manifest = null;

        if (!parcelName.startsWith(PARCEL_PREFIX_DIR))
            parcelName = PARCEL_PREFIX_DIR + parcelName;
        manifest = removeParcelFromManifest(document, parcelName);

        // first write contents of document to tmpfile
        File tmpfile = new File(document.getAbsolutePath() + ".tmp");

        try {
            ZipEntry outEntry;
            ZipEntry inEntry;
            byte[] bytes = new byte[1024];
            int len;

            documentStream = new ZipInputStream(new FileInputStream(document));
            outStream = new ZipOutputStream(new FileOutputStream(tmpfile));

            while ((inEntry = documentStream.getNextEntry()) != null) {

                if(inEntry.getName().startsWith(parcelName))
                    continue;

                outEntry = new ZipEntry(inEntry);
                outStream.putNextEntry(outEntry);

                if(inEntry.getName().equals("META-INF/manifest.xml") &&
                   manifest != null) {
                    InputStream manifestStream = null;
                    try {
                        manifestStream = manifest.getInputStream();
                        while ((len = manifestStream.read(bytes)) != -1)
                            outStream.write(bytes, 0, len);
                    }
                    finally {
                        if (manifestStream != null)
                            manifestStream.close();
                    }
                }
                else if (inEntry.isDirectory() == false) {
                    while ((len = documentStream.read(bytes)) != -1)
                        outStream.write(bytes, 0, len);
                }

                outStream.closeEntry();
            }
        }
        catch (IOException ioe) {
            tmpfile.delete();
            throw ioe;
        }
        finally {
            if (documentStream != null)
                documentStream.close();

            if (outStream != null)
                outStream.close();
        }

        if (document.delete() == false) {
            tmpfile.delete();
            throw new IOException("Could not overwrite " + document);
        }
        else
            tmpfile.renameTo(document);

        return document.getAbsolutePath();
    }

    private Manifest getManifestFromDocument(File document) {
        ZipFile documentZip = null;
        Manifest result = null;

        try {
            documentZip = new ZipFile(document);
            ZipEntry original = documentZip.getEntry("META-INF/manifest.xml");
            if (original != null) {
                result = new Manifest(documentZip.getInputStream(original));
            }
        }
        catch (IOException ioe) {
        }
        finally {
            try {
                if (documentZip != null)
                    documentZip.close();
            }
            catch (IOException ioe) {}
        }

        return result;
    }

    private Manifest addParcelToManifest(File document, File parcel)
        throws IOException {

        ZipFile parcelZip = null;
        Manifest result = null;

        result = getManifestFromDocument(document);
        if (result == null)
            return null;

        String language = getParcelLanguage(parcel);

        try {
            parcelZip = new ZipFile(parcel);

            String prefix = PARCEL_PREFIX_DIR + language + "/" +
                getParcelDirFromParcelZip(parcel.getName()) + "/";

            Enumeration entries = parcelZip.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry)entries.nextElement();
                result.add(prefix + entry.getName());
            }
        }
        catch (IOException ioe) {
            return null;
        }
        finally {
            try {
                if (parcelZip != null)
                    parcelZip.close();
            }
            catch (IOException ioe) {}
        }

        return result;
    }

    private Manifest removeParcelFromManifest(File document, String name) {
        Manifest result = null;

        result = getManifestFromDocument(document);
        if (result == null)
            return null;

        result.remove(name);
        return result;
    }

    private String getParcelLanguage(File file) throws IOException {
        ZipFile zf = null;
        ZipEntry ze = null;
        InputStream is = null;
        ParcelDescriptor pd;

        try {
            zf = new ZipFile(file);
            ze = zf.getEntry(PARCEL_DESCRIPTOR_XML);

            if (ze == null)
                throw new IOException("Could not find Parcel Descriptor in parcel");

            is = zf.getInputStream(ze);
            pd = new ParcelDescriptor(is);
        }
        finally {
            if (zf != null)
                zf.close();

            if (is != null)
                is.close();
        }

        return pd.getLanguage().toLowerCase();
    }
}