KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > applications > editwizard > Config


1 /*
2
3 This software is OSI Certified Open Source Software.
4 OSI Certified is a certification mark of the Open Source Initiative.
5
6 The license (Mozilla version 1.0) can be read at the MMBase site.
7 See http://www.MMBase.org/license
8
9 */

10 package org.mmbase.applications.editwizard;
11
12 import java.util.*;
13 import java.net.*;
14 import org.mmbase.util.xml.URIResolver;
15 import javax.servlet.jsp.PageContext JavaDoc;
16 import javax.servlet.http.HttpServletRequest JavaDoc;
17 import javax.servlet.http.HttpServletResponse JavaDoc;
18
19 import org.mmbase.util.ResourceLoader;
20
21 import org.mmbase.bridge.*;
22 import org.mmbase.util.logging.*;
23 import org.mmbase.util.xml.UtilReader;
24 import org.mmbase.util.Encode;
25
26 /**
27  * This struct contains configuration information for the jsps. This
28  * thing is put in the session. A subclass 'Configurator' can be used
29  * to fill this struct.
30  *
31  * @author Michiel Meeuwissen
32  * @since MMBase-1.6
33  * @version $Id: Config.java,v 1.63.2.1 2006/10/05 14:06:11 pierre Exp $
34  */

35
36 public class Config {
37
38     private static final long serialVersionUID = 1L; // increase this if object serialization changes (which we shouldn't do!)
39

40     /**
41      * Default maximum upload size for files (4 MB).
42      */

43     public final static int DEFAULT_MAX_UPLOAD_SIZE = 4 * 1024 * 1024;
44
45     private static final Logger log = Logging.getLoggerInstance(Config.class);
46
47     // protocol string to test referrer pages
48
private final static String JavaDoc PROTOCOL = "http://";
49
50     // default values
51

52     public static final String JavaDoc CONFIG_FILE = "editwizard.xml";
53
54     public static String JavaDoc wizardStyleSheet = "xsl/wizard.xsl";
55     public static String JavaDoc listStyleSheet = "xsl/list.xsl";
56     public static String JavaDoc searchlistStyleSheet = "xsl/searchlist.xsl";
57     public static int maxUploadSize = DEFAULT_MAX_UPLOAD_SIZE;
58
59     /**
60      * @since MMBase-1.8.1
61      */

62     private static final UtilReader reader = new UtilReader(CONFIG_FILE,
63                                                      new Runnable JavaDoc() {
64                                                          public void run() {
65                                                              readConfiguration(reader.getProperties());
66                                                          }
67                                                      });
68     static {
69         readConfiguration(reader.getProperties());
70     }
71
72     synchronized static void readConfiguration(Map configuration) {
73         String JavaDoc tmp = (String JavaDoc) configuration.get("wizardStyleSheet");
74         if (tmp != null && !tmp.equals("")) {
75             wizardStyleSheet = tmp;
76             log.service("Editwizard default wizard style sheet " + wizardStyleSheet);
77         }
78         tmp = (String JavaDoc) configuration.get("listStyleSheet");
79         if (tmp != null && !tmp.equals("")) {
80             listStyleSheet = tmp;
81             log.service("Editwizard default list style sheet " + listStyleSheet);
82         }
83         tmp = (String JavaDoc) configuration.get("searchlistStyleSheet");
84         if (tmp != null && !tmp.equals("")) {
85             searchlistStyleSheet = tmp;
86             log.service("Editwizard default searchlist style sheet " + searchlistStyleSheet);
87         }
88         tmp = (String JavaDoc) configuration.get("maxUploadSize");
89         if (tmp != null && !tmp.equals("")) {
90             try {
91                 maxUploadSize = Integer.parseInt(tmp);
92             } catch (Exception JavaDoc e) {}
93             log.service("Editwizard default max upload size " + maxUploadSize);
94         }
95
96     }
97
98     public String JavaDoc sessionKey = null;
99     public URIResolver uriResolver = null;
100     public int maxupload = Config.maxUploadSize;
101     public Stack subObjects = new Stack(); // stores the Lists and Wizards.
102
public String JavaDoc sessionId; // necessary if client doesn't accept cookies to store sessionid (this is appended to urls)
103
public String JavaDoc backPage;
104     public String JavaDoc templates;
105     public String JavaDoc language;
106     public String JavaDoc timezone;
107
108     /**
109      * Contains all auxiliary attributes to the first page. Using this map, they can be found in
110      * sub pages as well.
111      *
112      * @since MMBase-1.7
113      */

114     protected Map attributes;
115
116
117     // public String context; (contained in attributes now)
118

119     static public class SubConfig implements java.io.Serializable JavaDoc {
120         public boolean debug = false;
121         public String JavaDoc wizard;
122         public String JavaDoc page;
123         public HashMap popups = new HashMap(); // all popups now in use below this (key -> Config)
124

125         public HashMap attributes = new HashMap();
126
127         /**
128          * Basic configuration. The configuration object passed is updated with information retrieved
129          * from the request object with which the configurator was created. The following parameters are accepted:
130          *
131          * <ul>
132          * <li>wizard</li>
133          //* <li>origin</li>
134          //* <li>context</li>
135          * <li>debug</li>
136          * </ul>
137          *
138          * @since MMBase-1.6.4
139          * @param configurator the configurator containing request information
140          * @throws WizardException if expected parameters were not given or ad bad content
141          */

142         public void configure(Config.Configurator configurator) throws WizardException {
143             wizard = configurator.getParam("wizard", wizard);
144             if (wizard != null && wizard.startsWith("/")) {
145                 try {
146                     wizard = configurator.getResource(wizard).toString();
147                 } catch(MalformedURLException mfue) {
148                     throw new WizardException(mfue);
149                 }
150             }
151             configurator.fillAttributes(attributes);
152
153             // contained in Config#attributes now
154
// setAttribute("origin", configurator.getParam("origin"));
155
// setAttribute("context", configurator.getContext());
156
// debug parameter
157
debug = configurator.getParam("debug", debug);
158         }
159
160         /*
161         public void setAttribute(String name, String value) {
162             if (value != null) {
163                 log.debug("storing "+name+" :"+value);
164                 attributes.put(name,value);
165             }
166         }
167         */

168         /**
169          * Returns available attributes in a map, so they can be passed to the list stylesheet
170          */

171         public Map getAttributes() {
172             Map attributeMap = new HashMap(attributes);
173             return attributeMap;
174         }
175
176     }
177
178     static public class WizardConfig extends SubConfig {
179         public Wizard wiz;
180         public String JavaDoc objectNumber;
181         public String JavaDoc parentFid;
182         public String JavaDoc parentDid;
183         public String JavaDoc popupId;
184
185         /**
186          * Configure a wizard. The configuration object passed is updated with information retrieved
187          * from the request object with which the configurator was created. The following parameters are accepted:
188          *
189          * <ul>
190          * <li>popupid</li>
191          * <li>objectnumber</li>
192          * </ul>
193          *
194          * @since MMBase-1.6.4
195          * @param configurator the configurator containing request information
196          * @throws WizardException if expected parameters were not given
197          */

198         public void configure(Config.Configurator configurator) throws WizardException {
199             super.configure(configurator);
200             popupId = configurator.getParam("popupid", "");
201             objectNumber = configurator.getParam("objectnumber");
202         }
203
204         /**
205          * Returns available attributes in a map, so they can be passed to the list stylesheet
206          */

207         /*
208         public Map getAttributes() {
209             Map attributeMap = super.getAttributes();
210             attributeMap.put("popupid", popupId);
211             if (objectNumber!=null) attributeMap.put("objectnumber", objectNumber);
212
213             return attributeMap;
214         }
215         */

216     }
217
218     static public class ListConfig extends SubConfig {
219
220         // constants for 'search' parameter. Order of value matters (force must be bigger then yes)
221
public static final int SEARCH_NO = 0;
222
223         public static final int SEARCH_AUTO = 5; // search if searchfields given.
224

225         public static final int SEARCH_YES = 10;
226         public static final int SEARCH_FORCE = 11; // like 'yes', but searching occurs only if not searching empty string.
227

228
229         public String JavaDoc title;
230         public URL template;
231         public String JavaDoc fields;
232         public String JavaDoc startNodes;
233         public String JavaDoc nodePath;
234         public String JavaDoc constraints;
235         public String JavaDoc orderBy;
236         public String JavaDoc directions;
237         public String JavaDoc searchDir;
238
239         public String JavaDoc searchFields;
240         public String JavaDoc realSearchField;
241         public String JavaDoc searchValue="";
242         public String JavaDoc searchType="like";
243         public String JavaDoc baseConstraints;
244         public int search = SEARCH_AUTO;
245
246         public int age = -1;
247         public int start = 0;
248         public boolean distinct = false;
249         public int pagelength = 50;
250         public int maxpagecount = 10;
251
252         public boolean multilevel = false;
253         public String JavaDoc mainObjectName = null;
254         public List fieldList = null;
255
256         protected Cloud cloud;
257
258         ListConfig(Cloud cloud) {
259             this.cloud = cloud;
260         }
261
262         /**
263          * @deprecated
264          */

265         ListConfig() { // for backwards compatibility
266
this.cloud = null;
267         }
268
269         private boolean parsed = false;
270
271         protected static String JavaDoc removeDigits(String JavaDoc complete) {
272             int end = complete.length() - 1;
273             while (Character.isDigit(complete.charAt(end))) {
274                 --end;
275             }
276             return complete.substring(0, end + 1);
277         }
278
279         /**
280          * Configure a list page. The configuration object passed is updated with information retrieved
281          * from the request object with which the configurator was created. The following parameters are accepted:
282          *
283          * <ul>
284          * <li>title</li>
285          * <li>pagelength</li>
286          * <li>maxpagecount</li>
287          * <li>startnodes</li>
288          * <li>fields</li>
289          * <li>age</li>
290          * <li>start</li>
291          * <li>searchtype</li>
292          * <li>searchfields</li>
293          * <li>searchvalue</li>
294          * <li>searchdir</li>
295          * <li>constraints</li>
296          * <li>forcesearch</li>
297          * <li>realsearchfield</li>
298          * <li>directions</li>
299          * <li>orderby</li>
300          * <li>distinct</li>
301          * </ul>
302          *
303          * @since MMBase-1.6.4
304          * @param configurator the configurator containing request information
305          */

306         public void configure(Config.Configurator configurator) throws WizardException {
307             super.configure(configurator);
308             title = configurator.getParam("title", title);
309             pagelength = configurator.getParam("pagelength", new Integer JavaDoc(pagelength)).intValue();
310             maxpagecount = configurator.getParam("maxpagecount", new Integer JavaDoc(maxpagecount)).intValue();
311             startNodes = configurator.getParam("startnodes", startNodes);
312
313             // Get nodepath parameter. if a (new) parameter was passed,
314
// re-parse the node path and field list
315
// This allows for custom list stylesheets to make a query more or less complex through
316
// user interaction
317
String JavaDoc parameter = configurator.getParam("nodepath");
318             if (parameter != null) {
319                 nodePath = parameter;
320                 parsed = false;
321             }
322             if (nodePath == null) {
323                 throw new WizardException("The parameter 'nodepath' is required but not given.");
324             }
325
326             // Get fields parameter. if a (new) parameter was passed,
327
// re-parse the node path and field list
328
// This allows for custom list stylesheets to make a query more or less complex through
329
// user interaction
330
parameter = configurator.getParam("fields");
331             if (parameter != null) {
332                 fields = parameter;
333                 parsed = false;
334             }
335             if (fields == null) {
336                 //throw new WizardException("The parameter 'fields' is required but not given.");
337
log.debug("The parameter 'fields' is not given, going to take the first field");
338                 // this will happen during parsing.
339

340             }
341
342             age = configurator.getParam("age", new Integer JavaDoc(age)).intValue();
343             if (age >= 99999) age=-1;
344
345             start = configurator.getParam("start", new Integer JavaDoc(start)).intValue();
346             searchType = configurator.getParam("searchtype", searchType);
347             searchFields = configurator.getParam("searchfields", searchFields);
348             searchValue = configurator.getParam("searchvalue", searchValue);
349             searchDir = configurator.getParam("searchdir", searchDir);
350             searchDir = configurator.getParam("searchdirs", searchDir);
351             baseConstraints = configurator.getParam("constraints", baseConstraints);
352             String JavaDoc searchString = configurator.getParam("search", (String JavaDoc) null);
353             if (searchString != null) {
354                 searchString = searchString.toLowerCase();
355                 if (searchString.equals("auto")) {
356                     search = SEARCH_AUTO;
357                 } else if (searchString.equals("no")) {
358                     search = SEARCH_NO;
359                 } else if (searchString.equals("yes")) {
360                     search = SEARCH_YES;
361                 } else if (searchString.equals("force")) {
362                     search = SEARCH_FORCE;
363                 } else {
364                     throw new WizardException("Unknown value for search parameter '" + searchString + "'");
365                 }
366             } else {
367                 log.debug("Search is null?");
368             }
369
370             /// what the heck is this.
371
realSearchField = configurator.getParam("realsearchfield", realSearchField);
372
373             if (searchFields == null) {
374                 constraints = baseConstraints;
375             } else {
376                 StringBuffer JavaDoc constraintsBuffer;
377                 // search type: default
378
String JavaDoc sType = searchType;
379                 // get the actual field to search on.
380
// this can be 'owner' or 'number' instead of the original list of searchfields,
381
// in which case searchtype may change
382
String JavaDoc sFields = realSearchField;
383                 if (sFields == null) sFields = searchFields;
384                 if (sFields.equals("owner") || sFields.endsWith(".owner")) {
385                     sType = "like";
386                 } else if (sFields.equals("number") || sFields.endsWith(".number")) {
387                     sType = "equals";
388                 }
389                 String JavaDoc where = Encode.encode("ESCAPE_SINGLE_QUOTE",searchValue);
390                 constraintsBuffer = null;
391                 if (sType.equals("like")) {
392                     if (! "".equals(where)) {
393                         where = " LIKE '%" + where.toLowerCase() + "%'";
394                     }
395                 } else if (sType.equals("string")) {
396                     if (! "".equals(where)) {
397                         where = " = '" + where + "'";
398                     }
399                 } else {
400                     if (where.equals("")) {
401                         where = "0";
402                     }
403                     if (sType.equals("greaterthan")) {
404                         where = " > " + where;
405                     } else if (sType.equals("lessthan")) {
406                         where = " < " + where;
407                     } else if (sType.equals("notgreaterthan")) {
408                         where = " <= " + where;
409                     } else if (sType.equals("notlessthan")) {
410                         where = " >= " + where;
411                     } else if (sType.equals("notequals")) {
412                         where = " != " + where;
413                     } else { // equals
414
where = " = " + where;
415                     }
416                 }
417                 if (! "".equals(where)) {
418                     StringTokenizer searchTokens= new StringTokenizer(sFields, ",");
419                     while (searchTokens.hasMoreTokens()) {
420                         String JavaDoc tok = searchTokens.nextToken();
421                         if (constraintsBuffer != null) {
422                             constraintsBuffer.append(" OR ");
423                         } else {
424                             constraintsBuffer = new StringBuffer JavaDoc();
425                         }
426                         if (sType.equals("like")) {
427                             constraintsBuffer.append("lower([").append(tok).append("])").append(where);
428                         } else {
429                             constraintsBuffer.append('[').append(tok).append(']').append(where);
430                         }
431                     }
432                 }
433                 if (baseConstraints != null) {
434                     if (constraintsBuffer != null) {
435                         constraints = "(" + baseConstraints + ") and (" + constraintsBuffer.toString() + ")";
436                     } else {
437                         constraints = baseConstraints;
438                     }
439                 } else {
440                     if (constraintsBuffer != null) {
441                         constraints = constraintsBuffer.toString() ;
442                     } else {
443                         constraints = null;
444                     }
445                 }
446             }
447             searchDir = configurator.getParam("searchdir", searchDir);
448             directions = configurator.getParam("directions", directions);
449             orderBy = configurator.getParam("orderby", orderBy);
450             distinct = configurator.getParam("distinct", distinct);
451
452             // only perform the following is there was no prior parsing
453
if (!parsed) {
454                 String JavaDoc defaultTemplate = Config.listStyleSheet;
455                 if ("search".equals(configurator.getParam("listtype"))) {
456                      defaultTemplate =Config.searchlistStyleSheet;
457                 }
458                 String JavaDoc templatePath = configurator.getParam("template", defaultTemplate);
459                 try {
460                     template = configurator.resolveToURL(templatePath);
461                 } catch (Exception JavaDoc e) {
462                     throw new WizardException(e);
463                 }
464
465                 // determine mainObjectName from main parameter
466
mainObjectName = configurator.getParam("main", (String JavaDoc) null); // mainObjectName);
467

468                 boolean mainPresent = mainObjectName != null;
469
470                 // parse the nodePath.
471
StringTokenizer stok = new StringTokenizer(nodePath, ",");
472                 int nodecount = stok.countTokens();
473                 if (nodecount == 0) {
474                     throw new WizardException("The parameter 'nodepath' should be passed with a comma-separated list of nodemanagers.");
475                 }
476                 multilevel = nodecount > 1;
477                 if (mainObjectName == null) {
478                     // search last manager - default 'main' object.
479
while (stok.hasMoreTokens()) {
480                         mainObjectName = stok.nextToken();
481                     }
482                 }
483                 // now we always have a mainObjectName already (the last from nodePath)
484

485                 // so we can make up a nice default for fields.
486
if (fields == null) {
487                     if (cloud != null) {
488                         StringBuffer JavaDoc fieldsBuffer = new StringBuffer JavaDoc();
489                         FieldIterator i = cloud.getNodeManager(removeDigits(mainObjectName)).getFields(org.mmbase.bridge.NodeManager.ORDER_LIST).fieldIterator();
490                         while (i.hasNext()) {
491                             Field field = i.nextField();
492                             if (multilevel && field.isVirtual()) {
493                                 // cannot be queried any way.
494
// these fields are directly added the query. You could perhaps deterin virtual fields afterwards.
495
// should perhaps also be valid for monolevels.
496
continue;
497                             }
498                             fieldsBuffer.append(multilevel ? mainObjectName + "." : "" ).append(field.getName());
499                             if (i.hasNext()) fieldsBuffer.append(',');
500                         }
501                         fields = fieldsBuffer.toString();
502                     } else {
503                         // the list.jsp _does_ provide a cloud, but well, perhaps people have old list.jsp's?
504
throw new WizardException("The parameter 'fields' is required but not given (or make sure there is a cloud)");
505                     }
506                 }
507
508                 // create fieldlist
509
stok = new StringTokenizer(fields, ",");
510                 if (stok.countTokens() == 0) {
511                     throw new WizardException("The parameter 'fields' should be passed with a comma-separated list of fieldnames.");
512                 }
513
514                 fieldList = new ArrayList();
515                 while (stok.hasMoreTokens()) {
516                     String JavaDoc token = stok.nextToken();
517                     fieldList.add(token);
518                     // Check if the number field for a multilevel object was specified
519
// (determine mainObjectName from fieldlist)
520

521                     // MM: so, there are several ways to specify the 'main' object.
522
// 1. defaults to last in nodePath
523
// 2. with 'main' parameter
524
// 3. with the first 'number' field of the fields parameter.
525

526                     // I think 2 & 3 serve the same goal and 3 must be deprecated.
527

528                     if (! mainPresent && token.endsWith(".number")) {
529                         mainObjectName = token.substring(0, token.length() - 7);
530                         mainPresent = true;
531                         // Only to avoid reentering this 'if'. Of course the 'main' parameter actually is still not present.
532
}
533                 }
534
535                 if (search >= SEARCH_YES && searchFields == null) {
536                     if (cloud != null) {
537                         StringBuffer JavaDoc searchFieldsBuffer = new StringBuffer JavaDoc();
538                         FieldIterator i = cloud.getNodeManager(removeDigits(mainObjectName)).
539                             getFields(org.mmbase.bridge.NodeManager.ORDER_LIST).fieldIterator();
540                         while (i.hasNext()) {
541                             Field f = i.nextField();
542                             if (f.getType() == Field.TYPE_STRING && ! f.getName().equals("owner")) {
543                                 if (searchFieldsBuffer.length() > 0) searchFieldsBuffer.append(',');
544                                 searchFieldsBuffer.append(multilevel ? mainObjectName + "." : "" ).append(f.getName());
545                             }
546                         }
547                         searchFields = searchFieldsBuffer.toString();
548
549                     } else {
550                         // the list.jsp _does_ provide a cloud, but well, perhaps people have old list.jsp's?
551
throw new WizardException("Cannot auto-determin search-fields without a cloud (use a newer list.jsp");
552                     }
553                 }
554
555                 if (search == SEARCH_NO && searchFields != null) {
556                     log.debug("Using searchfields and explicitiy no search");
557                     searchFields = null;
558                 }
559
560                 // add the main object's numberfield to fields
561
// this ensures the field is retrieved even if distinct weas specified
562
String JavaDoc numberField = "number";
563                 if (multilevel) {
564                     numberField = mainObjectName + ".number";
565                 }
566                 if (fieldList.indexOf(numberField) == -1) {
567                     fields = numberField + "," + fields;
568                 }
569                 parsed = true;
570             }
571
572         }
573
574         /**
575          * Returns available attributes in a map, so they can be passed to the list stylesheet
576          */

577         public Map getAttributes() {
578             Map attributeMap = super.getAttributes();
579             // mandatory attributes
580
attributeMap.put("nodepath", nodePath);
581             attributeMap.put("fields", fields);
582             // optional attributes
583
if (title != null) attributeMap.put("title", title);
584             attributeMap.put("age", age+"");
585             if (multilevel) attributeMap.put("objecttype",mainObjectName);
586             if (startNodes!=null) attributeMap.put("startnodes", startNodes);
587             if (orderBy!=null) attributeMap.put("orderby", orderBy);
588             if (directions!=null) attributeMap.put("directions", directions);
589             attributeMap.put("distinct", distinct+"");
590             if (searchDir!=null) attributeMap.put("searchdir", searchDir);
591             if (baseConstraints!=null) attributeMap.put("constraints", baseConstraints);
592             // search attributes
593
if (searchType!=null) attributeMap.put("searchtype", searchType);
594             if (searchFields!=null) attributeMap.put("searchfields", searchFields);
595             if (realSearchField!=null) attributeMap.put("realsearchfield", realSearchField);
596             if (searchValue!=null) attributeMap.put("searchvalue", searchValue);
597
598             return attributeMap;
599         }
600     }
601
602     /**
603      * To fill the Config struct, this 'Configurator' exists. You
604      * could extend it to change wich query parameters must be used,
605      * and what are the defaults and so on.
606      */

607     public static class Configurator {
608         private static final Logger log = Logging.getLoggerInstance(Config.class);
609
610         protected PageContext JavaDoc page;
611         protected HttpServletRequest JavaDoc request;
612         protected HttpServletResponse JavaDoc response;
613         private Config config;
614
615         public Configurator(PageContext JavaDoc pageContext, Config c) throws WizardException, java.net.MalformedURLException JavaDoc {
616             page = pageContext;
617             request = (HttpServletRequest JavaDoc)page.getRequest();
618             response = (HttpServletResponse JavaDoc)page.getResponse();
619             config = c;
620
621             config.sessionId = response.encodeURL("test.jsp").substring(8);
622             if (log.isDebugEnabled()) {
623                 log.debug("Sessionid : " + config.sessionId);
624             }
625
626             if (config.language == null) {
627                 config.language = getParam("language", org.mmbase.bridge.ContextProvider.getDefaultCloudContext().getDefaultLocale().getLanguage());
628             }
629
630             if (config.timezone == null) {
631                 config.timezone = getParam("timezone", "");
632             }
633
634             /*
635               // contained in config.attributes now
636             if (config.context == null) {
637                 config.context = getParam("context");
638             }
639             */

640             if (config.attributes == null) {
641                 config.attributes = new HashMap();
642                 fillAttributes(config.attributes);
643             }
644             // The editwizard need to know the 'backpage' (for 'index' and 'logout' links).
645
// It can be specified by a 'referrer' parameter. If this is missing the
646
// 'Referer' http header is tried.
647
if (config.backPage == null) {
648                 log.debug("No backpage. Getting from parameters");
649                 config.backPage = org.mmbase.util.Encode.decode("ESCAPE_URL_PARAM", getParam("referrer", "")).replace('\\', '/'); // this translations seems to be needed by some windows setups
650

651                 if (config.backPage.equals("")) {
652                     log.debug("No backpage getting from header");
653                     config.backPage = request.getHeader("Referer");
654                 }
655                 if (config.backPage == null) {
656                     log.debug("No backpage setting to ''");
657                     config.backPage = "";
658                 }
659             }
660
661             // if no 'uriResolver' is configured yet, then there is one created right now:
662
// the uriResolver is used to find xml's and xsl's.
663
if (config.uriResolver == null) {
664                 if (log.isDebugEnabled()) {
665                     log.trace("creating uriresolver (backpage = " + config.backPage + ")");
666                 }
667                 URIResolver.EntryList extraDirs = new URIResolver.EntryList();
668
669                 /* Determin the 'referring' page, and add its directory to the URIResolver.
670                    That means that xml can be placed relative to this page, and xsl's int xsl-dir.
671                  */

672                 URL ref;
673                 // capture direct reference of http:// and https:// referers
674
int protocolPos= config.backPage.indexOf(PROTOCOL);
675
676
677
678
679                 if (protocolPos >=0 ) { // given absolutely
680
String JavaDoc path = new URL(config.backPage).getPath();
681                     ref = new URL(getResource(path.substring(request.getContextPath().length())), ".");
682                     // TODO: What if it happened to be not from the same server?
683
} else {
684                     // Was given relatively, that's trickie, because cannot use URL object to take of query.
685
String JavaDoc bp = config.backPage;
686                     int questionPos = bp.indexOf('?');
687                     if (questionPos != -1) {
688                         bp = bp.substring(0, questionPos);
689                     }
690                     URL path = getResource(bp);
691
692                     if (path != null) {
693                         ref = new URL(path, ".");
694                     } else {
695                         ref = null;
696                     }
697                 }
698                 if (ref != null) {
699                     if (! config.language.equals("")) {
700                         URL refi18n = new URL(ref, "i18n/" + config.language);
701                         if (getResource(refi18n.getPath()) != null) {
702                             extraDirs.add("refi18n:", refi18n);
703                         }
704                     }
705                     extraDirs.add("ref:", ref);
706                 } else {
707                     log.warn("" + ref + " does not exist");
708                 }
709
710                 /* Optionally, you can indicate with a 'templates' option where the xml's and
711                    xsl must be searched (if they cannot be found in the referring dir).
712                 */

713                 config.templates = request.getParameter("templates");
714
715                 if (config.templates != null) {
716                     URL templatesDir = getResource(config.templates);
717                     if (templatesDir == null) {
718                         throw new WizardException("" + config.templates + " does not exist");
719                     }
720                     extraDirs.add("templates:", templatesDir);
721                 }
722
723                 /**
724                  * Then of course also the directory of editwizard installation must be added. This will allow for the 'basic' xsl's to be found,
725                  * and also for 'library' editors.
726                  */

727
728                 URL jspFileDir = new URL(getResource(request.getServletPath()), "."); // the directory of this jsp (list, wizard)
729
URL basedir = new URL(jspFileDir, "../data/"); // ew default data/xsls is in ../data then
730

731                 if (! config.language.equals("")) {
732                     URL i18n = new URL(basedir, "i18n/" + config.language + "/");
733                     if (i18n == null) {
734                         if (! "en".equals(config.language)) { // english is default anyway
735
log.warn("Tried to internationalize the editwizard for language " + config.language + " for which support is lacking (" + i18n + " is not an existing directory)");
736                         }
737                     } else {
738                         extraDirs.add("i18n:", i18n);
739                     }
740                 }
741
742                 extraDirs.add("ew:", basedir);
743                 config.uriResolver = new URIResolver(jspFileDir, extraDirs);
744                 config.maxupload = getParam("maxsize", config.maxupload);
745             }
746         }
747
748         /*
749         public String getRealPath(String path) {
750             return page.getServletContext().getRealPath(path);
751         }
752         */

753         public URL getResource(String JavaDoc path) throws MalformedURLException {
754             return ResourceLoader.getWebRoot().getResource(path);
755             /// page.getServletContext().getResource(path) (not using ResourceLoader)
756
}
757
758
759         public URL resolveToURL(String JavaDoc templatePath) throws javax.xml.transform.TransformerException JavaDoc {
760             return config.uriResolver.resolveToURL(templatePath, null);
761         }
762
763
764         public PageContext JavaDoc getPage() {
765             return page;
766         }
767
768         protected String JavaDoc getParam(String JavaDoc paramName) {
769             return request.getParameter(paramName);
770         }
771
772         protected String JavaDoc getParam(String JavaDoc paramName, String JavaDoc defaultValue) {
773             String JavaDoc value = getParam(paramName);
774             if (value == null) value = defaultValue;
775             return value;
776         }
777
778         protected int getParam(String JavaDoc paramName, int def) {
779             String JavaDoc i = getParam(paramName);
780             if (i == null || i.equals("")) return def;
781             return new Integer JavaDoc(i).intValue();
782         }
783
784         protected Integer JavaDoc getParam(String JavaDoc paramName, Integer JavaDoc def) {
785             String JavaDoc i = getParam(paramName);
786             if (i == null || i.equals("")) return def;
787             return new Integer JavaDoc(i);
788         }
789
790         protected boolean getParam(String JavaDoc paramName, boolean def) {
791             String JavaDoc b = getParam(paramName);
792             if (b == null) return def;
793             return Boolean.valueOf(b).booleanValue();
794         }
795
796         protected Boolean JavaDoc getParam(String JavaDoc paramName, Boolean JavaDoc def) {
797             String JavaDoc b = getParam(paramName);
798             if (b == null) return def;
799             return Boolean.valueOf(b);
800         }
801
802         /**
803          * Fills the given map with all attributes from the URI, but first all attributes from the
804          * first call are added. No arrays supported, only single values.
805          * @since MMBase-1.7
806          */

807         protected void fillAttributes(Map map) {
808             map.putAll(config.attributes); // start with setting in global config
809

810             Enumeration e = request.getParameterNames();
811             while (e.hasMoreElements()) {
812                 String JavaDoc param = (String JavaDoc) e.nextElement();
813                 map.put(param, request.getParameter(param));
814             }
815
816             // map.putAll(request.getParameterMap()); key -> String[] (not useable)
817
// log.info(map);
818
}
819
820         public String JavaDoc getBackPage(){
821             if(config.subObjects.size() == 0) {
822                 return config.backPage;
823             } else {
824                 return ((SubConfig) config.subObjects.peek()).page;
825             }
826         }
827
828
829         public ListConfig createList(Cloud cloud) {
830             ListConfig l = new ListConfig(cloud);
831             l.page = response.encodeURL(request.getServletPath() + "?proceed=yes");
832             return l;
833         }
834
835         /**
836          * @deprecated use createList(cloud)
837          */

838         public ListConfig createList() {
839             return createList(null);
840         }
841
842         public Config.WizardConfig createWizard(Cloud cloud) throws WizardException {
843             WizardConfig wizard = new WizardConfig();
844             wizard.page = response.encodeURL(request.getServletPath() + "?proceed=yes");
845             config(wizard); // determine the objectnumber and assign the wizard name.
846
// wizard should now have a name!
847
if (wizard.wizard == null) {
848                 throw new WizardException("Wizardname may not be null, configurated by class with name: " + this.getClass().getName());
849             }
850             wizard.wiz = new Wizard(request.getContextPath(), config.uriResolver, wizard, cloud);
851             wizard.wiz.setSessionId(config.sessionId);
852             wizard.wiz.setSessionKey(config.sessionKey);
853             wizard.wiz.setReferrer(config.backPage);
854             wizard.wiz.setTemplatesDir(config.templates);
855             wizard.wiz.setTimezone(config.timezone);
856             return wizard;
857         }
858
859         /**
860          * Configure a list or wizard. The configuration object passed is updated with information retrieved
861          * from the request object with which the configurator was created.
862          * @since MMBase-1.6.4
863          * @param config the configuration object for the list or wizard.
864          */

865         public void config(Config.SubConfig config) throws WizardException {
866             config.configure(this);
867         }
868
869     }
870
871 }
872
Popular Tags