KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jrobin > mrtg > server > Server


1 /* ============================================================
2  * JRobin : Pure java implementation of RRDTool's functionality
3  * ============================================================
4  *
5  * Project Info: http://www.jrobin.org
6  * Project Lead: Sasa Markovic (saxon@jrobin.org);
7  *
8  * (C) Copyright 2003, by Sasa Markovic.
9  *
10  * Developers: Sasa Markovic (saxon@jrobin.org)
11  * Arne Vandamme (cobralord@jrobin.org)
12  *
13  * This library is free software; you can redistribute it and/or modify it under the terms
14  * of the GNU Lesser General Public License as published by the Free Software Foundation;
15  * either version 2.1 of the License, or (at your option) any later version.
16  *
17  * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
18  * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
19  * See the GNU Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public License along with this
22  * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
23  * Boston, MA 02111-1307, USA.
24  */

25 package org.jrobin.mrtg.server;
26
27 import org.jrobin.core.RrdDb;
28 import org.jrobin.core.RrdDbPool;
29 import org.jrobin.core.RrdException;
30 import org.jrobin.mrtg.MrtgException;
31 import org.jrobin.mrtg.MrtgConstants;
32 import org.w3c.dom.Document JavaDoc;
33 import org.w3c.dom.Element JavaDoc;
34 import org.w3c.dom.NodeList JavaDoc;
35
36 import javax.xml.parsers.DocumentBuilder JavaDoc;
37 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
38 import javax.xml.transform.OutputKeys JavaDoc;
39 import javax.xml.transform.Transformer JavaDoc;
40 import javax.xml.transform.TransformerFactory JavaDoc;
41 import javax.xml.transform.dom.DOMSource JavaDoc;
42 import javax.xml.transform.stream.StreamResult JavaDoc;
43 import java.io.File JavaDoc;
44 import java.io.FileOutputStream JavaDoc;
45 import java.io.IOException JavaDoc;
46 import java.io.FileWriter JavaDoc;
47 import java.util.Date JavaDoc;
48 import java.util.Hashtable JavaDoc;
49 import java.util.Vector JavaDoc;
50
51 public class Server implements MrtgConstants {
52     private static Server instance;
53
54     private DeviceList deviceList;
55     private Date JavaDoc startDate;
56
57     private Timer timer;
58     private RrdWriter rrdWriter;
59     private Listener listener;
60
61     private boolean active = false;
62
63     public synchronized static Server getInstance() {
64         if (instance == null) {
65             instance = new Server();
66         }
67         return instance;
68     }
69
70     private Server() {
71         RrdDb.setLockMode(RrdDb.NO_LOCKS);
72         RrdDbPool.getInstance().setCapacity(POOL_CAPACITY);
73     }
74
75     public synchronized void start(String JavaDoc[] acceptedClients) throws MrtgException {
76         if(active) {
77             throw new MrtgException("Cannot start Server, already started");
78         }
79         // set default backend factory
80
try {
81             RrdDb.setDefaultFactory(BACKEND_FACTORY_NAME);
82         } catch (RrdException e) {
83             throw new MrtgException("Inavlide backend factory (" + BACKEND_FACTORY_NAME + ")");
84         }
85         // create template files
86
try {
87             createXmlTemplateIfNecessary(Config.getRrdTemplateFile(), RRD_TEMPLATE_STR);
88             createXmlTemplateIfNecessary(Config.getGraphTemplateFile(), GRAPH_TEMPLATE_STR);
89         }
90         catch(IOException JavaDoc ioe) {
91             throw new MrtgException(ioe);
92         }
93         // load configuration
94
String JavaDoc hwFile = Config.getHardwareFile();
95         if(new File JavaDoc(hwFile).exists()) {
96             loadHardware();
97         }
98         else {
99             saveHardware();
100         }
101         // create threads
102
rrdWriter = new RrdWriter();
103         timer = new Timer();
104         listener = new Listener(acceptedClients);
105         startDate = new Date JavaDoc();
106         active = true;
107     }
108
109     private void createXmlTemplateIfNecessary(String JavaDoc filePath, String JavaDoc fileContent)
110         throws IOException JavaDoc {
111         File JavaDoc file = new File JavaDoc(filePath);
112         if(!file.exists()) {
113             FileWriter JavaDoc writer = new FileWriter JavaDoc(filePath, false);
114             writer.write(fileContent);
115             writer.flush();
116             writer.close();
117         }
118     }
119
120     public synchronized void stop() throws MrtgException {
121         if(!active) {
122             throw new MrtgException("Cannot stop Server, not started");
123         }
124         rrdWriter.terminate();
125         timer.terminate();
126         listener.terminate();
127         active = false;
128         try {
129             RrdDbPool.getInstance().reset();
130         } catch (IOException JavaDoc e) {
131             throw new MrtgException(e);
132         }
133     }
134
135     void saveHardware() throws MrtgException {
136         if(deviceList == null) {
137             deviceList = new DeviceList();
138         }
139         try {
140             DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
141             factory.setValidating(false);
142             factory.setNamespaceAware(false);
143             DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
144             Document JavaDoc doc = builder.newDocument();
145             Element JavaDoc root = doc.createElement("mrtg");
146             doc.appendChild(root);
147             Vector JavaDoc routers = deviceList.getRouters();
148             for(int i = 0; i < routers.size(); i++) {
149                 Device router = (Device) routers.get(i);
150                 router.appendXml(root);
151             }
152             TransformerFactory JavaDoc tFactory = TransformerFactory.newInstance();
153             Transformer JavaDoc transformer = tFactory.newTransformer();
154             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
155             transformer.setOutputProperty(OutputKeys.METHOD, "xml");
156             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
157             transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml");
158             transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
159             DOMSource JavaDoc source = new DOMSource JavaDoc(root);
160             FileOutputStream JavaDoc destination = new FileOutputStream JavaDoc(Config.getHardwareFile());
161             StreamResult JavaDoc result = new StreamResult JavaDoc(destination);
162             transformer.transform(source, result);
163             destination.close();
164         } catch (Exception JavaDoc e) {
165             throw new MrtgException(e);
166         }
167     }
168
169     private void loadHardware() throws MrtgException {
170         try {
171             DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
172             factory.setValidating(false);
173             factory.setNamespaceAware(false);
174             DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
175             Document JavaDoc doc = builder.parse(new File JavaDoc(Config.getHardwareFile()));
176             Element JavaDoc root = doc.getDocumentElement();
177             NodeList JavaDoc nodes = root.getElementsByTagName("router");
178             deviceList = new DeviceList();
179             Vector JavaDoc routers = deviceList.getRouters();
180             for(int i = 0; i < nodes.getLength(); i++) {
181                 routers.add(new Device(nodes.item(i)));
182             }
183         } catch (Exception JavaDoc e) {
184             throw new MrtgException(e);
185         }
186     }
187
188     public String JavaDoc toString() {
189         return deviceList.toString();
190     }
191
192     synchronized int addRouter(String JavaDoc host, String JavaDoc community, String JavaDoc descr, boolean active)
193         throws MrtgException {
194         int retCode = deviceList.addRouter(host, community, descr, active);
195         if(retCode == 0) {
196             saveHardware();
197         }
198         return retCode;
199     }
200
201     synchronized int updateRouter(String JavaDoc host, String JavaDoc community, String JavaDoc descr, boolean active)
202         throws MrtgException {
203         int retCode = deviceList.updateRouter(host, community, descr, active);
204         if(retCode == 0) {
205             saveHardware();
206         }
207         return retCode;
208     }
209
210     synchronized int removeRouter(String JavaDoc host) throws MrtgException {
211         int retCode = deviceList.removeRouter(host);
212         if(retCode == 0) {
213             saveHardware();
214         }
215         return retCode;
216     }
217
218     synchronized int addLink(String JavaDoc host, String JavaDoc ifDescr, String JavaDoc descr, int samplingInterval,
219                              boolean active)
220         throws MrtgException {
221         int retCode = deviceList.addLink(host, ifDescr, descr, samplingInterval, active);
222         if(retCode == 0) {
223             saveHardware();
224         }
225         return retCode;
226     }
227
228     synchronized int updateLink(String JavaDoc host, String JavaDoc ifDescr, String JavaDoc descr,
229                                 int samplingInterval, boolean active)
230         throws MrtgException {
231         int retCode = deviceList.updateLink(host, ifDescr, descr, samplingInterval, active);
232         if(retCode == 0) {
233             saveHardware();
234         }
235         return retCode;
236     }
237
238     synchronized int removeLink(String JavaDoc host, String JavaDoc ifDescr) throws MrtgException {
239         int retCode = deviceList.removeLink(host, ifDescr);
240         if(retCode == 0) {
241             saveHardware();
242             if(REMOVE_RRD_FOR_DEACTIVATED_LINK) {
243                 // remove the underlying RRD file
244
String JavaDoc rrdFile = RrdWriter.getRrdFilename(host, ifDescr);
245                 new File JavaDoc(rrdFile).delete();
246             }
247         }
248         return retCode;
249     }
250
251     synchronized byte[] getPngGraph(String JavaDoc host, String JavaDoc ifDescr, long start, long stop)
252         throws MrtgException {
253         Plotter grapher = new Plotter(host, ifDescr);
254         return grapher.getPngGraphBytes(start, stop);
255     }
256
257     synchronized Device[] getRouters() {
258         return (Device[]) deviceList.getRouters().toArray(new Device[0]);
259     }
260
261     String JavaDoc[] getAvailableLinks(String JavaDoc host) throws MrtgException {
262         Device router = deviceList.getRouterByHost(host);
263         try {
264             if(router != null) {
265                 return router.getAvailableLinks();
266             }
267             else {
268                 return null;
269             }
270         } catch (IOException JavaDoc e) {
271             throw new MrtgException(e);
272         }
273     }
274
275     DeviceList getDeviceList() {
276         return deviceList;
277     }
278
279     RrdWriter getRrdWriter() {
280         return rrdWriter;
281     }
282
283     Date JavaDoc getStartDate() {
284         return startDate;
285     }
286
287     Hashtable JavaDoc getServerInfo() {
288         Hashtable JavaDoc hash = new Hashtable JavaDoc();
289         hash.put("sampleCount", new Integer JavaDoc(rrdWriter.getSampleCount()));
290         hash.put("savesCount", new Integer JavaDoc(rrdWriter.getSavesCount()));
291         hash.put("goodSavesCount", new Integer JavaDoc(rrdWriter.getGoodSavesCount()));
292         hash.put("badSavesCount", new Integer JavaDoc(rrdWriter.getBadSavesCount()));
293         hash.put("startDate", startDate);
294         hash.put("poolEfficency", new Double JavaDoc(RrdDbPool.getInstance().getPoolEfficency()));
295         return hash;
296     }
297
298     public static void main(String JavaDoc[] acceptedClients) throws Exception JavaDoc {
299         Server s = Server.getInstance();
300         s.start(acceptedClients);
301     }
302
303 }
304
305
Popular Tags