001package es.ucm.fdi.gaia.jcolibri.connector;
002
003import org.apache.logging.log4j.LogManager;
004import java.net.URL;
005import java.util.*;
006
007import javax.xml.parsers.DocumentBuilder; 
008import javax.xml.parsers.DocumentBuilderFactory;
009
010import org.hibernate.Session;
011import org.hibernate.SessionFactory;
012import org.hibernate.Transaction;
013import org.hibernate.cfg.Configuration;
014import org.w3c.dom.Document;
015
016import es.ucm.fdi.gaia.jcolibri.cbrcore.CBRCase;
017import es.ucm.fdi.gaia.jcolibri.cbrcore.CaseBaseFilter;
018import es.ucm.fdi.gaia.jcolibri.cbrcore.CaseComponent;
019import es.ucm.fdi.gaia.jcolibri.cbrcore.Connector;
020import es.ucm.fdi.gaia.jcolibri.exception.AttributeAccessException;
021import es.ucm.fdi.gaia.jcolibri.exception.InitializingException;
022import es.ucm.fdi.gaia.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 3.0
036 *
037 */
038public class DataBaseConnector implements Connector {
039
040        private SessionFactory sessionFactory;
041        private String descriptionClassName;
042        private String solutionClassName;
043        private String justOfSolutionClassName;
044        private String resultClassName;
045        
046        
047        /* (non-Javadoc)
048         * @see jcolibri.cbrcore.Connector#close()
049         */
050        public void close() {}
051
052        /* (non-Javadoc)
053         * @see jcolibri.cbrcore.Connector#deleteCases(java.util.Collection)
054         */
055        public void deleteCases(Collection<CBRCase> cases) {}
056
057        /* (non-Javadoc)
058         * @see jcolibri.cbrcore.Connector#initFromXMLfile(java.io.File)
059         */
060        public void initFromXMLfile(URL file) throws InitializingException {
061                try {
062                        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
063                //factory.setValidating(true);   
064                //factory.setNamespaceAware(true);
065                DocumentBuilder builder = factory.newDocumentBuilder();
066                Document document = builder.parse( file.openStream() );
067                
068                String hcf = document.getElementsByTagName("HibernateConfigFile").item(0).getTextContent();
069                
070                String descriptionMapFile = document.getElementsByTagName("DescriptionMappingFile").item(0).getTextContent();
071                descriptionClassName = document.getElementsByTagName("DescriptionClassName").item(0).getTextContent();
072                
073                Configuration hbconfig = new Configuration();
074                hbconfig.configure(FileIO.findFile(hcf));
075                hbconfig.addURL(FileIO.findFile(descriptionMapFile));
076                
077                try{
078                        String solutionMapFile = document.getElementsByTagName("SolutionMappingFile").item(0).getTextContent();
079                        solutionClassName = document.getElementsByTagName("SolutionClassName").item(0).getTextContent();         
080                        hbconfig.addResource(solutionMapFile);
081                }catch(Exception e)
082                {
083                        LogManager.getLogger(this.getClass()).info("Case does not have solution");
084                }
085                
086                try{
087                        String justOfSolutionMapFile = document.getElementsByTagName("JustificationOfSolutionMappingFile").item(0).getTextContent();
088                        justOfSolutionClassName = document.getElementsByTagName("JustificationOfSolutionClassName").item(0).getTextContent();    
089                        hbconfig.addResource(justOfSolutionMapFile);
090                }catch(Exception e)
091                {
092                        LogManager.getLogger(this.getClass()).info("Case does not have justification of the solution");
093                }
094                
095                try{
096                        String resultMapFile = document.getElementsByTagName("ResultMappingFile").item(0).getTextContent();
097                        resultClassName = document.getElementsByTagName("ResultClassName").item(0).getTextContent();     
098                        hbconfig.addResource(resultMapFile);
099                }catch(Exception e)
100                {
101                        LogManager.getLogger(this.getClass()).info("Case does not have result");
102                }
103                     
104                
105                sessionFactory = hbconfig.buildSessionFactory();
106                                
107                } catch (Throwable ex) {
108                        throw new InitializingException(ex);
109                }
110
111        }
112
113        /* (non-Javadoc)
114         * @see jcolibri.cbrcore.Connector#retrieveAllCases()
115         */
116        public Collection<CBRCase> retrieveAllCases(){
117                
118                List<CBRCase> res = new ArrayList<>();
119
120                try {
121
122                        Session session;
123                        Transaction transaction;
124                                        
125                        List<?> descList;
126                        HashMap<Object, CaseComponent> solList = null;
127                        HashMap<Object, CaseComponent> justSolList = null;
128                        HashMap<Object, CaseComponent> resList = null;
129                        
130                        if(solutionClassName != null)
131                            solList = retrieveComponent(solutionClassName);
132
133                        if(justOfSolutionClassName != null)
134                            justSolList = retrieveComponent(justOfSolutionClassName);
135
136                        if(resultClassName != null)
137                            resList = retrieveComponent(resultClassName);
138
139                        session = sessionFactory.openSession(); 
140                        transaction = session.beginTransaction();
141                        descList = session.createQuery("from "+ descriptionClassName).list();                   
142                        transaction.commit();
143                        session.close();
144
145                        for(Iterator<?> iter = descList.iterator(); iter.hasNext();) {
146                                CBRCase _case = new CBRCase();
147                                CaseComponent desc = (CaseComponent)iter.next();
148                                _case.setDescription(desc);
149                                
150                                if(solutionClassName != null) {
151
152                                        CaseComponent cc = solList.get(desc.getIdAttribute().getValue(desc));
153                                        if(cc != null)
154                                                _case.setSolution(cc);
155
156                                }
157
158                                if(justOfSolutionClassName != null) {
159                                        CaseComponent cc = justSolList.get(desc.getIdAttribute().getValue(desc));
160                                        if(cc != null)
161                                                _case.setJustificationOfSolution(cc);
162                                }
163
164                                if(resultClassName != null) {
165                                        CaseComponent cc = resList.get(desc.getIdAttribute().getValue(desc));
166                                        if(cc != null)
167                                                _case.setResult(cc);
168                                }
169                                                
170                                res.add(_case);
171                                
172                        }
173
174                } catch (Exception e) {
175                        LogManager.getLogger().error(e);
176                }
177
178                LogManager.getLogger().info(res.size() + " cases read from the database.");
179                return res;
180        }
181
182        private HashMap<Object, CaseComponent> retrieveComponent(String className) throws AttributeAccessException {
183        Session session = sessionFactory.openSession();
184        Transaction transaction = session.beginTransaction();
185
186        HashMap<Object, CaseComponent> result = new HashMap<>();
187        List<?> list = session.createQuery("from " + className).list();
188
189        transaction.commit();
190        session.close();
191
192        // TODO - Pasar a Java 8, Streams
193        for(Object obj: list) {
194            CaseComponent cc = (CaseComponent) obj;
195            result.put(cc.getIdAttribute().getValue(cc), cc);
196        }
197
198        return result;
199    }
200
201        /* (non-Javadoc)
202         * @see jcolibri.cbrcore.Connector#retrieveSomeCases(jcolibri.cbrcore.CaseBaseFilter)
203         */
204        public List<CBRCase> retrieveSomeCases(CaseBaseFilter filter) {
205                return null;
206        }
207
208        /* (non-Javadoc)
209         * @see jcolibri.cbrcore.Connector#storeCases(java.util.Collection)
210         */
211        public void storeCases(Collection<CBRCase> cases) {
212
213            for(CBRCase c: cases) {
214                    saveOrUpdateCaseComponent(c.getDescription());
215                    saveOrUpdateCaseComponent(c.getSolution());
216                    saveOrUpdateCaseComponent(c.getJustificationOfSolution());
217                    saveOrUpdateCaseComponent(c.getResult());
218                }
219
220                LogManager.getLogger().info(cases.size() + " cases stored into the database.");
221
222        }
223
224        private void saveOrUpdateCaseComponent(CaseComponent caseComponent) {
225
226        Session session = sessionFactory.openSession();
227        Transaction transaction = session.beginTransaction();
228
229        if(caseComponent != null)
230            session.saveOrUpdate(caseComponent);
231
232        transaction.commit();
233        session.close();
234
235    }
236}