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

📄 zkbmanager.java

📁 Mandarax是一个规则引擎的纯Java实现。它支持多类型的事实和基于反映的规则
💻 JAVA
字号:
package org.mandarax.zkb;

/*
 * Copyright (C) 1999-2004 <A href="http://www-ist.massey.ac.nz/JBDietrich" target="_top">Jens Dietrich</a>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

import java.io.*;
import java.net.URL;
import java.util.Properties;
import org.apache.log4j.Category;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.mandarax.kernel.KnowledgeBase;
import org.mandarax.util.logging.LogCategories;
import org.mandarax.zkb.framework.ZKBDriver_2_0;

/**
 * Persistency manager supporting the serialization of knowledge bases. The
 * functionality is similar to the XBKManager. However, there are the following
 * differences:
 * <ol>
 * <li>The ZKB Manager serializes the knowledge base as XML, similiar to XKB.
 * It uses modified XKB drivers to achieve this.
 * <li>Objects (in particular objects used in constant terms) are not XML
 * serialized with the knowledge base. Instead, they are referenced by (string)
 * uris.
 * <li>Objects are serialized using a separate
 * <em>ObjectPersistncyService (OPS)</em>. The idea is to re-use existing
 * services such as binary and (JDK-) XML serialization.
 * <li>The two streams (knowledge base and objects (resources)) are zipped
 * together,
 * </ol>
 * <br>
 * Public methods are synchronized in order to ensure the consistency of the OPS
 * used (added in 3.2).
 * 
 * @author <A href="http://www-ist.massey.ac.nz/JBDietrich" target="_top">Jens Dietrich </A>
 * @version 3.4 <7 March 05>
 * @since 2.2
 */
public class ZKBManager implements LogCategories {

	// logging
	public static final Category LOG_ZKB = Category.getInstance("LOG_MANDARAX_ZKB");

	// meta property keys
	public static final String ZKB_DRIVER_CLASS = "zkb-driver-class";
	public static final String OPS = "ops-class";
	public static final String ATTACHMENT = "attachment-uri";
	private ObjectPersistencyService ops = new XMLSerializationOPS();
	private ZKBDriver driver = new ZKBDriver_2_0();
	private boolean usingSAX = false;
	private SAXBuilder saxBuilder = null;
	private boolean validate = false;
	private static IOManager DIR_IO = new DirectoryIOManager();
	private static IOManager ZIP_IO = new ZIPIOManager();

	/**
	 * Set the SAX builder. E.g., here we can set a special XML parser. Note
	 * that validation of the builder and validation set here could become
	 * inconsistent!
	 * @param builder a SAX builder
	 */
	public synchronized void setSAXBuilder(SAXBuilder builder) {
		saxBuilder = builder;
	}

	/**
	 * Constructor.
	 */
	public ZKBManager() {
		super();
	}

	/**
	 * Exports a knowledge base to an output stream.
	 * @param target the output (a file or output stream)
	 * @param kb a knowledge base
	 * @throws a ZKBException is thrown if export fails
	 */
	public synchronized void exportKnowledgeBase(Object target,KnowledgeBase kb) throws ZKBException {
		exportKnowledgeBase(target,kb,null);
	}

	/**
	 * Exports a knowledge base to an output stream.
	 * @param target the output (a file or output stream)
	 * @param kb a knowledge base
	 * @param attachment an attachment
	 * @throws a ZKBException is thrown if export fails
	 */
	public synchronized void exportKnowledgeBase(Object target,KnowledgeBase kb, Object attachment) throws ZKBException {

		IOManager ioMgr = this.getIOManager(target); 
		LOG_ZKB.debug("Using the following IO Manager to export kb: " + ioMgr);
		
		// write all data first into a memory buffer and decide later whether to
		// zip them
		// or store them as different files in a folder
		byte[] metaData, kbData, resourceData;
		ByteArrayOutputStream out = new ByteArrayOutputStream();

		// 1. prepare kb
		Document doc = driver.exportKnowledgeBase(kb, ops);

		try {

			// 2. build manifest
			Properties metadata = new Properties();
			metadata.setProperty(OPS, this.ops.getClass().getName());
			metadata.setProperty(ZKB_DRIVER_CLASS, driver.getClass().getName());

			// 3. export attachment
			if (attachment != null) {
				String attachmentUri = ops.findOrBind(attachment);
				metadata.setProperty(ATTACHMENT, attachmentUri);
			}
			metadata.store(out, "mandarax zkb meta data");
			out.close();
			metaData = out.toByteArray();

			// 4. export resources
			out = new ByteArrayOutputStream();
			ops.exportObjects(out);
			out.close();
			resourceData = out.toByteArray();

			// 5. export kb
			out = new ByteArrayOutputStream();
			XMLOutputter xmlOut = new XMLOutputter("  ", true);
			xmlOut.output(doc, out);
			out.close();
			kbData = out.toByteArray();

			// 6. write data
			ioMgr.write(target, metaData, kbData, resourceData, ops);
		} catch (Exception x) {
			throw new ZKBException(x.getMessage(), x);
		} finally {
			ops.reset();
		}
	}


	/**
	 * Import a knowledge base.
	 * @return a knowledge base
	 * @param source an input stream, file or url
	 * @throws a ZKBException is thrown if import fails
	 */
	public synchronized KnowledgeBase importKnowledgeBase(Object source) throws ZKBException {
		return importKnowledgeBaseAndAttachment(source).getKB();
	}

	/**
	 * Import a knowledge base.
	 * @return a knowledge base plus an attachment
	 * @param source an input stream, file or url
	 * @throws a ZKBException is thrown if import fails
	 */
	public synchronized KnowledgeBasePlusAttachment importKnowledgeBaseAndAttachment(Object source) throws ZKBException {
		IOManager ioMgr = this.getIOManager(source);
		LOG_ZKB.debug("Using the following IO Manager to import kb: " + ioMgr);
		
		IOManager.Data data = null;

		try {
			data = ioMgr.read(source);
		} catch (Exception x) {
			error("Cannot read zkb", x);
		}

		// build xkb driver
		ZKBDriver importZKB = null;
		String zkbDriverClassName = data.metaData.getProperty(ZKB_DRIVER_CLASS);
		try {
			LOG_ZKB.debug("Using ZKB driver : " + zkbDriverClassName);
			importZKB = (ZKBDriver) Class.forName(zkbDriverClassName)
					.newInstance();
		} catch (ClassNotFoundException x) {
			error("Cannot find class " + zkbDriverClassName, x);
		} catch (InstantiationException x) {
			error("Cannot instanciate " + zkbDriverClassName, x);
		} catch (IllegalAccessException x) {
			error("Cannot access class " + zkbDriverClassName, x);
		}

		// read objects
		try {
			data.ops.importObjects(new ByteArrayInputStream(data.resourceData));
		} catch (IOException x) {
			LOG_ZKB.error("Cannot read resources from zkb", x);
			throw new ZKBException(x.getMessage(), x);
		}

		// read kb
		KnowledgeBase kb = null;
		try {
			kb = importZKB.importKnowledgeBase(
					getDocument(new ByteArrayInputStream(data.kbData)),
					data.ops);

			// attachment
			Object attachment = null;
			String attachmentUri = data.metaData.getProperty(ATTACHMENT);
			if (attachmentUri != null)
				attachment = data.ops.lookup(attachmentUri);

			return new KnowledgeBasePlusAttachment(kb, attachment);
		} catch (Exception x) {
			error("Cannot read knowledge from zkb ", x);
		}
		return null;

	}


	/**
	 * Returns the object persistency service.
	 * 
	 * @return the object persistency service
	 */
	public synchronized ObjectPersistencyService getOps() {
		return ops;
	}

	/**
	 * Sets the object persistency service.
	 * 
	 * @param ops
	 *            The ops to set
	 */
	public synchronized void setOps(ObjectPersistencyService ops) {
		this.ops = ops;
	}

	/**
	 * Returns the driver.
	 * 
	 * @return ZKBDriver
	 */
	public synchronized ZKBDriver getDriver() {
		return driver;
	}

	/**
	 * Sets the driver.
	 * 
	 * @param driver
	 *            The driver to set
	 */
	public synchronized void setDriver(ZKBDriver driver) {
		this.driver = driver;
	}

	/**
	 * Get the document from the data sorce.
	 * 
	 * @return a document
	 * @param InputStream
	 *            the data source
	 */
	private Document getDocument(InputStream data) throws ZKBException {
		if (data == null) {
			throw new ZKBException("Cannot build document from null");
		}
		try {
			return getSAXBuilder().build(data);
		} catch (JDOMException x) {
			throw new ZKBException(x.getMessage(), x);
		} catch (IOException x) {
			throw new ZKBException(x.getMessage(), x);
		}
	}

	/**
	 * Get the SAX builder.
	 * 
	 * @return the SAX builder
	 */
	private SAXBuilder getSAXBuilder() {
		if (saxBuilder == null) {
			saxBuilder = new SAXBuilder(validate);
		}

		return saxBuilder;
	}

	/**
	 * Log and (re-)throw an exception.
	 * 
	 * @param msg
	 *            the exception message
	 * @param x
	 *            the cause
	 */
	private void error(String msg, Exception x) throws ZKBException {
		LOG_ZKB.error(msg);
		throw new ZKBException(msg, x);
	}

	/**
	 * Log and (re-)throw an exception.
	 * 
	 * @param msg
	 *            the exception message
	 */
	private void error(String msg) throws ZKBException {
		error(msg, null);
	}

	/**
	 * Get the IO Manager used to access a target or source.
	 * @param object the target or source
	 * @return the IOManager used
	 */
	private IOManager getIOManager(Object object) {
		if (object instanceof File) {
			File f = (File)object;
			if (f.isDirectory()) return DIR_IO;
			else return ZIP_IO;
		}
		else if (object instanceof InputStream) return ZIP_IO;
		else if (object instanceof URL) return ZIP_IO;
		return null;
	}

}

⌨️ 快捷键说明

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