001: /*
002: * $Header: /home/cvspublic/jakarta-struts/src/share/org/apache/struts/tiles/xmlDefinition/I18nFactorySet.java,v 1.13 2004/03/14 06:23:49 sraeburn Exp $
003: * $Revision: 1.13 $
004: * $Date: 2004/03/14 06:23:49 $
005: *
006: * Copyright 1999-2004 The Apache Software Foundation.
007: *
008: * Licensed under the Apache License, Version 2.0 (the "License");
009: * you may not use this file except in compliance with the License.
010: * You may obtain a copy of the License at
011: *
012: * http://www.apache.org/licenses/LICENSE-2.0
013: *
014: * Unless required by applicable law or agreed to in writing, software
015: * distributed under the License is distributed on an "AS IS" BASIS,
016: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
017: * See the License for the specific language governing permissions and
018: * limitations under the License.
019: */
020: package org.vfny.geoserver.config.web.tiles.definition;
021:
022: import org.apache.commons.logging.Log;
023: import org.apache.commons.logging.LogFactory;
024: import org.apache.struts.taglib.tiles.ComponentConstants;
025: import org.apache.struts.tiles.DefinitionsFactoryException;
026: import org.apache.struts.tiles.FactoryNotFoundException;
027: import org.apache.struts.tiles.xmlDefinition.DefinitionsFactory;
028: import org.apache.struts.tiles.xmlDefinition.FactorySet;
029: import org.apache.struts.tiles.xmlDefinition.XmlDefinitionsSet;
030: import org.apache.struts.tiles.xmlDefinition.XmlParser;
031: import org.springframework.core.io.Resource;
032: import org.springframework.web.context.support.WebApplicationContextUtils;
033: import org.xml.sax.SAXException;
034: import java.io.FileNotFoundException;
035: import java.io.IOException;
036: import java.io.InputStream;
037: import java.util.ArrayList;
038: import java.util.HashMap;
039: import java.util.Iterator;
040: import java.util.List;
041: import java.util.Locale;
042: import java.util.Map;
043: import java.util.StringTokenizer;
044: import javax.servlet.ServletContext;
045: import javax.servlet.ServletRequest;
046: import javax.servlet.http.HttpServletRequest;
047: import javax.servlet.http.HttpSession;
048:
049: /**
050: * Definitions factory.
051: * This implementation allows to have a set of definition factories.
052: * There is a main factory and one factory for each file associated to a Locale.
053: *
054: * To retrieve a definition, we first search for the appropriate factory using
055: * the Locale found in session context. If no factory is found, use the
056: * default one. Then we ask the factory for the definition.
057: *
058: * A definition factory file is loaded using main filename extended with locale code
059: * (ex : <code>templateDefinitions_fr.xml</code>). If no file is found under this name, use default file.
060: */
061: public class MultipleDefinitionsFactory extends FactorySet {
062: /**
063: *
064: */
065: private static final long serialVersionUID = 5245695468031817480L;
066:
067: /**
068: * Commons Logging instance.
069: */
070: protected static Log log = LogFactory
071: .getLog(MultipleDefinitionsFactory.class);
072:
073: /**
074: * Config file parameter name.
075: */
076: public static final String DEFINITIONS_CONFIG_PARAMETER_NAME = "definitions-config";
077:
078: /**
079: * Config file parameter name.
080: */
081: public static final String PARSER_DETAILS_PARAMETER_NAME = "definitions-parser-details";
082:
083: /**
084: * Config file parameter name.
085: */
086: public static final String PARSER_VALIDATE_PARAMETER_NAME = "definitions-parser-validate";
087:
088: /**
089: * Possible definition filenames.
090: */
091: public static final String[] DEFAULT_DEFINITION_FILENAMES = {
092: "/WEB-INF/tileDefinitions.xml",
093: "/WEB-INF/componentDefinitions.xml",
094: "/WEB-INF/instanceDefinitions.xml" };
095:
096: /**
097: * Maximum length of one branch of the resource search path tree.
098: * Used in getBundle().
099: */
100: private static final int MAX_BUNDLES_SEARCHED = 2;
101:
102: /**
103: * Default filenames extension.
104: */
105: public static final String FILENAME_EXTENSION = ".xml";
106:
107: /**
108: * Default factory.
109: */
110: protected DefinitionsFactory defaultFactory = null;
111:
112: /**
113: * XML parser used.
114: * Attribute is transient to allow serialization. In this implementaiton,
115: * xmlParser is created each time we need it ;-(.
116: */
117: protected transient XmlParser xmlParser;
118:
119: /**
120: * Do we want validating parser. Default is <code>false</code>.
121: * Can be set from servlet config file.
122: */
123: protected boolean isValidatingParser = false;
124:
125: /**
126: * Parser detail level. Default is 0.
127: * Can be set from servlet config file.
128: */
129: protected int parserDetailLevel = 0;
130:
131: /**
132: * Names of files containing instances descriptions.
133: */
134: private List filenames = null;
135:
136: /**
137: * Collection of already loaded definitions set, referenced by their suffix.
138: */
139: private Map loaded = null;
140:
141: /**
142: * Parameterless Constructor.
143: * Method {@link #initFactory} must be called prior to any use of created factory.
144: */
145: public MultipleDefinitionsFactory() {
146: super ();
147: }
148:
149: /**
150: * Constructor.
151: * Init the factory by reading appropriate configuration file.
152: * @param servletContext Servlet context.
153: * @param properties Map containing all properties.
154: * @throws FactoryNotFoundException Can't find factory configuration file.
155: */
156: public MultipleDefinitionsFactory(ServletContext servletContext,
157: Map properties) throws DefinitionsFactoryException {
158: initFactory(servletContext, properties);
159: }
160:
161: /**
162: * Initialization method.
163: * Init the factory by reading appropriate configuration file.
164: * This method is called exactly once immediately after factory creation in
165: * case of internal creation (by DefinitionUtil).
166: * @param servletContext Servlet Context passed to newly created factory.
167: * @param properties Map of name/property passed to newly created factory. Map can contains
168: * more properties than requested.
169: * @throws DefinitionsFactoryException An error occur during initialization.
170: */
171: public void initFactory(ServletContext servletContext,
172: Map properties) throws DefinitionsFactoryException {
173: // Set some property values
174: String value = (String) properties
175: .get(PARSER_VALIDATE_PARAMETER_NAME);
176:
177: if (value != null) {
178: isValidatingParser = Boolean.valueOf(value).booleanValue();
179: }
180:
181: value = (String) properties.get(PARSER_DETAILS_PARAMETER_NAME);
182:
183: if (value != null) {
184: try {
185: parserDetailLevel = Integer.valueOf(value).intValue();
186: } catch (NumberFormatException ex) {
187: log.error("Bad format for parameter '"
188: + PARSER_DETAILS_PARAMETER_NAME
189: + "'. Integer expected.");
190: }
191: }
192:
193: // init factory withappropriate configuration file
194: // Try to use provided filename, if any.
195: // If no filename are provided, try to use default ones.
196: String filename = (String) properties
197: .get(DEFINITIONS_CONFIG_PARAMETER_NAME);
198:
199: if (filename != null) { // Use provided filename
200:
201: try {
202: initFactory(servletContext, filename);
203:
204: if (log.isDebugEnabled()) {
205: log.debug("Factory initialized from file '"
206: + filename + "'.");
207: }
208: } catch (FileNotFoundException ex) { // A filename is specified, throw appropriate error.
209: log.error(ex.getMessage() + " : Can't find file '"
210: + filename + "'");
211: throw new FactoryNotFoundException(ex.getMessage()
212: + " : Can't find file '" + filename + "'");
213: }
214: } else { // try each default file names
215:
216: for (int i = 0; i < DEFAULT_DEFINITION_FILENAMES.length; i++) {
217: filename = DEFAULT_DEFINITION_FILENAMES[i];
218:
219: try {
220: initFactory(servletContext, filename);
221:
222: if (log.isInfoEnabled()) {
223: log.info("Factory initialized from file '"
224: + filename + "'.");
225: }
226: } catch (FileNotFoundException ex) {
227: // Do nothing
228: }
229: }
230: }
231: }
232:
233: /**
234: * Initialization method.
235: * Init the factory by reading appropriate configuration file.
236: * This method is called exactly once immediately after factory creation in
237: * case of internal creation (by DefinitionUtil).
238: * @param servletContext Servlet Context passed to newly created factory.
239: * @param proposedFilename File names, comma separated, to use as base file names.
240: * @throws DefinitionsFactoryException An error occur during initialization.
241: */
242: protected void initFactory(ServletContext servletContext,
243: String proposedFilename)
244: throws DefinitionsFactoryException, FileNotFoundException {
245: // Init list of filenames
246: StringTokenizer tokenizer = new StringTokenizer(
247: proposedFilename, ",");
248: this .filenames = new ArrayList(tokenizer.countTokens());
249:
250: while (tokenizer.hasMoreTokens()) {
251: this .filenames.add(tokenizer.nextToken().trim());
252: }
253:
254: loaded = new HashMap();
255: defaultFactory = createDefaultFactory(servletContext);
256:
257: if (log.isDebugEnabled()) {
258: log.debug("default factory:" + defaultFactory);
259: }
260: }
261:
262: /**
263: * Get default factory.
264: * @return Default factory
265: */
266: protected DefinitionsFactory getDefaultFactory() {
267: return defaultFactory;
268: }
269:
270: /**
271: * Create default factory .
272: * Create InstancesMapper for specified Locale.
273: * If creation failes, use default mapper and log error message.
274: * @param servletContext Current servlet context. Used to open file.
275: * @return Created default definition factory.
276: * @throws DefinitionsFactoryException If an error occur while creating factory.
277: * @throws FileNotFoundException if factory can't be loaded from filenames.
278: */
279: protected DefinitionsFactory createDefaultFactory(
280: ServletContext servletContext)
281: throws DefinitionsFactoryException, FileNotFoundException {
282: XmlDefinitionsSet rootXmlConfig = parseXmlFiles(servletContext,
283: "", null);
284:
285: if (rootXmlConfig == null) {
286: throw new FileNotFoundException();
287: }
288:
289: rootXmlConfig.resolveInheritances();
290:
291: if (log.isDebugEnabled()) {
292: log.debug(rootXmlConfig);
293: }
294:
295: DefinitionsFactory factory = new DefinitionsFactory(
296: rootXmlConfig);
297:
298: if (log.isDebugEnabled()) {
299: log.debug("factory loaded : " + factory);
300: }
301:
302: return factory;
303: }
304:
305: /**
306: * Extract key that will be used to get the sub factory.
307: * @param name Name of requested definition
308: * @param request Current servlet request.
309: * @param servletContext Current servlet context.
310: * @return the key or <code>null</code> if not found.
311: */
312: protected Object getDefinitionsFactoryKey(String name,
313: ServletRequest request, ServletContext servletContext) {
314: Locale locale = null;
315:
316: try {
317: HttpSession session = ((HttpServletRequest) request)
318: .getSession(false);
319:
320: if (session != null) {
321: locale = (Locale) session
322: .getAttribute(ComponentConstants.LOCALE_KEY);
323: }
324: } catch (ClassCastException ex) {
325: log.error("I18nFactorySet.getDefinitionsFactoryKey");
326: ex.printStackTrace();
327: }
328:
329: return locale;
330: }
331:
332: /**
333: * Create a factory for specified key.
334: * If creation failes, return default factory and log an error message.
335: * @param key The key.
336: * @param request Servlet request.
337: * @param servletContext Servlet context.
338: * @return Definition factory for specified key.
339: * @throws DefinitionsFactoryException If an error occur while creating factory.
340: */
341: protected DefinitionsFactory createFactory(Object key,
342: ServletRequest request, ServletContext servletContext)
343: throws DefinitionsFactoryException {
344: if (key == null) {
345: return getDefaultFactory();
346: }
347:
348: // Build possible postfixes
349: List possiblePostfixes = calculatePostixes("", (Locale) key);
350:
351: // Search last postix corresponding to a config file to load.
352: // First check if something is loaded for this postfix.
353: // If not, try to load its config.
354: XmlDefinitionsSet lastXmlFile = null;
355: DefinitionsFactory factory = null;
356: String curPostfix = null;
357: int i = 0;
358:
359: for (i = possiblePostfixes.size() - 1; i >= 0; i--) {
360: curPostfix = (String) possiblePostfixes.get(i);
361:
362: // Already loaded ?
363: factory = (DefinitionsFactory) loaded.get(curPostfix);
364:
365: if (factory != null) { // yes, stop search
366:
367: return factory;
368: }
369:
370: // Try to load it. If success, stop search
371: lastXmlFile = parseXmlFiles(servletContext, curPostfix,
372: null);
373:
374: if (lastXmlFile != null) {
375: break;
376: }
377: }
378:
379: // Have we found a description file ?
380: // If no, return default one
381: if (lastXmlFile == null) {
382: return getDefaultFactory();
383: }
384:
385: // We found something. Need to load base and intermediate files
386: String lastPostfix = curPostfix;
387: XmlDefinitionsSet rootXmlConfig = parseXmlFiles(servletContext,
388: "", null);
389:
390: for (int j = 0; j < i; j++) {
391: curPostfix = (String) possiblePostfixes.get(j);
392: parseXmlFiles(servletContext, curPostfix, rootXmlConfig);
393: }
394:
395: rootXmlConfig.extend(lastXmlFile);
396: rootXmlConfig.resolveInheritances();
397:
398: factory = new DefinitionsFactory(rootXmlConfig);
399: loaded.put(lastPostfix, factory);
400:
401: if (log.isDebugEnabled()) {
402: log.debug("factory loaded : " + factory);
403: }
404:
405: // return last available found !
406: return factory;
407: }
408:
409: /**
410: * Calculate the postixes along the search path from the base bundle to the
411: * bundle specified by baseName and locale.
412: * Method copied from java.util.ResourceBundle
413: * @param baseName the base bundle name
414: * @param locale the locale
415: */
416: private static List calculatePostixes(String baseName, Locale locale) {
417: final List result = new ArrayList(MAX_BUNDLES_SEARCHED);
418: final String language = locale.getLanguage();
419: final int languageLength = language.length();
420: final String country = locale.getCountry();
421: final int countryLength = country.length();
422: final String variant = locale.getVariant();
423: final int variantLength = variant.length();
424:
425: if ((languageLength + countryLength + variantLength) == 0) {
426: //The locale is "", "", "".
427: return result;
428: }
429:
430: final StringBuffer temp = new StringBuffer(baseName);
431: temp.append('_');
432: temp.append(language);
433:
434: if (languageLength > 0) {
435: result.add(temp.toString());
436: }
437:
438: if ((countryLength + variantLength) == 0) {
439: return result;
440: }
441:
442: temp.append('_');
443: temp.append(country);
444:
445: if (countryLength > 0) {
446: result.add(temp.toString());
447: }
448:
449: if (variantLength == 0) {
450: return result;
451: } else {
452: temp.append('_');
453: temp.append(variant);
454: result.add(temp.toString());
455:
456: return result;
457: }
458: }
459:
460: /**
461: * Parse files associated to postix if they exist.
462: * For each name in filenames, append postfix before file extension,
463: * then try to load the corresponding file.
464: * If file doesn't exist, try next one. Each file description is added to
465: * the XmlDefinitionsSet description.
466: * The XmlDefinitionsSet description is created only if there is a definition file.
467: * Inheritance is not resolved in the returned XmlDefinitionsSet.
468: * If no description file can be opened and no definiion set is provided, return <code>null</code>.
469: * @param postfix Postfix to add to each description file.
470: * @param xmlDefinitions Definitions set to which definitions will be added. If <code>null</code>, a definitions
471: * set is created on request.
472: * @return XmlDefinitionsSet The definitions set created or passed as parameter.
473: * @throws DefinitionsFactoryException On errors parsing file.
474: */
475: private XmlDefinitionsSet parseXmlFiles(
476: ServletContext servletContext, String postfix,
477: XmlDefinitionsSet xmlDefinitions)
478: throws DefinitionsFactoryException {
479: if ((postfix != null) && (postfix.length() == 0)) {
480: postfix = null;
481: }
482:
483: // Iterate throw each file name in list
484: Iterator i = filenames.iterator();
485:
486: while (i.hasNext()) {
487: String filename = concatPostfix((String) i.next(), postfix);
488: xmlDefinitions = parseXmlFile(servletContext, filename,
489: xmlDefinitions);
490: }
491:
492: return xmlDefinitions;
493: }
494:
495: /**
496: * Parse specified xml file and add definition to specified definitions set.
497: * This method is used to load several description files in one instances list.
498: * If filename exists and definition set is <code>null</code>, create a new set. Otherwise, return
499: * passed definition set (can be <code>null</code>).
500: * @param servletContext Current servlet context. Used to open file.
501: * @param filename Name of file to parse.
502: * @param xmlDefinitions Definitions set to which definitions will be added. If null, a definitions
503: * set is created on request.
504: * @return XmlDefinitionsSet The definitions set created or passed as parameter.
505: * @throws DefinitionsFactoryException On errors parsing file.
506: */
507: private XmlDefinitionsSet parseXmlFile(
508: ServletContext servletContext, String filename,
509: XmlDefinitionsSet xmlDefinitions)
510: throws DefinitionsFactoryException {
511: try {
512: /*InputStream input = servletContext.getResourceAsStream(filename);*/
513: InputStream input = null;
514: Resource[] resources = WebApplicationContextUtils
515: .getWebApplicationContext(servletContext)
516: .getResources(filename);
517: final int length = resources.length;
518:
519: for (int i = 0; i < length; i++) {
520: try {
521: input = resources[i].getURL().openStream(); /*getServletContext().getResource(path)*/
522: } catch (IOException e) {
523: //error loading from this resource. Probably it doesn't exist.
524: if (log.isDebugEnabled()) {
525: log.debug("", e);
526: }
527:
528: return xmlDefinitions;
529: }
530:
531: // Try to load using real path.
532: // This allow to load config file under websphere 3.5.x
533: // Patch proposed Houston, Stephen (LIT) on 5 Apr 2002
534: if (null == input) {
535: try {
536: input = new java.io.FileInputStream(
537: servletContext.getRealPath(filename));
538: } catch (Exception e) {
539: }
540: }
541:
542: // If still nothing found, this mean no config file is associated
543: if (input == null) {
544: if (log.isDebugEnabled()) {
545: log.debug("Can't open file '" + filename + "'");
546: }
547:
548: return xmlDefinitions;
549: }
550:
551: // Check if parser already exist.
552: // Doesn't seem to work yet.
553: //if( xmlParser == null )
554: if (true) {
555: xmlParser = new XmlParser();
556: xmlParser.setValidating(isValidatingParser);
557: }
558:
559: // Check if definition set already exist.
560: if (xmlDefinitions == null) {
561: xmlDefinitions = new XmlDefinitionsSet();
562: }
563:
564: xmlParser.parse(input, xmlDefinitions);
565: }
566: } catch (SAXException ex) {
567: if (log.isDebugEnabled()) {
568: log.debug("Error while parsing file '" + filename
569: + "'.");
570: ex.printStackTrace();
571: }
572:
573: throw new DefinitionsFactoryException(
574: "Error while parsing file '" + filename + "'. "
575: + ex.getMessage(), ex);
576: } catch (IOException ex) {
577: /*throw new DefinitionsFactoryException*/
578: if (log.isDebugEnabled()) {
579: log.debug("IO Error while parsing file '" + filename
580: + "'. " + ex.getMessage(), ex);
581: }
582: }
583:
584: return xmlDefinitions;
585: }
586:
587: /**
588: * Concat postfix to the name. Take care of existing filename extension.
589: * Transform the given name "name.ext" to have "name" + "postfix" + "ext".
590: * If there is no ext, return "name" + "postfix".
591: * @param name Filename.
592: * @param postfix Postfix to add.
593: * @return Concatenated filename.
594: */
595: private String concatPostfix(String name, String postfix) {
596: if (postfix == null) {
597: return name;
598: }
599:
600: // Search file name extension.
601: // take care of Unix files starting with .
602: int dotIndex = name.lastIndexOf(".");
603: int lastNameStart = name
604: .lastIndexOf(java.io.File.pathSeparator);
605:
606: if ((dotIndex < 1) || (dotIndex < lastNameStart)) {
607: return name + postfix;
608: }
609:
610: String ext = name.substring(dotIndex);
611: name = name.substring(0, dotIndex);
612:
613: return name + postfix + ext;
614: }
615:
616: /**
617: * Return String representation.
618: * @return String representation.
619: */
620: public String toString() {
621: StringBuffer buff = new StringBuffer("I18nFactorySet : \n");
622: buff.append("--- default factory ---\n");
623: buff.append(defaultFactory.toString());
624: buff.append("\n--- other factories ---\n");
625:
626: Iterator i = factories.values().iterator();
627:
628: while (i.hasNext()) {
629: buff.append(i.next().toString()).append("---------- \n");
630: }
631:
632: return buff.toString();
633: }
634: }
|