001package es.ucm.fdi.gaia.jcolibri.casebase;
002
003import java.util.ArrayList;
004import java.util.Collection;
005
006import es.ucm.fdi.gaia.jcolibri.cbrcore.CBRCase;
007import es.ucm.fdi.gaia.jcolibri.cbrcore.CBRCaseBase;
008import es.ucm.fdi.gaia.jcolibri.cbrcore.CaseBaseFilter;
009import es.ucm.fdi.gaia.jcolibri.cbrcore.Connector;
010import es.ucm.fdi.gaia.jcolibri.exception.InitializingException;
011
012/**
013 * Cached case base that only persists cases when closing.
014 * learn() and forget() are not synchronized with the persistence until close() is invoked.
015 * <p>
016 * This class presents better performance that LinelCaseBase as only access to the persistence once.
017 * This case base is used for evaluation.
018 * 
019 * @author Juan A. Recio-GarcĂ­a
020 * @see LinealCaseBase
021 */
022public class CachedLinealCaseBase implements CBRCaseBase {
023
024        private Connector connector;
025        private Collection<CBRCase> originalCases;
026        private Collection<CBRCase> workingCases;
027        
028        /**
029         * Closes the case base saving or deleting the cases of the persistence media
030         */
031        public void close() {
032                Collection<CBRCase> casesToRemove = new ArrayList<>(originalCases);
033                casesToRemove.removeAll(workingCases);
034
035                connector.deleteCases(casesToRemove);
036
037                Collection<CBRCase> casesToStore = new ArrayList<>(workingCases);
038                casesToStore.removeAll(originalCases);
039
040                connector.storeCases(casesToStore);
041                connector.close();
042        }
043
044        /**
045         * Forgets cases. It only removes the cases from the storage media when closing.
046         */
047        public void forgetCases(Collection<CBRCase> cases) {
048                workingCases.removeAll(cases);
049        }
050
051        /**
052         * Returns working cases.
053         */
054        public Collection<CBRCase> getCases() {
055                return workingCases;
056        }
057
058        /**
059         * TODO.
060         */
061        public Collection<CBRCase> getCases(CaseBaseFilter filter) {
062                // TODO
063                return null;
064        }
065
066        /**
067         * Initializes the Case Base with the cases read from the given connector.
068         */
069        public void init(Connector connector) throws InitializingException {
070                this.connector = connector;
071                originalCases = this.connector.retrieveAllCases();      
072                workingCases = new java.util.ArrayList<CBRCase>(originalCases);
073        }
074
075        /**
076         * Learns cases that are only saved when closing the Case Base.
077         */
078        public void learnCases(Collection<CBRCase> cases) {
079                workingCases.addAll(cases);
080        }
081
082}