KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > data > fields > ExpressionMarker


1 package org.jahia.data.fields;
2
3 import org.jahia.params.ParamBean;
4 import org.jahia.params.DummyServletRequestWrapper;
5
6 import java.util.Collections JavaDoc;
7 import org.jahia.utils.JahiaTools;
8 import java.util.Vector JavaDoc;
9 import org.jahia.exceptions.JahiaException;
10 import java.util.Comparator JavaDoc;
11 import org.apache.commons.jexl.Expression;
12 import org.apache.commons.jexl.ExpressionFactory;
13 import org.apache.commons.jexl.JexlContext;
14 import org.apache.commons.jexl.JexlHelper;
15
16 /**
17  * <p>Title: Marker used in field values and default values that can contain
18  * Jexl expressions that are evaluated.</p>
19  * <p>Description: </p>
20  * <p>Copyright: Copyright (c) 2002</p>
21  * <p>Company: Jahia Ltd</p>
22  * @author Serge Huber
23  * @version 1.0
24  */

25
26 public class ExpressionMarker implements Comparator JavaDoc {
27
28     private static org.apache.log4j.Logger logger =
29         org.apache.log4j.Logger.getLogger(ExpressionMarker.class);
30
31     private String JavaDoc expr;
32     private boolean storeMarker;
33     private ExpressionContext expressionContext;
34     private String JavaDoc value = null;
35     private ParamBean paramBean = null;
36
37     static private final String JavaDoc EXPR_ATTR_PREFIX = " expr=\"";
38     static private final String JavaDoc STOREMARKER_ATTR_PREFIX = " storeMarker=\"";
39     static private final int EXPR_ATTR_PREFIX_LEN = EXPR_ATTR_PREFIX.length();
40     static private final int STOREMARKER_ATTR_PREFIX_LEN =
41         STOREMARKER_ATTR_PREFIX.length();
42
43     public ExpressionMarker (String JavaDoc expr, boolean storeMarker,
44                              ParamBean paramBean) {
45         this.expr = expr;
46         this.storeMarker = storeMarker;
47         this.paramBean = paramBean;
48         this.expressionContext = new ExpressionContext(paramBean);
49     }
50
51     public String JavaDoc getExpr () {
52         return expr;
53     }
54
55     public void setExpr (String JavaDoc expr) {
56         this.expr = expr;
57     }
58
59     public boolean isStoreMarker () {
60         return storeMarker;
61     }
62
63     public void setStoreMarker (boolean storeMarker) {
64         this.storeMarker = storeMarker;
65     }
66
67     public String JavaDoc getValue () {
68         if (value == null && expr != null && !expr.equals("")) {
69             try {
70                 Expression e = ExpressionFactory.createExpression(expr);
71
72                 JexlContext jc = JexlHelper.createContext();
73                 jc.getVars().put("currentContext", expressionContext);
74                 jc.getVars().put("currentPage", expressionContext.getPageBean());
75                 jc.getVars().put("currentSite", expressionContext.getSiteBean());
76                 jc.getVars().put("currentJahia", expressionContext.getJahiaBean());
77                 jc.getVars().put("currentUser", expressionContext.getUser());
78                 jc.getVars().put("currentRequest",
79                                  expressionContext.getRequestBean());
80
81                 /* FIXME : We should never cache Expression because they should
82                 // be evaluated dynamically.
83                 // Consequently -> could we ever cache Field Value ???????
84
85                 // now evaluate the expression, getting the result
86                 Object o = ExpressionMarkerCache.getInstance()
87                     .evalutateExpression(expr,e,jc);
88                 */

89
90                Object JavaDoc o = e.evaluate(jc);
91
92                 if (o == null) {
93                     logger.warn("Didn't find object for expression " + expr);
94                 } else {
95                     if (o instanceof String JavaDoc) {
96                         value = (String JavaDoc) o;
97                     } else {
98                         value = o.toString();
99                     }
100                 }
101             } catch (Exception JavaDoc e) {
102                 logger.error("Error while evaluating JEXL expression [" + expr +
103                              "]", e);
104             }
105
106             return value;
107         } else {
108             return value;
109         }
110     }
111
112     /**
113      * Returns the real value ( by evaluating the expression ) if the value is
114      * a valid expression marker tag
115      *
116      * <jahia-expression expr="user/username" storeMarker="false"/>
117      *
118      * or the original value on any other case ( not a valid expression marker tag ).
119      *
120      * @param markerStr
121      * @param paramBean the current paramBean object
122      * @return
123      * @throws JahiaException
124      */

125     public static String JavaDoc getValue(String JavaDoc value, ParamBean paramBean)
126     throws JahiaException {
127
128         // Expression only work if we are in HttpServletRequest context
129
if ( paramBean == null || paramBean.getRealRequest() == null
130                  || (paramBean.getRealRequest() instanceof DummyServletRequestWrapper) ){
131             return value;
132         }
133
134         ExpressionMarker marker =
135                 ExpressionMarker.parseMarkerValue(value, paramBean);
136         if ( marker == null ){
137             return value;
138         }
139
140         String JavaDoc result = marker.getValue();
141
142         return result;
143     }
144
145     public void setValue (String JavaDoc value) {
146         this.value = value;
147     }
148
149     public ExpressionContext getExpressionContext () {
150         return expressionContext;
151     }
152
153     public void setExpressionContext (ExpressionContext expressionContext) {
154         this.expressionContext = expressionContext;
155     }
156
157     /**
158      * Generates a ExpressionMarker Bean from a expression marker value String
159      *
160      * @param value a valid tag :
161      * <jahia-expression expr="user/username" storeMarker="false"/>
162      * @return an expression marker bean or null on any parsing error.
163      */

164     public static ExpressionMarker parseMarkerValue (String JavaDoc markerStr,
165         ParamBean paramBean) {
166
167         if (markerStr == null) {
168             return null;
169         }
170
171         ExpressionMarker marker = null;
172         String JavaDoc val = markerStr.trim();
173         String JavaDoc expr = null;
174         boolean storeMarker = false;
175
176         if (val.startsWith("<jahia-expression") && val.endsWith("/>")) {
177
178             try {
179
180                 int pos = val.indexOf(EXPR_ATTR_PREFIX);
181                 if (pos != -1) {
182                     expr =
183                         val.substring(pos + EXPR_ATTR_PREFIX_LEN,
184                                       val.indexOf("\" ",
185                                                   pos + EXPR_ATTR_PREFIX_LEN));
186                     expr = JahiaTools.replacePattern(expr, "&quot;", "\"");
187                     expr = JahiaTools.replacePattern(expr, "&amp;", "&");
188                 }
189
190                 pos = val.indexOf(STOREMARKER_ATTR_PREFIX);
191                 if (pos != -1) {
192                     storeMarker = new Boolean JavaDoc(
193                         val.substring(pos + STOREMARKER_ATTR_PREFIX_LEN,
194                                       val.indexOf("\"",
195                                                   pos + STOREMARKER_ATTR_PREFIX_LEN)).
196                         trim()).booleanValue();
197                 }
198
199                 marker = new ExpressionMarker(expr, storeMarker, paramBean);
200             } catch (Throwable JavaDoc t) {
201                 logger.error("Error while parsing expression marker", t);
202             }
203         } else {
204             marker = new ExpressionMarker("", false, paramBean);
205             marker.setValue(markerStr);
206         }
207
208         return marker;
209     }
210
211     /**
212      * Build a vector of expression markers from an enumeration of values
213      *
214      * val1:val2:val3
215      *
216      * @param enumValues
217      * @param paramBean
218      * @return
219      * @throws JahiaException
220      */

221     public static Vector JavaDoc buildExpressionMarkers (String JavaDoc enumValues,
222                                                  ParamBean paramBean)
223         throws JahiaException {
224
225         String JavaDoc[] tokens = JahiaTools.getTokens(enumValues, ":");
226         Vector JavaDoc markers = new Vector JavaDoc();
227         for (int i = 0; i < tokens.length; i++) {
228             logger.debug("token=" + tokens[i]);
229             ExpressionMarker marker =
230                 ExpressionMarker.parseMarkerValue(tokens[i], paramBean);
231 // if (marker == null) {
232
// logger.debug("marker is null !");
233
// // invalid or not a expression marker signature
234
// // build a marker that return the value as it.
235
// marker = new ExpressionMarker("", false, paramBean);
236
// marker.setValue(tokens[i]);
237
// } else {
238
// // logger.debug("marker=[" + marker.getExpr() + "," + marker.getValue() + "]");
239
// }
240
markers.add(marker);
241         }
242         // sorts the markers
243
ExpressionMarker compMarker = new ExpressionMarker("", false, paramBean);
244         compMarker.setValue("");
245         Collections.sort(markers, compMarker);
246         return markers;
247     }
248
249     /**
250      * Generates a valid expression marker
251      *
252      * <jahia-expression expr="user/username" storeMarker="false"/>
253      *
254      * @param expr the expression string
255      * @param storeMarker boolean specifying whether the marker should be
256      * stored as-is or if the resolved value should be stored
257      * @return
258      */

259     public static String JavaDoc drawMarker (String JavaDoc expr, boolean storeMarker) {
260         StringBuffer JavaDoc buff = new StringBuffer JavaDoc("<jahia-expression");
261         buff.append(EXPR_ATTR_PREFIX);
262         String JavaDoc escapedExpr = expr;
263         escapedExpr = JahiaTools.replacePattern(escapedExpr, "&", "&amp;");
264         escapedExpr = JahiaTools.replacePattern(escapedExpr, "\"", "&quot;");
265         buff.append(escapedExpr);
266         buff.append("\"");
267         buff.append(STOREMARKER_ATTR_PREFIX);
268         buff.append(storeMarker);
269         buff.append("\"/>");
270         return buff.toString();
271     }
272
273     /**
274      * Generates a valid expression marker from internal value
275      *
276      * <jahia-expression expr="user/username" storeMarker="false"/>
277      *
278      * @return
279      */

280     public String JavaDoc drawMarker () {
281         if (expr != null && !expr.equals("")) {
282         return drawMarker(this.getExpr(),
283                           this.isStoreMarker());
284         } else {
285             return value;
286         }
287     }
288
289     //-------------------------------------------------------------------------
290
/**
291      * Compare between two objects, sort by their value
292      *
293      * @param Object
294      * @param Object
295      */

296     public int compare (Object JavaDoc c1, Object JavaDoc c2)
297         throws ClassCastException JavaDoc {
298
299         ExpressionMarker e1 = (ExpressionMarker) c1;
300         ExpressionMarker e2 = (ExpressionMarker) c2;
301
302         if ( (e1.getValue() == null) && (e2.getValue() == null)) {
303             return 0;
304         }
305
306         if (e1.getValue() == null) {
307             return -1;
308         }
309
310         if (e2.getValue() == null) {
311             return 1;
312         }
313
314         return ( (ExpressionMarker) c1)
315             .getValue()
316             .compareToIgnoreCase( ( (ExpressionMarker) c2).getValue().
317                                  toLowerCase());
318
319     }
320
321 }
322
Popular Tags