001package es.ucm.fdi.gaia.jcolibri.connector;
002
003import java.io.BufferedReader;
004import java.io.BufferedWriter;
005import java.io.FileWriter;
006import java.io.InputStreamReader;
007import java.net.URL;
008import java.util.ArrayList;
009import java.util.Collection;
010import java.util.Iterator;
011import java.util.LinkedList;
012import java.util.List;
013import java.util.ListIterator;
014import java.util.StringTokenizer;
015
016import javax.xml.parsers.DocumentBuilder;
017import javax.xml.parsers.DocumentBuilderFactory;
018
019import org.apache.logging.log4j.LogManager;
020import org.w3c.dom.Document;
021import org.w3c.dom.Node;
022import org.w3c.dom.NodeList;
023
024import es.ucm.fdi.gaia.jcolibri.cbrcore.Attribute;
025import es.ucm.fdi.gaia.jcolibri.cbrcore.CBRCase;
026import es.ucm.fdi.gaia.jcolibri.cbrcore.CaseBaseFilter;
027import es.ucm.fdi.gaia.jcolibri.cbrcore.CaseComponent;
028import es.ucm.fdi.gaia.jcolibri.cbrcore.Connector;
029import es.ucm.fdi.gaia.jcolibri.connector.plaintextutils.PlainTextTypeConverter;
030import es.ucm.fdi.gaia.jcolibri.exception.AttributeAccessException;
031import es.ucm.fdi.gaia.jcolibri.exception.InitializingException;
032import es.ucm.fdi.gaia.jcolibri.util.FileIO;
033
034/**
035 * <p>
036 * Implements a generic PlainText Connector.
037 * </p>
038 * It manages the persistence of the cases automatically into textual files. Features:
039 * <ul>
040 * <li>By default it only can manage a few data types, although developers can add
041 * their own ones implementing the TypeAdaptor interface.<br>
042 * Supported types and the type extension mechanism is explained in PlainTextTypeConverter.
043 * <li>Only works with one file.
044 * </ul>
045 * <p>
046 * This connector uses the property in the initFromXMLfile() parameter to obtain the
047 * configuration file. This file is a xml that follows the Schema defined in
048 * <a href="PlainTextConnector.xsd">/doc/configfilesSchemas/PlainTextConnector.xsd</a>:<p>
049 * <img src="PlainTextConnectorSchema.jpg">
050 * <p>
051 * This class does not implement any cache mechanims, so cases are read and
052 * written directly. This can be very inefficient in some operations (mainly in
053 * reading)
054 * <p>
055 * Some methods will fail when executing the connector with a case base file inside a jar file.
056 * The retrieve() methods will work properly but the methods that write in the file will fail. 
057 * Extract the file to the file system and run the connector with that location to solve these problems.
058 * <p>
059 * For an example see Test6.
060 * 
061 * @author Juan Antonio Recio GarcĂ­a
062 * @version 2.0
063 * @see PlainTextTypeConverter
064 * @see TypeAdaptor
065 */
066public class PlainTextConnector implements Connector {
067
068        /* Text file path. */
069        protected String PROP_FILEPATH = "";
070
071        /* Columns separator. */
072        protected String PROP_DELIM = "";
073    
074        private Class<? extends CaseComponent> descriptionClass;
075        private Class<? extends CaseComponent> solutionClass;
076        private Class<? extends CaseComponent> justOfSolutionClass;
077        private Class<? extends CaseComponent> resultClass;
078        
079        List<Attribute> descriptionMaps;
080        List<Attribute> solutionMaps;
081        List<Attribute> justOfSolutionMaps;
082        List<Attribute> resultMaps;
083        
084
085        public void initFromXMLfile(URL file) throws InitializingException {
086                try {
087                        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
088                        DocumentBuilder db = dbf.newDocumentBuilder();
089                        Document doc = db.parse(file.openStream());
090                        
091                        /** File containing cases */
092                        
093                        this.PROP_FILEPATH = doc.getElementsByTagName("FilePath").item(0).getTextContent();
094                        
095                        /** Text separator */
096                        
097                        this.PROP_DELIM    = doc.getElementsByTagName("Delimiters").item(0).getTextContent();
098                        
099                        /** classes that compose the case*/
100                        
101                        this.descriptionClass = Class.forName(doc.getElementsByTagName("DescriptionClassName").item(0).getTextContent()).asSubclass(CaseComponent.class);
102                        
103                        try{
104                                this.solutionClass =  Class.forName(doc.getElementsByTagName("SolutionClassName").item(0).getTextContent()).asSubclass(CaseComponent.class);
105                        }catch(Exception e) {}
106                        
107                        try{
108                                this.justOfSolutionClass =  Class.forName(doc.getElementsByTagName("JustificationOfSolutionClassName").item(0).getTextContent()).asSubclass(CaseComponent.class);
109                        }catch(Exception e) {}
110                        
111                        try{
112                                this.resultClass =  Class.forName(doc.getElementsByTagName("ResultClassName").item(0).getTextContent()).asSubclass(CaseComponent.class);
113                        }catch(Exception e) {}
114                        
115                        
116                        /** Mappings */
117                        
118                        this.descriptionMaps = findMaps(doc.getElementsByTagName("DescriptionMappings").item(0), this.descriptionClass);
119                        
120                        if(this.solutionClass != null)
121                                this.solutionMaps =  findMaps(doc.getElementsByTagName("SolutionMappings").item(0), this.solutionClass);
122                        
123                        if(this.justOfSolutionClass != null)
124                                this.justOfSolutionMaps = findMaps(doc.getElementsByTagName("JustificationOfSolutionMappings").item(0), this.justOfSolutionClass);
125                        
126                        if(this.resultClass != null)
127                                this.resultMaps = findMaps(doc.getElementsByTagName("ResultMappings").item(0), this.resultClass);
128                        
129                }catch(Exception e){
130                        throw new InitializingException(e);
131                }
132                
133
134        }
135
136        private List<Attribute> findMaps(Node n, Class<?> _class)
137        {
138                List<Attribute> res = new ArrayList<Attribute>();
139                NodeList childs = n.getChildNodes();
140                for(int i=0; i<childs.getLength(); i++)
141                {
142                        Node c = childs.item(i);
143                        if(c.getNodeName().equals("Map")){
144                                String attributeName = c.getTextContent();
145                                res.add(new Attribute(attributeName, _class));
146                        }
147                }
148                return res;
149        }
150        
151
152        public void close() {
153                //does nothing
154        }
155
156        /**
157         * Stores the cases in the data base. Note that this method does not control
158         * that the case name (== primary key) is repeated, so developers must be
159         * careful with this.
160         * 
161         * @param cases Cases to store.
162         * @throws Exception
163         */
164        public void storeCases(Collection<CBRCase> cases)
165        {
166                try {
167                        BufferedWriter br = null;
168                        br = new BufferedWriter(new FileWriter(FileIO.findFile(this.PROP_FILEPATH).getFile(), true));
169                        //if (br == null) throw new Exception("Error opening file for writing: "+ this.PROP_FILEPATH);
170
171                        char separator = this.PROP_DELIM.charAt(0);
172                        
173                        for (CBRCase _case : cases) {
174                                br.newLine();
175                                StringBuffer line = new StringBuffer();
176                                
177                                CaseComponent description = _case.getDescription();
178                                writeComponent(description, this.descriptionMaps, line, separator, true);
179                                
180                                CaseComponent solution = _case.getSolution();
181                                if(solution!=null)
182                                {
183                                        line.append(separator);
184                                        writeComponent(solution, this.solutionMaps,  line, separator, false);
185                                }
186                                
187                                CaseComponent justOfSolution = _case.getJustificationOfSolution();
188                                if(justOfSolution!=null)
189                                {
190                                        line.append(separator);
191                                        writeComponent(justOfSolution, this.justOfSolutionMaps,  line, separator, false);
192                                }
193                                
194                                CaseComponent result = _case.getResult();
195                                if(result!=null)
196                                {
197                                        line.append(separator);
198                                        writeComponent(result, this.resultMaps, line, separator, false);
199                                }
200
201                                br.write(line.toString());
202                        }
203                        br.close();
204                } catch (Exception e) {
205                        LogManager.getLogger(this.getClass()).error(e);
206                }
207        }
208        
209        private void writeComponent(CaseComponent comp, List<Attribute> maps, StringBuffer line, char separator, boolean includeId)
210        {
211                try {
212                        if(includeId)
213                                line.append(comp.getIdAttribute().getValue(comp));
214                        for(Attribute a: maps)
215                        {
216                                line.append(separator);
217                                line.append(a.getValue(comp));
218                        }
219                } catch (AttributeAccessException e) {
220                        LogManager.getLogger(this.getClass()).error(e);
221                }
222        }
223
224        /**
225         * Deletes cases from the case base. It only uses the case name (primary
226         * key) to remove the row. Note that this method is very inefficient because
227         * it reads all the database, removes the rows in memory, and writes it
228         * again into the text file.
229         * 
230         * @param cases
231         *            Cases to delete
232         */
233        public void deleteCases(Collection<CBRCase> cases){
234                try {
235                        BufferedReader br = null;
236                        br = new BufferedReader( new InputStreamReader(FileIO.findFile(this.PROP_FILEPATH).openStream()));
237                        //if (br == null) throw new Exception("Error opening file for reading: " + this.PROP_FILEPATH);
238
239                        ArrayList<String> lines = new ArrayList<String>();
240                        String line = "";
241                        while ((line = br.readLine()) != null) {
242                                if (line.startsWith("#") || (line.length() == 0)) {
243                                        lines.add(line);
244                                        continue;
245                                }
246
247                                StringTokenizer st = new StringTokenizer(line, this.PROP_DELIM);
248                                String caseId = st.nextToken();
249                                for (Iterator<CBRCase> cIter = cases.iterator(); cIter.hasNext();) {
250                                        CBRCase _case = cIter.next();
251                                        if (!caseId.equals(_case.getID().toString()))
252                                                lines.add(line);
253                                }
254                        }
255                        br.close();
256
257                        BufferedWriter bw = null;
258                        bw = new BufferedWriter(new FileWriter(FileIO.findFile(this.PROP_FILEPATH).getFile(), false));
259                        //if (bw == null) throw new Exception("Error opening file for writing: "+ this.PROP_FILEPATH);
260                        for (ListIterator<String> lIter = lines.listIterator(); lIter.hasNext();) {
261                                line = lIter.next();
262                                bw.write(line);
263                                bw.newLine();
264                        }
265                        bw.close();
266
267                } catch (Exception e) {
268                        LogManager.getLogger(this.getClass()).error(
269                                        "Error deleting cases " + e.getMessage());
270                }
271        }
272
273        /**
274         * Retrieves all cases from the text file. It maps data types using the
275         * PlainTextTypeConverter class.
276         * 
277         * @return Retrieved cases.
278         */
279        public List<CBRCase> retrieveAllCases() {
280                LinkedList<CBRCase> cases = new LinkedList<CBRCase>();
281                try {
282                        BufferedReader br = null;
283                        br = new BufferedReader( new InputStreamReader(FileIO.openFile(this.PROP_FILEPATH)));
284                        //if (br == null) throw new Exception("Error opening file: " + this.PROP_FILEPATH);
285
286                        String line = "";
287                        while ((line = br.readLine()) != null) {
288
289                                if (line.startsWith("#") || (line.length() == 0))
290                                        continue;
291                                StringTokenizer st = new StringTokenizer(line, this.PROP_DELIM);
292                                
293                                CBRCase _case = new CBRCase();
294                                
295                                CaseComponent description = (CaseComponent)this.descriptionClass.newInstance();
296                                fillComponent(description, st, this.descriptionMaps, true);
297                                _case.setDescription(description);
298                                
299                                if(this.solutionClass != null)
300                                {
301                                        CaseComponent solution = (CaseComponent)this.solutionClass.newInstance();
302                                        fillComponent(solution, st, this.solutionMaps, false);
303                                        _case.setSolution(solution);
304                                }
305                                if(this.justOfSolutionClass != null)
306                                {
307                                        CaseComponent justificationOfSolution = (CaseComponent)this.justOfSolutionClass.newInstance();
308                                        fillComponent(justificationOfSolution, st, this.justOfSolutionMaps, false);
309                                        _case.setJustificationOfSolution(justificationOfSolution);
310                                }
311                                if(this.resultClass != null)
312                                {
313                                        CaseComponent result = (CaseComponent)this.resultClass.newInstance();
314                                        fillComponent(result, st, this.resultMaps, false);
315                                        _case.setResult(result);
316                                }
317                                
318                                cases.add(_case);
319                        }
320                        br.close();
321                } catch (Exception e) {
322                        LogManager.getLogger(this.getClass()).error(
323                                        "Error retrieving cases " + e.getMessage());
324                }
325                return cases;
326        }
327
328
329        private void fillComponent(CaseComponent component, StringTokenizer st, List<Attribute> maps, boolean includeId)
330        {
331                try {
332                        Class<?> type;
333                        Object value;
334                        
335                        if(includeId)
336                        {
337                                Attribute idAttribute = component.getIdAttribute();
338                                type = idAttribute.getType();
339                                value = PlainTextTypeConverter.convert(st.nextToken(), type);
340                                idAttribute.setValue(component, value);
341                        }
342                        
343                        for(Attribute at : maps)
344                        {
345                                type = at.getType();
346                                value = PlainTextTypeConverter.convert(st.nextToken(), type);
347                                at.setValue(component, value);
348                        }
349                        
350                } catch (Exception e) {
351                        LogManager.getLogger(this.getClass()).error(
352                                        "Error creating case: " + e.getMessage());
353                }
354        }
355        
356        
357        public List<CBRCase> retrieveSomeCases(CaseBaseFilter filter) {
358                return null;
359        }
360        
361}