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:org.apache.hadoop.hive.serde2.lazy.LazyUtils.java

/**
 * Return the byte value of the number string.
 *
 * @param altValue/*  w  ww . ja v a  2  s  . c o  m*/
 *          The string containing a number.
 * @param defaultVal
 *          If the altValue does not represent a number, return the
 *          defaultVal.
 */
public static byte getByte(String altValue, byte defaultVal) {
    if (altValue != null && altValue.length() > 0) {
        try {
            return Byte.parseByte(altValue);
        } catch (NumberFormatException e) {
            return (byte) altValue.charAt(0);
        }
    }
    return defaultVal;
}

From source file:de.xaniox.heavyspleef.migration.GameMigrator.java

@SuppressWarnings({ "unchecked", "deprecation" })
private <T, K> T extractFlagValue(String legacyFlagString, Class<T> expected, Class<K> expectedGenericClass)
        throws MigrationException {
    String[] components = legacyFlagString.split(":");
    Validate.isTrue(components.length > 1, "Invalid legacy flag value string \"" + legacyFlagString + "\"");
    String valueString = components[1];

    T value = null;/*ww  w . ja va 2  s . co m*/

    if (expected == Boolean.class) {
        value = (T) (Boolean) Boolean.parseBoolean(valueString);
    } else if (expected == Integer.class) {
        value = (T) (Integer) Integer.parseInt(valueString);
    } else if (expected == Double.class) {
        value = (T) (Double) Double.parseDouble(valueString);
    } else if (expected == Location.class) {
        value = (T) legacyStringToLocation(valueString);
    } else if (expected == ItemStack.class) {
        String[] itemStackComponents = valueString.split("-");

        int id = Integer.parseInt(itemStackComponents[0]);
        byte data = 0;
        int amount = 1;

        if (itemStackComponents.length > 1) {
            data = Byte.parseByte(itemStackComponents[1]);

            if (itemStackComponents.length > 2) {
                amount = Integer.parseInt(itemStackComponents[2]);
            }
        }

        MaterialData materialData = new MaterialData(id, data);
        value = (T) materialData.toItemStack(amount);
    } else if (expected == List.class) {
        String[] listComponents = valueString.split(";");
        List<K> resultList = Lists.newArrayList();

        for (int i = 0; i < listComponents.length; i++) {
            String base64SerializedString = listComponents[i];
            byte[] serializedBytes = Base64Coder.decode(base64SerializedString);

            Map<String, Object> fields;

            try {
                fields = decodeSerializedObject(serializedBytes);
            } catch (IOException e) {
                throw new MigrationException(e);
            }

            K result = null;

            if (expectedGenericClass == ItemStack.class) {
                EnumObject materialEnumObject = (EnumObject) fields.get("material");

                Material material = Material.getMaterial(materialEnumObject.value.value);
                byte data = (byte) fields.get("data");
                int amount = (int) fields.get("amount");

                Object displayNameObj = fields.get("displayName");
                String displayName = null;

                if (displayNameObj != null) {
                    displayName = ((StringObject) displayNameObj).value;
                }

                List<String> lore = null;
                //The lore is a type of an instance as it is an ArrayList
                Instance arrayListInstance = (Instance) fields.get("lore");

                if (arrayListInstance != null) {
                    lore = Lists.newArrayList();
                    Map<Field, Object> arrayListFields = arrayListInstance.fielddata.values().iterator().next();

                    for (Entry<Field, Object> entry : arrayListFields.entrySet()) {
                        Field field = entry.getKey();
                        Object fieldValue = entry.getValue();

                        //Let's hope oracle doesn't change the array's field name in the future
                        if (fieldValue instanceof ArrayObject && field.name.equals("a")) {
                            ArrayObject array = (ArrayObject) fieldValue;
                            ArrayCollection collection = array.data;

                            for (Object collectionValue : collection) {
                                String loreLine = ((StringObject) collectionValue).value;
                                String[] parts = loreLine.split("\\n");

                                for (String part : parts) {
                                    lore.add(part);
                                }
                            }
                        }
                    }
                }

                MaterialData materialData = new MaterialData(material, data);
                ItemStack stack = materialData.toItemStack(amount);
                ItemMeta meta = stack.getItemMeta();

                if (displayName != null) {
                    meta.setDisplayName(displayName);
                }

                if (lore != null) {
                    meta.setLore(lore);
                }

                stack.setItemMeta(meta);
                result = (K) stack;
            } else if (expectedGenericClass == Location.class) {
                World world = Bukkit.getWorld(((StringObject) fields.get("world")).value);
                double x = (double) fields.get("x");
                double y = (double) fields.get("y");
                double z = (double) fields.get("z");

                float pitch = (float) fields.get("pitch");
                float yaw = (float) fields.get("yaw");

                Location location = new Location(world, x, y, z, yaw, pitch);
                result = (K) location;
            }

            resultList.add(result);
        }

        value = (T) resultList;
    }

    return value;
}

From source file:com.springrts.springls.statistics.Statistics.java

/**
 * Returns a list of the top 5 popular mods for a certain date.
 * The date must be in the format "ddMMyy". It will take the first entry for
 * every new hour and add it to the list. Other entries for the same hour
 * will be ignored./*from   w w  w . j  a v  a2  s  .co m*/
 * @return [list-len] "modname1" [numBattles1] "modname2" [numBattles2]" ...
 *   Where delimiter is TAB (not SPACE).
 *   An empty list is denoted by 0 value for list-len.
 * @see #currentlyPopularModList()
 */
private String getPopularModsList(String date) {

    String popularModsList;

    File file = new File(STATISTICS_FOLDER + date + ".dat");
    Reader inF = null;
    BufferedReader in = null;
    try {
        byte lastHour = -1;
        String line;
        inF = new FileReader(file);
        in = new BufferedReader(inF);
        List<ModBattles> modBattles = new ArrayList<ModBattles>();
        while ((line = in.readLine()) != null) {
            byte sHour = Byte.parseByte(line.substring(0, 2)); // 00 .. 23
            if (lastHour == sHour) {
                continue; // skip this input line
            }
            lastHour = sHour;
            String modFrequencyStr = Misc.makeSentence(line.split(" "), 5);
            String[] modFrequenciesRaw = modFrequencyStr.split("\t");
            if ((modFrequenciesRaw.length % 2) != 1) {
                // the number of arguments must be odd
                // -> numMods + (numMods * (modName + modFrequency))
                throw new Exception("Bad mod list format");
            }
            int numMods = Integer.parseInt(modFrequenciesRaw[0]);
            if (modFrequenciesRaw.length != (1 + (numMods * 2))) {
                throw new Exception("Bad mod list format");
            }
            for (int i = 0; i < numMods; i++) {
                int i2 = i * 2;
                String name = modFrequenciesRaw[i2 + 1];
                int battles = Integer.parseInt(modFrequenciesRaw[i2 + 2]);

                int modIndex = modBattles.indexOf(name);
                if (modIndex == -1) {
                    modBattles.add(new ModBattles(name, battles));
                } else {
                    modBattles.get(modIndex).addBattles(battles);
                }
            }
        }

        popularModsList = createModPopularityString(modBattles);
    } catch (Exception ex) {
        LOG.error("Error in getPopularModsList(). Skipping ...", ex);
        popularModsList = "0";
    } finally {
        try {
            if (in != null) {
                in.close();
            } else if (inF != null) {
                inF.close();
            }
        } catch (IOException ex) {
            LOG.trace("Failed closing statistics file-reader for file: " + file.getAbsolutePath(), ex);
        }
    }

    return popularModsList;
}

From source file:org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent.java

/**
 * Get INetAddress by host name or  IP Address
 *
 * @param host name or host IP String//from  w w  w . j  a v a2 s  .  c  om
 * @return InetAddress
 * @throws UnknownHostException
 */
private InetAddress getHostAddress(String host) throws UnknownHostException {

    String[] splittedString = host.split("\\.");

    if (splittedString.length == 4) {
        // check whether this is ip address or not.
        try {
            Integer.parseInt(splittedString[0]);
            Integer.parseInt(splittedString[1]);
            Integer.parseInt(splittedString[2]);
            Integer.parseInt(splittedString[3]);
            byte[] byteAddress = new byte[4];
            for (int i = 0; i < splittedString.length; i++) {
                if (Integer.parseInt(splittedString[i]) > 127) {
                    byteAddress[i] = new Integer(Integer.parseInt(splittedString[i]) - 256).byteValue();
                } else {
                    byteAddress[i] = Byte.parseByte(splittedString[i]);
                }
            }
            return InetAddress.getByAddress(byteAddress);
        } catch (Exception e) {
            log.debug(e);
            // ignore.
        }
    }
    // if not ip address return host name
    return InetAddress.getByName(host);
}

From source file:gsn.beans.StreamElement.java

public static StreamElement createElementFromREST(DataField[] outputFormat, String[] fieldNames,
        Object[] fieldValues) {//from  w ww.j  ava 2  s . c o  m
    ArrayList<Serializable> values = new ArrayList<Serializable>();
    // ArrayList<String> fields = new ArrayList<String>();

    long timestamp = -1;
    for (int i = 0; i < fieldNames.length; i++) {
        if (fieldNames[i].equalsIgnoreCase("TIMED")) {
            timestamp = Long.parseLong((String) fieldValues[i]);
            continue;
        }
        boolean found = false;
        for (DataField f : outputFormat) {
            if (f.getName().equalsIgnoreCase(fieldNames[i])) {
                //     fields.add(fieldNames[i]);
                found = true;
                break;
            }
        }
        if (found == false)
            continue;

        switch (findIndexInDataField(outputFormat, fieldNames[i])) {
        case DataTypes.DOUBLE:
            values.add(Double.parseDouble((String) fieldValues[i]));
            break;
        case DataTypes.FLOAT:
            values.add(Float.parseFloat((String) fieldValues[i]));
            break;
        case DataTypes.BIGINT:
            values.add(Long.parseLong((String) fieldValues[i]));
            break;
        case DataTypes.TINYINT:
            values.add(Byte.parseByte((String) fieldValues[i]));
            break;
        case DataTypes.SMALLINT:
            values.add(Short.parseShort((String) fieldValues[i]));
            break;
        case DataTypes.INTEGER:
            values.add(Integer.parseInt((String) fieldValues[i]));
            break;
        case DataTypes.CHAR:
        case DataTypes.VARCHAR:
            values.add(new String((byte[]) fieldValues[i]));
            break;
        case DataTypes.BINARY:
            try {
                //          StreamElementTest.md5Digest(fieldValues[ i ]);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            values.add((byte[]) fieldValues[i]);
            break;
        case -1:
        default:
            logger.error("The field name doesn't exit in the output structure : FieldName : "
                    + (String) fieldNames[i]);
        }

    }
    if (timestamp == -1)
        timestamp = System.currentTimeMillis();
    return new StreamElement(outputFormat, values.toArray(new Serializable[] {}), timestamp);
}

From source file:com.xhsoft.framework.common.utils.ClassUtil.java

/**
 * @param type//from  w  ww. ja v  a2s. c  om
 * @param s
 * @return Object
 * @author lizj
 */
public static Object cast(Class<?> type, String s) {
    if (s == null || type == null) {
        return null;
    }

    Object value = null;

    if (type == char.class || type == Character.class) {
        value = (s.length() > 0 ? Character.valueOf(s.charAt(0)) : null);
    } else if (type == boolean.class || type == Boolean.class) {
        String x = s.toLowerCase();

        boolean b = ("1".equals(x) || "y".equals(x) || "on".equals(x) || "yes".equals(x) || "true".equals(x));

        value = new Boolean(b);
    } else if (type == byte.class || type == Byte.class) {
        try {
            value = Byte.parseByte(s);
        } catch (NumberFormatException e) {
        }
    } else if (type == short.class || type == Short.class) {
        try {
            value = Short.parseShort(s);
        } catch (NumberFormatException e) {
        }
    } else if (type == int.class || type == Integer.class) {
        try {
            value = Integer.parseInt(s);
        } catch (NumberFormatException e) {
        }
    } else if (type == float.class || type == Float.class) {
        try {
            value = Float.parseFloat(s);
        } catch (NumberFormatException e) {
        }
    } else if (type == double.class || type == Double.class) {
        try {
            value = Double.parseDouble(s);
        } catch (NumberFormatException e) {
        }
    } else if (type == long.class || type == Long.class) {
        try {
            value = Long.parseLong(s);
        } catch (NumberFormatException e) {
        }
    } else if (type == String.class) {
        value = s;
    } else if (type == StringBuilder.class) {
        value = new StringBuilder(s);
    } else if (type == StringBuffer.class) {
        value = new StringBuffer(s);
    } else if (type == java.io.Reader.class) {
        value = new java.io.StringReader(s);
    } else if (type == java.util.Date.class) {
        if (s.length() > 0) {
            try {
                String format = (s.length() == "yyyy-MM-dd".length() ? "yyyy-MM-dd"
                        : "yyyy-MM-dd HH:mm:ss SSS");

                SimpleDateFormat dateFormat = new SimpleDateFormat(format);

                value = dateFormat.parse(s);
            } catch (java.text.ParseException e) {
                if (DEBUG) {
                    log.debug("Exception: " + e.getMessage());
                }
            }
        }
    } else if (type == java.sql.Date.class) {
        if (s.length() > 0) {
            try {
                String format = (s.length() == "yyyy-MM-dd".length() ? "yyyy-MM-dd"
                        : "yyyy-MM-dd HH:mm:ss SSS");

                SimpleDateFormat dateFormat = new SimpleDateFormat(format);

                java.util.Date date = dateFormat.parse(s);

                value = new java.sql.Date(date.getTime());
            } catch (java.text.ParseException e) {
                if (DEBUG) {
                    log.debug("Exception: " + e.getMessage());
                }
            }
        }
    } else if (type == java.sql.Timestamp.class) {
        if (s.length() > 0) {
            try {
                String format = (s.length() == "yyyy-MM-dd".length() ? "yyyy-MM-dd"
                        : "yyyy-MM-dd HH:mm:ss SSS");

                SimpleDateFormat dateFormat = new SimpleDateFormat(format);

                java.util.Date date = dateFormat.parse(s);

                value = new java.sql.Timestamp(date.getTime());
            } catch (java.text.ParseException e) {
                if (DEBUG) {
                    log.debug("Exception: " + e.getMessage());
                }
            }
        }
    }

    return value;
}

From source file:ch.unil.genescore.vegas.Snp.java

/** Parse homegrown format */
private void setGenotypeAndChrPosFromHomegrown(String[] nextLine) {

    assert (nextLine[0].equals(this.id_));

    String chr = nextLine[1];//  w w  w. j  ava  2s .  co m
    int start = Integer.parseInt(nextLine[2]);
    char minorAllele = 'N';
    if (nextLine[4].length() == 0) {
        minorAllele = 'D';
    } else if (nextLine[4].length() > 1) {
        minorAllele = 'I';
    } else {
        minorAllele = nextLine[4].charAt(0);
    }
    String[] genotypesStr = nextLine[nextLine.length - 1].split(";");
    byte[] genotypes = new byte[genotypesStr.length];
    for (int i = 0; i < genotypesStr.length; ++i) {
        genotypes[i] = Byte.parseByte(genotypesStr[i]);
    }

    // Do not initialize position and genotype for snps with a constant genotype
    if (isConstant(genotypes))
        return;

    genotypes_ = genotypes;
    this.setPosition(chr, start, start + 1, true);
    this.setMinorAllele(minorAllele);
}

From source file:com.hzc.framework.ssh.controller.WebUtil.java

/**
 * +?????/* www . j a  va 2s  . com*/
 *
 * @param path
 * @param c
 * @param ufc
 * @param <T>
 * @return
 * @throws Exception
 */
public static <T> T upload(String path, Class<T> c, UploadFileCall ufc) throws RuntimeException {
    try {
        HttpServletRequest request = getReq();

        ServletContext servletContext = getServletContext();
        File file = new File(servletContext.getRealPath(path));
        if (!file.exists())
            file.mkdir();

        MultipartRequest multi = new MultipartRequest(request, file.getAbsolutePath(), 1024 * 1024 * 1024,
                "UTF-8", new DefaultFileRenamePolicy());
        Enumeration params = multi.getParameterNames();
        T obj = c.newInstance();
        Field[] declaredFields = c.getDeclaredFields();

        // ??,??
        labelNext: while (params.hasMoreElements()) {
            String name = (String) params.nextElement();
            for (Field field : declaredFields) {
                field.setAccessible(true);
                String fieldName = field.getName();
                if (name.equals(fieldName)) {
                    String value = multi.getParameter(name);
                    if (null == value) {
                        continue;
                    }
                    Class<?> type = field.getType();
                    if (type == Long.class) {
                        field.set(obj, Long.parseLong(value));
                    } else if (type == String.class) {
                        field.set(obj, value);
                    } else if (type == Byte.class) {
                        field.set(obj, Byte.parseByte(value));
                    } else if (type == Integer.class) {
                        field.set(obj, Integer.parseInt(value));
                    } else if (type == Character.class) {
                        field.set(obj, value.charAt(0));
                    } else if (type == Boolean.class) {
                        field.set(obj, Boolean.parseBoolean(value));
                    } else if (type == Double.class) {
                        field.set(obj, Double.parseDouble(value));
                    } else if (type == Float.class) {
                        field.set(obj, Float.parseFloat(value));
                    }
                    continue labelNext;
                }
            }
        }
        ufc.form(obj, multi);
        Enumeration files = multi.getFileNames();
        while (files.hasMoreElements()) {
            String name = (String) files.nextElement();
            String filename = multi.getFilesystemName(name);
            String originalFilename = multi.getOriginalFileName(name);
            String type = multi.getContentType(name);
            File f = multi.getFile(name);
            ufc.file(obj, f, filename, originalFilename, type);
        }
        return obj;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.jeans.iservlet.action.asset.AssetAction.java

/**
 * ???Map??String[]?null<br>/*from   www  .  j ava2  s.  c  o m*/
 * ??action?action<br>
 * ?????null
 * 
 * @return
 * @throws Exception
 */
private Map<String, Object> transProps() throws Exception {
    Map<String, Object> p = new HashMap<String, Object>();
    Set<String> keys = props.keySet();
    for (String key : keys) {
        String value = ((String[]) props.get(key))[0];
        if ("expiredTime".equals(key) || "purchaseTime".equals(key)) {
            p.put(key, "".equals(value) ? null : (new SimpleDateFormat("yyyy-MM-dd")).parse(value));
        } else if ("quantity".equals(key) || "number".equals(key)) {
            p.put(key, Integer.parseInt(value));
        } else if ("cost".equals(key)) {
            p.put(key, BigDecimal.valueOf(Double.parseDouble(value)));
        } else if ("warranty".equals(key) || "importance".equals(key) || "softwareType".equals(key)
                || "type".equals(key) || "catalog".equals(key) || "state".equals(key)) {
            p.put(key, Byte.parseByte(value));
        } else if ("ownerId".equals(key)) {
            p.put("owner", (Employee) hrService.getUnit(Long.parseLong(value), HRUnit.EMPLOYEE));
        } else {
            p.put(key, value);
        }
    }
    if (!p.containsKey("company")) {
        p.put("company", getCurrentCompany());
    }
    return p;
}

From source file:com.facebook.litho.ComponentsStethoManagerImpl.java

private void applyReflectiveOverride(Object o, String key, String value) {
    try {/*  w w w . j  a va2 s  .co m*/
        final Field field = o.getClass().getDeclaredField(key);
        final Class type = field.getType();
        field.setAccessible(true);

        if (type.equals(short.class)) {
            field.set(o, Short.parseShort(value));
        } else if (type.equals(int.class)) {
            field.set(o, Integer.parseInt(value));
        } else if (type.equals(long.class)) {
            field.set(o, Long.parseLong(value));
        } else if (type.equals(float.class)) {
            field.set(o, Float.parseFloat(value));
        } else if (type.equals(double.class)) {
            field.set(o, Double.parseDouble(value));
        } else if (type.equals(boolean.class)) {
            field.set(o, Boolean.parseBoolean(value));
        } else if (type.equals(byte.class)) {
            field.set(o, Byte.parseByte(value));
        } else if (type.equals(char.class)) {
            field.set(o, value.charAt(0));
        } else if (CharSequence.class.isAssignableFrom(type)) {
            field.set(o, value);
        }
    } catch (Exception ignored) {
    }
}