KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > content > webapp > ftl > LimitedSubContentCacheTransform


1 /*
2  * $Id: LimitedSubContentCacheTransform.java 5462 2005-08-05 18:35:48Z jonesde $
3  *
4  * Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal
7  * in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8  * copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
9  *
10  * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
13  * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
14  * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
15  *
16  */

17 package org.ofbiz.content.webapp.ftl;
18
19 import java.io.IOException JavaDoc;
20 import java.io.Writer JavaDoc;
21 import java.sql.Timestamp JavaDoc;
22 import java.util.ArrayList JavaDoc;
23 import java.util.HashMap JavaDoc;
24 import java.util.List JavaDoc;
25 import java.util.Locale JavaDoc;
26 import java.util.Map JavaDoc;
27
28 import javax.servlet.http.HttpServletRequest JavaDoc;
29
30 import org.ofbiz.base.util.Debug;
31 import org.ofbiz.base.util.GeneralException;
32 import org.ofbiz.base.util.StringUtil;
33 import org.ofbiz.base.util.UtilDateTime;
34 import org.ofbiz.base.util.UtilValidate;
35 import org.ofbiz.base.util.template.FreeMarkerWorker;
36 import org.ofbiz.content.content.ContentServicesComplex;
37 import org.ofbiz.content.content.ContentWorker;
38 import org.ofbiz.entity.GenericDelegator;
39 import org.ofbiz.entity.GenericEntityException;
40 import org.ofbiz.entity.GenericValue;
41 import org.ofbiz.minilang.MiniLangException;
42 import org.ofbiz.webapp.ftl.LoopWriter;
43
44 import freemarker.core.Environment;
45 import freemarker.template.TemplateModelException;
46 import freemarker.template.TemplateTransformModel;
47 import freemarker.template.TransformControl;
48
49 /**
50  * LimitedSubContentCacheTransform - Freemarker Transform for URLs (links)
51  *
52  * @author <a HREF="mailto:byersa@automationgroups.com">Al Byers</a>
53  * @version $Rev: 5462 $
54  * @since 3.0
55  */

56 public class LimitedSubContentCacheTransform implements TemplateTransformModel {
57
58     public static final String JavaDoc module = LimitedSubContentCacheTransform.class.getName();
59
60     public static final String JavaDoc [] upSaveKeyNames = {"globalNodeTrail"};
61     public static final String JavaDoc [] saveKeyNames = {"contentId", "subContentId", "entityList", "entityIndex", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "entityList", "viewSize", "viewIndex", "highIndex", "lowIndex", "listSize", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail", "outputIndex"};
62
63     /**
64      * A wrapper for the FreeMarkerWorker version.
65      */

66     public static Object JavaDoc getWrappedObject(String JavaDoc varName, Environment env) {
67         return FreeMarkerWorker.getWrappedObject(varName, env);
68     }
69
70     public static String JavaDoc getArg(Map JavaDoc args, String JavaDoc key, Environment env) {
71         return FreeMarkerWorker.getArg(args, key, env);
72     }
73
74     public static String JavaDoc getArg(Map JavaDoc args, String JavaDoc key, Map JavaDoc ctx) {
75         return FreeMarkerWorker.getArg(args, key, ctx);
76     }
77
78
79     public Writer JavaDoc getWriter(final Writer JavaDoc out, Map JavaDoc args) {
80         //Profiler.begin("Limited");
81
final StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
82         final Environment env = Environment.getCurrentEnvironment();
83         //final Map templateRoot = (Map) FreeMarkerWorker.getWrappedObject("context", env);
84
final Map JavaDoc templateRoot = FreeMarkerWorker.createEnvironmentMap(env);
85         //FreeMarkerWorker.convertContext(templateRoot);
86
final GenericDelegator delegator = (GenericDelegator) FreeMarkerWorker.getWrappedObject("delegator", env);
87         final HttpServletRequest JavaDoc request = (HttpServletRequest JavaDoc) FreeMarkerWorker.getWrappedObject("request", env);
88         FreeMarkerWorker.getSiteParameters(request, templateRoot);
89         //templateRoot.put("buf", buf);
90
final Map JavaDoc savedValuesUp = new HashMap JavaDoc();
91         FreeMarkerWorker.saveContextValues(templateRoot, upSaveKeyNames, savedValuesUp);
92         final Map JavaDoc savedValues = new HashMap JavaDoc();
93         FreeMarkerWorker.overrideWithArgs(templateRoot, args);
94         String JavaDoc contentAssocTypeId = (String JavaDoc) templateRoot.get("contentAssocTypeId");
95         final Map JavaDoc pickedEntityIds = new HashMap JavaDoc();
96         //if (UtilValidate.isEmpty(contentAssocTypeId)) {
97
//throw new RuntimeException("contentAssocTypeId is empty");
98
//}
99
List JavaDoc assocTypes = StringUtil.split(contentAssocTypeId, "|");
100
101         String JavaDoc contentPurposeTypeId = (String JavaDoc) templateRoot.get("contentPurposeTypeId");
102         List JavaDoc purposeTypes = StringUtil.split(contentPurposeTypeId, "|");
103         templateRoot.put("purposeTypes", purposeTypes);
104         Locale JavaDoc locale = (Locale JavaDoc) templateRoot.get("locale");
105         if (locale == null) {
106             locale = Locale.getDefault();
107             templateRoot.put("locale", locale);
108         }
109
110         Map JavaDoc whenMap = new HashMap JavaDoc();
111         whenMap.put("followWhen", (String JavaDoc) templateRoot.get("followWhen"));
112         whenMap.put("pickWhen", (String JavaDoc) templateRoot.get("pickWhen"));
113         whenMap.put("returnBeforePickWhen", (String JavaDoc) templateRoot.get("returnBeforePickWhen"));
114         whenMap.put("returnAfterPickWhen", (String JavaDoc) templateRoot.get("returnAfterPickWhen"));
115         templateRoot.put("whenMap", whenMap);
116
117         String JavaDoc fromDateStr = (String JavaDoc) templateRoot.get("fromDateStr");
118         Timestamp JavaDoc fromDate = null;
119         if (UtilValidate.isNotEmpty(fromDateStr)) {
120             fromDate = UtilDateTime.toTimestamp(fromDateStr);
121         }
122         if (fromDate == null)
123             fromDate = UtilDateTime.nowTimestamp();
124
125         String JavaDoc limitSize = (String JavaDoc) templateRoot.get("limitSize");
126         final int returnLimit = Integer.parseInt(limitSize);
127         // limitMode will be "random" to begin with
128
String JavaDoc limitMode = (String JavaDoc) templateRoot.get("limitMode");
129         final GenericValue userLogin = (GenericValue) FreeMarkerWorker.getWrappedObject("userLogin", env);
130         List JavaDoc globalNodeTrail = (List JavaDoc) templateRoot.get("globalNodeTrail");
131         String JavaDoc strNullThruDatesOnly = (String JavaDoc) templateRoot.get("nullThruDatesOnly");
132         String JavaDoc orderBy = (String JavaDoc) templateRoot.get("orderBy");
133         Boolean JavaDoc nullThruDatesOnly = (strNullThruDatesOnly != null && strNullThruDatesOnly.equalsIgnoreCase("true")) ? new Boolean JavaDoc(true) : new Boolean JavaDoc(false);
134         String JavaDoc contentId = (String JavaDoc) templateRoot.get("subContentId");
135
136         templateRoot.put("contentId", null);
137         templateRoot.put("subContentId", null);
138
139         final String JavaDoc contentIdTo = contentId;
140
141         Map JavaDoc results = null;
142         //if (Debug.infoOn()) Debug.logInfo("in LimitedSubContentCache(0), assocTypes ." + assocTypes, module);
143
String JavaDoc contentAssocPredicateId = (String JavaDoc) templateRoot.get("contentAssocPredicateId");
144         try {
145             results = ContentServicesComplex.getAssocAndContentAndDataResourceCacheMethod(delegator, contentId, null, "From", fromDate, null, assocTypes, null, new Boolean JavaDoc(true), contentAssocPredicateId, orderBy);
146         } catch (MiniLangException e2) {
147             throw new RuntimeException JavaDoc(e2.getMessage());
148         } catch (GenericEntityException e) {
149             throw new RuntimeException JavaDoc(e.getMessage());
150         }
151         List JavaDoc longList = (List JavaDoc) results.get("entityList");
152         templateRoot.put("entityList", longList);
153         //if (Debug.infoOn()) Debug.logInfo("in limited, longList:" + longList , "");
154

155         return new LoopWriter(out) {
156
157             public void write(char cbuf[], int off, int len) {
158                 buf.append(cbuf, off, len);
159                 //StringBuffer ctxBuf = (StringBuffer) templateRoot.get("buf");
160
//ctxBuf.append(cbuf, off, len);
161
}
162
163             public void flush() throws IOException JavaDoc {
164                 out.flush();
165             }
166
167             public int onStart() throws TemplateModelException, IOException JavaDoc {
168
169                 List JavaDoc globalNodeTrail = (List JavaDoc) templateRoot.get("globalNodeTrail");
170                 String JavaDoc trailCsv = ContentWorker.nodeTrailToCsv(globalNodeTrail);
171                 boolean inProgress = false;
172                 //if (Debug.infoOn()) Debug.logInfo("in limited, returnLimit:" + returnLimit , "");
173
//if (Debug.infoOn()) Debug.logInfo("in limited, pickedEntityIds:" + pickedEntityIds , "");
174
if (pickedEntityIds.size() < returnLimit) {
175                     inProgress = getNextMatchingEntity(templateRoot, delegator, env);
176                 }
177                 FreeMarkerWorker.saveContextValues(templateRoot, saveKeyNames, savedValues);
178                 if (inProgress) {
179                     return TransformControl.EVALUATE_BODY;
180                 } else {
181                     return TransformControl.SKIP_BODY;
182                 }
183             }
184
185             public int afterBody() throws TemplateModelException, IOException JavaDoc {
186                 FreeMarkerWorker.reloadValues(templateRoot, savedValues, env);
187                 List JavaDoc list = (List JavaDoc) templateRoot.get("globalNodeTrail");
188                 List JavaDoc subList = list.subList(0, list.size() - 1);
189                 templateRoot.put("globalNodeTrail", subList);
190                 env.setVariable("globalNodeTrail", FreeMarkerWorker.autoWrap(subList, env));
191                 
192                 //if (Debug.infoOn()) Debug.logInfo("highIndex(2):" + highIndexInteger , "");
193
//if (Debug.infoOn()) Debug.logInfo("in limited, returnLimit(2):" + returnLimit , "");
194
//if (Debug.verboseOn()) Debug.logVerbose("in limited, pickedEntityIds(2):" + pickedEntityIds , "");
195
boolean inProgress = false;
196                 if (pickedEntityIds.size() < returnLimit) {
197                     inProgress = getNextMatchingEntity(templateRoot, delegator, env);
198                 }
199
200                 FreeMarkerWorker.saveContextValues(templateRoot, saveKeyNames, savedValues);
201                 if (inProgress) {
202                     return TransformControl.REPEAT_EVALUATION;
203                 } else {
204                     return TransformControl.END_EVALUATION;
205                 }
206             }
207
208             public void close() throws IOException JavaDoc {
209                 FreeMarkerWorker.reloadValues(templateRoot, savedValuesUp, env);
210                 String JavaDoc wrappedContent = buf.toString();
211                 out.write(wrappedContent);
212                 //try {
213
//Profiler.end("Limited");
214
//FileOutputStream fw = new FileOutputStream(new File("/usr/local/agi/ofbiz/hot-deploy/sfmp/misc/profile.data"));
215
//Profiler.print(fw);
216
//fw.close();
217
//} catch (IOException e) {
218
//Debug.logError("[PROFILER] " + e.getMessage(),"");
219
//}
220
}
221
222             public boolean prepCtx(GenericDelegator delegator, Map JavaDoc ctx, Environment env, GenericValue view) throws GeneralException {
223
224                 String JavaDoc dataResourceId = (String JavaDoc) view.get("drDataResourceId");
225                 String JavaDoc subContentIdSub = (String JavaDoc) view.get("contentId");
226                 // This order is taken so that the dataResourceType can be overridden in the transform arguments.
227
String JavaDoc subDataResourceTypeId = (String JavaDoc) ctx.get("subDataResourceTypeId");
228                 if (UtilValidate.isEmpty(subDataResourceTypeId)) {
229                     subDataResourceTypeId = (String JavaDoc) view.get("drDataResourceTypeId");
230                     // TODO: If this value is still empty then it is probably necessary to get a value from
231
// the parent context. But it will already have one and it is the same context that is
232
// being passed.
233
}
234
235                 String JavaDoc mimeTypeId = ContentWorker.getMimeTypeId(delegator, view, ctx);
236
237
238                 Map JavaDoc trailNode = ContentWorker.makeNode(view);
239                 Map JavaDoc whenMap = (Map JavaDoc) ctx.get("whenMap");
240                 Locale JavaDoc locale = (Locale JavaDoc) ctx.get("locale");
241                 if (locale == null) {
242                     locale = Locale.getDefault();
243                 }
244                 GenericValue assocContent = null;
245                 ContentWorker.checkConditions(delegator, trailNode, assocContent, whenMap);
246                 Boolean JavaDoc isReturnBeforeObj = (Boolean JavaDoc) trailNode.get("isReturnBefore");
247                 Boolean JavaDoc isReturnAfterObj = (Boolean JavaDoc) trailNode.get("isReturnAfter");
248                 Boolean JavaDoc isPickObj = (Boolean JavaDoc) trailNode.get("isPick");
249                 Boolean JavaDoc isFollowObj = (Boolean JavaDoc) trailNode.get("isFollow");
250                 //if (Debug.infoOn()) Debug.logInfo("in LimitedSubContentCache, isReturnBeforeObj" + isReturnBeforeObj + " isPickObj:" + isPickObj + " isFollowObj:" + isFollowObj + " isReturnAfterObj:" + isReturnAfterObj, module);
251
if ((isReturnBeforeObj == null || !isReturnBeforeObj.booleanValue()) && ((isPickObj != null &&
252                         isPickObj.booleanValue()) || (isFollowObj != null && isFollowObj.booleanValue()))) {
253                     List JavaDoc globalNodeTrail = (List JavaDoc) ctx.get("globalNodeTrail");
254                     if (globalNodeTrail == null) {
255                         globalNodeTrail = new ArrayList JavaDoc();
256                     }
257                     globalNodeTrail.add(trailNode);
258                     ctx.put("globalNodeTrail", globalNodeTrail);
259                     String JavaDoc csvTrail = ContentWorker.nodeTrailToCsv(globalNodeTrail);
260                     ctx.put("nodeTrailCsv", csvTrail);
261                     //if (Debug.infoOn()) Debug.logInfo("prepCtx, csvTrail(2):" + csvTrail, "");
262
int indentSz = globalNodeTrail.size();
263                     ctx.put("indent", new Integer JavaDoc(indentSz));
264
265                     ctx.put("subDataResourceTypeId", subDataResourceTypeId);
266                     ctx.put("mimeTypeId", mimeTypeId);
267                     ctx.put("subContentId", subContentIdSub);
268                     ctx.put("content", view);
269
270                     env.setVariable("subDataResourceTypeId", FreeMarkerWorker.autoWrap(subDataResourceTypeId, env));
271                     env.setVariable("indent", FreeMarkerWorker.autoWrap(new Integer JavaDoc(indentSz), env));
272                     env.setVariable("nodeTrailCsv", FreeMarkerWorker.autoWrap(csvTrail, env));
273                     env.setVariable("globalNodeTrail", FreeMarkerWorker.autoWrap(globalNodeTrail, env));
274                     env.setVariable("content", FreeMarkerWorker.autoWrap(view, env));
275                     env.setVariable("mimeTypeId", FreeMarkerWorker.autoWrap(mimeTypeId, env));
276                     env.setVariable("subContentId", FreeMarkerWorker.autoWrap(subContentIdSub, env));
277                     return true;
278                 } else {
279                     return false;
280                 }
281             }
282
283             public GenericValue getRandomEntity() {
284
285                 GenericValue pickEntity = null;
286                 List JavaDoc lst = (List JavaDoc) templateRoot.get("entityList");
287                 if (Debug.verboseOn()) Debug.logVerbose("in limited, lst:" + lst, "");
288
289                 while (pickEntity == null && lst.size() > 0) {
290                     double randomValue = Math.random();
291                     //if (Debug.infoOn()) Debug.logInfo("in limited, randomValue:" + randomValue , "");
292
int idx = (int) (lst.size() * randomValue);
293                     //if (Debug.infoOn()) Debug.logInfo("in limited, idx:" + idx , "");
294
pickEntity = (GenericValue) lst.get(idx);
295                     String JavaDoc pickEntityId = pickEntity.getString("contentId");
296                     if (pickedEntityIds.get(pickEntityId) == null) {
297                         pickedEntityIds.put(pickEntityId, pickEntity);
298                         lst.remove(idx);
299                     } else {
300                         pickEntity = null;
301                     }
302                 }
303                 return pickEntity;
304             }
305
306             public boolean getNextMatchingEntity(Map JavaDoc templateRoot, GenericDelegator delegator, Environment env) throws IOException JavaDoc {
307                 boolean matchFound = false;
308                 GenericValue pickEntity = getRandomEntity();
309
310                 while (pickEntity != null && !matchFound) {
311                     try {
312                         matchFound = prepCtx(delegator, templateRoot, env, pickEntity);
313                     } catch (GeneralException e) {
314                         throw new IOException JavaDoc(e.getMessage());
315                     }
316                     if (!matchFound)
317                         pickEntity = getRandomEntity();
318                 }
319                 return matchFound;
320             }
321         };
322     }
323 }
324
Popular Tags