1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.exorcist.core.zip;
17
18 import java.io.FileOutputStream;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.util.Iterator;
22 import java.util.logging.Logger;
23 import java.util.zip.ZipEntry;
24 import java.util.zip.ZipOutputStream;
25
26 import net.sf.exorcist.api.ContentException;
27 import net.sf.exorcist.api.ContentImporter;
28 import net.sf.exorcist.api.ContentState;
29
30 /***
31 * Importer plugin for the Exorcist content state file format.
32 * This plugin can be used to save content into an Exorcist
33 * content state file.
34 */
35 public class ZipImporter extends ZipBase implements ContentImporter {
36
37 /*** Static logger instance. */
38 private static final Logger logger =
39 Logger.getLogger(ZipImporter.class.getName());
40
41 /***
42 * Writes the contents of the given {@link ContentState} instance
43 * to the content state file.
44 *
45 * @param state the content state to be written to the state file
46 * @throws ContentException if the content state file could not be written
47 * @see ContentImporter#importContent(ContentState)
48 */
49 public void importContent(ContentState state) throws ContentException {
50 ZipOutputStream zip = null;
51 try {
52 logger.info("Writing content state file " + getZipfile());
53 zip = new ZipOutputStream(new FileOutputStream(getZipfile()));
54
55 logger.fine("Writing " + CONTENT_XML + " to " + getZipfile());
56 writeEntry(zip, CONTENT_XML, state.getContent());
57
58 Iterator iterator = state.getAttachmentHashes().iterator();
59 while (iterator.hasNext()) {
60 String hash = (String) iterator.next();
61 logger.fine(
62 "Writing attachment " + hash + " to " + getZipfile());
63 String part = hash.substring(0, 2) + "/" + hash.substring(2, 4);
64 writeEntry(
65 zip, DATA + "/" + part + "/" + hash,
66 state.getAttachment(hash));
67 }
68 } catch (IOException e) {
69 throw new ContentException(e);
70 } finally {
71 logger.fine("Closing content state file " + getZipfile());
72 try { zip.close(); } catch (Exception e) {}
73 }
74 }
75
76 /***
77 * Static utility method for writing a single entry to the given
78 * zip output stream.
79 * <p>
80 * Note that the given input stream is fully consumed <em>and closed</em>
81 * by this method.
82 *
83 * @param zip the zip output stream
84 * @param name name of the entry to be written
85 * @param in contents of the entry to be written
86 * @throws IOException if the entry could not be written
87 */
88 private static void writeEntry(
89 ZipOutputStream zip, String name, InputStream in)
90 throws IOException {
91 zip.putNextEntry(new ZipEntry(name));
92 try {
93 byte[] buffer = new byte[4096];
94 for (int n = in.read(buffer); n != -1; n = in.read(buffer)) {
95 zip.write(buffer, 0, n);
96 }
97 } finally {
98 try { in.close(); } catch (Exception e) {}
99 }
100 zip.closeEntry();
101 }
102
103 }