KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > dotmarketing > portlets > cmsmaintenance > action > ViewCmsMaintenanceAction


1 package com.dotmarketing.portlets.cmsmaintenance.action;
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.Date JavaDoc;
16 import java.util.HashSet JavaDoc;
17 import java.util.Iterator JavaDoc;
18 import java.util.List JavaDoc;
19 import java.util.Map JavaDoc;
20 import java.util.Set JavaDoc;
21 import java.util.regex.Matcher JavaDoc;
22 import java.util.regex.Pattern JavaDoc;
23 import java.util.zip.ZipEntry JavaDoc;
24 import java.util.zip.ZipInputStream JavaDoc;
25 import java.util.zip.ZipOutputStream JavaDoc;
26
27 import javax.portlet.ActionRequest;
28 import javax.portlet.ActionResponse;
29 import javax.portlet.PortletConfig;
30 import javax.portlet.RenderRequest;
31 import javax.portlet.RenderResponse;
32 import javax.portlet.WindowState;
33 import javax.servlet.ServletException JavaDoc;
34 import javax.servlet.http.HttpServletRequest JavaDoc;
35 import javax.servlet.http.HttpServletResponse JavaDoc;
36 import javax.servlet.jsp.PageContext JavaDoc;
37
38 import net.sf.hibernate.HibernateException;
39 import net.sf.hibernate.metadata.ClassMetadata;
40
41 import org.apache.commons.beanutils.BeanUtils;
42 import org.apache.struts.action.ActionForm;
43 import org.apache.struts.action.ActionForward;
44 import org.apache.struts.action.ActionMapping;
45
46 import com.dotmarketing.beans.Clickstream;
47 import com.dotmarketing.beans.ClickstreamRequest;
48 import com.dotmarketing.beans.Inode;
49 import com.dotmarketing.cache.BannerCache;
50 import com.dotmarketing.cache.HostCache;
51 import com.dotmarketing.cache.IdentifierCache;
52 import com.dotmarketing.cache.LiveCache;
53 import com.dotmarketing.cache.PageNotFoundCache;
54 import com.dotmarketing.cache.PermissionCache;
55 import com.dotmarketing.cache.VirtualLinksCache;
56 import com.dotmarketing.cache.WorkingCache;
57 import com.dotmarketing.cms.factories.PublicCompanyFactory;
58 import com.dotmarketing.cms.factories.PublicRoleFactory;
59 import com.dotmarketing.cms.factories.PublicUserFactory;
60 import com.dotmarketing.db.DotHibernate;
61 import com.dotmarketing.factories.InodeFactory;
62 import com.dotmarketing.portal.struts.DotPortletAction;
63 import com.dotmarketing.portlets.cmsmaintenance.struts.CmsMaintenanceForm;
64 import com.dotmarketing.portlets.containers.factories.ContainerFactory;
65 import com.dotmarketing.portlets.containers.model.Container;
66 import com.dotmarketing.portlets.contentlet.factories.ContentletFactory;
67 import com.dotmarketing.portlets.contentlet.model.Contentlet;
68 import com.dotmarketing.portlets.htmlpages.factories.HTMLPageFactory;
69 import com.dotmarketing.portlets.htmlpages.model.HTMLPage;
70 import com.dotmarketing.portlets.links.factories.LinkFactory;
71 import com.dotmarketing.portlets.links.model.Link;
72 import com.dotmarketing.portlets.templates.factories.TemplateFactory;
73 import com.dotmarketing.portlets.templates.model.Template;
74 import com.dotmarketing.util.Config;
75 import com.dotmarketing.util.Logger;
76 import com.dotmarketing.util.LuceneUtils;
77 import com.dotmarketing.util.UtilMethods;
78 import com.dotmarketing.util.WebKeys;
79 import com.liferay.portal.model.Company;
80 import com.liferay.portal.model.Role;
81 import com.liferay.portal.model.User;
82 import com.liferay.portlet.ActionRequestImpl;
83 import com.liferay.portlet.ActionResponseImpl;
84 import com.liferay.util.servlet.SessionMessages;
85 import com.oreilly.servlet.MultipartRequest;
86 import com.thoughtworks.xstream.XStream;
87 import com.thoughtworks.xstream.io.xml.DomDriver;
88 ;
89
90 /**
91  * This class group all the CMS Maintenance Task
92  * (Cache controll, search and replace, import/export content )
93  *
94  * @author Oswaldo
95  *
96  */

97 public class ViewCmsMaintenanceAction extends DotPortletAction {
98     
99     
100     /**
101      * The path where backup files are stored
102      */

103     String JavaDoc backupFilePath = "../backup";
104     
105     /**
106      * The path where tmp files are stored. This gets wiped alot
107      */

108     String JavaDoc backupTempFilePath = "../backup/temp";
109     
110     
111     public ActionForward render(
112             ActionMapping mapping, ActionForm form, PortletConfig config,
113             RenderRequest req, RenderResponse res)
114     throws Exception JavaDoc {
115         
116         Logger.debug(this, "Running ViewCmsMaintenanceAction!!!! = " + req.getWindowState());
117         
118         try {
119             //gets the user
120
_initCacheValues(req);
121             
122             if (req.getWindowState().equals(WindowState.MAXIMIZED)) {
123                 Logger.debug(this, "Showing view action cms maintenance maximized");
124                 return mapping.findForward("portlet.ext.cmsmaintenance.view_cms_maintenance");
125             } else {
126                 Logger.debug(this, "Showing view action cms maintenance minimized");
127                 return mapping.findForward("portlet.ext.cmsmaintenance.view");
128             }
129         }
130         catch (Exception JavaDoc e) {
131             req.setAttribute(PageContext.EXCEPTION, e);
132             return mapping.findForward(com.liferay.portal.util.Constants.COMMON_ERROR);
133         }
134     }
135     
136     public void processAction(
137             ActionMapping mapping, ActionForm form, PortletConfig config,
138             ActionRequest req, ActionResponse res)
139     throws Exception JavaDoc
140     {
141         String JavaDoc message = "";
142         CmsMaintenanceForm ccf = (CmsMaintenanceForm) form;
143         String JavaDoc cmd = req.getParameter("cmd");
144         
145         //Manage all the cache Task
146
if(cmd.equals("cache")){
147             
148             String JavaDoc cacheName = ccf.getCacheName();
149             if (cacheName.equals(com.dotmarketing.util.WebKeys.Cache.CACHE_OPTIMIZE_INDEX)) {
150                 LuceneUtils.optimizeCurrentIndex();
151                 message = "message.cmsmaintenance.cache.indexoptimized";
152             } else if (cacheName.equals(com.dotmarketing.util.WebKeys.Cache.CACHE_CONTENTS_INDEX)) {
153                 if (ContentletFactory.reIndexAllContentlets())
154                     message = "message.cmsmaintenance.cache.indexrebuilt";
155                 else
156                     message = "message.cmsmaintenance.cache.failedtorebuild";
157             } else if (!(cacheName.equals(com.dotmarketing.util.WebKeys.Cache.CACHE_WORKING_FILES) || cacheName.equals(com.dotmarketing.util.WebKeys.Cache.CACHE_LIVE_FILES)))
158             {
159                 _flush(com.dotmarketing.util.WebKeys.Cache.CACHE_WORKING_FILES);
160                 message = (cacheName.equals(WebKeys.Cache.CACHE_ALL_CACHES) ? "message.cmsmaintenance.cache.flushallcache" : "message.cmsmaintenance.cache.flushcache");
161             } else {
162                 _deleteFiles(com.dotmarketing.util.WebKeys.Cache.CACHE_LIVE_FILES);
163                 _deleteFiles(com.dotmarketing.util.WebKeys.Cache.CACHE_WORKING_FILES);
164                 
165                 message = "message.cmsmaintenance.cache.deletefiles";
166             }
167         } //Manage all the search and replace Task
168
else if(cmd.equals("searchandreplace")){
169             
170             message = "Search and Replace complete <br>" + searchAndReplace(ccf);
171             
172             _deleteFiles(com.dotmarketing.util.WebKeys.Cache.CACHE_LIVE_FILES);
173             _deleteFiles(com.dotmarketing.util.WebKeys.Cache.CACHE_WORKING_FILES);
174             _flush(com.dotmarketing.util.WebKeys.Cache.CACHE_ALL_CACHES);
175             
176         }//Manage all the import/ export Task
177
else {
178             
179             File JavaDoc f = new File JavaDoc(Config.CONTEXT.getRealPath(backupFilePath));
180             f.mkdirs();
181             f = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath));
182             f.mkdirs();
183             deleteTempFiles();
184             
185             if(cmd.equals("createZip")) {
186                 
187                 message = "Creating XML Files. ";
188                 createXMLFiles();
189                 String JavaDoc x = UtilMethods.dateToJDBC(new Date JavaDoc()).replace(':', '-').replace(' ', '_');
190                 File JavaDoc zipFile = new File JavaDoc(Config.CONTEXT.getRealPath(backupFilePath + "/backup_" + x + "_.zip"));
191                 message +="Zipping up to file:" + zipFile.getAbsolutePath();
192                 BufferedOutputStream JavaDoc bout = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(zipFile));
193                 
194                 zipTempDirectoryToStream(bout);
195                 message +=". Done.";
196                 
197             }else if(cmd.equals("wipeOutDotCMSDatabase")) {
198                 
199                 message = "Deleted dotCMS Database";
200                 deleteDotCMS();
201                 
202             }else if(cmd.equals("downloadZip")) {
203                 
204                 message ="File Downloaded";
205                 String JavaDoc x = UtilMethods.dateToJDBC(new Date JavaDoc()).replace(':', '-').replace(' ', '_');
206                 File JavaDoc zipFile = new File JavaDoc(Config.CONTEXT.getRealPath(backupFilePath + "/backup_" + x + "_.zip"));
207                 
208                 ActionResponseImpl responseImpl = (ActionResponseImpl) res;
209                 HttpServletResponse JavaDoc httpResponse = responseImpl.getHttpServletResponse();
210                 httpResponse.setHeader("Content-type", "");
211                 httpResponse.setHeader("Content-Disposition", "attachment; filename=" + zipFile.getName());
212                 
213                 createXMLFiles();
214                 
215                 zipTempDirectoryToStream(httpResponse.getOutputStream());
216                 
217             }else if(cmd.equals("upload")) {
218                 ActionResponseImpl responseImpl = (ActionResponseImpl) res;
219                 HttpServletResponse JavaDoc httpResponse = responseImpl.getHttpServletResponse();
220
221                 ActionRequestImpl requestImpl = (ActionRequestImpl) req;
222                 HttpServletRequest JavaDoc httpRequest = requestImpl.getHttpServletRequest();
223                 
224                 message ="file upload Done.";
225                 doUpload(httpRequest, httpResponse);
226             }
227         }
228         
229         SessionMessages.add(req, "message",message);
230         String JavaDoc referer = req.getParameter("referer");
231         setForward(req,referer);
232     }
233     
234     
235     private void _flush(String JavaDoc cacheName)
236     throws Exception JavaDoc
237     {
238         if (cacheName.equals(BannerCache.class.getName()))
239         {
240             //Flush the cache
241
BannerCache.clearCache();
242         }
243         else if (cacheName.equals(HostCache.class.getName()))
244         {
245             //Flush the cache
246
HostCache.clearCache();
247         }
248         else if (cacheName.equals(IdentifierCache.class.getName()))
249         {
250             //Flush the cache
251
IdentifierCache.clearCache();
252         }
253         else if (cacheName.equals(LiveCache.class.getName()))
254         {
255             //Flush the cache
256
LiveCache.clearCache();
257         }
258         else if (cacheName.equals(PageNotFoundCache.class.getName()))
259         {
260             //Flush the cache
261
PageNotFoundCache.clearCache();
262         }
263         else if (cacheName.equals(PermissionCache.class.getName()))
264         {
265             //Flush the cache
266
PermissionCache.clearCache();
267         }
268         else if (cacheName.equals(VirtualLinksCache.class.getName()))
269         {
270             //Flush the cache
271
VirtualLinksCache.clearCache();
272         }
273         else if (cacheName.equals(WorkingCache.class.getName()))
274         {
275             //Flush the cache
276
WorkingCache.clearCache();
277         }
278         else if (cacheName.equals(WebKeys.Cache.CACHE_ALL_CACHES))
279         {
280             //Flush all caches
281
BannerCache.clearCache();
282             HostCache.clearCache();
283             IdentifierCache.clearCache();
284             LiveCache.clearCache();
285             PageNotFoundCache.clearCache();
286             PermissionCache.clearCache();
287             WorkingCache.clearCache();
288             
289             //This clear should be at last
290
VirtualLinksCache.clearCache();
291         }
292     }
293     
294     private void _deleteFiles(String JavaDoc cacheName)
295     throws Exception JavaDoc
296     {
297         try
298         {
299             String JavaDoc realPath = "";
300             
301             String JavaDoc velocityRootPath = Config.getStringProperty("VELOCITY_ROOT");
302             if (velocityRootPath.startsWith("/WEB-INF")) {
303                 velocityRootPath = Config.CONTEXT.getRealPath(velocityRootPath);
304             }
305             
306             if (cacheName.equals(com.dotmarketing.util.WebKeys.Cache.CACHE_LIVE_FILES))
307             {
308                 realPath = velocityRootPath + File.separator + "live";
309             }
310             else
311             {
312                 realPath = velocityRootPath + File.separator + "working";
313             }
314             File JavaDoc file = new File JavaDoc(realPath);
315             if (file.isDirectory())
316             {
317                 _deleteRoot(file);
318                 Logger.debug(ViewCmsMaintenanceAction.class,"The directory " + realPath + " has been deleted");
319             }
320         }
321         catch(Exception JavaDoc ex)
322         {
323             Logger.error(ViewCmsMaintenanceAction.class,ex.toString());
324             throw ex;
325         }
326     }
327     
328     private boolean _deleteRoot(File JavaDoc root) throws Exception JavaDoc
329     {
330         boolean returnValue = true;
331         File JavaDoc[] childs = root.listFiles();
332         for(int i = 0; i < childs.length; i++)
333         {
334             File JavaDoc child = childs[i];
335             if (child.isFile())
336             {
337                 returnValue = returnValue && child.delete();
338             }
339             if (child.isDirectory())
340             {
341                 returnValue = returnValue && _deleteRoot(child);
342             }
343         }
344         return returnValue;
345     }
346     
347     private int _numberRoot(File JavaDoc root) throws Exception JavaDoc
348     {
349         int returnValue = 0;
350         File JavaDoc[] childs = root.listFiles();
351         for(int i = 0; i < childs.length; i++)
352         {
353             File JavaDoc child = childs[i];
354             if (child.isFile())
355             {
356                 returnValue++;
357             }
358             if (child.isDirectory())
359             {
360                 returnValue += _numberRoot(child);
361             }
362         }
363         return returnValue;
364     }
365     
366     /**
367      * Initialice cache values
368      * @param req
369      */

370     private void _initCacheValues(RenderRequest req)
371     {
372         int liveCount = 0;
373         int workingCount = 0;
374         try
375         {
376             String JavaDoc velocityRootPath = Config.getStringProperty("VELOCITY_ROOT");
377             if (velocityRootPath.startsWith("/WEB-INF")) {
378                 velocityRootPath = Config.CONTEXT.getRealPath(velocityRootPath);
379             }
380             String JavaDoc livePath = velocityRootPath + File.separator + "live";
381             String JavaDoc workingPath = velocityRootPath + File.separator + "working";
382             
383             //Count the Live Files
384
File JavaDoc file = new File JavaDoc(livePath);
385             liveCount = _numberRoot(file);
386             
387             //Count the working files
388
file = new File JavaDoc(workingPath);
389             workingCount = _numberRoot(file);
390         }
391         catch(Exception JavaDoc ex)
392         {
393             Logger.error(ViewCmsMaintenanceAction.class,"Error calculating the number of files");
394         }
395         finally
396         {
397             req.setAttribute(WebKeys.Cache.CACHE_NUMBER_LIVE_FILES,new Integer JavaDoc(liveCount));
398             req.setAttribute(WebKeys.Cache.CACHE_NUMBER_WORKING_FILES,new Integer JavaDoc(workingCount));
399         }
400     }
401     
402     
403     private String JavaDoc searchAndReplace(CmsMaintenanceForm form){
404         String JavaDoc message="";
405         boolean isAdmin = false;
406         
407         if (UtilMethods.isSet(form.getUserId())) {
408             List JavaDoc<Role> roles = com.dotmarketing.factories.RoleFactory.getAllRolesForUser(form.getUserId());
409             for (Role role : roles) {
410                 if (role.getName().equals(Config.getStringProperty("ADMINISTRATOR_ROLE"))) {
411                     isAdmin = true;
412                     break;
413                 }
414             }
415         }
416         
417         if (isAdmin) {
418             
419             String JavaDoc searchString = form.getSearchString();
420             String JavaDoc replaceString = form.getReplaceString();
421             if (UtilMethods.isSet(searchString) && UtilMethods.isSet(replaceString)) {
422                 DotHibernate db = new DotHibernate(Contentlet.class);
423                 db.startTransaction();
424                 
425                 try{
426                     
427 // Contentlets
428
String JavaDoc originalPatter = searchString;
429                     String JavaDoc newPatter = replaceString;
430                     Pattern JavaDoc patter = Pattern.compile(originalPatter);
431                     Matcher JavaDoc matcher = patter.matcher("");
432                     int cicleValue = 1000;
433                     int offSet = 0;
434                     int contentletsCounter = 0;
435                     
436                     //Construct the query
437
StringBuffer JavaDoc sqlQuery = new StringBuffer JavaDoc();
438                     sqlQuery.append("SELECT {contentlet.*} FROM contentlet, inode contentlet_1_ ");
439                     sqlQuery.append("WHERE contentlet.inode = contentlet_1_.inode");
440                     sqlQuery.append(" ORDER BY contentlet.inode ASC");
441                     
442                     //Set the pagination parameters
443
String JavaDoc query = sqlQuery.toString();
444                     db.setSQLQuery(query);
445                     db.setFirstResult(offSet);
446                     db.setMaxResults(cicleValue);
447                     
448                     //Execute the query
449

450                     List JavaDoc<Contentlet> contentlets = db.list();
451                     int size = contentlets.size();
452                     while(size > 0)
453                     {
454                         for(int i = 0;i < size;i++)
455                         {
456                             Contentlet contentlet = contentlets.get(i);
457                             //text 1
458
if (UtilMethods.isSet(contentlet.getText1()))
459                             {
460                                 matcher.reset(contentlet.getText1());
461                                 contentlet.setText1(matcher.replaceAll(newPatter));
462                             }
463                             //text 2
464
if (UtilMethods.isSet(contentlet.getText2()))
465                             {
466                                 matcher.reset(contentlet.getText2());
467                                 contentlet.setText2(matcher.replaceAll(newPatter));
468                             }
469                             //text 3
470
if (UtilMethods.isSet(contentlet.getText3()))
471                             {
472                                 matcher.reset(contentlet.getText3());
473                                 contentlet.setText3(matcher.replaceAll(newPatter));
474                             }
475                             //text 4
476
if (UtilMethods.isSet(contentlet.getText4()))
477                             {
478                                 matcher.reset(contentlet.getText4());
479                                 contentlet.setText4(matcher.replaceAll(newPatter));
480                             }
481                             //text 5
482
if (UtilMethods.isSet(contentlet.getText5()))
483                             {
484                                 matcher.reset(contentlet.getText5());
485                                 contentlet.setText5(matcher.replaceAll(newPatter));
486                             }
487                             //text 6
488
if (UtilMethods.isSet(contentlet.getText6()))
489                             {
490                                 matcher.reset(contentlet.getText6());
491                                 contentlet.setText6(matcher.replaceAll(newPatter));
492                             }
493                             //text 7
494
if (UtilMethods.isSet(contentlet.getText7()))
495                             {
496                                 matcher.reset(contentlet.getText7());
497                                 contentlet.setText7(matcher.replaceAll(newPatter));
498                             }
499                             //text 8
500
if (UtilMethods.isSet(contentlet.getText8()))
501                             {
502                                 matcher.reset(contentlet.getText8());
503                                 contentlet.setText8(matcher.replaceAll(newPatter));
504                             }
505                             //text 9
506
if (UtilMethods.isSet(contentlet.getText9()))
507                             {
508                                 matcher.reset(contentlet.getText9());
509                                 contentlet.setText9(matcher.replaceAll(newPatter));
510                             }
511                             //text 10
512
if (UtilMethods.isSet(contentlet.getText10()))
513                             {
514                                 matcher.reset(contentlet.getText10());
515                                 contentlet.setText10(matcher.replaceAll(newPatter));
516                             }
517                             //text 11
518
if (UtilMethods.isSet(contentlet.getText11()))
519                             {
520                                 matcher.reset(contentlet.getText11());
521                                 contentlet.setText11(matcher.replaceAll(newPatter));
522                             }
523                             //text 12
524
if (UtilMethods.isSet(contentlet.getText12()))
525                             {
526                                 matcher.reset(contentlet.getText12());
527                                 contentlet.setText12(matcher.replaceAll(newPatter));
528                             }
529                             //text 13
530
if (UtilMethods.isSet(contentlet.getText13()))
531                             {
532                                 matcher.reset(contentlet.getText13());
533                                 contentlet.setText13(matcher.replaceAll(newPatter));
534                             }
535                             //text 14
536
if (UtilMethods.isSet(contentlet.getText14()))
537                             {
538                                 matcher.reset(contentlet.getText14());
539                                 contentlet.setText14(matcher.replaceAll(newPatter));
540                             }
541                             //text 15
542
if (UtilMethods.isSet(contentlet.getText15()))
543                             {
544                                 matcher.reset(contentlet.getText15());
545                                 contentlet.setText15(matcher.replaceAll(newPatter));
546                             }
547                             //text 16
548
if (UtilMethods.isSet(contentlet.getText16()))
549                             {
550                                 matcher.reset(contentlet.getText16());
551                                 contentlet.setText16(matcher.replaceAll(newPatter));
552                             }
553                             //text 17
554
if (UtilMethods.isSet(contentlet.getText17()))
555                             {
556                                 matcher.reset(contentlet.getText17());
557                                 contentlet.setText17(matcher.replaceAll(newPatter));
558                             }
559                             //text 18
560
if (UtilMethods.isSet(contentlet.getText18()))
561                             {
562                                 matcher.reset(contentlet.getText18());
563                                 contentlet.setText18(matcher.replaceAll(newPatter));
564                             }
565                             //text 19
566
if (UtilMethods.isSet(contentlet.getText19()))
567                             {
568                                 matcher.reset(contentlet.getText19());
569                                 contentlet.setText19(matcher.replaceAll(newPatter));
570                             }
571                             //text 20
572
if (UtilMethods.isSet(contentlet.getText20()))
573                             {
574                                 matcher.reset(contentlet.getText20());
575                                 contentlet.setText20(matcher.replaceAll(newPatter));
576                             }
577                             //text 21
578
if (UtilMethods.isSet(contentlet.getText21()))
579                             {
580                                 matcher.reset(contentlet.getText21());
581                                 contentlet.setText21(matcher.replaceAll(newPatter));
582                             }
583                             //text 22
584
if (UtilMethods.isSet(contentlet.getText22()))
585                             {
586                                 matcher.reset(contentlet.getText22());
587                                 contentlet.setText22(matcher.replaceAll(newPatter));
588                             }
589                             //text 23
590
if (UtilMethods.isSet(contentlet.getText23()))
591                             {
592                                 matcher.reset(contentlet.getText23());
593                                 contentlet.setText23(matcher.replaceAll(newPatter));
594                             }
595                             //text24
596
if (UtilMethods.isSet(contentlet.getText24()))
597                             {
598                                 matcher.reset(contentlet.getText24());
599                                 contentlet.setText24(matcher.replaceAll(newPatter));
600                             }
601                             //text 25
602
if (UtilMethods.isSet(contentlet.getText25()))
603                             {
604                                 matcher.reset(contentlet.getText25());
605                                 contentlet.setText25(matcher.replaceAll(newPatter));
606                             }
607                             //Text Area 1
608
if (UtilMethods.isSet(contentlet.getText_area1()))
609                             {
610                                 matcher.reset(contentlet.getText_area1());
611                                 contentlet.setText_area1(matcher.replaceAll(newPatter));
612                             }
613                             //Text Area 2
614
if (UtilMethods.isSet(contentlet.getText_area2()))
615                             {
616                                 matcher.reset(contentlet.getText_area2());
617                                 contentlet.setText_area2(matcher.replaceAll(newPatter));
618                             }
619                             //Text Area 3
620
if (UtilMethods.isSet(contentlet.getText_area3()))
621                             {
622                                 matcher.reset(contentlet.getText_area3());
623                                 contentlet.setText_area3(matcher.replaceAll(newPatter));
624                             }
625                             //Text Area 4
626
if (UtilMethods.isSet(contentlet.getText_area4()))
627                             {
628                                 matcher.reset(contentlet.getText_area4());
629                                 contentlet.setText_area4(matcher.replaceAll(newPatter));
630                             }
631                             //Text Area 5
632
if (UtilMethods.isSet(contentlet.getText_area5()))
633                             {
634                                 matcher.reset(contentlet.getText_area5());
635                                 contentlet.setText_area5(matcher.replaceAll(newPatter));
636                             }
637                             //Text Area 6
638
if (UtilMethods.isSet(contentlet.getText_area6()))
639                             {
640                                 matcher.reset(contentlet.getText_area6());
641                                 contentlet.setText_area6(matcher.replaceAll(newPatter));
642                             }
643                             //Text Area 7
644
if (UtilMethods.isSet(contentlet.getText_area7()))
645                             {
646                                 matcher.reset(contentlet.getText_area7());
647                                 contentlet.setText_area7(matcher.replaceAll(newPatter));
648                             }
649                             //Text Area 8
650
if (UtilMethods.isSet(contentlet.getText_area8()))
651                             {
652                                 matcher.reset(contentlet.getText_area8());
653                                 contentlet.setText_area8(matcher.replaceAll(newPatter));
654                             }
655                             //Text Area 9
656
if (UtilMethods.isSet(contentlet.getText_area9()))
657                             {
658                                 matcher.reset(contentlet.getText_area9());
659                                 contentlet.setText_area9(matcher.replaceAll(newPatter));
660                             }
661                             //Text Area 10
662
if (UtilMethods.isSet(contentlet.getText_area10()))
663                             {
664                                 matcher.reset(contentlet.getText_area10());
665                                 contentlet.setText_area10(matcher.replaceAll(newPatter));
666                             }
667                             //Text Area 11
668
if (UtilMethods.isSet(contentlet.getText_area11()))
669                             {
670                                 matcher.reset(contentlet.getText_area11());
671                                 contentlet.setText_area11(matcher.replaceAll(newPatter));
672                             }
673                             //Text Area 12
674
if (UtilMethods.isSet(contentlet.getText_area12()))
675                             {
676                                 matcher.reset(contentlet.getText_area12());
677                                 contentlet.setText_area12(matcher.replaceAll(newPatter));
678                             }
679                             //Text Area 13
680
if (UtilMethods.isSet(contentlet.getText_area13()))
681                             {
682                                 matcher.reset(contentlet.getText_area13());
683                                 contentlet.setText_area13(matcher.replaceAll(newPatter));
684                             }
685                             //Text Area 14
686
if (UtilMethods.isSet(contentlet.getText_area14()))
687                             {
688                                 matcher.reset(contentlet.getText_area14());
689                                 contentlet.setText_area14(matcher.replaceAll(newPatter));
690                             }
691                             //Text Area 15
692
if (UtilMethods.isSet(contentlet.getText_area15()))
693                             {
694                                 matcher.reset(contentlet.getText_area15());
695                                 contentlet.setText_area15(matcher.replaceAll(newPatter));
696                             }
697                             //Text Area 16
698
if (UtilMethods.isSet(contentlet.getText_area16()))
699                             {
700                                 matcher.reset(contentlet.getText_area16());
701                                 contentlet.setText_area16(matcher.replaceAll(newPatter));
702                             }
703                             //Text Area 17
704
if (UtilMethods.isSet(contentlet.getText_area17()))
705                             {
706                                 matcher.reset(contentlet.getText_area17());
707                                 contentlet.setText_area17(matcher.replaceAll(newPatter));
708                             }
709                             //Text Area 18
710
if (UtilMethods.isSet(contentlet.getText_area18()))
711                             {
712                                 matcher.reset(contentlet.getText_area18());
713                                 contentlet.setText_area18(matcher.replaceAll(newPatter));
714                             }
715                             //Text Area 19
716
if (UtilMethods.isSet(contentlet.getText_area19()))
717                             {
718                                 matcher.reset(contentlet.getText_area19());
719                                 contentlet.setText_area19(matcher.replaceAll(newPatter));
720                             }
721                             //Text Area 20
722
if (UtilMethods.isSet(contentlet.getText_area20()))
723                             {
724                                 matcher.reset(contentlet.getText_area20());
725                                 contentlet.setText_area20(matcher.replaceAll(newPatter));
726                             }
727                             //Text Area 21
728
if (UtilMethods.isSet(contentlet.getText_area21()))
729                             {
730                                 matcher.reset(contentlet.getText_area21());
731                                 contentlet.setText_area21(matcher.replaceAll(newPatter));
732                             }
733                             //Text Area 22
734
if (UtilMethods.isSet(contentlet.getText_area22()))
735                             {
736                                 matcher.reset(contentlet.getText_area22());
737                                 contentlet.setText_area22(matcher.replaceAll(newPatter));
738                             }
739                             //Text Area 23
740
if (UtilMethods.isSet(contentlet.getText_area23()))
741                             {
742                                 matcher.reset(contentlet.getText_area23());
743                                 contentlet.setText_area23(matcher.replaceAll(newPatter));
744                             }
745                             //Text Area 24
746
if (UtilMethods.isSet(contentlet.getText_area24()))
747                             {
748                                 matcher.reset(contentlet.getText_area24());
749                                 contentlet.setText_area24(matcher.replaceAll(newPatter));
750                             }
751                             //Text Area 25
752
if (UtilMethods.isSet(contentlet.getText_area25()))
753                             {
754                                 matcher.reset(contentlet.getText_area25());
755                                 contentlet.setText_area25(matcher.replaceAll(newPatter));
756                             }
757                             InodeFactory.saveInode(contentlet);
758                             contentletsCounter++;
759                             
760                         }
761                         offSet += cicleValue;
762                         db.setFirstResult(offSet);
763                         db.setMaxResults(cicleValue);
764                         contentlets = db.list();
765                         size = contentlets.size();
766                     }
767                     
768                     
769                     //Links
770
int linksCounter = 0;
771                     
772                     List JavaDoc links = LinkFactory.getLinkByCondition("url like '%" + searchString + "%'");
773                     Iterator JavaDoc it = links.iterator();
774                     while (it.hasNext()) {
775                         Link link = (Link)it.next();
776                         String JavaDoc url = link.getUrl();
777                         url = url.replaceAll(searchString, replaceString);
778                         link.setUrl(url);
779                         InodeFactory.saveInode(link);
780                         linksCounter++;
781                     }
782                     
783                     //Containers
784
int containersCounter = 0;
785                     List JavaDoc containers = ContainerFactory.getContainerByCondition("(code like '%" + searchString + "%' or pre_loop like '%" + searchString + "%' or post_loop like '%" + searchString + "%')");
786                     it = containers.iterator();
787                     while (it.hasNext()) {
788                         Container container = (Container)it.next();
789                         String JavaDoc code = container.getCode();
790                         code = code.replaceAll(searchString, replaceString);
791                         container.setCode(code);
792                         String JavaDoc preLoop = container.getPreLoop();
793                         preLoop = preLoop.replaceAll(searchString, replaceString);
794                         container.setPreLoop(preLoop);
795                         String JavaDoc postLoop = container.getPostLoop();
796                         postLoop = postLoop.replaceAll(searchString, replaceString);
797                         container.setPostLoop(postLoop);
798                         InodeFactory.saveInode(container);
799                         containersCounter++;
800                     }
801                     
802                     
803                     //Templates
804
int templatesCounter = 0;
805                     
806                     List JavaDoc templates = TemplateFactory.getTemplateByCondition("body like '%" + searchString + "%'");
807                     it = templates.iterator();
808                     while (it.hasNext()) {
809                         Template template = (Template)it.next();
810                         String JavaDoc body = template.getBody();
811                         body = body.replaceAll(searchString, replaceString);
812                         template.setBody(body);
813                         InodeFactory.saveInode(template);
814                         templatesCounter++;
815                     }
816                     
817                     
818                     //HTML Pages
819
int pagesCounter = 0;
820                     List JavaDoc pages = HTMLPageFactory.getHTMLPageByCondition("redirect like '%" + searchString + "%'");
821                     it = pages.iterator();
822                     while (it.hasNext()) {
823                         HTMLPage htmlpage = (HTMLPage)it.next();
824                         String JavaDoc redirect = htmlpage.getRedirect();
825                         redirect = redirect.replaceAll(searchString, replaceString);
826                         htmlpage.setRedirect(redirect);
827                         InodeFactory.saveInode(htmlpage);
828                         pagesCounter++;
829                     }
830                     
831                     db.commitTransaction();
832                     
833                     StringBuffer JavaDoc buf = new StringBuffer JavaDoc("Modifications Summary<br>");
834                     buf.append(contentletsCounter+" Contentlets proccesed!!<br>");
835                     buf.append(linksCounter+" Links modified!!<br>");
836                     buf.append(containersCounter+" Containers modified!!<br>");
837                     buf.append(templatesCounter+" Templates modified!!<br>");
838                     buf.append(pagesCounter+" HTMLPages modified!!<br>");
839                     message=buf.toString();
840                     
841                 }catch(Exception JavaDoc e){
842                     message ="<h1>A error occured running the replace, the transaction was rollbacked!!</h1><br><h2>Exception message: <%=e.getMessage()%></h2>";
843                     db.rollbackTransaction();
844                     e.printStackTrace();
845                 }
846                 
847             }
848         }
849         return message;
850     }
851     
852     /**
853      * This method takes an xml file and will try to import it via XStream and
854      * Hibernate
855      *
856      * @param f
857      * File to be parsed and imported
858      * @param out
859      * Printwriter to write responses to Reponse Printwriter so this
860      * method can write to screen.
861      *
862      * @author Will
863      */

864     
865     private void doXMLFileImport(File JavaDoc f, PrintWriter JavaDoc out) {
866         BufferedInputStream JavaDoc _bin = null;
867         try {
868             XStream _xstream = null;
869             String JavaDoc _className = null;
870             Class JavaDoc _importClass = null;
871             DotHibernate _dh = null;
872             
873             _className = f.getName().substring(0, f.getName().lastIndexOf("."));
874             _xstream = new XStream(new DomDriver());
875             _importClass = Class.forName(_className);
876             out.println("Importing:\t" + _className);
877             if (_importClass.equals(User.class)) {
878                 
879             } else if (_importClass.equals(Company.class)) {
880                 
881             } else if (_importClass.equals(Role.class)) {
882                 
883             } else {
884                 
885                 _dh = new DotHibernate(_importClass);
886                 _bin = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(f));
887                 List JavaDoc l = (List JavaDoc) _xstream.fromXML(_bin);
888                 out.println("Found :\t" + l.size() + " " + _className + "(s)");
889                 String JavaDoc id = _dh.getSession().getSessionFactory().getClassMetadata(_importClass).getIdentifierPropertyName();
890                 for (int j = 0; j < l.size(); j++) {
891                     Object JavaDoc obj = l.get(j);
892                     if (UtilMethods.isSet(id)) {
893                         String JavaDoc prop = BeanUtils.getProperty(obj, id);
894                         
895                         try {
896                             Long JavaDoc myId = new Long JavaDoc(Long.parseLong(prop));
897                             _dh.saveWithPrimaryKey(obj, myId);
898                         } catch (Exception JavaDoc e) {
899                             _dh.saveWithPrimaryKey(obj, prop);
900                         }
901                         
902                     } else {
903                         _dh.save(obj);
904                     }
905                 }
906                 
907             }
908         } catch (FileNotFoundException JavaDoc e) {
909             // TODO Auto-generated catch block
910
e.printStackTrace();
911         } catch (ClassNotFoundException JavaDoc e1) {
912             e1.printStackTrace();
913         } catch (HibernateException e) {
914             // TODO Auto-generated catch block
915
e.printStackTrace();
916         } catch (IllegalAccessException JavaDoc e) {
917             // TODO Auto-generated catch block
918
e.printStackTrace();
919         } catch (InvocationTargetException JavaDoc e) {
920             // TODO Auto-generated catch block
921
e.printStackTrace();
922         } catch (NoSuchMethodException JavaDoc e) {
923             // TODO Auto-generated catch block
924
e.printStackTrace();
925         } finally {
926             try {
927                 if (_bin != null) {
928                     _bin.close();
929                 }
930             } catch (IOException JavaDoc e) {
931                 // TODO Auto-generated catch block
932
e.printStackTrace();
933             }
934         }
935         
936     }
937     
938     /**
939      * This method will pull a list of all tables /classed being managed by
940      * hibernate and export them, one class per file to the backupTempFilePath
941      * as valid XML. It uses XStream to write the xml out to the files.
942      *
943      * @throws ServletException
944      * @throws IOException
945      * @author Will
946      */

947     private void createXMLFiles() throws ServletException JavaDoc, IOException JavaDoc {
948         
949         deleteTempFiles();
950         
951         Set JavaDoc<Class JavaDoc> _tablesToDump = new HashSet JavaDoc<Class JavaDoc>();
952         try {
953             
954             /* get a list of all our tables */
955             Map JavaDoc map = DotHibernate.getSession().getSessionFactory().getAllClassMetadata();
956             Iterator JavaDoc it = map.entrySet().iterator();
957             while (it.hasNext()) {
958                 Map.Entry JavaDoc pairs = (Map.Entry JavaDoc) it.next();
959                 Class JavaDoc x = (Class JavaDoc) pairs.getKey();
960                 if (!x.equals(Inode.class) && !x.equals(Clickstream.class) && !x.equals(ClickstreamRequest.class))
961                     _tablesToDump.add(x);
962                 
963             }
964             XStream _xstream = null;
965             DotHibernate _dh = null;
966             List JavaDoc _list = null;
967             File JavaDoc _writing = null;
968             BufferedOutputStream JavaDoc _bout = null;
969             
970             for (Class JavaDoc clazz : _tablesToDump) {
971                 _xstream = new XStream(new DomDriver());
972                 
973                 /*
974                  * String _shortClassName =
975                  * clazz.getName().substring(clazz.getName().lastIndexOf("."),clazz.getName().length());
976                  * xstream.alias(_shortClassName, clazz);
977                  */

978                 
979                 _writing = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath + "/" + clazz.getName() + ".xml"));
980                 _bout = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(_writing));
981                 _dh = new DotHibernate(clazz);
982                 _dh.setQuery("from " + clazz.getName());
983                 
984                 _list = _dh.list();
985                 System.out.println("writing : " + _list.size() + " records to " + clazz.getName());
986                 _xstream.toXML(_list, _bout);
987                 
988                 _bout.close();
989                 _list = null;
990                 _dh = null;
991                 _bout = null;
992                 System.gc();
993             }
994             
995             /* Run Liferay's Tables */
996             /* Companies */
997             _list = PublicCompanyFactory.getCompanies();
998             _xstream = new XStream(new DomDriver());
999             _writing = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath + "/" + Company.class.getName() + ".xml"));
1000            _bout = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(_writing));
1001            _xstream.toXML(_list, _bout);
1002            _bout.close();
1003            _list = null;
1004            _bout = null;
1005            
1006            /* Users */
1007            _list = PublicUserFactory.getAllUsers();
1008            _xstream = new XStream(new DomDriver());
1009            _writing = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath + "/" + User.class.getName() + ".xml"));
1010            _bout = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(_writing));
1011            _xstream.toXML(_list, _bout);
1012            _bout.close();
1013            _list = null;
1014            _bout = null;
1015            
1016            /* Roles */
1017            _list = PublicRoleFactory.getAllRoles();
1018            _xstream = new XStream(new DomDriver());
1019            _writing = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath + "/" + Role.class.getName() + ".xml"));
1020            _bout = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(_writing));
1021            _xstream.toXML(_list, _bout);
1022            _bout.close();
1023            _list = null;
1024            _bout = null;
1025            
1026            /* Groups */
1027            
1028        } catch (HibernateException e) {
1029            
1030            e.printStackTrace();
1031        }
1032        
1033    }
1034    
1035    /**
1036     * Will zip up all files in the tmp directory and send the result to the
1037     * given OutputStream
1038     *
1039     * @param out
1040     * OutputStream to write the zip files to
1041     * @throws IOException
1042     * @author Will
1043     */

1044    private void zipTempDirectoryToStream(OutputStream JavaDoc out) throws IOException JavaDoc {
1045        
1046        byte b[] = new byte[512];
1047        ZipOutputStream JavaDoc zout = new ZipOutputStream JavaDoc(out);
1048        File JavaDoc f = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath));
1049        String JavaDoc[] s = f.list();
1050        for (int i = 0; i < s.length; i++) {
1051            InputStream JavaDoc in = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(f = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath + "/" + s[i]))));
1052            ZipEntry JavaDoc e = new ZipEntry JavaDoc(s[i].replace(File.separatorChar, '/'));
1053            zout.putNextEntry(e);
1054            int len = 0;
1055            while ((len = in.read(b)) != -1) {
1056                zout.write(b, 0, len);
1057            }
1058            zout.closeEntry();
1059            in.close();
1060        }
1061        zout.close();
1062        out.close();
1063    }
1064    
1065    /**
1066     * Does what it says - deletes all files from the backupTempFilePath
1067     * @author Will
1068     */

1069    private void deleteTempFiles() {
1070        File JavaDoc f = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath));
1071        String JavaDoc[] _tempFiles = f.list();
1072        for (int i = 0; i < _tempFiles.length; i++) {
1073            f = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath + "/" + _tempFiles[i]));
1074            f.delete();
1075        }
1076        
1077    }
1078    
1079    /**
1080     * Takes a ZipInputStream and filename and will extract them to the
1081     * backupTempFilePath
1082     *
1083     * @param zin
1084     * ZipInputStream
1085     * @param s
1086     * FileName to be extracted
1087     * @throws IOException
1088     * @author Will
1089     */

1090    private void unzip(ZipInputStream JavaDoc zin, String JavaDoc s) throws IOException JavaDoc {
1091        System.out.println("unzipping " + s);
1092        File JavaDoc f = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath + "/" + s));
1093        BufferedOutputStream JavaDoc out = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(f));
1094        byte[] b = new byte[512];
1095        int len = 0;
1096        while ((len = zin.read(b)) != -1) {
1097            out.write(b, 0, len);
1098        }
1099        out.close();
1100    }
1101    
1102    /**
1103     * Simple FileNameFilter for XML files
1104     *
1105     * @author will
1106     *
1107     */

1108    private class XMLFileNameFilter implements FilenameFilter JavaDoc {
1109        
1110        public boolean accept(File JavaDoc f, String JavaDoc s) {
1111            if (s.toLowerCase().endsWith(".xml")) {
1112                return true;
1113            } else {
1114                return false;
1115            }
1116        }
1117        
1118    }
1119    
1120    /**
1121     * This is not completed should delete all the dotcms data from an install
1122     * @author Will
1123     */

1124    private void deleteDotCMS() {
1125        try {
1126            /* get a list of all our tables */
1127            Set JavaDoc<Class JavaDoc> _tablesToDump = new HashSet JavaDoc<Class JavaDoc>();
1128            Map JavaDoc map;
1129            
1130            map = DotHibernate.getSession().getSessionFactory().getAllClassMetadata();
1131            
1132            Iterator JavaDoc it = map.entrySet().iterator();
1133            while (it.hasNext()) {
1134                Map.Entry JavaDoc pairs = (Map.Entry JavaDoc) it.next();
1135                ClassMetadata cmd = (ClassMetadata) pairs.getValue();
1136                
1137            }
1138        } catch (HibernateException e) {
1139            // TODO Auto-generated catch block
1140
e.printStackTrace();
1141        }
1142        
1143    }
1144    
1145    /**
1146     * Handles the file upload for the Servlet. It will send files to be
1147     * unzipped if nessary
1148     *
1149     * @param request
1150     * @param response
1151     * @throws IOException
1152     */

1153    private void doUpload(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws IOException JavaDoc {
1154        deleteTempFiles();
1155        String JavaDoc tempdir = Config.CONTEXT.getRealPath(backupTempFilePath);
1156        
1157        MultipartRequest mpr;
1158        try {
1159            mpr = new MultipartRequest(request, tempdir, 1000000000);
1160            File JavaDoc importFile = mpr.getFile("fileUpload");
1161            
1162            /*
1163             * Unzip zipped backups
1164             */

1165            if (importFile != null && importFile.getName().toLowerCase().endsWith(".zip")) {
1166                
1167                InputStream JavaDoc in = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(importFile));
1168                ZipInputStream JavaDoc zin = new ZipInputStream JavaDoc(in);
1169                ZipEntry JavaDoc e;
1170                
1171                while ((e = zin.getNextEntry()) != null) {
1172                    unzip(zin, e.getName());
1173                }
1174                zin.close();
1175                importFile.delete();
1176            }
1177            
1178        } catch (IOException JavaDoc e) {
1179            // TODO Auto-generated catch block
1180
e.printStackTrace();
1181        }
1182        File JavaDoc f = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath));
1183        String JavaDoc[] _tempFiles = f.list(new XMLFileNameFilter());
1184        PrintWriter JavaDoc out = response.getWriter();
1185        out.println("<pre>Found " + _tempFiles.length + " files to import");
1186        for (int i = 0; i < _tempFiles.length; i++) {
1187            File JavaDoc _importFile = new File JavaDoc(Config.CONTEXT.getRealPath(backupTempFilePath + "/" + _tempFiles[i]));
1188            doXMLFileImport(_importFile, out);
1189            out.flush();
1190        }
1191        out.println("Done Importing");
1192        
1193    }
1194    
1195}
1196
Popular Tags