Example usage for org.apache.commons.lang3.math NumberUtils toInt

List of usage examples for org.apache.commons.lang3.math NumberUtils toInt

Introduction

In this page you can find the example usage for org.apache.commons.lang3.math NumberUtils toInt.

Prototype

public static int toInt(final String str, final int defaultValue) 

Source Link

Document

Convert a String to an int, returning a default value if the conversion fails.

If the string is null, the default value is returned.

 NumberUtils.toInt(null, 1) = 1 NumberUtils.toInt("", 1)   = 1 NumberUtils.toInt("1", 0)  = 1 

Usage

From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java

private void initialize() {
    try {/*from w w  w  . j a va2s  .  c o  m*/
        // Disable delimiter parsing so getString() returns the whole
        // property, even if there are commas
        mirthConfig.setDelimiterParsingDisabled(true);
        mirthConfig.setFile(new File(ClassPathResource.getResourceURI("mirth.properties")));
        mirthConfig.load();

        MigrationController.getInstance().migrateConfiguration(mirthConfig);

        // load the server version
        versionConfig.setDelimiterParsingDisabled(true);
        InputStream versionPropertiesStream = ResourceUtil.getResourceStream(this.getClass(),
                "version.properties");
        versionConfig.load(versionPropertiesStream);
        IOUtils.closeQuietly(versionPropertiesStream);

        if (mirthConfig.getString(PROPERTY_TEMP_DIR) != null) {
            File tempDataDirFile = new File(mirthConfig.getString(PROPERTY_TEMP_DIR));

            if (!tempDataDirFile.exists()) {
                if (tempDataDirFile.mkdirs()) {
                    logger.debug("created tempdir: " + tempDataDirFile.getAbsolutePath());
                } else {
                    logger.error("error creating tempdir: " + tempDataDirFile.getAbsolutePath());
                }
            }

            System.setProperty("java.io.tmpdir", tempDataDirFile.getAbsolutePath());
            logger.debug("set temp data dir: " + tempDataDirFile.getAbsolutePath());
        }

        File appDataDirFile = null;

        if (mirthConfig.getString(PROPERTY_APP_DATA_DIR) != null) {
            appDataDirFile = new File(mirthConfig.getString(PROPERTY_APP_DATA_DIR));

            if (!appDataDirFile.exists()) {
                if (appDataDirFile.mkdir()) {
                    logger.debug("created app data dir: " + appDataDirFile.getAbsolutePath());
                } else {
                    logger.error("error creating app data dir: " + appDataDirFile.getAbsolutePath());
                }
            }
        } else {
            appDataDirFile = new File(".");
        }

        appDataDir = appDataDirFile.getAbsolutePath();
        logger.debug("set app data dir: " + appDataDir);

        baseDir = new File(ClassPathResource.getResourceURI("mirth.properties")).getParentFile().getParent();
        logger.debug("set base dir: " + baseDir);

        if (mirthConfig.getString(CHARSET) != null) {
            System.setProperty(CHARSET, mirthConfig.getString(CHARSET));
        }

        String[] httpsClientProtocolsArray = mirthConfig.getStringArray(HTTPS_CLIENT_PROTOCOLS);
        if (ArrayUtils.isNotEmpty(httpsClientProtocolsArray)) {
            // Support both comma separated and multiline values
            List<String> httpsClientProtocolsList = new ArrayList<String>();
            for (String protocol : httpsClientProtocolsArray) {
                httpsClientProtocolsList.addAll(Arrays.asList(StringUtils.split(protocol, ',')));
            }
            httpsClientProtocols = httpsClientProtocolsList
                    .toArray(new String[httpsClientProtocolsList.size()]);
        } else {
            httpsClientProtocols = MirthSSLUtil.DEFAULT_HTTPS_CLIENT_PROTOCOLS;
        }

        String[] httpsServerProtocolsArray = mirthConfig.getStringArray(HTTPS_SERVER_PROTOCOLS);
        if (ArrayUtils.isNotEmpty(httpsServerProtocolsArray)) {
            // Support both comma separated and multiline values
            List<String> httpsServerProtocolsList = new ArrayList<String>();
            for (String protocol : httpsServerProtocolsArray) {
                httpsServerProtocolsList.addAll(Arrays.asList(StringUtils.split(protocol, ',')));
            }
            httpsServerProtocols = httpsServerProtocolsList
                    .toArray(new String[httpsServerProtocolsList.size()]);
        } else {
            httpsServerProtocols = MirthSSLUtil.DEFAULT_HTTPS_SERVER_PROTOCOLS;
        }

        String[] httpsCipherSuitesArray = mirthConfig.getStringArray(HTTPS_CIPHER_SUITES);
        if (ArrayUtils.isNotEmpty(httpsCipherSuitesArray)) {
            // Support both comma separated and multiline values
            List<String> httpsCipherSuitesList = new ArrayList<String>();
            for (String cipherSuite : httpsCipherSuitesArray) {
                httpsCipherSuitesList.addAll(Arrays.asList(StringUtils.split(cipherSuite, ',')));
            }
            httpsCipherSuites = httpsCipherSuitesList.toArray(new String[httpsCipherSuitesList.size()]);
        } else {
            httpsCipherSuites = MirthSSLUtil.DEFAULT_HTTPS_CIPHER_SUITES;
        }

        String deploy = String.valueOf(mirthConfig.getProperty(STARTUP_DEPLOY));
        if (StringUtils.isNotBlank(deploy)) {
            startupDeploy = Boolean.parseBoolean(deploy);
        }

        // Check for server GUID and generate a new one if it doesn't exist
        PropertiesConfiguration serverIdConfig = new PropertiesConfiguration(
                new File(getApplicationDataDir(), "server.id"));

        if ((serverIdConfig.getString("server.id") != null)
                && (serverIdConfig.getString("server.id").length() > 0)) {
            serverId = serverIdConfig.getString("server.id");
        } else {
            serverId = generateGuid();
            logger.debug("generated new server id: " + serverId);
            serverIdConfig.setProperty("server.id", serverId);
            serverIdConfig.save();
        }

        passwordRequirements = PasswordRequirementsChecker.getInstance().loadPasswordRequirements(mirthConfig);

        apiBypassword = mirthConfig.getString(API_BYPASSWORD);
        if (StringUtils.isNotBlank(apiBypassword)) {
            apiBypassword = new String(Base64.decodeBase64(apiBypassword), "US-ASCII");
        }

        statsUpdateInterval = NumberUtils.toInt(mirthConfig.getString(STATS_UPDATE_INTERVAL),
                DonkeyStatisticsUpdater.DEFAULT_UPDATE_INTERVAL);

        // Check for configuration map properties
        if (mirthConfig.getString(CONFIGURATION_MAP_PATH) != null) {
            configurationFile = mirthConfig.getString(CONFIGURATION_MAP_PATH);
        } else {
            configurationFile = getApplicationDataDir() + File.separator + "configuration.properties";
        }

        PropertiesConfiguration configurationMapProperties = new PropertiesConfiguration();
        configurationMapProperties.setDelimiterParsingDisabled(true);
        configurationMapProperties.setListDelimiter((char) 0);
        try {
            configurationMapProperties.load(new File(configurationFile));
        } catch (ConfigurationException e) {
            logger.warn("Failed to find configuration map file");
        }

        Map<String, ConfigurationProperty> configurationMap = new HashMap<String, ConfigurationProperty>();
        Iterator<String> iterator = configurationMapProperties.getKeys();

        while (iterator.hasNext()) {
            String key = iterator.next();
            String value = configurationMapProperties.getString(key);
            String comment = configurationMapProperties.getLayout().getCanonicalComment(key, false);

            configurationMap.put(key, new ConfigurationProperty(value, comment));
        }

        setConfigurationProperties(configurationMap, false);
    } catch (Exception e) {
        logger.error("Failed to initialize configuration controller", e);
    }
}

From source file:com.esri.geoevent.test.performance.ui.FixtureController.java

@FXML
public void addConsumer(final ActionEvent event) {
    String hostName = consumerHostName.getText();
    int port = NumberUtils.toInt(consumerPort.getText(), 0);
    if (StringUtils.isEmpty(hostName) || port == 0) {
        //TODO: Validation error
    } else {/*from w w w  .  j a  v a 2 s  .  c o  m*/
        ConnectableRemoteHost remoteHost = new ConnectableRemoteHost(hostName, port);
        consumersTable.getItems().add(remoteHost);
        addConsumer(remoteHost);
    }
}

From source file:com.synopsys.integration.blackduck.configuration.BlackDuckServerConfigBuilder.java

public int getTimemoutInSeconds() {
    return NumberUtils.toInt(builderProperties.get(TIMEOUT_KEY),
            BlackDuckServerConfigBuilder.DEFAULT_TIMEOUT_SECONDS);
}

From source file:com.omertron.thetvdbapi.TheTVDBApi.java

/**
 * Convert a string to a number and then validate it
 *
 * @param number/*from w w w. j a  va2  s  . c o  m*/
 * @return
 */
private boolean isValidNumber(String number) {
    return isValidNumber(NumberUtils.toInt(number, 0));
}

From source file:com.kegare.caveworld.util.CaveUtils.java

public static boolean biomeFilter(BiomeGenBase biome, String filter) {
    if (biome == null || Strings.isNullOrEmpty(filter)) {
        return false;
    }//from  w  w  w  .java2 s  .  c  o m

    if (biome.biomeID == NumberUtils.toInt(filter, -1) || containsIgnoreCase(biome.biomeName, filter)) {
        return true;
    }

    try {
        if (BiomeDictionary.isBiomeOfType(biome, Type.valueOf(filter.toUpperCase()))) {
            return true;
        }
    } catch (Throwable e) {
    }

    try {
        if (blockFilter(new BlockEntry(biome.topBlock, biome.field_150604_aj), filter)) {
            return true;
        }
    } catch (Throwable e) {
    }

    try {
        if (blockFilter(new BlockEntry(biome.fillerBlock, biome.field_76754_C), filter)) {
            return true;
        }
    } catch (Throwable e) {
    }

    try {
        BiomeType type = BiomeType.valueOf(filter.toUpperCase());

        if (type != null) {
            for (BiomeEntry entry : BiomeManager.getBiomes(type)) {
                if (entry.biome.biomeID == biome.biomeID) {
                    return true;
                }
            }
        }
    } catch (Throwable e) {
    }

    return false;
}

From source file:com.synopsys.integration.blackduck.configuration.BlackDuckServerConfigBuilder.java

public int getProxyPort() {
    return NumberUtils.toInt(builderProperties.get(PROXY_PORT_KEY), 0);
}

From source file:com.erudika.para.rest.Api1.java

protected final Inflector<ContainerRequestContext, Response> linksHandler() {
    return new Inflector<ContainerRequestContext, Response>() {
        public Response apply(ContainerRequestContext ctx) {
            MultivaluedMap<String, String> params = ctx.getUriInfo().getQueryParameters();
            MultivaluedMap<String, String> pathp = ctx.getUriInfo().getPathParameters();
            String id = pathp.getFirst(Config._ID);
            String type = pathp.getFirst(Config._TYPE);
            String id2 = pathp.getFirst("id2");
            String type2 = pathp.getFirst("type2");
            App app = RestUtils.getPrincipalApp();

            if (app == null) {
                return RestUtils.getStatusResponse(Response.Status.BAD_REQUEST);
            }/*from  w  ww  .  j  a  v  a  2 s .c  o  m*/

            String typeSingular = (type == null) ? null : ParaObjectUtils.getAllTypes(app).get(type);
            type = (typeSingular == null) ? type : typeSingular;

            id2 = StringUtils.isBlank(id2) ? params.getFirst(Config._ID) : id2;
            type2 = StringUtils.isBlank(type2) ? params.getFirst(Config._TYPE) : type2;

            ParaObject pobj = ParaObjectUtils.toObject(type);
            pobj.setId(id);
            pobj = dao.read(app.getAppIdentifier(), pobj.getId());

            Pager pager = new Pager();
            pager.setPage(NumberUtils.toLong(params.getFirst("page"), 0));
            pager.setSortby(params.getFirst("sort"));
            pager.setDesc(Boolean.parseBoolean(params.containsKey("desc") ? params.getFirst("desc") : "true"));
            pager.setLimit(NumberUtils.toInt(params.getFirst("limit"), pager.getLimit()));

            String childrenOnly = params.getFirst("childrenonly");

            if (pobj != null) {
                if (POST.equals(ctx.getMethod()) || PUT.equals(ctx.getMethod())) {
                    if (id2 != null) {
                        String linkid = pobj.link(id2);
                        if (linkid == null) {
                            return RestUtils.getStatusResponse(Response.Status.BAD_REQUEST,
                                    "Failed to create link.");
                        } else {
                            return Response.ok(linkid, MediaType.TEXT_PLAIN_TYPE).build();
                        }
                    } else {
                        return RestUtils.getStatusResponse(Response.Status.BAD_REQUEST,
                                "Parameters 'type' and 'id' are missing.");
                    }
                } else if (GET.equals(ctx.getMethod())) {
                    Map<String, Object> result = new HashMap<String, Object>();
                    if (type2 != null) {
                        if (id2 != null) {
                            return Response.ok(pobj.isLinked(type2, id2), MediaType.TEXT_PLAIN_TYPE).build();
                        } else {
                            List<ParaObject> items = new ArrayList<ParaObject>();
                            if (childrenOnly == null) {
                                if (params.containsKey("count")) {
                                    pager.setCount(pobj.countLinks(type2));
                                } else {
                                    items = pobj.getLinkedObjects(type2, pager);
                                }
                            } else {
                                if (params.containsKey("count")) {
                                    pager.setCount(pobj.countChildren(type2));
                                } else {
                                    if (params.containsKey("field") && params.containsKey("term")) {
                                        items = pobj.getChildren(type2, params.getFirst("field"),
                                                params.getFirst("term"), pager);
                                    } else {
                                        items = pobj.getChildren(type2, pager);
                                    }
                                }
                            }
                            result.put("items", items);
                            result.put("totalHits", pager.getCount());
                            return Response.ok(result).build();
                        }
                    } else {
                        return RestUtils.getStatusResponse(Response.Status.BAD_REQUEST,
                                "Parameter 'type' is missing.");
                    }
                } else if (DELETE.equals(ctx.getMethod())) {
                    if (type2 == null && id2 == null) {
                        pobj.unlinkAll();
                    } else if (type2 != null) {
                        if (id2 != null) {
                            pobj.unlink(type2, id2);
                        } else if (childrenOnly != null) {
                            pobj.deleteChildren(type2);
                        }
                    }
                    return Response.ok().build();
                }
            }
            return RestUtils.getStatusResponse(Response.Status.NOT_FOUND, "Object not found: " + id);
        }
    };
}

From source file:lineage2.gameserver.handler.admincommands.impl.AdminEditChar.java

/**
 * Method useAdminCommand.//from ww w.j a v a  2  s .  c o  m
 * @param comm Enum<?>
 * @param wordList String[]
 * @param fullString String
 * @param activeChar Player
 * @return boolean * @see lineage2.gameserver.handler.admincommands.IAdminCommandHandler#useAdminCommand(Enum<?>, String[], String, Player)
 */
@Override
public boolean useAdminCommand(Enum<?> comm, String[] wordList, String fullString, Player activeChar) {
    Commands command = (Commands) comm;
    if (activeChar.getPlayerAccess().CanRename) {
        if (fullString.startsWith("admin_settitle")) {
            try {
                String val = fullString.substring(15);
                GameObject target = activeChar.getTarget();
                Player player = null;
                if (target == null) {
                    return false;
                }
                if (target.isPlayer()) {
                    player = (Player) target;
                    player.setTitle(val);
                    player.sendMessage("Your title has been changed by a GM");
                    player.sendChanges();
                } else if (target.isNpc()) {
                    ((NpcInstance) target).setTitle(val);
                    target.decayMe();
                    target.spawnMe();
                }
                return true;
            } catch (StringIndexOutOfBoundsException e) {
                activeChar.sendMessage("You need to specify the new title.");
                return false;
            }
        } else if (fullString.startsWith("admin_setclass")) {
            try {
                String val = fullString.substring(15);
                int id = Integer.parseInt(val.trim());
                GameObject target = activeChar.getTarget();
                if ((target == null) || !target.isPlayer()) {
                    target = activeChar;
                }
                if (id > (ClassId.VALUES.length - 1)) {
                    activeChar.sendMessage(
                            "There are no classes over " + String.valueOf(ClassId.VALUES.length - 1) + "  id.");
                    return false;
                }
                Player player = target.getPlayer();
                player.setClassId(id, true, false);
                player.sendMessage("Your class has been changed by a GM");
                player.broadcastCharInfo();
                return true;
            } catch (StringIndexOutOfBoundsException e) {
                activeChar.sendMessage("You need to specify the new class id.");
                return false;
            }
        } else if (fullString.startsWith("admin_setname")) {
            try {
                String val = fullString.substring(14);
                GameObject target = activeChar.getTarget();
                Player player;
                if ((target != null) && target.isPlayer()) {
                    player = (Player) target;
                } else {
                    return false;
                }
                if (mysql.simple_get_int("count(*)", "characters", "`char_name` like '" + val + "'") > 0) {
                    activeChar.sendMessage("Name already exist.");
                    return false;
                }
                Log.add("Character " + player.getName() + " renamed to " + val + " by GM "
                        + activeChar.getName(), "renames");
                player.reName(val);
                player.sendMessage("Your name has been changed by a GM");
                return true;
            } catch (StringIndexOutOfBoundsException e) {
                activeChar.sendMessage("You need to specify the new name.");
                return false;
            }
        }
    }
    if (!activeChar.getPlayerAccess().CanEditChar && !activeChar.getPlayerAccess().CanViewChar) {
        return false;
    }
    if (fullString.equals("admin_current_player")) {
        showCharacterList(activeChar, null);
    } else if (fullString.startsWith("admin_character_list")) {
        try {
            String val = fullString.substring(21);
            Player target = GameObjectsStorage.getPlayer(val);
            showCharacterList(activeChar, target);
        } catch (StringIndexOutOfBoundsException e) {
        }
    } else if (fullString.startsWith("admin_show_characters")) {
        try {
            String val = fullString.substring(22);
            int page = Integer.parseInt(val);
            listCharacters(activeChar, page);
        } catch (StringIndexOutOfBoundsException e) {
        }
    } else if (fullString.startsWith("admin_find_character")) {
        try {
            String val = fullString.substring(21);
            findCharacter(activeChar, val);
        } catch (StringIndexOutOfBoundsException e) {
            activeChar.sendMessage("You didnt enter a character name to find.");
            listCharacters(activeChar, 0);
        }
    } else if (!activeChar.getPlayerAccess().CanEditChar) {
        return false;
    } else if (fullString.equals("admin_edit_character")) {
        editCharacter(activeChar);
    } else if (fullString.equals("admin_character_actions")) {
        showCharacterActions(activeChar);
    } else if (fullString.equals("admin_nokarma")) {
        setTargetKarma(activeChar, 0);
    } else if (fullString.startsWith("admin_setkarma")) {
        try {
            String val = fullString.substring(15);
            int karma = Integer.parseInt(val);
            setTargetKarma(activeChar, karma);
        } catch (StringIndexOutOfBoundsException e) {
            activeChar.sendMessage("Please specify new karma value.");
        }
    } else if (fullString.startsWith("admin_save_modifications")) {
        try {
            String val = fullString.substring(24);
            adminModifyCharacter(activeChar, val);
        } catch (StringIndexOutOfBoundsException e) {
            activeChar.sendMessage("Error while modifying character.");
            listCharacters(activeChar, 0);
        }
    } else if (fullString.equals("admin_rec")) {
        GameObject target = activeChar.getTarget();
        Player player = null;
        if ((target != null) && target.isPlayer()) {
            player = (Player) target;
        } else {
            return false;
        }
        player.setRecomHave(player.getRecomHave() + 1);
        player.sendMessage("You have been recommended by a GM");
        player.broadcastCharInfo();
    } else if (fullString.startsWith("admin_rec")) {
        try {
            String val = fullString.substring(10);
            int recVal = Integer.parseInt(val);
            GameObject target = activeChar.getTarget();
            Player player = null;
            if ((target != null) && target.isPlayer()) {
                player = (Player) target;
            } else {
                return false;
            }
            player.setRecomHave(player.getRecomHave() + recVal);
            player.sendMessage("You have been recommended by a GM");
            player.broadcastCharInfo();
        } catch (NumberFormatException e) {
            activeChar.sendMessage("Command format is //rec <number>");
        }
    } else if (fullString.startsWith("admin_sethero")) {
        GameObject target = activeChar.getTarget();
        Player player;
        if ((wordList.length > 1) && (wordList[1] != null)) {
            player = GameObjectsStorage.getPlayer(wordList[1]);
            if (player == null) {
                activeChar.sendMessage("Character " + wordList[1] + " not found in game.");
                return false;
            }
        } else if ((target != null) && target.isPlayer()) {
            player = (Player) target;
        } else {
            activeChar.sendMessage("You must specify the name or target character.");
            return false;
        }
        if (player.isHero()) {
            player.setHero(false);
            player.updatePledgeClass();
            player.removeSkill(SkillTable.getInstance().getInfo(395, 1));
            player.removeSkill(SkillTable.getInstance().getInfo(396, 1));
            player.removeSkill(SkillTable.getInstance().getInfo(1374, 1));
            player.removeSkill(SkillTable.getInstance().getInfo(1375, 1));
            player.removeSkill(SkillTable.getInstance().getInfo(1376, 1));
        } else {
            player.setHero(true);
            player.updatePledgeClass();
            player.addSkill(SkillTable.getInstance().getInfo(395, 1));
            player.addSkill(SkillTable.getInstance().getInfo(396, 1));
            player.addSkill(SkillTable.getInstance().getInfo(1374, 1));
            player.addSkill(SkillTable.getInstance().getInfo(1375, 1));
            player.addSkill(SkillTable.getInstance().getInfo(1376, 1));
        }
        player.sendSkillList();
        player.sendMessage("Admin has changed your hero status.");
        player.broadcastUserInfo();
    } else if (fullString.startsWith("admin_setnoble")) {
        GameObject target = activeChar.getTarget();
        Player player;
        if ((wordList.length > 1) && (wordList[1] != null)) {
            player = GameObjectsStorage.getPlayer(wordList[1]);
            if (player == null) {
                activeChar.sendMessage("Character " + wordList[1] + " not found in game.");
                return false;
            }
        } else if ((target != null) && target.isPlayer()) {
            player = (Player) target;
        } else {
            activeChar.sendMessage("You must specify the name or target character.");
            return false;
        }
        if (player.isNoble()) {
            Olympiad.removeNoble(player);
            player.setNoble(false);
            player.sendMessage("Admin changed your noble status, now you are not nobless.");
        } else {
            Olympiad.addNoble(player);
            player.setNoble(true);
            player.sendMessage("Admin changed your noble status, now you are Nobless.");
        }
        player.updatePledgeClass();
        player.updateNobleSkills();
        player.sendSkillList();
        player.broadcastUserInfo();
    } else if (fullString.startsWith("admin_setsex")) {
        GameObject target = activeChar.getTarget();
        Player player = null;
        if ((target != null) && target.isPlayer()) {
            player = (Player) target;
        } else {
            return false;
        }
        player.changeSex();
        player.sendMessage("Your gender has been changed by a GM");
        player.broadcastUserInfo();
    } else if (fullString.startsWith("admin_setcolor")) {
        try {
            String val = fullString.substring(15);
            GameObject target = activeChar.getTarget();
            Player player = null;
            if ((target != null) && target.isPlayer()) {
                player = (Player) target;
            } else {
                return false;
            }
            player.setNameColor(Integer.decode("0x" + val));
            player.sendMessage("Your name color has been changed by a GM");
            player.broadcastUserInfo();
        } catch (StringIndexOutOfBoundsException e) {
            activeChar.sendMessage("You need to specify the new color.");
        }
    } else if (fullString.startsWith("admin_add_exp_sp_to_character")) {
        addExpSp(activeChar);
    } else if (fullString.startsWith("admin_add_exp_sp")) {
        try {
            final String val = fullString.substring(16).trim();
            String[] vals = val.split(" ");
            long exp = NumberUtils.toLong(vals[0], 0L);
            int sp = vals.length > 1 ? NumberUtils.toInt(vals[1], 0) : 0;
            adminAddExpSp(activeChar, exp, sp);
        } catch (Exception e) {
            activeChar.sendMessage("Usage: //add_exp_sp <exp> <sp>");
        }
    } else if (fullString.startsWith("admin_trans")) {
        StringTokenizer st = new StringTokenizer(fullString);
        if (st.countTokens() > 1) {
            st.nextToken();
            int transformId = 0;
            try {
                transformId = Integer.parseInt(st.nextToken());
            } catch (Exception e) {
                activeChar.sendMessage("Specify a valid integer value.");
                return false;
            }
            if ((transformId != 0) && (activeChar.getTransformation() != 0)) {
                activeChar.sendPacket(Msg.YOU_ALREADY_POLYMORPHED_AND_CANNOT_POLYMORPH_AGAIN);
                return false;
            }
            activeChar.setTransformation(transformId);
            activeChar.sendMessage("Transforming...");
        } else {
            activeChar.sendMessage("Usage: //trans <ID>");
        }
    } else if (fullString.startsWith("admin_setsubclass")) {
        final GameObject target = activeChar.getTarget();
        if ((target == null) || !target.isPlayer()) {
            activeChar.sendPacket(Msg.SELECT_TARGET);
            return false;
        }
        final Player player = (Player) target;
        StringTokenizer st = new StringTokenizer(fullString);
        if (st.countTokens() > 1) {
            st.nextToken();
            int classId = Short.parseShort(st.nextToken());
            if (!player.addSubClass(classId, true, 0, 0, false, 0)) {
                activeChar.sendMessage(new CustomMessage(
                        "lineage2.gameserver.model.instances.L2VillageMasterInstance.SubclassCouldNotBeAdded",
                        activeChar));
                return false;
            }
            player.sendPacket(Msg.CONGRATULATIONS_YOU_HAVE_TRANSFERRED_TO_A_NEW_CLASS);
        } else {
            setSubclass(activeChar, player);
        }
    } else if (fullString.startsWith("admin_setfame")) {
        try {
            String val = fullString.substring(14);
            int fame = Integer.parseInt(val);
            setTargetFame(activeChar, fame);
        } catch (StringIndexOutOfBoundsException e) {
            activeChar.sendMessage("Please specify new fame value.");
        }
    } else if (fullString.startsWith("admin_setbday")) {
        String msgUsage = "Usage: //setbday YYYY-MM-DD";
        String date = fullString.substring(14);
        if ((date.length() != 10) || !Util.isMatchingRegexp(date, "[0-9]{4}-[0-9]{2}-[0-9]{2}")) {
            activeChar.sendMessage(msgUsage);
            return false;
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            dateFormat.parse(date);
        } catch (ParseException e) {
            activeChar.sendMessage(msgUsage);
        }
        if ((activeChar.getTarget() == null) || !activeChar.getTarget().isPlayer()) {
            activeChar.sendMessage("Please select a character.");
            return false;
        }
        if (!mysql.set("update characters set createtime = UNIX_TIMESTAMP('" + date + "') where obj_Id = "
                + activeChar.getTarget().getObjectId())) {
            activeChar.sendMessage(msgUsage);
            return false;
        }
        activeChar.sendMessage("New Birthday for " + activeChar.getTarget().getName() + ": " + date);
        activeChar.getTarget().getPlayer().sendMessage("Admin changed your birthday to: " + date);
    } else if (fullString.startsWith("admin_give_item")) {
        if (wordList.length < 3) {
            activeChar.sendMessage("Usage: //give_item id count <target>");
            return false;
        }
        int id = Integer.parseInt(wordList[1]);
        int count = Integer.parseInt(wordList[2]);
        if ((id < 1) || (count < 1) || (activeChar.getTarget() == null) || !activeChar.getTarget().isPlayer()) {
            activeChar.sendMessage("Usage: //give_item id count <target>");
            return false;
        }
        ItemFunctions.addItem(activeChar.getTarget().getPlayer(), id, count, true);
    } else if (fullString.startsWith("admin_add_bang")) {
        if (!Config.ALT_PCBANG_POINTS_ENABLED) {
            activeChar.sendMessage("Error! Pc Bang Points service disabled!");
            return true;
        }
        if (wordList.length < 1) {
            activeChar.sendMessage("Usage: //add_bang count <target>");
            return false;
        }
        int count = Integer.parseInt(wordList[1]);
        if ((count < 1) || (activeChar.getTarget() == null) || !activeChar.getTarget().isPlayer()) {
            activeChar.sendMessage("Usage: //add_bang count <target>");
            return false;
        }
        Player target = activeChar.getTarget().getPlayer();
        target.addPcBangPoints(count, false);
        activeChar.sendMessage("You have added " + count + " Pc Bang Points to " + target.getName());
    } else if (fullString.startsWith("admin_set_bang")) {
        if (!Config.ALT_PCBANG_POINTS_ENABLED) {
            activeChar.sendMessage("Error! Pc Bang Points service disabled!");
            return true;
        }
        if (wordList.length < 1) {
            activeChar.sendMessage("Usage: //set_bang count <target>");
            return false;
        }
        int count = Integer.parseInt(wordList[1]);
        if ((count < 1) || (activeChar.getTarget() == null) || !activeChar.getTarget().isPlayer()) {
            activeChar.sendMessage("Usage: //set_bang count <target>");
            return false;
        }
        Player target = activeChar.getTarget().getPlayer();
        target.setPcBangPoints(count);
        target.sendMessage("Your Pc Bang Points count is now " + count);
        target.sendPacket(new ExPCCafePointInfo(target, count, 1, 2, 12));
        activeChar.sendMessage("You have set " + target.getName() + "'s Pc Bang Points to " + count);
    } else if (fullString.startsWith("admin_reset_mentor_penalty")) {
        if (activeChar.getTarget().getPlayer() == null) {
            activeChar.sendMessage("You have no target selected.");
            return false;
        }
        if (Mentoring.getTimePenalty(activeChar.getTargetId()) > 0) {
            Mentoring.setTimePenalty(activeChar.getTargetId(), 0, -1);
            activeChar.getTarget().getPlayer().sendMessage("Your mentor penalty has been lifted by a GM.");
            activeChar.sendMessage(
                    activeChar.getTarget().getPlayer().getName() + "'s mentor penalty has been lifted.");
        } else {
            activeChar.sendMessage("The selected character has no penalty.");
            return false;
        }
    }
    return true;
}

From source file:ching.icecreaming.action.ResourceDescriptors.java

private boolean searchFilter(String searchField, String searchOper, String searchString, Object object1) {
    boolean result1 = true;
    String string1 = null;// w w w . j a va2  s.  com
    Integer integer1 = null;
    java.sql.Timestamp timestamp1 = null;
    org.joda.time.DateTime dateTime1 = null, dateTime2 = null;
    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");
    java.util.Date date1 = null;

    if (object1 instanceof String) {
        string1 = (String) object1;
        switch (searchOper) {
        case "eq":
            result1 = StringUtils.equals(string1, searchString);
            break;
        case "ne":
            result1 = !StringUtils.equals(string1, searchString);
            break;
        case "bw":
            result1 = StringUtils.startsWith(string1, searchString);
            break;
        case "bn":
            result1 = !StringUtils.startsWith(string1, searchString);
            break;
        case "ew":
            result1 = StringUtils.endsWith(string1, searchString);
            break;
        case "en":
            result1 = !StringUtils.endsWith(string1, searchString);
            break;
        case "cn":
            result1 = StringUtils.contains(string1, searchString);
            break;
        case "nc":
            result1 = !StringUtils.contains(string1, searchString);
            break;
        case "nu":
            result1 = StringUtils.isBlank(string1);
            break;
        case "nn":
            result1 = StringUtils.isNotBlank(string1);
            break;
        case "in":
        case "ni":
        case "lt":
        case "le":
        case "gt":
        case "ge":
        default:
            break;
        }
    } else if (object1 instanceof Integer) {
        if (NumberUtils.isNumber(searchString)) {
            integer1 = (Integer) object1;
            switch (searchOper) {
            case "eq":
                result1 = (NumberUtils.toInt(searchString, 0) == integer1.intValue());
                break;
            case "ne":
                result1 = (NumberUtils.toInt(searchString, 0) != integer1.intValue());
                break;
            case "lt":
                result1 = (NumberUtils.toInt(searchString, 0) > integer1.intValue());
                break;
            case "le":
                result1 = (NumberUtils.toInt(searchString, 0) >= integer1.intValue());
                break;
            case "gt":
                result1 = (NumberUtils.toInt(searchString, 0) < integer1.intValue());
                break;
            case "ge":
                result1 = (NumberUtils.toInt(searchString, 0) <= integer1.intValue());
                break;
            case "bw":
            case "bn":
            case "ew":
            case "en":
            case "cn":
            case "nc":
            case "in":
            case "ni":
            case "nu":
            case "nn":
            default:
                break;
            }
        }
    } else if (object1 instanceof java.sql.Timestamp || object1 instanceof java.util.Date) {
        if (object1 instanceof java.sql.Timestamp) {
            timestamp1 = (java.sql.Timestamp) object1;
            dateTime1 = new org.joda.time.DateTime(timestamp1.getTime());
        } else if (object1 instanceof java.util.Date) {
            date1 = (java.util.Date) object1;
            if (date1 != null)
                dateTime1 = new org.joda.time.DateTime(date1);
        }
        try {
            dateTime2 = dateTimeFormatter.parseDateTime(searchString);
        } catch (java.lang.IllegalArgumentException exception1) {
            dateTime2 = null;
        }
        if (dateTime2 != null && dateTime1 != null) {
            switch (searchOper) {
            case "eq":
                result1 = dateTime1.equals(dateTime2);
                break;
            case "ne":
                result1 = !dateTime1.equals(dateTime2);
                break;
            case "lt":
                result1 = dateTime1.isBefore(dateTime2);
                break;
            case "le":
                result1 = (dateTime1.isBefore(dateTime2) || dateTime1.equals(dateTime2));
                break;
            case "gt":
                result1 = dateTime1.isAfter(dateTime2);
                break;
            case "ge":
                result1 = (dateTime1.isAfter(dateTime2) || dateTime1.equals(dateTime2));
                break;
            case "bw":
            case "bn":
            case "ew":
            case "en":
            case "cn":
            case "nc":
            case "in":
            case "ni":
                break;
            case "nu":
                result1 = (timestamp1 == null);
                break;
            case "nn":
                result1 = (timestamp1 != null);
                break;
            default:
                break;
            }
        }
    }
    return !result1;
}

From source file:com.moviejukebox.plugin.TheTvDBPlugin.java

/**
 * Locate the specific DVD episode from the list of episodes
 *
 * @param episodeList/*  ww w  . ja  va2s.co  m*/
 * @param seasonNumber
 * @param episodeNumber
 * @return
 */
private static Episode findDvdEpisode(List<Episode> episodeList, int seasonNumber, int episodeNumber) {
    if (episodeList == null || episodeList.isEmpty()) {
        return null;
    }

    for (Episode episode : episodeList) {
        int dvdSeason = NumberUtils.toInt(episode.getDvdSeason(), -1);
        int dvdEpisode = (int) NumberUtils.toFloat(episode.getDvdEpisodeNumber(), -1.0f);

        if ((dvdSeason == seasonNumber) && (dvdEpisode == episodeNumber)) {
            return episode;
        }
    }
    return null;
}