⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 butorconfig.java

📁 一个实用工具类
💻 JAVA
字号:
/* * Copyright (C) butor.com. All rights reserved. * * This software is published under the terms of the GNU Library General * Public License (GNU LGPL), a copy of which has been included with this * distribution in the LICENSE.txt file.  */package org.butor.config.lowlevel;import java.io.File;import java.io.IOException;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import org.butor.config.IConfig;import org.butor.helper.Message;import org.butor.log.Log;import org.xml.sax.SAXException;import org.xml.sax.XMLReader;import org.xml.sax.helpers.XMLReaderFactory;/** * @version 	1.0 * @author */public class ButorConfig extends PropertyContainer	implements IConfigLoader, IConfig {	/**	 * config property key to retreive the application name of the config.	 */	public static final String PROPERTY_APP_NAME = "app_name";	protected List f_errors = new ArrayList();	protected String f_confFilenameAndPath = null;	protected String f_filename = null;	protected String[] f_suffixes = null;	/**	 * Constructor for Config.	 */	public ButorConfig(ButorConfig parent) {		super();				f_confDir = parent.getConfDir();		f_appDir  = parent.getAppDir();		f_logDir  = parent.getLogDir();		f_repositoryConfDir = parent.getRepositoryConfDir();	}	/**	 * Constructor for Config.	 */	public ButorConfig(String confFilenameAndPath) throws IOException {		this(confFilenameAndPath, null, null, null,null);	}	/**	 * Constructor for Config.	 */	public ButorConfig(		String confFilenameAndPath,		String appDir,		String repositoryConfDir,		String logDir,		String[] suffixes)		throws IOException {					super();				f_confFilenameAndPath = confFilenameAndPath;		f_appDir = appDir;		f_logDir = logDir;				if (repositoryConfDir != null) {			f_repositoryConfDir = repositoryConfDir +				(repositoryConfDir.endsWith(File.separator) ? "" : File.separator);		}				f_suffixes = suffixes;		if (f_confFilenameAndPath == null) {			Log.logStr(this, Log.LOG_TYPE_WARN, "ButorConfig", 				"Got NULL config file name and path!");			return;		}				// We must extract the config dir		File file = new File(confFilenameAndPath);				f_confDir =	file.getParent();		f_filename = file.getName();		loadOneConfigFile(this, f_filename, true);				mergeExternalConfigs();				if (Log.shouldLog(this.getClass().getName(), Log.LOG_LEVEL_LOW)) {						Log.logStr(this, Log.LOG_TYPE_INFO, "ButorConfig", 				"loaded the following config:" +this.toString());		}	}	/**	 * 	 */	public String getConfigFilename() {		return f_confFilenameAndPath;	}	/**	 * Add a property list	 * 	 * @param list PropertyList, property list	 */	public void addPropertyList(PropertyList list) {		if (list == null) {			Log.logStr(				this,				Log.LOG_TYPE_WARN,				"addPropertyList()",				"Got NULL list!");			return;		}		list.setAppDir(f_appDir);		list.setConfDir(f_confDir);		list.setRepositoryConfDir(f_repositoryConfDir);		list.setLogDir(f_logDir);		addProperty(list.getName(), list);	}	/**	 * remove a property list element.	 *	 * @param name String, Property list name	 */	protected void removePropertyList(String name) {		Object value = getProperty(name);		if (value instanceof IProperties) {			removeProperty(value);		}	}	/**	* toString this object content.	* 	* @return String.	*/	public String toString() {		StringBuffer buffer =			new StringBuffer("\n==================== BEGIN OF CONFIG ======================\n");		buffer.append(super.toString());		buffer.append("\n\n");		buffer.append(getProperties().toString());		buffer.append(			"\n==================== END OF CONFIG ======================\n");		return buffer.toString();	}	/**	 * Append Config to this one.	 * Existing properties will be overriden.	 * 	 * @param config IConfig.	 */	protected synchronized void merge(IConfigLoader configToAppend) {		synchronized (configToAppend) {			if (configToAppend == null) {				return;			}			// errors			if (configToAppend.isErrorsOccured()) {				List errors = configToAppend.getOccuredErrors();				f_errors.addAll(errors);			}			// Append properties			Iterator it = configToAppend.getProperties().iterator();			Property newP;			while (it.hasNext()) {				newP = (Property) it.next();				Object oldVal =					this.getProperty((String) newP.getKey());				if (oldVal != null) {					Log.logStr(						this,						Log.LOG_TYPE_INFO,						"merge()",						"Overriding property, key=["							+ newP.getKey()							+ "], oldValue=["							+ oldVal							+ "], newValue=["							+ newP.getValue()							+ "]");					if (oldVal instanceof PropertyList) {						((PropertyList)newP.getValue()).setConfDir(((PropertyList)oldVal).getConfDir());						((PropertyList)newP.getValue()).setAppDir(((PropertyList)oldVal).getAppDir());						((PropertyList)newP.getValue()).setLogDir(((PropertyList)oldVal).getLogDir());						((PropertyList)newP.getValue()).setRepositoryConfDir(((PropertyList)oldVal).getRepositoryConfDir());					}					this.removeProperty(newP.getKey());				}				addProperty(newP.getKey(), newP.getValue());			}		}	}	/**	 * Find and return the filename and its path	 * 1) Check if the file exists in the external config directory.	 * 2) Check if the file exists in the application config directory.	 */	protected String findFile(String filename) {		String filenameAndPath = null;		File file = null;				if (f_repositoryConfDir != null) {			filenameAndPath = f_repositoryConfDir +filename;			Log.logStr(Log.LOG_LEVEL_LOW, this, Log.LOG_TYPE_INFO, "findFile()", 				"Looking for file [" +filenameAndPath +"] ...");			file = new File(filenameAndPath);			if (file.exists() && file.isFile()) {				return filenameAndPath;			}		}				if (f_confDir != null) {			filenameAndPath = f_confDir +File.separator +filename;			Log.logStr(Log.LOG_LEVEL_LOW, this, Log.LOG_TYPE_INFO, "findFile()", 				"Looking for file [" +filenameAndPath +"] ...");			file = new File(filenameAndPath);			if (file.exists() && file.isFile()) {				return filenameAndPath;			}		}				return null;	}	/**	 * Load configuration file. get the file from	 * the external config directory if exists. If not try	 * the application config directory.	 */	protected void loadOneConfigFile(		IConfigLoader config,		String filename,		boolean validateXml)		throws IOException {		String filenameAndPath = findFile(filename);		if (filenameAndPath == null) {			Log.logStr(				Log.LOG_LEVEL_LOW,				this,				Log.LOG_TYPE_INFO,				"loadOneConfigFile()",				"Config file not found [" + filename + "]");			return;		}				Log.logStr(			this,			Log.LOG_TYPE_INFO,			"loadOneConfigFile()",			"Found and Loading config file [" + filenameAndPath + "]");		try {			SaxErrorHandler errorHandler = new SaxErrorHandler();			XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");			parser.setErrorHandler(errorHandler);			ConfigParseHandler handler = new ConfigParseHandler(config);			parser.setContentHandler(handler);			parser.setEntityResolver(new ButorConfigEntityResolver());			parser.parse(filenameAndPath);			config.setOccuredErrors(errorHandler.getErrorList());					} catch (SAXException e) {			Log.logException(this, Log.LOG_TYPE_ERROR, "loadOneConfigFile()", e);			throw new IOException(e.getMessage());		}	}	/**	 * 	 */	protected void mergeExternalConfigs() {		if (f_suffixes == null) {			return;		}		/*		 * Configs to override default properties.		 * prepare environment path and files name & prefixes.		 */		IConfigLoader config = null;		String envFile = null;		/*		 * for each suffixe in the list, if a file have the config file name		 * and end with the prefix then load it to override/add special properties.		 * order of the list is important.		 */		for (int i = 0; i < f_suffixes.length; i++) {			if (f_suffixes[i] == null) {				continue;			}			envFile = f_filename + "." + f_suffixes[i];			Log.logStr(				this,				Log.LOG_TYPE_INFO,				"mergeSpecificConfigs()",				"Merging config file [" + envFile + "]");			config = new ButorConfig(this);			boolean retryWithoutXmlValidation = false;				try {				loadOneConfigFile(config, envFile, true);								if (config != null) {					merge(config);				}			} catch (IOException e) {				Log.logStr(					this,					Log.LOG_TYPE_ERROR,					"mergeSpecificConfigs()",					e.getMessage()						+ " Will try to load without validating XML ...");				Message error = new Message();				error.setSeverity(Message.SEVERITY_ERROR);				error.setText(e.getMessage());				f_errors.add(error);				retryWithoutXmlValidation = true;			}			if (retryWithoutXmlValidation) {				try {					loadOneConfigFile(config, envFile, false);					merge(config);				} catch (IOException e) {					Log.logException(						this,						Log.LOG_TYPE_ERROR,						"mergeSpecificConfigs()",						e);				}			}		}	}	/**	 * 	 */	public boolean isErrorsOccured() {		return (f_errors != null && f_errors.size() > 0);	}	/**	 * 	 */	public List getOccuredErrors() {		return f_errors;	}	/**	 * 	 */	public void setOccuredErrors(List errors) {		f_errors = errors;	}	/**	 * @see org.butor.wak.config.lowlevel.IProperties#getName()	 */	public String getName() {		// Name at this level has no meaning.		return null;	}	/**	 * Get the application name	 */	public String getAppName() {		return System.getProperty(PROPERTY_APP_NAME, getProperty(PROPERTY_APP_NAME, null));	}}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -