<commit_before>/*
 * Copyright 2007 The Kuali Foundation.
 * 
 * Licensed under the Educational Community License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.opensource.org/licenses/ecl1.php
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.kuali.module.purap.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.kuali.core.bo.BusinessObject;
import org.kuali.core.document.Document;
import org.kuali.core.util.ObjectUtils;
import org.kuali.module.purap.PurapConstants;

public class PurApObjectUtils {
    private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(PurApObjectUtils.class);

    /**
     * 
     * This method copies based on a class template it does not copy fields in Known Uncopyable Fields
     * Note: this only copies fields actually in the base class, it doesn't copy inherited fields currently
     * @param base the base class
     * @param src the class to copy from
     * @param target the class to copy to
     */
//    public static void populateFromBaseClass(Class base,BusinessObject src,BusinessObject target,Map supplementalUncopyable) {
//        List<String> fieldNames = new ArrayList<String>();
//        Field[] fields = base.getDeclaredFields();
//        for (Field field : fields) {
//            fieldNames.add(field.getName());
//        }
//        for (String fieldName : fieldNames) {
//            if(!PurapConstants.KNOWN_UNCOPYABLE_FIELDS.containsKey(fieldName) && !supplementalUncopyable.containsKey(fieldName)) { 
//                try {
//                    ObjectUtils.setObjectProperty(target, fieldName, ObjectUtils.getPropertyValue(src, fieldName));
//                }
//                catch (Exception e) {
//                    //purposefully skip for now 
//                    //(I wish objectUtils getPropertyValue threw named errors instead of runtime) so I could
//                    //selectively skip
//                    LOG.debug("couldn't set field '"+fieldName+"' due to exception with class name '"+e.getClass().getName()+"'");
//                }
//            }
//        }
//    }
    public static void populateFromBaseClass(Class base,BusinessObject src,BusinessObject target,Map supplementalUncopyable) {
        List<String> fieldNames = new ArrayList<String>();
        Field[] fields = base.getDeclaredFields();
        for (Field field : fields) {
            fieldNames.add(field.getName());
        }
        for (String fieldName : fieldNames) {
            if ( (isProcessableField(base, fieldName, PurapConstants.KNOWN_UNCOPYABLE_FIELDS)) && (isProcessableField(base, fieldName, supplementalUncopyable)) ) {
                attemptCopyOfFieldName(base.getName(), fieldName, src, target);
            }
        }
    }
    
    private static boolean isProcessableField(Class baseClass, String fieldName, Map excludedFieldNames) {
        if (excludedFieldNames.containsKey(fieldName)) {
            Class potentialClassName = (Class) excludedFieldNames.get(fieldName);
            if ( (ObjectUtils.isNull(potentialClassName)) || (potentialClassName.equals(baseClass)) ) {
                return false;
            }
        }
        return true;
    }
    
    private static void attemptCopyOfFieldName(String baseClassName, String fieldName, BusinessObject sourceObject, BusinessObject targetObject) {
        try {
            ObjectUtils.setObjectProperty(targetObject, fieldName, ObjectUtils.getPropertyValue(sourceObject, fieldName));
        }
        catch (Exception e) {
            //purposefully skip for now 
            //(I wish objectUtils getPropertyValue threw named errors instead of runtime) so I could
            //selectively skip
            LOG.debug("couldn't set field '"+fieldName+"' using base class '"+baseClassName+"' due to exception with class name '"+e.getClass().getName()+"'");
        }
    }
    
    /**
     * 
     * This method copies based on a class template it does not copy fields in Known Uncopyable Fields
     * @param base the base class
     * @param src 
     * @param target
     */
    public static void populateFromBaseClass(Class base,BusinessObject src,BusinessObject target) {
        populateFromBaseClass(base,src,target,new HashMap());
    }
    
    /**
     * FIXME: this needs to be fixed!
     * This method is a temporary place holder until I get this done right
     * @param po
     * @param newPO
     */<commit_msg>KULPURAP-1485 - updated purap object utils to allow for po change docs proper saving and routing<commit_after>/*
 * Copyright 2007 The Kuali Foundation.
 * 
 * Licensed under the Educational Community License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.opensource.org/licenses/ecl1.php
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.kuali.module.purap.util;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.kuali.core.bo.BusinessObject;
import org.kuali.core.document.Document;
import org.kuali.core.util.ObjectUtils;
import org.kuali.core.util.TypedArrayList;
import org.kuali.core.web.format.FormatException;
import org.kuali.module.purap.PurapConstants;

public class PurApObjectUtils {
    private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(PurApObjectUtils.class);

    /**
     * 
     * This method copies based on a class template it does not copy fields in Known Uncopyable Fields
     * Note: this only copies fields actually in the base class, it doesn't copy inherited fields currently
     * @param base the base class
     * @param src the class to copy from
     * @param target the class to copy to
     */
//    public static void populateFromBaseClass(Class base,BusinessObject src,BusinessObject target,Map supplementalUncopyable) {
//        List<String> fieldNames = new ArrayList<String>();
//        Field[] fields = base.getDeclaredFields();
//        for (Field field : fields) {
//            fieldNames.add(field.getName());
//        }
//        for (String fieldName : fieldNames) {
//            if(!PurapConstants.KNOWN_UNCOPYABLE_FIELDS.containsKey(fieldName) && !supplementalUncopyable.containsKey(fieldName)) { 
//                try {
//                    ObjectUtils.setObjectProperty(target, fieldName, ObjectUtils.getPropertyValue(src, fieldName));
//                }
//                catch (Exception e) {
//                    //purposefully skip for now 
//                    //(I wish objectUtils getPropertyValue threw named errors instead of runtime) so I could
//                    //selectively skip
//                    LOG.debug("couldn't set field '"+fieldName+"' due to exception with class name '"+e.getClass().getName()+"'");
//                }
//            }
//        }
//    }
    public static void populateFromBaseClass(Class base,BusinessObject src,BusinessObject target,Map supplementalUncopyable) {
        List<String> fieldNames = new ArrayList<String>();
        Field[] fields = base.getDeclaredFields();
        for (Field field : fields) {
            fieldNames.add(field.getName());
        }
        for (String fieldName : fieldNames) {
            if ( (isProcessableField(base, fieldName, PurapConstants.KNOWN_UNCOPYABLE_FIELDS)) && (isProcessableField(base, fieldName, supplementalUncopyable)) ) {
                attemptCopyOfFieldName(base.getName(), fieldName, src, target, supplementalUncopyable);
            }
        }
    }
    
    private static boolean isProcessableField(Class baseClass, String fieldName, Map excludedFieldNames) {
        if (excludedFieldNames.containsKey(fieldName)) {
            Class potentialClassName = (Class) excludedFieldNames.get(fieldName);
            if ( (ObjectUtils.isNull(potentialClassName)) || (potentialClassName.equals(baseClass)) ) {
                return false;
            }
        }
        return true;
    }
    
    private static void attemptCopyOfFieldName(String baseClassName, String fieldName, BusinessObject sourceObject, BusinessObject targetObject, Map supplementalUncopyable) {
        try {
            Object propertyValue = ObjectUtils.getPropertyValue(sourceObject, fieldName);
            if ( (ObjectUtils.isNotNull(propertyValue)) && (Collection.class.isAssignableFrom(propertyValue.getClass())) ) {
                LOG.debug("attempting to copy collection field '"+fieldName+"' using base class '"+baseClassName+"' and property value class '" + propertyValue.getClass() + "'");
                copyCollection(fieldName, targetObject, propertyValue, supplementalUncopyable);
            }
            else {
                String propertyValueClass = (ObjectUtils.isNotNull(propertyValue)) ? propertyValue.getClass().toString() : "(null)";
                LOG.debug("attempting to set field '"+fieldName+"' using base class '"+baseClassName+"' and property value class '" + propertyValueClass + "'");
                ObjectUtils.setObjectProperty(targetObject, fieldName, propertyValue);
            }
        }
        catch (Exception e) {
            //purposefully skip for now 
            //(I wish objectUtils getPropertyValue threw named errors instead of runtime) so I could
            //selectively skip
            LOG.info("couldn't set field '"+fieldName+"' using base class '"+baseClassName+"' due to exception with class name '"+e.getClass().getName()+"'",e);
        }
    }
    
    private static void copyCollection(String fieldName, BusinessObject targetObject, Object propertyValue, Map supplementalUncopyable) throws FormatException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        Collection sourceList = (Collection) propertyValue;
//        LOG.debug("collection will be typed using class '" + propertyValue.getClass() + "'");
        Collection listToSet = null;
//        try {
//            listToSet = new TypedArrayList(propertyValue.getClass());
//        }
//        catch (Exception e) {
//            LOG.info("couldn't set class '"+propertyValue.getClass()+"' on collection... using ArrayList",e);
            listToSet = new ArrayList();
//        }
        for (Iterator iterator = sourceList.iterator(); iterator.hasNext();) {
            Object sourceCollectionObject = iterator.next();
            Object targetCollectionObject = ObjectUtils.createNewObjectFromClass(sourceCollectionObject.getClass());
            LOG.debug("attempting to copy collection member with class '" + sourceCollectionObject.getClass() + "'");
            populateFromBaseClass(sourceCollectionObject.getClass(), (BusinessObject)sourceCollectionObject, (BusinessObject)targetCollectionObject, supplementalUncopyable);
//            Object targetCollectionObject = ObjectUtils.deepCopy((Serializable)sourceCollectionObject);
            listToSet.add(targetCollectionObject);
        }
        ObjectUtils.setObjectProperty(targetObject, fieldName, listToSet);
    }
    
    /**
     * 
     * This method copies based on a class template it does not copy fields in Known Uncopyable Fields
     * @param base the base class
     * @param src 
     * @param target
     */
    public static void populateFromBaseClass(Class base,BusinessObject src,BusinessObject target) {
        populateFromBaseClass(base,src,target,new HashMap());
    }
    
    /**
     * FIXME: this needs to be fixed!
     * This method is a temporary place holder until I get this done right
     * @param po
     * @param newPO
     */
{'fraction_non_alphanumeric': 0.09730419524645079, 'fraction_numerical': 0.0017546658159196043, 'mean_word_length': 2.8333842861510243, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5655971', 'n_tokens_mistral': 3269, 'n_tokens_neox': 3156, 'n_words': 950}