001/**
002 * Copyright 2005-2016 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 */
016package org.kuali.rice.krms.framework.engine.expression;
017
018import org.kuali.rice.krms.api.KrmsApiServiceLocator;
019import org.kuali.rice.krms.api.engine.expression.ComparisonOperatorService;
020
021/**
022 * Contains utility methods for working with the ComparisonOperatorService
023 */
024public final class ComparisonOperatorServiceUtils {
025
026    // don't allow instances
027    private ComparisonOperatorServiceUtils() {
028        throw new UnsupportedOperationException();
029    }
030
031    /**
032     * <P>checks if the value needs to be coerced from a String to another type, and if so it looks for an
033     * applicable StringCoercionExtension.</p>
034     *
035     * @param value the value of the argument that may or may not need coercion
036     * @param expectedType the name of the type that the function is expecting for the argument
037     * @param comparisonOperatorService the ComparisonOperatorService instance to use (if needed) for finding a StringCoercionExtension
038     * @return the coerced value, or the unchanged value if (1) no coercion needs to be done or (2) an applicable
039     * StringCoercionExtension can't be found.
040     */
041    public static Object coerceIfNeeded(Object value, String expectedType, ComparisonOperatorService comparisonOperatorService) {
042
043        Object result = value;
044
045        if (value instanceof String && !"java.lang.String".equals(expectedType)) {
046            String valueString = value.toString();
047            StringCoercionExtension coercionExtension =
048                    comparisonOperatorService.findStringCoercionExtension(expectedType, valueString);
049            if (coercionExtension != null) {
050                result = coercionExtension.coerce(expectedType, valueString);
051            }
052        }
053
054        return result;
055    }
056}