001    /**
002     * DataBaseConnector.java
003     * jCOLIBRI2 framework. 
004     * @author Juan A. Recio-García.
005     * GAIA - Group for Artificial Intelligence Applications
006     * http://gaia.fdi.ucm.es
007     * 02/01/2007
008     */
009    package jcolibri.connector;
010    
011    import org.hibernate.*;
012    import org.hibernate.cfg.*;
013    import java.net.URL;
014    import java.util.*;
015    
016    import javax.xml.parsers.DocumentBuilder; 
017    import javax.xml.parsers.DocumentBuilderFactory;  
018    import org.w3c.dom.Document;
019    
020    import jcolibri.cbrcore.*;
021    import jcolibri.exception.InitializingException;
022    import jcolibri.util.FileIO;
023    
024    /**
025     * Implements a data base connector using the <a href="www.hibernate.org">Hibernate package</a>.
026     * <p>
027     * The configuration file follows the schema defined in
028     * <a href="DataBaseConnector.xsd">/doc/configfilesSchemas/DataBaseConnector.xsd</a>:
029     * <p>
030     * <img src="DataBaseConnectorSchema.jpg">
031     * <p> 
032     * There are several examples that incrementally show how to use this connector: Test1, Test2, Test3, Test4 and Test5.
033     * 
034     * @author Juan Antonio Recio García
035     * @version 2.0
036     * 
037     * @see jcolibri.test.test1.Test1
038     * @see jcolibri.test.test2.Test2
039     * @see jcolibri.test.test3.Test3
040     * @see jcolibri.test.test4.Test4
041     * @see jcolibri.test.test5.Test5
042     */
043    public class DataBaseConnector implements Connector {
044    
045            SessionFactory sessionFactory;
046            private String descriptionClassName;
047            private String solutionClassName;
048            private String justOfSolutionClassName;
049            private String resultClassName;
050            
051            
052            /* (non-Javadoc)
053             * @see jcolibri.cbrcore.Connector#close()
054             */
055            public void close() {
056                    // TODO Auto-generated method stub
057            }
058    
059            /* (non-Javadoc)
060             * @see jcolibri.cbrcore.Connector#deleteCases(java.util.Collection)
061             */
062            public void deleteCases(Collection<CBRCase> cases) {
063                    // TODO Auto-generated method stub
064    
065            }
066    
067            /* (non-Javadoc)
068             * @see jcolibri.cbrcore.Connector#initFromXMLfile(java.io.File)
069             */
070            public void initFromXMLfile(URL file) throws InitializingException {
071                    try {
072                            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
073                    //factory.setValidating(true);   
074                    //factory.setNamespaceAware(true);
075                    DocumentBuilder builder = factory.newDocumentBuilder();
076                    Document document = builder.parse( file.openStream() );
077                    
078                    String hcf = document.getElementsByTagName("HibernateConfigFile").item(0).getTextContent();
079                    
080                    String descriptionMapFile = document.getElementsByTagName("DescriptionMappingFile").item(0).getTextContent();
081                    descriptionClassName = document.getElementsByTagName("DescriptionClassName").item(0).getTextContent();
082                    
083                    Configuration hbconfig = new Configuration();
084                    hbconfig.configure(FileIO.findFile(hcf));
085                    hbconfig.addURL(FileIO.findFile(descriptionMapFile));
086                    
087                    try{
088                            String solutionMapFile = document.getElementsByTagName("SolutionMappingFile").item(0).getTextContent();
089                            solutionClassName = document.getElementsByTagName("SolutionClassName").item(0).getTextContent();         
090                            hbconfig.addResource(solutionMapFile);
091                    }catch(Exception e)
092                    {
093                            org.apache.commons.logging.LogFactory.getLog(this.getClass()).info("Case does not have solution");
094                    }
095                    
096                    try{
097                            String justOfSolutionMapFile = document.getElementsByTagName("JustificationOfSolutionMappingFile").item(0).getTextContent();
098                            justOfSolutionClassName = document.getElementsByTagName("JustificationOfSolutionClassName").item(0).getTextContent();    
099                            hbconfig.addResource(justOfSolutionMapFile);
100                    }catch(Exception e)
101                    {
102                            org.apache.commons.logging.LogFactory.getLog(this.getClass()).info("Case does not have justification of the solution");
103                    }
104                    
105                    try{
106                            String resultMapFile = document.getElementsByTagName("ResultMappingFile").item(0).getTextContent();
107                            resultClassName = document.getElementsByTagName("ResultClassName").item(0).getTextContent();     
108                            hbconfig.addResource(resultMapFile);
109                    }catch(Exception e)
110                    {
111                            org.apache.commons.logging.LogFactory.getLog(this.getClass()).info("Case does not have result");
112                    }
113                         
114                    
115                    sessionFactory = hbconfig.buildSessionFactory();
116                                    
117                    } catch (Throwable ex) {
118                            throw new InitializingException(ex);
119                    }
120    
121            }
122    
123            /* (non-Javadoc)
124             * @see jcolibri.cbrcore.Connector#retrieveAllCases()
125             */
126            public Collection<CBRCase> retrieveAllCases(){
127                    
128                    java.util.ArrayList<CBRCase> res = new java.util.ArrayList<CBRCase>();
129            
130                    try 
131                    {
132                            Session session;// = sessionFactory.openSession();                              
133                            Transaction transaction; //= session.beginTransaction();
134                                            
135                            List descList = null;
136                            HashMap<Object, CaseComponent> solList = null;
137                            HashMap<Object, CaseComponent> justSolList = null;
138                            HashMap<Object, CaseComponent> resList = null;
139                            
140                            
141                            if(solutionClassName != null)
142                            {
143                                    session = sessionFactory.openSession(); 
144                                    transaction = session.beginTransaction();
145    
146                                    solList = new HashMap<Object, CaseComponent>();
147                                    List l = session.createQuery("from " + solutionClassName).list();
148                                    
149                                    transaction.commit();
150                                    session.close();
151                                    
152                                    for(Iterator iter = l.iterator(); iter.hasNext();)
153                                    {
154                                            CaseComponent cc = (CaseComponent)iter.next();
155                                            solList.put(cc.getIdAttribute().getValue(cc), cc);
156                                    }
157                            }
158                            if(justOfSolutionClassName != null)
159                            {
160                                    session = sessionFactory.openSession(); 
161                                    transaction = session.beginTransaction();
162    
163                                    justSolList = new HashMap<Object, CaseComponent>();
164                                    List l = session.createQuery("from " + justOfSolutionClassName).list();
165                                    transaction.commit();
166                                    session.close();
167    
168                                    for(Iterator iter = l.iterator(); iter.hasNext();)
169                                    {
170                                            CaseComponent cc = (CaseComponent)iter.next();
171                                            justSolList.put(cc.getIdAttribute().getValue(cc), cc);
172                                    }
173                            }
174                            if(resultClassName != null)
175                            {
176                                    session = sessionFactory.openSession(); 
177                                    transaction = session.beginTransaction();
178    
179                                    resList = new HashMap<Object, CaseComponent>();
180                                    List l = session.createQuery("from " + resultClassName).list();
181                                    transaction.commit();
182                                    session.close();
183    
184                                    for(Iterator iter = l.iterator(); iter.hasNext();)
185                                    {
186                                            CaseComponent cc = (CaseComponent)iter.next();
187                                            resList.put(cc.getIdAttribute().getValue(cc), cc);
188                                    }
189                            }
190    
191                            session = sessionFactory.openSession(); 
192                            transaction = session.beginTransaction();
193                            descList = session.createQuery("from "+ descriptionClassName).list();                   
194                            transaction.commit();
195                            session.close();
196    
197                            for(Iterator iter = descList.iterator(); iter.hasNext();)
198                            {
199                                    CBRCase _case = new CBRCase();
200                                    CaseComponent desc = (CaseComponent)iter.next();
201                                    _case.setDescription(desc);
202                                    
203                                    if(solutionClassName != null)
204                                    {
205                                            CaseComponent cc = solList.get(desc.getIdAttribute().getValue(desc));
206                                            if(cc != null)
207                                                    _case.setSolution(cc);
208                                    }
209                                    if(justOfSolutionClassName != null)
210                                    {
211                                            CaseComponent cc = justSolList.get(desc.getIdAttribute().getValue(desc));
212                                            if(cc != null)
213                                                    _case.setJustificationOfSolution(cc);
214                                    }                                               
215                                    if(resultClassName != null)
216                                    {
217                                            CaseComponent cc = resList.get(desc.getIdAttribute().getValue(desc));
218                                            if(cc != null)
219                                                    _case.setResult(cc);
220                                    }
221                                                    
222                                    res.add(_case);
223                                    
224                            }
225                            
226                            //transaction.commit();
227                            //session.close();
228                            
229                    } catch (Exception e) {
230                            org.apache.commons.logging.LogFactory.getLog(this.getClass()).error(e);
231                    }
232                    org.apache.commons.logging.LogFactory.getLog(this.getClass()).info(res.size()+" cases read from the database.");
233                    return res;
234            }
235    
236            /* (non-Javadoc)
237             * @see jcolibri.cbrcore.Connector#retrieveSomeCases(jcolibri.cbrcore.CaseBaseFilter)
238             */
239            public Collection<CBRCase> retrieveSomeCases(CaseBaseFilter filter) {
240                    // TODO Auto-generated method stub
241                    return null;
242            }
243    
244            /* (non-Javadoc)
245             * @see jcolibri.cbrcore.Connector#storeCases(java.util.Collection)
246             */
247            public void storeCases(Collection<CBRCase> cases) {
248                    
249                    
250                    for(CBRCase c: cases)
251                    {
252                            Session session = sessionFactory.openSession(); 
253                            Transaction transaction = session.beginTransaction();
254                                    session.save(c.getDescription());
255                            transaction.commit();
256                            session.close();
257    
258                            session = sessionFactory.openSession(); 
259                            transaction = session.beginTransaction();
260                            if(c.getSolution()!= null)
261                                    session.saveOrUpdate(c.getSolution());
262                            transaction.commit();
263                            session.close();
264    
265                            session = sessionFactory.openSession(); 
266                            transaction = session.beginTransaction();
267                            if(c.getJustificationOfSolution() != null)
268                                    session.saveOrUpdate(c.getJustificationOfSolution());
269                            transaction.commit();
270                            session.close();
271    
272                            session = sessionFactory.openSession(); 
273                            transaction = session.beginTransaction();
274                            if(c.getResult() != null)
275                                    session.saveOrUpdate(c.getResult());
276                            transaction.commit();
277                            session.close();
278                    }
279                    
280    
281                    org.apache.commons.logging.LogFactory.getLog(this.getClass()).info(cases.size()+" cases stored into the database.");
282    
283            }
284    }