001package org.unix4j.convert;
002
003import java.util.concurrent.atomic.AtomicInteger;
004import java.util.concurrent.atomic.AtomicLong;
005
006public class IntegerConverters {
007        public static final ValueConverter<Integer> NUMBER_TO_INTEGER = new ValueConverter<Integer>() {
008                @Override
009                public Integer convert(Object value) throws IllegalArgumentException {
010                        if (value instanceof Number) {
011                                return ((Number)value).intValue();
012                        }
013                        return null;
014                }
015        };
016        public static final ValueConverter<Integer> NUMBER_ROUNDED_TO_INTEGER = new ValueConverter<Integer>() {
017                @Override
018                public Integer convert(Object value) throws IllegalArgumentException {
019                        if (value instanceof Long || value instanceof Integer || value instanceof Short || value instanceof Byte || value instanceof AtomicLong || value instanceof AtomicInteger) {
020                                return ((Number)value).intValue();
021                        }
022                        if (value instanceof Number) {
023                                return (int)Math.round(((Number)value).doubleValue());
024                        }
025                        return null;
026                }
027        };
028        public static final ValueConverter<Integer> STRING_TO_INTEGER = new ValueConverter<Integer>() {
029                @Override
030                public Integer convert(Object value) throws IllegalArgumentException {
031                        if (value != null) {
032                                try {
033                                        return Integer.parseInt(value.toString());
034                                } catch (NumberFormatException e) {
035                                        return null;
036                                }
037                        }
038                        return null;
039                }
040        };
041        public static final ValueConverter<Integer> DEFAULT = new CompositeValueConverter<Integer>().add(NUMBER_TO_INTEGER).add(STRING_TO_INTEGER);
042        public static final ValueConverter<Integer> ROUND = new CompositeValueConverter<Integer>().add(NUMBER_ROUNDED_TO_INTEGER).add(STRING_TO_INTEGER);
043}