1
22
23 package com.liferay.portal.kernel.zip;
24
25 import com.liferay.portal.kernel.log.Log;
26 import com.liferay.portal.kernel.log.LogFactoryUtil;
27 import com.liferay.portal.kernel.util.ByteArrayMaker;
28 import com.liferay.portal.kernel.util.ObjectValuePair;
29 import com.liferay.portal.kernel.util.StringPool;
30
31 import java.io.File;
32 import java.io.FileInputStream;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.io.Serializable;
36
37 import java.util.ArrayList;
38 import java.util.LinkedHashMap;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.zip.ZipEntry;
42 import java.util.zip.ZipInputStream;
43
44
51 public class ZipReader implements Serializable {
52
53 public ZipReader(File file) throws Exception {
54 _zis = new ZipInputStream(new FileInputStream(file));
55 }
56
57 public ZipReader(InputStream stream) {
58 try {
59 _zis = new ZipInputStream(stream);
60
61 while (true) {
62 ZipEntry entry = _zis.getNextEntry();
63
64 if (entry == null) {
65 break;
66 }
67
68 String currentName = entry.getName();
69
70 ByteArrayMaker bam = new ByteArrayMaker();
71
72 while (true) {
73 int count = _zis.read(_data, 0, _BUFFER);
74
75 if (count == -1) {
76 break;
77 }
78
79 bam.write(_data, 0, count);
80 }
81
82 byte[] byteArray = bam.toByteArray();
83
84 _entries.put(currentName, byteArray);
85
86 int pos = currentName.lastIndexOf(StringPool.SLASH);
87
88 String folderPath = StringPool.BLANK;
89 String fileName = currentName;
90
91 if (pos > 0) {
92 folderPath = currentName.substring(0, pos + 1);
93 fileName = currentName.substring(pos + 1);
94 }
95
96 List files = (List)_folderEntries.get(folderPath);
97
98 if (files == null) {
99 files = new ArrayList();
100
101 _folderEntries.put(folderPath, files);
102 }
103
104 files.add(new ObjectValuePair(fileName, byteArray));
105 }
106 }
107 catch (IOException ioe) {
108 _log.error(ioe, ioe);
109 }
110 finally {
111 try {
112 _zis.close();
113 }
114 catch (Exception e) {
115 if (_log.isWarnEnabled()) {
116 _log.warn(e);
117 }
118 }
119 }
120 }
121
122 public Map getEntries() {
123 return _entries;
124 }
125
126 public String getEntryAsString(String name) {
127 byte[] byteArray = getEntryAsByteArray(name);
128
129 if (byteArray != null) {
130 return new String(byteArray);
131 }
132
133 return null;
134 }
135
136 public byte[] getEntryAsByteArray(String name) {
137 return (byte[])_entries.get(name);
138 }
139
140 public Map getFolderEntries() {
141 return _folderEntries;
142 }
143
144 private static final int _BUFFER = 2048;
145
146 private static Log _log = LogFactoryUtil.getLog(ZipReader.class);
147
148 private ZipInputStream _zis;
149 private Map _entries = new LinkedHashMap();
150 private Map _folderEntries = new LinkedHashMap();
151 private byte[] _data = new byte[_BUFFER];
152
153 }