jtdaoadapter.java

来自「Java Pattern Oriented Framework (Jt) 是为了」· Java 代码 · 共 2,310 行 · 第 1/4 页

JAVA
2,310
字号
                return (out);
        } else
            return (null);

    }
    
    /**
     * Find DAO
     */
 /*   
    private Object find (Object obj, Object key) {
        //Session session;
        Object output = null;

        if (obj == null) {
            handleError ("find: invalid parameter obj (null)");
            return (null);
        }    
        
        if (key == null) {
            handleError ("find: invalid parameter key (null)");           
            return (null);
        }    


        
        return (output);
    }
*/ 
   
   private JtDAOContext retrieveContext () {
       
       JtDAOContext context;
       
       if (JtDAOContext.getInstance() == null) {
           factory.createObject(JtDAOContext.JtCLASS_NAME);    // Create JtDAOContext singleton       
       }
       
       context = (JtDAOContext) JtDAOContext.getInstance();
       
       if (context == null) {
           handleError ("Unable to create DAO context.");
           return (null);
       }
       return (context);
   }
    
    
   private boolean retrieveConfiguration (JtDAOContext context) {

       Hashtable configTable;
       JtDAOAdapter adapter = null;
   
       if (context == null)
           return (false);

       configTable = context.getConfigTable();

       if (configTable == null)
           return (false);
       

       adapter = (JtDAOAdapter) configTable.get(configFile);
       if (adapter == null)
           return (false);
       
       
       // Copy
       if (adapter != null) {
           this.setDriver(adapter.getDriver());
           this.setUrl(adapter.getUrl());
           this.setPassword(adapter.getPassword());
           this.setUser(adapter.getUser());  
           this.classTable = adapter.classTable;  // careful           
       }
       
       return (true);
       
   }
   
   private void saveConfiguration (JtDAOContext context) {

       Hashtable configTable;
       JtDAOAdapter adapter = new JtDAOAdapter ();
       

       if (context == null)
           return;
       

       adapter.setDriver(this.getDriver());
       adapter.setUrl(this.getUrl());
       adapter.setPassword(this.getPassword());
       adapter.setUser(this.getUser());  
       adapter.classTable = this.classTable;  // careful        
       
       configTable = context.getConfigTable();

       if (configTable != null) {
           configTable.put(configFile, adapter);
       }           
       
   }
    
   private void initialize () {
       JtJDBCAdapter jdbcAdapter;
       Connection conn;
       JtDAOContext context;

       
       handleTrace ("JtDAOAdapter:initialize ...");
       
       
       context = retrieveContext ();
       
       if (context == null) {
           return;   
       }

       if (!retrieveConfiguration (context)) {
           readConfigFile ();
           saveConfiguration (context);
       }    
       
       if (db != null)
           return;

       db = (JtObject) factory.createObject (JtJDBCAdapter.JtCLASS_NAME, "db");
       
       jdbcAdapter = (JtJDBCAdapter) db;
       
       
       if (datasource != null) {
           jdbcAdapter.setDatasource(datasource);
       } else {

           if (driver == null) {
               handleError ("datasource or driver attribute needs to be set.");
               return;           
           }   

           if (user == null) {
               handleError ("datasource or user attribute needs to be set.");
               return;           
           }   

           if (url == null) {
               handleError ("datasource or driver attribute needs to be set.");
               return;           
           }   

           if (password == null) {
               handleError ("datasource or password attribute needs to be set.");
               return;           
           }  

           jdbcAdapter.setDriver(driver) ;
           jdbcAdapter.setUser(user);       
           jdbcAdapter.setUrl(url);  
           jdbcAdapter.setPassword(password);     
       }       

       // Connect to the data source

       factory.sendMessage (jdbcAdapter, new JtMessage (JtJDBCAdapter.JtCONNECT));
       
       if (propagateException (jdbcAdapter) != null)
           return;


       if (autocommit == false) { // check
           conn = jdbcAdapter.getConnection();


           try {
               conn.setAutoCommit(autocommit);
           } catch (SQLException e) {
               handleException (e);
           }
       }
       
       
   }
    
    
    /**
     * Delete DAO
     */
   
    private Object delete (Object obj) {
        JtMessage msg;
        String query;
        //Object conn;
        //ResultSet res;
        Object out;
        PreparedStatement pst;

        msg = new JtMessage ();

        //if (db == null)
        //    realize ();
        
        if (obj == null) {
            handleError ("delete: invalid parameter obj (null)");
            return (null);
        }

        attr = getAttributes (obj); // check

        query = buildDeleteQuery (obj);

        if (query == null || db == null)
            return (null);

        
        msg.setMsgId (JtJDBCAdapter.JtPREPARE_STATEMENT);
        msg.setMsgContent (query);

        pst = (PreparedStatement) factory.sendMessage (db, msg);
        

        if (propagateException (db) != null)
            return (null);

        if (pst == null)
            return (null);  // check

        if (!setKeyParameters (pst, retrieveKeys (obj.getClass().getName()), obj, 1, false))
            return null; 


        msg.setMsgId (JtJDBCAdapter.JtEXECUTE_PREPARED_UPDATE);
        msg.setMsgContent (pst);
        out = factory.sendMessage (db, msg); //check



        if (propagateException (db) != null)
            return (null);
        

        try {
            pst.close ();
        }
        catch (Exception ex) {
            handleException (ex);
        }
    
        
        //msg.setMsgId (JtJDBCAdapter.JtUPDATE);
        //msg.setMsgContent (query);

        //out = factory.sendMessage (db, msg);
        //propagateException (db);

        if (out instanceof Integer) {
            if (((Integer) out).intValue () != 1)
                return (null);
            else
                return (out); // check
        } else
            return (null);

    }
    
    /**
     * Begin transaction
     */
    private void beginTransaction () {
        //Session session = null;

        //this.setObjException(null);  // reset the exception - check redundant
        
        if (db == null)
            return;
        
        factory.sendMessage (db, new JtMessage (JtJDBCAdapter.JtBEGIN_TRANSACTION));
        
        propagateException (db);
       
        /*
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            if (session != null)
                session.beginTransaction();
        } catch (Exception ex) {
            handleException (ex);
        }
        */
    }
    
    
    /**
     *  Rollback transaction
     */
    
    private void rollbackTransaction () {
        //Session session = null;
        
        if (db == null)
            return;
        
        factory.sendMessage (db, new JtMessage (JtJDBCAdapter.JtROLLBACK));
        
        propagateException (db);

        /*
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();

            if (session != null)
                session.getTransaction().rollback();
        } catch (Exception ex) {
            handleException (ex);
        }
        */
    }
    
    /**
     *  Commit transaction
     */
    
    private void commitTransaction () {
        //Session session = null;
        
        if (db == null)
            return;
        
        factory.sendMessage (db, new JtMessage (JtJDBCAdapter.JtCOMMIT));
        
        propagateException (db);
/*
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();

            if (session != null)
                session.getTransaction().commit();
        } catch (Exception ex) {
            handleException (ex);
        }
*/
    }
    
    private Object mapRow (Object obj, ResultSet rs, boolean checkColumn) {

        //Object args[];
        PropertyDescriptor[] prop;
        int i;
        Class p;
        BeanInfo info = null;
        String value; // check
        String column;
        java.util.Date dateValue;
        
        if (obj == null || rs == null)
            return (null);

        try {

            info = Introspector.getBeanInfo(
                    obj.getClass (), obj.getClass ().getSuperclass());
        } catch(Exception e) {
            handleException (e);
            return (null);
        }

        prop = info.getPropertyDescriptors();
        for(i = 0; i < prop.length; i++) {
            //System.out.print ("Attribute:" + 
            //prop[i].getName());
            p = prop[i].getPropertyType();

            column = getMapping (obj.getClass().getName(), prop[i].getName());

            if (column == null) {
                continue;
            }
            
            
            // Chech if the column exists
            if (checkColumn)
                try {
                    rs.findColumn(column);
                } catch (SQLException e) {
                    continue;
                }

            if (p.getName().equals ("java.util.Date") ){
                dateValue = getDateValue (rs, column);
                factory.setValue (obj, prop[i].getName(), dateValue); 
                continue;
                //value = getRSDateValue (rs, column);
            } else if (p.getName().equals ("boolean") ){         
                value = getRSBooleanValue (rs, column);
            } else // check
                value = getRSValue (rs, column);

            //handleTrace ("factory.setValue:" + prop[i].getName() + ":" + value, 0);
            factory.setValue (obj, prop[i].getName(), value);     

        }
        return (obj);
    }
    
    
    // find: find records based on a query

    private List findRecords (String query, Object obj1) {
        JtMessage msg;
        ResultSet res;
        Object obj;
        List col = new LinkedList ();

        msg = new JtMessage ();

        
        if (obj1 == null)
            return null;
            

        attr = getAttributes (obj1); // check

        //query = build_select_query ();

        if (query == null || db == null)
            return (null);

        
        msg.setMsgId (JtJDBCAdapter.JtEXECUTE_QUERY);
        msg.setMsgContent (query);


        res = (ResultSet) factory.sendMessage (db, msg);

        if (propagateException (db) != null)
            return (null);


        if (res == null)
            return (null);

        msg.setMsgId (JtCollection.JtADD);

        try {

            while (res.next()) {
                obj = obj1.getClass().newInstance ();

                //((JtDAO) obj).setKey (key);
                //((JtDAO) obj).setTable (table);

                obj = mapRow (obj, res, true);
                if (obj == null)
                    continue; // check

                //msg.setMsgContent (obj);
                //sendMessage (col, msg);
                col.add(obj);

            }

        } catch (Exception e) {
            handleException (e);
            return (null);
        } 

        try {
            res.close ();
        }
        catch (Exception ex) {
            handleException (ex);
        }

        return (col);
    }
    
    
    /*
     * Execute a Query
     */
    
    
    private Object executeQuery (String query, Object obj) {
        List result = null;

        if (query == null || obj == null)
            return (null);

        
        result = findRecords (query, obj); 
        return result;

    }
    
/*    
    private String retrieveResourceName (String className) {
        StringBuffer buffer = new StringBuffer ();
        int i;
        char c;
        
        if (className == null)
            return (null);
        
        
        for (i = 0; i < className.length(); i++) {
            c = className.charAt(i);
            if (c == '.')
                buffer.append('/');
            else
                buffer.append(c);
        }
        
        buffer.append(".hbm.xml");
       
        return (buffer.toString());
        
        
    }
  */
    
    private void readConfigFile () {
        JDOMAdapter adapter = new JDOMAdapter ();
        JtMessage msg = new JtMessage (JDOMAdapter.READ_STREAM);
        JtMessage msg1 = new JtMessage (JDOMAdapter.FIND_ELEMENTS);
        List list;
        Iterator it;
        Element elem;
        String res;
        
        InputStream resStream;
        
        
        if (configFile == null) {
            handleError ("configFile attribute needs to be set.");
            return;   
        }   
        
        resStream = this.getClass().getClassLoader().getResourceAsStream (configFile);
                
        if (resStream == null)
            return;
    
        adapter.setInputStream(resStream);
        
        factory.sendMessage(adapter, msg);
        
        msg1.setMsgContent("mapping");
        list = (List) factory.sendMessage(adapter, msg1);
        
        if (list == null || list.isEmpty())
            return;
        it = list.iterator();
        
        while (it.hasNext()) {
            elem = (Element) it.next();
            res = elem.getAttributeValue ("resource");
            readMappingStream (res);
            //resourceTable.put(res, res);
        }
        
        msg1.setMsgContent("property");
        list = (List) factory.sendMessage(adapter, msg1);
        
        if (list == null || list.isEmpty())
            return;
        it = list.iterator();
        
        while (it.hasNext()) {
            elem = (Element) it.next();
            res = elem.getAttributeValue ("name");
            if ("connection.driver_class".equals(res))
                this.setDriver(elem.getText());

            if ("connection.url".equals(res))
                this.setUrl(elem.getText());
            
            if ("connection.username".equals(res))
                this.setUser(elem.getText());

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?