001/**
002 * DefineNewIdsMethod.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 * 07/01/2007
008 */
009package es.ucm.fdi.gaia.jcolibri.method.revise;
010
011import java.util.HashMap;
012
013import org.apache.log4j.LogManager;
014
015import es.ucm.fdi.gaia.jcolibri.cbrcore.Attribute;
016import es.ucm.fdi.gaia.jcolibri.cbrcore.CBRCase;
017import es.ucm.fdi.gaia.jcolibri.cbrcore.CaseComponent;
018import es.ucm.fdi.gaia.jcolibri.exception.ExecutionException;
019
020
021
022/**
023 * Defines new ids for the case components of a case. This way it can be stored in the persistence media without overwriting an existing case.
024 * @author Juan A. Recio-Garcia
025 *
026 */
027public class DefineNewIdsMethod {
028
029        /**
030         * Changes the values of the ID attributes of a case with new ones. 
031         * This method traverses the CaseComponent tree of a case modifing the values of the ids attributes with new objects.
032         * @param _case to modify the ids 
033         * @param componentsKeys stores the new values of the IDs attributes
034         * @throws ExecutionException
035         */
036        public static void defineNewIdsMethod(CBRCase _case, HashMap<Attribute, Object> componentsKeys) throws ExecutionException
037        {
038                        defineNewIds(_case.getDescription(), componentsKeys);
039                        defineNewIds(_case.getSolution(), componentsKeys);
040                        defineNewIds(_case.getJustificationOfSolution(), componentsKeys);
041                        defineNewIds(_case.getResult(), componentsKeys);
042        }
043        
044        private static void defineNewIds(CaseComponent cc, HashMap<Attribute, Object> componentsKeys) throws ExecutionException
045        {
046                if(cc == null)
047                        return;
048                Attribute keyAtt = cc.getIdAttribute();
049                Object newkeyvalue = componentsKeys.get(keyAtt);
050                
051                try {
052                        if(newkeyvalue != null)
053                                keyAtt.setValue(cc, newkeyvalue);
054
055                        for(java.lang.reflect.Field f: cc.getClass().getDeclaredFields())
056                        {
057                                Attribute at = new Attribute(f);
058                                Object o = at.getValue(cc);
059                                if(o instanceof CaseComponent)
060                                        defineNewIds((CaseComponent)o, componentsKeys);
061                        }
062                } catch (Exception e) {
063                        LogManager.getLogger(DefineNewIdsMethod.class).error(e);
064                } 
065                
066        }
067}