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:com.pandich.dropwizard.curator.refresh.Refresher.java

protected final Object getValue(final A element, final NodeValue nodeValue) {
    final String rawValue = nodeValue.getValue();

    final Class<?> clazz = getType(element);

    final CuratorMapper<?> mapper = this.mappers.get(clazz);
    if (mapper != null) {
        return mapper.readValueFroMString(rawValue);
    }/*ww w. ja  va2s. c  om*/

    if (isAssignable(clazz, String.class)) {
        return rawValue;
    }

    if (isAssignable(clazz, Boolean.class)) {
        return Boolean.valueOf(rawValue);
    }

    if (isAssignable(clazz, Character.class)) {
        return CharUtils.toChar(rawValue);
    }

    if (isAssignable(clazz, Byte.class)) {
        return Byte.valueOf(rawValue);
    }

    if (isAssignable(clazz, Short.class)) {
        return Short.valueOf(rawValue);
    }

    if (isAssignable(clazz, Integer.class)) {
        return Integer.valueOf(rawValue);
    }

    if (isAssignable(clazz, Long.class)) {
        return Long.valueOf(rawValue);
    }

    if (isAssignable(clazz, Float.class)) {
        return Float.valueOf(rawValue);
    }

    if (isAssignable(clazz, Double.class)) {
        return Double.valueOf(rawValue);
    }

    if (isAssignable(clazz, BigInteger.class)) {
        return new BigInteger(rawValue);
    }

    if (isAssignable(clazz, BigDecimal.class)) {
        return new BigDecimal(rawValue);
    }

    try {
        return objectMapper.readValue(rawValue, clazz);
    } catch (IOException e) {
        throw new RuntimeException("type '" + clazz.getName() + "' is not supported", e);
    }
}

From source file:com.facebook.presto.accumulo.model.Row.java

/**
 * Converts the given String into a Java object based on the given Presto type
 *
 * @param str String to convert//from   w ww .jav  a2 s .c o m
 * @param type Presto Type
 * @return Java object
 * @throws PrestoException If the type is not supported by this function
 */
public static Object valueFromString(String str, Type type) {
    if (str == null || str.isEmpty()) {
        return null;
    } else if (Types.isArrayType(type)) {
        Type elementType = Types.getElementType(type);
        ImmutableList.Builder<Object> listBuilder = ImmutableList.builder();
        for (String element : Splitter.on(',').split(str)) {
            listBuilder.add(valueFromString(element, elementType));
        }
        return AccumuloRowSerializer.getBlockFromArray(elementType, listBuilder.build());
    } else if (Types.isMapType(type)) {
        Type keyType = Types.getKeyType(type);
        Type valueType = Types.getValueType(type);
        ImmutableMap.Builder<Object, Object> mapBuilder = ImmutableMap.builder();
        for (String element : Splitter.on(',').split(str)) {
            ImmutableList.Builder<String> builder = ImmutableList.builder();
            List<String> keyValue = builder.addAll(Splitter.on("->").split(element)).build();
            checkArgument(keyValue.size() == 2,
                    format("Map element %s has %d entries, not 2", element, keyValue.size()));

            mapBuilder.put(valueFromString(keyValue.get(0), keyType),
                    valueFromString(keyValue.get(1), valueType));
        }
        return AccumuloRowSerializer.getBlockFromMap(type, mapBuilder.build());
    } else if (type.equals(BIGINT)) {
        return Long.parseLong(str);
    } else if (type.equals(BOOLEAN)) {
        return Boolean.parseBoolean(str);
    } else if (type.equals(DATE)) {
        return new Date(DATE_PARSER.parseDateTime(str).getMillis());
    } else if (type.equals(DOUBLE)) {
        return Double.parseDouble(str);
    } else if (type.equals(INTEGER)) {
        return Integer.parseInt(str);
    } else if (type.equals(REAL)) {
        return Float.parseFloat(str);
    } else if (type.equals(SMALLINT)) {
        return Short.parseShort(str);
    } else if (type.equals(TIME)) {
        return new Time(TIME_PARSER.parseDateTime(str).getMillis());
    } else if (type.equals(TIMESTAMP)) {
        return new Timestamp(TIMESTAMP_PARSER.parseDateTime(str).getMillis());
    } else if (type.equals(TINYINT)) {
        return Byte.valueOf(str);
    } else if (type.equals(VARBINARY)) {
        return str.getBytes(UTF_8);
    } else if (type instanceof VarcharType) {
        return str;
    } else {
        throw new PrestoException(NOT_SUPPORTED, "Unsupported type " + type);
    }
}

From source file:com.eventsourcing.postgresql.PostgreSQLJournalTest.java

@Test
@SneakyThrows/*  w ww .j  a  v  a  2 s  .c  om*/
public void serializationNull() {
    HybridTimestamp timestamp = new HybridTimestamp(timeProvider);
    timestamp.update();

    Journal.Transaction tx = journal.beginTransaction();
    SerializationEvent event = SerializationEvent.builder().test(TestClass.builder().build()).build();
    event = (SerializationEvent) journal.journal(tx, event);
    tx.rollback();

    TestClass test = event.getTest();

    assertEquals(test.pByte, 0);
    assertEquals(test.oByte, Byte.valueOf((byte) 0));

    assertEquals(test.pByteArr.length, 0);
    assertEquals(test.oByteArr.length, 0);

    assertEquals(test.pShort, 0);
    assertEquals(test.oShort, Short.valueOf((short) 0));

    assertEquals(test.pInt, 0);
    assertEquals(test.oInt, Integer.valueOf(0));

    assertEquals(test.pLong, 0);
    assertEquals(test.oLong, Long.valueOf(0));

    assertTrue(test.pFloat == 0.0);
    assertEquals(test.oFloat, Float.valueOf((float) 0.0));

    assertEquals(test.pDouble, 0.0);
    assertEquals(test.oDouble, Double.valueOf(0.0));

    assertEquals(test.pBoolean, false);
    assertEquals(test.oBoolean, Boolean.FALSE);

    assertEquals(test.str, "");

    assertEquals(test.uuid, new UUID(0, 0));

    assertEquals(test.e, TestClass.E.A);

    assertNotNull(test.value);
    assertEquals(test.value.value, "");

    assertNotNull(test.value1);
    assertTrue(test.value1.value().isEmpty());

    assertNotNull(test.list);
    assertEquals(test.list.size(), 0);

    assertNotNull(test.map);
    assertEquals(test.map.size(), 0);

    assertNotNull(test.optional);
    assertFalse(test.optional.isPresent());

    assertNotNull(test.bigDecimal);
    assertEquals(test.bigDecimal, BigDecimal.ZERO);

    assertNotNull(test.bigInteger);
    assertEquals(test.bigInteger, BigInteger.ZERO);

    assertNotNull(test.date);
    assertEquals(test.date, new Date(0));

}

From source file:com.ebay.erl.mobius.core.mapred.DefaultMobiusReducer.java

@Override
public void configure(JobConf conf) {
    super.configure(conf);
    this.conf = conf;

    ///////////////////////////////////////////
    // setup the criteria to be applied in the
    // final projections
    ///////////////////////////////////////////
    if (this.conf.get(ConfigureConstants.PERSISTANT_CRITERIA, null) != null) {
        try {//ww w.j a va 2 s  .  c om
            this._persistantCriteria = (TupleCriterion) SerializableUtil
                    .deserializeFromBase64(this.conf.get(ConfigureConstants.PERSISTANT_CRITERIA), this.conf);
        } catch (IOException e) {
            throw new IllegalArgumentException("Cannot deserialize " + ConfigureConstants.PERSISTANT_CRITERIA
                    + " from [" + this.conf.get(ConfigureConstants.PERSISTANT_CRITERIA) + "]", e);
        }
    }

    ////////////////////////////////////////
    // setup <code>_allDatasetIDs</code>
    ////////////////////////////////////////
    String[] allDSIDs = this.conf.getStrings(ConfigureConstants.ALL_DATASET_IDS, Util.ZERO_SIZE_STRING_ARRAY);
    this._allDatasetIDs = new Byte[allDSIDs.length];
    for (int i = 0; i < allDSIDs.length; i++) {
        this._allDatasetIDs[i] = Byte.valueOf(allDSIDs[i]);
    }
    if (this._allDatasetIDs.length == 0)
        throw new IllegalStateException(ConfigureConstants.ALL_DATASET_IDS + " is not set.");

    ////////////////////////////////////////
    // setup <code>_lastDatasetID</code>
    ////////////////////////////////////////
    this._lastDatasetID = this._allDatasetIDs[this._allDatasetIDs.length - 1];

    this._allButNotLastDatasetIDs = new Byte[this._allDatasetIDs.length - 1];
    for (int i = 0; i < this._allDatasetIDs.length - 1; i++)
        this._allButNotLastDatasetIDs[i] = this._allDatasetIDs[i];

    ///////////////////////////////////////
    // setup <code>_projections</code>
    //////////////////////////////////////
    try {
        this._projections = (Projectable[]) SerializableUtil
                .deserializeFromBase64(this.conf.get(ConfigureConstants.PROJECTION_COLUMNS), this.conf);
        List<String> outptuColumnNames = new ArrayList<String>();
        for (Projectable p : this._projections) {
            p.setCalledByCombiner(false);
            // save the output columns in user specified order
            // so that the tuples in the final projections
            // can emit the columns in user expected ordering.
            for (String name : p.getOutputSchema())
                outptuColumnNames.add(name);
        }
        this.outputColumnNames = outptuColumnNames.toArray(new String[outptuColumnNames.size()]);
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }

    // use then in final cross-product.

    for (Projectable func : this._projections) {
        if (func.requireDataFromMultiDatasets()) {
            // there is at least one projectable function require columns
            // from different datasets, these functions require cross-product
            // the values from different datasets to compute their values,
            // we need to set this flag to true so later we will do the 
            // cross product.
            requirePreCrossProduct = true;

            if (func instanceof GroupFunction) {
                if (this.multiDatasetGroupFunction == null)
                    this.multiDatasetGroupFunction = new LinkedList<GroupFunction>();
                this.multiDatasetGroupFunction.add((GroupFunction) func);
            } else if (func instanceof ExtendFunction) {
                if (this.multiDatasetExtendFunction == null)
                    this.multiDatasetExtendFunction = new LinkedList<ExtendFunction>();
                this.multiDatasetExtendFunction.add((ExtendFunction) func);
            } else {
                throw new IllegalArgumentException(func.getClass().getCanonicalName()
                        + " is not a sub-class of " + GroupFunction.class.getCanonicalName() + " nor, "
                        + ExtendFunction.class.getCanonicalName());
            }
        } else {
            // projectable functions that require columns from one dataset only.

            boolean onlyUseGroupKey = true;

            Byte datasetID = func.getParticipatedDataset().toArray(new Dataset[0])[0].getID();
            if (func instanceof GroupFunction) {
                List<GroupFunction> funcs = null;
                if ((funcs = this.singleDatasetGroupFunction.get(datasetID)) == null) {
                    funcs = new LinkedList<GroupFunction>();
                    this.singleDatasetGroupFunction.put(datasetID, funcs);
                }
                funcs.add((GroupFunction) func);
            } else if (func instanceof ExtendFunction) {
                List<ExtendFunction> funcs = null;
                if ((funcs = this.singleDatasetExtendFunction.get(datasetID)) == null) {
                    funcs = new LinkedList<ExtendFunction>();
                    this.singleDatasetExtendFunction.put(datasetID, funcs);
                }
                funcs.add((ExtendFunction) func);
                if (!func.useGroupKeyOnly())
                    onlyUseGroupKey = false;
            } else {
                throw new IllegalArgumentException(func.getClass().getCanonicalName()
                        + " is not a sub-class of " + GroupFunction.class.getCanonicalName() + " nor, "
                        + ExtendFunction.class.getCanonicalName());
            }

            this.onlyHasGroupKeyExtendFunctions.put(datasetID, onlyUseGroupKey);
        }
    }

    this.isOuterJoin = this.conf.getBoolean(ConfigureConstants.IS_OUTER_JOIN, false);

    ////////////////////////////////////////
    // setup <code>nullReplacement</code>
    ////////////////////////////////////////
    try {
        if (this.conf.get(ConfigureConstants.NULL_REPLACEMENT, null) != null) {

            byte[] binary = Base64
                    .decodeBase64(this.conf.get(ConfigureConstants.NULL_REPLACEMENT).getBytes("UTF-8"));
            byte type = (byte) this.conf.getInt(ConfigureConstants.NULL_REPLACEMENT_TYPE, -1);

            ByteArrayInputStream buffer = new ByteArrayInputStream(binary);
            DataInputStream input = new DataInputStream(buffer);

            List<Object> temp = new LinkedList<Object>();
            ReadFieldImpl reader = new ReadFieldImpl(temp, input, this.conf);
            reader.handle(type);

            this.nullReplacement = temp.remove(0);
        }
    } catch (IOException e) {
        throw new RuntimeException("Cannot deserialize null_replacement from:" + "["
                + this.conf.get(ConfigureConstants.NULL_REPLACEMENT) + "]", e);
    }

}

From source file:candr.yoclip.option.OptionField.java

protected void setByteOption(final T bean, final String value) {

    final Byte byteValue = StringUtils.isEmpty(value) ? 0 : Byte.valueOf(value);
    set(bean, new Value<T>() {

        public void set(final T bean, final Field field) throws IllegalAccessException {

            field.set(bean, byteValue);//from   www. jav a2s  .  co m
        }
    });
}

From source file:controller.ViewPackageController.java

@RequestMapping(value = "/createOrder", method = RequestMethod.GET)
public String createOrder(HttpServletRequest req, ModelMap mm, Authentication authen) {
    try {/*from w w  w. ja v a  2s. com*/
        LinkedHashMap<OderDetail, Requirement> orderSession = null;
        orderSession = (LinkedHashMap<OderDetail, Requirement>) req.getSession().getAttribute("orderSession");
        if (orderSession == null) {
            mm.put("msg", "No Package choosed");
            return "createOrder";
        } else {
            Set<OderDetail> listOrderDetail = new HashSet<>();
            Set<Requirement> listRequirement = new HashSet<>();
            listOrderDetail = orderSession.keySet();
            for (Requirement rq : orderSession.values()) {
                if (rq != null) {
                    listRequirement.add(rq);
                }
            }
            Customer customer = cusModel.find(authen.getName(), "username", false).get(0);
            customer.setRequirements(listRequirement);
            Calendar c = Calendar.getInstance();
            c.add(Calendar.MONTH, 1);
            Order order = null;
            int orderID = orderModel.getOrderIDByCustomerNonActive(customer.getCustomerId());
            if (orderID == 0) {
                order = new Order(customer, new Date(), c.getTime(), Byte.valueOf("0"), null);
                orderModel.addOrUpdate(order);
            } else {
                order = orderModel.getByID(orderID);
            }
            Set<OderDetail> listDetailTmp = order.getOderDetails();
            for (OderDetail od : listOrderDetail) {
                od.setId(new OderDetailId(order.getOderId(), od.getPackages().getPackageId()));
                for (OderDetail tmp : listDetailTmp) {
                    if (od.getPackages().getPackageId() == tmp.getPackages().getPackageId()) {
                        od.setQuantity(od.getQuantity() + 1);
                        break;
                    }
                }
            }
            order.setOderDetails(listOrderDetail);

            orderModel.addOrUpdate(order);
            cusModel.addOrUpdate(customer);

            req.getSession().setAttribute("orderSession", null);
            mm.put("msg", "Order Created");
        }
    } catch (Exception ex) {
        mm.put("msg", ex.getMessage());
    }
    return "createOrder";
}

From source file:RealFunctionValidation.java

public static Object readAndWritePrimitiveValue(final DataInputStream in, final DataOutputStream out,
        final Class<?> type) throws IOException {

    if (!type.isPrimitive()) {
        throw new IllegalArgumentException("type must be primitive");
    }/*from  w  w  w  . j ava2 s.  com*/
    if (type.equals(Boolean.TYPE)) {
        final boolean x = in.readBoolean();
        out.writeBoolean(x);
        return Boolean.valueOf(x);
    } else if (type.equals(Byte.TYPE)) {
        final byte x = in.readByte();
        out.writeByte(x);
        return Byte.valueOf(x);
    } else if (type.equals(Character.TYPE)) {
        final char x = in.readChar();
        out.writeChar(x);
        return Character.valueOf(x);
    } else if (type.equals(Double.TYPE)) {
        final double x = in.readDouble();
        out.writeDouble(x);
        return Double.valueOf(x);
    } else if (type.equals(Float.TYPE)) {
        final float x = in.readFloat();
        out.writeFloat(x);
        return Float.valueOf(x);
    } else if (type.equals(Integer.TYPE)) {
        final int x = in.readInt();
        out.writeInt(x);
        return Integer.valueOf(x);
    } else if (type.equals(Long.TYPE)) {
        final long x = in.readLong();
        out.writeLong(x);
        return Long.valueOf(x);
    } else if (type.equals(Short.TYPE)) {
        final short x = in.readShort();
        out.writeShort(x);
        return Short.valueOf(x);
    } else {
        // This should never occur.
        throw new IllegalStateException();
    }
}

From source file:candr.yoclip.option.OptionSetter.java

protected void setByteOption(final T bean, final String value) {

    final Byte byteValue = StringUtils.isEmpty(value) ? 0 : Byte.valueOf(value);
    set(bean, new Value<T>() {

        public void set(final T bean, final Method setter)
                throws InvocationTargetException, IllegalAccessException {

            setter.invoke(bean, byteValue);
        }/*from  w  w w. j  a  v a2 s.co m*/
    });
}

From source file:org.droidparts.reflect.util.TypeHelper.java

public static Object parseValue(Class<?> valCls, String valStr) throws IllegalArgumentException {
    if (isByte(valCls)) {
        return Byte.valueOf(valStr);
    } else if (isShort(valCls)) {
        return Short.valueOf(valStr);
    } else if (isInteger(valCls)) {
        return Integer.valueOf(valStr);
    } else if (isLong(valCls)) {
        return Long.valueOf(valStr);
    } else if (isFloat(valCls)) {
        if (valStr.equals("-")) {
            return Float.valueOf("0");
        } else {//from w ww. j  a  va  2 s . c o  m
            return Float.valueOf(valStr);
        }

    } else if (isDouble(valCls)) {
        return Double.valueOf(valStr);
    } else if (isBoolean(valCls)) {
        return Boolean.valueOf(valStr);
    } else if (isCharacter(valCls)) {
        return Character.valueOf((valStr.length() == 0) ? ' ' : valStr.charAt(0));
    } else if (isString(valCls)) {
        return valStr;
    } else if (isEnum(valCls)) {
        return instantiateEnum(valCls, valStr);
    } else if (isUUID(valCls)) {
        return UUID.fromString(valStr);
    } else if (isDate(valCls)) {
        // fIX: date fixed wort app

        Date dateObj = null;
        try {
            dateObj = SimpleDateFormatFactory.getInstance().getFormatter().parse(String.valueOf(valStr));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dateObj;

    } else if (isJsonObject(valCls) || isJsonArray(valCls)) {
        try {
            return isJsonObject(valCls) ? new JSONObject(valStr) : new JSONArray(valStr);
        } catch (JSONException e) {
            throw new IllegalArgumentException(e);
        }
    } else {
        throw new IllegalArgumentException(
                "Unable to convert '" + valStr + "' to " + valCls.getSimpleName() + ".");
    }
}

From source file:org.mili.core.properties.Props.java

private static <T> T getValue(String k, Object s, Class<T> c) {
    Validate.notNull(c);//from   w  w  w .j a va2 s .  c  o m
    Validate.notEmpty(k);
    if (c == Byte.class) {
        return s == null ? getValue(k, "0", c) : (T) Byte.valueOf(s.toString());
    } else if (c == Boolean.class) {
        return s == null ? getValue(k, "false", c) : (T) Boolean.valueOf(s.toString());
    } else if (c == Short.class) {
        return s == null ? getValue(k, "0", c) : (T) Short.valueOf(s.toString());
    } else if (c == Integer.class) {
        return s == null ? getValue(k, "0", c) : (T) Integer.valueOf(s.toString());
    } else if (c == Float.class) {
        return s == null ? getValue(k, "0", c) : (T) Float.valueOf(s.toString());
    } else if (c == Long.class) {
        return s == null ? getValue(k, "0", c) : (T) Long.valueOf(s.toString());
    } else if (c == Double.class) {
        return s == null ? getValue(k, "0", c) : (T) Double.valueOf(s.toString());
    } else if (c == Character.class) {
        return s == null ? (T) Character.valueOf(' ') : (T) Character.valueOf(s.toString().charAt(0));
    } else if (c == String.class) {
        return s == null ? null : (T) String.valueOf(s);
    } else {
        return (T) s;
        /*
         * throw new IllegalArgumentException("no supported type found[" + c.getName() +
         * "] for property[" + k + "].");
         */
    }

}