KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > mx > persistence > ObjectStreamPersistenceManager


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.mx.persistence;
23
24 import java.io.File JavaDoc;
25 import java.io.FileInputStream JavaDoc;
26 import java.io.FileOutputStream JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.io.ObjectInputStream JavaDoc;
29 import java.io.ObjectOutputStream JavaDoc;
30 import javax.management.Attribute JavaDoc;
31 import javax.management.AttributeList JavaDoc;
32 import javax.management.Descriptor JavaDoc;
33 import javax.management.MBeanAttributeInfo JavaDoc;
34 import javax.management.MBeanException JavaDoc;
35 import javax.management.MBeanInfo JavaDoc;
36 import javax.management.modelmbean.ModelMBeanAttributeInfo JavaDoc;
37 import javax.management.modelmbean.ModelMBeanInfo JavaDoc;
38
39 import org.jboss.mx.modelmbean.ModelMBeanConstants;
40 import org.jboss.mx.modelmbean.ModelMBeanInvoker;
41 import org.jboss.mx.persistence.PersistenceManager;
42
43 import org.jboss.logging.Logger;
44 import org.jboss.util.StringPropertyReplacer;
45
46 /**
47  * Object Stream Persistence Manager. <p>
48  *
49  * Persists the MBean to the file system using an Object Stream.
50  * Includes code based on examples in Juha's JMX Book. <p>
51  *
52  * Object Streams written to disk are admittedly lacking in the area of
53  * "long-term", "portable", or "human-readable" persistence. They are fairly
54  * straightforward, however.
55  * Primarily, this class is useful for demonstration and "quick & dirty" persistence.
56  *
57  * @todo currently metadata as well as data is stored. only data needs to be stored.
58  * @author Matt Munz
59  * @author Scott.Stark@jboss.org
60  * @version $Revision: 37459 $
61  */

62 public class ObjectStreamPersistenceManager
63     extends Object JavaDoc
64     implements PersistenceManager
65 {
66    protected static Logger log = Logger.getLogger(ObjectStreamPersistenceManager.class);
67    /** A flag set to true to prevent attribute updates from within load
68     * triggering stores.
69     */

70    protected boolean isLoading;
71
72    // Constructors --------------------------------------------------
73

74    public ObjectStreamPersistenceManager()
75    {
76       super();
77    }
78
79
80    // Public --------------------------------------------------------
81

82    /**
83     * deserializes state from the object input stream
84     *
85     * @param mbean
86     * @param metadata
87     * @exception MBeanException
88     */

89    public void load(ModelMBeanInvoker mbean, MBeanInfo JavaDoc metadata) throws MBeanException JavaDoc
90    {
91       log.debug("load, resource:"+mbean.getResource());
92
93       if (metadata == null)
94       {
95          return;
96       }
97       if( log.isTraceEnabled() )
98          log.trace("metadata: "+metadata);
99
100       File JavaDoc storeFile = getStoreFile(metadata, false);
101       if (storeFile == null)
102       {
103          return;
104       }
105
106       try
107       {
108          FileInputStream JavaDoc fis = new FileInputStream JavaDoc(storeFile);
109          ObjectInputStream JavaDoc ois = new ObjectInputStream JavaDoc(fis);
110          ModelMBeanInfo JavaDoc storeMetadata = (ModelMBeanInfo JavaDoc) ois.readObject();
111          ois.close();
112          log.debug("metadata deserialized");
113          if( log.isTraceEnabled() )
114             log.trace("storeMetadata: "+storeMetadata);
115          loadFromMetadata(mbean, storeMetadata);
116       }
117       catch (Exception JavaDoc e)
118       {
119          log.error("Error loading MBean state", e);
120       }
121    }
122
123    /** What we need to get here is 1) the persist location, and 2) the entire
124     * contents of the mbean. #2 contains the entire contents (state) of the
125     * model object, as well as the meta data that the mbean provides.
126     * As such, serializing this (MBeanInfo) object (brute force) in effect
127     * serializes the model as well.
128     *
129     * @param metadata
130     * @exception MBeanException
131     */

132    public void store(MBeanInfo JavaDoc metadata) throws MBeanException JavaDoc
133    {
134       if (isLoading())
135       {
136          return;
137       }
138
139       log.debug("store");
140       if( log.isTraceEnabled() )
141          log.trace("metadata: " + metadata);
142       File JavaDoc storeFile = getStoreFile(metadata, true);
143       if( storeFile == null )
144       {
145          return;
146       }
147
148       try
149       {
150          log.debug("Storing to file: "+storeFile.getAbsolutePath());
151          FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(storeFile);
152          ObjectOutputStream JavaDoc oos = new ObjectOutputStream JavaDoc(fos);
153          oos.writeObject(metadata);
154       }
155       catch (IOException JavaDoc e)
156       {
157          throw new MBeanException JavaDoc(e, "Error in persisting MBean.");
158       }
159    }
160
161    // Protected -----------------------------------------------------
162

163    /** Obtain the attribute values from the metadata and invoke setAttributes
164     * on the mbean invoker.
165     *
166     * @param mbean the invoker and assocaited mbean resource
167     * @param metadata the metadata to use as the attributes value source
168     */

169    protected void loadFromMetadata(ModelMBeanInvoker mbean, ModelMBeanInfo JavaDoc metadata)
170    {
171       AttributeList JavaDoc attributes = new AttributeList JavaDoc();
172       // iterate over all attributes in metadata
173
MBeanAttributeInfo JavaDoc[] attrs = metadata.getAttributes();
174       for (int i = 0; i < attrs.length; i++)
175       {
176          /// for each attribute, create a new Attribute object and add it to the collection
177
ModelMBeanAttributeInfo JavaDoc attributeInfo = (ModelMBeanAttributeInfo JavaDoc)attrs[i];
178          Descriptor JavaDoc attrDesc = attributeInfo.getDescriptor();
179          Object JavaDoc name = attrDesc.getFieldValue(ModelMBeanConstants.NAME);
180          Object JavaDoc value = attrDesc.getFieldValue(ModelMBeanConstants.ATTRIBUTE_VALUE);
181          Object JavaDoc updated = attrDesc.getFieldValue(ModelMBeanConstants.LAST_UPDATED_TIME_STAMP2);
182          
183          // set only if value has been set; otherwise cannot distinguish
184
// between a null value and a value never set
185
if (updated != null)
186          {
187             log.debug("loading attribute name: " + name + ", value: " + value);
188             Attribute JavaDoc curAttribute = new Attribute JavaDoc(name.toString(), value);
189             attributes.add(curAttribute);
190          }
191       }
192
193       try
194       {
195          setIsLoading(true);
196          mbean.setAttributes(attributes);
197       }
198       finally
199       {
200          setIsLoading(false);
201       }
202    }
203
204    protected boolean isLoading()
205    {
206       return isLoading;
207    }
208
209    protected void setIsLoading(boolean newIsLoading)
210    {
211       isLoading = newIsLoading;
212    }
213    protected File JavaDoc getStoreFile(MBeanInfo JavaDoc metadata, boolean createFile)
214       throws MBeanException JavaDoc
215    {
216       Descriptor JavaDoc d = ((ModelMBeanInfo JavaDoc)metadata).getMBeanDescriptor();
217       String JavaDoc dirPath = (String JavaDoc)d.getFieldValue(ModelMBeanConstants.PERSIST_LOCATION);
218       String JavaDoc file = (String JavaDoc) d.getFieldValue(ModelMBeanConstants.PERSIST_NAME);
219       if( dirPath == null )
220       {
221          log.debug("No "+ModelMBeanConstants.PERSIST_LOCATION
222             +" descriptor value found, using '.'");
223          dirPath = ".";
224       }
225       if( file == null )
226       {
227          log.debug("No "+ModelMBeanConstants.PERSIST_NAME+" descriptor value found");
228          return null;
229       }
230
231       dirPath = StringPropertyReplacer.replaceProperties(dirPath);
232       file = StringPropertyReplacer.replaceProperties(file);
233       File JavaDoc dir = new File JavaDoc(dirPath);
234       File JavaDoc storeFile = new File JavaDoc(dir, file);
235       boolean exists = storeFile.exists();
236       log.debug("Store file is: "+storeFile.getAbsolutePath());
237       if( exists == false && createFile == true )
238       {
239          dir.mkdirs();
240          try
241          {
242             storeFile.createNewFile();
243          }
244          catch(IOException JavaDoc e)
245          {
246             throw new MBeanException JavaDoc(e, "Failed to create store file");
247          }
248       }
249       else if( exists == false )
250       {
251          storeFile = null;
252       }
253       return storeFile;
254    }
255 }
256
Popular Tags