001: package org.drools.brms.server.selector;
002:
003: import java.io.IOException;
004: import java.util.HashMap;
005: import java.util.Iterator;
006: import java.util.Map;
007: import java.util.Properties;
008:
009: import org.apache.log4j.Logger;
010: import org.drools.repository.AssetItem;
011:
012: public class SelectorManager {
013:
014: private static final Logger log = Logger
015: .getLogger(SelectorManager.class);
016: public static String SELECTOR_CONFIG_PROPERTIES = "/selectors.properties";
017: private static final SelectorManager INSTANCE = new SelectorManager(
018: SELECTOR_CONFIG_PROPERTIES);
019:
020: /**
021: * This is a map of the selectors to use.
022: */
023: public final Map<String, AssetSelector> selectors = new HashMap<String, AssetSelector>();
024:
025: SelectorManager(String configPath) {
026: log.debug("Loading selectors");
027: Properties props = new Properties();
028: try {
029: props.load(this .getClass().getResourceAsStream(configPath));
030: for (Iterator iter = props.keySet().iterator(); iter
031: .hasNext();) {
032: String selectorName = (String) iter.next();
033: String val = props.getProperty(selectorName);
034: if (val.endsWith("drl")) {
035: selectors.put(selectorName, loadRuleSelector(val));
036: } else {
037: selectors.put(selectorName,
038: loadSelectorImplementation(val));
039: }
040: }
041: } catch (IOException e) {
042: log.error("Unable to load selectors.", e);
043: }
044: }
045:
046: /**
047: * Return a selector. If the name is null or empty it will return a nil/default selector
048: * (one that lets everything through). If the selector iis not found, it will return null;
049: */
050: public AssetSelector getSelector(String name) {
051: if (name == null || "".equals(name.trim())) {
052: return nilSelector();
053: } else {
054: if (this .selectors.containsKey(name)) {
055:
056: return this .selectors.get(name);
057: } else {
058: log.debug("No selector found by the name of " + name);
059: return null;
060: }
061: }
062: }
063:
064: private AssetSelector nilSelector() {
065: return new AssetSelector() {
066: public boolean isAssetAllowed(AssetItem asset) {
067: return true;
068: }
069: };
070: }
071:
072: private AssetSelector loadSelectorImplementation(String val)
073: throws IOException {
074:
075: try {
076: return (AssetSelector) Thread.currentThread()
077: .getContextClassLoader().loadClass(val)
078: .newInstance();
079:
080: } catch (InstantiationException e) {
081: log.error(e);
082: return null;
083: } catch (IllegalAccessException e) {
084: log.error(e);
085: return null;
086: } catch (ClassNotFoundException e) {
087: log.error(e);
088: return null;
089: }
090:
091: }
092:
093: private AssetSelector loadRuleSelector(String val) {
094:
095: return new RuleBasedSelector(val);
096: }
097:
098: public static SelectorManager getInstance() {
099: return INSTANCE;
100: }
101:
102: }
|