1 16 17 import java.sql.*; 18 import java.io.Serializable ; 19 import java.io.*; 20 21 import org.apache.velocity.context.AbstractContext; 22 import org.apache.velocity.context.Context; 23 24 41 42 public class DBContext extends AbstractContext 43 { 44 Connection conn = null; 45 46 public DBContext() 47 { 48 super(); 49 setup(); 50 } 51 52 public DBContext( Context inner ) 53 { 54 super( inner ); 55 setup(); 56 } 57 58 63 public Object internalGet( String key ) 64 { 65 try 66 { 67 String data = null; 68 69 String sql = "SELECT k, val FROM contextstore WHERE k ='"+key+"'"; 70 71 Statement s = conn.createStatement(); 72 73 ResultSet rs = s.executeQuery( sql ); 74 75 if(rs.next()) 76 data = rs.getString("val"); 77 78 rs.close(); 79 s.close(); 80 81 ObjectInputStream in = new ObjectInputStream( new ByteArrayInputStream( data.getBytes() )); 82 83 Object o = in.readObject(); 84 85 in.close(); 86 87 return o; 88 } 89 catch(Exception e) 90 { 91 System.out.println("internalGet() : " + e ); 92 } 93 94 return null; 95 } 96 97 103 public Object internalPut( String key, Object value ) 104 { 105 try 106 { 107 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 108 ObjectOutputStream out = new ObjectOutputStream( baos ); 109 110 out.writeObject( value ); 111 String data = baos.toString(); 112 113 out.close(); 114 baos.close(); 115 116 Statement s = conn.createStatement(); 117 118 s.executeUpdate( "DELETE FROM contextstore WHERE k = '" + key + "'" ); 119 s.executeUpdate( "INSERT INTO contextstore (k,val) values ('"+key+"','" + data + "')" ); 120 121 s.close(); 122 } 123 catch(Exception e) 124 { 125 System.out.println("internalGet() : " + e ); 126 } 127 128 return null; 129 } 130 131 136 public boolean internalContainsKey(Object key) 137 { 138 return false; 139 } 140 141 146 public Object [] internalGetKeys() 147 { 148 return null; 149 } 150 151 156 public Object internalRemove(Object key) 157 { 158 return null; 159 } 160 161 162 private void setup() 163 { 164 try 165 { 166 Class.forName("org.gjt.mm.mysql.Driver").newInstance(); 167 conn = DriverManager.getConnection("jdbc:mysql://localhost/test?user=root"); 168 } 169 catch (Exception e) 170 { 171 System. out.println(e); 172 } 173 174 return; 175 } 176 } 177 178 | Popular Tags |