KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > dotmarketing > servlets > ImportExportXMLServlet


1 package com.dotmarketing.servlets;
2
3 import java.io.BufferedInputStream JavaDoc;
4 import java.io.BufferedOutputStream JavaDoc;
5 import java.io.File JavaDoc;
6 import java.io.FileInputStream JavaDoc;
7 import java.io.FileNotFoundException JavaDoc;
8 import java.io.FileOutputStream JavaDoc;
9 import java.io.FilenameFilter JavaDoc;
10 import java.io.IOException JavaDoc;
11 import java.io.InputStream JavaDoc;
12 import java.io.OutputStream JavaDoc;
13 import java.io.PrintWriter JavaDoc;
14 import java.lang.reflect.InvocationTargetException JavaDoc;
15 import java.util.ArrayList JavaDoc;
16 import java.util.Date JavaDoc;
17 import java.util.HashSet JavaDoc;
18 import java.util.Iterator JavaDoc;
19 import java.util.List JavaDoc;
20 import java.util.Map JavaDoc;
21 import java.util.Set JavaDoc;
22 import java.util.zip.ZipEntry JavaDoc;
23 import java.util.zip.ZipInputStream JavaDoc;
24 import java.util.zip.ZipOutputStream JavaDoc;
25
26 import javax.servlet.ServletConfig JavaDoc;
27 import javax.servlet.ServletException JavaDoc;
28 import javax.servlet.http.HttpServlet JavaDoc;
29 import javax.servlet.http.HttpServletRequest JavaDoc;
30 import javax.servlet.http.HttpServletResponse JavaDoc;
31 import javax.servlet.http.HttpSession JavaDoc;
32
33 import org.apache.commons.beanutils.BeanUtils;
34
35 import net.sf.hibernate.HibernateException;
36 import net.sf.hibernate.metadata.ClassMetadata;
37
38 import com.dotmarketing.beans.Clickstream;
39 import com.dotmarketing.beans.ClickstreamRequest;
40 import com.dotmarketing.beans.Inode;
41 import com.dotmarketing.cms.factories.PublicCompanyFactory;
42 import com.dotmarketing.cms.factories.PublicRoleFactory;
43 import com.dotmarketing.cms.factories.PublicUserFactory;
44 import com.dotmarketing.db.DotHibernate;
45 import com.dotmarketing.portlets.categories.model.Category;
46 import com.dotmarketing.util.Config;
47 import com.dotmarketing.util.UtilMethods;
48 import com.liferay.portal.model.Company;
49 import com.liferay.portal.model.Role;
50 import com.liferay.portal.model.User;
51 import com.oreilly.servlet.MultipartRequest;
52 import com.thoughtworks.xstream.XStream;
53 import com.thoughtworks.xstream.io.xml.DomDriver;
54
55 /**
56  * Description of the Class
57  *
58  * @author Will
59  * @created September 18, 2002
60  */

61
62 public class ImportExportXMLServlet extends HttpServlet JavaDoc {
63     /**
64      * The path where backup files are stored
65      */

66     String JavaDoc backupFilePath = "../backup";
67
68     /**
69      * The path where tmp files are stored. This gets wiped alot
70      */

71     String JavaDoc backupTempFilePath = "../backup/temp";
72
73     public void init(ServletConfig JavaDoc config) throws ServletException JavaDoc {
74         // Create backup and temp directory
75
File JavaDoc f = new File JavaDoc(Config.CONTEXT.getRealPath(backupFilePath));
76         f.mkdirs();
77         f = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath));
78         f.mkdirs();
79         deleteTempFiles();
80     }
81
82     /**
83      * The main Servlet method takes the URL parameter called "action"
84      */

85     public void service(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
86
87         String JavaDoc action = request.getParameter("action");
88         HttpSession JavaDoc session = request.getSession();
89         if (!session.isNew()) {
90             if ("upload".equals(action)) {
91
92                 doUpload(request, response);
93                 return;
94             }
95
96             /*
97              * Creates a zip in the backup folder
98              */

99             if ("createZip".equals(action)) {
100                 response.getWriter().println("Creating XML Files");
101                 createXMLFiles();
102                 String JavaDoc x = UtilMethods.dateToJDBC(new Date JavaDoc()).replace(':', '-').replace(' ', '_');
103                 File JavaDoc zipFile = new File JavaDoc(Config.CONTEXT.getRealPath(backupFilePath + "/backup_" + x + "_.zip"));
104                 response.getWriter().println("Zipping up to file:" + zipFile.getAbsolutePath());
105                 BufferedOutputStream JavaDoc bout = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(zipFile));
106
107                 zipTempDirectoryToStream(bout);
108                 response.getWriter().println("Done.");
109                 return;
110             }
111
112             /*
113              * Wipes out the dotCMS db
114              */

115             if ("wipeOutDotCMSDatabase".equals(action)) {
116                 response.getWriter().println("Deleting everything");
117
118             }
119
120             /*
121              * Creates and downloads a zip folder
122              */

123             if ("downloadZip".equals(action)) {
124
125                 String JavaDoc x = UtilMethods.dateToJDBC(new Date JavaDoc()).replace(':', '-').replace(' ', '_');
126                 File JavaDoc zipFile = new File JavaDoc(Config.CONTEXT.getRealPath(backupFilePath + "/backup_" + x + "_.zip"));
127
128                 response.setHeader("Content-type", "");
129                 response.setHeader("Content-Disposition", "attachment; filename=" + zipFile.getName());
130
131                 createXMLFiles();
132
133                 zipTempDirectoryToStream(response.getOutputStream());
134                 return;
135             }
136
137         }
138
139         response.setContentType("text/html");
140         PrintWriter JavaDoc out = response.getWriter();
141         out.println("<html>");
142         out.println("<head>");
143         out.println("<title>");
144         out.println("Import/Export dotCMS Content");
145         out.println("</title>");
146         out.println("<style type=\"text/css\">");
147         out.println("@import \"/css/global.css\";");
148         out.println("</style>");
149         out.println("</head>");
150         out.println("<body>");
151         out.println("<h1>Import/Export dotCMS Content</h1><hr size='1'>");
152         out.println("<ul>");
153         out.println("<li>");
154         out.println("<a HREF='?action=createZip'>Backup to Zip File</a>");
155         out.println("</li>");
156         out.println("<li>");
157         out.println("<a HREF='?action=wipeOutDotCMSDatabase'>Delete the dotCMS database</a>");
158         out.println("</li>");
159         out.println("<li>");
160         out.println("<a HREF='?action=downloadZip'>Download Zip File</a>");
161         out.println("</li>");
162         out.println("</ul>");
163         out.println("<form method='post' action='?action=upload' enctype='multipart/form-data'>");
164         out.println("<table cellpadding='4'><tr><td style='font-size:12px;'>file to import:</td><td><input type='file' name='fileUpload'></td></tr>");
165         out.println("<tr><td></td><td>");
166         out.println("<input type='submit' class=\"core-button\" value='upload xml or zip file'></td></tr></table></form>");
167         out.println("</body>");
168         out.println("</html>");
169     }
170
171     /**
172      * Handles the file upload for the Servlet. It will send files to be
173      * unzipped if nessary
174      *
175      * @param request
176      * @param response
177      * @throws IOException
178      */

179     private void doUpload(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws IOException JavaDoc {
180         deleteTempFiles();
181         String JavaDoc tempdir = Config.CONTEXT.getRealPath(backupTempFilePath);
182
183         MultipartRequest mpr;
184         try {
185             mpr = new MultipartRequest(request, tempdir, 1000000000);
186             File JavaDoc importFile = mpr.getFile("fileUpload");
187
188             /*
189              * Unzip zipped backups
190              */

191             if (importFile != null && importFile.getName().toLowerCase().endsWith(".zip")) {
192
193                 InputStream JavaDoc in = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(importFile));
194                 ZipInputStream JavaDoc zin = new ZipInputStream JavaDoc(in);
195                 ZipEntry JavaDoc e;
196
197                 while ((e = zin.getNextEntry()) != null) {
198                     unzip(zin, e.getName());
199                 }
200                 zin.close();
201                 importFile.delete();
202             }
203
204         } catch (IOException JavaDoc e) {
205             // TODO Auto-generated catch block
206
e.printStackTrace();
207         }
208         File JavaDoc f = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath));
209         String JavaDoc[] _tempFiles = f.list(new XMLFileNameFilter());
210         PrintWriter JavaDoc out = response.getWriter();
211         out.println("<pre>Found " + _tempFiles.length + " files to import");
212         for (int i = 0; i < _tempFiles.length; i++) {
213             File JavaDoc _importFile = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath + "/" + _tempFiles[i]));
214             System.gc();
215             doXMLFileImport(_importFile, out);
216             out.flush();
217         }
218         out.println("Done Importing");
219         
220     }
221
222     /**
223      * This method takes an xml file and will try to import it via XStream and
224      * Hibernate
225      *
226      * @param f
227      * File to be parsed and imported
228      * @param out
229      * Printwriter to write responses to Reponse Printwriter so this
230      * method can write to screen.
231      */

232
233     private void doXMLFileImport(File JavaDoc f, PrintWriter JavaDoc out) {
234         BufferedInputStream JavaDoc _bin = null;
235         try {
236             XStream _xstream = null;
237             String JavaDoc _className = null;
238             Class JavaDoc _importClass = null;
239             DotHibernate _dh = null;
240
241             _className = f.getName().substring(0, f.getName().lastIndexOf("."));
242             _xstream = new XStream(new DomDriver());
243             _importClass = Class.forName(_className);
244             out.println("Importing:\t" + _className);
245             if (_importClass.equals(User.class)) {
246
247             } else if (_importClass.equals(Company.class)) {
248
249             } else if (_importClass.equals(Role.class)) {
250
251             } else {
252
253                 _dh = new DotHibernate(_importClass);
254                 _bin = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(f));
255                 List JavaDoc l = (List JavaDoc) _xstream.fromXML(_bin);
256                 out.println("Found :\t" + l.size() + " " + _className + "(s)");
257                 String JavaDoc id = _dh.getSession().getSessionFactory().getClassMetadata(_importClass).getIdentifierPropertyName();
258                 for (int j = 0; j < l.size(); j++) {
259                     Object JavaDoc obj = l.get(j);
260                     if (UtilMethods.isSet(id)) {
261                         String JavaDoc prop = BeanUtils.getProperty(obj, id);
262
263                         try {
264                             Long JavaDoc myId = new Long JavaDoc(Long.parseLong(prop));
265                             _dh.saveWithPrimaryKey(obj, myId);
266                         } catch (Exception JavaDoc e) {
267                             _dh.saveWithPrimaryKey(obj, prop);
268                         }
269
270                     } else {
271                         _dh.save(obj);
272                     }
273                 }
274
275             }
276         } catch (FileNotFoundException JavaDoc e) {
277             // TODO Auto-generated catch block
278
e.printStackTrace();
279         } catch (ClassNotFoundException JavaDoc e1) {
280             e1.printStackTrace();
281         } catch (HibernateException e) {
282             // TODO Auto-generated catch block
283
e.printStackTrace();
284         } catch (IllegalAccessException JavaDoc e) {
285             // TODO Auto-generated catch block
286
e.printStackTrace();
287         } catch (InvocationTargetException JavaDoc e) {
288             // TODO Auto-generated catch block
289
e.printStackTrace();
290         } catch (NoSuchMethodException JavaDoc e) {
291             // TODO Auto-generated catch block
292
e.printStackTrace();
293         } finally {
294             try {
295                 if (_bin != null) {
296                     _bin.close();
297                 }
298             } catch (IOException JavaDoc e) {
299                 // TODO Auto-generated catch block
300
e.printStackTrace();
301             }
302         }
303
304     }
305
306     /**
307      * This method will pull a list of all tables /classed being managed by
308      * hibernate and export them, one class per file to the backupTempFilePath
309      * as valid XML. It uses XStream to write the xml out to the files.
310      *
311      * @throws ServletException
312      * @throws IOException
313      */

314     private void createXMLFiles() throws ServletException JavaDoc, IOException JavaDoc {
315
316         deleteTempFiles();
317
318         Set JavaDoc<Class JavaDoc> _tablesToDump = new HashSet JavaDoc<Class JavaDoc>();
319         try {
320
321             /* get a list of all our tables */
322             Map JavaDoc map = DotHibernate.getSession().getSessionFactory().getAllClassMetadata();
323             Iterator JavaDoc it = map.entrySet().iterator();
324             while (it.hasNext()) {
325                 Map.Entry JavaDoc pairs = (Map.Entry JavaDoc) it.next();
326                 Class JavaDoc x = (Class JavaDoc) pairs.getKey();
327                 if (!x.equals(Inode.class) && !x.equals(Clickstream.class) && !x.equals(ClickstreamRequest.class))
328                     _tablesToDump.add(x);
329
330             }
331             XStream _xstream = null;
332             DotHibernate _dh = null;
333             List JavaDoc _list = null;
334             File JavaDoc _writing = null;
335             BufferedOutputStream JavaDoc _bout = null;
336
337             for (Class JavaDoc clazz : _tablesToDump) {
338                 _xstream = new XStream(new DomDriver());
339
340                 /*
341                  * String _shortClassName =
342                  * clazz.getName().substring(clazz.getName().lastIndexOf("."),clazz.getName().length());
343                  * xstream.alias(_shortClassName, clazz);
344                  */

345
346                 _writing = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath + "/" + clazz.getName() + ".xml"));
347                 _bout = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(_writing));
348                 _dh = new DotHibernate(clazz);
349                 _dh.setQuery("from " + clazz.getName());
350
351                 _list = _dh.list();
352                 System.out.println("writing : " + _list.size() + " records to " + clazz.getName());
353                 _xstream.toXML(_list, _bout);
354
355                 _bout.close();
356                 _list = null;
357                 _dh = null;
358                 _bout = null;
359                 System.gc();
360             }
361
362             /* Run Liferay's Tables */
363             /* Companies */
364             _list = PublicCompanyFactory.getCompanies();
365             _xstream = new XStream(new DomDriver());
366             _writing = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath + "/" + Company.class.getName() + ".xml"));
367             _bout = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(_writing));
368             _xstream.toXML(_list, _bout);
369             _bout.close();
370             _list = null;
371             _bout = null;
372
373             /* Users */
374             _list = PublicUserFactory.getAllUsers();
375             _xstream = new XStream(new DomDriver());
376             _writing = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath + "/" + User.class.getName() + ".xml"));
377             _bout = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(_writing));
378             _xstream.toXML(_list, _bout);
379             _bout.close();
380             _list = null;
381             _bout = null;
382
383             /* Roles */
384             _list = PublicRoleFactory.getAllRoles();
385             _xstream = new XStream(new DomDriver());
386             _writing = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath + "/" + Role.class.getName() + ".xml"));
387             _bout = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(_writing));
388             _xstream.toXML(_list, _bout);
389             _bout.close();
390             _list = null;
391             _bout = null;
392
393             /* Groups */
394
395         } catch (HibernateException e) {
396
397             e.printStackTrace();
398         }
399
400     }
401
402     /**
403      * Will zip up all files in the tmp directory and send the result to the
404      * given OutputStream
405      *
406      * @param out
407      * OutputStream to write the zip files to
408      * @throws IOException
409      */

410     private void zipTempDirectoryToStream(OutputStream JavaDoc out) throws IOException JavaDoc {
411
412         byte b[] = new byte[512];
413         ZipOutputStream JavaDoc zout = new ZipOutputStream JavaDoc(out);
414         File JavaDoc f = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath));
415         String JavaDoc[] s = f.list();
416         for (int i = 0; i < s.length; i++) {
417             InputStream JavaDoc in = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(f = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath + "/" + s[i]))));
418             ZipEntry JavaDoc e = new ZipEntry JavaDoc(s[i].replace(File.separatorChar, '/'));
419             zout.putNextEntry(e);
420             int len = 0;
421             while ((len = in.read(b)) != -1) {
422                 zout.write(b, 0, len);
423             }
424             zout.closeEntry();
425             in.close();
426         }
427         zout.close();
428         out.close();
429     }
430
431     /**
432      * Does what it says - deletes all files from the backupTempFilePath
433      *
434      */

435     private void deleteTempFiles() {
436         File JavaDoc f = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath));
437         String JavaDoc[] _tempFiles = f.list();
438         for (int i = 0; i < _tempFiles.length; i++) {
439             f = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath + "/" + _tempFiles[i]));
440             f.delete();
441         }
442
443     }
444
445     /**
446      * Takes a ZipInputStream and filename and will extract them to the
447      * backupTempFilePath
448      *
449      * @param zin
450      * ZipInputStream
451      * @param s
452      * FileName to be extracted
453      * @throws IOException
454      */

455     private void unzip(ZipInputStream JavaDoc zin, String JavaDoc s) throws IOException JavaDoc {
456         System.out.println("unzipping " + s);
457         File JavaDoc f = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath + "/" + s));
458         BufferedOutputStream JavaDoc out = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(f));
459         byte[] b = new byte[512];
460         int len = 0;
461         while ((len = zin.read(b)) != -1) {
462             out.write(b, 0, len);
463         }
464         out.close();
465     }
466
467     /**
468      * Simple FileNameFilter for XML files
469      *
470      * @author will
471      *
472      */

473     private class XMLFileNameFilter implements FilenameFilter JavaDoc {
474
475         public boolean accept(File JavaDoc f, String JavaDoc s) {
476             if (s.toLowerCase().endsWith(".xml")) {
477                 return true;
478             } else {
479                 return false;
480             }
481         }
482
483     }
484
485     /**
486      * This is not completed should delete all the dotcms data from an install
487      *
488      */

489     private void deleteDotCMS() {
490         try {
491             /* get a list of all our tables */
492             Set JavaDoc<Class JavaDoc> _tablesToDump = new HashSet JavaDoc<Class JavaDoc>();
493             Map JavaDoc map;
494
495             map = DotHibernate.getSession().getSessionFactory().getAllClassMetadata();
496
497             Iterator JavaDoc it = map.entrySet().iterator();
498             while (it.hasNext()) {
499                 Map.Entry JavaDoc pairs = (Map.Entry JavaDoc) it.next();
500                 ClassMetadata cmd = (ClassMetadata) pairs.getValue();
501
502             }
503         } catch (HibernateException e) {
504             // TODO Auto-generated catch block
505
e.printStackTrace();
506         }
507
508     }
509 }
510
Popular Tags