com.tera.common.configuration.converter.FieldConverters.java Source code

Java tutorial

Introduction

Here is the source code for com.tera.common.configuration.converter.FieldConverters.java

Source

/**
 * This file is part of tera-api.
 * 
 * tera-api is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * tera-api is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with tera-api.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.tera.common.configuration.converter;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.NotImplementedException;

import com.tera.common.configuration.exception.FieldTransformException;
import com.tera.common.util.BundleClassLoader;
import com.tera.common.vcontext.service.VirtualContextService;

/**
 * @author ATracer
 */
public enum FieldConverters implements FieldConverterFactory, FieldConverter {

    INTEGER {
        @Override
        public boolean matches(Class<?> clazz) {
            return classEquals(Integer.class, clazz) || classEquals(int.class, clazz);
        }

        @Override
        public Object convert(Field field, String value) {
            return Integer.parseInt(value);
        }
    },

    FLOAT {
        @Override
        public boolean matches(Class<?> clazz) {
            return classEquals(Float.class, clazz);
        }

        @Override
        public Object convert(Field field, String value) {
            return Float.parseFloat(value);
        }
    },

    STRING {
        @Override
        public boolean matches(Class<?> clazz) {
            return classEquals(String.class, clazz);
        }

        @Override
        public Object convert(Field field, String value) {
            return value;
        }
    },

    BOOLEAN {
        @Override
        public boolean matches(Class<?> clazz) {
            return classEquals(Boolean.class, clazz) || classEquals(boolean.class, clazz);
        }

        @Override
        public Object convert(Field field, String value) {
            return Boolean.valueOf(value);
        }
    },

    CLAZZ {
        @Override
        public boolean matches(Class<?> clazz) {
            return classEquals(Class.class, clazz);
        }

        @Override
        public Object convert(Field field, String value) {
            String[] parts = value.split(":");
            if (parts.length > 1) {
                return convert(field, parts[0], parts[1]);
            }
            try {
                ClassLoader cl = field.getClass().getClassLoader();
                if (cl != null) {
                    return Class.forName(value, false, field.getClass().getClassLoader());
                }
                return Class.forName(value);
            } catch (ClassNotFoundException e) {
                throw new FieldTransformException("There is no class with name " + value);
            }
        }

        /**
         * @param field
         * @param value
         * @param bundle
         * @return
         */
        private Object convert(Field field, String value, String bundle) {
            VirtualContextService vcService = VirtualContextService.getDefault();
            BundleClassLoader classLoader = vcService.getClassLoader(bundle);
            try {
                return classLoader.loadClass(value);
            } catch (ClassNotFoundException e) {
                throw new FieldTransformException("There is no class with name" + value + " in bundle " + bundle);
            }
        }
    },

    INETADDRESS {
        @Override
        public boolean matches(Class<?> clazz) {
            return classEquals(InetSocketAddress.class, clazz);
        }

        @Override
        public Object convert(Field field, String value) {
            String[] parts = value.split(":");

            if (parts.length != 2) {
                throw new FieldTransformException("Can't transform property, must be in format \"address:port\"");
            }

            try {
                if ("*".equals(parts[0])) {
                    return new InetSocketAddress(Integer.parseInt(parts[1]));
                }
                InetAddress address = InetAddress.getByName(parts[0]);
                int port = Integer.parseInt(parts[1]);
                return new InetSocketAddress(address, port);
            } catch (Exception e) {
                throw new FieldTransformException(e);
            }
        }
    },

    ENUM {
        @Override
        public boolean matches(Class<?> clazz) {
            return false;
        }

        @Override
        public Object convert(Field field, String value) {
            Class<?> clazz = field.getType();
            Enum<?>[] enumConstants = (Enum[]) clazz.getEnumConstants();
            for (Enum<?> enumValue : enumConstants) {
                if (enumValue.name().equalsIgnoreCase(value)) {
                    return enumValue;
                }
            }
            throw new IllegalArgumentException(
                    "No specified enum value is available: " + clazz.getName() + " " + value);
        }
    },

    LIST {
        @Override
        public boolean matches(Class<?> clazz) {
            return classEquals(List.class, clazz);
        }

        @Override
        public Object convert(Field field, String value) {
            Class<?> genericType = (Class<?>) ((ParameterizedType) field.getGenericType())
                    .getActualTypeArguments()[0];
            FieldConverter converter = getConverterFor(genericType);
            String[] values = value.split(",");
            List<Object> resultList = new ArrayList<Object>();
            for (String v : values) {
                if (!v.isEmpty()) {
                    Object resultValue = converter.convert(field, v);
                    resultList.add(resultValue);
                }
            }
            return resultList;
        }
    },

    WRAPPER {
        @Override
        public boolean matches(Class<?> clazz) {
            return false;
        }

        @Override
        public Object convert(Field field, String value) {
            throw new IllegalAccessError();
        }
    };

    /**
     * @param original
     * @param target
     * @return
     */
    private static boolean classEquals(Class<?> original, Class<?> target) {
        return original == target;
    }

    @Override
    public FieldConverter getConverterFor(Class<?> clazz) {
        for (FieldConverters fConverter : FieldConverters.values()) {
            if (fConverter.matches(clazz)) {
                return fConverter;
            }
        }
        if (clazz.isEnum()) {
            return ENUM;
        }
        throw new NotImplementedException("No implementation available for converting: " + clazz.getName());
    }

}