Example usage for java.lang Byte parseByte

List of usage examples for java.lang Byte parseByte

Introduction

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

Prototype

public static byte parseByte(String s) throws NumberFormatException 

Source Link

Document

Parses the string argument as a signed decimal byte .

Usage

From source file:com.netflix.astyanax.thrift.ThriftUtils.java

public static Object valueForBasicType(Object value, byte type) {
    switch (ThriftTypes.values()[type]) {
    case BYTE:/*from w w  w .j  a v  a  2 s. c  om*/
        return Byte.parseByte((String) value);
    case BOOL:
        return Boolean.parseBoolean((String) value);
    case DOUBLE:
        return Double.parseDouble((String) value);
    case I16:
        return Short.parseShort((String) value);
    case I32:
        return Integer.parseInt((String) value);
    case I64:
        return Long.parseLong((String) value);
    case STRING:
        return value;
    default:
        return null;
    }
}

From source file:com.github.strawberry.redis.RedisLoader.java

private static Option loadFromRedis(JedisPool pool, final Field field, final Redis annotation) {
    return using(pool)._do(new F<Jedis, Option>() {

        @Override/*from   w  w w .  ja  va  2  s.c  om*/
        public Option f(Jedis jedis) {
            Object value = null;

            Class<?> fieldType = field.getType();

            String pattern = annotation.value();
            boolean allowNull = annotation.allowNull();

            Set<String> redisKeys = Sets.newTreeSet(jedis.keys(pattern));
            if (redisKeys.size() == 1) {
                String redisKey = Iterables.getOnlyElement(redisKeys);
                if (fieldType.equals(char[].class)) {
                    value = jedis.get(redisKey).toCharArray();
                } else if (fieldType.equals(Character[].class)) {
                    value = ArrayUtils.toObject(jedis.get(redisKey).toCharArray());
                } else if (fieldType.equals(char.class) || fieldType.equals(Character.class)) {
                    String toConvert = jedis.get(redisKey);
                    if (toConvert.length() == 1) {
                        value = jedis.get(redisKey).charAt(0);
                    } else {
                        throw ConversionException.of(toConvert, redisKey, fieldType);
                    }
                } else if (fieldType.equals(String.class)) {
                    value = jedis.get(redisKey);
                } else if (fieldType.equals(byte[].class)) {
                    value = jedis.get(redisKey.getBytes());
                } else if (fieldType.equals(Byte[].class)) {
                    value = ArrayUtils.toObject(jedis.get(redisKey.getBytes()));
                } else if (fieldType.equals(boolean.class) || fieldType.equals(Boolean.class)) {
                    String toConvert = jedis.get(redisKey);
                    if (BOOLEAN.matcher(toConvert).matches()) {
                        value = TRUE.matcher(toConvert).matches();
                    } else {
                        throw ConversionException.of(toConvert, redisKey, fieldType);
                    }
                } else if (Map.class.isAssignableFrom(fieldType)) {
                    value = mapOf(field, jedis, redisKey);
                } else if (Collection.class.isAssignableFrom(fieldType)) {
                    value = collectionOf(field, jedis, redisKey);
                } else {
                    String toConvert = jedis.get(redisKey);
                    try {
                        if (fieldType.equals(byte.class) || fieldType.equals(Byte.class)) {
                            value = Byte.parseByte(jedis.get(redisKey));
                        } else if (fieldType.equals(short.class) || fieldType.equals(Short.class)) {
                            value = Short.parseShort(toConvert);
                        } else if (fieldType.equals(int.class) || fieldType.equals(Integer.class)) {
                            value = Integer.parseInt(toConvert);
                        } else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) {
                            value = Long.parseLong(toConvert);
                        } else if (fieldType.equals(BigInteger.class)) {
                            value = new BigInteger(toConvert);
                        } else if (fieldType.equals(float.class) || fieldType.equals(Float.class)) {
                            value = Float.parseFloat(toConvert);
                        } else if (fieldType.equals(double.class) || fieldType.equals(Double.class)) {
                            value = Double.parseDouble(toConvert);
                        } else if (fieldType.equals(BigDecimal.class)) {
                            value = new BigDecimal(toConvert);
                        }
                    } catch (NumberFormatException exception) {
                        throw ConversionException.of(exception, toConvert, redisKey, fieldType);
                    }
                }
            } else if (redisKeys.size() > 1) {
                if (Map.class.isAssignableFrom(fieldType)) {
                    value = nestedMapOf(field, jedis, redisKeys);
                } else if (Collection.class.isAssignableFrom(fieldType)) {
                    value = nestedCollectionOf(field, jedis, redisKeys);
                }
            } else {
                if (!allowNull) {
                    value = nonNullValueOf(fieldType);
                }
            }
            return Option.fromNull(value);
        }
    });
}

From source file:com.ibm.bi.dml.runtime.matrix.SortMR.java

/**
 * /*w  w  w.ja v  a 2 s  .  c o m*/
 * @param str
 * @return
 * @throws DMLRuntimeException 
 */
public static MRInstruction parseSortInstruction(String str) throws DMLRuntimeException {
    SortKeys.OperationTypes otype = SortMR.getSortInstructionType(str);
    if (otype != SortKeys.OperationTypes.Indexes)
        return (MRInstruction) UnaryInstruction.parseInstruction(str);
    else {
        InstructionUtils.checkNumFields(str, 4);
        String[] sparts = InstructionUtils.getInstructionParts(str);
        byte in = Byte.parseByte(sparts[1]);
        byte out = Byte.parseByte(sparts[2]);
        return new UnaryInstruction(null, in, out, str);
    }
}

From source file:com.hortonworks.nifi.processors.BulkFetchDistributedMapCache.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();// w  ww . jav a  2 s .  co  m
    if (flowFile == null) {
        return;
    }

    final ComponentLog logger = getLogger();
    final String cacheKey = context.getProperty(PROP_CACHE_ENTRY_IDENTIFIER)
            .evaluateAttributeExpressions(flowFile).getValue();
    if (StringUtils.isBlank(cacheKey)) {
        logger.error("FlowFile {} has no attribute for given Cache Entry Identifier",
                new Object[] { flowFile });
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
        return;
    }
    final DistributedMapCacheClient cache = context.getProperty(PROP_DISTRIBUTED_CACHE_SERVICE)
            .asControllerService(DistributedMapCacheClient.class);
    String selectedEncoding = context.getProperty(PROP_CHARACTER_SET).getValue();
    try {
        logger.info("********** CacheKey: " + cacheKey);
        String[] keys = cacheKey.split(",");
        logger.info("********** KeysArray: " + Arrays.toString(keys));
        List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
        for (String key : keys) {
            logger.info("********** In Loop for key: " + key);
            if (cache.containsKey(key, keySerializer)) {
                Map<String, Object> currentResult = new HashMap<String, Object>();
                String currentResultJson = new String(cache.get(key, keySerializer, valueDeserializer),
                        selectedEncoding);
                logger.info("********** In Loop Current Result: " + currentResultJson);
                currentResult.put(key, new ObjectMapper().readValue(currentResultJson, HashMap.class));
                results.add(currentResult);
            } else {
                logger.info("Could not find an entry in cache for {}; ", new Object[] { flowFile });
            }
        }
        logger.info("********** KeyListMaps: " + results);
        String jsonResult = new ObjectMapper().writeValueAsString(results);
        if (jsonResult.isEmpty()) {
            session.transfer(flowFile, REL_NOT_FOUND);
            logger.info("Could not find any of the entries in cache for {}; routing to not-found",
                    new Object[] { flowFile });
        } else {
            boolean putInAttribute = context.getProperty(PROP_PUT_CACHE_VALUE_IN_ATTRIBUTE).isSet();
            if (putInAttribute) {
                String attributeName = context.getProperty(PROP_PUT_CACHE_VALUE_IN_ATTRIBUTE)
                        .evaluateAttributeExpressions(flowFile).getValue();
                String attributeValue = jsonResult;

                int maxLength = context.getProperty(PROP_PUT_ATTRIBUTE_MAX_LENGTH).asInteger();
                if (maxLength < attributeValue.length()) {
                    attributeValue = attributeValue.substring(0, maxLength);
                }

                flowFile = session.putAttribute(flowFile, attributeName, attributeValue);
            } else {
                flowFile = session.write(flowFile, new OutputStreamCallback() {
                    @Override
                    public void process(OutputStream out) throws IOException {
                        out.write(Byte.parseByte(jsonResult));
                    }
                });
            }

            session.transfer(flowFile, REL_SUCCESS);
            if (putInAttribute) {
                logger.info("Found a cache key of {} and added an attribute to {} with it's value.",
                        new Object[] { cacheKey, flowFile });
            } else {
                logger.info("Found a cache key of {} and replaced the contents of {} with it's value.",
                        new Object[] { cacheKey, flowFile });
            }
        }
    } catch (final IOException e) {
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
        logger.error("Unable to communicate with cache when processing {} due to {}",
                new Object[] { flowFile, e });
    }
}

From source file:org.firesoa.common.util.JavaDataTypeConvertor.java

public static Byte convertToByte(Object object) throws ClassCastException {
    if (object == null)
        return 0;
    if (object instanceof Byte) {
        return (Byte) object;
    }//  w w  w .  j a  v  a 2 s . co  m

    else if (object instanceof String && isNum((String) object)) {
        String s = ((String) object).trim();
        if (s.equals("")) {
            s = "0";
        }
        return Byte.parseByte(s);
    }
    throw new ClassCastException(
            "Can NOT convert from " + object.getClass().toString() + " to java.lang.Integer");
}

From source file:org.jboss.dashboard.factory.PropertyChangeProcessingInstruction.java

protected byte toByte(String parameter) throws Exception {
    return Byte.parseByte(parameter);
}

From source file:org.apache.sqoop.mapreduce.hcat.SqoopHCatExportHelper.java

private Object convertStringTypes(Object val, String javaColType) {
    String valStr = val.toString();
    if (javaColType.equals(BIG_DECIMAL_TYPE)) {
        return new BigDecimal(valStr);
    } else if (javaColType.equals(DATE_TYPE) || javaColType.equals(TIME_TYPE)
            || javaColType.equals(TIMESTAMP_TYPE)) {
        // Oracle expects timestamps for Date also by default based on version
        // Just allow all date types to be assignment compatible
        if (valStr.length() == 10 && valStr.matches("^\\d{4}-\\d{2}-\\d{2}$")) {
            // Date in yyyy-mm-dd format
            Date d = Date.valueOf(valStr);
            if (javaColType.equals(DATE_TYPE)) {
                return d;
            } else if (javaColType.equals(TIME_TYPE)) {
                return new Time(d.getTime());
            } else if (javaColType.equals(TIMESTAMP_TYPE)) {
                return new Timestamp(d.getTime());
            }//from  www  .j a v a 2 s  .c  o m
        } else if (valStr.length() == 8 && valStr.matches("^\\d{2}:\\d{2}:\\d{2}$")) {
            // time in hh:mm:ss
            Time t = Time.valueOf(valStr);
            if (javaColType.equals(DATE_TYPE)) {
                return new Date(t.getTime());
            } else if (javaColType.equals(TIME_TYPE)) {
                return t;
            } else if (javaColType.equals(TIMESTAMP_TYPE)) {
                return new Timestamp(t.getTime());
            }
        } else if (valStr.length() >= 19 && valStr.length() <= 26
                && valStr.matches("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}(.\\d+)?$")) {
            // timestamp in yyyy-mm-dd hh:mm:ss
            Timestamp ts = Timestamp.valueOf(valStr);
            if (javaColType.equals(DATE_TYPE)) {
                return new Date(ts.getTime());
            } else if (javaColType.equals(TIME_TYPE)) {
                return new Time(ts.getTime());
            } else if (javaColType.equals(TIMESTAMP_TYPE)) {
                return ts;
            }
        } else {
            return null;
        }
    } else if (javaColType.equals(STRING_TYPE)) {
        return valStr;
    } else if (javaColType.equals(BOOLEAN_TYPE)) {
        return Boolean.valueOf(valStr);
    } else if (javaColType.equals(BYTE_TYPE)) {
        return Byte.parseByte(valStr);
    } else if (javaColType.equals(SHORT_TYPE)) {
        return Short.parseShort(valStr);
    } else if (javaColType.equals(INTEGER_TYPE)) {
        return Integer.parseInt(valStr);
    } else if (javaColType.equals(LONG_TYPE)) {
        return Long.parseLong(valStr);
    } else if (javaColType.equals(FLOAT_TYPE)) {
        return Float.parseFloat(valStr);
    } else if (javaColType.equals(DOUBLE_TYPE)) {
        return Double.parseDouble(valStr);
    }
    return null;
}

From source file:org.apache.sysml.runtime.matrix.SortMR.java

public static MRInstruction parseSortInstruction(String str) throws DMLRuntimeException {
    SortKeys.OperationTypes otype = SortMR.getSortInstructionType(str);
    if (otype != SortKeys.OperationTypes.Indexes)
        return (MRInstruction) UnaryInstruction.parseInstruction(str);
    else {//from  ww  w.  jav a  2  s .  c  o  m
        InstructionUtils.checkNumFields(str, 4);
        String[] sparts = InstructionUtils.getInstructionParts(str);
        byte in = Byte.parseByte(sparts[1]);
        byte out = Byte.parseByte(sparts[2]);
        return new UnaryInstruction(null, in, out, str);
    }
}

From source file:org.apache.bval.jsr.xml.ValidationMappingParser.java

private Object convertToResultType(Class<?> returnType, String value, String defaultPackage) {
    /**//from   w ww.j ava 2s. c om
     * Class is represented by the fully qualified class name of the class.
     * spec: Note that if the raw string is unqualified,
     * default package is taken into account.
     */
    if (returnType.equals(Class.class)) {
        value = toQualifiedClassName(value, defaultPackage);
    }
    if (Byte.class.equals(returnType) || byte.class.equals(returnType)) { // spec mandates it
        return Byte.parseByte(value);
    }
    if (Short.class.equals(returnType) || short.class.equals(returnType)) {
        return Short.parseShort(value);
    }
    if (Integer.class.equals(returnType) || int.class.equals(returnType)) {
        return Integer.parseInt(value);
    }
    if (Long.class.equals(returnType) || long.class.equals(returnType)) {
        return Long.parseLong(value);
    }
    if (Float.class.equals(returnType) || float.class.equals(returnType)) {
        return Float.parseFloat(value);
    }
    if (Double.class.equals(returnType) || double.class.equals(returnType)) {
        return Double.parseDouble(value);
    }
    if (Boolean.class.equals(returnType) || boolean.class.equals(returnType)) {
        return Boolean.parseBoolean(value);
    }
    if (Character.class.equals(returnType) || char.class.equals(returnType)) {
        if (value.length() > 1) {
            throw new IllegalArgumentException("a char has a length of 1");
        }
        return value.charAt(0);
    }

    /* Converter lookup */
    Converter converter = ConvertUtils.lookup(returnType);
    if (converter == null && returnType.isEnum()) {
        converter = EnumerationConverter.getInstance();
    }

    if (converter == null) {
        return converter;
    }
    return converter.convert(returnType, value);
}

From source file:org.omegat.util.StaticUtils.java

/**
 * Decodes the array of bytes that was stored in a plain text file as a
 * string, back to array of bytes./*  ww w.ja  va  2s .  c om*/
 */
public static byte[] uudecode(String buf) {
    String[] bytes = buf.split("#");
    byte[] res = new byte[bytes.length];
    for (int i = 0; i < bytes.length; i++) {
        try {
            res[i] = Byte.parseByte(bytes[i]);
        } catch (NumberFormatException e) {
            res[i] = 0;
        }
    }
    return res;
}