Example usage for java.lang Short parseShort

List of usage examples for java.lang Short parseShort

Introduction

In this page you can find the example usage for java.lang Short parseShort.

Prototype

public static short parseShort(String s) throws NumberFormatException 

Source Link

Document

Parses the string argument as a signed decimal short .

Usage

From source file:edu.umn.msi.tropix.proteomics.conversion.DtaNameUtils.java

public static DtaNameSummary getDtaNameSummary(final String filename) {
    final Matcher matcher = DTA_PATTERN.matcher(FilenameUtils.getName(filename));
    matcher.matches();/*from w  w w  .  j a v  a2  s  .com*/
    final String basename = matcher.group(1);
    final int start = Integer.parseInt(matcher.group(2));
    final int end = Integer.parseInt(matcher.group(3));
    final short charge = Short.parseShort(matcher.group(4));
    return new DtaNameSummary(basename, start, end, charge);
}

From source file:com.jaspersoft.jasperserver.war.cascade.handlers.converters.ShortDataConverter.java

@Override
public Short stringToValue(String rawData) throws JSValidationException {
    return StringUtils.isNotEmpty(rawData) ? Short.parseShort(rawData) : null;
}

From source file:org.openwms.common.comm.CommonMessageFactory.java

public static MessageHeaders createHeaders(String telegram, Map<String, Object> headers) {
    String sync = telegram.substring(0, CommHeader.LENGTH_SYNC_FIELD);

    int start = sync.length();
    int end = start + CommHeader.LENGTH_MESSAGE_LENGTH_FIELD;
    short messageLength = Short.parseShort(telegram.substring(start, end));

    start = end;//from  w ww.  j  a  v a 2  s  .c o  m
    end += CommHeader.LENGTH_SENDER_FIELD;
    String sender = telegram.substring(start, end);

    start = end;
    end += CommHeader.LENGTH_RECEIVER_FIELD;
    String receiver = telegram.substring(start, end);

    start = end;
    end += CommHeader.LENGTH_SEQUENCE_NO_FIELD;
    short sequenceNo = Short.parseShort(telegram.substring(start, end));
    Map<String, Object> h = new HashMap<>(headers);
    h.put(CommHeader.SYNC_FIELD_NAME, sync);
    h.put(CommHeader.MSG_LENGTH_FIELD_NAME, messageLength);
    h.put(CommHeader.SENDER_FIELD_NAME, sender);
    h.put(CommHeader.RECEIVER_FIELD_NAME, receiver);
    h.put(CommHeader.SEQUENCE_FIELD_NAME, sequenceNo);
    return new MessageHeaders(h);
}

From source file:de.tor.tribes.types.TribeStatsElement.java

public static TribeStatsElement loadFromFile(File pStatFile) {
    TribeStatsElement elem = new TribeStatsElement(null);
    Integer tribeId = Integer.parseInt(pStatFile.getName().substring(0, pStatFile.getName().lastIndexOf(".")));
    elem.setTribe(DataHolder.getSingleton().getTribes().get(tribeId));
    BufferedReader r = null;/*from  w w  w . j  a v  a 2  s  .  co  m*/
    try {
        r = new BufferedReader(new FileReader(pStatFile));
        String line = "";
        while ((line = r.readLine()) != null) {
            String[] data = line.split(";");
            long timestamp = Long.parseLong(data[0]);
            int rank = Integer.parseInt(data[1]);
            long points = Long.parseLong(data[2]);
            short villages = Short.parseShort(data[3]);
            long bashOff = Long.parseLong(data[4]);
            short rankOff = Short.parseShort(data[5]);
            long bashDef = Long.parseLong(data[6]);
            short rankDef = Short.parseShort(data[7]);
            elem.addLoadedData(timestamp, rank, points, villages, bashOff, rankOff, bashDef, rankDef);
        }
    } catch (Exception e) {
        return null;
    } finally {
        try {
            r.close();
        } catch (Exception ignored) {
        }
    }
    return elem;
}

From source file:com.gmail.frogocomics.schematic.BiomeWorldV2Object.java

public static BiomeWorldV2Object load(File file) throws IOException {

    BufferedReader settingsReader;

    if (!file.exists()) {
        throw new FileNotFoundException();
    }/* w w w  .  j a  v  a 2 s . com*/
    settingsReader = new BufferedReader(new FileReader(file));
    int lineNumber = 0;
    String thisLine;
    ArrayList<BiomeWorldObjectBlock> bo2Blocks = new ArrayList<>();

    while ((thisLine = settingsReader.readLine()) != null) {
        lineNumber++;
        if (Pattern.compile("[0-9]").matcher(thisLine.substring(0, 1)).matches()
                || thisLine.substring(0, 1).equalsIgnoreCase("-")) {
            //Example: -1,-1,5:18.4
            // x,z,y:id.data
            String[] location = thisLine.split(":")[0].split(",");
            String[] block = thisLine.split(":")[1].split("\\.");
            bo2Blocks.add(new BiomeWorldObjectBlock(Integer.parseInt(location[0]),
                    Integer.parseInt(location[2]), Integer.parseInt(location[1]), Short.parseShort(block[0]),
                    Byte.parseByte(block[1])));
        }
    }

    ArrayList<Integer> maxXMap = new ArrayList<>();
    ArrayList<Integer> maxYMap = new ArrayList<>();
    ArrayList<Integer> maxZMap = new ArrayList<>();
    for (BiomeWorldObjectBlock bo2 : bo2Blocks) {
        maxXMap.add(bo2.getX());
        maxYMap.add(bo2.getY());
        maxZMap.add(bo2.getZ());
    }

    int maxX = Collections.max(maxXMap);
    int maxY = Collections.max(maxYMap);
    int maxZ = Collections.max(maxZMap);
    int minX = Collections.min(maxXMap);
    int minY = Collections.min(maxYMap);
    int minZ = Collections.min(maxZMap);
    int differenceX = maxX - minX + 1;
    int differenceY = maxY - minY + 1;
    int differenceZ = maxZ - minZ + 1;

    HashMap<Integer, Set<BiomeWorldObjectBlock>> blocks = new HashMap<>();
    for (int i = 0; i < differenceY + 1; i++) {
        blocks.put(i, new HashSet<>());
    }

    for (BiomeWorldObjectBlock bo2 : bo2Blocks) {
        Set<BiomeWorldObjectBlock> a = blocks.get(bo2.getY() - minY);
        a.add(bo2);
        blocks.replace(bo2.getY(), a);
    }

    //System.out.println(differenceX + " " + differenceZ);
    SliceStack schematic = new SliceStack(differenceY, differenceX, differenceZ);

    for (Map.Entry<Integer, Set<BiomeWorldObjectBlock>> next : blocks.entrySet()) {
        Slice slice = new Slice(differenceX, differenceZ);
        for (BiomeWorldObjectBlock block : next.getValue()) {
            //System.out.println("Added block at " + String.valueOf(block.getX() - minX) + "," + String.valueOf(block.getZ() - minZ));
            slice.setBlock(block.getBlock(), block.getX() - minX, block.getZ() - minZ);
        }
        schematic.addSlice(slice);
    }
    //System.out.println(schematic.toString());

    return new BiomeWorldV2Object(schematic, FilenameUtils.getBaseName(file.getAbsolutePath()));
}

From source file:com.madrobot.di.Converter.java

public static Object convertTo(final JSONObject jsonObject, final String fieldName, final Class<?> clz,
        final Field field) {

    Object value = null;/*from   w  w w. ja va  2s .c  om*/

    if (clzTypeKeyMap.containsKey(clz)) {
        try {
            final int code = clzTypeKeyMap.get(clz);
            switch (code) {
            case TYPE_STRING:
                value = jsonObject.optString(fieldName);
                break;
            case TYPE_SHORT:
                value = Short.parseShort(jsonObject.optString(fieldName, "0"));
                break;
            case TYPE_INT:
                value = jsonObject.optInt(fieldName);
                break;
            case TYPE_LONG:
                value = jsonObject.optLong(fieldName);
                break;
            case TYPE_CHAR:
                String chatValue = jsonObject.optString(fieldName);
                if (chatValue.length() > 0) {
                    value = chatValue.charAt(0);
                } else {
                    value = '\0';
                }
                break;
            case TYPE_FLOAT:
                value = Float.parseFloat(jsonObject.optString(fieldName, "0.0f"));
                break;
            case TYPE_DOUBLE:
                value = jsonObject.optDouble(fieldName);
                break;
            case TYPE_BOOLEAN:
                value = jsonObject.optString(fieldName);
                if (field.isAnnotationPresent(BooleanFormat.class)) {
                    BooleanFormat formatAnnotation = field.getAnnotation(BooleanFormat.class);
                    String trueFormat = formatAnnotation.trueFormat();
                    String falseFormat = formatAnnotation.falseFormat();
                    if (trueFormat.equals(value)) {
                        value = true;
                    } else if (falseFormat.equals(value)) {
                        value = false;
                    } else {
                        Log.e(JSONDeserializer.TAG,
                                "Expecting " + trueFormat + " / " + falseFormat + " but its " + value);
                    }
                } else {
                    value = Boolean.parseBoolean((String) value);
                }
                break;
            case TYPE_DATE:
                value = DateFormat.getDateInstance().parse(jsonObject.optString(fieldName));
                break;
            }
        } catch (NumberFormatException e) {
            Log.e(JSONDeserializer.TAG, e.getMessage());
        } catch (ParseException e) {
            Log.e(JSONDeserializer.TAG, e.getMessage());
        }
    }
    return value;
}

From source file:com.primeleaf.krystal.web.action.cpanel.EditUserAction.java

public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL);

    if (request.getMethod().equalsIgnoreCase("POST")) {
        short userId = 0;
        try {/*from www.  ja  v  a  2s. c  om*/
            userId = Short
                    .parseShort(request.getParameter("userid") != null ? request.getParameter("userid") : "0");
        } catch (Exception e) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input");
            return (new UsersAction().execute(request, response));
        }
        UserDAO.getInstance().setReadCompleteObject(true);
        User user = UserDAO.getInstance().readUserById(userId);

        if (user == null) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid User");
            return (new UsersAction().execute(request, response));
        }

        String userName = request.getParameter("txtUserName") != null ? request.getParameter("txtUserName")
                : "";
        String realName = request.getParameter("txtRealName") != null ? request.getParameter("txtRealName")
                : "";
        String userEmail = request.getParameter("txtUserEmail") != null ? request.getParameter("txtUserEmail")
                : "";
        String userDescription = request.getParameter("txtDescription") != null
                ? request.getParameter("txtDescription")
                : "";
        String active = request.getParameter("radActive") != null ? request.getParameter("radActive") : "Y";
        String userType = request.getParameter("radUserType") != null ? request.getParameter("radUserType")
                : "A";

        if (!GenericValidator.maxLength(userName, 15)) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for User Name");
            return (new UsersAction().execute(request, response));
        }
        if (!GenericValidator.maxLength(realName, 50)) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for Real Name");
            return (new UsersAction().execute(request, response));
        }
        if (!GenericValidator.isEmail(userEmail)) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input");
            return (new UsersAction().execute(request, response));
        }
        if (!GenericValidator.maxLength(userEmail, 50)) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for User Email");
            return (new UsersAction().execute(request, response));
        }
        if (!GenericValidator.maxLength(userDescription, 50)) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for User Description");
            return (new UsersAction().execute(request, response));
        }
        if (!"Y".equalsIgnoreCase(active)) {
            active = "N";
        }
        if (!User.USER_TYPE_ADMIN.equalsIgnoreCase(userType)) {
            userType = User.USER_TYPE_USER;
        }

        //check if new email address is different then existing one
        if (!user.getUserEmail().equalsIgnoreCase(userEmail)) {
            //it is different so validate
            if (UserDAO.getInstance().validateUserEmail(userEmail)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "User with " + userEmail + " already exist");
                return (new UsersAction().execute(request, response));
            }
        }

        if (user.getUserName().equalsIgnoreCase(ServerConstants.SYSTEM_ADMIN_USER)) {
            active = "Y"; //Administrator user can never be in activated.
            userType = User.USER_TYPE_ADMIN;
        }
        try {
            user.setUserId(userId);
            user.setRealName(realName);
            user.setUserName(userName);
            user.setUserDescription(userDescription);
            user.setUserEmail(userEmail);

            if ("Y".equalsIgnoreCase(active)) {
                user.setActive(true);
            } else {
                user.setActive(false);
            }

            user.setUserType(userType);

            UserDAO.getInstance().updateUser(user, false);

            AuditLogManager.log(new AuditLogRecord(user.getUserId(), AuditLogRecord.OBJECT_USER,
                    AuditLogRecord.ACTION_EDITED, loggedInUser.getUserName(), request.getRemoteAddr(),
                    AuditLogRecord.LEVEL_INFO, "ID :" + user.getUserId(), "Name : " + user.getUserName()));
            request.setAttribute(HTTPConstants.REQUEST_MESSAGE,
                    "User " + userName.toUpperCase() + " updated successfully");
            return (new UsersAction().execute(request, response));
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        int userId = 0;
        try {
            userId = Integer
                    .parseInt(request.getParameter("userid") != null ? request.getParameter("userid") : "0");
        } catch (Exception e) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input");
            return (new UsersAction().execute(request, response));
        }
        UserDAO.getInstance().setReadCompleteObject(true);
        User user = UserDAO.getInstance().readUserById(userId);
        UserDAO.getInstance().setReadCompleteObject(false);

        if (user == null) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid User");
            return (new UsersAction().execute(request, response));
        }

        request.setAttribute("USER", user);

    }
    return (new EditUserView(request, response));
}

From source file:com.taobao.adfs.database.tdhsocket.client.util.ConvertUtil.java

public static short getShortFromString(String stringVal) throws SQLException {
    if (StringUtils.isBlank(stringVal)) {
        return 0;
    }/*from   ww w.  jav a2  s .  c  o m*/
    try {
        int decimalIndex = stringVal.indexOf(".");

        if (decimalIndex != -1) {
            double valueAsDouble = Double.parseDouble(stringVal);
            return (short) valueAsDouble;
        }

        return Short.parseShort(stringVal);
    } catch (NumberFormatException e) {
        throw new SQLException("Parse integer error:" + stringVal);
    }
}

From source file:co.marcin.novaguilds.util.ItemStackUtils.java

@SuppressWarnings("deprecation")
public static ItemStack stringToItemStack(String str) {
    if (!str.isEmpty()) {
        ItemStack itemStack;//  w w w  . j a v a  2s. c  o m
        Material material;
        String name = "";
        int amount = 0;
        List<String> lore = new ArrayList<>();
        String loreString = "";
        String bookAuthor = null;
        String bookBook = null;
        String player = null;
        short durability = 0;
        PotionType potionType = null;
        int potionLevel = 0;
        byte data = (byte) 0;
        Map<Enchantment, Integer> enchantments = new HashMap<>();

        String[] explode = str.split(" ");

        String materialString = explode[0];

        DyeColor color;

        if (explode[0].contains(":")) {
            String[] dataSplit = explode[0].split(":");
            materialString = dataSplit[0];
            String dataString = dataSplit[1];

            if (NumberUtils.isNumeric(dataString)) {
                durability = Short.parseShort(dataString);
                data = Byte.parseByte(dataString);
            } else {
                color = DyeColor.valueOf(dataString.toUpperCase());
                if (color != null) {
                    data = color.getData();
                }

                durability = data;
            }
        }

        if (NumberUtils.isNumeric(materialString)) {
            material = Material.getMaterial(Integer.parseInt(materialString));
        } else {
            material = Material.getMaterial(materialString.toUpperCase());
        }

        if (material == null) {
            return stringToItemStack("DIRT 1 name:&cINVALID_ITEM");
        }

        if (explode.length > 1) { //amount
            if (NumberUtils.isNumeric(explode[1])) {
                amount = Integer.parseInt(explode[1]);
                explode[1] = null;
            }
        } else {
            amount = material.getMaxStackSize();
        }

        explode[0] = null;

        for (String detail : explode) {
            if (detail != null) {
                if (detail.contains(":")) {
                    String[] detailSplit = detail.split(":");
                    String value = detailSplit[1];
                    //Bukkit.getLogger().info(detailSplit[0] + " : " + value);
                    switch (detailSplit[0].toLowerCase()) {
                    case "name":
                        name = value;
                        break;
                    case "lore":
                        loreString = value;
                        break;
                    case "title":
                        name = value;
                        break;
                    case "author":
                        bookAuthor = value;
                        break;
                    case "book":
                        bookBook = value;
                        break;
                    case "power":
                        if (material == Material.BOW) {
                            enchantments.put(Enchantment.ARROW_DAMAGE, Integer.valueOf(value));
                        } else if (material == Material.POTION) {
                            if (NumberUtils.isNumeric(value)) {
                                potionLevel = Integer.parseInt(value);
                            }
                        } else if (material == Material.FIREWORK) {
                            //TODO
                        }
                        break;
                    case "effect":
                        if (material == Material.POTION) {
                            potionType = PotionType.valueOf(value.toUpperCase());
                        }
                        break;
                    case "duration":
                        break;
                    case "color":
                        color = DyeColor.valueOf(value.toUpperCase());
                        break;
                    case "player":
                        player = value;
                        break;
                    case "fade":
                        break;
                    case "shape":
                        break;

                    case "sharpness":
                    case "alldamage":
                        enchantments.put(Enchantment.DAMAGE_ALL, Integer.valueOf(value));
                        break;
                    case "arrowdamage":
                    case "ardmg":
                        enchantments.put(Enchantment.ARROW_DAMAGE, Integer.valueOf(value));
                        break;
                    case "baneofarthropods":
                        enchantments.put(Enchantment.DAMAGE_ARTHROPODS, Integer.valueOf(value));
                        break;
                    case "durability":
                    case "unbreaking":
                        enchantments.put(Enchantment.DURABILITY, Integer.valueOf(value));
                        break;
                    case "fire":
                    case "fireaspect":
                        enchantments.put(Enchantment.FIRE_ASPECT, Integer.valueOf(value));
                        break;
                    case "knockback":
                        enchantments.put(Enchantment.KNOCKBACK, Integer.valueOf(value));
                        break;
                    case "looting":
                    case "fortune":
                        enchantments.put(Enchantment.LOOT_BONUS_BLOCKS, Integer.valueOf(value));
                        break;
                    case "mobloot":
                        enchantments.put(Enchantment.LOOT_BONUS_MOBS, Integer.valueOf(value));
                        break;
                    case "smite":
                    case "undeaddamage":
                        enchantments.put(Enchantment.DAMAGE_UNDEAD, Integer.valueOf(value));
                        break;
                    case "arrowknockback":
                    case "punch":
                        enchantments.put(Enchantment.ARROW_KNOCKBACK, Integer.valueOf(value));
                        break;
                    case "flame":
                    case "flamearrow":
                        enchantments.put(Enchantment.ARROW_FIRE, Integer.valueOf(value));
                        break;
                    case "infarrows":
                    case "infinity":
                        enchantments.put(Enchantment.ARROW_INFINITE, Integer.valueOf(value));
                        break;
                    case "digspeed":
                    case "efficiency":
                        enchantments.put(Enchantment.DIG_SPEED, Integer.valueOf(value));
                    case "silktouch":
                        enchantments.put(Enchantment.SILK_TOUCH, Integer.valueOf(value));
                        break;
                    case "highcrit":
                    case "thorns":
                        enchantments.put(Enchantment.THORNS, Integer.valueOf(value));
                        break;
                    case "blastprotect":
                        enchantments.put(Enchantment.PROTECTION_EXPLOSIONS, Integer.valueOf(value));
                        break;
                    case "fallprot":
                    case "featherfall":
                        enchantments.put(Enchantment.PROTECTION_FALL, Integer.valueOf(value));
                        break;
                    case "fireprot":
                    case "fireprotect":
                        enchantments.put(Enchantment.PROTECTION_FIRE, Integer.valueOf(value));
                        break;
                    case "projectileprotection":
                    case "projprot":
                        enchantments.put(Enchantment.PROTECTION_PROJECTILE, Integer.valueOf(value));
                        break;
                    case "protect":
                    case "protection":
                        enchantments.put(Enchantment.PROTECTION_ENVIRONMENTAL, Integer.valueOf(value));
                        break;
                    case "waterworker":
                        enchantments.put(Enchantment.WATER_WORKER, Integer.valueOf(value));
                        break;
                    case "respiration":
                    case "breath":
                    case "aquainfinity":
                        enchantments.put(Enchantment.OXYGEN, Integer.valueOf(value));
                        break;
                    case "luck":
                        enchantments.put(Enchantment.LUCK, Integer.valueOf(value));
                        break;
                    case "lure":
                        enchantments.put(Enchantment.LURE, Integer.valueOf(value));
                        break;
                    }
                }
            }
        }

        //replace _ with spaces
        name = name.replace("_", " ");
        name = StringUtils.fixColors(name);
        loreString = loreString.replace("_", " ");
        loreString = StringUtils.fixColors(loreString);

        if (loreString.contains("|")) {
            Collections.addAll(lore, org.apache.commons.lang.StringUtils.split(loreString, '|'));
        } else {
            lore.add(loreString);
        }

        itemStack = new ItemStack(material, amount, data);
        itemStack.addUnsafeEnchantments(enchantments);
        ItemMeta itemMeta = itemStack.getItemMeta();

        if (!name.isEmpty()) {
            itemMeta.setDisplayName(name);
        }

        if (!loreString.isEmpty()) {
            itemMeta.setLore(lore);
        }

        if (material == Material.POTION && potionLevel != 0 && potionType != null) {
            Potion potion = new Potion(potionType, potionLevel);
            potion.apply(itemStack);
        }

        itemStack.setDurability(durability);
        itemStack.setItemMeta(itemMeta);

        if (player != null && itemStack.getType() == Material.SKULL_ITEM) {
            SkullMeta skullMeta = (SkullMeta) Bukkit.getItemFactory().getItemMeta(Material.SKULL_ITEM);
            skullMeta.setOwner(player);
            itemStack.setItemMeta(skullMeta);
        }

        return itemStack;
    }

    return stringToItemStack("DIRT 1 name:&cINVALID_ITEM");
}

From source file:io.servicecomb.serviceregistry.version.Version.java

private short parseNumber(String name, String allVersion, String version) {
    short value = 0;
    try {/* w  w  w .  jav  a  2 s.co  m*/
        value = Short.parseShort(version);
    } catch (NumberFormatException e) {
        throw new IllegalStateException(
                String.format("Invalid %s \"%s\", version \"%s\".", name, version, allVersion), e);
    }

    if (value < 0) {
        throw new IllegalStateException(
                String.format("%s \"%s\" can not be negative, version \"%s\".", name, version, allVersion));
    }

    return value;
}