Global.helma.Zip (file)
constructor function for Zip Objects

  • Parameter either:
    - (Object) a File object - (Object) an instance of Helma.File - (Object) an instance of java.io.File - (String) the path to the zip file
Sourcecode in /home/hannes/helma/modules/helma/Zip.js:
33:   helma.Zip = function (file) {
34:   
35:       /**
36:        * private function that extracts the data of a file
37:        * in a .zip archive. If a destination Path is given it
38:        * writes the extracted data directly to disk using the
39:        * name of the ZipEntry Object, otherwise it returns the
40:        * byte array containing the extracted data
41:        * @param Object jAva.util.zip.ZipFile Object
42:       * @param Object java.util.zip.ZipEntry Object to extract
43:       * @param String destination path to extract ZipEntry Object to
44:       * @return Object ByteArray containing the data of the ZipEntry
45:       */
46:      var extractEntry = function(zFile, entry, destPath) {
47:          var size = entry.getSize();
48:          if (entry.isDirectory() || size <= 0)
49:              return null;
50:  
51:          var zInStream = new java.io.BufferedInputStream(zFile.getInputStream(entry));
52:          var buf = new java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, size);
53:          zInStream.read(buf, 0, size);
54:          zInStream.close();
55:  
56:          if (!destPath) {
57:              // no filesystem destination given, so return
58:              // the byte array containing the extracted data
59:              return buf;
60:          }
61:          // extract the file to the given path
62:          var dest = new java.io.File(destPath, entry.getName());
63:          if (entry.isDirectory())
64:              dest.mkdirs();
65:          else if (buf) {
66:              if (!dest.getParentFile().exists())
67:                  dest.getParentFile().mkdirs();
68:              try {
69:                  var outStream = new java.io.BufferedOutputStream(new java.io.FileOutputStream(dest));
70:                  outStream.write(buf, 0, size);
71:              } finally {
72:                  outStream.close();
73:              }
74:          }
75:          return null;
76:      };
77:  
78:      /**
79:       * private function for adding a single file to the .zip archive
80:       * @param Object java.util.zip.ZipOutputStream
81:       * @param Object instance of java.io.File representing the file to be added
82:       * @param Int compression-level (0-9)
83:       * @param String path of the directory in the archive to which the
84:       *                    file should be added (optional)
85:       */
86:      var addFile = function(zOutStream, f, level, pathPrefix) {
87:          var fInStream = new java.io.BufferedInputStream(new java.io.FileInputStream(f));
88:          buf = new java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, f.length());
89:          fInStream.read(buf, 0, f.length());
90:  
91:          var name = new java.lang.StringBuffer();
92:          if (pathPrefix) {
93:              // append clean pathPrefix to name buffer
94:              var st = new java.util.StringTokenizer(pathPrefix, "\\/");
95:              while (st.hasMoreTokens()) {
96:                  name.append(st.nextToken());
97:                  name.append("/");
98:              }
99:          }
100:          name.append(f.getName());
101:          var entry = new java.util.zip.ZipEntry(name.toString());
102:          entry.setSize(f.length());
103:          entry.setTime(f.lastModified());
104:          zOutStream.setLevel(level);
105:          zOutStream.putNextEntry(entry);
106:          zOutStream.write(buf, 0, buf.length);
107:          zOutStream.closeEntry();
108:          fInStream.close();
109:          return true;
110:      };
111:  
112:      /**
113:       * private function that constructs an instance
114:       * of java.io.File based on a JS File or Helma.File object
115:       * @param Object either a string or an instance of java.io.File, File or Helma.File
116:       * @return Object instance of java.io.File
117:       */
118:      var evalFile = function(f) {
119:          if (f instanceof java.io.File)
120:              return f;
121:          var result;
122:          if (typeof f == "string")
123:              result = new java.io.File(f);
124:          else
125:              result = new java.io.File(f.getAbsolutePath());
126:          if (!result.exists())
127:              throw("Error creating Zip Object: File '" + f + "' doesn't exist.");
128:          return result;
129:      };
130:      
131:      /**
132:      * returns an array containing the entries of a .zip file as objects
133:      * (see Entry for description)
134:      * @param Object File object representing the .zip file on disk
135:      * @return Object result object
136:      */
137:     this.list = function() {
138:         var result = new helma.Zip.Content();
139:         var zFile = new java.util.zip.ZipFile(file);
140:         var entries = zFile.entries();
141:         while (entries.hasMoreElements())
142:             result.add(new helma.Zip.Entry(entries.nextElement()));
143:         zFile.close();
144:         return result;
145:     };
146: 
147:     /**
148:      * extracts a single file from a .zip archive
149:      * if a destination path is given it directly writes
150:      * the extracted file to disk
151:      * @param Object File object representing the .zip file on disk
152:      * @param String Name of the file to extract
153:      * @param String (optional) destination path to write file to
154:      * @return Object JS Object (see Entry for description)
155:      */
156:     this.extract = function(name, destPath) {
157:         var zFile = new java.util.zip.ZipFile(file);
158:         var entry = zFile.getEntry(name);
159:         if (!entry)
160:             return null;
161:         var result = new helma.Zip.Entry(entry);
162:         result.data = extractEntry(zFile, entry, destPath);
163:         zFile.close();
164:         return result;
165:     };
166: 
167:     /**
168:      * extracts all files in a .zip archive
169:      * if a destination path is given it directly writes
170:      * the extracted files to disk (preserves directory structure
171:      * of .zip archive if existing!)
172:      * @param String (optional) destination path to write file to
173:      * @return Object Array containing JS objects for each entry
174:      *                     (see Entry for description)
175:      */
176:     this.extractAll = function(destPath) {
177:         var result = new helma.Zip.Content();
178:         var zFile = new java.util.zip.ZipFile(file);
179:         var entries = zFile.entries();
180:         while (entries.hasMoreElements()) {
181:             var entry = entries.nextElement();
182:             var e = new helma.Zip.Entry(entry);
183:             e.data = extractEntry(zFile, entry, destPath);
184:             result.add(e);
185:         }
186:         zFile.close();
187:         return result;
188:     };
189: 
190:     /**
191:      * adds a single file or a whole directory (recursive!) to the .zip archive
192:      * @param either
193:      *          - (Object) a File object
194:      *          - (Object) an instance of java.io.File
195:      *          - (String) the path to the file that should be added
196:      * @param Int Level to use for compression (default: 9 = best compression)
197:      * @param String name of the directory in the archive into which the
198:      *                    file should be added (optional)
199:      * @return Boolean true
200:      */
201:     this.add = function (f, level, pathPrefix) {
202:         var f = evalFile(f);
203: 
204:         // evaluate arguments
205:         if (arguments.length == 2) {
206:             if (typeof arguments[1] == "string") {
207:                 pathPrefix = arguments[1];
208:                 level = 9;
209:             } else {
210:                 level = parseInt(arguments[1], 10);
211:                 pathPrefix = null;
212:             }
213:         } else if (level == null || isNaN(level)) {
214:             level = 9;
215:         }
216:         // only levels between 0 and 9 are allowed
217:         level = Math.max(0, Math.min(9, level));
218: 
219:         if (f.isDirectory()) {
220:             // add a whole directory to the zip file (recursive!)
221:             var files = (new helma.File(f.getAbsolutePath())).listRecursive();
222:             for (var i in files) {
223:                 var fAdd = new java.io.File(files[i]);
224:                 if (!fAdd.isDirectory()) {
225:                     var p = fAdd.getPath().substring(f.getAbsolutePath().length, fAdd.getParent().length);
226:                     if (pathPrefix)
227:                         p = pathPrefix + p;
228:                     addFile(zOutStream, fAdd, level, p);
229:                 }
230:             }
231:         } else
232:             addFile(zOutStream, f, level, pathPrefix);
233:         return true;
234:     };
235: 
236:     /**
237:      * adds a new entry to the zip file
238:      * @param Object byte[] containing the data to add
239:      * @param String name of the file to add
240:      * @param Int compression level (0-9, default: 9)
241:      * @return Boolean true
242:      */
243:     this.addData = function(buf, name, level) {
244:         var entry = new java.util.zip.ZipEntry(name);
245:         entry.setSize(buf.length);
246:         entry.setTime(new Date());
247:         if (level == null || isNaN(level))
248:             zOutStream.setLevel(9);
249:         else
250:             zOutStream.setLevel(Math.max(0, Math.min(9, parseInt(level, 10))));
251:         zOutStream.putNextEntry(entry);
252:         zOutStream.write(buf, 0, buf.length);
253:         zOutStream.closeEntry();
254:         return true;
255:     };
256: 
257:     /**
258:      * closes the ZipOutputStream
259:      */
260:     this.close = function() {
261:         zOutStream.close();
262:         return;
263:     };
264: 
265:     /**
266:      * returns the binary data of the zip file
267:      * @return Object ByteArray containing the binary data of the zip file
268:      */
269:     this.getData = function() {
270:         return bOutStream.toByteArray();
271:      };
272:     
273:     /**
274:      * saves the archive by closing the output stream
275:      * @param String path (including the name) to save the zip file to
276:      * @return Boolean true
277:      */
278:     this.save = function(dest) {
279:         if (!dest)
280:             throw new Error("no destination for ZipFile given");
281:         // first of all, close the ZipOutputStream
282:         zOutStream.close();
283:         var destFile = new java.io.File(dest);
284:         try {
285:             var outStream = new java.io.FileOutputStream(destFile);
286:             bOutStream.writeTo(outStream);
287:         } finally {
288:             outStream.close();
289:         }
290:         return true;
291:     };
292: 
293:     this.toString = function() {
294:         if (file)
295:             return "[Zip Object " + file.getAbsolutePath() + "]";
296:         else
297:             return "[Zip Object]";
298:     };
299: 
300:     /**
301:      * constructor body
302:      */
303:     var bOutStream = new java.io.ByteArrayOutputStream();
304:     var zOutStream = new java.util.zip.ZipOutputStream(bOutStream);
305:     if (file) {
306:         file = evalFile(file);
307:     }
308: 
309:     for (var i in this)
310:         this.dontEnum(i);
311: 
312:     return this;
313: }