1 17 package org.apache.servicemix.store.jdbc; 18 19 import java.io.IOException ; 20 import java.io.ObjectInputStream ; 21 import java.io.ObjectOutputStream ; 22 import java.sql.Connection ; 23 24 import org.apache.activeio.util.ByteArrayInputStream; 25 import org.apache.activeio.util.ByteArrayOutputStream; 26 import org.apache.commons.logging.Log; 27 import org.apache.commons.logging.LogFactory; 28 import org.apache.servicemix.store.Store; 29 30 public class JdbcStore implements Store { 31 32 private static final Log log = LogFactory.getLog(JdbcStore.class); 33 34 private JdbcStoreFactory factory; 35 private String name; 36 37 public JdbcStore(JdbcStoreFactory factory, String name) { 38 this.factory = factory; 39 this.name = name; 40 } 41 42 public boolean hasFeature(String name) { 43 return PERSISTENT.equals(name) || 44 (CLUSTERED.equals(name) && factory.isClustered()) || 45 (TRANSACTIONAL.equals(name) && factory.isTransactional()); 46 } 47 48 public void store(String id, Object data) throws IOException { 49 log.debug("Storing object with id: " + id); 50 Connection connection = null; 51 try { 52 ByteArrayOutputStream buffer = new ByteArrayOutputStream(); 53 ObjectOutputStream out = new ObjectOutputStream (buffer); 54 out.writeObject(data); 55 out.close(); 56 connection = factory.getDataSource().getConnection(); 57 factory.getAdapter().doStoreData(connection, name + ":" + id, buffer.toByteArray()); 58 } catch (Exception e) { 59 throw (IOException ) new IOException ("Error storing object").initCause(e); 60 } finally { 61 if (connection != null) { 62 try { 63 connection.close(); 64 } catch (Exception e) { 65 throw (IOException ) new IOException ("Error closing connection").initCause(e); 66 } 67 } 68 } 69 } 70 71 public String store(Object data) throws IOException { 72 String id = factory.getIdGenerator().generateId(); 73 store(id, data); 74 return id; 75 } 76 77 public Object load(String id) throws IOException { 78 log.debug("Loading object with id: " + id); 79 Connection connection = null; 80 try { 81 connection = factory.getDataSource().getConnection(); 82 byte[] data = factory.getAdapter().doLoadData(connection, name + ":" + id); 83 Object result = null; 84 if (data != null) { 85 ObjectInputStream ois = new ObjectInputStream (new ByteArrayInputStream(data)); 86 result = ois.readObject(); 87 factory.getAdapter().doRemoveData(connection, name + ":" + id); 88 } 89 return result; 90 } catch (Exception e) { 91 throw (IOException ) new IOException ("Error storing object").initCause(e); 92 } finally { 93 if (connection != null) { 94 try { 95 connection.close(); 96 } catch (Exception e) { 97 throw (IOException ) new IOException ("Error closing connection").initCause(e); 98 } 99 } 100 } 101 } 102 103 } 104 | Popular Tags |