KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > info > magnolia > cms > module > ModuleUtil


1 /**
2  *
3  * Magnolia and its source-code is licensed under the LGPL.
4  * You may copy, adapt, and redistribute this file for commercial or non-commercial use.
5  * When copying, adapting, or redistributing this document in keeping with the guidelines above,
6  * you are required to provide proper attribution to obinary.
7  * If you reproduce or distribute the document without making any substantive modifications to its content,
8  * please use the following attribution line:
9  *
10  * Copyright 1993-2005 obinary Ltd. (http://www.obinary.com) All rights reserved.
11  *
12  */

13 package info.magnolia.cms.module;
14
15 import info.magnolia.cms.beans.config.ModuleLoader;
16 import info.magnolia.cms.core.Content;
17 import info.magnolia.cms.core.HierarchyManager;
18 import info.magnolia.cms.core.ItemType;
19 import info.magnolia.cms.core.SystemProperty;
20 import info.magnolia.cms.security.AccessDeniedException;
21
22 import java.io.BufferedOutputStream JavaDoc;
23 import java.io.File JavaDoc;
24 import java.io.FileOutputStream JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.InputStream JavaDoc;
27 import java.io.InputStreamReader JavaDoc;
28 import java.io.LineNumberReader JavaDoc;
29 import java.util.Enumeration JavaDoc;
30 import java.util.HashMap JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.Map JavaDoc;
33 import java.util.jar.JarEntry JavaDoc;
34 import java.util.jar.JarFile JavaDoc;
35
36 import javax.jcr.PathNotFoundException;
37 import javax.jcr.RepositoryException;
38
39 import org.apache.commons.collections.map.ListOrderedMap;
40 import org.apache.commons.lang.StringUtils;
41
42
43 /**
44  * This is a util providing some methods for the registration process of a module.
45  * @author philipp
46  * @version $Revision$ ($Author$)
47  */

48 public final class ModuleUtil {
49
50     /**
51      * used by the installFiles() method
52      * @author philipp
53      */

54     public interface IncludeMatcher {
55
56         /**
57          * @param name
58          * @return true if this file should get installed
59          */

60         boolean match(String JavaDoc name);
61
62         /**
63          * trans from the path from the jar entry name into a real path
64          * @param name
65          * @return the path to which this file should get installed
66          */

67         String JavaDoc transform(String JavaDoc name);
68     }
69
70     /**
71      * install files from a specifig directory
72      * @author philipp
73      */

74     public static class DirectoryIncludeMatcher implements IncludeMatcher {
75
76         private String JavaDoc path;
77
78         public DirectoryIncludeMatcher(String JavaDoc path) {
79             this.path = path;
80         }
81
82         public boolean match(String JavaDoc name) {
83             return name.startsWith(path);
84         }
85
86         public String JavaDoc transform(String JavaDoc name) {
87             return StringUtils.removeStart(name, path);
88         }
89     }
90
91     /**
92      * Util has no public constructor
93      */

94     private ModuleUtil() {
95     }
96
97     /**
98      * blocksize
99      */

100     public static final int DATA_BLOCK_SIZE = 1024 * 1024;
101
102     /**
103      * registers the properties in the repository
104      * @param hm
105      * @param name
106      * @throws IOException
107      * @throws RepositoryException
108      * @throws PathNotFoundException
109      * @throws AccessDeniedException
110      */

111     public static void registerProperties(HierarchyManager hm, String JavaDoc name) throws IOException JavaDoc, AccessDeniedException,
112         PathNotFoundException, RepositoryException {
113         Map JavaDoc map = new ListOrderedMap();
114
115         // not using properties since they are not ordered
116
// Properties props = new Properties();
117
// props.load(ModuleUtil.class.getResourceAsStream("/" + name.replace('.', '/') + ".properties"));
118
InputStream JavaDoc stream = ModuleUtil.class.getResourceAsStream("/" + name.replace('.', '/') + ".properties"); //$NON-NLS-1$ //$NON-NLS-2$
119
LineNumberReader JavaDoc lines = new LineNumberReader JavaDoc(new InputStreamReader JavaDoc(stream));
120
121         String JavaDoc line = lines.readLine();
122         while (line != null) {
123             line = line.trim();
124             if (line.length() > 0 && !line.startsWith("#")) { //$NON-NLS-1$
125
String JavaDoc key = StringUtils.substringBefore(line, "=").trim(); //$NON-NLS-1$
126
String JavaDoc value = StringUtils.substringAfter(line, "=").trim(); //$NON-NLS-1$
127
map.put(key, value);
128             }
129             line = lines.readLine();
130         }
131         lines.close();
132         stream.close();
133         registerProperties(hm, map);
134     }
135
136     public static void registerProperties(HierarchyManager hm, Map JavaDoc map) throws AccessDeniedException,
137         PathNotFoundException, RepositoryException {
138         for (Iterator JavaDoc iter = map.keySet().iterator(); iter.hasNext();) {
139             String JavaDoc key = (String JavaDoc) iter.next();
140             String JavaDoc value = (String JavaDoc) map.get(key);
141
142             String JavaDoc name = StringUtils.substringAfterLast(key, "."); //$NON-NLS-1$
143
String JavaDoc path = StringUtils.substringBeforeLast(key, ".").replace('.', '/'); //$NON-NLS-1$
144
Content node = createPath(hm, path);
145             node.getNodeData(name, true).setValue(value);
146         }
147     }
148
149     public static Content createPath(HierarchyManager hm, String JavaDoc path) throws AccessDeniedException,
150         PathNotFoundException, RepositoryException {
151         return createPath(hm, path, ItemType.CONTENTNODE);
152     }
153
154     public static Content createPath(HierarchyManager hm, String JavaDoc path, ItemType type) throws AccessDeniedException,
155         PathNotFoundException, RepositoryException {
156         // remove leading /
157
path = StringUtils.removeStart(path, "/");
158
159         String JavaDoc[] names = path.split("/"); //$NON-NLS-1$
160
Content node = hm.getRoot();
161         for (int i = 0; i < names.length; i++) {
162             String JavaDoc name = names[i];
163             if (node.hasContent(name)) {
164                 node = node.getContent(name);
165             }
166             else {
167                 node = node.createContent(name, type);
168             }
169         }
170         return node;
171     }
172
173     /**
174      * @param jar
175      * @throws Exception
176      * @deprecated use installFiles(jar, path) or installFiles(jar, matcher)
177      */

178     public static void installFiles(JarFile JavaDoc jar) throws Exception JavaDoc {
179         IncludeMatcher matcher = new IncludeMatcher() {
180
181             public boolean match(String JavaDoc name) {
182                 if (!name.equals("/") //$NON-NLS-1$
183
&& !name.endsWith("/") //$NON-NLS-1$
184
&& !name.startsWith("CH") //$NON-NLS-1$
185
&& !name.startsWith("META-INF") //$NON-NLS-1$
186
&& !name.endsWith(".JAR")) { //$NON-NLS-1$
187
return true;
188                 }
189                 return false;
190             }
191
192             public String JavaDoc transform(String JavaDoc name) {
193                 return name;
194             }
195         };
196
197         installFiles(jar, matcher);
198     }
199
200     public static void installFiles(JarFile JavaDoc jar, final String JavaDoc path) throws Exception JavaDoc {
201         installFiles(jar, new DirectoryIncludeMatcher(path));
202     }
203
204     /**
205      * Extracts files of a jar and stores them in the magnolia file structure
206      * @param jar the jar containing the files (jsp, images)
207      * @param matcher checks if the file must get installed
208      * @param prefix the prefix to remove from the names
209      * @throws Exception io exception
210      */

211     public static void installFiles(JarFile JavaDoc jar, IncludeMatcher matcher) throws Exception JavaDoc {
212
213         String JavaDoc root = null;
214         // Try to get root
215
try {
216             File JavaDoc f = new File JavaDoc(SystemProperty.getProperty(SystemProperty.MAGNOLIA_APP_ROOTDIR));
217             if (f.isDirectory()) {
218                 root = f.getAbsolutePath();
219             }
220         }
221         catch (Exception JavaDoc e) {
222             // nothing
223
}
224
225         if (root == null) {
226             throw new Exception JavaDoc("Invalid magnolia " + SystemProperty.MAGNOLIA_APP_ROOTDIR + " path"); //$NON-NLS-1$ //$NON-NLS-2$
227
}
228
229         Map JavaDoc files = new HashMap JavaDoc();
230         Enumeration JavaDoc entries = jar.entries();
231         while (entries.hasMoreElements()) {
232             JarEntry JavaDoc entry = (JarEntry JavaDoc) entries.nextElement();
233             String JavaDoc name = entry.getName().toUpperCase();
234
235             // Exclude root, dirs, ch-dir, META-INF-dir and jars
236
if (matcher.match(name.toUpperCase())) { //$NON-NLS-1$
237
files.put(new File JavaDoc(root, matcher.transform(name)), entry);
238             }
239         }
240
241         // Loop throgh files an check writeable
242
String JavaDoc error = StringUtils.EMPTY;
243         Iterator JavaDoc iter = files.keySet().iterator();
244         while (iter.hasNext()) {
245             File JavaDoc file = (File JavaDoc) iter.next();
246             String JavaDoc s = StringUtils.EMPTY;
247             if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
248                 s = "Can't create directories for " + file.getAbsolutePath(); //$NON-NLS-1$
249
}
250             else if (!file.getParentFile().canWrite()) {
251                 s = "Can't write to " + file.getAbsolutePath(); //$NON-NLS-1$
252
}
253             if (s.length() > 0) {
254                 if (error.length() > 0) {
255                     error += "\r\n"; //$NON-NLS-1$
256
}
257                 error += s;
258             }
259         }
260
261         if (error.length() > 0) {
262             throw new Exception JavaDoc("Errors while installing files: " + error); //$NON-NLS-1$
263
}
264
265         // Copy files
266
iter = files.keySet().iterator();
267         while (iter.hasNext()) {
268             File JavaDoc file = (File JavaDoc) iter.next();
269             JarEntry JavaDoc entry = (JarEntry JavaDoc) files.get(file);
270
271             int byteCount = 0;
272             byte[] data = new byte[DATA_BLOCK_SIZE];
273
274             InputStream JavaDoc in = null;
275             BufferedOutputStream JavaDoc out = null;
276
277             try {
278                 in = jar.getInputStream(entry);
279                 out = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(file), DATA_BLOCK_SIZE);
280
281                 while ((byteCount = in.read(data, 0, DATA_BLOCK_SIZE)) != -1) {
282                     out.write(data, 0, byteCount);
283                 }
284             }
285             finally {
286                 try {
287                     out.close();
288                 }
289                 catch (Exception JavaDoc e) {
290                     // nothing
291
}
292             }
293         }
294     }
295
296     /**
297      * Create a minimal module configuration
298      * @param node the module node
299      * @param name module name
300      * @param className the class used
301      * @param version version number of the module
302      * @return the modified node (not yet stored)
303      * @throws AccessDeniedException exception
304      * @throws PathNotFoundException exception
305      * @throws RepositoryException exception
306      */

307     public static Content createMinimalConfiguration(Content node, String JavaDoc name, String JavaDoc className, String JavaDoc version)
308         throws AccessDeniedException, PathNotFoundException, RepositoryException {
309         node.createNodeData("version").setValue(version); //$NON-NLS-1$
310
node.createNodeData("license"); //$NON-NLS-1$
311
node.createContent("Config"); //$NON-NLS-1$
312
node.createContent("VirtualURIMapping", ItemType.CONTENTNODE); //$NON-NLS-1$
313

314         Content register = node.createContent(ModuleLoader.CONFIG_NODE_REGISTER, ItemType.CONTENTNODE);
315         register.createNodeData("moduleName"); //$NON-NLS-1$
316
register.createNodeData("moduleDescription"); //$NON-NLS-1$
317
register.createNodeData("class").setValue(className); //$NON-NLS-1$
318
register.createNodeData("repository"); //$NON-NLS-1$
319
register.createContent("sharedRepositories", ItemType.CONTENTNODE); //$NON-NLS-1$
320
register.createContent("initParams", ItemType.CONTENTNODE); //$NON-NLS-1$
321
return node;
322     }
323
324 }
Popular Tags