KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > openedit > modules > update > UpdateModule


1 /*
2 Copyright (c) 2004 eInnovation Inc. All rights reserved
3
4 This library is free software; you can redistribute it and/or modify it under the terms
5 of the GNU Lesser General Public License as published by the Free Software Foundation;
6 either version 2.1 of the License, or (at your option) any later version.
7
8 This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
9 without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 See the GNU Lesser General Public License for more details.
11 */

12
13 /*
14  * Created on Feb 17, 2004
15  *
16  * Updated by: Todd Fisher\Christopher Burke
17  * Date: 6/27/2005
18  * Comments: updated updateProject to download and save install.xml and run ANT shell script
19  */

20 package com.openedit.modules.update;
21
22 import java.io.File JavaDoc;
23 import java.util.ArrayList JavaDoc;
24 import java.util.Arrays JavaDoc;
25 import java.util.Collections JavaDoc;
26 import java.util.HashMap JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.List JavaDoc;
29 import java.util.Map JavaDoc;
30
31 import org.apache.commons.httpclient.HttpClient;
32 import org.apache.commons.httpclient.methods.PostMethod;
33 import org.apache.commons.httpclient.methods.multipart.FilePart;
34 import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
35 import org.apache.commons.httpclient.methods.multipart.Part;
36 import org.apache.commons.httpclient.methods.multipart.StringPart;
37 import org.apache.commons.logging.Log;
38 import org.apache.commons.logging.LogFactory;
39 import org.dom4j.Element;
40 import org.springframework.beans.factory.config.BeanDefinition;
41 import org.springframework.beans.factory.support.AbstractBeanDefinition;
42
43 import com.openedit.OpenEditException;
44 import com.openedit.OpenEditRuntimeException;
45 import com.openedit.WebPageRequest;
46 import com.openedit.WebServer;
47 import com.openedit.modules.BaseModule;
48 import com.openedit.modules.admin.filemanager.FileUpload;
49 import com.openedit.modules.scriptrunner.ScriptModule;
50 import com.openedit.page.Page;
51 import com.openedit.users.User;
52 import com.openedit.util.XmlUtil;
53
54 /**
55  * This module allows users to update their version of OpenEdit.
56  *
57  * @author dbrown
58  */

59 public class UpdateModule extends BaseModule
60 {
61     protected WebServer fieldWebServer;
62     
63     private static final Log log = LogFactory.getLog(UpdateModule.class);
64     
65     
66     public void updateProject( WebPageRequest inContext ) throws Exception JavaDoc
67     {
68         String JavaDoc project = inContext.getRequestParameter("project-name");
69         String JavaDoc beanname = inContext.getRequestParameter("spring-name");
70         //loadUpdateModule( inContext, module); //this should be CartModule or Edit
71
//run ANT with a shell exe? or use the ANT library?
72
String JavaDoc confirm = inContext.getRequestParameter("confirm");
73         String JavaDoc returnMessage = null;
74         String JavaDoc strUrl = null;
75         loadUpdateModule(inContext, beanname);
76         if ( project != null && project.length() > 0 && confirm != null && confirm.trim().equalsIgnoreCase("true"))
77         {
78             
79             //*** taking project name read in, splitting it to get project name
80
//*** Example: openedit-intranet
81
//*** Example after split: intranet
82

83             //*** download and save .xml file into update directory through http://
84
//*** would prefer to read web site in through a config file
85
strUrl = "http://dev.openedit.org/anthill/projects/" + project + "/install.js";
86             
87             //*** configure file path variable
88
String JavaDoc strOutputFile = "/WEB-INF/install.js";
89
90             //*** get root path of this object
91
String JavaDoc root = getRoot().getAbsolutePath();
92             if ( root.endsWith("/"))
93             {
94                 root = root.substring(0,root.length() - 1);
95             }
96             
97             //*** connect to configured web site
98
File JavaDoc out = new File JavaDoc( root, strOutputFile);
99             new Downloader().download(strUrl,out);
100
101             ScriptModule module = (ScriptModule)getModule("Script");
102             Map JavaDoc variables = new HashMap JavaDoc();
103             variables.put("context", inContext);
104             List JavaDoc logs = new ArrayList JavaDoc();
105             logs.add("Downloading latest upgrade script...");
106             inContext.putPageValue("log", logs);
107             variables.put("log", logs);
108             try
109             {
110                 log.info("Upgrading " + project);
111                 module.execScript(variables, strOutputFile );
112                 returnMessage = "COMPLETED";
113             }
114             catch ( OpenEditException ex)
115             {
116                 returnMessage = ex.getMessage();
117                 inContext.putPageValue("exception" , ex);
118                 log.error(ex);
119             }
120         }
121         else
122         {
123             returnMessage = "CONFIRM";
124         }
125         inContext.putPageValue("returnMessage" , returnMessage);
126         
127         //Read in the output file?
128
//redirect the user to a blank page
129
}
130     
131     /**
132      *
133      * @param inContext
134      * @param inModule
135      * @throws Exception
136      */

137     public void loadUpdateModule( WebPageRequest inContext, String JavaDoc inBean ) throws Exception JavaDoc
138     {
139         inContext.putPageValue( "updateModule", this );
140         //inContext.putPageValue("website", getWebSite());
141
//find out the version of the module in question
142
if (inBean != null)
143         {
144             Bean obj = createBean(inBean);
145             inContext.putPageValue("bean",obj);
146         }
147         
148     }
149         
150     /**
151      *
152      * @param inReq
153      * @throws Exception
154      */

155     public List JavaDoc listModules(WebPageRequest inReq) throws Exception JavaDoc
156     {
157         List JavaDoc allModules = new ArrayList JavaDoc();
158         List JavaDoc sortedNames = new ArrayList JavaDoc();
159         
160         String JavaDoc[] names = getWebServer().getBeanFactory().getBeanDefinitionNames();
161         sortedNames = Arrays.asList(names);
162         
163         for (int i = 0; i < sortedNames.size(); i++) {
164             String JavaDoc name = (String JavaDoc)sortedNames.get(i);
165             Bean bean = createBean(name);
166             if( bean != null)
167             {
168                 allModules.add(bean);
169             }
170         }
171         
172         //Collections.sort(allModules, new BeanComparator() );
173
inReq.putPageValue("allModules",allModules);
174         return allModules;
175     }
176
177     protected Bean createBean(String JavaDoc springId)
178     {
179         if ( getWebServer().getBeanFactory().containsBean(springId))
180         {
181             BeanDefinition beanDe = getWebServer().getBeanFactory().getBeanDefinition(springId);
182             if ( !(beanDe instanceof AbstractBeanDefinition))
183             {
184                 throw new OpenEditRuntimeException("Spring version not supported yet");
185                 
186             }
187             AbstractBeanDefinition beanDef = (AbstractBeanDefinition)beanDe;
188             Bean bean = new Bean();
189             
190             // get name of module
191
bean.setName(springId);
192             bean.setBeanDefinition(beanDef.getBeanClass());
193             
194             // get version of module
195
String JavaDoc version = beanDef.getBeanClass().getPackage().getImplementationVersion();
196             bean.setVersion(version);
197             
198             // get title of module
199
String JavaDoc title = beanDef.getBeanClass().getPackage().getImplementationTitle();
200             bean.setTitle(title);
201             return bean;
202         }
203         return null;
204     }
205     
206     /**
207      *
208      * @param inReq
209      * @throws Exception
210      */

211     public void listPageValues(WebPageRequest inReq) throws Exception JavaDoc
212     {
213         List JavaDoc allModules = new ArrayList JavaDoc();
214         
215         
216         List JavaDoc sortedNames = new ArrayList JavaDoc(inReq.getPageMap().keySet() );
217         Collections.sort(sortedNames);
218         
219         for (int i = 0; i < sortedNames.size(); i++) {
220             
221             String JavaDoc name = (String JavaDoc)sortedNames.get(i);
222             Bean bean = new Bean();
223             bean.setName(name);
224             Object JavaDoc obj = inReq.getPageValue(name);
225             
226             if ( obj instanceof String JavaDoc)
227             {
228                 bean.setValue((String JavaDoc)obj);
229             }
230             
231             bean.setBeanDefinition(obj.getClass());
232             allModules.add(bean);
233         }
234         
235         inReq.putPageValue("allPageValues",allModules);
236     }
237
238     public WebServer getWebServer()
239     {
240         return fieldWebServer;
241     }
242
243     public void setWebServer(WebServer inWebServer)
244     {
245         fieldWebServer = inWebServer;
246     }
247     public List JavaDoc loadSiteList(WebPageRequest inReq) throws Exception JavaDoc
248     {
249         Page sites = getPageManager().getPage("/openedit/update/sites.xml");
250         Element root = new XmlUtil().getXml( sites.getReader(), sites.getCharacterEncoding() );
251         List JavaDoc all = new ArrayList JavaDoc();
252         for (Iterator JavaDoc iter = root.elementIterator("site"); iter.hasNext();)
253         {
254             Element child = (Element) iter.next();
255             Site site = new Site();
256             site.setId(child.attributeValue("id"));
257             site.setText(child.attributeValue("text"));
258             site.setHref(child.attributeValue("href"));
259             all.add( site);
260         }
261         
262         List JavaDoc dirs = new ArrayList JavaDoc();
263         dirs.add("/");
264         List JavaDoc names = getPageManager().getChildrenNames("/");
265         for (Iterator JavaDoc iterator = names.iterator(); iterator.hasNext();)
266         {
267             String JavaDoc path = (String JavaDoc) iterator.next();
268             Page dir = getPageManager().getPage(path);
269             if( dir.isFolder() )
270             {
271                 dirs.add(path);
272             }
273         }
274         inReq.putPageValue("dirs", dirs);
275         
276         inReq.putPageValue("sites", all);
277         return all;
278     }
279     public Site selectSite(WebPageRequest inReq) throws Exception JavaDoc
280     {
281         String JavaDoc id = inReq.getRequestParameter("siteid");
282         if( id == null)
283         {
284             return null;
285         }
286         List JavaDoc sites = loadSiteList(inReq);
287         Site selected = null;
288         for (Iterator JavaDoc iter = sites.iterator(); iter.hasNext();)
289         {
290             Site site = (Site) iter.next();
291             if ( site.getId().equals(id))
292             {
293                 selected = site;
294             }
295         }
296         //set password
297
if ( selected != null)
298         {
299             String JavaDoc username = inReq.getRequestParameter("username");
300             String JavaDoc password = inReq.getRequestParameter("password");
301             selected.setUsername(username);
302             selected.setPassword(password);
303         }
304         inReq.putPageValue("sitetopush", selected);
305         return selected;
306     }
307     public void pushDirectory(WebPageRequest inReq) throws Exception JavaDoc
308     {
309         Site toUpgrade = selectSite( inReq );
310         inReq.setRequestParameter("name", "pushed to " + toUpgrade.getId());
311         File JavaDoc backup = backUpDirectory(inReq);
312
313         String JavaDoc url = toUpgrade.getHref();
314         if (!url.startsWith("http://"))
315         {
316             url = "http://" + url;
317         }
318         
319         if ( !url.endsWith("/"))
320         {
321             url += "/";
322         }
323         url += "openedit/update/receivepush.html";
324         log.info("posting here:" + url);
325         
326         PostMethod postMethod = new PostMethod(url);
327
328         Part[] parts = {
329             new StringPart("username", toUpgrade.getUsername()),
330             new StringPart("password", toUpgrade.getPassword()),
331             new StringPart("savedas", backup.getName()),
332             new FilePart("file", backup) };
333         
334         postMethod.setRequestEntity( new MultipartRequestEntity(parts, postMethod.getParams()) );
335         
336         HttpClient client = new HttpClient();
337         //client.getHttpConnectionManager().getParams().setConnectionTimeout(0);
338
int statusCode1 = client.executeMethod(postMethod);
339         postMethod.releaseConnection();
340         if( statusCode1 == 200)
341         {
342             inReq.putPageValue("message", "Push is completed." );
343         }
344         else
345         {
346             inReq.putPageValue("message", "Status code: <b>" + statusCode1 + "</b><br>" + postMethod.getResponseBodyAsString() );
347         }
348     }
349     public File JavaDoc backUpDirectory(WebPageRequest inReq) throws Exception JavaDoc
350     {
351         Backup backup = new Backup();
352         backup.setRoot(getRoot());
353         String JavaDoc subdir = inReq.getRequiredParameter("directory");
354         backup.setIncludePath(subdir);
355         backup.setPageManager(getPageManager());
356         
357         //String backupName = inReq.getRequiredParameter("name");
358
String JavaDoc backupName = inReq.getUserName() + subdir;
359         File JavaDoc results = backup.backupCurrentSite(backupName);
360         inReq.putPageValue("result", results);
361         return results;
362     }
363     public List JavaDoc listVersions(WebPageRequest inReq) throws Exception JavaDoc
364     {
365         Backup backup = new Backup();
366         backup.setRoot(getRoot());
367         backup.setPageManager(getPageManager());
368         List JavaDoc versions = backup.listSiteVersions();
369         inReq.putPageValue("versionlist", versions);
370         return versions;
371     }
372     public void restoreVersion(WebPageRequest inReq) throws Exception JavaDoc
373     {
374         String JavaDoc name = inReq.getRequestParameter("versionid");
375         if( name != null)
376         {
377             //check that we are logged in
378
Backup backup = new Backup();
379             backup.setRoot(getRoot());
380             backup.setPageManager(getPageManager());
381             File JavaDoc version = backup.loadVersion( name );
382             if ( version == null)
383             {
384                 log.error("No such backup found " + name);
385                 inReq.putPageValue("error", "No such file");
386             }
387             else
388             {
389                 backup.restoreBackup(version);
390             }
391         }
392         else
393         {
394             log.error("No versionid parameter");
395         }
396         
397     }
398     public void receivePush(WebPageRequest inReq) throws Exception JavaDoc
399     {
400         //this is an upload then a restore
401
FileUpload command = new FileUpload();
402         command.setPageManager(getPageManager());
403         Map JavaDoc properties = command.parseArguments(inReq);
404         if ( properties == null)
405         {
406             log.error("Nothing posted");
407             return;
408         }
409         String JavaDoc username = (String JavaDoc)properties.get("username");
410         String JavaDoc password = (String JavaDoc)properties.get("password");
411         
412         User admin = getUserManager().getUser(username);
413         if ( !getUserManager().authenticate(admin, password) )
414         {
415             throw new OpenEditException("Did not authenticate: " + username);
416         }
417         else
418         {
419             inReq.setUser(admin);
420         }
421         String JavaDoc id = (String JavaDoc)properties.get("savedas");
422         if ( id != null && id.length() > 0)
423         {
424             String JavaDoc path = "/WEB-INF/versions/" +id;
425             Page page = command.saveFile(properties,path,inReq);
426             if ( page.exists() && page.getContentItem().getLength() > 5000)
427             {
428                 //TODO: Make sure we can unzip it
429
//backup
430
//backUpDirectory(inReq); //Restore now keeps old copies in the WEB-INF/trash directory
431
inReq.setRequestParameter("versionid",id);
432                 restoreVersion(inReq);
433             }
434             else
435             {
436                 log.error("Page did not save " + path);
437             }
438         }
439         else
440         {
441             log.error("No ID found");
442         }
443     }
444     
445 }
Popular Tags