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:adalid.core.programmers.AbstractJavaProgrammer.java

protected String getString(Object object, Class<?> type) {
    if (object == null || type == null) {
        return null;
    }/*from w ww.j av a  2 s. co m*/
    String errmsg = "cannot get \"" + javaLangLess(type) + "\" from \"" + object + "\"";
    String string = getString(object);
    try {
        if (string == null) {
            return null;
        } else if (Boolean.class.isAssignableFrom(type)) {
            return "" + Boolean.valueOf(string);
        } else if (Character.class.isAssignableFrom(type)) {
            return getCharacterString(string);
        } else if (String.class.isAssignableFrom(type)) {
            return string;
        } else if (Byte.class.isAssignableFrom(type)) {
            return "" + Byte.valueOf(string);
        } else if (Short.class.isAssignableFrom(type)) {
            return "" + Short.valueOf(string);
        } else if (Integer.class.isAssignableFrom(type)) {
            return "" + Integer.valueOf(string);
        } else if (Long.class.isAssignableFrom(type)) {
            return "" + Long.valueOf(string);
        } else if (Float.class.isAssignableFrom(type)) {
            return "" + Float.valueOf(string);
        } else if (Double.class.isAssignableFrom(type)) {
            return "" + Double.valueOf(string);
        } else if (BigInteger.class.isAssignableFrom(type)) {
            return "" + new BigInteger(string);
        } else if (BigDecimal.class.isAssignableFrom(type)) {
            return "" + new BigDecimal(string);
        } else if (object instanceof java.util.Date && Date.class.isAssignableFrom(type)) {
            string = TimeUtils.jdbcDateString(object);
            return getString(Date.valueOf(string));
        } else if (object instanceof java.util.Date && Time.class.isAssignableFrom(type)) {
            string = TimeUtils.jdbcTimeString(object);
            return getString(Time.valueOf(string));
        } else if (object instanceof java.util.Date && Timestamp.class.isAssignableFrom(type)) {
            string = TimeUtils.jdbcTimestampString(object);
            return getString(Timestamp.valueOf(string));
        } else {
            return null;
        }
    } catch (IllegalArgumentException ex) {
        //          logger.error(errmsg, ThrowableUtils.getCause(ex));
        logger.error(errmsg);
        return null;
    }
}

From source file:com.healthmarketscience.jackcess.impl.ColumnImpl.java

/**
 * Deserialize a raw byte value for this column into an Object
 * @param data The raw byte value//  w  w  w .  j a va2s.  c  o m
 * @param order Byte order in which the raw value is stored
 * @return The deserialized Object
 * @usage _advanced_method_
 */
public Object read(byte[] data, ByteOrder order) throws IOException {
    ByteBuffer buffer = ByteBuffer.wrap(data).order(order);

    switch (getType()) {
    case BOOLEAN:
        throw new IOException("Tried to read a boolean from data instead of null mask.");
    case BYTE:
        return Byte.valueOf(buffer.get());
    case INT:
        return Short.valueOf(buffer.getShort());
    case LONG:
        return Integer.valueOf(buffer.getInt());
    case DOUBLE:
        return Double.valueOf(buffer.getDouble());
    case FLOAT:
        return Float.valueOf(buffer.getFloat());
    case SHORT_DATE_TIME:
        return readDateValue(buffer);
    case BINARY:
        return data;
    case TEXT:
        return decodeTextValue(data);
    case MONEY:
        return readCurrencyValue(buffer);
    case NUMERIC:
        return readNumericValue(buffer);
    case GUID:
        return readGUIDValue(buffer, order);
    case UNKNOWN_0D:
    case UNKNOWN_11:
        // treat like "binary" data
        return data;
    case COMPLEX_TYPE:
        return new ComplexValueForeignKeyImpl(this, buffer.getInt());
    default:
        throw new IOException("Unrecognized data type: " + _type);
    }
}

From source file:bammerbom.ultimatecore.bukkit.resources.utils.BossbarUtil.java

public Object getSpawnPacket() {
    Class<?> Entity = Util.getCraftClass("Entity");
    Class<?> EntityLiving = Util.getCraftClass("EntityLiving");
    Class<?> EntityEnderDragon = Util.getCraftClass("EntityEnderDragon");
    Object packet = null;/* w w w .  j  a  v  a 2 s .c o m*/
    try {
        this.dragon = EntityEnderDragon.getConstructor(new Class[] { Util.getCraftClass("World") })
                .newInstance(new Object[] { getWorld() });

        Method setLocation = Util.getMethod(EntityEnderDragon, "setLocation",
                new Class[] { Double.TYPE, Double.TYPE, Double.TYPE, Float.TYPE, Float.TYPE });
        setLocation.invoke(this.dragon, new Object[] { Integer.valueOf(getX()), Integer.valueOf(getY()),
                Integer.valueOf(getZ()), Integer.valueOf(getPitch()), Integer.valueOf(getYaw()) });

        Method setInvisible = Util.getMethod(EntityEnderDragon, "setInvisible", new Class[] { Boolean.TYPE });
        setInvisible.invoke(this.dragon, new Object[] { Boolean.valueOf(isVisible()) });

        Method setCustomName = Util.getMethod(EntityEnderDragon, "setCustomName", new Class[] { String.class });
        setCustomName.invoke(this.dragon, new Object[] { this.name });

        Method setHealth = Util.getMethod(EntityEnderDragon, "setHealth", new Class[] { Float.TYPE });
        setHealth.invoke(this.dragon, new Object[] { Float.valueOf(this.health) });

        Field motX = Util.getField(Entity, "motX");
        motX.set(this.dragon, Byte.valueOf(getXvel()));

        Field motY = Util.getField(Entity, "motY");
        motY.set(this.dragon, Byte.valueOf(getYvel()));

        Field motZ = Util.getField(Entity, "motZ");
        motZ.set(this.dragon, Byte.valueOf(getZvel()));

        Method getId = Util.getMethod(EntityEnderDragon, "getId", new Class[0]);
        this.id = ((Number) getId.invoke(this.dragon, new Object[0])).intValue();

        Class<?> PacketPlayOutSpawnEntityLiving = Util.getCraftClass("PacketPlayOutSpawnEntityLiving");

        packet = PacketPlayOutSpawnEntityLiving.getConstructor(new Class[] { EntityLiving })
                .newInstance(new Object[] { this.dragon });
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }

    return packet;
}

From source file:com.kylinolap.rest.service.QueryService.java

/**
 * @param preparedState/*from   www  .  j  a v a2s.com*/
 * @param param
 * @throws SQLException
 */
private void setParam(PreparedStatement preparedState, int index, StateParam param) throws SQLException {
    boolean isNull = (null == param.getValue());

    Class<?> clazz = Object.class;
    try {
        clazz = Class.forName(param.getClassName());
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    Rep rep = Rep.of(clazz);

    switch (rep) {
    case PRIMITIVE_CHAR:
    case CHARACTER:
    case STRING:
        preparedState.setString(index, isNull ? null : String.valueOf(param.getValue()));
        break;
    case PRIMITIVE_INT:
    case INTEGER:
        preparedState.setInt(index, isNull ? null : Integer.valueOf(param.getValue()));
        break;
    case PRIMITIVE_SHORT:
    case SHORT:
        preparedState.setShort(index, isNull ? null : Short.valueOf(param.getValue()));
        break;
    case PRIMITIVE_LONG:
    case LONG:
        preparedState.setLong(index, isNull ? null : Long.valueOf(param.getValue()));
        break;
    case PRIMITIVE_FLOAT:
    case FLOAT:
        preparedState.setFloat(index, isNull ? null : Float.valueOf(param.getValue()));
        break;
    case PRIMITIVE_DOUBLE:
    case DOUBLE:
        preparedState.setDouble(index, isNull ? null : Double.valueOf(param.getValue()));
        break;
    case PRIMITIVE_BOOLEAN:
    case BOOLEAN:
        preparedState.setBoolean(index, isNull ? null : Boolean.parseBoolean(param.getValue()));
        break;
    case PRIMITIVE_BYTE:
    case BYTE:
        preparedState.setByte(index, isNull ? null : Byte.valueOf(param.getValue()));
        break;
    case JAVA_UTIL_DATE:
    case JAVA_SQL_DATE:
        preparedState.setDate(index, isNull ? null : java.sql.Date.valueOf(param.getValue()));
        break;
    case JAVA_SQL_TIME:
        preparedState.setTime(index, isNull ? null : Time.valueOf(param.getValue()));
        break;
    case JAVA_SQL_TIMESTAMP:
        preparedState.setTimestamp(index, isNull ? null : Timestamp.valueOf(param.getValue()));
        break;
    default:
        preparedState.setObject(index, isNull ? null : param.getValue());
    }
}

From source file:org.apache.hadoop.hive.ql.exec.GroupByOperator.java

/**
 * The size of the element at position 'pos' is returned, if possible. If the
 * field is of variable length, STRING, a list of such field names for the
 * field position is maintained, and the size for such positions is then
 * actually calculated at runtime./*ww  w .j av  a  2s .c  o m*/
 *
 * @param pos
 *          the position of the key
 * @param c
 *          the type of the key
 * @param f
 *          the field to be added
 * @return the size of this datatype
 **/
private int getSize(int pos, Class<?> c, Field f) {
    if (c.isPrimitive() || c.isInstance(Boolean.valueOf(true)) || c.isInstance(Byte.valueOf((byte) 0))
            || c.isInstance(Short.valueOf((short) 0)) || c.isInstance(Integer.valueOf(0))
            || c.isInstance(Long.valueOf(0)) || c.isInstance(new Float(0)) || c.isInstance(new Double(0))) {
        return javaSizePrimitiveType;
    }

    if (c.isInstance(new String())) {
        int idx = 0;
        varLenFields v = null;
        for (idx = 0; idx < aggrPositions.size(); idx++) {
            v = aggrPositions.get(idx);
            if (v.getAggrPos() == pos) {
                break;
            }
        }

        if (idx == aggrPositions.size()) {
            v = new varLenFields(pos, new ArrayList<Field>());
            aggrPositions.add(v);
        }

        v.getFields().add(f);
        return javaObjectOverHead;
    }

    return javaSizeUnknownType;
}

From source file:com.ntsync.shared.RequestGenerator.java

private static int readRowContainer(SecretKey key, List<RawContact> serverDirtyList,
        List<ContactGroup> serverGroupList, final byte[] response, final int contEndPos, int startPos,
        byte contType) throws UnsupportedEncodingException {
    int skippedRows = 0;
    String rowId = null;/*from   ww  w  . ja  v  a2 s  .c o  m*/
    Map<Byte, ByteBuffer> values = new HashMap<Byte, ByteBuffer>();
    int pos = startPos;

    while (pos < contEndPos && pos >= 0) {
        byte valueKey = response[pos];
        if (valueKey == ContactConstants.ROWID) {
            boolean ok = addRow(key, serverDirtyList, serverGroupList, contType, rowId, values);
            if (!ok) {
                skippedRows++;
            }
            values.clear();

            // Read RowId
            pos += 1;
            int rowIdLen = SyncDataHelper.readInt(response, pos);
            pos += ROWID_LEN;
            // UTF-8 is default on Android
            rowId = new String(response, pos, rowIdLen, SyncDataHelper.DEFAULT_CHARSET_NAME);
            pos += rowIdLen;
        } else if (valueKey == ContactConstants.SERVERROW_ID || valueKey == ContactConstants.MODIFIED
                || valueKey == ContactConstants.HASH || valueKey == ContactConstants.DELETED) {
            pos += 1;
            int valueLen = SyncDataHelper.readInt(response, pos);
            pos += VALUE_LEN;
            if (pos + valueLen <= contEndPos && valueLen >= 0) {
                values.put(valueKey, ByteBuffer.wrap(response, pos, valueLen));
            } else {
                LOG.warn(INVALID_BUFFER_MSG, pos, valueLen, contEndPos);
            }
            pos += valueLen;
        } else {
            // 1byte key, //16byte iv// //4 len
            pos += 1;

            int valueLen = SyncDataHelper.readInt(response, pos + CryptoHelper.IV_LEN);
            int bufLen = CryptoHelper.PREAMBLE_LEN + valueLen;
            if (pos + bufLen <= contEndPos && valueLen >= 0) {
                values.put(Byte.valueOf((byte) valueKey), ByteBuffer.wrap(response, pos, bufLen));
            } else {
                LOG.warn(INVALID_BUFFER_MSG, pos, valueLen, contEndPos);
            }
            pos += bufLen;
        }
    }

    boolean ok = addRow(key, serverDirtyList, serverGroupList, contType, rowId, values);
    if (!ok) {
        skippedRows++;
    }
    return skippedRows;
}

From source file:bammerbom.ultimatecore.bukkit.configuration.ConfigSection.java

public List<Byte> getByteList(String path) {
    List<?> list = getList(path);

    if (list == null) {
        return new ArrayList<>(0);
    }//from  w  w  w  . j  a  va  2s. c o  m

    List<Byte> result = new ArrayList<>();

    for (Object object : list) {
        if (object instanceof Byte) {
            result.add((Byte) object);
        } else if (object instanceof String) {
            try {
                result.add(Byte.valueOf((String) object));
            } catch (Exception ex) {
            }
        } else if (object instanceof Character) {
            result.add((byte) ((Character) object).charValue());
        } else if (object instanceof Number) {
            result.add(((Number) object).byteValue());
        }
    }

    return result;
}

From source file:org.j2free.admin.ReflectionMarshaller.java

/**
 * //from   w ww. ja  va  2s . c o  m
 * @param entity
 * @param parameterMap
 * @param controller
 * @return
 * @throws MarshallingException
 */
public Object marshallIn(Object entity, Map<String, String[]> parameterMap, Controller controller)
        throws MarshallingException {
    Field field;
    Converter converter;
    Method setter;
    String[] newValues;

    log.debug("Marshalling in instance of " + entity.getClass().getSimpleName());

    boolean error = false, success = false, isEntity = false, isCollection = false;

    Class collectionType;
    Class fieldType;

    for (Map.Entry<Field, Converter> ent : instructions.entrySet()) {

        // reset flags
        error = success = isEntity = isCollection = false;

        field = ent.getKey();
        converter = ent.getValue();

        if (converter.isReadOnly()) {
            log.debug("Skipping read-only field " + field.getName());
            continue;
        }

        newValues = parameterMap.get(field.getName());

        if (newValues == null || newValues.length == 0) {
            log.debug("Skipping field " + field.getName() + ", no new value set.");
            continue;
        }

        isEntity = converter.isEntity();
        isCollection = converter.isCollection();

        fieldType = field.getType();
        collectionType = isCollection ? converter.getType() : null;

        log.debug("Marshalling in field " + field.getName());

        // try to get the original value
        try {
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            if (field.isAccessible()) {
                log.debug(field.getName() + " is accessible");
                if (!isEntity && !isCollection) {

                    log.debug("!isEntity && !isCollection");

                    // if it's an array, it needs special treatment
                    if (fieldType.isArray()) {
                        log.debug(field.getName() + " is an Array");

                        Class arrayType = fieldType.getComponentType();

                        // If we can, just convert with a cast()
                        if (arrayType.isAssignableFrom(String.class)) {
                            log.debug(arrayType.getName() + " is assignable from String.class");

                            Object[] newArray = new Object[newValues.length];
                            for (int i = 0; i < newValues.length; i++) {
                                newArray[i] = arrayType.cast(newValues[i]);
                            }
                            field.set(entity, newArray);

                        } else {

                            if (isInteger(fieldType)) {

                                Integer[] newArray = new Integer[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Integer.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isFloat(fieldType)) {

                                Float[] newArray = new Float[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Float.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isDouble(fieldType)) {

                                Double[] newArray = new Double[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Double.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isShort(fieldType)) {

                                Short[] newArray = new Short[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Short.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isChar(fieldType)) {

                                field.set(entity, ServletUtils.join(newValues, "").toCharArray());

                            } else if (isLong(fieldType)) {

                                Long[] newArray = new Long[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Long.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isBoolean(fieldType)) {

                                Boolean[] newArray = new Boolean[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Boolean.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isByte(fieldType)) {

                                Byte[] newArray = new Byte[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Byte.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else {
                                throw new MarshallingException(
                                        "Don't know how to marshall an array of a non-primitive, and non-assignable type! field = "
                                                + field.getName());
                            }
                        }

                    } else {

                        // Check out if it's assignable via a straight cast,
                        // that could save time
                        if (fieldType.isAssignableFrom(String.class)) {
                            log.debug(fieldType.getName() + " is assignable from String.class");
                            // this might throw an exception, but we're going
                            // to ignore it because there are other ways of
                            // setting the value if this doesn't work.
                            try {
                                field.set(entity, fieldType.cast(newValues[0]));
                                log.debug("Assigned via cast");
                            } catch (Exception e) {
                                log.debug("Error setting field by cast", e);
                            }
                            success = true;
                        }

                        // if it wasn't assignable via a straight cast, try
                        // working around it.
                        if (!success) {
                            if (isInteger(fieldType) && !newValues[0].equals("")) {
                                field.setInt(entity, Integer.valueOf(newValues[0]));
                            } else if (isFloat(fieldType) && !newValues[0].equals("")) {
                                field.setFloat(entity, Float.valueOf(newValues[0]));
                            } else if (isDouble(fieldType) && !newValues[0].equals("")) {
                                field.setDouble(entity, Double.valueOf(newValues[0]));
                            } else if (isShort(fieldType) && !newValues[0].equals("")) {
                                field.setShort(entity, Short.valueOf(newValues[0]));
                            } else if (isChar(fieldType)) {
                                field.setChar(entity, newValues[0].charAt(0));
                            } else if (isLong(fieldType) && !newValues[0].equals("")) {
                                field.setLong(entity, Long.valueOf(newValues[0]));
                            } else if (isBoolean(fieldType) && !newValues[0].equals("")) {
                                field.setBoolean(entity, Boolean.valueOf(newValues[0]));
                            } else if (isByte(fieldType) && !newValues[0].equals("")) {
                                field.setByte(entity, Byte.valueOf(newValues[0]));
                            } else if (isDate(fieldType)) {
                                if (newValues[0].equals("")) {
                                    field.set(entity, null);
                                } else {
                                    try {
                                        field.set(entity, asDate(newValues[0]));
                                    } catch (ParseException pe) {
                                        log.warn("Error parsing date: " + newValues[0], pe);
                                    }
                                }
                            } else if (!newValues[0].equals("")) {
                                log.debug("Not sure how to set " + field.getName() + " of type "
                                        + fieldType.getName() + ", attemping cast.");
                                field.set(entity, fieldType.cast(newValues[0]));
                            } else if (newValues[0].equals("")) {
                                log.debug("Skipping field " + field.getName()
                                        + ", empty string value passed in.");
                            }
                        }
                    }

                } else if (isEntity && !isCollection) {

                    log.debug("isEntity && !isCollection");

                    ReflectionMarshaller innerMarshaller = ReflectionMarshaller.getForClass(fieldType);
                    field.set(entity, controller.proxy(fieldType, innerMarshaller.asIdType(newValues[0])));

                } else if (!isEntity && isCollection) {

                    log.debug("!isEntity && isCollection");

                    throw new MarshallingException("Error, collections of non-entities are not yet supported.");

                } else if (isEntity && isCollection) {

                    log.debug("isEntity && isCollection");

                    // for now, this is going to expect the parameter to be a
                    // comma-delimited string of entity ids
                    String[] idsString = newValues[0].toString().split(",");
                    Collection collection = (Collection) field.get(entity);

                    log.debug("newValues.length = " + newValues.length);
                    log.debug("newValues[0] = " + newValues[0]);
                    log.debug("idsString.length = " + idsString.length);

                    if (collection == null)
                        collection = new LinkedList();

                    collection.clear();

                    if (idsString.length > 0) {

                        ReflectionMarshaller collectionMarshaller = ReflectionMarshaller
                                .getForClass(collectionType);

                        log.debug("CollectionType = " + collectionType.getName());

                        for (String idString : idsString) {
                            if (idString.equals("")) {
                                log.debug("Skipping empty idString");
                                continue;
                            }
                            collection.add(
                                    controller.proxy(collectionType, collectionMarshaller.asIdType(idString)));
                        }

                    }

                    field.set(entity, collection);
                }
            } else {
                error = true;
            }
        } catch (IllegalAccessException iae) {
            log.error("Unable to set " + field.getName() + " directly.", iae);
            error = true;
        } catch (ClassCastException cce) {
            log.error("Error setting " + field.getName() + ".", cce);
            error = true;
        }

        // if we hit an error getting it directly, try via the getter
        if (error) {
            error = false;
            try {
                setter = converter.getSetter();
                if (setter != null) {
                    if (!setter.isAccessible()) {
                        setter.setAccessible(true);
                    }
                    if (setter.isAccessible()) {
                        if (!isEntity && !isCollection) {

                            // if it's an array, it needs special treatment
                            if (fieldType.isArray()) {
                                log.debug(field.getName() + " is an Array");

                                Class arrayType = fieldType.getComponentType();

                                // If we can, just convert with a cast()
                                if (arrayType.isAssignableFrom(String.class)) {
                                    log.debug(arrayType.getName() + " is assignable from String.class");

                                    Object[] newArray = new Object[newValues.length];
                                    for (int i = 0; i < newValues.length; i++) {
                                        newArray[i] = arrayType.cast(newValues[i]);
                                    }
                                    setter.invoke(entity, newArray);

                                } else {

                                    if (isInteger(fieldType)) {

                                        Integer[] newArray = new Integer[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Integer.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else if (isFloat(fieldType)) {

                                        Float[] newArray = new Float[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Float.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else if (isDouble(fieldType)) {

                                        Double[] newArray = new Double[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Double.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else if (isShort(fieldType)) {

                                        Short[] newArray = new Short[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Short.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else if (isChar(fieldType)) {

                                        setter.invoke(entity, ServletUtils.join(newValues, "").toCharArray());

                                    } else if (isLong(fieldType)) {

                                        Long[] newArray = new Long[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Long.valueOf(newValues[i]);
                                        }
                                        field.set(entity, (Object[]) newArray);

                                    } else if (isBoolean(fieldType)) {

                                        Boolean[] newArray = new Boolean[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Boolean.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else if (isByte(fieldType)) {

                                        Byte[] newArray = new Byte[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Byte.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else {
                                        throw new MarshallingException(
                                                "Don't know how to marshall an array of a non-primitive, and non-assignable type! field = "
                                                        + field.getName());
                                    }
                                }

                            } else {
                                // Check out if it's assignable via a straight cast,
                                // that could save time
                                if (fieldType.isAssignableFrom(String.class)) {
                                    log.debug(fieldType.getName() + " is assignable from String.class");
                                    // this might throw an exception, but we're going
                                    // to ignore it because there are other ways of
                                    // setting the value if this doesn't work.
                                    try {
                                        setter.invoke(entity, fieldType.cast(newValues[0]));
                                    } catch (Exception e) {
                                        log.debug("Error setting field by cast", e);
                                    }
                                    success = true;
                                }

                                // if it wasn't assignable via a straight cast, try
                                // working around it.
                                if (!success) {
                                    if (isInteger(fieldType)) {
                                        setter.invoke(entity, Integer.valueOf(newValues[0]));
                                    } else if (isFloat(fieldType)) {
                                        setter.invoke(entity, Float.valueOf(newValues[0]));
                                    } else if (isDouble(fieldType)) {
                                        setter.invoke(entity, Double.valueOf(newValues[0]));
                                    } else if (isShort(fieldType)) {
                                        setter.invoke(entity, Short.valueOf(newValues[0]));
                                    } else if (isChar(fieldType)) {
                                        setter.invoke(entity, newValues[0].charAt(0));
                                    } else if (isLong(fieldType)) {
                                        setter.invoke(entity, Long.valueOf(newValues[0]));
                                    } else if (isBoolean(fieldType)) {
                                        setter.invoke(entity, Boolean.valueOf(newValues[0]));
                                    } else if (isByte(fieldType)) {
                                        setter.invoke(entity, Byte.valueOf(newValues[0]));
                                    } else if (isDate(fieldType)) {
                                        if (newValues[0].equals("")) {
                                            field.set(entity, null);
                                        } else {
                                            try {
                                                setter.invoke(entity, asDate(newValues[0]));
                                            } catch (ParseException pe) {
                                                log.warn("Error parsing date: " + newValues[0], pe);
                                            }
                                        }
                                    } else {
                                        log.debug("Not sure how to set " + field.getName() + " of type "
                                                + fieldType.getName() + ", attemping cast.");
                                        setter.invoke(entity, fieldType.cast(newValues[0]));
                                    }
                                }
                            }

                        } else if (isEntity && !isCollection) {

                            ReflectionMarshaller innerMarshaller = ReflectionMarshaller.getForClass(fieldType);
                            setter.invoke(entity,
                                    controller.proxy(fieldType, innerMarshaller.asIdType(newValues[0])));

                        } else if (!isEntity && isCollection) {

                            throw new MarshallingException(
                                    "Error, collections of non-entities are not yet supported.");

                        } else if (isEntity && isCollection) {
                            // for now, this is going to expect the parameter to be a
                            // comma-delimited string of entity ids
                            String[] idsString = newValues[0].toString().split(",");
                            Collection collection = (Collection) field.get(entity);

                            if (collection == null)
                                collection = new LinkedList();

                            if (idsString.length == 0 && collection.isEmpty())
                                continue;

                            collection.clear();

                            if (idsString.length > 0) {

                                ReflectionMarshaller collectionMarshaller = ReflectionMarshaller
                                        .getForClass(collectionType);

                                for (String idString : idsString) {
                                    if (idString.equals("")) {
                                        log.debug("Skipping empty idString");
                                        continue;
                                    }
                                    collection.add(controller.proxy(collectionType,
                                            collectionMarshaller.asIdType(idString)));
                                }
                            }

                            setter.invoke(entity, collection);
                        }
                    } else {
                        error = true;
                    }
                } else {
                    error = true;
                }
            } catch (IllegalAccessException iae) {
                log.error("Error accessing setter", iae);
                error = true;
            } catch (InvocationTargetException ite) {
                log.error("Error invoking setter", ite);
                error = true;
            }
        }

        if (error) {
            throw new MarshallingException("Unable to marshall in field " + field.getName() + ".");
        }
    }
    return entity;
}

From source file:com.zimbra.common.util.HttpUtil.java

/**
 * The main difference between java.net.URLDecoder.decode()
 * and this method is the handling of "+" sign.  URLDecoder
 * will turn + into ' ' (space), and not suitable for
 * decoding URL used in HTTP request.//from   w  w  w  . j  a  va2  s.  c  o m
 */
public static String urlUnescape(String escaped) {
    // all the encoded byte groups should be converted to
    // string together
    ArrayList<Byte> segment = new ArrayList<Byte>();
    StringBuilder buf = null;
    for (int i = 0; i < escaped.length(); i++) {
        char c = escaped.charAt(i);
        if (c == '%' && i < (escaped.length() - 2)) {
            String bytes = escaped.substring(i + 1, i + 3);
            try {
                // java Byte type is signed with range of -0x80 to 0x7F.
                // it cannot convert segment of encoded UTF-8 string
                // with high bit set.  we'll parse using Integer
                // then cast the result back to signed Byte.
                // e.g. 0xED becomes 237 as Integer, then -19 as Byte
                int b = Integer.parseInt(bytes, 16);
                segment.add(Byte.valueOf((byte) b));
            } catch (NumberFormatException e) {
            }
            if (buf == null) {
                buf = new StringBuilder(escaped.substring(0, i));
            }
            i += 2;
            // append to the buffer if we are at the end of the string,
            // or if this is the last encoded character in the segment.
            if (i + 1 == escaped.length() || escaped.charAt(i + 1) != '%') {
                try {
                    buf.append(new String(Bytes.toArray(segment), "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                }
                segment.clear();
            }
            continue;
        }
        if (buf != null) {
            buf.append(c);
        }
    }
    if (buf != null)
        return buf.toString();
    return escaped;
}

From source file:org.apache.felix.webconsole.internal.compendium.ConfigManager.java

/**
 * @throws NumberFormatException// w ww  .jav  a  2  s . co m
 *             If the value cannot be converted to a number and type
 *             indicates a numeric type
 */
private Object getType(int type, String value) {
    switch (type) {
    case AttributeDefinition.BYTE:
        return Byte.valueOf(value);
    case AttributeDefinition.CHARACTER:
        char c = (value.length() > 0) ? value.charAt(0) : 0;
        return new Character(c);
    case AttributeDefinition.BOOLEAN:
        return Boolean.valueOf(value);
    case AttributeDefinition.LONG:
        return Long.valueOf(value);
    case AttributeDefinition.INTEGER:
        return Integer.valueOf(value);
    case AttributeDefinition.SHORT:
        return Short.valueOf(value);
    case AttributeDefinition.DOUBLE:
        return Double.valueOf(value);
    case AttributeDefinition.FLOAT:
        return Float.valueOf(value);

    default:
        // includes AttributeDefinition.STRING
        return value;
    }
}