View Javadoc

1   package org.sourceforge.mbeanmonitoring.report;
2   
3   /**
4    **      Author:
5    **              Laurent Le Grandois <Laurent.Le.Grandois@gmail.com>
6    **              Gilles Bardouillet  <Gilles.Bardouillet@gmail.com>
7    **
8    **  This program is free software; you can redistribute it and/or modify
9    ** it under the terms of the GNU General Public License as published by
10   **  the Free Software Foundation; either version 2 of the License, or
11   **  (at your option) any later version.
12   **
13   ** This program is distributed in the hope that it will be useful,
14   **  but WITHOUT ANY WARRANTY; without even the implied warranty of
15   **  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   **  GNU General Public License for more details.
17   **
18   **  You should have received a copy of the GNU General Public License
19   ** along with this program; if not, write to the Free Software
20   **
21   */
22  import java.io.File;
23  import java.io.FileReader;
24  import java.io.InputStream;
25  import java.io.InputStreamReader;
26  import java.io.Reader;
27  import java.text.SimpleDateFormat;
28  import java.util.Date;
29  import java.util.Enumeration;
30  import java.util.Properties;
31  
32  import javax.naming.InitialContext;
33  
34  import org.apache.log4j.PropertyConfigurator;
35  import org.jboss.jmx.adaptor.rmi.RMIAdaptor;
36  import org.sourceforge.mbeanmonitoring.report.castor.Mbean;
37  import org.sourceforge.mbeanmonitoring.report.castor.ServerParam;
38  import org.sourceforge.mbeanmonitoring.report.castor.Stat;
39  
40  public class Capture {
41  
42  	ServerParam params;
43  
44  	static String KEY_MBEAN_FILE = "MBean.filename";
45  	static String KEY_MBEAN_NAME = "name";
46  	static String KEY_MBEAN_ATTRS = "attrs";
47  	static String KEY_APPENDER = "appender";
48  
49  	static String CURRENT_DIRECTORY = "current";
50  
51  	static boolean isGraphRuntime = false;
52  
53  	private RMIAdaptor rmiServer;
54  	private Properties[] infos;
55  
56  	private static Properties log4j;
57  
58  	private String getFileName(String mbeanName) {
59  		return mbeanName.replace('.', '_').replace(':', '_').replace('=', '_').replace('/', '_').replace(',', '_');
60  	}
61  
62  	private Properties setLogs() {
63  		// --- LOG4J parametres --------------------------------------------
64  		boolean succes = false;
65  		String folder = this.params.getGenereTo() + System.getProperty("file.separator") + CURRENT_DIRECTORY;
66  
67  		if (!Capture.isGraphRuntime) {
68  			// test if log folder exist
69  			File folderFile = new File(folder);
70  			// test if current folder exist
71  			if (folderFile != null || folderFile.exists()) {
72  				SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss");
73  				Date date = new Date();
74  				String folderArchive = sdf.format(date);// + "." + fichierXML;
75  				succes = folderFile.renameTo(new File(this.params.getGenereTo() + System.getProperty("file.separator")
76  						+ folderArchive));
77  				if (!succes)
78  					System.out.println("CAN NOT RENAME FOLDER " + folderFile.getName());
79  			}
80  			File currentRep = new File(folder);
81  			if (currentRep != null || !currentRep.exists()) {
82  				succes = currentRep.mkdirs();
83  				if (!succes)
84  					System.out.println("CAN NOT CREATE FOLDER " + folderFile.getName());
85  			}
86  		}
87  
88  		Properties properties = new Properties();
89  
90  		for (int i = 0; i < infos.length; i++) {
91  
92  			String mbeanName = this.infos[i].getProperty(KEY_MBEAN_NAME);
93  			String fileName = this.infos[i].getProperty(KEY_MBEAN_FILE, mbeanName);
94  			System.out.println("Fichier = " + fileName);
95  
96  			String appender = "log4j.appender." + this.infos[i].getProperty(KEY_APPENDER);
97  			properties.put("log4j.category." + this.infos[i].getProperty(KEY_APPENDER), "DEBUG, "
98  					+ this.infos[i].getProperty(KEY_APPENDER));
99  			properties.put(appender, "org.apache.log4j.RollingFileAppender");
100 			properties.put(appender + ".File", folder + "/" + fileName + "." + this.params.getExtension());
101 			properties.put(appender + ".layout", "org.apache.log4j.PatternLayout");
102 			properties.put(appender + ".layout.ConversionPattern", "%d{dd/MM/yyyy" + this.params.getSeparateur()
103 					+ "HH:mm:ss}" + this.params.getSeparateur() + "%m%n");
104 			properties.put(appender + ".MaxFileSize", this.params.getMaxFileSize());
105 			properties.put(appender + ".MaxBackupIndex", new Integer(this.params.getMaxBackupIndex()).toString());
106 		}
107 		return properties;
108 	}
109 
110 	//////////////////////////////////////////////////////////////////////////////////////////////////////
111 	// Get the parameters from the XML file ${xmlfile}
112 	//////////////////////////////////////////////////////////////////////////////////////////////////////
113 
114 	private Reader getUserParameters(String fileName) {
115 		if (fileName != null) {
116 			return this.getParametersFromXMLFile(fileName);
117 		}
118 		return null ;
119 	}
120 
121 	private Reader getParametersFromXMLFile(String fileName) {
122 		System.out.println("Filename : " + fileName);
123 		FileReader file = null;
124 		try {
125 			file = new FileReader(fileName);
126 		} catch (Exception e) {
127 			e.printStackTrace();
128 		}
129 		return file;
130 	}
131 
132 	public Capture() {
133 		this(null);
134 	}
135 
136 	public Capture(String fileName) {
137 		// Get the parameters from XML file(s)
138 
139 		try {
140 			// read the user parameters
141 			System.out.println("Try to read the customized parameters from: " + fileName);
142 			ServerParam custoParams = new ServerParam();
143 			custoParams = ServerParam.unmarshal(getUserParameters(fileName));
144 
145 			custoParams.validate();
146 
147 			this.params = custoParams;
148 		} catch (Exception e) {
149 			e.printStackTrace();
150 			this.params = null;
151 		}
152 
153 		// Get the JNDI propreties, get the JNDI Context, then get the RMI Adaptor
154 
155 		try {
156 			/*
157 			 * The Hardcoded way...
158 			 * 
159 			 * Properties jndiProps = new Properties();
160 			 * jndiProps.put(Context.INITIAL_CONTEXT_FACTORY,
161 			 * "org.jnp.interfaces.NamingContextFactory");
162 			 * jndiProps.put(Context.PROVIDER_URL, "jnp://localhost:1099");
163 			 * jndiProps.put(Context.URL_PKG_PREFIXES,
164 			 * "org.jboss.naming:org.jnp.interfaces");
165 			 */
166 
167 			Properties jndiProps = new Properties();
168 			jndiProps.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
169 			jndiProps.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
170 			jndiProps.put("java.naming.provider.url", "jnp://" + this.params.getHost() + ":" + this.params.getPort());
171 
172 			// Get the JNDI Context
173 			InitialContext ic = new InitialContext(jndiProps);
174 
175 			// Get the RMI Adaptor
176 			this.rmiServer = (RMIAdaptor) ic.lookup("jmx/rmi/RMIAdaptor");
177 		}
178 
179 		catch (Exception e) {
180 			e.printStackTrace();
181 			return;
182 		}
183 
184 		//
185 		Mbean[] mbeans = this.params.getMbean();
186 		int nbMBeans = mbeans.length;
187 		Properties[] newInfos = new Properties[nbMBeans];
188 
189 		for (int i = 0; i < nbMBeans; i++) {
190 			newInfos[i] = new Properties();
191 			String mbeanName = mbeans[i].getDomain().toString() + ":" + mbeans[i].getName();
192 			newInfos[i].put(KEY_MBEAN_NAME, mbeanName);
193 			if (mbeans[i].getFilename() == null)
194 				mbeans[i].setFilename(this.getFileName(mbeanName));
195 			newInfos[i].put(KEY_APPENDER, new File(fileName).getName() + "*" + mbeans[i].getFilename());
196 			newInfos[i].put(KEY_MBEAN_FILE, mbeans[i].getFilename());
197 
198 			int nbMBeansAttrs = mbeans[i].getAttribute().length;
199 			String[] attrs = new String[nbMBeansAttrs];
200 			for (int j = 0; j < nbMBeansAttrs; j++) {
201 				attrs[j] = mbeans[i].getAttribute()[j].getName();
202 				Stat[] stats = mbeans[i].getAttribute()[j].getStat();
203 
204 				if (stats == null)
205 					stats = new Stat[0];
206 				newInfos[i].put(attrs[j], stats);
207 			}
208 			newInfos[i].put(KEY_MBEAN_ATTRS, attrs);
209 		}
210 
211 		this.infos = newInfos;
212 
213 		Capture.configureLog4J(this.setLogs());
214 	}
215 
216 	private static void configureLog4J(Properties logs) {
217 		if (Capture.log4j == null)
218 			log4j = new Properties();
219 		Enumeration newKeys = logs.propertyNames();
220 		while (newKeys.hasMoreElements()) {
221 			String key = (String) newKeys.nextElement();
222 			log4j.put(key, logs.get(key));
223 		}
224 		PropertyConfigurator.configure(Capture.log4j);
225 	}
226 
227 	public void startCapture() {
228 		if (this.rmiServer != null && this.params != null && this.params.isValid()) {
229 			TasksScheduler scheduler = new TasksScheduler();
230 
231 			MServer server = new MServer(this.rmiServer, this.infos, this.params.getSeparateur());
232 			for (int i = 0; i < this.params.getNbThreads(); i++) { // nbThreads
233 				// threads in
234 				// the pool
235 				if (i == 0)
236 					server.logColumnNames();
237 				//server.setId(i);
238 				scheduler.addRunnableTasks(server);
239 			}
240 			//System.out.println( "START CAPTURE" );
241 			scheduler.startScheduledTasks(this.params.getDelay()); // One task
242 			// launch
243 			// every
244 			// "waitfor"
245 			// second...
246 		}
247 	}
248 
249 	public static void main(String[] args) {
250 		if (args.length > 0) {
251 			for (int i = 0; i < args.length; i++) {
252 				new Capture(args[i]).startCapture();
253 			}
254 		} else
255 			new Capture().startCapture();
256 	}
257 }