KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > info > magnolia > cms > beans > config > Bootstrapper


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-2006 obinary Ltd. (http://www.obinary.com) All rights reserved.
11  */

12 package info.magnolia.cms.beans.config;
13
14 import info.magnolia.cms.core.Path;
15 import info.magnolia.cms.core.SystemProperty;
16 import info.magnolia.cms.core.ie.DataTransporter;
17 import info.magnolia.context.MgnlContext;
18
19 import java.io.File JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.util.Collection JavaDoc;
22 import java.util.Comparator JavaDoc;
23 import java.util.Iterator JavaDoc;
24 import java.util.Set JavaDoc;
25 import java.util.SortedSet JavaDoc;
26 import java.util.TreeSet JavaDoc;
27
28 import org.apache.commons.io.FileUtils;
29 import org.apache.commons.io.filefilter.FileFilterUtils;
30 import org.apache.commons.io.filefilter.IOFileFilter;
31 import org.apache.commons.lang.StringUtils;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35
36 /**
37  * Bootstrapper: loads content from xml when a magnolia is started with an uninitialized repository.
38  * @author Fabrizio Giustina
39  * @version $Revision: 6586 $ ($Author: philipp $)
40  */

41 public final class Bootstrapper {
42     
43     /**
44      * Logger.
45      */

46     private static Logger log = LoggerFactory.getLogger(Bootstrapper.class);
47
48     /**
49      * Used to process an additional filtering for the bootstrap files
50      * @author philipp
51      */

52     public interface BootstrapFilter {
53
54         boolean accept(String JavaDoc filename);
55     }
56
57     /**
58      * don't instantiate
59      */

60     private Bootstrapper() {
61         // unused
62
}
63
64     /**
65      * Repositories appears to be empty and the <code>"magnolia.bootstrap.dir</code> directory is configured in
66      * web.xml. Loops over all the repositories and try to load any xml file found in a subdirectory with the same name
67      * of the repository. For example the <code>config</code> repository will be initialized using all the
68      * <code>*.xml</code> files found in <code>"magnolia.bootstrap.dir</code><strong>/config</strong> directory.
69      * @param bootdirs bootstrap dir
70      */

71     public static void bootstrapRepositories(String JavaDoc[] bootdirs, BootstrapFilter filter) {
72
73         if (log.isInfoEnabled()) {
74             log.info("-----------------------------------------------------------------"); //$NON-NLS-1$
75
log.info("Trying to initialize repositories from:");
76             for (int i = 0; i < bootdirs.length; i++) {
77                 log.info(bootdirs[i]);
78             }
79             log.info("-----------------------------------------------------------------"); //$NON-NLS-1$
80
}
81
82         Iterator JavaDoc repositoryNames = ContentRepository.getAllRepositoryNames();
83         while (repositoryNames.hasNext()) {
84             String JavaDoc repositoryName = (String JavaDoc) repositoryNames.next();
85
86             if (!bootstrapRepository(repositoryName, filter, bootdirs)) {
87                 // exeption was already logged
88
break;
89             }
90
91             log.info("Repository [{}] has been initialized.", repositoryName); //$NON-NLS-1$
92
}
93     }
94
95     /**
96      * Bootstrap a repository using the default bootstrap directories
97      * @param repositoryName
98      * @param filter
99      * @return true if succeeded
100      */

101     public static boolean bootstrapRepository(String JavaDoc repositoryName, BootstrapFilter filter) {
102         return bootstrapRepository(repositoryName, filter, getBootstrapDirs());
103     }
104
105     /**
106      * Bootstrap a specific repository
107      * @param repositoryName
108      * @param filter
109      * @param bootdirs
110      * @return
111      */

112     public static boolean bootstrapRepository(String JavaDoc repositoryName, BootstrapFilter filter, String JavaDoc[] bootdirs) {
113         Set JavaDoc xmlfileset = getBootstrapFiles(bootdirs, repositoryName, filter);
114
115         if (xmlfileset.isEmpty()) {
116             log.info("No bootstrap files found for repository [{}], skipping...", repositoryName); //$NON-NLS-1$
117
return true;
118         }
119
120         log.info("Trying to import content from {} files into repository [{}]", //$NON-NLS-1$
121
Integer.toString(xmlfileset.size()), repositoryName);
122
123         return bootstrapFiles(repositoryName, xmlfileset);
124     }
125
126     /**
127      * Bootstrap the passed set of files
128      * @param repositoryName
129      * @param filesSet
130      * @return
131      */

132     public static boolean bootstrapFiles(String JavaDoc repositoryName, Set JavaDoc filesSet) {
133         File JavaDoc[] files = (File JavaDoc[]) filesSet.toArray(new File JavaDoc[filesSet.size()]);
134         return bootstrapFiles(repositoryName, files);
135     }
136
137     /**
138      * Bootstrap the array of files
139      * @param repositoryName
140      * @param files
141      * @return
142      */

143     public static boolean bootstrapFiles(String JavaDoc repositoryName, File JavaDoc[] files) {
144         try {
145             for (int k = 0; k < files.length; k++) {
146                 File JavaDoc xmlFile = files[k];
147                 if(log.isDebugEnabled()){
148                     log.debug("execute importfile {}", xmlFile);
149                 }
150                 DataTransporter.executeBootstrapImport(xmlFile, repositoryName);
151             }
152         }
153         catch (IOException JavaDoc ioe) {
154             log.error(ioe.getMessage(), ioe);
155         }
156         catch (OutOfMemoryError JavaDoc e) {
157             int maxMem = (int) (Runtime.getRuntime().maxMemory() / 1024 / 1024);
158             int needed = Math.max(256, maxMem + 128);
159             log.error("Unable to complete bootstrapping: out of memory.\n" //$NON-NLS-1$
160
+ "{} MB were not enough, try to increase the amount of memory available by adding the -Xmx{}m parameter to the server startup script.\n" //$NON-NLS-1$
161
+ "You will need to completely remove the magnolia webapp before trying again", //$NON-NLS-1$
162
Integer.toString(maxMem), Integer.toString(needed));
163             return false;
164         }
165         return true;
166     }
167
168     /**
169      * Get the files to bootstrap. The method garantees that only one file is imported if it occures twice in the
170      * bootstrap dir. The set is returned sorted, so that the execution fo the import will import the upper most nodes
171      * first. This is done using the filelength.
172      * @param bootdirs
173      * @param repositoryName
174      * @param filter
175      * @return the sorted set
176      */

177     public static SortedSet JavaDoc getBootstrapFiles(String JavaDoc[] bootdirs, final String JavaDoc repositoryName, final BootstrapFilter filter) {
178         SortedSet JavaDoc xmlfileset = new TreeSet JavaDoc(new Comparator JavaDoc() {
179
180             // remove file with the same name in different dirs
181
public int compare(Object JavaDoc file1obj, Object JavaDoc file2obj) {
182                 File JavaDoc file1 = (File JavaDoc) file1obj;
183                 File JavaDoc file2 = (File JavaDoc) file2obj;
184
185                 String JavaDoc name1 = getName(file1); //$NON-NLS-1$
186
String JavaDoc name2 = getName(file2); //$NON-NLS-1$
187

188                 String JavaDoc ext1 = getExtension(file1);
189                 String JavaDoc ext2 = getExtension(file2);
190                 
191                 if(StringUtils.equals(ext1, ext2)){
192                     // a simple way to detect nested nodes
193
if (name1.length() != name2.length()) {
194                         return name1.length() - name2.length();
195                     }
196                 }
197                 else{
198                     // import xml first
199
if(ext1.equalsIgnoreCase("xml")){
200                         return -1;
201                     }
202                     else if(ext2.equalsIgnoreCase("properties")){
203                         return 1;
204                     }
205                 }
206                 
207                 return name1.compareTo(name2);
208             }
209             
210         });
211
212         for (int j = 0; j < bootdirs.length; j++) {
213             String JavaDoc bootdir = bootdirs[j];
214             File JavaDoc xmldir = new File JavaDoc(bootdir);
215             if (!xmldir.exists() || !xmldir.isDirectory()) {
216                 continue;
217             }
218
219             Collection JavaDoc files = FileUtils.listFiles(xmldir, new IOFileFilter(){
220                 public boolean accept(File JavaDoc file) {
221                     return accept(file.getParentFile(), file.getName());
222                 }
223                 public boolean accept(File JavaDoc dir, String JavaDoc name) {
224                     return name.startsWith(repositoryName + ".")
225                         && filter.accept(name)
226                         && (name.endsWith(DataTransporter.XML) || name.endsWith(DataTransporter.ZIP) || name
227                             .endsWith(DataTransporter.GZ) || name.endsWith(DataTransporter.PROPERTIES));
228                 }
229             }, FileFilterUtils.trueFileFilter());
230
231             xmlfileset.addAll(files);
232         }
233         
234         return xmlfileset;
235     }
236
237     private static String JavaDoc getExtension(File JavaDoc file){
238         String JavaDoc ext = StringUtils.substringAfterLast(file.getName(),".");
239         if(("." + ext).equals(DataTransporter.GZ) || ("." + ext).equals(DataTransporter.ZIP)){
240             ext = StringUtils.substringAfterLast(StringUtils.substringBeforeLast(file.getName(), "."), ".");
241         }
242         return ext;
243     }
244
245     private static String JavaDoc getName(File JavaDoc file){
246         String JavaDoc name = StringUtils.substringBeforeLast(file.getName(),".");
247         if(name.endsWith(DataTransporter.XML) || name.endsWith(DataTransporter.PROPERTIES)){
248             name = StringUtils.substringBeforeLast(file.getName(),".");
249         }
250         return name;
251     }
252     
253     /**
254      * Return the standard bootstrap dirs defined in the magnolia.properies file
255      * @return Array of directory names
256      */

257     public static String JavaDoc[] getBootstrapDirs() {
258         String JavaDoc bootdirProperty = SystemProperty.getProperty(SystemProperty.MAGNOLIA_BOOTSTRAP_ROOTDIR);
259
260         if (StringUtils.isEmpty(bootdirProperty)) {
261             return new String JavaDoc[0];
262         }
263
264         String JavaDoc[] bootDirs = StringUtils.split(bootdirProperty);
265
266         // converts to absolute paths
267
for (int j = 0; j < bootDirs.length; j++) {
268             bootDirs[j] = Path.getAbsoluteFileSystemPath(bootDirs[j]);
269         }
270         return bootDirs;
271     }
272
273 }
274
Popular Tags