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

📄 conf.java

📁 urlrewritefilter-2.6-src.zip
💻 JAVA
字号:
/**
 * Copyright (c) 2005, Paul Tuckey
 * All rights reserved.
 *
 * Each copy or derived work must preserve the copyright notice and this
 * notice unmodified.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */
package org.tuckey.web.filters.urlrewrite;

import org.tuckey.web.filters.urlrewrite.utils.Log;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXParseException;

import javax.servlet.ServletContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Configuration object for urlrewrite filter.
 *
 * @author Paul Tuckey
 * @version $Revision: 1.21 $ $Date: 2005/12/07 10:27:02 $
 */
public final class Conf {

    private static Log log = Log.getLog(Conf.class);

    private final List errors = new ArrayList();
    private final List rules = new ArrayList(50);
    private List outboundRules = new ArrayList(50);
    private boolean ok = false;
    private Date loadedDate = null;
    private int ruleIdCounter = 0;
    private int outboundRuleIdCounter = 0;
    private String fileName;

    private ServletContext context;

    /**
     * Empty const for testing etc.
     */
    public Conf() {
        loadedDate = new Date();
    }

    /**
     * Normal constructor.
     */
    public Conf(ServletContext context, final InputStream inputStream, String fileName) {
        // make sure context is setup before calling initialise()
        this.context = context;
        this.fileName = fileName;
        loadDom(inputStream);
        initialise();
        loadedDate = new Date();
    }

    /**
     * Constructor when run elements don't need to be initialised correctly, for docuementation etc.
     */
    public Conf(InputStream inputStream, String conffile) {
        this(null, inputStream, conffile);
    }


    /**
     * @param inputStream stream of the conf file to load
     */
    private synchronized void loadDom(final InputStream inputStream) {
        if (inputStream == null) {
            log.error("inputstream is null");
            return;
        }
        DocumentBuilder parser;

        /**
         * the thing that resolves dtd's and other xml entities.
         */
        ConfHandler handler = new ConfHandler();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        log.debug("XML builder factory is: " + factory.getClass().getName());
        factory.setValidating(true);
        factory.setNamespaceAware(true);
        factory.setIgnoringComments(true);
        factory.setIgnoringElementContentWhitespace(true);
        try {
            parser = factory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            log.error("Unable to setup XML parser for reading conf", e);
            return;
        }
        log.debug("XML Parser: " + parser.getClass().getName());

        parser.setErrorHandler(handler);
        parser.setEntityResolver(handler);

        try {
            log.debug("about to parse conf");
            Document doc = parser.parse(inputStream);
            processConfDoc(doc);

        } catch (SAXParseException e) {
            addError("Parse error on line " + e.getLineNumber() + " " + e.getMessage(), e);

        } catch (Exception e) {
            addError("Exception loading conf " + " " + e.getMessage(), e);
        }
    }

    private void processConfDoc(Document doc) {
        Element rootElement = doc.getDocumentElement();
        NodeList rootElementList = rootElement.getChildNodes();
        for (int i = 0; i < rootElementList.getLength(); i++) {
            Node node = rootElementList.item(i);

            if (node.getNodeType() == Node.ELEMENT_NODE &&
                    ((Element) node).getTagName().equals("rule")) {
                Element ruleElement = (Element) node;
                // we have a rule node
                Rule rule = new Rule();

                processRuleBasics(ruleElement, rule);
                procesConditions(ruleElement, rule);
                processRuns(ruleElement, rule);

                Node toNode = ruleElement.getElementsByTagName("to").item(0);
                rule.setTo(getNodeValue(toNode));
                rule.setToType(getAttrValue(toNode, "type"));
                rule.setToLast(getAttrValue(toNode, "last"));
                if ("true".equalsIgnoreCase(getAttrValue(toNode, "encode"))) rule.setEncodeToUrl(true);

                processSetAttributes(ruleElement, rule);

                addRule(rule);

            } else if (node.getNodeType() == Node.ELEMENT_NODE &&
                    ((Element) node).getTagName().equals("outbound-rule")) {

                Element ruleElement = (Element) node;
                // we have a rule node
                OutboundRule rule = new OutboundRule();

                processRuleBasics(ruleElement, rule);
                if ("true".equalsIgnoreCase(getAttrValue(ruleElement, "encodefirst"))) rule.setEncodeFirst(true);

                procesConditions(ruleElement, rule);
                processRuns(ruleElement, rule);

                Node toNode = ruleElement.getElementsByTagName("to").item(0);
                rule.setTo(getNodeValue(toNode));
                rule.setToLast(getAttrValue(toNode, "last"));
                if ("false".equalsIgnoreCase(getAttrValue(toNode, "encode"))) rule.setEncodeToUrl(false);

                processSetAttributes(ruleElement, rule);

                addOutboundRule(rule);
            }
        }
    }

    private static void processRuleBasics(Element ruleElement, RuleBase rule) {
        if ("false".equalsIgnoreCase(getAttrValue(ruleElement, "enabled"))) rule.setEnabled(false);

        Node nameNode = ruleElement.getElementsByTagName("name").item(0);
        rule.setName(getNodeValue(nameNode));

        Node noteNode = ruleElement.getElementsByTagName("note").item(0);
        rule.setNote(getNodeValue(noteNode));

        Node fromNode = ruleElement.getElementsByTagName("from").item(0);
        rule.setFrom(getNodeValue(fromNode));
        if ("true".equalsIgnoreCase(getAttrValue(fromNode, "casesensitive"))) rule.setFromCaseSensitive(true);
    }

    private static void processSetAttributes(Element ruleElement, RuleBase rule) {
        NodeList setNodes = ruleElement.getElementsByTagName("set");
        for (int j = 0; j < setNodes.getLength(); j++) {
            Node setNode = setNodes.item(j);
            if (setNode == null) continue;
            SetAttribute setAttribute = new SetAttribute();
            setAttribute.setValue(getNodeValue(setNode));
            setAttribute.setType(getAttrValue(setNode, "type"));
            setAttribute.setName(getAttrValue(setNode, "name"));
            rule.addSetAttribute(setAttribute);
        }
    }

    private static void processRuns(Element ruleElement, RuleBase rule) {
        NodeList runNodes = ruleElement.getElementsByTagName("run");
        for (int j = 0; j < runNodes.getLength(); j++) {
            Node runNode = runNodes.item(j);

            if (runNode == null) continue;
            Run run = new Run();

            if (runNode.getNodeType() == Node.ELEMENT_NODE) {
                Element runElement = (Element) runNode;
                NodeList initParamsNodeList = runElement.getElementsByTagName("init-param");
                for (int k = 0; k < initParamsNodeList.getLength(); k++) {
                    Node initParamNode = initParamsNodeList.item(k);
                    if (initParamNode == null) continue;
                    if (initParamNode.getNodeType() != Node.ELEMENT_NODE) continue;
                    Element initParamElement = (Element) initParamNode;
                    Node paramNameNode = initParamElement.getElementsByTagName("param-name").item(0);
                    Node paramValueNode = initParamElement.getElementsByTagName("param-value").item(0);
                    run.addInitParam(getNodeValue(paramNameNode), getNodeValue(paramValueNode));
                }
            }
            run.setClassStr(getAttrValue(runNode, "class"));
            run.setMethodStr(getAttrValue(runNode, "method"));
            run.setNewEachTime("true".equalsIgnoreCase(getAttrValue(runNode, "neweachtime")));
            rule.addRun(run);
        }
    }

    private static void procesConditions(Element ruleElement, RuleBase rule) {
        NodeList conditionNodes = ruleElement.getElementsByTagName("condition");
        for (int j = 0; j < conditionNodes.getLength(); j++) {
            Node conditionNode = conditionNodes.item(j);
            if (conditionNode == null) continue;
            Condition condition = new Condition();
            condition.setValue(getNodeValue(conditionNode));
            condition.setType(getAttrValue(conditionNode, "type"));
            condition.setName(getAttrValue(conditionNode, "name"));
            condition.setNext(getAttrValue(conditionNode, "next"));
            condition.setCaseSensitive("true".equalsIgnoreCase(getAttrValue(conditionNode, "casesensitive")));
            condition.setOperator(getAttrValue(conditionNode, "operator"));
            rule.addCondition(condition);
        }
    }

    private static String getNodeValue(Node node) {
        if (node == null) return null;
        NodeList nodeList = node.getChildNodes();
        if (nodeList == null) return null;
        Node child = nodeList.item(0);
        if (child == null) return null;
        if ((child.getNodeType() == Node.TEXT_NODE)) {
            String value = ((Text) child).getData();
            return value.trim();
        }
        return null;
    }

    private static String getAttrValue(Node n, String attrName) {
        if (n == null) return null;
        NamedNodeMap attrs = n.getAttributes();
        if (attrs == null) return null;
        Node attr = attrs.getNamedItem(attrName);
        if (attr == null) return null;
        String val = attr.getNodeValue();
        if (val == null) return null;
        return val.trim();
    }

    /**
     * Initialise the conf file.  This will run initialise on each rule and condition in the conf file.
     */
    public void initialise() {
        if (log.isDebugEnabled()) {
            log.debug("now initialising conf");
        }
        boolean rulesOk = true;
        for (int i = 0; i < rules.size(); i++) {
            final Rule rule = (Rule) rules.get(i);
            if (!rule.initialise(context)) {
                // if we failed to initialise anything set the status to bad
                rulesOk = false;
            }
        }
        for (int i = 0; i < outboundRules.size(); i++) {
            final OutboundRule outboundRule = (OutboundRule) outboundRules.get(i);
            if (!outboundRule.initialise(context)) {
                // if we failed to initialise anything set the status to bad
                rulesOk = false;
            }
        }
        if (rulesOk) {
            ok = true;
        }
    }

    /**
     * Destory the conf gracefully.
     */
    public void destroy() {
        for (int i = 0; i < rules.size(); i++) {
            final Rule rule = (Rule) rules.get(i);
            rule.destroy();
        }
    }

    /**
     * Will add the rule to the rules list.
     *
     * @param rule The Rule to add
     */
    public void addRule(final Rule rule) {
        rule.setId(ruleIdCounter++);
        rules.add(rule);
    }

    /**
     * Will add the rule to the rules list.
     *
     * @param outboundRule The outbound rule to add
     */
    public void addOutboundRule(final OutboundRule outboundRule) {
        outboundRule.setId(outboundRuleIdCounter++);
        outboundRules.add(outboundRule);
    }

    /**
     * Will get the List of errors.
     *
     * @return the List of errors
     */
    public List getErrors() {
        return errors;
    }

    /**
     * Will get the List of rules.
     *
     * @return the List of rules
     */
    public List getRules() {
        return rules;
    }

    /**
     * Will get the List of outbound rules.
     *
     * @return the List of outbound rules
     */
    public List getOutboundRules() {
        return outboundRules;
    }

    /**
     * true if the conf has been loaded ok.
     *
     * @return boolean
     */
    public boolean isOk() {
        return ok;
    }

    private void addError(final String errorMsg, final Exception e) {
        errors.add(errorMsg);
        log.error(errorMsg, e);
    }

    public Date getLoadedDate() {
        return loadedDate;
    }

    public String getFileName() {
        return fileName;
    }

}

⌨️ 快捷键说明

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