KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > dotmarketing > portlets > contentlet > ajax > ContentletAjax


1 package com.dotmarketing.portlets.contentlet.ajax;
2
3 import java.io.BufferedInputStream JavaDoc;
4 import java.io.File JavaDoc;
5 import java.io.FileInputStream JavaDoc;
6 import java.util.ArrayList JavaDoc;
7 import java.util.Enumeration JavaDoc;
8 import java.util.HashMap JavaDoc;
9 import java.util.Iterator JavaDoc;
10 import java.util.List JavaDoc;
11 import java.util.Map JavaDoc;
12 import java.util.Properties JavaDoc;
13 import java.util.TreeSet JavaDoc;
14
15 import javax.servlet.http.HttpServletRequest JavaDoc;
16 import javax.servlet.http.HttpSession JavaDoc;
17
18 import org.apache.commons.logging.LogFactory;
19 import org.apache.lucene.document.Document;
20 import org.apache.lucene.queryParser.ParseException;
21 import org.apache.lucene.queryParser.QueryParser;
22
23 import uk.ltd.getahead.dwr.WebContextFactory;
24
25 import com.dotmarketing.cache.FieldsCache;
26 import com.dotmarketing.cms.factories.PublicUserFactory;
27 import com.dotmarketing.factories.IdentifierFactory;
28 import com.dotmarketing.factories.InodeFactory;
29 import com.dotmarketing.lucene.DotAnalyzer;
30 import com.dotmarketing.portlets.contentlet.factories.ContentletFactory;
31 import com.dotmarketing.portlets.contentlet.factories.ReindexationProcessStatus;
32 import com.dotmarketing.portlets.contentlet.model.Contentlet;
33 import com.dotmarketing.portlets.structure.factories.StructureFactory;
34 import com.dotmarketing.portlets.structure.model.Field;
35 import com.dotmarketing.portlets.structure.model.Structure;
36 import com.dotmarketing.util.Config;
37 import com.dotmarketing.util.Logger;
38 import com.dotmarketing.util.LuceneHits;
39 import com.dotmarketing.util.LuceneUtils;
40 import com.dotmarketing.util.UtilMethods;
41 import com.dotmarketing.util.WebKeys;
42 import com.liferay.portal.model.Role;
43 import com.liferay.portal.model.User;
44
45 /**
46  * @author David
47  */

48 public class ContentletAjax {
49
50     private java.text.DateFormat JavaDoc modDateFormat = java.text.DateFormat.getDateTimeInstance(java.text.DateFormat.SHORT,
51             java.text.DateFormat.SHORT);
52
53     public Map JavaDoc<String JavaDoc, String JavaDoc> getContentletData(String JavaDoc inode) {
54         Contentlet cont = (Contentlet) InodeFactory.getInode(inode, Contentlet.class);
55         Structure targetStructure = cont.getStructure();
56         List JavaDoc<Field> targetFields = FieldsCache.getFieldsByStructureInode(targetStructure.getInode());
57         Map JavaDoc<String JavaDoc, String JavaDoc> map = new HashMap JavaDoc<String JavaDoc, String JavaDoc>();
58         for (Field f : targetFields) {
59             if (f.isIndexed() || f.isListed()) {
60                 String JavaDoc fieldName = f.getFieldName();
61                 Object JavaDoc fieldValueObj = com.dotmarketing.portlets.contentlet.factories.ContentletFactory.getFieldValue(
62                         cont, f.getFieldName());
63                 String JavaDoc fieldValue = "";
64                 if (fieldValueObj instanceof java.util.Date JavaDoc) {
65                     if (fieldValueObj != null)
66                         fieldValue = modDateFormat.format(fieldValueObj);
67                 } else if (fieldValueObj instanceof java.sql.Timestamp JavaDoc) {
68                     if (fieldValueObj != null) {
69                         java.util.Date JavaDoc fieldDate = new java.util.Date JavaDoc(((java.sql.Timestamp JavaDoc) fieldValueObj).getTime());
70                         fieldValue = modDateFormat.format(fieldDate);
71                     }
72                 } else {
73                     if (fieldValueObj != null)
74                         fieldValue = fieldValueObj.toString();
75                 }
76                 map.put(fieldName, fieldValue);
77             }
78         }
79         map.put("identifier", String.valueOf(IdentifierFactory.getIdentifierByInode(cont).getInode()));
80         map.put("inode", String.valueOf(cont.getInode()));
81         return map;
82     }
83
84     /**
85      * This method is used by the backend to pull the content from the lucene
86      * index and also checks the user permissions to see the content
87      *
88      * @param structureInode
89      * Inode of the structure content to be listed
90      * @param fields
91      * Fields to filters, where the position i (where i is odd)
92      * represent the field name and the position i + 1 represent the
93      * field value to filter
94      * @param categories
95      * The categories inodes to filter
96      * @param showDeleted
97      * If true show the deleted elements only
98      * @param page
99      * The page number to show (starting with 1)
100      * @param orderBy
101      * The field name to be used to sort the content
102      * @return The list of contents that match the parameters at the position 0
103      * the result included a hashmap with some useful information like
104      * the total number of results, ...
105      */

106     public List JavaDoc searchContentlets(String JavaDoc structureInode, List JavaDoc<String JavaDoc> fields, List JavaDoc<String JavaDoc> categories,
107             boolean showDeleted, int page, String JavaDoc orderBy) {
108
109         HttpSession JavaDoc sess = WebContextFactory.get().getSession();
110         HttpServletRequest JavaDoc req = WebContextFactory.get().getHttpServletRequest();
111
112         // User info
113
User currentUser = null;
114         try {
115             currentUser = com.liferay.portal.util.PortalUtil.getUser(req);
116         } catch (Exception JavaDoc e) {
117             Logger.error(this, "Error trying to obtain the current liferay user from the request.", e);
118         }
119         boolean isAdmin = false;
120         List JavaDoc<Role> roles = new ArrayList JavaDoc<Role>();
121         if (!PublicUserFactory.isACMSAdmin(currentUser)) {
122             roles = com.dotmarketing.factories.RoleFactory.getAllRolesForUser(currentUser.getUserId());
123         } else
124             isAdmin = true;
125
126         // Buiilding search params and lucene query
127
StringBuffer JavaDoc luceneQuery = new StringBuffer JavaDoc();
128
129         Map JavaDoc lastSearchMap = new HashMap JavaDoc();
130         sess.setAttribute(WebKeys.CONTENTLET_LAST_SEARCH, lastSearchMap);
131
132         Structure st = StructureFactory.getStructureByInode(structureInode);
133         lastSearchMap.put("structure", st);
134
135         Map JavaDoc<String JavaDoc, String JavaDoc> fieldsSearch = new HashMap JavaDoc<String JavaDoc, String JavaDoc>();
136         
137         QueryParser parser = new QueryParser ("", new DotAnalyzer());
138         
139         for (int i = 0; i < fields.size(); i = i + 2) {
140             String JavaDoc fieldName = (String JavaDoc) fields.get(i);
141             String JavaDoc fieldValue = (String JavaDoc) fields.get(i + 1);
142             if (UtilMethods.isSet(fieldValue)) {
143                 fieldsSearch.put(fieldName, fieldValue);
144                 
145                 try {
146                     luceneQuery.append("+" + fieldName + ":" + parser.parse(fieldValue).toString() + "* ");
147                 } catch (ParseException e) {
148                     luceneQuery.append("+" + fieldName + ":" + fieldValue + "* ");
149                 }
150             }
151         }
152         lastSearchMap.put("fieldsSearch", fieldsSearch);
153
154         for (String JavaDoc cat : categories) {
155             luceneQuery.append("+c" + cat + "c:on ");
156         }
157         lastSearchMap.put("categories", categories);
158
159         if (!UtilMethods.isSet(orderBy))
160             orderBy = "modDate desc";
161
162         lastSearchMap.put("showDeleted", showDeleted);
163
164         lastSearchMap.put("page", page);
165         int perPage = Config.getIntProperty("PER_PAGE");
166         int offset = perPage * (page - 1);
167
168         lastSearchMap.put("orderBy", orderBy);
169
170         // Permissions in the query
171
if (!isAdmin) {
172             luceneQuery.append("+(");
173             for (Role role : roles) {
174                 luceneQuery.append("permissions:P" + role.getRoleId() + ".1P* ");
175             }
176             luceneQuery.append(")");
177         }
178
179         luceneQuery.append(" +working:true");
180
181         //Executing the query
182
long before = System.currentTimeMillis();
183         LuceneHits hits = ContentletFactory.indexSearch(st, luceneQuery.toString(), showDeleted,
184                 offset, perPage, orderBy);
185         long after = System.currentTimeMillis();
186         Logger.debug(ContentletAjax.class, "searchContentlets: Time to search on lucene =" + (after - before) + " ms.");
187
188         
189         before = System.currentTimeMillis();
190         
191         //The reesults list returned to the page
192
List JavaDoc results = new ArrayList JavaDoc();
193         
194         //Adding the result counters as the first row of the results
195
Map JavaDoc counters = new HashMap JavaDoc();
196         results.add(counters);
197
198         //Adding the headers as the second row of the results
199
List JavaDoc headers = new ArrayList JavaDoc();
200         Map JavaDoc<String JavaDoc, Field> fieldsMapping = new HashMap JavaDoc<String JavaDoc, Field>();
201         List JavaDoc<Field> stFields = FieldsCache.getFieldsByStructureInode(st.getInode());
202         for (Field f : stFields) {
203             if (f.isListed()) {
204                 fieldsMapping.put(f.getFieldContentlet(), f);
205                 headers.add(f.getMap());
206             }
207         }
208         if (headers.size() == 0) {
209             headers.add("Identifier");
210         }
211         results.add(headers);
212
213         //Adding the query results
214
for (int i = 0; i < hits.length(); i++) {
215             Document doc = hits.doc(i);
216
217             Map JavaDoc<String JavaDoc, String JavaDoc> searchResult = new HashMap JavaDoc<String JavaDoc, String JavaDoc>();
218             
219             for (String JavaDoc fieldContentlet : fieldsMapping.keySet()) {
220                 String JavaDoc fieldValue = doc.get(fieldContentlet);
221                 Field field = (Field) fieldsMapping.get(fieldContentlet);
222                 if (field.getFieldType().equals(WebKeys.TypeField.DATE)) {
223                     if (UtilMethods.isSet(fieldValue))
224                         fieldValue = UtilMethods.dateToHTMLDate(LuceneUtils.fromLuceneDate(fieldValue));
225                 } else if (field.getFieldType().equals(WebKeys.TypeField.DATETIME)) {
226                     if (UtilMethods.isSet(fieldValue))
227                         fieldValue = UtilMethods.dateToHTMLDate(LuceneUtils.fromLuceneDate(fieldValue))
228                                 + " "
229                                 + UtilMethods.dateToHTMLTime(LuceneUtils.fromLuceneDate(fieldValue));
230                 }else if (field.getFieldType().equals(WebKeys.TypeField.CHECKBOX) || field.getFieldType().equals(WebKeys.TypeField.MULTISELECT)) {
231                     if (UtilMethods.isSet(fieldValue))
232                         fieldValue = fieldValue.replaceAll("# #",",").replaceAll("#","");
233                 }
234                 searchResult.put(fieldContentlet, fieldValue);
235             }
236             searchResult.put("inode", doc.get("inode"));
237             searchResult.put("Identifier", doc.get("identifier"));
238             searchResult.put("identifier", doc.get("identifier"));
239             String JavaDoc fieldValue = UtilMethods.dateToHTMLDate(LuceneUtils.fromLuceneDate(doc.get("modDate"))) + " "
240                     + UtilMethods.dateToHTMLTime(LuceneUtils.fromLuceneDate(doc.get("modDate")));
241             searchResult.put("modDate", fieldValue);
242             String JavaDoc user = "";
243             User contentEditor = PublicUserFactory.getUserByUserId(doc.get("modUser"));
244             if (contentEditor.getFirstName() == null || contentEditor.getLastName() == null) {
245                 user = doc.get("modUser");
246             } else {
247                 user = contentEditor.getFullName();
248             }
249             searchResult.put("modUser", user);
250             searchResult.put("working", doc.get("working"));
251             searchResult.put("live", doc.get("live"));
252             searchResult.put("deleted", doc.get("deleted"));
253             searchResult.put("locked", doc.get("locked"));
254             searchResult.put("structureInode", doc.get("structureInode"));
255             searchResult.put("languageId", doc.get("languageId"));
256             searchResult.put("permissions", doc.get("permissions"));
257
258             results.add(searchResult);
259         }
260
261         counters.put("total", hits.getTotal());
262         counters.put("hasPrevious", page != 1);
263         counters.put("hasNext", offset + perPage < hits.getTotal());
264         // Data to show in the bottom content listing page
265
counters.put("luceneQuery", hits.getLuceneQuery().replaceAll("working:true", "live:true"));
266         counters.put("sortByUF", orderBy);
267
268         after = System.currentTimeMillis();
269         Logger.debug(ContentletAjax.class, "searchContentlets: Time to process results= " + (after - before) + " ms.");
270         
271         return results;
272     }
273
274     public Map JavaDoc getReindexationProgress() {
275         return ReindexationProcessStatus.getProcessIndexationMap();
276     }
277
278     public ArrayList JavaDoc<String JavaDoc[]> doSearchGlossaryTerm(String JavaDoc valueToComplete, String JavaDoc language) throws Exception JavaDoc {
279         ArrayList JavaDoc<String JavaDoc[]> list = new ArrayList JavaDoc<String JavaDoc[]>(15);
280         
281         Properties JavaDoc props = retrieveProperties(Long.parseLong(language));
282         
283         String JavaDoc[] term;
284         String JavaDoc key;
285         
286         valueToComplete = valueToComplete.toLowerCase();
287         
288         ArrayList JavaDoc<String JavaDoc> keysList = new ArrayList JavaDoc<String JavaDoc>(300);
289         keysList.ensureCapacity(300);
290         
291         for (Enumeration JavaDoc keys = props.keys(); keys.hasMoreElements();)
292             keysList.add((String JavaDoc) keys.nextElement());
293         
294         TreeSet JavaDoc<String JavaDoc> set = new TreeSet JavaDoc<String JavaDoc>(keysList);
295         Iterator JavaDoc<String JavaDoc> iter = set.iterator();
296         
297         for (int i = 0; (i < 15) && iter.hasNext();) {
298             key = iter.next();
299             if (key.toLowerCase().startsWith(valueToComplete)) {
300                 term = new String JavaDoc[] {key, (70 < props.getProperty(key).length() ? props.getProperty(key).substring(0, 69) : props.getProperty(key))};
301                 list.add(term);
302                 ++i;
303             }
304         }
305         
306         return list;
307     }
308
309     private String JavaDoc getGlobalVariablesPath() {
310         String JavaDoc globalVarsPath = Config.getStringProperty("GLOBAL_VARIABLES_PATH");
311         if (!UtilMethods.isSet(globalVarsPath)) {
312             globalVarsPath = Config.CONTEXT.getRealPath(File.separator + ".." + File.separator + "common"
313                     + File.separator + "ext-ejb" + File.separator + "content" + File.separator);
314         }
315         if (!globalVarsPath.endsWith(File.separator))
316             globalVarsPath = globalVarsPath + File.separator;
317         return globalVarsPath;
318     }
319
320     private Properties JavaDoc retrieveProperties(long langId) throws Exception JavaDoc {
321         Properties JavaDoc property = new Properties JavaDoc();
322
323         try {
324             // Loading properties file
325

326             String JavaDoc filePath = getGlobalVariablesPath() + "cms_language_" + langId + ".properties";
327
328             BufferedInputStream JavaDoc is = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(filePath));
329
330             LogFactory.getLog(this.getClass()).debug("ClassLoader: " + is);
331             if (is != null) {
332                 property = new Properties JavaDoc();
333                 property.load(is);
334
335                 LogFactory.getLog(this.getClass()).debug("has: " + property.size() + " keys");
336             } else {
337                 property = new Properties JavaDoc();
338             }
339             is.close();
340         } catch (Exception JavaDoc e) {
341             Logger.error(this, "Could not load this file =" + "cms_language_" + langId + "_properties", e);
342         }
343
344         return property;
345     }
346 }
Popular Tags