documentgenerator.java

来自「opennms得相关源码 请大家看看」· Java 代码 · 共 694 行 · 第 1/2 页

JAVA
694
字号
//// This file is part of the OpenNMS(R) Application.//// OpenNMS(R) is Copyright (C) 2002-2003 The OpenNMS Group, Inc.  All rights reserved.// OpenNMS(R) is a derivative work, containing both original code, included code and modified// code that was published under the GNU General Public License. Copyrights for modified // and included code are below.//// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.//// Copyright (C) 2003 Networked Knowledge Systems, Inc.//// 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.//// For more information contact://      Derek Glidden   <dglidden@opennms.org>//      http://www.nksi.com/////package org.opennms.web.map;import java.io.IOException;import java.net.URI;import java.util.Enumeration;import java.util.Hashtable;import java.util.Iterator;import java.util.Vector;import javax.servlet.ServletContext;import org.apache.batik.dom.svg.SAXSVGDocumentFactory;import org.apache.batik.dom.svg.SVGDOMImplementation;import org.apache.batik.util.XMLResourceDescriptor;import org.opennms.web.category.CategoryModel;import org.opennms.web.category.CategoryUtil;import org.w3c.dom.DOMImplementation;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;/** * The core of the SVG generation. We get a Vector of MapNode objects, do all * our calculations to figure out how to draw the map, where everything goes, * and generate the SVG here. *  * @author <A HREF="mailto:dglidden@opennms.org">Derek Glidden </A> * @author <A HREF="http://www.nksi.com/">NKSi </A> */public class DocumentGenerator {    private int documentWidth;    private int documentHeight;    private Document document;    private String namespace;    private Vector nodes;    private Hashtable iconNames;    private ServletContext ctx;    private String mapType;    private String urlBase;    /**     * constructor     */    public DocumentGenerator() {        this.documentWidth = 0;        this.documentHeight = 0;        this.document = null;        this.namespace = null;        this.mapType = new String();        this.urlBase = new String();        this.nodes = new Vector();        this.iconNames = new Hashtable();        // this maps from the "server type" to the filename for the        // SVG icon. except that loading the icons from disk into        // the SVG we generate isn't working, so at the moment, this        // is dead code.        iconNames.put("infrastructure", "images/infrastructure.svg");        iconNames.put("laptop", "images/laptop.svg");        iconNames.put("opennms", "images/opennms.svg");        iconNames.put("other", "images/other.svg");        iconNames.put("printer", "images/printer.svg");        iconNames.put("server", "images/server.svg");        iconNames.put("telephony", "images/telephony.svg");        iconNames.put("unspecified", "images/unspecified.svg");        iconNames.put("workstation", "images/workstation.svg");        // loadIcons();    }    /**     * log a message. preferably use the ServletContext' log method, but if we     * don't have one, just go out to System.err     */    private void log(String message) {        if (this.ctx == null) {            System.err.println(message);        } else {            this.ctx.log(message);        }    }    /**     * set the Vector of nodes that we need to map     */    public void setNodes(Vector nodes) {        this.nodes = nodes;    }    /**     * set the ServletContext so we can find the path to load icons from the     * filesystem directly and use the log method.     */    public void setServletContext(ServletContext ctx) {        this.ctx = ctx;    }    /**     * set the URL base so we can create absolute references to content embedded     * in our SVG     */    public void setUrlBase(String base) {        this.urlBase = base;    }    /**     * set the type of map we want to draw: "tree" or "boring"     */    public void setMapType(String type) {        this.mapType = type;    }    /**     * load the SVG icon data so we can embed it directly into the SVG we output     * instead of loading each icon as an external entity.     *      * this doesn't work right for some reason. when the SVG is rendered, the     * icons are all messed up or don't show up. For now, forget trying to load     * the icons as "symbol" elements inside of the SVG document and just refer     * to them as external entities...     *      * When I have more time, I will try to fix this.     */    private void loadIcons() {        try {            String parser = XMLResourceDescriptor.getXMLParserClassName();            SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);            DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();            Enumeration e = iconNames.keys();            System.err.println("Loading icons");            while (e.hasMoreElements()) {                String icon = (String) e.nextElement();                String filename = (String) iconNames.get(icon);                String uriStr = "file:///opt/tomcat/webapps/batik/images/" + filename;                URI uri = new URI(uriStr);                // log("loading icon " + icon + " from " + uriStr);                // log("URI is " + uri.toString());                // log("Scheme is " + uri.getScheme());                Document iconDoc = f.createDocument(uri.toString());                Element iconRootElement = iconDoc.getDocumentElement();                // log("Icon loaded");                Element symbol = this.document.createElementNS(this.namespace, "symbol");                symbol.setAttributeNS(null, "id", icon);                // log("Symbol element created");                Node clonedIcon = this.document.importNode(iconRootElement, true);                // log("icon cloned");                symbol.appendChild(clonedIcon);                this.document.getDocumentElement().appendChild(symbol);            }        } catch (IOException e) {            log("IOException in DocumentGenerator.loadIcons()");            log(e.toString());        } catch (Exception e) {            log("Exception in DocumentGenerator.loadIcons()");            log(e.toString());        }    }    /**     * tell me if a given node is child of another node     *      * @param parent     *            the parent node you are testing for the parent-child     *            relationship     * @param child     *            the child node you are testing for the parent-child     *            relationship     */    private boolean isChildNode(MapNode parent, MapNode child) {        return parent.getNodeID() == child.getNodeParent();    }    /**     * find out how many immediate parent hosts for this host. (adapted from     * nagios code)     *      * @param child     *            the child node for which you wish to find the number of     *            parents     */    private int numberOfImmediateParents(MapNode child) {        int parents = 0;        Iterator i = this.nodes.iterator();        while (i.hasNext()) {            MapNode parent = (MapNode) i.next();            if (isChildNode(parent, child)) {                parents++;            }        }        return parents;    }    /**     * figure out the max child width for the map. (adapted from nagios code)     *      * @param parent     *            the parent node for which you wish to find the maximum width     *            of children somewhere down its tree of child nodes     */    private int findMaxChildWidth(MapNode parent) {        int childWidth = 0;        Iterator i = this.nodes.iterator();        while (i.hasNext()) {            MapNode child = (MapNode) i.next();            if (isChildNode(parent, child)) {                childWidth += findMaxChildWidth(child);            }        }        if (childWidth == 0) {            return 1;        } else {            return childWidth;        }    }    /**     * calculate coordinates for all hosts, doing a balanced-tree drawing     * thingie. (heavily adapted from nagios code. in fact, it would be better     * to say this is based on the algorithms nagios uses than to say it's in     * any way based on that code...)     *      * @param parent     *            the parent node for which you will start to calculate the rest     *            of the tree coordinates     */    private void calculateBalancedTreeCoordinates(MapNode parent) {        int parentWidth = findMaxChildWidth(parent);        int startDrawingX = parent.getX() - ((parentWidth - 1) / 2);        int currentDrawingX = startDrawingX;        Iterator i = this.nodes.iterator();        while (i.hasNext()) {            MapNode n = (MapNode) i.next();            if (isChildNode(parent, n)) {                int thisWidth = findMaxChildWidth(n);                n.setX(currentDrawingX + ((thisWidth - 1) / 2));                n.setY(parent.getY() + 1);                currentDrawingX += (thisWidth);                calculateBalancedTreeCoordinates(n);            }        }    }    /**     * start the job of figuring out where on the screen to draw each host by     * starting to calculate the Balanced Tree coordinates from the root node     * (node "0")     */    private void calculateTreeHostCoordinates() {        MapNode rootNode = (MapNode) this.nodes.get(0);        int maxWidth = findMaxChildWidth(rootNode);        rootNode.setX((maxWidth / 2));        rootNode.setY(0);        calculateBalancedTreeCoordinates(rootNode);    }    /**     * do a really stupid and simple "draw hosts left to right, 10 columns by as     * many rows as necessary     */    private void calculateBoringHostCoordinates() {        int row = 0;        int col = 0;        // we start at 1 since the "pseudo-node" for the OpenNMS        // monitor is inserted into the node array at 0 and will never        // have any real status associated with it        for (int i = 1; i < this.nodes.size(); i++) {            MapNode mn = (MapNode) this.nodes.get(i);            mn.setX(col);            mn.setY(row);            if (i % 8 == 0) {                col = 0;                row++;            } else {

⌨️ 快捷键说明

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