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:io.apiman.gateway.engine.es.ESSharedStateComponent.java

/**
 * Reads a stored primitive.//from  ww  w.  j  ava  2  s .  c om
 * @param result
 */
protected Object readPrimitive(JestResult result) throws Exception {
    PrimitiveBean pb = result.getSourceAsObject(PrimitiveBean.class);
    String value = pb.getValue();
    Class<?> c = Class.forName(pb.getType());
    if (c == String.class) {
        return value;
    } else if (c == Long.class) {
        return Long.parseLong(value);
    } else if (c == Integer.class) {
        return Integer.parseInt(value);
    } else if (c == Double.class) {
        return Double.parseDouble(value);
    } else if (c == Boolean.class) {
        return Boolean.parseBoolean(value);
    } else if (c == Byte.class) {
        return Byte.parseByte(value);
    } else if (c == Short.class) {
        return Short.parseShort(value);
    } else if (c == Float.class) {
        return Float.parseFloat(value);
    } else {
        throw new Exception("Unsupported primitive: " + c); //$NON-NLS-1$
    }
}

From source file:org.diorite.config.serialization.YamlDeserializationData.java

@Nullable
@SuppressWarnings({ "unchecked", "rawtypes" })
private <T> T deserializeSpecial(Class<T> type, Node node, @Nullable T def) {
    if (DioriteReflectionUtils.getWrapperClass(type).equals(Boolean.class)) {
        node.setTag(Tag.STR);//from  w  w  w  .  j  a v a  2  s .c o m
        T t = (T) this.toBool(this.constructor.constructObject(node).toString());
        if (t == null) {
            return def;
        }
        return t;
    }
    if (Enum.class.isAssignableFrom(type)) {
        node.setTag(Tag.STR);
        Enum valueSafe = DioriteReflectionUtils
                .getEnumValueSafe(this.constructor.constructObject(node).toString(), -1, (Class) type);
        if (valueSafe == null) {
            return def;
        }
        return (T) valueSafe;
    }
    if (Number.class.isAssignableFrom(DioriteReflectionUtils.getWrapperClass(type))) {
        Class<?> numType = DioriteReflectionUtils.getWrapperClass(type);
        node.setTag(new Tag(String.class));
        String deserialize = this.constructor.constructObject(node).toString();
        if (numType == Byte.class) {
            return (T) (Byte) Byte.parseByte(deserialize);
        } else if (numType == Short.class) {
            return (T) (Short) Short.parseShort(deserialize);
        } else if (numType == Integer.class) {
            return (T) (Integer) Integer.parseInt(deserialize);
        } else if (numType == Long.class) {
            return (T) (Long) Long.parseLong(deserialize);
        } else if (numType == Float.class) {
            return (T) (Float) Float.parseFloat(deserialize);
        } else if (numType == Double.class) {
            return (T) (Double) Double.parseDouble(deserialize);
        }
    }
    if (type != Object.class) {
        node.setTag(new Tag(type));
    }
    return (T) this.constructor.constructObject(node);
}

From source file:org.ff4j.commonsconf.FF4jConfiguration.java

/** {@inheritDoc} */
@Override/*w  w w.  j a  v a 2s. c o m*/
public byte getByte(String key) {
    String value = null;
    try {
        value = (String) getValue(key);
        return Byte.parseByte(value);
    } catch (NumberFormatException nbe) {
        throw new InvalidPropertyTypeException("Cannot create Byte from " + value, nbe);
    }
}

From source file:com.itemanalysis.psychometrics.irt.estimation.ItemResponseFileSummary.java

private ItemResponseVector[] readTapData() {
    byte[][] tap = new byte[35][18];
    try {/*from   w ww  .  j  a  v a  2s. c  o m*/
        File f = FileUtils.toFile(this.getClass().getResource("/testdata/tap-data.txt"));
        BufferedReader br = new BufferedReader(new FileReader(f));
        String line = "";
        String[] s = null;
        int row = 0;
        while ((line = br.readLine()) != null) {
            s = line.split(",");
            for (int j = 0; j < s.length; j++) {
                tap[row][j] = Byte.parseByte(s[j]);
            }
            row++;
        }
        br.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    Frequency freq = new Frequency();
    for (int i = 0; i < tap.length; i++) {
        freq.addValue(Arrays.toString(tap[i]));
    }

    ItemResponseVector[] responseData = new ItemResponseVector[freq.getUniqueCount()];
    ItemResponseVector irv = null;
    Iterator<Comparable<?>> iter = freq.valuesIterator();
    int index = 0;

    //create array of ItemResponseVector objects
    while (iter.hasNext()) {
        //get response string from frequency summary and convert to byte array
        Comparable<?> value = iter.next();
        String s = value.toString();
        s = s.substring(1, s.lastIndexOf("]"));
        String[] sa = s.split(",");
        byte[] rv = new byte[sa.length];
        for (int i = 0; i < sa.length; i++) {
            rv[i] = Byte.parseByte(sa[i].trim());
        }

        //create response vector objects
        irv = new ItemResponseVector(rv, Long.valueOf(freq.getCount(value)).doubleValue());
        responseData[index] = irv;
        index++;
    }
    //        //display results of summary
    //        for(int i=0;i<responseData.length;i++){
    //            System.out.println(responseData[i].toString() + ": " + responseData[i].getFrequency());
    //        }

    return responseData;
}

From source file:xbird.storage.indexer.ValueIndexer.java

public Value getTypedValue(String value) {
    if (type != STRING && type != TRIMMED) {
        value = value.trim();//from   w ww  . ja v  a  2  s.co  m

        if (value.length() == 0) {
            return EmptyValue;
        }

        byte[] b = new byte[typeSize];
        try {
            switch (type) {
            case INTEGER:
                long l = Long.parseLong(value);
                b[0] = (byte) ((l >>> 56) & 0xFF);
                b[1] = (byte) ((l >>> 48) & 0xFF);
                b[2] = (byte) ((l >>> 40) & 0xFF);
                b[3] = (byte) ((l >>> 32) & 0xFF);
                b[4] = (byte) ((l >>> 24) & 0xFF);
                b[5] = (byte) ((l >>> 16) & 0xFF);
                b[6] = (byte) ((l >>> 8) & 0xFF);
                b[7] = (byte) ((l >>> 0) & 0xFF);
                break;
            case FLOAT:
                double d = Double.parseDouble(value);
                int i1 = (int) Math.round(d);
                int i2 = (int) Math.round((d - i1) * 1000000000);
                b[0] = (byte) ((i1 >>> 24) & 0xFF);
                b[1] = (byte) ((i1 >>> 16) & 0xFF);
                b[2] = (byte) ((i1 >>> 8) & 0xFF);
                b[3] = (byte) ((i1 >>> 0) & 0xFF);
                b[4] = (byte) ((i2 >>> 24) & 0xFF);
                b[5] = (byte) ((i2 >>> 16) & 0xFF);
                b[6] = (byte) ((i2 >>> 8) & 0xFF);
                b[7] = (byte) ((i2 >>> 0) & 0xFF);
                break;
            case BYTE:
                b[0] = Byte.parseByte(value);
                break;
            case CHAR:
                char c = value.charAt(0);
                b[0] = (byte) ((c >>> 8) & 0xFF);
                b[1] = (byte) ((c >>> 0) & 0xFF);
                break;
            case BOOLEAN:
                if ("[true][yes][1][y][on]".indexOf("[" + value.toLowerCase() + "]") != -1) {
                    b[0] = 1;
                } else if ("[false][no][0][n][off]".indexOf("[" + value.toLowerCase() + "]") != -1) {
                    b[0] = 0;
                } else {
                    return EmptyValue;
                }
                break;
            default:
                if (LOG.isWarnEnabled()) {
                    LOG.warn("invalid type : " + type);
                }
            }
            return new Value(b);
        } catch (Exception e) {
            return EmptyValue;
        }
    }

    if (type == TRIMMED) {
        value = QueryEngine.normalizeString(value);
    }

    return new Value(value);
}

From source file:net.naijatek.myalumni.util.utilities.ParamUtil.java

public static byte getParameterByte(final HttpServletRequest request, final String param)
        throws BadInputException {
    String inputStr = getParameter(request, param, true);
    byte ret;/*from  w w  w .j a v a 2  s  .  c  o  m*/
    try {
        ret = Byte.parseByte(inputStr);
    } catch (NumberFormatException e) {
        throw new BadInputException(
                "Cannot parse the parameter \"" + param + "\" to an Byte value!. Please try again.");
    }
    return ret;
}

From source file:com.opengamma.web.json.FudgeMsgJSONReader.java

private byte byteValue(final Object o) {
    if (o instanceof Number) {
        return ((Number) o).byteValue();
    } else if (o instanceof String) {
        return Byte.parseByte((String) o);
    } else {//  w  ww  . ja v  a 2  s. c  om
        throw new NumberFormatException(o + " is not a number");
    }
}

From source file:adams.flow.transformer.exiftagoperation.ApacheCommonsExifTagWrite.java

/**
 * Processes the incoming data./*ww w.ja  v  a2s.  c  o  m*/
 *
 * @param input   the input to process
 * @param errors   for storing errors
 * @return      the generated output
 */
@Override
protected Object doProcess(Object input, MessageCollection errors) {
    Object result;
    File inputFile;
    File tmpFile;
    JpegImageMetadata meta;
    TiffImageMetadata exif;
    TiffOutputSet outputSet;
    TiffOutputDirectory exifDir;
    FileOutputStream fos;
    BufferedOutputStream bos;

    result = null;

    if (input instanceof String)
        inputFile = new PlaceholderFile((String) input).getAbsoluteFile();
    else
        inputFile = ((File) input).getAbsoluteFile();
    tmpFile = TempUtils.createTempFile(getClass().getSimpleName().toLowerCase() + "-", ".jpg");

    fos = null;
    bos = null;
    try {
        meta = (JpegImageMetadata) Imaging.getMetadata(inputFile);
        if (meta != null) {
            exif = meta.getExif();
            if (exif != null) {
                outputSet = exif.getOutputSet();
                if (outputSet != null) {
                    exifDir = outputSet.getOrCreateExifDirectory();
                    if (exifDir != null) {
                        exifDir.removeField(m_Tag.getTagInfo());
                        if (m_Tag.getTagInfo() instanceof TagInfoAscii)
                            exifDir.add((TagInfoAscii) m_Tag.getTagInfo(), m_Value);
                        else if (m_Tag.getTagInfo() instanceof TagInfoByte)
                            exifDir.add((TagInfoByte) m_Tag.getTagInfo(), Byte.parseByte(m_Value));
                        else if (m_Tag.getTagInfo() instanceof TagInfoShort)
                            exifDir.add((TagInfoShort) m_Tag.getTagInfo(), Short.parseShort(m_Value));
                        else if (m_Tag.getTagInfo() instanceof TagInfoDouble)
                            exifDir.add((TagInfoDouble) m_Tag.getTagInfo(), Double.parseDouble(m_Value));
                        else if (m_Tag.getTagInfo() instanceof TagInfoFloat)
                            exifDir.add((TagInfoFloat) m_Tag.getTagInfo(), Float.parseFloat(m_Value));
                        else if (m_Tag.getTagInfo() instanceof TagInfoRational)
                            exifDir.add((TagInfoRational) m_Tag.getTagInfo(),
                                    RationalNumber.valueOf(Double.parseDouble(m_Value)));
                        else
                            errors.add("Unhandled tag info type: " + Utils.classToString(m_Tag.getTagInfo()));
                        if (errors.isEmpty()) {
                            fos = new FileOutputStream(tmpFile);
                            bos = new BufferedOutputStream(fos);
                            new ExifRewriter().updateExifMetadataLossless(inputFile, bos, outputSet);
                            if (!FileUtils.copy(tmpFile, inputFile))
                                errors.add("Failed to replace " + inputFile + " with updated EXIF from "
                                        + tmpFile);
                            if (!FileUtils.delete(tmpFile))
                                errors.add("Failed to delete tmp file: " + tmpFile);
                        }
                    } else {
                        errors.add("Failed to obtain EXIF directory: " + input);
                    }
                } else {
                    errors.add("Failed to obtain output set: " + input);
                }
            } else {
                errors.add("No EXIF meta-data available: " + input);
            }
        } else {
            errors.add("No meta-data available: " + input);
        }
    } catch (Exception e) {
        errors.add("Failed to read EXIF tag " + m_Tag + " from: " + input, e);
    } finally {
        FileUtils.closeQuietly(bos);
        FileUtils.closeQuietly(fos);
    }

    if (errors.isEmpty())
        result = input;

    return result;
}

From source file:com.aionemu.gameserver.model.templates.item.ItemTemplate.java

/**
 * @param u/*from  w ww .  j ava 2s .c om*/
 * @param parent
 */
void afterUnmarshal(Unmarshaller u, Object parent) {
    if (id != null) {
        setItemId(Integer.parseInt(id));
    }
    String[] parts = restrict.split(",");
    restricts = new int[17]; // 4.5
    for (int i = 0; i < parts.length; i++) {
        restricts[i] = Integer.parseInt(parts[i]);
    }
    if (restrictMax != null) {
        String[] partsMax = restrictMax.split(",");
        restrictsMax = new byte[17];
        for (int i = 0; i < partsMax.length; i++) {
            restrictsMax[i] = Byte.parseByte(partsMax[i]);
        }
    }
    if (weaponStats == null) {
        weaponStats = emptyWeaponStats;
    }
}

From source file:org.openhab.binding.insteonhub.internal.InsteonHubBinding.java

@Override
protected void internalReceiveCommand(String itemName, Command command) {
    // get configuration for this item
    InsteonHubBindingConfig config = InsteonHubBindingConfigUtil.getConfigForItem(providers, itemName);
    if (config == null) {
        logger.error(BINDING_NAME + " received command for unknown item '" + itemName + "'");
        return;/*from   w  ww  .  j  a  v a2 s  . c om*/
    }

    // parse info from config
    BindingType type = config.getBindingType();
    String hubId = config.getDeviceInfo().getHubId();
    String deviceId = config.getDeviceInfo().getDeviceId();

    // lookup proxy from this configuration
    InsteonHubProxy proxy = proxies.get(hubId);
    if (proxy == null) {
        logger.error(BINDING_NAME + " received command for unknown hub id '" + hubId + "'");
        return;
    }

    if (logger.isDebugEnabled()) {
        logger.debug(BINDING_NAME + " processing command '" + command + "' of type '"
                + command.getClass().getSimpleName() + "' for item '" + itemName + "'");
    }

    try {
        // process according to type
        if (type == BindingType.SWITCH) {
            // set value on or off
            if (command instanceof OnOffType) {
                proxy.setDevicePower(deviceId, command == OnOffType.ON);
            }
        } else if (type == BindingType.DIMMER) {
            // INSTEON Dimmer supports Dimmer and RollerShutter types
            if (command instanceof OnOffType) {
                // ON or OFF => Set level to 255 or 0
                int level = command == OnOffType.ON ? 255 : 0;
                proxy.setDeviceLevel(deviceId, level);
            } else if (command instanceof IncreaseDecreaseType) {
                // Increase/Decrease => Incremental Brighten/Dim
                InsteonHubAdjustmentType adjustmentType;
                if (command == IncreaseDecreaseType.INCREASE)
                    adjustmentType = InsteonHubAdjustmentType.BRIGHTEN;
                else
                    adjustmentType = InsteonHubAdjustmentType.DIM;
                if (setDimTimeout(itemName)) {
                    proxy.startDeviceAdjustment(deviceId, adjustmentType);
                }
            } else if (command instanceof UpDownType) {
                // Up/Down => Start Brighten/Dim
                InsteonHubAdjustmentType adjustmentType;
                if (command == UpDownType.UP)
                    adjustmentType = InsteonHubAdjustmentType.BRIGHTEN;
                else
                    adjustmentType = InsteonHubAdjustmentType.DIM;
                proxy.startDeviceAdjustment(deviceId, adjustmentType);
            } else if (command instanceof StopMoveType) {
                // Stop => Stop Brighten/Dim
                if (command == StopMoveType.STOP) {
                    proxy.stopDeviceAdjustment(deviceId);
                }
            } else {
                // set level from 0 to 100 percent value
                byte percentByte = Byte.parseByte(command.toString());
                float percent = percentByte * .01f;
                int level = (int) (255 * percent);
                proxy.setDeviceLevel(deviceId, level);
            }

        }
    } catch (Throwable t) {
        logger.error("Error processing command '" + command + "' for item '" + itemName + "'", t);
    }
}