Example usage for org.apache.commons.lang3 StringUtils isNumeric

List of usage examples for org.apache.commons.lang3 StringUtils isNumeric

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils isNumeric.

Prototype

public static boolean isNumeric(final CharSequence cs) 

Source Link

Document

Checks if the CharSequence contains only Unicode digits.

Usage

From source file:de.alpharogroup.wicket.js.addon.core.PercentNumberFormatTextValue.java

/**
 * Check string.//from w  ww  . j  a va2 s. c o m
 *
 * @param value
 *            the value
 * @return the integer
 */
private Integer checkString(final String value) {
    Integer val = 50;
    if (value != null && !value.isEmpty()) {
        if (value.endsWith("%")) {
            final String sVal = value.substring(0, value.length() - 1);
            if (StringUtils.isNumeric(sVal)) {
                val = Integer.valueOf(sVal);
            }
        } else {
            if (StringUtils.isNumeric(value)) {
                val = Integer.valueOf(value);
            }

        }
    }
    return val;
}

From source file:com.nike.cerberus.endpoints.admin.GetSDBMetaData.java

/**
 * validates that the limit query is a valid number >= 1
 * @param limitQueryValue/*www  .  ja  v a  2  s. c o  m*/
 */
protected void validateLimitQuery(String limitQueryValue) {
    if (!StringUtils.isNumeric(limitQueryValue) || Integer.parseInt(limitQueryValue) < 1) {
        throw ApiException.newBuilder()
                .withApiErrors(new ApiErrorBase(DefaultApiError.INVALID_QUERY_PARAMS.getName(),
                        DefaultApiError.INVALID_QUERY_PARAMS.getErrorCode(),
                        String.format("limit query param must be an int >= 1, '%s' given", limitQueryValue),
                        DefaultApiError.INVALID_QUERY_PARAMS.getHttpStatusCode()))
                .build();
    }
}

From source file:com.glaf.core.web.springmvc.MxDBUploadJsonController.java

@RequestMapping
public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setContentType("text/html; charset=UTF-8");

    LoginContext loginContext = RequestUtils.getLoginContext(request);

    // ???//from   ww  w . j a v a2  s .c o  m
    String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp", "swf" };
    // ?
    long maxSize = FileUtils.MB_SIZE * 5;

    String allowSize = CustomProperties.getString("upload.maxSize");
    if (StringUtils.isEmpty(allowSize)) {
        allowSize = SystemProperties.getString("upload.maxSize");
    }

    if (StringUtils.isNotEmpty(allowSize) && StringUtils.isNumeric(allowSize)) {
        maxSize = Long.parseLong(allowSize);
    }

    MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
    String businessKey = request.getParameter("businessKey");
    String serviceKey = request.getParameter("serviceKey");
    Map<String, MultipartFile> fileMap = req.getFileMap();
    Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet();
    for (Entry<String, MultipartFile> entry : entrySet) {
        MultipartFile mFile = entry.getValue();
        if (mFile.getOriginalFilename() != null && mFile.getSize() > 0) {
            // ?
            if (mFile.getSize() > maxSize) {
                response.getWriter().write(getError("??"));
                return;
            }
            String fileName = mFile.getOriginalFilename();
            // ??
            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            if (!Arrays.<String>asList(fileTypes).contains(fileExt)) {
                response.getWriter().write(getError("??????"));
                return;
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String newFileName = df.format(new Date()) + "_" + new Random().nextInt(10000) + "." + fileExt;
            try {
                DataFile dataFile = new BlobItemEntity();
                dataFile.setBusinessKey(businessKey);
                dataFile.setCreateBy(loginContext.getActorId());
                dataFile.setCreateDate(new Date());
                dataFile.setFileId(newFileName);
                dataFile.setLastModified(System.currentTimeMillis());
                dataFile.setName(fileName);
                if (StringUtils.isNotEmpty(serviceKey)) {
                    dataFile.setServiceKey(serviceKey);
                } else {
                    dataFile.setServiceKey("IMG_" + loginContext.getActorId());
                }
                dataFile.setData(mFile.getBytes());
                dataFile.setFilename(fileName);
                dataFile.setType(fileExt);
                dataFile.setSize(mFile.getSize());
                dataFile.setStatus(1);
                blobService.insertBlob(dataFile);
            } catch (Exception ex) {
                ex.printStackTrace();
                response.getWriter().write(getError(""));
                return;
            }

            JSONObject object = new JSONObject();
            object.put("error", 0);
            object.put("url", request.getContextPath() + "/rs/blob/file/" + newFileName);
            response.getWriter().write(object.toString());
        }
    }
}

From source file:ljpf.versions.Version.java

public static Version parse(final String version) {
    final String[] split = PATTERN.split(version);

    if (split.length < 1) {
        throw new IllegalArgumentException("Version must have at least 2 components");
    }// ww  w  .j  av a 2  s . co  m

    Integer[] versionDigits = new Integer[3];
    String info = null;

    for (int i = 0; i < split.length; i++) {

        if (!StringUtils.isNumeric(split[i])) {
            info = extractInfo(split, i);
        } else {
            versionDigits[i] = Integer.valueOf(split[i]);
        }
    }

    return new Version(versionDigits[0], versionDigits[1], versionDigits[2], info);
}

From source file:io.stallion.users.UserAdder.java

public void execute(CommandOptionsBase options, String action) throws Exception {

    Log.info("Settings: siteName {0} email password {1}", Settings.instance().getSiteName(),
            Settings.instance().getEmail().getPassword());

    Scanner scanner = new Scanner(System.in);
    Console console = System.console();

    if (empty(action)) {
        //System.out.print("Create new user or edit existing? (new/edit): ");

        //String newEdit = scanner.next();

        System.out.print("Create new user or edit existing? (new/edit): ");
        //String newEdit = console.readLine("Create new user or edit existing? (new/edit): ");
        action = scanner.nextLine();/*ww w.  j  a v  a2 s. c  om*/
    }
    User user = null;
    if ("new".equals(action)) {
        user = new User();
        user.setPredefined(true);
    } else if ("edit".equals(action)) {
        System.out.print("Enter the email, username, or ID of the user you wish to edit:");
        String idMaybe = scanner.next();
        if (StringUtils.isNumeric(idMaybe)) {
            user = (User) UserController.instance().forId(Long.parseLong(idMaybe));
        }
        if (user == null) {
            user = (User) UserController.instance().forUniqueKey("email", idMaybe);
        }
        if (user == null) {
            user = (User) UserController.instance().forUniqueKey("username", idMaybe);
        }
        if (user == null) {
            System.out.print("Could not find user for key: " + idMaybe);
            System.exit(1);
        }
    } else {
        System.out.print("Invalid choice. Choose either 'new' or 'edit'");
        System.exit(1);
    }

    System.out.print("User's given name: ");
    String givenName = scanner.nextLine();
    if (!empty(givenName)) {
        user.setGivenName(givenName);
    }

    System.out.print("User's family name: ");
    String familyName = scanner.nextLine();
    if (!empty(familyName)) {
        user.setFamilyName(familyName);
        user.setDisplayName(user.getGivenName() + " " + user.getFamilyName());
    }

    System.out.print("User's email: ");
    String email = scanner.nextLine();
    if (!empty(email)) {
        user.setEmail(email);
        user.setUsername(user.getEmail());
    }

    System.out.print("Enter password: ");
    String password = "";
    if (console != null) {
        password = new String(console.readPassword());
    } else {
        password = new String(scanner.nextLine());
    }
    //System.out.printf("password: \"%s\"\n", password);
    if (empty(password) && empty(user.getBcryptedPassword())) {
        throw new UsageException("You must set a password!");
    } else if (!empty(password)) {
        String hashed = BCrypt.hashpw(password, BCrypt.gensalt());
        user.setBcryptedPassword(hashed);
    }

    if (empty(user.getSecret())) {
        user.setSecret(RandomStringUtils.randomAlphanumeric(18));
    }
    if (empty(user.getEncryptionSecret())) {
        user.setEncryptionSecret(RandomStringUtils.randomAlphanumeric(36));
    }

    user.setPredefined(true);
    user.setRole(Role.ADMIN);
    user.setId(Context.dal().getTickets().nextId());
    user.setFilePath(GeneralUtils.slugify(user.getEmail() + "---" + user.getId().toString()) + ".json");
    UserController.instance().save(user);

    System.out.print("User saved with email " + user.getEmail() + " and id " + user.getId());

}

From source file:mb.MbAdministrator.java

public void increaseUserBalance() {
    Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();

    if (selectedUser == null || balanceIncrement == null || !StringUtils.isNumeric(balanceIncrement)) {
        JsfUtil.addErrorMessage(ResourceBundle.getBundle("localization.messages", locale)
                .getString("AdministratorUserBalance_failure"));
        return;// w w w. j ava  2 s .c  o m
    }
    double newBalance = selectedUser.getBalance() + Double.parseDouble(balanceIncrement);

    selectedUser.setBalance(newBalance);

    try {
        getEjbUser().edit(selectedUser);
        JsfUtil.addSuccessMessage(ResourceBundle.getBundle("localization.messages", locale)
                .getString("AdministratorUserBalance_success"));
    } catch (Exception e) {
        JsfUtil.addErrorMessage(ResourceBundle.getBundle("localization.messages", locale)
                .getString("AdministratorUserBalance_failure"));
    }
    setDefaultUserBalanceTableValue();
}

From source file:com.santhoshknn.sudoku.GridExtractor.java

/**
 * Parses the supplied input to extract a 9x9 grid of integers substituting
 * the supplied x with a 0//w w  w. j  av  a2s. c o  m
 *
 * @param input
 * @return extracted gridresponse
 */
public GridResponse parse(final String input) {

    int[][] grid = new int[9][9];
    String error = null;
    GridResponse response = new GridResponse();
    log.info("Parsing supplied input string to create sudoku grid");
    // Strip whitespaces if any
    String sanitized = StringUtils.deleteWhitespace(input);
    // Fail early. Check if the length is 161 (81 + 80 commas)
    if (StringUtils.isBlank(sanitized) || StringUtils.length(sanitized) != GRID_SIZE) {
        error = INPUT_LENGTH_INVALID;
    } else {
        String[] tokens = sanitized.split(",");
        int row = 0, col = 0;
        for (int k = 0; k < 81; k++) { // tokens = 81
            if (StringUtils.equals("x", tokens[k]))
                grid[row][col] = 0;
            else if (StringUtils.isNumeric(tokens[k])) {
                // What if the user enters a number > 9? However, accept 0
                // since it could mean an empty cell
                int number = Integer.parseInt(tokens[k]);
                if (number > 9) {
                    error = INVALID_NUMBER_ERROR + ":" + number;
                    break;
                }
                grid[row][col] = number;
            } else {
                // Invalid character. Fail
                error = INVALID_CHAR_ERROR;
                break;
            }
            col++;
            if ((k + 1) % 9 == 0) { // Update row & reset column
                row++;
                col = 0;
            }
        }
    }
    if (null == error)
        response.setGrid(grid);
    else {
        response.setError(error);
        log.error(error);
    }
    return response;
}

From source file:com.glaf.ui.web.springmvc.MxUserPortalController.java

@RequestMapping
public ModelAndView myPortal(ModelMap modelMap, HttpServletRequest request) {
    LoginContext loginContext = RequestUtils.getLoginContext(request);
    if (loginContext == null) {
        return new ModelAndView("/modules/login");
    }/*ww w  .  ja  va 2s. c o  m*/
    RequestUtils.setRequestParameterToAttribute(request);

    UserPanel userPanel = panelService.getUserPanel(loginContext.getActorId());
    if (userPanel == null) {
        userPanel = panelService.getUserPanel("system");
    }

    Map<String, Integer> panelPxMap = new java.util.HashMap<String, Integer>();
    Map<String, Integer> panelMap = new java.util.HashMap<String, Integer>();
    if (userPanel != null && userPanel.getPanelInstances() != null) {
        String layoutName = userPanel.getLayoutName();
        Set<PanelInstance> set = userPanel.getPanelInstances();
        Iterator<PanelInstance> iter = set.iterator();
        while (iter.hasNext()) {
            PanelInstance p = iter.next();
            if (StringUtils.isNumeric(p.getName())) {
                int pos = Math.abs(Integer.parseInt(p.getName()));
                if (pos > 0) {
                    panelPxMap.put(p.getPanelId(), pos);

                    if ("P2".equals(layoutName)) {
                        if (pos % 2 == 1) {
                            panelMap.put(p.getPanelId(), 0);
                        } else {
                            panelMap.put(p.getPanelId(), 1);
                        }
                    } else if ("P3".equals(layoutName)) {
                        if (pos % 3 == 1) {
                            panelMap.put(p.getPanelId(), 0);
                        } else if (pos % 3 == 2) {
                            panelMap.put(p.getPanelId(), 1);
                        } else if (pos % 3 == 0) {
                            panelMap.put(p.getPanelId(), 2);
                        }
                    } else {
                        panelMap.put(p.getPanelId(), 0);
                    }
                }
            }
        }
    }

    List<UserPortal> userPortals = userPortalService.getUserPortals(loginContext.getActorId());
    if (userPortals == null || userPortals.isEmpty()) {
        userPortals = userPortalService.getUserPortals("system");
        if (userPortals == null || userPortals.isEmpty()) {
            List<Panel> panels = panelService.getPanels("system");
            if (panels != null && !panels.isEmpty()) {
                int i = 100;
                for (Panel panel : panels) {
                    UserPortal p = new UserPortal();
                    p.setActorId(loginContext.getActorId());
                    p.setPanelId(panel.getId());
                    if (panelMap.get(panel.getId()) != null) {
                        p.setColumnIndex(panelMap.get(panel.getId()));
                    } else {
                        p.setColumnIndex(0);
                    }
                    if (panelPxMap.get(panel.getId()) != null) {
                        p.setPosition(panelPxMap.get(panel.getId()));
                    } else {
                        p.setPosition(i++);
                    }
                    userPortals.add(p);
                }
                userPortalService.save(loginContext.getActorId(), userPortals);
                userPortals = userPortalService.getUserPortals(loginContext.getActorId());
            }
        }
    }

    List<UserPortal> sysPortals = userPortalService.getUserPortals("system");

    if (userPortals == null) {
        userPortals = new java.util.ArrayList<UserPortal>();
    }

    if (sysPortals != null && !sysPortals.isEmpty()) {
        userPortals.addAll(sysPortals);
    }

    for (UserPortal p : userPortals) {
        String panelId = p.getPanelId();
        p.setPanel(panelService.getPanel(panelId));
    }

    modelMap.put("userPanel", userPanel);
    modelMap.put("userPortals", userPortals);

    return new ModelAndView("/modules/ui/portal/myPortal", modelMap);
}

From source file:forge.game.cost.CostPart.java

/**
 * Convert amount.//from   ww w .ja va 2 s  . c  o  m
 * 
 * @return the integer
 */
public final Integer convertAmount() {
    return StringUtils.isNumeric(amount) ? Integer.parseInt(amount) : null;
}

From source file:com.moviejukebox.plugin.poster.MovieDbPosterPlugin.java

@Override
public String getIdFromMovieInfo(String title, String searchYear) {
    List<MovieInfo> movieList;
    try {/* w  w w  .j  a v a  2s  .  c o m*/
        int movieYear = 0;
        if (StringTools.isValidString(searchYear) && StringUtils.isNumeric(searchYear)) {
            movieYear = Integer.parseInt(searchYear);
        }

        ResultList<MovieInfo> result = tmdb.searchMovie(title, 0, languageCode, INCLUDE_ADULT, movieYear, 0,
                SearchType.PHRASE);
        movieList = result.getResults();
    } catch (MovieDbException ex) {
        LOG.warn("Failed to get TMDB ID for {} ({}) - {}", title, searchYear, ex.getMessage());
        return Movie.UNKNOWN;
    }

    if (movieList.isEmpty()) {
        return Movie.UNKNOWN;
    }

    if (movieList.size() == 1) {
        // Only one movie so return that id
        return String.valueOf(movieList.get(0).getId());
    }

    for (MovieInfo moviedb : movieList) {
        if (Compare.movies(moviedb, title, searchYear, TheMovieDbPlugin.SEARCH_MATCH)) {
            return String.valueOf(moviedb.getId());
        }
    }

    return Movie.UNKNOWN;
}