Example usage for java.lang Byte valueOf

List of usage examples for java.lang Byte valueOf

Introduction

In this page you can find the example usage for java.lang Byte valueOf.

Prototype

public static Byte valueOf(String s) throws NumberFormatException 

Source Link

Document

Returns a Byte object holding the value given by the specified String .

Usage

From source file:org.ibeans.impl.support.util.Utils.java

/**
 * Gets a byte from a value in a null-safe manner.
 * <p/>//  w  w w  .j a v  a 2 s .c  o m
 *
 * @param answer       the object value
 * @param defaultValue the default to use if null or of incorrect type
 * @return the value as a byte, or the defaultValue
 */
public static byte getByte(final Object answer, byte defaultValue) {
    if (answer == null) {
        return defaultValue;
    } else if (answer instanceof Number) {
        return ((Number) answer).byteValue();
    } else if (answer instanceof String) {
        try {
            return Byte.valueOf((String) answer).byteValue();
        } catch (NumberFormatException e) {
            //handled below
        }
    }
    if (logger.isWarnEnabled()) {
        logger.warn("Value exists but cannot be converted to byte: " + answer + ", returning default value: "
                + defaultValue);
    }
    return defaultValue;
}

From source file:com.swordlord.gozer.datatypeformat.DataTypeHelper.java

/**
 * Return compatible class for typedValue based on untypedValueClass 
 * // w w w.j  av a2 s  .co m
 * @param untypedValueClass
 * @param typedValue
 * @return
 */
public static Object fromDataType(Class<?> untypedValueClass, Object typedValue) {
    Log LOG = LogFactory.getLog(DataTypeHelper.class);

    if (typedValue == null) {
        return null;
    }

    if (untypedValueClass == null) {
        return typedValue;
    }

    if (ClassUtils.isAssignable(typedValue.getClass(), untypedValueClass)) {
        return typedValue;
    }

    String strTypedValue = null;
    boolean isStringTypedValue = typedValue instanceof String;

    Number numTypedValue = null;
    boolean isNumberTypedValue = typedValue instanceof Number;

    Boolean boolTypedValue = null;
    boolean isBooleanTypedValue = typedValue instanceof Boolean;

    Date dateTypedValue = null;
    boolean isDateTypedValue = typedValue instanceof Date;

    if (isStringTypedValue) {
        strTypedValue = (String) typedValue;
    }
    if (isNumberTypedValue) {
        numTypedValue = (Number) typedValue;
    }
    if (isBooleanTypedValue) {
        boolTypedValue = (Boolean) typedValue;
    }
    if (isDateTypedValue) {
        dateTypedValue = (Date) typedValue;
    }

    Object v = null;
    if (String.class.equals(untypedValueClass)) {
        v = ObjectUtils.toString(typedValue);
    } else if (BigDecimal.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = NumberUtils.createBigDecimal(strTypedValue);
        } else if (isNumberTypedValue) {
            v = new BigDecimal(numTypedValue.doubleValue());
        } else if (isBooleanTypedValue) {
            v = new BigDecimal(BooleanUtils.toInteger(boolTypedValue.booleanValue()));
        } else if (isDateTypedValue) {
            v = new BigDecimal(dateTypedValue.getTime());
        }
    } else if (Boolean.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = BooleanUtils.toBooleanObject(strTypedValue);
        } else if (isNumberTypedValue) {
            v = BooleanUtils.toBooleanObject(numTypedValue.intValue());
        } else if (isDateTypedValue) {
            v = BooleanUtils.toBooleanObject((int) dateTypedValue.getTime());
        }
    } else if (Byte.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = Byte.valueOf(strTypedValue);
        } else if (isNumberTypedValue) {
            v = new Byte(numTypedValue.byteValue());
        } else if (isBooleanTypedValue) {
            v = new Byte((byte) BooleanUtils.toInteger(boolTypedValue.booleanValue()));
        } else if (isDateTypedValue) {
            v = new Byte((byte) dateTypedValue.getTime());
        }
    } else if (byte[].class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = strTypedValue.getBytes();
        }
    } else if (Double.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = NumberUtils.createDouble(strTypedValue);
        } else if (isNumberTypedValue) {
            v = new Double(numTypedValue.doubleValue());
        } else if (isBooleanTypedValue) {
            v = new Double(BooleanUtils.toInteger(boolTypedValue.booleanValue()));
        } else if (isDateTypedValue) {
            v = new Double(dateTypedValue.getTime());
        }
    } else if (Float.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = NumberUtils.createFloat(strTypedValue);
        } else if (isNumberTypedValue) {
            v = new Float(numTypedValue.floatValue());
        } else if (isBooleanTypedValue) {
            v = new Float(BooleanUtils.toInteger(boolTypedValue.booleanValue()));
        } else if (isDateTypedValue) {
            v = new Float(dateTypedValue.getTime());
        }
    } else if (Short.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = NumberUtils.createInteger(strTypedValue);
        } else if (isNumberTypedValue) {
            v = new Integer(numTypedValue.intValue());
        } else if (isBooleanTypedValue) {
            v = BooleanUtils.toIntegerObject(boolTypedValue.booleanValue());
        } else if (isDateTypedValue) {
            v = new Integer((int) dateTypedValue.getTime());
        }
    } else if (Integer.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = NumberUtils.createInteger(strTypedValue);
        } else if (isNumberTypedValue) {
            v = new Integer(numTypedValue.intValue());
        } else if (isBooleanTypedValue) {
            v = BooleanUtils.toIntegerObject(boolTypedValue.booleanValue());
        } else if (isDateTypedValue) {
            v = new Integer((int) dateTypedValue.getTime());
        }
    } else if (Long.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = NumberUtils.createLong(strTypedValue);
        } else if (isNumberTypedValue) {
            v = new Long(numTypedValue.longValue());
        } else if (isBooleanTypedValue) {
            v = new Long(BooleanUtils.toInteger(boolTypedValue.booleanValue()));
        } else if (isDateTypedValue) {
            v = new Long(dateTypedValue.getTime());
        }
    } else if (java.sql.Date.class.equals(untypedValueClass)) {
        if (isNumberTypedValue) {
            v = new java.sql.Date(numTypedValue.longValue());
        } else if (isDateTypedValue) {
            v = new java.sql.Date(dateTypedValue.getTime());
        }
    } else if (java.sql.Time.class.equals(untypedValueClass)) {
        if (isNumberTypedValue) {
            v = new java.sql.Time(numTypedValue.longValue());
        } else if (isDateTypedValue) {
            v = new java.sql.Time(dateTypedValue.getTime());
        }
    } else if (java.sql.Timestamp.class.equals(untypedValueClass)) {
        if (isNumberTypedValue) {
            v = new java.sql.Timestamp(numTypedValue.longValue());
        } else if (isDateTypedValue) {
            v = new java.sql.Timestamp(dateTypedValue.getTime());
        }
    } else if (Date.class.equals(untypedValueClass)) {
        if (isNumberTypedValue) {
            v = new Date(numTypedValue.longValue());
        } else if (isStringTypedValue) {
            try {
                v = DateFormat.getDateInstance().parse(strTypedValue);
            } catch (ParseException e) {
                LOG.error("Unable to parse the date : " + strTypedValue);
                LOG.debug(e.getMessage());
            }
        }
    }
    return v;
}

From source file:org.red5.io.mock.Output.java

/** {@inheritDoc} */
public void writeArray(Object array, Serializer serializer) {
    list.add(Byte.valueOf(DataTypes.CORE_ARRAY));
    list.add(array);
}

From source file:org.locationtech.udig.ui.BasicTypeCellEditor.java

private Object convertToType(String value) {
    if (type == Short.class) {
        return Short.valueOf(value);
    } else if (type == String.class) {
        return StringUtils.trimToNull(value);
    } else if (type == Integer.class) {
        return Integer.valueOf(value);
    } else if (type == Byte.class) {
        return Byte.valueOf(value);
    } else if (type == Character.class) {
        return value.charAt(0);
    } else if (type == Long.class) {
        return Long.valueOf(value);
    } else if (type == Double.class) {
        return Double.valueOf(value);
    } else if (type == Float.class) {
        return Float.valueOf(value);
    } else if (type == BigDecimal.class) {
        return new BigDecimal(value);
    } else if (type == BigInteger.class) {
        return new BigInteger(value);
    }//  w w w . jav  a 2  s .  co m
    return null;
}

From source file:com.qumoon.commons.BeanMapper.java

public static <T> T convertProto2Bean(com.google.protobuf.GeneratedMessage message, T descObject,
        Class srcClass) {//from   www. java 2  s  .co m
    for (Field srcField : srcClass.getDeclaredFields()) {
        Descriptors.FieldDescriptor fd = message.getDescriptorForType().findFieldByName(srcField.getName());
        if (null == fd) {
            continue;
        }
        try {
            String fieldStrValue = String.valueOf(message.getField(fd));
            if (fieldStrValue.isEmpty()) {
                continue;
            }
            if (srcField.getType() == BigDecimal.class) {
                PropertyUtils.setProperty(descObject, srcField.getName(), new BigDecimal(fieldStrValue));
            } else {
                if (srcField.getType() == Date.class) {
                    PropertyUtils.setProperty(descObject, srcField.getName(),
                            new Date((Long) (message.getField(fd))));
                } else {
                    if (srcField.getType() == Byte.class) {
                        PropertyUtils.setProperty(descObject, srcField.getName(), Byte.valueOf(fieldStrValue));
                    } else {
                        PropertyUtils.setProperty(descObject, srcField.getName(), message.getField(fd));
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            continue;
        }
    }
    return descObject;
}

From source file:org.eobjects.analyzer.util.convert.StandardTypeConverter.java

@Override
public Object fromString(Class<?> type, String str) {
    if (ReflectionUtils.isString(type)) {
        return str;
    }/* www.  j a  va 2  s  . c o m*/
    if (ReflectionUtils.isBoolean(type)) {
        return Boolean.valueOf(str);
    }
    if (ReflectionUtils.isCharacter(type)) {
        return Character.valueOf(str.charAt(0));
    }
    if (ReflectionUtils.isInteger(type)) {
        return Integer.valueOf(str);
    }
    if (ReflectionUtils.isLong(type)) {
        return Long.valueOf(str);
    }
    if (ReflectionUtils.isByte(type)) {
        return Byte.valueOf(str);
    }
    if (ReflectionUtils.isShort(type)) {
        return Short.valueOf(str);
    }
    if (ReflectionUtils.isDouble(type)) {
        return Double.valueOf(str);
    }
    if (ReflectionUtils.isFloat(type)) {
        return Float.valueOf(str);
    }
    if (ReflectionUtils.is(type, Class.class)) {
        try {
            return Class.forName(str);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("Class not found: " + str, e);
        }
    }
    if (type.isEnum()) {
        try {
            Object[] enumConstants = type.getEnumConstants();

            // first look for enum constant matches
            Method nameMethod = Enum.class.getMethod("name");
            for (Object e : enumConstants) {
                String name = (String) nameMethod.invoke(e);
                if (name.equals(str)) {
                    return e;
                }
            }

            // check for aliased enums
            for (Object e : enumConstants) {
                String name = (String) nameMethod.invoke(e);
                Field field = type.getField(name);
                Alias alias = ReflectionUtils.getAnnotation(field, Alias.class);
                if (alias != null) {
                    String[] aliasValues = alias.value();
                    for (String aliasValue : aliasValues) {
                        if (aliasValue.equals(str)) {
                            return e;
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new IllegalStateException("Unexpected error occurred while examining enum", e);
        }
        throw new IllegalArgumentException("No such enum '" + str + "' in enum class: " + type.getName());
    }
    if (ReflectionUtils.isDate(type)) {
        return toDate(str);
    }
    if (ReflectionUtils.is(type, File.class)) {
        return new File(str.replace('\\', File.separatorChar));
    }
    if (ReflectionUtils.is(type, Calendar.class)) {
        Date date = toDate(str);
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c;
    }
    if (ReflectionUtils.is(type, Pattern.class)) {
        try {
            return Pattern.compile(str);
        } catch (PatternSyntaxException e) {
            throw new IllegalArgumentException("Invalid regular expression syntax in '" + str + "'.", e);
        }
    }
    if (ReflectionUtils.is(type, java.sql.Date.class)) {
        Date date = toDate(str);
        return new java.sql.Date(date.getTime());
    }
    if (ReflectionUtils.isNumber(type)) {
        return ConvertToNumberTransformer.transformValue(str);
    }
    if (ReflectionUtils.is(type, Serializable.class)) {
        logger.warn("fromString(...): No built-in handling of type: {}, using deserialization", type.getName());
        byte[] bytes = (byte[]) parentConverter.fromString(byte[].class, str);
        ChangeAwareObjectInputStream objectInputStream = null;
        try {
            objectInputStream = new ChangeAwareObjectInputStream(new ByteArrayInputStream(bytes));
            objectInputStream.addClassLoader(type.getClassLoader());
            Object obj = objectInputStream.readObject();
            return obj;
        } catch (Exception e) {
            throw new IllegalStateException("Could not deserialize to " + type + ".", e);
        } finally {
            FileHelper.safeClose(objectInputStream);
        }
    }

    throw new IllegalArgumentException("Could not convert to type: " + type.getName());
}

From source file:org.red5.io.mock.Output.java

/** {@inheritDoc} */
public void writeMap(Map<Object, Object> map, Serializer serializer) {
    list.add(Byte.valueOf(DataTypes.CORE_MAP));
    list.add(map);/*from   w  w  w .  j  av  a  2  s  .co m*/
}

From source file:com.p5solutions.core.jpa.orm.ConversionUtilityImpl.java

/**
 * Convert string.//from  w w  w .  j  av  a  2s .com
 * 
 * @param value
 *          the value
 * @param clazz
 *          the clazz
 * @return the object
 */
protected Object convertString(String value, Class<?> clazz) {
    if (ReflectionUtility.isBooleanClass(clazz)) {
        return Boolean.valueOf(value);
    } else if (ReflectionUtility.isShortClass(clazz)) {
        return Short.valueOf(value);
    } else if (ReflectionUtility.isIntegerClass(clazz)) {
        return Integer.valueOf(value);
    } else if (ReflectionUtility.isLongClass(clazz)) {
        return Long.valueOf(value);
    } else if (ReflectionUtility.isFloatClass(clazz)) {
        return Float.valueOf(value);
    } else if (ReflectionUtility.isDoubleClass(clazz)) {
        return Double.valueOf(value);
    } else if (ReflectionUtility.isBigDecimalClass(clazz)) {
        return new BigDecimal(value);
    } else if (ReflectionUtility.isBigIntegerClass(clazz)) {
        return new BigInteger(value);
    } else if (ReflectionUtility.isByteClass(clazz)) {
        return Byte.valueOf(value);
    } else if (ReflectionUtility.isDateOrTimestamp(clazz)) {
        try {
            return DATE_FORMAT.parse(value);
        } catch (ParseException e) {
            logger.error("Unable to parse " + value + " using date formatter " + DATE_FORMAT_STRING);
            return value;
        }
    } else {
        logger.warn("Unable to identify appropriate conversion strategy for value " + value
                + " using class type " + clazz);
    }

    return value;
}

From source file:com.p5solutions.core.utils.NumberUtils.java

/**
 * Parses the number./*from  w  w w.j ava2  s  . c o m*/
 * 
 * @param number
 *          the number
 * @param clazz
 *          the clazz
 * @return the object
 */
@SuppressWarnings("unchecked")
public static <T> T valueOf(String number, Class<?> clazz) {

    // if the string representation of the number is empty or null
    // then return a null, as it cannot be parsed by the <ClassNumber>.valueOf()
    if (Comparison.isEmptyOrNullTrim(number)) {
        return (T) null;
    }

    if (ReflectionUtility.isByteClass(clazz)) {
        return (T) Byte.valueOf(number);
    } else if (ReflectionUtility.isShortClass(clazz)) {
        return (T) Short.valueOf(number);
    } else if (ReflectionUtility.isIntegerClass(clazz)) {
        return (T) Integer.valueOf(number);
    } else if (ReflectionUtility.isLongClass(clazz)) {
        return (T) Long.valueOf(number);
    } else if (ReflectionUtility.isFloatClass(clazz)) {
        return (T) Short.valueOf(number);
    } else if (ReflectionUtility.isDoubleClass(clazz)) {
        return (T) Double.valueOf(number);
    } else if (ReflectionUtility.isBigDecimalClass(clazz)) {
        return (T) BigDecimal.valueOf(Double.valueOf(number));
    }

    return (T) null;
}

From source file:org.rhq.core.domain.server.PersistenceUtility.java

@SuppressWarnings("unchecked")
// used in hibernate.jsp
public static Object cast(String value, Type hibernateType) {
    if (hibernateType instanceof PrimitiveType) {
        Class<?> type = ((PrimitiveType) hibernateType).getPrimitiveClass();
        if (type.equals(Byte.TYPE)) {
            return Byte.valueOf(value);
        } else if (type.equals(Short.TYPE)) {
            return Short.valueOf(value);
        } else if (type.equals(Integer.TYPE)) {
            return Integer.valueOf(value);
        } else if (type.equals(Long.TYPE)) {
            return Long.valueOf(value);
        } else if (type.equals(Float.TYPE)) {
            return Float.valueOf(value);
        } else if (type.equals(Double.TYPE)) {
            return Double.valueOf(value);
        } else if (type.equals(Boolean.TYPE)) {
            return Boolean.valueOf(value);
        }// w  w  w.ja  v  a  2  s .c  om
    } else if (hibernateType instanceof EntityType) {
        String entityName = ((EntityType) hibernateType).getAssociatedEntityName();
        try {
            Class<?> entityClass = Class.forName(entityName);
            Object entity = entityClass.newInstance();

            Field primaryKeyField = entityClass.getDeclaredField("id");
            primaryKeyField.setAccessible(true);
            primaryKeyField.setInt(entity, Integer.valueOf(value));
            return entity;
        } catch (Throwable t) {
            throw new IllegalArgumentException("Type[" + entityName + "] must have PK field named 'id'");
        }
    } else if (hibernateType instanceof CustomType) {
        if (Enum.class.isAssignableFrom(hibernateType.getReturnedClass())) {
            Class<? extends Enum<?>> enumClass = hibernateType.getReturnedClass();
            Enum<?>[] enumValues = enumClass.getEnumConstants();
            try {
                int enumOrdinal = Integer.valueOf(value);
                try {
                    return enumValues[enumOrdinal];
                } catch (ArrayIndexOutOfBoundsException aioobe) {
                    throw new IllegalArgumentException("There is no " + enumClass.getSimpleName()
                            + " enum with ordinal '" + enumOrdinal + "'");
                }
            } catch (NumberFormatException nfe) {
                String ucaseValue = value.toUpperCase();
                for (Enum<?> nextEnum : enumValues) {
                    if (nextEnum.name().toUpperCase().equals(ucaseValue)) {
                        return nextEnum;
                    }
                }
                throw new IllegalArgumentException(
                        "There is no " + enumClass.getSimpleName() + " enum with name '" + value + "'");
            }
        }
    }
    return value;
}