001: /*
002: * WbPersistence.java
003: *
004: * This file is part of SQL Workbench/J, http://www.sql-workbench.net
005: *
006: * Copyright 2002-2008, Thomas Kellerer
007: * No part of this code maybe reused without the permission of the author
008: *
009: * To contact the author please send an email to: support@sql-workbench.net
010: *
011: */
012: package workbench.util;
013:
014: import java.beans.BeanInfo;
015: import java.beans.ExceptionListener;
016: import java.beans.IntrospectionException;
017: import java.beans.Introspector;
018: import java.beans.PropertyDescriptor;
019: import java.beans.XMLDecoder;
020: import java.beans.XMLEncoder;
021: import java.io.BufferedInputStream;
022: import java.io.BufferedOutputStream;
023: import java.io.FileInputStream;
024: import java.io.FileOutputStream;
025: import java.io.IOException;
026: import java.io.InputStream;
027:
028: import workbench.log.LogMgr;
029:
030: public class WbPersistence implements ExceptionListener {
031: private String filename;
032:
033: public WbPersistence() {
034: }
035:
036: public WbPersistence(String file) {
037: filename = file;
038: }
039:
040: /**
041: * Makes a property of the given class transient, so that it won't be written
042: * into the XML file when saved using WbPersistence
043: * @param clazz
044: * @param property
045: */
046: public static void makeTransient(Class clazz, String property) {
047: try {
048: BeanInfo info = Introspector.getBeanInfo(clazz);
049: PropertyDescriptor propertyDescriptors[] = info
050: .getPropertyDescriptors();
051: for (int i = 0; i < propertyDescriptors.length; i++) {
052: PropertyDescriptor pd = propertyDescriptors[i];
053: if (pd.getName().equals(property)) {
054: pd.setValue("transient", Boolean.TRUE);
055: }
056: }
057: } catch (IntrospectionException e) {
058: }
059: }
060:
061: public Object readObject() throws Exception {
062: if (this .filename == null)
063: throw new IllegalArgumentException("No filename specified!");
064: InputStream in = new BufferedInputStream(new FileInputStream(
065: filename), 32 * 1024);
066: return readObject(in);
067: }
068:
069: public Object readObject(InputStream in) throws Exception {
070: try {
071: XMLDecoder e = new XMLDecoder(in, null, this );
072: Object result = e.readObject();
073: e.close();
074: return result;
075: } finally {
076: try {
077: in.close();
078: } catch (Throwable th) {
079: }
080: }
081: }
082:
083: public void writeObject(Object aValue) throws IOException {
084: if (aValue == null)
085: return;
086:
087: BufferedOutputStream out = null;
088: try {
089: out = new BufferedOutputStream(new FileOutputStream(
090: filename), 32 * 1024);
091: XMLEncoder e = new XMLEncoder(out);
092: e.writeObject(aValue);
093: e.close();
094: } finally {
095: try {
096: out.close();
097: } catch (Throwable th) {
098: }
099: }
100: }
101:
102: public void exceptionThrown(Exception e) {
103: LogMgr.logError("WbPersistence", "Error reading file "
104: + filename, e);
105: }
106:
107: }
|