001    /**
002     * Copyright 2005-2013 The Kuali Foundation
003     *
004     * Licensed under the Educational Community License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.opensource.org/licenses/ecl2.php
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    package org.kuali.rice.core.framework.persistence.ojb.conversion;
017    
018    import org.apache.ojb.broker.accesslayer.conversions.FieldConversion;
019    import org.kuali.rice.core.api.util.type.KualiDecimal;
020    
021    import java.math.BigDecimal;
022    
023    /**
024     * 
025     * 
026     */
027    public class OjbDecimalPercentageFieldConversion extends OjbKualiDecimalFieldConversion implements FieldConversion {
028    
029        private static BigDecimal oneHundred = new BigDecimal(100.0000);
030    
031        /**
032         * Convert percentages to decimals for proper storage.
033         * 
034         * @see FieldConversion#javaToSql(Object)
035         */
036        public Object javaToSql(Object source) {
037    
038            // Convert to BigDecimal using existing conversion.
039            source = super.javaToSql(source);
040    
041            // Check for null, and verify object type.
042            // Do conversion if our type is correct (BigDecimal).
043            if (source != null && source instanceof BigDecimal) {
044                BigDecimal converted = (BigDecimal) source;
045                return converted.divide(oneHundred, 4, KualiDecimal.ROUND_BEHAVIOR);
046            }
047            else {
048                return null;
049            }
050        }
051    
052        /**
053         * Convert database decimals to 'visual' percentages for use in our business objects.
054         * 
055         * @see FieldConversion#sqlToJava(Object)
056         */
057        public Object sqlToJava(Object source) {
058    
059            // Check for null, and verify object type.
060            // Do conversion if our type is correct (BigDecimal).
061            if (source != null && source instanceof BigDecimal) {
062                BigDecimal converted = (BigDecimal) source;
063    
064                // Once we have converted, we need to do the super conversion to KualiDecimal.
065                return super.sqlToJava(converted.multiply(oneHundred));
066            }
067            else {
068                return null;
069            }
070        }
071    }