KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > snipsnap > config > InitializeDatabase


1 /*
2  * This file is part of "SnipSnap Wiki/Weblog".
3  *
4  * Copyright (c) 2002 Stephan J. Schmidt, Matthias L. Jugel
5  * All Rights Reserved.
6  *
7  * Please visit http://snipsnap.org/ for updates and contact.
8  *
9  * --LICENSE NOTICE--
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  * --LICENSE NOTICE--
24  */

25 package org.snipsnap.config;
26
27 import org.snipsnap.app.Application;
28 import org.snipsnap.app.ApplicationManager;
29 import org.snipsnap.app.ApplicationStorage;
30 import org.snipsnap.container.Components;
31 import org.snipsnap.snip.HomePage;
32 import org.snipsnap.snip.Snip;
33 import org.snipsnap.snip.SnipSpace;
34 import org.snipsnap.snip.XMLSnipImport;
35 import org.snipsnap.snip.label.RenderEngineLabel;
36 import org.snipsnap.user.Permissions;
37 import org.snipsnap.user.Roles;
38 import org.snipsnap.user.User;
39 import org.snipsnap.user.UserManager;
40 import org.snipsnap.user.UserManagerFactory;
41 import org.snipsnap.net.admin.ThemeHelper;
42
43 import java.io.*;
44 import java.util.Collection JavaDoc;
45 import java.util.Locale JavaDoc;
46 import java.util.Properties JavaDoc;
47 import java.util.Map JavaDoc;
48
49 /**
50  * @author Matthias L. Jugel
51  * @version $Id: InitializeDatabase.java 1606 2004-05-17 10:56:18Z leo $
52  */

53 public class InitializeDatabase {
54
55   private static ThreadLocal JavaDoc output = new ThreadLocal JavaDoc();
56
57   private static void message(String JavaDoc message) {
58     if (null != output.get()) {
59       PrintWriter writer = (PrintWriter) output.get();
60       writer.println("[" + Application.get().getConfiguration().getName() + "] " + message);
61       writer.flush();
62     }
63   }
64
65   public static String JavaDoc init(Configuration config, Writer w) throws Exception JavaDoc {
66     output.set(new PrintWriter(w));
67
68     Application app = Application.get();
69     app.setConfiguration(config);
70
71     ApplicationManager appManager = (ApplicationManager) Components.getComponent(ApplicationManager.class);
72     Collection JavaDoc prefixes = appManager.getPrefixes();
73
74     if (prefixes != null && prefixes.contains(config.getPrefix())) {
75       throw new Exception JavaDoc("the prefix " + config.getPrefix() + " already exists");
76     }
77
78     Properties JavaDoc prefixProps = appManager.createApplication(config.getName(), config.getPrefix());
79     String JavaDoc appOid = prefixProps.getProperty(ApplicationStorage.OID);
80     try {
81       message("created application oid: " + appOid);
82       app.storeObject(Application.OID, appOid);
83
84       new File(config.getFileStore()).mkdirs();
85       // automatically created by the indexer
86
// (new File(config.getIndexPath())).mkdirs();
87

88       // get an instance of the snip space
89
SnipSpace space = (SnipSpace) Components.getComponent(SnipSpace.class);
90
91       createAdministrator(config);
92
93       // disable notifications and pings before loading snips and posting
94
String JavaDoc ping = config.get(Configuration.APP_PERM_WEBLOGSPING);
95       String JavaDoc notify = config.get(Configuration.APP_PERM_NOTIFICATION);
96       config.set(Configuration.APP_PERM_WEBLOGSPING, "deny");
97       config.set(Configuration.APP_PERM_NOTIFICATION, "deny");
98
99       // load defaults
100
InputStream data = getLocalizedResource("i18n.snipsnap", "snip", config.getLocale());
101       XMLSnipImport.load(data, XMLSnipImport.OVERWRITE | XMLSnipImport.IMPORT_USERS | XMLSnipImport.IMPORT_SNIPS);
102
103
104       message("loading defaults into configuration space");
105       // load other configurations
106
createConfigSnipFromFile(Configuration.SNIPSNAP_CONFIG_API, "/defaults/apidocs.txt", space);
107       createConfigSnipFromFile(Configuration.SNIPSNAP_CONFIG_ASIN, "/defaults/asinservices.txt", space);
108       createConfigSnipFromFile(Configuration.SNIPSNAP_CONFIG_BOOK, "/defaults/bookservices.txt", space);
109       createConfigSnipFromFile(Configuration.SNIPSNAP_CONFIG_PING, "/defaults/weblogsping.txt", space);
110       createConfigSnipFromFile(Configuration.SNIPSNAP_CONFIG_ROBOTS, "/defaults/robotdetect.txt", space);
111       createConfigSnipFromFile(Configuration.SNIPSNAP_CONFIG_ROBOTS_TXT, "/defaults/robots.txt", space);
112       createConfigSnipFromFile(Configuration.SNIPSNAP_CONFIG_WIKI, "/defaults/intermap.txt", space);
113
114       Map JavaDoc themeFiles = ThemeHelper.getThemeDocuments(config, ThemeHelper.FILES);
115       XMLSnipImport.load(new FileInputStream((File) themeFiles.get(config.getTheme())),
116                          XMLSnipImport.OVERWRITE | XMLSnipImport.IMPORT_SNIPS);
117
118       postFirstBlog(config, space);
119
120       config.set(Configuration.APP_PERM_WEBLOGSPING, ping);
121       config.set(Configuration.APP_PERM_NOTIFICATION, notify);
122
123       ConfigurationManager configManager = ConfigurationManager.getInstance();
124       configManager.addConfiguration(appOid, config);
125
126       // last, but not least store to file and configuration snip
127
storeConfiguration(config, space);
128
129     } catch (Exception JavaDoc e) {
130       appManager.removeApplication(appOid);
131       config.getFileStore(appOid).delete();
132       e.printStackTrace();
133       throw e;
134     }
135
136     return appOid;
137   }
138
139   public static void createConfigSnipFromFile(String JavaDoc name, String JavaDoc file, SnipSpace space) throws IOException {
140     String JavaDoc content = getResourceAsString(InitializeDatabase.class.getResourceAsStream(file));
141     createConfigSnip(name, content, space);
142   }
143
144   public static Snip createConfigSnip(String JavaDoc name, String JavaDoc content, SnipSpace space) {
145     Snip snip = space.create(name, content);
146     snip.getPermissions().add(Permissions.EDIT_SNIP, Roles.ADMIN);
147     snip.getPermissions().add(Permissions.ATTACH_TO_SNIP, Roles.ADMIN);
148     snip.getLabels().addLabel(new RenderEngineLabel("RenderEngine", "org.snipsnap.render.PlainTextRenderEngine"));
149     space.systemStore(snip);
150     return snip;
151   }
152
153   private static void postFirstBlog(Configuration config, SnipSpace space) throws IOException {
154     message("posting initial weblog entry");
155     String JavaDoc weblogPost = getResourceAsString(getLocalizedResource("i18n.welcome", "blog", config.getLocale()));
156     String JavaDoc title = weblogPost.substring(0, weblogPost.indexOf('\n'));
157     weblogPost = weblogPost.substring(weblogPost.indexOf('\n') + 1);
158     space.getBlog().post(weblogPost, title);
159   }
160
161   public final static String JavaDoc LOGO_FILE = "_logofile";
162   public final static String JavaDoc LOGO_FILE_TYPE = "_logofiletype";
163
164   private static void storeConfiguration(Configuration config, SnipSpace space) throws IOException {
165     String JavaDoc logoFileName = config.get(LOGO_FILE);
166     String JavaDoc logoFileType = config.get(LOGO_FILE_TYPE);
167     config.getProperties().remove(LOGO_FILE);
168     config.getProperties().remove(LOGO_FILE_TYPE);
169
170     message("creating configuration snip '" + Configuration.SNIPSNAP_CONFIG + "'");
171     config.setConfigured("true");
172     ByteArrayOutputStream configStream = new ByteArrayOutputStream();
173     config.store(configStream);
174     Snip configSnip = createConfigSnip(Configuration.SNIPSNAP_CONFIG,
175                                        new String JavaDoc(configStream.toString("UTF-8")),
176                                        space);
177     String JavaDoc logo = config.getLogo();
178     if (logoFileName != null && !"".equals(logoFileName)) {
179       File logoFile = new File(logoFileName);
180       File relativeFileLocation = new File(new File(Configuration.SNIPSNAP_CONFIG), logo);
181       new File(config.getFilePath(), Configuration.SNIPSNAP_CONFIG).mkdirs();
182       File attFile = new File(config.getFilePath(), relativeFileLocation.getPath());
183       FileInputStream in = new FileInputStream(logoFile);
184       FileOutputStream out = new FileOutputStream(attFile);
185       byte[] buf = new byte[4096];
186       int length = 0;
187       while ((length = in.read(buf)) != -1) {
188         out.write(buf, 0, length);
189       }
190       out.close();
191       in.close();
192       configSnip.getAttachments().addAttachment(logo, logoFileType, attFile.length(),
193                                                 relativeFileLocation.getPath());
194       space.store(configSnip);
195     }
196   }
197
198   private static User createAdministrator(Configuration config) {
199     // create admin account
200
message("creating administrator account and snip");
201     UserManager um = UserManagerFactory.getInstance();
202     User admin = um.load(config.getAdminLogin());
203     if (admin != null) {
204       message("overriding administrator: " + admin);
205       um.remove(admin);
206     }
207     admin = um.create(config.getAdminLogin(), config.getAdminPassword(), config.getAdminEmail());
208     admin.getRoles().add(Roles.ADMIN);
209     admin.getRoles().add(Roles.EDITOR);
210     um.store(admin);
211
212     // make sure the encrypted password is stored
213
config.setAdminPassword(admin.getPasswd());
214
215     // set current user and create it's homepage
216
Application.get().setUser(admin);
217     HomePage.create(config.getAdminLogin());
218
219     return admin;
220   }
221
222
223   private static String JavaDoc getResourceAsString(InputStream is) throws IOException {
224     BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
225     StringBuffer JavaDoc contents = new StringBuffer JavaDoc();
226     String JavaDoc line = null;
227     while ((line = in.readLine()) != null) {
228       contents.append(line).append("\n");
229     }
230     return contents.toString();
231   }
232
233   /**
234    * Get the input stream for a localized resource file given the resource base
235    * name and its extension and locale.
236    * @param resource the base name of the resource
237    * @param ext the file name extension (like .snip, .blog)
238    * @param locale the locale currently used
239    * @return the input stream of the resource or null if none was found
240    */

241   private static InputStream getLocalizedResource(String JavaDoc resource, String JavaDoc ext, Locale JavaDoc locale) {
242     InputStream is = findLocalizedResource(resource, ext, locale);
243     if (is == null) {
244       is = getResource(resource, null, null, null, ext);
245     }
246     return is;
247   }
248
249   /**
250    * Method to find a certain resource based on locale information.
251    * @param base the base name of the resource
252    * @param ext extension of the resource appended as ".ext"
253    * @return the resource found or null
254    */

255   private static InputStream findLocalizedResource(String JavaDoc base, String JavaDoc ext, Locale JavaDoc locale) {
256     String JavaDoc language = locale.getLanguage();
257     String JavaDoc country = locale.getCountry();
258     String JavaDoc variant = locale.getVariant();
259
260     InputStream is = null;
261     if ((is = getResource(base, language, country, variant, ext)) != null) {
262       return is;
263     } else if ((is = getResource(base, language, country, null, ext)) != null) {
264       return is;
265     } else if ((is = getResource(base, language, null, null, ext)) != null) {
266       return is;
267     }
268     return getResource(base, "en", null, null, ext);
269   }
270
271   /**
272    * Loads a resource from the CLASSPATH by appending language, country, variant to the base name.
273    * Example: messages_en_US.snip or messages_en.snip
274    * @param base the base name of the file
275    * @param ext extension appended as ".ext" to the resource name
276    * @return an input stream of the resource or null
277    */

278   private static InputStream getResource(String JavaDoc base, String JavaDoc language, String JavaDoc country, String JavaDoc variant, String JavaDoc ext) {
279     String JavaDoc file = "/" + base.replace('.', '/') +
280       (language != null ? "_" + language : "") +
281       (country != null ? "_" + country : "") +
282       (variant != null ? "_" + variant : "") +
283       "." + ext;
284     return InitializeDatabase.class.getResourceAsStream(file);
285   }
286 }
287
Popular Tags