1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.myfaces.custom.dojo;
21
22 import org.apache.commons.lang.StringUtils;
23 import org.apache.commons.logging.Log;
24 import org.apache.commons.logging.LogFactory;
25 import org.apache.myfaces.renderkit.html.util.AddResource;
26 import org.apache.myfaces.renderkit.html.util.AddResourceFactory;
27 import org.apache.myfaces.shared_tomahawk.renderkit.html.HTML;
28
29 import javax.faces.component.UIComponent;
30 import javax.faces.context.FacesContext;
31 import javax.faces.context.ResponseWriter;
32 import javax.servlet.http.HttpServletRequest;
33 import java.io.IOException;
34 import java.lang.reflect.InvocationTargetException;
35 import java.lang.reflect.Method;
36 import java.util.*;
37 import java.util.Map.Entry;
38
39
40
41
42
43
44
45
46
47
48
49 public final class DojoUtils {
50 private static final String MYFACES_DOJO_DEBUGCONSOLE_ID = "myfaces_Dojo_Debugger";
51
52 private static final String DEBUG_CONSOLE_TYPE = "DebugConsole";
53
54 private static final String LAYOUT_ALIGN_ATTR = "layoutAlign";
55
56 private static final String DISPLAY_CLOSE_ACTION_ATTR = "displayCloseAction";
57
58 private static final String RESIZABLE_ATTR = "resizable";
59
60 private static final String HAS_SHADOW_ATTR = "hasShadow";
61
62 private static final String CONSTRAIN_TO_CONTAINER_ATTR = "constrainToContainer";
63
64 private static final String ICON_SRC_ATTR = "iconSrc";
65
66 private static final String TITLE_ATTR = "title";
67
68 private static final String INCL_TYPE_REQ_KEY = "DOJO_DEVELOPMENT_INCLUDE";
69
70 private static final Log log = LogFactory.getLog(DojoUtils.class);
71
72 private static final String DOJO_PROVIDE = "dojo.provide:";
73
74 private static final String DOJO_REQUIRE = "dojo.require:";
75
76 private static final String DOJO_NAMESPACE = "dojo.namespace:";
77
78 private static final String DJCONFIG_INITKEY = "/*djconfig init*/";
79
80 private static final String BODY_SCRIPT_INFOS_ATTRIBUTE_NAME = "bodyScriptInfos";
81
82 private static final String DOJO_FILE_UNCOMPRESSED = "dojo.js.uncompressed.js";
83
84 private static final String DOJO_FILE = "dojo.js";
85
86 private static final String DJCONFIG_REQ_KEY = "MYFACES_DJCONFIG";
87
88 private static final String DOJOEXTENSIONS_NAMESPACE = "dojo.setModulePrefix('extensions', '../dojoextensions.ResourceLoader');";
89
90 private DojoUtils() {
91
92 }
93
94
95
96
97
98
99
100
101
102
103
104
105 public static Map getAttributeMap(FacesContext facesContext, String[] attributeNames, UIComponent component) {
106 Log log = null;
107
108 Class componentClass = component.getClass();
109 Map returnMap = new HashMap();
110 for (int cnt = 0; cnt < attributeNames.length; cnt++) {
111 try {
112 String attributeName = attributeNames[cnt];
113
114 if (attributeName.equals("id") || attributeName.equals("widgetId")) {
115 String calculatedId = DojoUtils.calculateWidgetId(facesContext, component);
116 returnMap.put("id", calculatedId);
117 } else {
118 String attributeCasedName = attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1);
119 String getForm = "get" + attributeCasedName;
120 String isForm = "is" + attributeCasedName;
121 Method m = null;
122
123
124
125 while ((componentClass != null) && (m == null)) {
126 m = componentClass.getDeclaredMethod(getForm, null);
127 if (m == null) {
128
129 m = componentClass.getDeclaredMethod(isForm, null);
130 }
131 if (m == null) {
132
133 componentClass = componentClass.getSuperclass();
134 }
135 }
136 if (m != null) {
137 Object execRetval = m.invoke(component, null);
138 if (execRetval != null)
139 returnMap.put(attributeName, execRetval);
140 }
141 }
142 } catch (Exception e) {
143 if (log == null)
144 log = LogFactory.getLog(DojoUtils.class);
145
146 log.error("getAttributeMap", e);
147 }
148 }
149 return returnMap;
150 }
151
152
153
154
155
156
157
158
159
160
161
162 public static void addDebugConsole(FacesContext facesContext, UIComponent component) throws IOException {
163
164
165 if (isInlineScriptSet(facesContext, "/*DOJO DEBUGCONSOLE ON*/"))
166 return;
167
168 AddResource addResource = AddResourceFactory.getInstance(facesContext);
169 addResource.addInlineScriptAtPosition(facesContext, AddResource.HEADER_BEGIN, "/*DOJO DEBUGCONSOLE ON*/");
170
171 ResponseWriter writer = facesContext.getResponseWriter();
172
173
174
175
176 writer.startElement(HTML.DIV_ELEM, component);
177 writer.writeAttribute(HTML.ID_ATTR, MYFACES_DOJO_DEBUGCONSOLE_ID, null);
178 writer.writeAttribute(HTML.STYLE_ATTR, "width: 400px; height: 500px; left: 200px;", null);
179 writer.endElement(HTML.DIV_ELEM);
180
181 Map attributeMap = new HashMap();
182 attributeMap.put(TITLE_ATTR, "MyFaces Dojo Debug console");
183 attributeMap.put(ICON_SRC_ATTR, "images/flatScreen.gif");
184 attributeMap.put(CONSTRAIN_TO_CONTAINER_ATTR, new Integer(1));
185 attributeMap.put(HAS_SHADOW_ATTR, new Boolean(true));
186 attributeMap.put(RESIZABLE_ATTR, new Boolean(true));
187 attributeMap.put(DISPLAY_CLOSE_ACTION_ATTR, new Boolean(true));
188 attributeMap.put(LAYOUT_ALIGN_ATTR, "client");
189 renderWidgetInitializationCode(writer, component, DEBUG_CONSOLE_TYPE, attributeMap, MYFACES_DOJO_DEBUGCONSOLE_ID, true);
190 }
191
192
193
194
195 public static boolean isDojoInitialized(FacesContext facesContext)
196 {
197 return isInlineScriptCheck(facesContext, DJCONFIG_INITKEY);
198 }
199
200 public static void addMainInclude(FacesContext facesContext, UIComponent component, String javascriptLocation, DojoConfig config) throws IOException {
201
202 AddResource addResource = AddResourceFactory.getInstance(facesContext);
203
204
205
206
207
208 if (!isInlineScriptSet(facesContext, DJCONFIG_INITKEY)) {
209 addResource.addInlineScriptAtPosition(facesContext, AddResource.HEADER_BEGIN, DJCONFIG_INITKEY);
210 addResource.addInlineScriptAtPosition(facesContext, AddResource.HEADER_BEGIN, config.toString());
211
212 String dojofile = ((getExpanded(facesContext) != null) && getExpanded(facesContext).booleanValue()) ? DOJO_FILE_UNCOMPRESSED : DOJO_FILE;
213
214 if (javascriptLocation != null) {
215 addResource.addJavaScriptAtPosition(facesContext, AddResource.HEADER_BEGIN, javascriptLocation + dojofile);
216 } else {
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233 addResource.addJavaScriptAtPositionPlain(facesContext, AddResource.HEADER_BEGIN, DojoResourceLoader.class, dojofile);
234 }
235 addResource.addInlineScriptAtPosition(facesContext, AddResource.HEADER_BEGIN, DOJOEXTENSIONS_NAMESPACE);
236 }
237 }
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253 public static void addNamespace(FacesContext facesContext, UIComponent component, String namespace, String location) throws IOException {
254
255 if (isInlineScriptSet(facesContext, DOJO_NAMESPACE + namespace))
256 return;
257
258 String namespaceStr = createNamespaceScript(namespace, location);
259 writeInlineScript(facesContext, component, namespaceStr);
260 }
261
262
263
264
265
266
267
268
269
270
271
272
273 public static void addProvide(FacesContext context, String provided) {
274
275 if (isInlineScriptSet(context, DOJO_PROVIDE + provided))
276 return;
277
278 AddResource addResource = AddResourceFactory.getInstance(context);
279 String providedBuilder = createDojoProvideScript(provided);
280
281 addResource.addInlineScriptAtPosition(context, AddResource.HEADER_BEGIN, providedBuilder);
282 }
283
284
285
286
287
288
289
290
291
292 public static void addProvide(FacesContext facesContext, UIComponent component, String provided) throws IOException {
293
294 if (isInlineScriptSet(facesContext, DOJO_PROVIDE + provided))
295 return;
296
297 String providedBuilder = createDojoProvideScript(provided);
298
299 writeInlineScript(facesContext, component, providedBuilder);
300
301 }
302
303
304
305
306
307
308
309
310 public static void addRequire(FacesContext facesContext, UIComponent component, String[] requires) throws IOException {
311 for (int cnt = 0; cnt < requires.length; cnt++)
312 addRequire(facesContext, component, requires[cnt]);
313 }
314
315
316
317
318
319
320
321 public static void addRequire(FacesContext facesContext, UIComponent component, String required) throws IOException {
322
323 if (isInlineScriptSet(facesContext, DOJO_REQUIRE + required))
324 return;
325
326 String requireAsScript = createDojoRequireString(required);
327 writeInlineScript(facesContext, component, requireAsScript);
328 }
329
330
331
332
333
334
335
336
337 public static String createDebugStatement(String stmnt) {
338 return "dojo.debug(\"" + stmnt + "\");\n";
339 }
340
341
342
343
344
345
346
347
348
349 public static String createDebugStatement(String stmnt, String value) {
350 return "dojo.debug(\"" + stmnt + ":\");dojo.debug(" + value + ");\n";
351 }
352
353
354
355
356
357
358
359
360 public static String createDojoProvideScript(String provided) {
361
362 StringBuffer providedBuilder = new StringBuffer(32);
363 providedBuilder.append("dojo.provide('");
364 providedBuilder.append(provided.trim());
365 providedBuilder.append("');");
366
367 return providedBuilder.toString();
368 }
369
370
371
372
373
374
375
376
377 public static String createDojoRequireString(String required) {
378 StringBuffer requiredBuilder = new StringBuffer(32);
379 requiredBuilder.append("dojo.require('");
380 requiredBuilder.append(required.trim());
381 requiredBuilder.append("');");
382
383 return requiredBuilder.toString();
384 }
385
386
387
388
389
390
391
392 public static DojoConfig getDjConfigInstance(FacesContext context) {
393
394
395
396
397 DojoConfig djConfig = (DojoConfig) ((HttpServletRequest) context.getExternalContext().getRequest()).getAttribute(DJCONFIG_REQ_KEY);
398
399 if (djConfig == null) {
400 djConfig = new DojoConfig();
401 ((HttpServletRequest) context.getExternalContext().getRequest()).setAttribute(DJCONFIG_REQ_KEY, djConfig);
402 }
403
404 return djConfig;
405 }
406
407
408
409
410
411
412
413 public static Boolean getExpanded(FacesContext facesContext) {
414
415 HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest();
416 Boolean devStatus = (Boolean) request.getAttribute(INCL_TYPE_REQ_KEY);
417 DojoConfig config = getDjConfigInstance(facesContext);
418 if (devStatus == null)
419 devStatus = new Boolean(false);
420 devStatus = new Boolean(devStatus.booleanValue() || (config.getDevelopment() != null && config.getDevelopment().booleanValue()));
421
422 return devStatus;
423 }
424
425
426
427
428
429
430
431
432
433
434 public static boolean isInlineScriptSet(FacesContext context, String inlineScript) {
435
436
437 HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
438 Set set = getBodyScriptInfos(request);
439
440 if (!set.contains(inlineScript)) {
441 set.add(inlineScript);
442
443 return false;
444 }
445
446 return true;
447 }
448
449
450
451
452 public static boolean isInlineScriptCheck(FacesContext context, String inlineScript)
453 {
454
455 HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
456 Set set = getBodyScriptInfos(request);
457
458 return set.contains(inlineScript);
459 }
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477 public static String renderWidgetInitializationCode(FacesContext facesContext, UIComponent component, String dojoType, Map paramMap) throws IOException {
478 ResponseWriter writer = facesContext.getResponseWriter();
479 String clientId = component.getClientId(facesContext);
480 return renderWidgetInitializationCode(writer, component, dojoType, paramMap, clientId, true);
481 }
482
483
484
485
486
487
488
489
490
491
492
493
494 public static String renderWidgetInitializationCode(FacesContext facesContext, UIComponent component, String dojoType, String[] attributeNames)
495 throws IOException {
496 Map paramMap = DojoUtils.getAttributeMap(facesContext, attributeNames, component);
497 return renderWidgetInitializationCode(facesContext, component, dojoType, paramMap);
498 }
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514 public static String renderWidgetInitializationCode(ResponseWriter writer, UIComponent component, String dojoType, Map paramMap, String clientId,
515 boolean refId) throws IOException {
516
517 writer.startElement(HTML.SCRIPT_ELEM, component);
518 writer.writeAttribute(HTML.TYPE_ATTR, HTML.SCRIPT_TYPE_TEXT_JAVASCRIPT, null);
519
520 String javascriptVar = (String) paramMap.get("widgetVar");
521 if (StringUtils.isBlank(javascriptVar))
522 javascriptVar = calculateWidgetVarName(clientId);
523
524 Iterator it = paramMap.entrySet().iterator();
525
526 writer.write("var ");
527 writer.write(javascriptVar);
528 writer.write(" = ");
529
530 writer.write("dojo.widget.createWidget(\"");
531 writer.write(dojoType);
532 writer.write("\",");
533
534 writer.write("{");
535 boolean first = true;
536 while (it.hasNext()) {
537 Entry entry = (Entry) it.next();
538 Object value = entry.getValue();
539 if (value != null) {
540 if (!first)
541 writer.write(",");
542 writer.write(entry.getKey().toString());
543 writer.write(":");
544
545 boolean isString = value instanceof String;
546 if (isString)
547 {
548 if( value.equals("true")
549 || value.equals("false") )
550 isString = false;
551 }
552 if (isString)
553 writer.write("'");
554 writer.write(value.toString());
555 if (isString)
556 writer.write("'");
557 first = false;
558 }
559
560 }
561 writer.write("}");
562 if (refId) {
563 writer.write(",dojo.byId('");
564 writer.write(clientId);
565 writer.write("')");
566 }
567 writer.write(");");
568
569 writer.endElement(HTML.SCRIPT_ELEM);
570 return javascriptVar;
571 }
572
573
574
575
576
577
578
579
580
581 public static String calculateWidgetVarName(String clientId) {
582 return clientId.replaceAll("\\:", "_") + "_dojoControl";
583 }
584
585
586
587
588
589 public static String calculateWidgetId(FacesContext context, UIComponent widget) {
590 String widgetVarName = "";
591 if (widget instanceof DojoWidget) {
592 widgetVarName = ((DojoWidget) widget).getWidgetId();
593 }
594 if (StringUtils.isBlank(widgetVarName)) {
595 widgetVarName = calculateWidgetVarName(widget.getClientId(context));
596 }
597 return widgetVarName;
598 }
599
600
601
602
603
604
605 public static String calculateWidgetVarName(FacesContext context, UIComponent widget) {
606 String widgetVarName = "";
607 if (widget instanceof DojoWidget) {
608 widgetVarName = ((DojoWidget) widget).getWidgetVar();
609 }
610 if (StringUtils.isBlank(widgetVarName)) {
611 widgetVarName = calculateWidgetVarName(widget.getClientId(context));
612 }
613 return widgetVarName;
614 }
615
616
617
618
619
620
621
622
623
624
625 public static void mergeExternalDjConfig(FacesContext context, DojoConfig config) {
626
627
628
629 DojoConfig configSingleton = getDjConfigInstance(context);
630 Class dcConfigClass = DojoConfig.class;
631 Method[] djConfigFieldArr = dcConfigClass.getMethods();
632
633 for (int cnt = 0; cnt < djConfigFieldArr.length; cnt++) {
634
635 try {
636 Method configPropertyField = djConfigFieldArr[cnt];
637 String methodCore = null;
638
639 if ((!configPropertyField.getName().startsWith("getClass") && configPropertyField.getName().startsWith("get"))
640 || configPropertyField.getName().startsWith("is"))
641 methodCore = (configPropertyField.getName().startsWith("get")) ? configPropertyField.getName().substring(3) : configPropertyField.getName()
642 .substring(2);
643
644 if (methodCore != null) {
645 Object val = configPropertyField.invoke(config, null);
646
647 if (val != null) {
648 Class[] setterParams = new Class[1];
649 setterParams[0] = val.getClass();
650
651 Method setMethod = dcConfigClass.getMethod("set" + methodCore, setterParams);
652
653 if (setMethod != null) {
654 Object[] setterArgs = new Object[1];
655 setterArgs[0] = val;
656 setMethod.invoke(configSingleton, setterArgs);
657 }
658 }
659 }
660 } catch (IllegalArgumentException e) {
661 log.error(e);
662 } catch (SecurityException e) {
663 log.error(e);
664 } catch (IllegalAccessException e) {
665 log.error(e);
666 } catch (InvocationTargetException e) {
667 log.error(e);
668 } catch (NoSuchMethodException e) {
669 log.error(e);
670 }
671 }
672
673 }
674
675
676
677
678
679
680
681
682
683
684
685 public static void setExpanded(FacesContext facesContext, Boolean expanded) {
686 HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest();
687 request.setAttribute(INCL_TYPE_REQ_KEY, expanded);
688 }
689
690
691
692
693
694
695
696
697
698
699 public static void writeDebugStatement(ResponseWriter writer, String stmnt) throws IOException {
700 stmnt = createDebugStatement(stmnt);
701 writer.write(stmnt);
702 }
703
704
705
706
707
708
709
710
711
712
713
714
715 private static String createNamespaceScript(String namespace, String location) {
716 StringBuffer namespaceBuilder = new StringBuffer(32);
717 namespaceBuilder.append("dojo.hostenv.setModulePrefix('");
718 namespaceBuilder.append(namespace);
719 namespaceBuilder.append("','");
720 namespaceBuilder.append(location);
721 namespaceBuilder.append("');");
722
723 String namespaceStr = namespaceBuilder.toString();
724
725 return namespaceStr;
726 }
727
728 private static Set getBodyScriptInfos(HttpServletRequest request) {
729 Set set = (Set) request.getAttribute(BODY_SCRIPT_INFOS_ATTRIBUTE_NAME);
730
731 if (set == null) {
732 set = new TreeSet();
733 request.setAttribute(BODY_SCRIPT_INFOS_ATTRIBUTE_NAME, set);
734 }
735
736 return set;
737 }
738
739
740
741
742
743
744
745
746
747
748 private static void writeInlineScript(FacesContext facesContext, UIComponent component, String script) throws IOException {
749 ResponseWriter writer = facesContext.getResponseWriter();
750 writer.startElement(HTML.SCRIPT_ELEM, component);
751 writer.writeAttribute(HTML.TYPE_ATTR, HTML.SCRIPT_TYPE_TEXT_JAVASCRIPT, null);
752 writer.write(script);
753 writer.endElement(HTML.SCRIPT_ELEM);
754 }
755
756 }