001/*
002 *  Copyright 2018 Anyware Services
003 *
004 *  Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0
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.ametys.core.model.type;
017
018import java.util.List;
019
020import org.apache.commons.lang3.StringUtils;
021
022import org.ametys.runtime.model.exception.BadItemTypeException;
023
024/**
025 * Abstract class for double element types
026 */
027public abstract class AbstractDoubleElementType extends AbstractElementType<Double>
028{
029    public Double castValue(String value) throws BadItemTypeException
030    {
031        if (StringUtils.isEmpty(value))
032        {
033            return null;
034        }
035        try
036        {
037            return Double.valueOf(value);
038        }
039        catch (NumberFormatException e)
040        {
041            throw new BadItemTypeException("Unable to cast '" + value + "' to a double", e);
042        }
043    }
044    
045    public Object fromJSONForClient(Object json)
046    {
047        if (json == null)
048        {
049            return null;
050        }
051        else if (json instanceof Number)
052        {
053            return ((Number) json).doubleValue();
054        }
055        else if (json instanceof List)
056        {
057            @SuppressWarnings("unchecked")
058            List<Object> jsonList = (List<Object>) json;
059            Double[] result = new Double[jsonList.size()];
060            for (int i = 0; i < jsonList.size(); i++)
061            {
062                Object singleJSON = jsonList.get(i);
063                if (singleJSON instanceof Number)
064                {
065                    result[i] = ((Number) singleJSON).doubleValue();
066                }
067                else
068                {
069                    throw new IllegalArgumentException("Try to convert the non Double JSON object '" + json + "' into a Double");
070                }
071            }
072            return result;
073        }
074        else
075        {
076            throw new IllegalArgumentException("Try to convert the non Double JSON object '" + json + "' into a Double");
077        }
078    }
079    
080    public boolean isSimple()
081    {
082        return true;
083    }
084    
085    @Override
086    public boolean isCompatible(Object value)
087    {
088        return super.isCompatible(value) || value instanceof Float || value instanceof Float[];
089    }
090}