KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > test > jmx > xmbean > XMLFilePersistenceManager


1 /*
2   * JBoss, Home of Professional Open Source
3   * Copyright 2005, JBoss Inc., and individual contributors as indicated
4   * by the @authors tag. See the copyright.txt in the distribution for a
5   * full listing of individual contributors.
6   *
7   * This is free software; you can redistribute it and/or modify it
8   * under the terms of the GNU Lesser General Public License as
9   * published by the Free Software Foundation; either version 2.1 of
10   * the License, or (at your option) any later version.
11   *
12   * This software is distributed in the hope that it will be useful,
13   * but WITHOUT ANY WARRANTY; without even the implied warranty of
14   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   * Lesser General Public License for more details.
16   *
17   * You should have received a copy of the GNU Lesser General Public
18   * License along with this software; if not, write to the Free
19   * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20   * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21   */

22 package org.jboss.test.jmx.xmbean;
23
24 import java.beans.PropertyEditor JavaDoc;
25 import java.io.BufferedReader JavaDoc;
26 import java.io.File JavaDoc;
27 import java.io.FileInputStream JavaDoc;
28 import java.io.FileOutputStream JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.InputStreamReader JavaDoc;
31 import javax.management.Attribute JavaDoc;
32 import javax.management.AttributeList JavaDoc;
33 import javax.management.Descriptor JavaDoc;
34 import javax.management.MBeanAttributeInfo JavaDoc;
35 import javax.management.MBeanException JavaDoc;
36 import javax.management.MBeanInfo JavaDoc;
37 import javax.management.modelmbean.ModelMBeanAttributeInfo JavaDoc;
38 import javax.management.modelmbean.ModelMBeanInfo JavaDoc;
39
40 import org.jboss.mx.metadata.MBeanInfoConversion;
41 import org.jboss.mx.modelmbean.ModelMBeanConstants;
42 import org.jboss.mx.modelmbean.ModelMBeanInvoker;
43 import org.jboss.mx.persistence.PersistenceManager;
44
45 import org.jboss.logging.Logger;
46 import org.jboss.util.StringPropertyReplacer;
47 import org.jboss.util.propertyeditor.PropertyEditors;
48
49 /**
50  * XML File Persistence Manager. <p>
51  *
52  * Persists the MBean to the file system using an XML file.
53  *
54  * The file has to follow this (simple) DTD:
55  * <pre>
56  * <!ELEMENT attribute (#PCDATA)>
57  * <!ATTLIST attribute
58  * name CDATA #REQUIRED
59  * type CDATA #REQUIRED
60  * >
61  * <!ELEMENT attributes (attribute*)>
62  * </pre>
63  *
64  * @author Heiko.Rupp@cellent.de
65  * @author <a HREF="mailto:dimitris@jboss.org">Dimitris Andreadis</a>.
66  * @version $Revision: 37406 $
67  */

68 public class XMLFilePersistenceManager extends Object JavaDoc
69    implements PersistenceManager
70 {
71    protected static Logger log = Logger.getLogger(XMLFilePersistenceManager.class);
72    /** A flag set to true to prevent attribute updates from within load
73     * triggering stores.
74     */

75    protected boolean isLoading;
76
77    // Constructors --------------------------------------------------
78

79    public XMLFilePersistenceManager()
80    {
81       super();
82    }
83
84    // Public --------------------------------------------------------
85

86    /**
87     * Loads the attributes from the given file
88     *
89     * @param mbean to store to
90     * @param metadata with file location etc.
91     * @exception MBeanException
92     */

93    public void load(ModelMBeanInvoker mbean, MBeanInfo JavaDoc metadata)
94       throws MBeanException JavaDoc
95    {
96       log.debug("load, resource:" + mbean.getResource());
97
98       if (metadata == null)
99       {
100          return;
101       }
102       if (log.isTraceEnabled())
103          log.trace("metadata: " + metadata);
104
105       File JavaDoc storeFile = getStoreFile(metadata, false);
106       if (storeFile == null)
107       {
108          return;
109       }
110
111       try
112       {
113          AttributeList JavaDoc attributes = new AttributeList JavaDoc();
114
115          FileInputStream JavaDoc fis = new FileInputStream JavaDoc(storeFile);
116          BufferedReader JavaDoc buf = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(fis));
117
118          String JavaDoc line, line2;
119          while ((line = buf.readLine()) != null)
120          {
121             log.trace("Line: " + line);
122             if (line.equals("<attributes>"))
123                continue;
124             if (line.equals("</attributes>"))
125                continue;
126
127             // trim leading spaces
128
line = line.substring(line.indexOf("<"));
129
130             if (!line.startsWith("<attribute"))
131             {
132                log.warn("Unknown line, skipping " + line);
133                continue;
134             }
135
136             // read attribute name
137
int pos = line.indexOf("name=\"") + 6; // skip name="
138
line2 = line.substring(pos);
139             int pos2 = line2.indexOf("\"");
140             String JavaDoc name = line2.substring(0, pos2);
141             log.debug("name: " + name);
142
143             // read attribute type
144
pos = line.indexOf("type=\"") + 6; // skip type="
145
line2 = line.substring(pos);
146             pos2 = line2.indexOf("\"");
147             String JavaDoc type = line2.substring(0, pos2);
148             log.debug("type: " + type);
149
150             // read attribute value
151
pos = line.indexOf(">");
152             pos2 = line.lastIndexOf("<");
153             String JavaDoc value = line.substring(pos + 1, pos2);
154             log.debug("value :" + value);
155
156             Object JavaDoc oVal = convert(value, type);
157             Attribute JavaDoc att = new Attribute JavaDoc(name, oVal);
158             attributes.add(att);
159
160          } // while
161

162          mbean.setAttributes(attributes);
163       }
164       catch (Exception JavaDoc e)
165       {
166          log.error("Error loading MBean state", e);
167       }
168       setIsLoading(false);
169    }
170
171    /** What we need to get here is 1) the persist location, and 2) the entire
172     * contents of the mbean. #2 contains the entire contents (state) of the
173     * model object, as well as the meta data that the mbean provides.
174     * As such, serializing this (MBeanInfo) object (brute force) in effect
175     * serializes the model as well.
176     *
177     * @param metadata
178     * @exception MBeanException
179     */

180    public void store(MBeanInfo JavaDoc metadata) throws MBeanException JavaDoc
181    {
182       if (isLoading())
183       {
184          return;
185       }
186
187       ModelMBeanInfo JavaDoc mmeta =
188          MBeanInfoConversion.toModelMBeanInfo(metadata, true);
189
190       log.debug("store");
191       if (log.isTraceEnabled())
192          log.trace("metadata: " + metadata);
193       File JavaDoc storeFile = getStoreFile(metadata, true);
194       if (storeFile == null)
195       {
196          return;
197       }
198
199       try
200       {
201          log.debug("Storing to file: " + storeFile.getAbsolutePath());
202          FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(storeFile);
203          MBeanAttributeInfo JavaDoc[] mais = mmeta.getAttributes();
204          StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
205          buf.append("<attributes>\n");
206          for (int i = 0; i < mais.length; i++)
207          {
208             ModelMBeanAttributeInfo JavaDoc mai = (ModelMBeanAttributeInfo JavaDoc) mais[i];
209             buf.append(" <attribute name=\"" + mai.getName() + "\" ");
210             buf.append("type=\"" + mai.getType() + "\">");
211             log.debug("Trying to load " + mai.getName());
212             Descriptor JavaDoc aDesc = mai.getDescriptor();
213             if (aDesc==null)
214                 throw new Exception JavaDoc("aDesc is null");
215             log.debug(aDesc.toString());
216             Object JavaDoc att = aDesc.getFieldValue(ModelMBeanConstants.ATTRIBUTE_VALUE);
217             if (att!=null)
218                 buf.append(att.toString());
219             else
220                 log.warn("att was null");
221             buf.append("</attribute>\n");
222          }
223          buf.append("</attributes>");
224          log.trace(buf.toString());
225          fos.write(buf.toString().getBytes());
226          fos.close();
227       }
228       catch (Exception JavaDoc e)
229       {
230             e.printStackTrace();
231          throw new MBeanException JavaDoc(e, "Error in persisting MBean.");
232       }
233    }
234
235    // Protected -----------------------------------------------------
236

237    protected boolean isLoading()
238    {
239       return isLoading;
240    }
241
242    protected void setIsLoading(boolean newIsLoading)
243    {
244       isLoading = newIsLoading;
245    }
246
247    /**
248     * Obtain the store location from the ModelMBean Descriptor.
249     * If the file name does not end on ".xml", it will be converted
250     * to do so.
251     * @param metadata
252     * @param createFile
253     * @return
254     * @throws MBeanException
255     */

256    protected File JavaDoc getStoreFile(MBeanInfo JavaDoc metadata, boolean createFile)
257       throws MBeanException JavaDoc
258    {
259       Descriptor JavaDoc d = ((ModelMBeanInfo JavaDoc) metadata).getMBeanDescriptor();
260       String JavaDoc dirPath =
261          (String JavaDoc) d.getFieldValue(ModelMBeanConstants.PERSIST_LOCATION);
262       String JavaDoc file = (String JavaDoc) d.getFieldValue(ModelMBeanConstants.PERSIST_NAME);
263       if (dirPath == null)
264       {
265          log.debug(
266             "No "
267                + ModelMBeanConstants.PERSIST_LOCATION
268                + " descriptor value found, using '.'");
269          dirPath = ".";
270       }
271       if (file == null)
272       {
273          log.debug(
274             "No "
275                + ModelMBeanConstants.PERSIST_NAME
276                + " descriptor value found");
277          return null;
278       }
279
280       dirPath = StringPropertyReplacer.replaceProperties(dirPath);
281       file = StringPropertyReplacer.replaceProperties(file);
282       // tack on .xml if not there
283
if (!file.endsWith(".xml"))
284          file = file + ".xml";
285       File JavaDoc dir = new File JavaDoc(dirPath);
286       File JavaDoc storeFile = new File JavaDoc(dir, file);
287       boolean exists = storeFile.exists();
288       log.debug("Store file is: " + storeFile.getAbsolutePath());
289       if (exists == false && createFile == true)
290       {
291          dir.mkdirs();
292          try
293          {
294             storeFile.createNewFile();
295          }
296          catch (IOException JavaDoc e)
297          {
298             throw new MBeanException JavaDoc(e, "Failed to create store file");
299          }
300       }
301       else if (exists == false)
302       {
303          storeFile = null;
304       }
305       return storeFile;
306    }
307
308    /**
309     * Convert val into an Object of type type -- same as in twiddle.setCommand
310     * @param val The given value
311     * @param oType the wanted return type
312     * @return the value in the correct representation
313     * @throws Exception various :)
314     */

315    private Object JavaDoc convert(String JavaDoc val, String JavaDoc oType) throws Exception JavaDoc
316    {
317       PropertyEditor JavaDoc editor = PropertyEditors.getEditor(oType);
318       editor.setAsText(val);
319       return editor.getValue();
320    }
321 }
322
Popular Tags