KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > dotmarketing > portlets > contentlet > factories > ContentletFactory


1 package com.dotmarketing.portlets.contentlet.factories;
2
3 import java.lang.reflect.Method JavaDoc;
4 import java.util.ArrayList JavaDoc;
5 import java.util.Calendar JavaDoc;
6 import java.util.Date JavaDoc;
7 import java.util.GregorianCalendar JavaDoc;
8 import java.util.HashMap JavaDoc;
9 import java.util.List JavaDoc;
10 import java.util.Map JavaDoc;
11 import java.util.StringTokenizer JavaDoc;
12 import java.util.regex.Matcher JavaDoc;
13 import java.util.regex.Pattern JavaDoc;
14
15 import javax.portlet.WindowState;
16 import javax.servlet.http.HttpServletRequest JavaDoc;
17
18 import org.apache.commons.beanutils.PropertyUtils;
19
20 //import org.apache.lucene.analysis.WhitespaceAnalyzer;
21
//import org.apache.lucene.analysis.standard.StandardAnalyzer;
22
import com.dotmarketing.lucene.DotAnalyzer;
23
24 import org.apache.lucene.document.Document;
25 import org.apache.lucene.queryParser.QueryParser;
26 import org.apache.lucene.search.BooleanClause;
27 import org.apache.lucene.search.BooleanQuery;
28 import org.apache.lucene.search.Query;
29
30 import com.dotmarketing.beans.Host;
31 import com.dotmarketing.beans.Identifier;
32 import com.dotmarketing.beans.Inode;
33 import com.dotmarketing.beans.MultiTree;
34 import com.dotmarketing.beans.Permission;
35 import com.dotmarketing.beans.PermissionAsset;
36 import com.dotmarketing.beans.WebAsset;
37 import com.dotmarketing.cache.FieldsCache;
38 import com.dotmarketing.cache.IdentifierCache;
39 import com.dotmarketing.cache.PermissionCache;
40 import com.dotmarketing.cache.StructureCache;
41 import com.dotmarketing.cms.factories.PublicCompanyFactory;
42 import com.dotmarketing.cms.factories.PublicUserFactory;
43 import com.dotmarketing.db.DbConnectionFactory;
44 import com.dotmarketing.db.DotConnect;
45 import com.dotmarketing.db.DotHibernate;
46 import com.dotmarketing.factories.HostFactory;
47 import com.dotmarketing.factories.IdentifierFactory;
48 import com.dotmarketing.factories.InodeFactory;
49 import com.dotmarketing.factories.MultiTreeFactory;
50 import com.dotmarketing.factories.PermissionFactory;
51 import com.dotmarketing.factories.WebAssetFactory;
52 import com.dotmarketing.portlets.categories.model.Category;
53 import com.dotmarketing.portlets.containers.model.Container;
54 import com.dotmarketing.portlets.contentlet.model.Contentlet;
55 import com.dotmarketing.portlets.files.model.File;
56 import com.dotmarketing.portlets.folders.model.Folder;
57 import com.dotmarketing.portlets.htmlpages.model.HTMLPage;
58 import com.dotmarketing.portlets.indexation.factory.IndexationFactory;
59 import com.dotmarketing.portlets.indexation.model.Indexation;
60 import com.dotmarketing.portlets.languagesmanager.factories.LanguageFactory;
61 import com.dotmarketing.portlets.links.model.Link;
62 import com.dotmarketing.portlets.structure.factories.FieldFactory;
63 import com.dotmarketing.portlets.structure.factories.StructureFactory;
64 import com.dotmarketing.portlets.structure.model.Field;
65 import com.dotmarketing.portlets.structure.model.Structure;
66 import com.dotmarketing.services.ContentletMapServices;
67 import com.dotmarketing.services.ContentletServices;
68 import com.dotmarketing.util.Config;
69 import com.dotmarketing.util.Logger;
70 import com.dotmarketing.util.LuceneHits;
71 import com.dotmarketing.util.LuceneUtils;
72 import com.dotmarketing.util.Mailer;
73 import com.dotmarketing.util.PortletURLUtil;
74 import com.dotmarketing.util.UtilMethods;
75 import com.liferay.portal.PortalException;
76 import com.liferay.portal.SystemException;
77 import com.liferay.portal.model.Role;
78 import com.liferay.portal.model.User;
79
80 /**
81  *
82  * @author David
83  */

84 public class ContentletFactory {
85
86     public static final String JavaDoc ADD_TO_INDEX = "ADD_TO_INDEX";
87
88     public static final String JavaDoc ADD_TO_INDEX_REINDEXATION = "ADD_TO_INDEX_REINDEXATION";
89
90     public static final Contentlet getContentlet(String JavaDoc id) {
91         return (Contentlet) InodeFactory.getInode(id, Contentlet.class);
92     }
93
94     public static final Contentlet getContentletForLanguage(long languageId, Inode inode) {
95         try {
96             String JavaDoc condition = "language_id = " + languageId + " and working=" + com.dotmarketing.db.DbConnectionFactory.getDBTrue()
97                     + " and deleted = " + com.dotmarketing.db.DbConnectionFactory.getDBFalse();
98
99             return (Contentlet) InodeFactory.getChildOfClassbyCondition(inode, Contentlet.class, condition);
100         } catch (Exception JavaDoc e) {
101             return new Contentlet();
102         }
103     }
104
105     public static final Contentlet getContentletNoLock(long id) {
106         DotHibernate dh = new DotHibernate(Contentlet.class);
107         StringBuffer JavaDoc querie = new StringBuffer JavaDoc();
108         querie.append("select {contentlet.*} from contentlet with (nolock), inode contentlet_1_ with (nolock) ");
109         querie.append("where contentlet.inode = contentlet_1_.inode and contentlet.inode = " + id);
110
111         dh.setSQLQuery(querie.toString());
112
113         return (Contentlet) dh.load();
114     }
115
116     public static final Contentlet getContentlet(long id) {
117         return (Contentlet) InodeFactory.getInode(String.valueOf(id), Contentlet.class);
118     }
119
120     public static final java.util.List JavaDoc getContentletsByContainerAndPage(Container c, HTMLPage html, String JavaDoc language) {
121
122         if (!UtilMethods.isSet(c.getSortContentletsBy())) {
123             c.setSortContentletsBy("sort_order");
124         }
125         return getContentletsByOrderAndParents(c.getInode(), html.getInode(), c.getSortContentletsBy(), false, language);
126     }
127
128     public static final java.util.List JavaDoc getContentletsByStructure(long structureInode, String JavaDoc orderby) {
129         String JavaDoc condition = "structure_inode =" + structureInode;
130         return InodeFactory.getInodesOfClassByConditionAndOrderBy(Contentlet.class, condition, orderby);
131     }
132
133     public static final java.util.List JavaDoc getContentletsByStructure(long structureInode) {
134         String JavaDoc condition = "structure_inode =" + structureInode;
135         return InodeFactory.getInodesOfClassByCondition(Contentlet.class, condition);
136     }
137
138     public static final java.util.List JavaDoc getContentletsByOrderAndParents(long i, long i2, String JavaDoc orderby) {
139         return getContentletsByOrderAndParents(i, i2, orderby, false, "");
140     }
141
142     public static final java.util.List JavaDoc getContentletsByOrderAndParents(long i, long i2, String JavaDoc orderby, String JavaDoc language) {
143         return getContentletsByOrderAndParents(i, i2, orderby, false, language);
144     }
145
146     @SuppressWarnings JavaDoc("unchecked")
147     public static final java.util.List JavaDoc<Contentlet> getContentletsByOrderAndParents(long i, long i2, String JavaDoc orderby, boolean previewMode,
148             String JavaDoc language) {
149
150         String JavaDoc condition = "";
151
152         if (previewMode)
153             condition = "working=" + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " and deleted = "
154                     + com.dotmarketing.db.DbConnectionFactory.getDBFalse();
155         else
156             condition = "live=" + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " and deleted = "
157                     + com.dotmarketing.db.DbConnectionFactory.getDBFalse();
158         if (!UtilMethods.isSet(language) || language.equals("0")) {
159             language = String.valueOf(LanguageFactory.getDefaultLanguage().getId());
160         }
161         condition += " and language_id = " + language;
162
163         DotHibernate dh = new DotHibernate(Contentlet.class);
164
165         if (orderby.equals("tree_order") || !UtilMethods.isSet(orderby)) {
166             orderby = "multi_tree.tree_order";
167         }
168         String JavaDoc query = "select {contentlet.*} from contentlet, inode contentlet_1_, identifier, tree, multi_tree "
169                 + "where contentlet.inode = contentlet_1_.inode and contentlet.inode = tree.child and tree.parent = identifier.inode and "
170                 + "multi_tree.child = identifier.inode and multi_tree.parent1 = ? and multi_tree.parent2 = ? and " + condition + " order by "
171                 + orderby;
172
173         dh.setSQLQuery(query);
174         dh.setParam(i);
175         dh.setParam(i2);
176
177         return dh.list();
178     }
179
180     @SuppressWarnings JavaDoc("unchecked")
181     public static final java.util.List JavaDoc<Contentlet> getContentletsByStuctureAndCategory(Structure st, Category cat, String JavaDoc orderby) {
182
183         String JavaDoc condition = "";
184
185         condition = "live=" + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " and deleted = "
186                 + com.dotmarketing.db.DbConnectionFactory.getDBFalse() + " and structure_inode = " + st.getInode();
187
188         DotHibernate dh = new DotHibernate(Contentlet.class);
189
190         String JavaDoc query = "select {contentlet.*} from contentlet, inode contentlet_1_, tree "
191                 + "where contentlet.inode = contentlet_1_.inode and contentlet.inode = tree.child and tree.parent = ? and " + condition
192                 + " order by " + orderby;
193
194         dh.setSQLQuery(query);
195         dh.setParam(cat.getInode());
196
197         return dh.list();
198     }
199
200     @SuppressWarnings JavaDoc("unchecked")
201     public static final java.util.List JavaDoc<Contentlet> getContentletsByStuctureAndCategory(Structure st, Category cat, String JavaDoc orderby, int maxResults) {
202
203         String JavaDoc condition = "";
204
205         condition = "live=" + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " and deleted = "
206                 + com.dotmarketing.db.DbConnectionFactory.getDBFalse() + " and structure_inode = " + st.getInode();
207
208         DotHibernate dh = new DotHibernate(Contentlet.class);
209
210         String JavaDoc query = "select {contentlet.*} from contentlet, inode contentlet_1_, tree "
211                 + "where contentlet.inode = contentlet_1_.inode and contentlet.inode = tree.child and tree.parent = ? and " + condition
212                 + " order by " + orderby;
213
214         dh.setSQLQuery(query);
215         dh.setParam(cat.getInode());
216         if (maxResults > 0)
217             dh.setMaxResults(maxResults);
218
219         return dh.list();
220     }
221
222     @SuppressWarnings JavaDoc("unchecked")
223     public static final java.util.List JavaDoc<Contentlet> getContentletsByStuctureAndFieldValue(Structure st, String JavaDoc fieldName, String JavaDoc fieldValue,
224             String JavaDoc orderby, int maxResults) {
225
226         List JavaDoc<Field> fields = FieldsCache.getFieldsByStructureInode(st.getInode());
227
228         Field theField = null;
229         for (Field f : fields) {
230             if (f.getFieldName().equals(fieldName)) {
231                 theField = f;
232                 break;
233             }
234         }
235
236         if (theField == null)
237             return new ArrayList JavaDoc<Contentlet>();
238
239         String JavaDoc condition = "";
240
241         condition = " live=" + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " and deleted = "
242                 + com.dotmarketing.db.DbConnectionFactory.getDBFalse() + " and structure_inode = " + st.getInode() + " and "
243                 + theField.getFieldContentlet() + " = '" + fieldValue + "'";
244
245         DotHibernate dh = new DotHibernate(Contentlet.class);
246
247         String JavaDoc query = "select {contentlet.*} from contentlet, inode contentlet_1_ " + "where contentlet.inode = contentlet_1_.inode and "
248                 + condition;
249
250         if (UtilMethods.isSet(orderby))
251             query += " order by " + orderby;
252
253         dh.setSQLQuery(query);
254         if (maxResults > 0)
255             dh.setMaxResults(maxResults);
256
257         return dh.list();
258     }
259
260     public static final java.util.List JavaDoc<Contentlet> getContentletsByStuctureAndFieldsValues(Structure st, Map JavaDoc<String JavaDoc, String JavaDoc> fieldsMap,
261             List JavaDoc<String JavaDoc> orderByfields, boolean descOrder) {
262
263         boolean firstToOrder = true;
264         StringBuffer JavaDoc orderByCond = new StringBuffer JavaDoc();
265         StringBuffer JavaDoc fieldsCondition = new StringBuffer JavaDoc();
266
267         List JavaDoc<Field> fields = FieldsCache.getFieldsByStructureInode(st.getInode());
268
269         for (Field f : fields) {
270             if (fieldsMap.containsKey(f.getFieldName())) {
271                 fieldsCondition.append("and " + f.getFieldContentlet() + " = '" + fieldsMap.get(f.getFieldName()) + "'");
272             }
273             if (orderByfields.contains(f.getFieldName())) {
274                 if (!firstToOrder)
275                     orderByCond.append(",");
276                 else
277                     firstToOrder = false;
278                 orderByCond.append(f.getFieldContentlet() + " ");
279                 if (descOrder)
280                     orderByCond.append("desc ");
281             }
282         }
283
284         String JavaDoc condition = "";
285
286         condition = " live=" + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " and deleted = "
287                 + com.dotmarketing.db.DbConnectionFactory.getDBFalse() + " and structure_inode = " + st.getInode() + " " + fieldsCondition;
288
289         DotHibernate dh = new DotHibernate(Contentlet.class);
290
291         String JavaDoc query = "select {contentlet.*} from contentlet, inode contentlet_1_ " + "where contentlet.inode = contentlet_1_.inode and "
292                 + condition;
293
294         if (orderByCond.length() > 0)
295             query += " order by " + orderByCond.toString();
296
297         dh.setSQLQuery(query);
298
299         return dh.list();
300     }
301
302     public static final java.util.List JavaDoc<Contentlet> getContentletsByStuctureAndFieldsValuesLike(Structure st, Map JavaDoc<String JavaDoc, String JavaDoc> fieldsMap,
303             List JavaDoc<String JavaDoc> orderByfields, boolean descOrder) {
304
305         boolean firstToOrder = true;
306         StringBuffer JavaDoc orderByCond = new StringBuffer JavaDoc();
307         StringBuffer JavaDoc fieldsCondition = new StringBuffer JavaDoc();
308
309         List JavaDoc<Field> fields = FieldsCache.getFieldsByStructureInode(st.getInode());
310
311         for (Field f : fields) {
312             if (fieldsMap.containsKey(f.getFieldName())) {
313                 fieldsCondition.append("and " + f.getFieldContentlet() + " like '%" + fieldsMap.get(f.getFieldName()) + "%'");
314             }
315             if (orderByfields.contains(f.getFieldName())) {
316                 if (!firstToOrder)
317                     orderByCond.append(",");
318                 else
319                     firstToOrder = false;
320                 orderByCond.append(f.getFieldContentlet() + " ");
321                 if (descOrder)
322                     orderByCond.append("desc ");
323             }
324         }
325
326         String JavaDoc condition = "";
327
328         condition = " live=" + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " and deleted = "
329                 + com.dotmarketing.db.DbConnectionFactory.getDBFalse() + " and structure_inode = " + st.getInode() + " " + fieldsCondition;
330
331         DotHibernate dh = new DotHibernate(Contentlet.class);
332
333         String JavaDoc query = "select {contentlet.*} from contentlet, inode contentlet_1_ " + "where contentlet.inode = contentlet_1_.inode and "
334                 + condition;
335
336         if (orderByCond.length() > 0)
337             query += " order by " + orderByCond.toString();
338
339         Logger.debug(ContentletFactory.class, "getContentletsByStuctureAndFieldsValues: query = " + query);
340
341         dh.setSQLQuery(query);
342
343         return dh.list();
344     }
345
346     public static final int getContentletsCountByStuctureAndFieldsValues(Structure st, Map JavaDoc<String JavaDoc, String JavaDoc> fieldsMap) {
347
348         StringBuffer JavaDoc fieldsCondition = new StringBuffer JavaDoc();
349
350         List JavaDoc<Field> fields = FieldsCache.getFieldsByStructureInode(st.getInode());
351
352         for (Field f : fields) {
353             if (fieldsMap.containsKey(f.getFieldName())) {
354                 fieldsCondition.append("and " + f.getFieldContentlet() + " = '" + fieldsMap.get(f.getFieldName()) + "'");
355             }
356         }
357
358         String JavaDoc condition = "";
359
360         condition = " live=" + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " and deleted = "
361                 + com.dotmarketing.db.DbConnectionFactory.getDBFalse() + " and structure_inode = " + st.getInode() + " " + fieldsCondition;
362
363         DotConnect dc = new DotConnect();
364
365         String JavaDoc query = "select count(*) as count from contentlet, inode contentlet_1_ " + "where contentlet.inode = contentlet_1_.inode and "
366                 + condition;
367
368         dc.setSQL(query);
369
370         return Integer.parseInt((String JavaDoc) ((Map JavaDoc) dc.getResults().get(0)).get("count"));
371     }
372
373     public static final java.util.List JavaDoc getWorkingContentletsByOrderAndParents(long i, long i2) {
374
375         String JavaDoc condition = "working=" + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " and deleted = "
376                 + com.dotmarketing.db.DbConnectionFactory.getDBFalse();
377
378         DotHibernate dh = new DotHibernate(Contentlet.class);
379
380         String JavaDoc query = "select {contentlet.*} from contentlet, inode contentlet_1_, identifier, tree, multi_tree "
381                 + "where contentlet.inode = contentlet_1_.inode and contentlet.inode = tree.child and tree.parent = identifier.inode and "
382                 + "multi_tree.child = identifier.inode and multi_tree.parent1 = ? and multi_tree.parent2 = ? and " + condition;
383
384         dh.setSQLQuery(query);
385         dh.setParam(i);
386         dh.setParam(i2);
387
388         return dh.list();
389     }
390
391     public static final java.util.List JavaDoc getWorkingContentlets() {
392         DotHibernate dh = new DotHibernate(Contentlet.class);
393
394         String JavaDoc condition = "working=" + com.dotmarketing.db.DbConnectionFactory.getDBTrue();
395         String JavaDoc query = "select {contentlet.*} from contentlet, inode contentlet_1_ " + "where contentlet.inode = contentlet_1_.inode and "
396                 + condition;
397         dh.setSQLQuery(query);
398
399         return dh.list();
400     }
401
402     public static final java.util.List JavaDoc getContentletsByParent(Inode i) {
403
404         return InodeFactory.getChildrenClass(i, Contentlet.class);
405
406     }
407
408     public static final java.util.List JavaDoc getContentletsByOrderAndParent(Inode i, String JavaDoc orderby) {
409
410         return InodeFactory.getChildrenClassByConditionAndOrderBy(i, Contentlet.class, " 1=1 ", orderby);
411
412     }
413
414     public static Contentlet save(Contentlet x) {
415         DotHibernate.saveOrUpdate(x);
416         return x;
417     }
418
419     public static Contentlet getInstance() {
420         Logger.debug(ContentletFactory.class, "Contentlet getInstance()");
421         Contentlet contentlet = new Contentlet();
422         GregorianCalendar JavaDoc cal = new GregorianCalendar JavaDoc();
423         contentlet.setModDate(cal.getTime());
424         // contentlet.setStartDate(cal.getTime());
425
cal.add(Calendar.YEAR, 10);
426         // contentlet.setEndDate(cal.getTime());
427
contentlet.setType("contentlet");
428         return contentlet;
429     }
430
431     public static java.util.List JavaDoc getChildrenContentletsByOrder(Inode i) {
432
433         return getContentletsByOrderAndParent(i, "sort_by");
434
435     }
436
437     @SuppressWarnings JavaDoc("unchecked")
438     public static java.util.List JavaDoc<Contentlet> getActiveContentlets() {
439         DotHibernate dh = new DotHibernate(Contentlet.class);
440         dh.setQuery("from inode in class com.dotmarketing.portlets.contentlet.model.Contentlet");
441
442         return (java.util.List JavaDoc<Contentlet>) dh.list();
443     }
444
445     public static java.util.List JavaDoc getContentletsByOrderAndParent(String JavaDoc orderby, Inode o) {
446
447         String JavaDoc condition = " working = " + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " and deleted = "
448                 + com.dotmarketing.db.DbConnectionFactory.getDBFalse();
449         return InodeFactory.getChildrenClassByConditionAndOrderBy(o, Contentlet.class, condition, orderby);
450
451     }
452
453     public static java.util.List JavaDoc getContentletsByOrder(String JavaDoc orderby) {
454         DotHibernate dh = new DotHibernate(Contentlet.class);
455         dh.setQuery("from inode in class com.dotmarketing.portlets.contentlet.model.Contentlet where working = "
456                 + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " and deleted = " + com.dotmarketing.db.DbConnectionFactory.getDBFalse()
457                 + " order by " + orderby);
458
459         return dh.list();
460     }
461
462     public static java.util.List JavaDoc getContentletChildrenByCondition(Inode o, String JavaDoc condition) {
463
464         return InodeFactory.getChildrenClassByConditionAndOrderBy(o, Contentlet.class, condition, "title, sort_order");
465
466     }
467
468     public static java.util.List JavaDoc getContentletByCondition(String JavaDoc condition) {
469         DotHibernate dh = new DotHibernate(Contentlet.class);
470         dh.setQuery("from inode in class com.dotmarketing.portlets.contentlet.model.Contentlet where " + condition + " order by title, sort_order");
471         return dh.list();
472     }
473
474     public static java.util.List JavaDoc<Long JavaDoc> getContentletsInodesByCondition(String JavaDoc condition) {
475         ArrayList JavaDoc<Long JavaDoc> inodesList = new ArrayList JavaDoc();
476         DotConnect dc = new DotConnect();
477         if (UtilMethods.isSet(condition))
478             dc.setSQL("select inode.inode from contentlet, inode where inode.inode = contentlet.inode and " + condition);
479         else
480             dc.setSQL("select inode.inode from contentlet, inode where inode.inode = contentlet.inode");
481
482         ArrayList JavaDoc<Map JavaDoc<String JavaDoc, String JavaDoc>> results = dc.getResults();
483         for (Map JavaDoc<String JavaDoc, String JavaDoc> result : results) {
484             String JavaDoc inode = result.get("inode");
485             try {
486                 inodesList.add(Long.parseLong(inode));
487             } catch (NumberFormatException JavaDoc e) {
488                 Logger.warn(ContentletFactory.class, "Exception pulling contentlets inode from database with condition: " + condition, e);
489             }
490         }
491         return inodesList;
492     }
493
494     public static java.util.List JavaDoc<Long JavaDoc> getContentletsInodesByConditionNoLock(String JavaDoc condition) {
495         ArrayList JavaDoc<Long JavaDoc> inodesList = new ArrayList JavaDoc();
496         DotConnect dc = new DotConnect();
497         if (UtilMethods.isSet(condition))
498             dc.setSQL("select inode.inode from contentlet with (nolock), inode with (nolock) where inode.inode = contentlet.inode and " + condition);
499         else
500             dc.setSQL("select inode.inode from contentlet with (nolock), inode with (nolock) where inode.inode = contentlet.inode");
501
502         ArrayList JavaDoc<Map JavaDoc<String JavaDoc, String JavaDoc>> results = dc.getResults();
503         for (Map JavaDoc<String JavaDoc, String JavaDoc> result : results) {
504             String JavaDoc inode = result.get("inode");
505             try {
506                 inodesList.add(Long.parseLong(inode));
507             } catch (NumberFormatException JavaDoc e) {
508                 Logger.warn(ContentletFactory.class, "Exception pulling contentlets inode from database with condition: " + condition, e);
509             }
510         }
511         return inodesList;
512     }
513
514     public static java.util.List JavaDoc getContentletChildren(Inode o) {
515
516         return InodeFactory.getChildrenClassByConditionAndOrderBy(o, Contentlet.class, "0=0", "inode, sort_order");
517
518     }
519
520     public static Contentlet getContentletByLiveAndFolderAndTitle(Inode parent, String JavaDoc title) {
521
522         return (Contentlet) InodeFactory.getChildOfClassbyCondition(parent, Contentlet.class, "title = '" + title + "' and live = "
523                 + com.dotmarketing.db.DbConnectionFactory.getDBTrue());
524
525     }
526
527     public static java.util.List JavaDoc getContentletsPerRoleAndCondition(Host host, Role[] roles, String JavaDoc condition) {
528         return getContentletsPerRoleAndCondition(host.getInode(), roles, condition);
529     }
530
531     public static java.util.List JavaDoc getContentletsPerRoleAndCondition(long hostId, Role[] roles, String JavaDoc condition) {
532
533         java.util.List JavaDoc entries = new java.util.ArrayList JavaDoc();
534         java.util.List JavaDoc folders = com.dotmarketing.portlets.folders.factories.FolderFactory.getFoldersByParent(hostId);
535         return com.dotmarketing.portlets.folders.factories.FolderFactory.getFoldersAndEntriesByRoles(folders, entries, roles, Contentlet.class,
536                 condition);
537
538     }
539
540     public static java.util.List JavaDoc getContentletsPerRole(Host host, Role[] roles) {
541         return getContentletsPerRole(host.getInode(), roles);
542     }
543
544     public static java.util.List JavaDoc getContentletsPerRole(long hostId, Role[] roles) {
545         java.util.List JavaDoc entries = new java.util.ArrayList JavaDoc();
546         java.util.List JavaDoc folders = com.dotmarketing.portlets.folders.factories.FolderFactory.getFoldersByParent(hostId);
547         return com.dotmarketing.portlets.folders.factories.FolderFactory.getFoldersAndEntriesByRoles(folders, entries, roles, Contentlet.class);
548     }
549
550     public static java.util.List JavaDoc getContentletsAndPermissionsPerRoleAndCondition(Role[] roles, String JavaDoc condition, int limit, int offset, String JavaDoc orderby) {
551
552         java.util.List JavaDoc<PermissionAsset> entries = new java.util.ArrayList JavaDoc<PermissionAsset>();
553         orderby = "contentlet." + orderby;
554         java.util.List JavaDoc elements = WebAssetFactory.getAssetsPerConditionWithPermission(condition, Contentlet.class, roles, limit, offset, orderby, 0);
555         java.util.Iterator JavaDoc elementsIter = elements.iterator();
556
557         while (elementsIter.hasNext()) {
558
559             Contentlet contentlet = (Contentlet) elementsIter.next();
560             Folder folderParent = (Folder) InodeFactory.getParentOfClass(contentlet, Folder.class);
561
562             java.util.List JavaDoc permissions = PermissionCache.getPermissionIdsByRolesFromCache(contentlet, roles);
563
564             PermissionAsset permAsset = new PermissionAsset();
565             permAsset.setPathToMe(folderParent.getPath());
566             permAsset.setPermissions(permissions);
567             permAsset.setAsset(contentlet);
568             entries.add(permAsset);
569         }
570
571         return entries;
572     }
573
574     public static boolean existsContentlet(String JavaDoc friendlyName) {
575
576         DotHibernate dh = new DotHibernate(Contentlet.class);
577         dh.setQuery("from inode in class com.dotmarketing.portlets.contentlet.model.Contentlet where friendly_name = ?");
578         dh.setParam(friendlyName);
579         return (((java.util.List JavaDoc) dh.list()).size() > 0);
580     }
581
582     public static java.util.List JavaDoc getAssetsAndPermissionsPerRoleAndCondition(Host host, Role[] roles, String JavaDoc condition, int limit, int offset,
583             String JavaDoc orderby, Class JavaDoc assetsClass, String JavaDoc tableName) {
584         return getAssetsAndPermissionsPerRoleAndCondition(host.getInode(), roles, condition, limit, offset, orderby, assetsClass, tableName);
585     }
586
587     public static java.util.List JavaDoc getAssetsAndPermissionsPerRoleAndCondition(long hostId, Role[] roles, String JavaDoc condition, int limit, int offset,
588             String JavaDoc orderby, Class JavaDoc assetsClass, String JavaDoc tableName) {
589         java.util.List JavaDoc<PermissionAsset> entries = new java.util.ArrayList JavaDoc<PermissionAsset>();
590         orderby = tableName + "." + orderby;
591         java.util.List JavaDoc identifiers = IdentifierFactory.getIdentifiersPerConditionWithPermission(hostId, condition, assetsClass, roles, limit, offset,
592                 orderby);
593         java.util.Iterator JavaDoc identifiersIter = identifiers.iterator();
594
595         while (identifiersIter.hasNext()) {
596
597             Identifier identifier = (Identifier) identifiersIter.next();
598             java.util.List JavaDoc elements = IdentifierFactory.getWorkingChildrenOfClass(identifier, assetsClass, "language_id");
599             java.util.Iterator JavaDoc elementsIter = elements.iterator();
600
601             while (elementsIter.hasNext()) {
602
603                 WebAsset asset = (WebAsset) elementsIter.next();
604                 Folder folderParent = (Folder) InodeFactory.getParentOfClass(asset, Folder.class);
605                 java.util.List JavaDoc permissions = PermissionCache.getPermissionIdsByRolesFromCache(asset, roles);
606                 PermissionAsset permAsset = new PermissionAsset();
607                 if (folderParent == null || folderParent.getPath() == null) {
608                     Logger.warn(ContentletFactory.class, "THERE IS NO FOLDER PATH FOR THIS ASSET!!!!=" + asset.getInode());
609                 }
610                 permAsset.setPathToMe(folderParent.getPath());
611                 permAsset.setPermissions(permissions);
612                 permAsset.setIdentifier(identifier.getInode());
613                 permAsset.setAsset(asset);
614                 entries.add(permAsset);
615             }
616
617         }
618
619         return entries;
620     }
621
622     // Generic method for all Assets.
623
public static java.util.List JavaDoc getAssetsAndPermissionsPerRoleAndCondition(Role[] roles, String JavaDoc condition, int limit, int offset, String JavaDoc orderby,
624             Class JavaDoc assetsClass, String JavaDoc tableName) {
625
626         java.util.List JavaDoc<PermissionAsset> entries = new java.util.ArrayList JavaDoc<PermissionAsset>();
627         orderby = tableName + "." + orderby;
628         java.util.List JavaDoc identifiers = IdentifierFactory
629                 .getIdentifiersPerConditionWithPermission(condition, assetsClass, roles, limit, offset, orderby);
630         java.util.Iterator JavaDoc identifiersIter = identifiers.iterator();
631
632         while (identifiersIter.hasNext()) {
633
634             Identifier identifier = (Identifier) identifiersIter.next();
635             java.util.List JavaDoc elements = IdentifierFactory.getWorkingChildrenOfClass(identifier, assetsClass, "language_id");
636             java.util.Iterator JavaDoc elementsIter = elements.iterator();
637
638             while (elementsIter.hasNext()) {
639
640                 WebAsset asset = (WebAsset) elementsIter.next();
641                 Folder folderParent = (Folder) InodeFactory.getParentOfClass(asset, Folder.class);
642                 java.util.List JavaDoc permissions = PermissionCache.getPermissionIdsByRolesFromCache(asset, roles);
643                 PermissionAsset permAsset = new PermissionAsset();
644                 if (folderParent == null || folderParent.getPath() == null) {
645                     Logger.warn(ContentletFactory.class, "THERE IS NO FOLDER PATH FOR THIS ASSET!!!!=" + asset.getInode());
646                 }
647                 permAsset.setPathToMe(folderParent.getPath());
648                 permAsset.setPermissions(permissions);
649                 permAsset.setIdentifier(identifier.getInode());
650                 permAsset.setAsset(asset);
651                 entries.add(permAsset);
652             }
653
654         }
655
656         return entries;
657     }
658
659     public static void addImageToContentlet(Contentlet contentlet, long imageInode, String JavaDoc relationName) {
660         if (imageInode != 0) {
661             File image = (File) InodeFactory.getInode(imageInode, File.class);
662             Identifier identifier = IdentifierFactory.getIdentifierByInode(image);
663             contentlet.addChild(identifier, relationName);
664         }
665     }
666
667     public static void addFileToContentlet(Contentlet contentlet, long fileInode, String JavaDoc relationName) {
668         if (fileInode != 0) {
669             File file = (File) InodeFactory.getInode(fileInode, File.class);
670             Identifier identifier = IdentifierFactory.getIdentifierByInode(file);
671             contentlet.addChild(identifier, relationName);
672         }
673     }
674
675     public static void addLinkToContentlet(Contentlet contentlet, long linkInode, String JavaDoc relationName) {
676         if (linkInode != 0) {
677             Link link = (Link) InodeFactory.getInode(linkInode, Link.class);
678             Identifier identifier = IdentifierFactory.getIdentifierByInode(link);
679             contentlet.addChild(identifier, relationName);
680         }
681     }
682
683     public static boolean existsContentletWithTitle(String JavaDoc tile) {
684         Contentlet contentlet = (Contentlet) InodeFactory.getInodeOfClassByCondition(Contentlet.class, "title like '" + tile + "'");
685         Logger.debug(ContentletFactory.class, "existsContentlet=" + (contentlet.getInode() > 0));
686         return (contentlet.getInode() > 0);
687     }
688
689     public static Contentlet copyContentlet(Contentlet currentContentlet) {
690
691         // gets the new information for the template from the request object
692
Contentlet newContentlet = new Contentlet();
693
694         InodeFactory.saveInode(newContentlet);
695
696         newContentlet.copy(currentContentlet);
697         newContentlet.setLocked(false);
698         newContentlet.setLive(false);
699         newContentlet.setFriendlyName(currentContentlet.getFriendlyName() + " (COPY) ");
700         newContentlet.setTitle(currentContentlet.getTitle() + " (COPY) ");
701
702         // newContentlet.setOtherText(currentContentlet.getOtherText());
703
// persists the webasset
704
// InodeFactory.saveInode(newContentlet);
705

706         // add the new categories
707
String JavaDoc[] arr = null; // currentContentlet.getCategories();
708
if (arr != null) {
709             for (int i = 0; i < arr.length; i++) {
710                 Category node = (Category) InodeFactory.getInode(arr[i], Category.class);
711                 node.addChild(newContentlet);
712             }
713         }
714
715         // creates new identifier for this webasset and persists it
716
Identifier newIdentifier = IdentifierFactory.createNewIdentifier(newContentlet);
717
718         Logger.debug(ContentletFactory.class, "newIdentifier inode=" + newIdentifier.getInode());
719
720         // Copy permissions
721
PermissionFactory.copyPermissions(currentContentlet, newContentlet);
722
723         // writes the contentlet to a working directory under velocity folder
724
ContentletServices.writeContentletToFile(newContentlet, newIdentifier, true);
725         // writes the contentlet object to a file
726
ContentletMapServices.writeContentletMapToFile(newContentlet, true);
727         return newContentlet;
728     }
729
730     public static Object JavaDoc getFieldValue(Contentlet content, String JavaDoc fieldName) {
731         Structure structure = StructureFactory.getStructureByInode(content.getStructureInode());
732         Field theField = null;
733         List JavaDoc<Field> fields = FieldsCache.getFieldsByStructureInode(structure.getInode());
734         for (Field field : fields) {
735             if (field.getFieldName().equals(fieldName)) {
736                 theField = field;
737                 break;
738             }
739         }
740         if (theField == null)
741             return null;
742         try {
743             return PropertyUtils.getProperty(content, theField.getFieldContentlet());
744         } catch (Exception JavaDoc e) {
745             Logger.error(ContentletFactory.class, e.getMessage(), e);
746             return null;
747         }
748     }
749
750     public static Object JavaDoc getFieldValue(Contentlet content, Field theField) {
751         try {
752             return PropertyUtils.getProperty(content, theField.getFieldContentlet());
753         } catch (Exception JavaDoc e) {
754             Logger.error(ContentletFactory.class, e.getMessage(), e);
755             return null;
756         }
757     }
758
759     @SuppressWarnings JavaDoc("unchecked")
760     public static final java.util.List JavaDoc<Contentlet> getContentletsByStructureAndOrder(Structure st, String JavaDoc orderFieldName, String JavaDoc direction,
761             int maxResults) {
762
763         List JavaDoc<Field> fields = FieldsCache.getFieldsByStructureInode(st.getInode());
764
765         Field theField = null;
766         for (Field f : fields) {
767             if (f.getFieldName().equals(orderFieldName)) {
768                 theField = f;
769                 break;
770             }
771         }
772
773         if (theField == null)
774             return new ArrayList JavaDoc<Contentlet>();
775
776         String JavaDoc condition = "";
777
778         condition = " live=" + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " and deleted = "
779                 + com.dotmarketing.db.DbConnectionFactory.getDBFalse() + " and structure_inode = " + st.getInode();
780         // + theField.getFieldContentlet() + " = '" + fieldValue + "'";
781

782         DotHibernate dh = new DotHibernate(Contentlet.class);
783
784         String JavaDoc query = "select {contentlet.*} from contentlet, inode contentlet_1_ " + "where contentlet.inode = contentlet_1_.inode and "
785                 + condition;
786
787         if (UtilMethods.isSet(theField.getFieldContentlet()))
788             query += " order by " + theField.getFieldContentlet() + " " + direction;
789
790         dh.setSQLQuery(query);
791         if (maxResults > 0)
792             dh.setMaxResults(maxResults);
793
794         return dh.list();
795
796     }
797
798     @SuppressWarnings JavaDoc("unchecked")
799     public static List JavaDoc<Contentlet> getContentsByStructureAndCategoryList(Structure structure, String JavaDoc categoryInodelist, List JavaDoc conditionFields,
800             String JavaDoc searchCondition, String JavaDoc orderFieldName, String JavaDoc direction, int offset, int maxResults) {
801
802         List JavaDoc<Field> fields = FieldsCache.getFieldsByStructureInode(structure.getInode());
803
804         Field theField = null;
805         for (Field f : fields) {
806             if (f.getFieldName().equals(orderFieldName)) {
807                 theField = f;
808                 break;
809             }
810         }
811
812         if (theField == null)
813             return new ArrayList JavaDoc<Contentlet>();
814
815         String JavaDoc condition = "";
816
817         condition = " live=" + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " and deleted = "
818                 + com.dotmarketing.db.DbConnectionFactory.getDBFalse() + " and structure_inode = " + structure.getInode();
819
820         DotHibernate dh = new DotHibernate(Contentlet.class);
821
822         StringBuffer JavaDoc query = new StringBuffer JavaDoc();
823         query.append("select {contentlet.*} from contentlet contentlet, inode contentlet_1_ where contentlet.inode = contentlet_1_.inode and ");
824         query.append(condition);
825
826         if (UtilMethods.isSet(categoryInodelist)) {
827             query.append(" and contentlet.inode in (select child from tree where tree.parent in(" + categoryInodelist + " ) )");
828         }
829         if (UtilMethods.isSet(searchCondition)) {
830             query.append(" and (");
831             int counter = 0;
832             for (Object JavaDoc fieldName : conditionFields) {
833                 counter = counter + 1;
834                 Field theSearchField = null;
835                 for (Field f : fields) {
836                     if (f.getFieldName().equals((String JavaDoc) fieldName)) {
837                         theSearchField = f;
838                         query.append(theSearchField.getFieldContentlet() + " like '%" + searchCondition + "%'");
839                         if (conditionFields.size() != 1 && counter < conditionFields.size()) {
840                             query.append(" or ");
841                         }
842                         break;
843                     }
844                 }
845             }
846             query.append(" )");
847         }
848
849         if (UtilMethods.isSet(theField.getFieldContentlet()))
850             query.append(" order by " + theField.getFieldContentlet() + " " + direction);
851
852         dh.setSQLQuery(query.toString());
853
854         dh.setFirstResult(offset);
855         if (maxResults > 0)
856             dh.setMaxResults(maxResults);
857
858         return dh.list();
859
860     }
861
862     public static List JavaDoc<Contentlet> getContentsByStructureCategoryListAndCondition(Structure structure, String JavaDoc categoryInodelist,
863             String JavaDoc searchCondition, String JavaDoc orderFieldName, String JavaDoc direction, int offset, int maxResults) {
864
865         List JavaDoc<Field> fields = FieldsCache.getFieldsByStructureInode(structure.getInode());
866
867         Field theField = null;
868         for (Field f : fields) {
869             if (f.getFieldName().equals(orderFieldName)) {
870                 theField = f;
871                 break;
872             }
873         }
874
875         if (theField == null)
876             return new ArrayList JavaDoc<Contentlet>();
877
878         DotHibernate dh = new DotHibernate(Contentlet.class);
879
880         StringBuffer JavaDoc query = new StringBuffer JavaDoc();
881         query.append("select {contentlet.*} from contentlet contentlet, inode contentlet_1_ where contentlet.inode = contentlet_1_.inode ");
882
883         if (UtilMethods.isSet(searchCondition))
884             query.append(" and " + searchCondition);
885
886         if (UtilMethods.isSet(categoryInodelist)) {
887             query.append(" and contentlet.inode in (select child from tree where tree.parent in (" + categoryInodelist + " ) )");
888         }
889
890         if (UtilMethods.isSet(theField.getFieldContentlet()))
891             query.append(" order by " + theField.getFieldContentlet() + " " + direction);
892
893         dh.setSQLQuery(query.toString());
894
895         dh.setFirstResult(offset);
896         if (maxResults > 0)
897             dh.setMaxResults(maxResults);
898
899         return dh.list();
900
901     }
902
903     public static int getContentletByCategoriesCount(String JavaDoc structureType, String JavaDoc categoriesInodes, List JavaDoc conditionFields, String JavaDoc searchCondition) {
904         DotConnect dc = new DotConnect();
905         Structure structure = StructureFactory.getStructureByType(structureType);
906         StringBuffer JavaDoc sqlQuery = new StringBuffer JavaDoc();
907         sqlQuery.append("SELECT count(*) as count FROM contentlet, inode contentlet_1_ ");
908         sqlQuery.append("WHERE contentlet.inode = contentlet_1_.inode and contentlet.live = " + com.dotmarketing.db.DbConnectionFactory.getDBTrue()
909                 + " and contentlet.deleted = " + com.dotmarketing.db.DbConnectionFactory.getDBFalse());
910         sqlQuery.append(" and structure_inode = " + structure.getInode());
911         if (UtilMethods.isSet(categoriesInodes)) {
912             sqlQuery.append(" and contentlet.inode in (select child from tree where tree.parent in(" + categoriesInodes + " ) )");
913         }
914
915         if (UtilMethods.isSet(searchCondition)) {
916             sqlQuery.append(" and (");
917             int counter = 0;
918             List JavaDoc<Field> fields = FieldsCache.getFieldsByStructureInode(structure.getInode());
919             for (Object JavaDoc fieldName : conditionFields) {
920                 counter = counter + 1;
921                 Field theSearchField = null;
922                 for (Field f : fields) {
923                     if (f.getFieldName().equals((String JavaDoc) fieldName)) {
924                         theSearchField = f;
925                         sqlQuery.append(theSearchField.getFieldContentlet() + " like '%" + searchCondition + "%'");
926                         if (conditionFields.size() != 1 && counter < conditionFields.size()) {
927                             sqlQuery.append(" or ");
928                         }
929                         break;
930                     }
931                 }
932
933             }
934             sqlQuery.append(" )");
935         }
936
937         dc.setSQL(sqlQuery.toString());
938
939         ArrayList JavaDoc list = dc.getResults();
940         return Integer.parseInt((String JavaDoc) ((Map JavaDoc) list.get(0)).get("count"));
941     }
942
943     public static final java.util.List JavaDoc<Contentlet> getContentletsByStuctureAndFieldsValues(Structure st, Map JavaDoc<String JavaDoc, String JavaDoc> fieldsMap) {
944
945         StringBuffer JavaDoc fieldsCondition = new StringBuffer JavaDoc();
946
947         List JavaDoc<Field> fields = FieldsCache.getFieldsByStructureInode(st.getInode());
948
949         for (Field f : fields) {
950             if (fieldsMap.containsKey(f.getFieldName())) {
951                 fieldsCondition.append("and " + f.getFieldContentlet() + " = '" + UtilMethods.sqlify(fieldsMap.get(f.getFieldName())) + "'");
952             }
953         }
954
955         String JavaDoc condition = "";
956
957         condition = " live=" + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " and deleted = "
958                 + com.dotmarketing.db.DbConnectionFactory.getDBFalse() + " and structure_inode = " + st.getInode() + " " + fieldsCondition;
959
960         DotHibernate dh = new DotHibernate(Contentlet.class);
961
962         String JavaDoc query = "select {contentlet.*} from contentlet, inode contentlet_1_ " + "where contentlet.inode = contentlet_1_.inode and "
963                 + condition;
964
965         dh.setSQLQuery(query);
966
967         return dh.list();
968     }
969
970     @SuppressWarnings JavaDoc("unchecked")
971     public static List JavaDoc<Map JavaDoc> getContentletReferences(Contentlet cont) {
972         List JavaDoc<Map JavaDoc> results = new ArrayList JavaDoc<Map JavaDoc>();
973         Identifier id = IdentifierFactory.getIdentifierByInode(cont);
974         if (id.getInode() == 0)
975             return results;
976         List JavaDoc<MultiTree> trees = MultiTreeFactory.getMultiTreeByChild(id);
977         for (MultiTree tree : trees) {
978             HTMLPage page = (HTMLPage) IdentifierFactory.getWorkingChildOfClass(InodeFactory.getInode(tree.getParent1(), Identifier.class),
979                     HTMLPage.class);
980             Container container = (Container) IdentifierFactory.getWorkingChildOfClass(InodeFactory.getInode(tree.getParent2(), Identifier.class),
981                     Container.class);
982             if (page.getInode() > 0 && container.getInode() > 0) {
983                 Map JavaDoc<String JavaDoc, Object JavaDoc> map = new HashMap JavaDoc<String JavaDoc, Object JavaDoc>();
984                 map.put("page", page);
985                 map.put("container", container);
986                 results.add(map);
987             }
988         }
989         return results;
990     }
991
992     public static void setFieldValue(Contentlet content, String JavaDoc fieldName, Object JavaDoc fieldValue) {
993         Structure structure = StructureFactory.getStructureByInode(content.getStructureInode());
994         Field theField = null;
995         List JavaDoc<Field> fields = FieldsCache.getFieldsByStructureInode(structure.getInode());
996         for (Field field : fields) {
997             if (field.getFieldName().equals(fieldName)) {
998                 theField = field;
999                 break;
1000            }
1001        }
1002        if (theField == null)
1003            return;
1004        try {
1005            StringBuffer JavaDoc methodName = new StringBuffer JavaDoc("set");
1006            Object JavaDoc fieldValueObject = fieldValue;
1007
1008            methodName.append(theField.getFieldContentlet().substring(0, 1).toUpperCase());
1009            methodName.append(theField.getFieldContentlet().substring(1, theField.getFieldContentlet().length()));
1010
1011            if (fieldValueObject instanceof String JavaDoc) {
1012                Method JavaDoc m = content.getClass().getMethod(methodName.toString(), new Class JavaDoc[] { String JavaDoc.class });
1013                m.invoke(content, new Object JavaDoc[] { fieldValueObject });
1014            }
1015
1016            else if (fieldValueObject instanceof Date JavaDoc) {
1017                Method JavaDoc m = content.getClass().getMethod(methodName.toString(), new Class JavaDoc[] { Date JavaDoc.class });
1018                m.invoke(content, new Object JavaDoc[] { fieldValueObject });
1019            } else if (fieldValueObject instanceof Float JavaDoc) {
1020                Method JavaDoc m = content.getClass().getMethod(methodName.toString(), new Class JavaDoc[] { Float.TYPE });
1021                m.invoke(content, new Object JavaDoc[] { fieldValueObject });
1022
1023            } else if (fieldValueObject instanceof Long JavaDoc || fieldValueObject instanceof Integer JavaDoc) {
1024                Method JavaDoc m = content.getClass().getMethod(methodName.toString(), new Class JavaDoc[] { Long.TYPE });
1025                m.invoke(content, new Object JavaDoc[] { fieldValueObject });
1026
1027            } else if (fieldValueObject instanceof Boolean JavaDoc) {
1028                Method JavaDoc m = content.getClass().getMethod(methodName.toString(), new Class JavaDoc[] { Boolean.TYPE });
1029                m.invoke(content, new Object JavaDoc[] { fieldValueObject });
1030
1031            }
1032
1033        } catch (Exception JavaDoc e) {
1034            Logger.error(ContentletFactory.class, e.getMessage(), e);
1035            return;
1036        }
1037    }
1038    
1039    @SuppressWarnings JavaDoc("unchecked")
1040    public static void cleanContentletsField(Structure structure, Field field){
1041        List JavaDoc<Contentlet> contentList = getContentletsByStructure(structure.getInode());
1042        
1043        Object JavaDoc fieldValue = null;
1044        
1045        if(field.getFieldContentlet().indexOf("bool") != -1){
1046            fieldValue = Boolean.valueOf(false);
1047        }else if(field.getFieldContentlet().indexOf("date") != -1){
1048            fieldValue = new Date JavaDoc();
1049        }else if(field.getFieldContentlet().indexOf("float") != -1){
1050            fieldValue = Float.valueOf(0);
1051        }else if(field.getFieldContentlet().indexOf("integer") != -1){
1052            fieldValue = Integer.valueOf(0);
1053        }else if(field.getFieldContentlet().indexOf("text") != -1){
1054            fieldValue = new String JavaDoc();
1055        }
1056        
1057        for(Contentlet content : contentList){
1058            
1059            setFieldValue(content, field.getFieldName(), fieldValue);
1060            InodeFactory.saveInode(content);
1061        }
1062    }
1063
1064    public static Date JavaDoc calculateNextReviewDate(String JavaDoc reviewInterval) {
1065        return calculateNextReviewDate(new Date JavaDoc(), reviewInterval);
1066    }
1067
1068    public static Date JavaDoc calculateNextReviewDate(Date JavaDoc baseDate, String JavaDoc reviewInterval) {
1069        Pattern JavaDoc p = Pattern.compile("(\\d+)([dmy])");
1070        Matcher JavaDoc m = p.matcher(reviewInterval);
1071        boolean b = m.matches();
1072        GregorianCalendar JavaDoc cal = new GregorianCalendar JavaDoc();
1073        cal.setTime(baseDate);
1074        if (b) {
1075            int num = Integer.parseInt(m.group(1));
1076            String JavaDoc qual = m.group(2);
1077            if (qual.equals("d")) {
1078                cal.add(GregorianCalendar.DATE, num);
1079            }
1080            if (qual.equals("m")) {
1081                cal.add(GregorianCalendar.MONTH, num);
1082            }
1083            if (qual.equals("y")) {
1084                cal.add(GregorianCalendar.YEAR, num);
1085            }
1086        }
1087        return cal.getTime();
1088    }
1089
1090    // LUCENE INDEX RELATED METHODS
1091

1092    // LUCENE INDEX SEARCH METHODS
1093
/**
1094     * Makes a lucene index search
1095     *
1096     * @param st
1097     * Content Structure you are looking for
1098     * @param keywords
1099     * Keywords to match against structure fields
1100     * @param deleted
1101     * Show only deleted contentlets
1102     * @param sortBy
1103     * Sort by this field (can be the structure logical field name or
1104     * the db name)
1105     * @param fieldsAnd
1106     * If true applies and conditions between all the fields of the
1107     * structure
1108     * @param categoriesAnd
1109     * If true applies and conditions between all the categories
1110     * @return A LuceneHits object with the matches
1111     */

1112    public static LuceneHits indexSearch(Structure st, String JavaDoc keywords, boolean deleted, String JavaDoc sortBy, boolean fieldsAnd, boolean categoriesAnd) {
1113        return indexSearch(st, keywords, deleted, -1, -1, sortBy, fieldsAnd, categoriesAnd);
1114    }
1115
1116    /**
1117     * Makes a lucene index search
1118     *
1119     * @param st
1120     * Content Structure you are looking for
1121     * @param keywords
1122     * Keywords to match against structure fields
1123     * @param deleted
1124     * Show only deleted contentlets
1125     * @param offset
1126     * Starting point of the search
1127     * @param limit
1128     * Max number of contents to retrieve
1129     * @param sortBy
1130     * Sort by this field (can be the structure logical field name or
1131     * the db name)
1132     * @param fieldsAnd
1133     * If true applies and conditions between all the fields of the
1134     * structure
1135     * @param categoriesAnd
1136     * If true applies and conditions between all the categories
1137     * @return A LuceneHits object with the matches
1138     */

1139    public static LuceneHits indexSearch(Structure st, String JavaDoc keywords, boolean deleted, int offset, int limit, String JavaDoc sortBy, boolean fieldsAnd,
1140            boolean categoriesAnd) {
1141        return indexSearch(st, keywords, new ArrayList JavaDoc<String JavaDoc>(), deleted, offset, limit, sortBy, fieldsAnd, categoriesAnd);
1142    }
1143
1144    /**
1145     * Makes a lucene index search
1146     *
1147     * @param st
1148     * Content Structure you are looking for
1149     * @param keywords
1150     * Keywords to match against structure fields
1151     * @param categories
1152     * A string array of categories inodes to filter the search
1153     * @param deleted
1154     * Show only deleted contentlets
1155     * @param offset
1156     * Starting point of the search
1157     * @param limit
1158     * Max number of contents to retrieve
1159     * @param sortBy
1160     * Sort by this field (can be the structure logical field name or
1161     * the db name)
1162     * @param fieldsAnd
1163     * If true applies and conditions between all the fields of the
1164     * structure
1165     * @param categoriesAnd
1166     * If true applies and conditions between all the categories
1167     * @return A LuceneHits object with the matches
1168     */

1169    public static LuceneHits indexSearch(Structure st, String JavaDoc keywords, List JavaDoc<String JavaDoc> categories, boolean deleted, int offset, int limit,
1170            String JavaDoc sortBy, boolean fieldsAnd, boolean categoriesAnd) {
1171
1172        Map JavaDoc<String JavaDoc, String JavaDoc> keywordsMap = new HashMap JavaDoc<String JavaDoc, String JavaDoc>();
1173        List JavaDoc<Field> fields = FieldsCache.getFieldsByStructureInode(st.getInode());
1174        for (Field f : fields) {
1175            if (f.isIndexed()) {
1176                keywordsMap.put(f.getFieldContentlet(), keywords);
1177            }
1178        }
1179
1180        return indexSearch(st, keywordsMap, true, categories, deleted, offset, limit, sortBy, fieldsAnd, categoriesAnd);
1181
1182    }
1183
1184    /**
1185     * Makes a lucene index search
1186     *
1187     * @param st
1188     * Content Structure you are looking for
1189     * @param fieldsSearch
1190     * Map of fields name and keywords to match againsts
1191     * @param categories
1192     * A string array of categories inodes to filter the search
1193     * @param deleted
1194     * Show only deleted contentlets
1195     * @param offset
1196     * Starting point of the search
1197     * @param limit
1198     * Max number of contents to retrieve
1199     * @param fieldsAnd
1200     * If true applies and conditions between the fields provided
1201     * @param categoriesAnd
1202     * If true applies and conditions between all the categories
1203     * @param sortBy
1204     * Sort by this field (can be the structure logical field name or
1205     * the db name)
1206     * @return A LuceneHits object with the matches
1207     */

1208    public static LuceneHits indexSearch(Structure st, Map JavaDoc fieldsSearch, List JavaDoc<String JavaDoc> categories, boolean deleted, int offset, int limit,
1209            String JavaDoc sortBy, boolean fieldsAnd, boolean categoriesAnd) {
1210        return indexSearch(st, fieldsSearch, false, categories, deleted, offset, limit, sortBy, fieldsAnd, categoriesAnd);
1211    }
1212
1213    /**
1214     * Makes a lucene index search
1215     *
1216     * @param st
1217     * Content Structure you are looking for
1218     * @param keywords
1219     * Keywords to search
1220     * @param categories
1221     * Categories to match
1222     * @param deleted
1223     * Search deleted contents only
1224     * @param offset
1225     * Start index of the search
1226     * @param limit
1227     * Max number of matches to retrieve
1228     * @param searchfield
1229     * Structure field to use for the search
1230     * @param sortBy
1231     * Sort by this field (can be the structure logical field name or
1232     * the db name)
1233     * @param fieldsAnd
1234     * If true applies and conditions between all the fields of the
1235     * structure
1236     * @param categoriesAnd
1237     * If true applies and conditions between all the categories
1238     * @return A LuceneHits object with the matches
1239     */

1240
1241    public static LuceneHits indexSearchByField(Structure st, String JavaDoc keywords, List JavaDoc<String JavaDoc> categories, boolean deleted, int offset, int limit,
1242            String JavaDoc searchfield, String JavaDoc sortBy, boolean fieldsAnd, boolean categoriesAnd) {
1243
1244        Map JavaDoc<String JavaDoc, String JavaDoc> keywordsMap = new HashMap JavaDoc<String JavaDoc, String JavaDoc>();
1245        keywordsMap.put(searchfield, keywords);
1246
1247        return indexSearch(st, keywordsMap, false, categories, deleted, offset, limit, sortBy, fieldsAnd, categoriesAnd);
1248    }
1249
1250    /**
1251     * Makes a lucene index search
1252     *
1253     * @param st
1254     * Content Structure you are looking for
1255     * @param fieldsSearch
1256     * Map of fields name and keywords to match againsts
1257     * @param categories
1258     * A string array of categories inodes to filter the search
1259     * @param deleted
1260     * Show only deleted contentlets
1261     * @param offset
1262     * Starting point of the search
1263     * @param limit
1264     * Max number of contents to retrieve
1265     * @param sortBy
1266     * Sort by this field (can be the structure logical field name or
1267     * the db name)
1268     * @param fieldsAnd
1269     * If true applies and conditions between the fields provided
1270     * @param categoriesAnd
1271     * If true applies and conditions between all the categories
1272     * @return A LuceneHits object with the matches
1273     */

1274    public static LuceneHits indexSearch(Structure st, Map JavaDoc fieldsSearch, boolean usingDBNames, List JavaDoc<String JavaDoc> categories, boolean deleted, int offset,
1275            int limit, String JavaDoc sortBy, boolean fieldsAnd, boolean categoriesAnd) {
1276
1277        LuceneHits hits = new LuceneHits();
1278        try {
1279
1280            BooleanQuery booleanQuery = new BooleanQuery();
1281
1282            if (fieldsSearch.containsKey("languageId")) {
1283                LuceneUtils.addRequiredQueryTerm(booleanQuery, "languageId", ((String JavaDoc) fieldsSearch.get("languageId")).trim(), false);
1284            }
1285            if (fieldsSearch.containsKey("identifier")) {
1286                LuceneUtils.addRequiredQueryTerm(booleanQuery, "identifier", ((String JavaDoc) fieldsSearch.get("identifier")).trim(), false);
1287            }
1288
1289            if (fieldsSearch.size() > 0) {
1290                BooleanQuery innerQuery = new BooleanQuery();
1291
1292                if (st != null && st.getInode() > 0) {
1293                    List JavaDoc<Field> fields = FieldsCache.getFieldsByStructureInode(st.getInode());
1294                    for (Field f : fields) {
1295                        if (usingDBNames) {
1296                            if (fieldsSearch.containsKey(f.getFieldContentlet())) {
1297                                String JavaDoc fieldName = f.getFieldContentlet();
1298                                String JavaDoc fieldValue = (String JavaDoc) fieldsSearch.get(f.getFieldContentlet());
1299                                if (fieldsAnd) {
1300                                    if (!fieldName.startsWith("date"))
1301                                        LuceneUtils.addRequiredQueryTerm(innerQuery, fieldName, fieldValue, true);
1302                                    else
1303                                        LuceneUtils.addRequiredDateTerm(innerQuery, fieldName, fieldValue);
1304                                } else {
1305                                    if (!fieldName.startsWith("date"))
1306                                        LuceneUtils.addQueryTerm(innerQuery, fieldName, fieldValue);
1307                                    else
1308                                        LuceneUtils.addDateTerm(innerQuery, fieldName, fieldValue);
1309                                }
1310                            }
1311                        } else {
1312                            if (fieldsSearch.containsKey(f.getFieldName())) {
1313                                String JavaDoc fieldName = f.getFieldContentlet();
1314                                String JavaDoc fieldValue = (String JavaDoc) fieldsSearch.get(f.getFieldName());
1315                                if (fieldsAnd) {
1316                                    if (!fieldName.startsWith("date"))
1317                                        LuceneUtils.addRequiredQueryTerm(innerQuery, fieldName, fieldValue, true);
1318                                    else
1319                                        LuceneUtils.addRequiredDateTerm(innerQuery, fieldName, fieldValue);
1320                                } else {
1321                                    if (!fieldName.startsWith("date"))
1322                                        LuceneUtils.addQueryTerm(innerQuery, fieldName, fieldValue);
1323                                    else
1324                                        LuceneUtils.addDateTerm(innerQuery, fieldName, fieldValue);
1325                                }
1326                            }
1327                        }
1328                    }
1329                }
1330
1331                if (!innerQuery.toString().equals("")) {
1332                    booleanQuery.add(innerQuery, BooleanClause.Occur.MUST);
1333                }
1334            }
1335
1336            if (categories.size() > 0) {
1337                BooleanQuery innerQuery = new BooleanQuery();
1338
1339                for (String JavaDoc catInode : categories) {
1340                    if (UtilMethods.isSet(catInode) && !catInode.equals("0"))
1341                        try {
1342                            Integer.parseInt(catInode);
1343                            if (categoriesAnd)
1344                                LuceneUtils.addRequiredQueryTerm(innerQuery, "c" + catInode + "c", "on", false);
1345                            else
1346                                LuceneUtils.addQueryTerm(innerQuery, "c" + catInode + "c", "on");
1347                        } catch (NumberFormatException JavaDoc e) {
1348                        }
1349                }
1350
1351                if (UtilMethods.isSet(innerQuery.toString())) {
1352                    booleanQuery.add(innerQuery, BooleanClause.Occur.MUST);
1353                }
1354            }
1355
1356            if (!usingDBNames) {
1357                boolean desc = false;
1358                String JavaDoc compField;
1359                if (sortBy.endsWith("desc")) {
1360                    desc = true;
1361                    compField = sortBy.substring(0, sortBy.indexOf("desc")).trim();
1362                } else if (sortBy.endsWith("asc")) {
1363                    compField = sortBy.substring(0, sortBy.indexOf("asc")).trim();
1364                } else
1365                    compField = sortBy.trim();
1366                if (!compField.equals("moddate")) {
1367                    Field sortField = FieldFactory.getFieldByName(st.getInode(), compField);
1368                    if (sortField.getInode() > 0) {
1369                        sortBy = sortField.getFieldContentlet();
1370                        if (desc)
1371                            sortBy = sortBy + " desc";
1372                    }
1373                }
1374            }
1375
1376            hits = indexSearch(st, booleanQuery.toString(), deleted, offset, limit, sortBy);
1377
1378            return hits;
1379        } catch (Exception JavaDoc ex) {
1380            Logger.error(ContentletFactory.class, "indexSearch: Error Searching Contentlets - fieldSearch: " + fieldsSearch + ", deleted = "
1381                    + deleted, ex);
1382            return hits;
1383        }
1384    }
1385
1386    public static LuceneHits indexSearch(Structure st, String JavaDoc query, boolean deleted, int offset, int limit, String JavaDoc sortBy) {
1387
1388        LuceneHits hits = new LuceneHits();
1389        try {
1390
1391            query = LuceneUtils.findAndReplaceQueryDates(query);
1392
1393            BooleanQuery booleanQuery = new BooleanQuery();
1394
1395            LuceneUtils.addRequiredQueryTerm(booleanQuery, "type", "content", false);
1396            LuceneUtils.addRequiredQueryTerm(booleanQuery, "deleted", ((Boolean JavaDoc) deleted).toString(), false);
1397            LuceneUtils.addRequiredQueryTerm(booleanQuery, "structureInode", st.getInode() + "", false);
1398
1399// QueryParser parser = new QueryParser("", new WhitespaceAnalyzer());
1400
QueryParser parser = new QueryParser("", new DotAnalyzer());
1401            
1402            if (UtilMethods.isSet(query)) {
1403                Query luceneQuery = parser.parse(query);
1404                booleanQuery.add(luceneQuery, BooleanClause.Occur.MUST);
1405            }
1406
1407            Query finalQuery = parser.parse(booleanQuery.toString());
1408
1409            hits = LuceneUtils.searchInCurrentIndex(finalQuery, offset, limit, sortBy);
1410
1411            hits.setLuceneQuery(finalQuery.toString());
1412
1413        } catch (Exception JavaDoc ex) {
1414            Logger.error(ContentletFactory.class, "indexSearch: Error Searching Contentlets - lucene query: " + query + ", deleted = " + deleted, ex);
1415        }
1416        return hits;
1417    }
1418
1419    @SuppressWarnings JavaDoc("unchecked")
1420    public static LuceneHits getContentsByStructureAndCategoryListWithLucene(Structure structure, String JavaDoc categoryInodelist, String JavaDoc searchCondition,
1421            String JavaDoc orderFieldName, int offset, int maxResults) {
1422
1423        List JavaDoc<String JavaDoc> categoriesList = new ArrayList JavaDoc();
1424        if (UtilMethods.isSet(categoryInodelist)) {
1425
1426            StringTokenizer JavaDoc token = new StringTokenizer JavaDoc(categoryInodelist, ",");
1427            while (token.hasMoreElements()) {
1428                categoriesList.add(token.nextToken());
1429            }
1430
1431        }
1432
1433        if (!UtilMethods.isSet(searchCondition)) {
1434            searchCondition = "";
1435        }
1436
1437        return indexSearch(structure, searchCondition, categoriesList, false, offset, maxResults, orderFieldName, false, true);
1438
1439    }
1440
1441    // LUCENE INDEX UPDATE/WRITE METHODS
1442

1443    public static boolean shuttingDown = false;
1444
1445    @SuppressWarnings JavaDoc("unchecked")
1446    private static Document getLuceneDocumentForContentlet(Contentlet contentlet) {
1447        Document doc = new Document();
1448        boolean MSSQL = DbConnectionFactory.getDBType().equals(DbConnectionFactory.MSSQL);
1449        try {
1450            if (contentlet.getInode() > 0) {
1451
1452                // Field properties
1453
long structureInode = contentlet.getStructureInode();
1454                if (structureInode > 0) {
1455                    List JavaDoc<Field> fields = null;
1456                    Structure st = null;
1457
1458                    st = StructureCache.getStructureByInode(structureInode);
1459                    fields = FieldsCache.getFieldsByStructureInode(st.getInode());
1460
1461                    for (Field f : fields) {
1462                        if (f.isIndexed()) {
1463                            try {
1464                                Object JavaDoc valueObj = ContentletFactory.getFieldValue(contentlet, f);
1465                                if (valueObj instanceof Date JavaDoc) {
1466                                    if (valueObj != null) {
1467                                        doc.add(LuceneUtils.getDateField(f.getFieldContentlet(), ((Date JavaDoc) valueObj)));
1468                                    }
1469                                } else {
1470                                    if (valueObj != null) {
1471                                        if(f.getFieldType().equals("checkbox") || f.getFieldType().equals("multi_select"))
1472                                            doc.add(LuceneUtils.getIndexedField(f.getFieldContentlet(), UtilMethods.listToString(valueObj.toString())));
1473                                        else
1474                                            doc.add(LuceneUtils.getIndexedField(f.getFieldContentlet(), valueObj.toString()));
1475                                    }
1476                                }
1477                            } catch (Exception JavaDoc e) {
1478                                Logger.warn(ContentletFactory.class, "Error indexing field: " + f.getFieldName() + " of contentlet: "
1479                                        + contentlet.getInode(), e);
1480                            }
1481                        } else {
1482                            try {
1483                                Object JavaDoc valueObj = ContentletFactory.getFieldValue(contentlet, f);
1484                                if (valueObj instanceof Date JavaDoc) {
1485                                    if (valueObj != null) {
1486                                        org.apache.lucene.document.Field lf = LuceneUtils.getUnIndexedField(f.getFieldContentlet(), LuceneUtils
1487                                                .toLuceneDate((Date JavaDoc) valueObj));
1488                                        doc.add(lf);
1489                                    }
1490                                } else {
1491                                    if (valueObj != null) {
1492                                        doc.add(new org.apache.lucene.document.Field(f.getFieldContentlet(), valueObj.toString(),
1493                                                org.apache.lucene.document.Field.Store.YES, org.apache.lucene.document.Field.Index.NO));
1494                                    }
1495                                }
1496                            } catch (Exception JavaDoc e) {
1497                                Logger.warn(ContentletFactory.class, "Error indexing field: " + f.getFieldName() + " of contentlet: "
1498                                        + contentlet.getInode(), e);
1499                            }
1500                        }
1501                    }
1502                }
1503
1504                // Add contentlet categories to the index
1505
List JavaDoc<Category> categories = null;
1506                if (MSSQL) {
1507                    categories = InodeFactory.getParentsOfClassNoLock(contentlet, Category.class);
1508                } else {
1509                    categories = InodeFactory.getParentsOfClass(contentlet, Category.class);
1510                }
1511
1512                for (Category category : categories) {
1513                    List JavaDoc<Category> parentsCategories = null;
1514                    if (MSSQL) {
1515                        parentsCategories = InodeFactory.getParentsOfClassNoLock(category, Category.class);
1516                    } else {
1517                        parentsCategories = InodeFactory.getParentsOfClass(category, Category.class);
1518                    }
1519
1520                    for (Category parentCategory : parentsCategories) {
1521                        doc.add(new org.apache.lucene.document.Field("c" + parentCategory.getInode() + "c", "on",
1522                                org.apache.lucene.document.Field.Store.YES, org.apache.lucene.document.Field.Index.UN_TOKENIZED));
1523                    }
1524                    doc.add(new org.apache.lucene.document.Field("c" + category.getInode() + "c", "on", org.apache.lucene.document.Field.Store.YES,
1525                            org.apache.lucene.document.Field.Index.UN_TOKENIZED));
1526                }
1527
1528                // Other Properties to show in the listing
1529
doc.add(LuceneUtils.getKeywordField("inode", ((Long JavaDoc) contentlet.getInode()).toString()));
1530                doc.add(LuceneUtils.getKeywordField("type", "content"));
1531                doc.add(LuceneUtils.getDateField("modDate", contentlet.getModDate()));
1532                doc.add(LuceneUtils.getKeywordField("modUser", contentlet.getModUser() == null ? "" : contentlet.getModUser()));
1533                doc.add(LuceneUtils.getKeywordField("working", ((Boolean JavaDoc) contentlet.isWorking()).toString()));
1534                doc.add(LuceneUtils.getKeywordField("live", ((Boolean JavaDoc) contentlet.isLive()).toString()));
1535                doc.add(LuceneUtils.getKeywordField("deleted", ((Boolean JavaDoc) contentlet.isDeleted()).toString()));
1536                doc.add(LuceneUtils.getKeywordField("locked", ((Boolean JavaDoc) contentlet.isLocked()).toString()));
1537                doc.add(LuceneUtils.getKeywordField("structureInode", ((Long JavaDoc) contentlet.getStructureInode()).toString()));
1538                doc.add(LuceneUtils.getKeywordField("languageId", ((Long JavaDoc) contentlet.getLanguageId()).toString()));
1539                if(contentlet.getIdentifier() > 0){
1540                    doc.add(LuceneUtils.getKeywordField("identifier", String.valueOf(contentlet.getIdentifier())));
1541                }
1542                
1543                else if (MSSQL) {
1544                    doc.add(LuceneUtils.getKeywordField("identifier", ((Long JavaDoc) IdentifierFactory.getIdentifierByInodeNoLock(contentlet).getInode())
1545                            .toString()));
1546                } else {
1547                    doc.add(LuceneUtils.getKeywordField("identifier", ((Long JavaDoc) IdentifierCache.getIdentifierByInodeFromCache(contentlet).getInode()).toString()));
1548                }
1549
1550                if (MSSQL) {
1551                    List JavaDoc<Permission> permissions = PermissionFactory.getPermissionsNoLock(contentlet);
1552                    doc.add(LuceneUtils.getIndexedField("permissions", PermissionFactory.permissionsToString(permissions)));
1553                } else {
1554                    List JavaDoc<Permission> permissions = PermissionCache.getPermissionsFromCache(contentlet);
1555                    doc.add(LuceneUtils.getIndexedField("permissions", PermissionFactory.permissionsToString(permissions)));
1556                }
1557            }
1558        } catch (Exception JavaDoc e) {
1559            Logger.error(ContentletFactory.class, "Unable to obtain the lucene document for contentlet: " + contentlet.getInode(), e);
1560            e.printStackTrace();
1561        }
1562
1563        return doc;
1564
1565    }
1566
1567    private static synchronized void modifyContentletIndex(Contentlet contentlet, String JavaDoc action) {
1568
1569        // Sanity checks
1570
// If the system is shutting down, do nothing that will kill
1571
// our index
1572
if (shuttingDown || contentlet.getInode() == 0) {
1573            return;
1574        }
1575
1576        Identifier iden = IdentifierCache.getIdentifierByInodeFromCache(contentlet);
1577        Contentlet liveCont = (Contentlet) IdentifierFactory.getLiveChildOfClass(iden, Contentlet.class);
1578        Contentlet workingCont = (Contentlet) IdentifierFactory.getWorkingChildOfClass(iden, Contentlet.class);
1579        
1580        //Indexing the working contentlet
1581
Document doc = getLuceneDocumentForContentlet(workingCont);
1582        if (ADD_TO_INDEX.equals(action)) {
1583            LuceneUtils.removeDocByIdenToCurrentIndex(String.valueOf(iden.getInode()));
1584            LuceneUtils.writeInodeToCurrentIndex(doc);
1585        }
1586        if (ReindexationProcessStatus.inFullReindexation()) {
1587            LuceneUtils.removeDocByIdenToReindexationIndex(String.valueOf(iden.getInode()));
1588            LuceneUtils.writeInodeToReindexationIndex(doc);
1589        }
1590        
1591        //Indexing the live contentlet if it's not the same one as the working one
1592
if(liveCont.getInode() != workingCont.getInode() && liveCont.getInode() > 0) {
1593            doc = getLuceneDocumentForContentlet(liveCont);
1594            if (ADD_TO_INDEX.equals(action))
1595                LuceneUtils.writeInodeToCurrentIndex(doc);
1596            if (ReindexationProcessStatus.inFullReindexation())
1597                LuceneUtils.writeInodeToReindexationIndex(doc);
1598        }
1599        
1600    }
1601
1602    public static void reIndexContentlet(Contentlet contentlet) {
1603        boolean log = true;
1604        reIndexContentlet(contentlet, log);
1605    }
1606
1607    public static void reIndexContentlet(Contentlet contentlet, boolean log) {
1608
1609        modifyContentletIndex(contentlet, ADD_TO_INDEX);
1610        if (log) {
1611            long objectToIndex = contentlet.getInode();
1612            _logIndexation(objectToIndex);
1613        }
1614    }
1615
1616    public static boolean reIndexAllContentletsByStructure(Structure st) {
1617        boolean log = true;
1618        return reIndexAllContentletsByStructure(st, log);
1619    }
1620
1621    public synchronized static boolean reIndexAllContentletsByStructure(Structure st, boolean log) {
1622        if (st != null) {
1623            ReindexerThread thread = new ContentletFactory().new ReindexerThread(st);
1624            thread.start();
1625        } else {
1626            if (ReindexationProcessStatus.inFullReindexation())
1627                return false;
1628            ReindexerThread thread = new ContentletFactory().new ReindexerThread();
1629            thread.start();
1630        }
1631        if (log) {
1632            if (st != null) {
1633                long objectToIndex = st.getInode();
1634                _logIndexation(objectToIndex);
1635            } else {
1636                long objectToIndex = 0;
1637                _logIndexation(objectToIndex);
1638            }
1639        }
1640        return true;
1641    }
1642
1643    public static boolean reIndexAllContentlets() {
1644        boolean log = true;
1645        return reIndexAllContentlets(log);
1646    }
1647
1648    public static boolean reIndexAllContentlets(boolean log) {
1649        return reIndexAllContentletsByStructure(null, log);
1650    }
1651
1652    private class ReindexerThread extends Thread JavaDoc {
1653
1654        private Structure st = null;
1655
1656        public ReindexerThread(Structure st) {
1657            super("Structure Reindexer Thread " + st.getName() + " - " + st.getInode());
1658            this.st = st;
1659        }
1660
1661        public ReindexerThread() {
1662            super("Full Content Reindexer Thread");
1663        }
1664
1665        public void run() {
1666            if (st == null && ReindexationProcessStatus.inFullReindexation())
1667                return;
1668            else if (st == null) {
1669                ReindexationProcessStatus.setInFullReindexation(true);
1670            }
1671            boolean MSSQL = DbConnectionFactory.getDBType().equals(DbConnectionFactory.MSSQL);
1672            try {
1673                List JavaDoc<Long JavaDoc> contentletsInodes = new ArrayList JavaDoc<Long JavaDoc>();
1674                if (st == null) {
1675                    Logger.info(this, "Full Reindexation started.");
1676                    String JavaDoc condition = "(contentlet.live = " + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " or contentlet.working = "
1677                            + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + ")";
1678
1679                    if (MSSQL) {
1680                        contentletsInodes = ContentletFactory.getContentletsInodesByConditionNoLock(condition);
1681                    } else {
1682                        contentletsInodes = ContentletFactory.getContentletsInodesByCondition(condition);
1683                    }
1684
1685                } else {
1686                    Logger.info(this, "Structure Reindexation started.");
1687                    String JavaDoc condition = "contentlet.structure_inode = " + st.getInode() + " and (contentlet.live = "
1688                            + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " or contentlet.working = "
1689                            + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + ")";
1690
1691                    if (DbConnectionFactory.getDBType().equals(DbConnectionFactory.MSSQL)) {
1692                        contentletsInodes = ContentletFactory.getContentletsInodesByConditionNoLock(condition);
1693                    } else {
1694                        contentletsInodes = ContentletFactory.getContentletsInodesByCondition(condition);
1695                    }
1696                }
1697
1698                boolean go = true;
1699
1700                if (contentletsInodes.size() == 0) {
1701                    Logger.info(ContentletFactory.class, "Nothing found to reindex, reindexing abondoned.");
1702                    go = false;
1703                }
1704                if (st == null) {
1705                    go = LuceneUtils.recreateNewIndexFolder();
1706                    ReindexationProcessStatus.setContentCountToIndex(contentletsInodes.size());
1707                }
1708
1709                if (go) {
1710                    for (Long JavaDoc inode : contentletsInodes) {
1711                        Contentlet cont = null;
1712                        if (MSSQL) {
1713                            cont = ContentletFactory.getContentletNoLock(inode);
1714                        } else {
1715                            cont = ContentletFactory.getContentlet(inode);
1716                        }
1717                        if (cont.getInode() > 0) {
1718                            modifyContentletIndex(cont, ADD_TO_INDEX_REINDEXATION);
1719                            if (st == null)
1720                                ReindexationProcessStatus.updateIndexationProgress(1);
1721                            try {
1722
1723                                Logger.debug(this, "Reindexation thread. Commiting contentlets ");
1724                                sleep(150);
1725                            } catch (InterruptedException JavaDoc e) {
1726                                Logger.error(this, "Error occurred trying to reindex contentlet: " + cont.getInode(), e);
1727                            }
1728                        } else {
1729                            Logger.error(this, "Couldn't find the inode: " + inode + ", database down?, stopping the process!");
1730                        }
1731
1732                    }
1733                    if (st == null) {
1734
1735                        // Checking if the new index has been built correctly
1736
String JavaDoc condition = "(live = " + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " or working = "
1737                                + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + ")";
1738                        int inodesCount = ContentletFactory.getContentletByCondition(condition).size();
1739
1740                        BooleanQuery booleanQuery = new BooleanQuery();
1741                        LuceneUtils.addRequiredQueryTerm(booleanQuery, "type", "content", false);
1742                        
1743// QueryParser parser = new QueryParser("", new StandardAnalyzer());
1744
QueryParser parser = new QueryParser("", new DotAnalyzer());
1745                        
1746                        Query finalQuery = parser.parse(booleanQuery.toString());
1747                        LuceneHits hits = LuceneUtils.searchInReindexationIndex(finalQuery, 0, 0, "");
1748                        if (hits.getTotal() < inodesCount) {
1749                            Logger.warn("The new index documents count doesn't match the real contentlet count. The new index will be discarded.");
1750                            return;
1751                        }
1752
1753                        LuceneUtils.changeToTheNewLuceneDir();
1754
1755                    }
1756                    // Calling optimize method to keep the number of lucene
1757
// files short
1758
LuceneUtils.optimizeCurrentIndex();
1759                }
1760            } catch (Exception JavaDoc e) {
1761                Logger.error("Exception ocurred trying to index all the content", e);
1762            } finally {
1763                DotHibernate.closeSession();
1764                ReindexationProcessStatus.setInFullReindexation(false);
1765            }
1766            if (st == null)
1767                Logger.info(this, "Full reindexation ended.");
1768            else
1769                Logger.info(this, "Structure reindexation ended.");
1770        }
1771    }
1772
1773    private static void _logIndexation(long objectToIndex) {
1774        String JavaDoc[] serversIds = Config.getStringArrayProperty("DIST_INDEXATION_SERVERS_IDS");
1775        String JavaDoc serverId = Config.getStringProperty("DIST_INDEXATION_SERVER_ID");
1776        boolean indexationEnabled = Config.getBooleanProperty("DIST_INDEXATION_ENABLED");
1777        
1778        if (indexationEnabled) {
1779            Date JavaDoc timestamp = IndexationFactory.getDBDate();
1780            for (String JavaDoc serversId : serversIds) {
1781                if (!serverId.equals(serversId)) {
1782                    Indexation indexation = new Indexation();
1783                    indexation.setObjectToIndex(objectToIndex);
1784                    indexation.setTimestamp(timestamp);
1785                    indexation.setServerId(serversId);
1786                    IndexationFactory.saveIndexation(indexation);
1787                }
1788            }
1789        }
1790    }
1791
1792    // END OF LUCENE INDEX RELATED METHODS
1793

1794    @SuppressWarnings JavaDoc("unchecked")
1795    public static final java.util.List JavaDoc<Contentlet> getContentletsByStuctureAndCategoryList(Structure st, List JavaDoc<Category> categories,int quantity, String JavaDoc orderby)
1796    {
1797        String JavaDoc condition = "";
1798        condition = "live=" + DbConnectionFactory.getDBTrue() + " and deleted = " + DbConnectionFactory.getDBFalse() +
1799        " and structure_inode = " + st.getInode();
1800        
1801        long[] categoriesInode = new long[0];
1802        if (categories != null)
1803        {
1804            int size = categories.size();
1805            categoriesInode = new long[size];
1806            for(int i=0; i < size;i++)
1807            {
1808                categoriesInode[i] = categories.get(i).getInode();
1809            }
1810        }
1811        
1812        /*DotHibernate dh = new DotHibernate (Contentlet.class);
1813        
1814        String query = "select";
1815        
1816        if(quantity > 0){
1817            query = query + " top "+quantity;
1818        }
1819        
1820        query = query + " {contentlet.*} from contentlet, inode contentlet_1_, tree " +
1821        "where contentlet.inode = contentlet_1_.inode and contentlet.inode = tree.child and " +
1822        condition + " order by " + orderby;
1823        
1824        dh.setSQLQuery(query);
1825        
1826        if(categories != null && categories.size() > 0){
1827            for(Category cat : categories){
1828                dh.setParam(cat.getInode());
1829            }
1830        }
1831        return dh.list();*/

1832        return InodeFactory.getChildrenClassByConditionAndOrderBy(categoriesInode,Contentlet.class,condition,orderby,quantity);
1833    }
1834
1835    public static void _sendContentletPublishNotification (Contentlet contentlet, HttpServletRequest JavaDoc req) throws PortalException, SystemException {
1836        Map JavaDoc<String JavaDoc, String JavaDoc[]> params = new HashMap JavaDoc<String JavaDoc, String JavaDoc[]> ();
1837        params.put("struts_action", new String JavaDoc [] {"/ext/contentlet/edit_contentlet"});
1838        params.put("cmd", new String JavaDoc [] {"edit"});
1839        params.put("inode", new String JavaDoc [] { String.valueOf(contentlet.getInode()) });
1840        String JavaDoc contentURL = PortletURLUtil.getActionURL(req, WindowState.MAXIMIZED.toString(), params);
1841        List JavaDoc<Map JavaDoc> references = getContentletReferences(contentlet);
1842        List JavaDoc<Map JavaDoc> validReferences = new ArrayList JavaDoc<Map JavaDoc> ();
1843        User currentUser = com.liferay.portal.util.PortalUtil.getUser(req);
1844        for (Map JavaDoc reference : references) {
1845            HTMLPage page = (HTMLPage)reference.get("page");
1846            User pageUser = PublicUserFactory.findUserByUserId(page.getModUser());
1847            if (!pageUser.getUserId().equals(currentUser.getUserId()))
1848                validReferences.add(reference);
1849        }
1850        if (validReferences.size() > 0) {
1851            ContentChangeNotificationThread notificationThread =
1852                (new ContentletFactory()).new ContentChangeNotificationThread (contentlet, validReferences, contentURL, HostFactory.getCurrentHost(req).getHostname());
1853            notificationThread.start();
1854        }
1855    }
1856    
1857    // Contentlet change notifications thread
1858
private class ContentChangeNotificationThread extends Thread JavaDoc {
1859
1860        private String JavaDoc serverName;
1861        private String JavaDoc contentletEditURL;
1862        private Contentlet contentlet;
1863        private List JavaDoc<Map JavaDoc> references;
1864        
1865        public ContentChangeNotificationThread (Contentlet cont, List JavaDoc<Map JavaDoc> references, String JavaDoc contentletEditURL, String JavaDoc serverName) {
1866            super ("ContentChangeNotificationThread");
1867            this.contentletEditURL = contentletEditURL;
1868            this.references = references;
1869            this.serverName = serverName;
1870            contentlet = cont;
1871        }
1872        
1873        @Override JavaDoc
1874        public void run() {
1875            try {
1876                String JavaDoc editorName = UtilMethods.getUserFullName(contentlet.getModUser());
1877                
1878                for (Map JavaDoc reference : references) {
1879                    HTMLPage page = (HTMLPage)reference.get("page");
1880                    String JavaDoc body = "<html><body><p>This is just a note from the dotCMS system to inform you that a " +
1881                            "piece of content you are using on a page you manage has been edited.</p>" +
1882                            "<p/>" +
1883                            "<p>Details:</p>" +
1884                            "<p/>" +
1885                            "<p><b>Content:</b> <a HREF=\"http://" + serverName + contentletEditURL + "\">" + contentlet.getTitle () + "</a></p>" +
1886                            "<p><b>Your Page:</b> <a HREF=\"http://" + serverName + page.getURI() + "\"> " + page.getTitle() + "</a></p>" +
1887                            "<p><b>Edited By:</b> " + editorName + " </p></body></html>";
1888                    User pageUser = PublicUserFactory.findUserByUserId(page.getModUser());
1889                    String JavaDoc fromEmail = Config.getStringProperty("EMAIL_SYSTEM_ADDRESS");
1890                    Mailer mailer = new Mailer();
1891                    mailer.setFromEmail(fromEmail);
1892                    mailer.setToEmail(pageUser.getEmailAddress());
1893                    mailer.setSubject("dotCMS Notification");
1894                    mailer.setHTMLAndTextBody(body);
1895                    mailer.sendMessage();
1896                }
1897            } catch (Exception JavaDoc e) {
1898                Logger.error(this, "Error ocurring trying to send the content change notifications.", e);
1899            } finally {
1900                DotHibernate.closeSession();
1901            }
1902        }
1903    }
1904
1905}
1906
1907
Popular Tags