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

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

Introduction

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

Prototype

public static boolean isNumber(final String str) 

Source Link

Document

Checks whether the String a valid Java number.

Valid numbers include hexadecimal marked with the 0x or 0X qualifier, octal numbers, scientific notation and numbers marked with a type qualifier (e.g.

Usage

From source file:org.structr.schema.action.Function.java

public static Object numberOrString(final String value) {

    if (value != null) {

        if ("true".equals(value.toLowerCase())) {
            return true;
        }//from   w ww .  ja  v a2  s  .  c o  m

        if ("false".equals(value.toLowerCase())) {
            return false;
        }

        if (NumberUtils.isNumber(value)) {
            return NumberUtils.createNumber(value);
        }
    }

    return value;
}

From source file:org.ut.biolab.medsavant.MedSavantServlet.java

private void loadConfiguration() throws ServletException {
    String host = null;/*from w  w  w. j a va  2s  .  co m*/
    String uname = null;
    String pass = null;
    String dbase = null;
    String maxSimultaneousUploadsStr = null;
    int p = -1;
    try {
        Properties props = new Properties();
        InputStream in = getConfigInputStream();
        props.load(in);
        in.close();

        host = props.getProperty("host", "");
        uname = props.getProperty("username", "");
        pass = props.getProperty("password", "");
        dbase = props.getProperty("db", "");
        maxSimultaneousUploadsStr = props.getProperty("max_simultaneous_uploads", "").trim();
        String portStr = props.getProperty("port", "-1").trim();
        if (StringUtils.isBlank(portStr) || !NumberUtils.isNumber(portStr)) {
            LOG.error("No port specified in configuration, cannot continue");
        }
        if (maxSimultaneousUploadsStr == null) {
            throw new ServletException("No maximum number of simultaneous uploads specified.  Cannot continue");
        }
        p = Integer.parseInt(portStr);
        if (p <= 0) {
            throw new ServletException(
                    "Illegal port specified in configuration: " + portStr + ", cannot continue.");
        }

        maxSimultaneousUploads = Integer.parseInt(maxSimultaneousUploadsStr);
        if (maxSimultaneousUploads <= 0) {
            throw new ServletException("Illegal number of maximum simultaneous uploads in configuration: "
                    + maxSimultaneousUploadsStr + ", cannot continue.");
        }

        uploadSem = new Semaphore(maxSimultaneousUploads, true);
        if (StringUtils.isBlank(uname)) {
            throw new ServletException("No username specified in configuration file, cannot continue.");
        }
        if (StringUtils.isBlank(pass)) {
            throw new ServletException("No password specified in configuration file, cannot continue.");
        }
        if (StringUtils.isBlank(dbase)) {
            throw new ServletException("No database specified in configuration file, cannot continue.");
        }
        if (StringUtils.isBlank(host)) {
            throw new ServletException("No host specified in configuration file, cannot continue.");
        }
    } catch (IOException iex) {
        throw new ServletException("IO Exception reading config file, cannot continue: " + iex.getMessage());
    }
    this.medSavantServerHost = host;
    this.medSavantServerPort = p;
    this.username = uname;
    this.password = pass;
    this.db = dbase;

    LOG.info("Configured with:");
    LOG.info("Host = " + host);
    LOG.info("Port = " + p);
    LOG.info("Username = " + uname);
    LOG.info("Database = " + this.db);
}

From source file:org.wso2.carbon.identity.handler.event.account.lock.AccountLockHandler.java

/**
 * This is used to handle post authentication event in account lock handler
 *
 * @param event : Post Authentication Event
 * @throws EventException : EventException
 */// ww  w  .j  a v  a  2  s  . c o  m
private void handlePostAuthentication(Event event) throws EventException {

    AuthenticationContext authenticationContext = (AuthenticationContext) event.getEventProperties()
            .get(IdentityStoreConstants.AUTHENTICATION_CONTEXT);

    if (authenticationContext == null) {
        throw new EventException("No context found for authentication");
    }

    if (authenticationContext.isAuthenticated()) {
        User authenticatedUser = authenticationContext.getUser();
        //Handle locked state. Throws an exception if user is locked
        handleLockedState(authenticatedUser);

        //set user failed attempts to zero upon a successful attempt
        setUserFailedAttempts(authenticatedUser, 0);

    } else {
        //Authentication failure
        if (authenticationContext instanceof FailedAuthenticationContext) {
            //Get authentication failed user list. It is a list since multiple domains can have same username
            List<User> userList = ((FailedAuthenticationContext) authenticationContext).getFailedUsers();

            for (User user : userList) {
                try {
                    if (UserState.valueOf(user.getState()).isInGroup(UserState.Group.LOCKED)) {
                        //No need to process. Invalid credential, locked user
                        continue;
                    }

                    int userFailedAttemptsCount = 0;

                    //Read the failedCount claim
                    String userFailedAttemptsCountString = getUserClaimValue(user,
                            AccountConstants.FAILED_LOGIN_ATTEMPTS_CLAIM);
                    if (NumberUtils.isNumber(userFailedAttemptsCountString)) {
                        userFailedAttemptsCount = Integer.parseInt(userFailedAttemptsCountString);
                    }

                    //increase the failed count by 1
                    userFailedAttemptsCount++;

                    //if user failed count is more than maxFailedAttempts count, the account should be locked
                    if (userFailedAttemptsCount >= accountLockBean.getMaxFailedAttempts()) {
                        lockInvalidCredentialUserAccount(user);
                    } else {
                        // Set user failed attempts count
                        setUserFailedAttempts(user, userFailedAttemptsCount);
                    }
                } catch (IdentityStoreException | UserNotFoundException e) {
                    throw new EventException("Unexpected error: ", e);
                }
            }

        }
    }
}

From source file:org.wso2.carbon.identity.handler.event.account.lock.AccountLockHandler.java

/**
 * This is used to handle lock state in account lock handler
 *
 * @param user : user//from  ww  w.java 2s .  co  m
 * @throws EventException :EventException
 */
private void handleLockedState(User user) throws EventException {

    if (UserState.valueOf(user.getState()) == null) {
        if (log.isDebugEnabled()) {
            log.debug("Invalid user state: " + user.getState());
        }
        throw new EventException("Invalid user state: " + user.getState());
    }

    if (UserState.valueOf(user.getState()).isInGroup(UserState.Group.LOCKED)) {

        //Check user unlock time exceeds or not
        if (LOCKED_INVALID_CREDENTIAL__VERIFIED.toString().equals(user.getState())
                || LOCKED_INVALID_CREDENTIAL__UNVERIFIED.toString().equals(user.getState())) {
            String unlockedTimeString;
            try {
                unlockedTimeString = getUserClaimValue(user, AccountConstants.ACCOUNT_UNLOCK_TIME_CLAIM);

                if (NumberUtils.isNumber(unlockedTimeString)) {
                    long unlockTime = Long.parseLong(unlockedTimeString);
                    if (unlockTime != 0 && System.currentTimeMillis() >= unlockTime) {
                        if (log.isDebugEnabled()) {
                            log.debug("Unlocked user account: " + user.getUniqueUserId());
                        }

                        //Account state and  unlock email will be sent in post update claim handler.
                        setClaimInIdentityStore(user.getUniqueUserId(), AccountConstants.ACCOUNT_LOCKED_CLAIM,
                                String.valueOf(false), null);
                        return;
                    }
                }
            } catch (IdentityStoreException | UserNotFoundException e) {
                throw new EventException("Error reading account lock claim, user: " + user.getUniqueUserId(),
                        e);
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("User Account is locked: " + user.getUniqueUserId());
        }
        throw new EventException("User Account is locked: " + user.getUniqueUserId());
    }
}

From source file:org.wso2.carbon.identity.handler.event.account.lock.AccountLockHandler.java

/**
 * This is used to lock user account for invalid credentials
 *
 * @param user : user/*  ww  w  .j  a va  2  s.  c  o m*/
 * @throws EventException         EventException
 * @throws IdentityStoreException IdentityStoreException
 * @throws UserNotFoundException  UserNotFoundException
 */
private void lockInvalidCredentialUserAccount(User user)
        throws EventException, IdentityStoreException, UserNotFoundException {
    //Update lifecycle state to lock
    updateLifeCycleState(user, true, false);

    int failedLoginLockoutCountValue = 0;

    String failedLoginLockoutCountString = getUserClaimValue(user,
            AccountConstants.FAILED_LOGIN_LOCKOUT_COUNT_CLAIM);
    if (NumberUtils.isNumber(failedLoginLockoutCountString)) {
        failedLoginLockoutCountValue = Integer.parseInt(failedLoginLockoutCountString);
    }

    //Set a unlock time
    long lockTime = (long) (TimeUnit.MINUTES.toMillis(accountLockBean.getAccountLockTimeInMinutes())
            * Math.pow(accountLockBean.getLockedTimeRatio(), failedLoginLockoutCountValue));

    failedLoginLockoutCountValue++;

    long unlockTime = System.currentTimeMillis() + lockTime;

    Map<String, String> claims = new HashMap<>();
    claims.put(AccountConstants.ACCOUNT_LOCKED_CLAIM, String.valueOf(true));
    claims.put(AccountConstants.FAILED_LOGIN_ATTEMPTS_CLAIM, String.valueOf(0));
    claims.put(AccountConstants.ACCOUNT_UNLOCK_TIME_CLAIM, String.valueOf(unlockTime));
    claims.put(AccountConstants.FAILED_LOGIN_LOCKOUT_COUNT_CLAIM, String.valueOf(failedLoginLockoutCountValue));
    setClaimsInIdentityStore(user.getUniqueUserId(), claims, null);

    if (accountLockBean.isNotificationInternallyManage()) {
        triggerNotification(user.getUniqueUserId(), AccountConstants.EMAIL_TEMPLATE_TYPE_ACC_LOCKED);
    }
}

From source file:org.wso2.carbon.uuf.internal.deployment.AppCreator.java

private Configuration createConfiguration(AppReference appReference) {
    AppConfig appConfig = YamlFileParser.parse(appReference.getConfiguration(), AppConfig.class);
    Configuration configuration = new Configuration();
    configuration.setContextPath(appConfig.getContextPath());
    configuration.setThemeName(appConfig.getTheme());
    configuration.setLoginPageUri(appConfig.getLoginPageUri());
    configuration.setLogoutPageUri(appConfig.getLogoutPageUri());
    configuration.setAuthenticator(appConfig.getAuthenticator());
    Map<Integer, String> errorPageUris = appConfig.getErrorPages().entrySet().stream()
            .filter(entry -> NumberUtils.isNumber(entry.getKey()))
            .collect(toMap(entry -> Integer.valueOf(entry.getKey()), Map.Entry::getValue));
    configuration.setErrorPageUris(errorPageUris);
    configuration.setDefaultErrorPageUri(appConfig.getErrorPages().get("default"));
    configuration//from  ww w . ja  v a  2s.  com
            .setMenus(appConfig.getMenus().stream().map(AppConfig.Menu::toConfigurationMenu).collect(toList()));
    configuration
            .setAcceptingCsrfPatterns(Sets.newHashSet(appConfig.getSecurity().getCsrfPatterns().getAccept()));
    configuration
            .setRejectingCsrfPatterns(Sets.newHashSet(appConfig.getSecurity().getCsrfPatterns().getReject()));
    configuration
            .setAcceptingXssPatterns(Sets.newHashSet(appConfig.getSecurity().getXssPatterns().getAccept()));
    configuration
            .setRejectingXssPatterns(Sets.newHashSet(appConfig.getSecurity().getXssPatterns().getReject()));
    configuration.setResponseHeaders(appConfig.getSecurity().getResponseHeaders());
    configuration.setOther(appConfig.getOther());
    return configuration;
}

From source file:org.wso2.siddhi.extension.map.CreateFromXMLFunctionExtension.java

private Object getMapFromXML(OMElement parentElement) throws XMLStreamException {
    Map<Object, Object> topLevelMap = new HashMap<Object, Object>();
    Iterator iterator = parentElement.getChildElements();
    while (iterator.hasNext()) {
        OMElement streamAttributeElement = (OMElement) iterator.next();
        String key = streamAttributeElement.getQName().toString();
        Object value;/*from  w w w  .  j a va  2 s .c o  m*/
        if (streamAttributeElement.getFirstElement() != null) {
            value = getMapFromXML(streamAttributeElement);
        } else {
            String elementText = streamAttributeElement.getText();
            if (elementText.equals("true") || elementText.equals("false")) {
                value = Boolean.parseBoolean(elementText);
            } else {
                if (NumberUtils.isNumber(elementText)) {
                    try {
                        value = numberFormat.parse(elementText);
                    } catch (ParseException e) {
                        value = elementText;
                    }
                } else {
                    value = elementText;
                }
            }
        }
        topLevelMap.put(key, value);
    }
    return topLevelMap;
}

From source file:org.xwiki.filter.confluence.xml.internal.ConfluenceXMLPackage.java

public Collection<Integer> getAttachments(int pageId) {
    File folder = getAttachmentsFolder(pageId);

    Collection<Integer> attachments;
    if (folder.exists()) {
        String[] attachmentFolders = folder.list();

        attachments = new TreeSet<Integer>();
        for (String attachmentIdString : attachmentFolders) {
            if (NumberUtils.isNumber(attachmentIdString)) {
                attachments.add(Integer.valueOf(attachmentIdString));
            }/*  w  w w .  j  av  a2s .c  o  m*/
        }
    } else {
        attachments = Collections.emptyList();
    }

    return attachments;
}

From source file:org.xwiki.filter.confluence.xml.internal.ConfluenceXMLPackage.java

public Collection<Integer> getUsers() {
    File folder = getUsersFolder();

    Collection<Integer> users;
    if (folder.exists()) {
        String[] userFolders = folder.list();

        users = new TreeSet<Integer>();
        for (String userIdString : userFolders) {
            if (NumberUtils.isNumber(userIdString)) {
                users.add(Integer.valueOf(userIdString));
            }/*from   ww w .j ava2  s.c o  m*/
        }
    } else {
        users = Collections.emptyList();
    }

    return users;
}

From source file:org.xwiki.filter.confluence.xml.internal.ConfluenceXMLPackage.java

public Collection<Integer> getGroups() {
    File folder = getGroupsFolder();

    Collection<Integer> groups;
    if (folder.exists()) {
        String[] groupFolders = folder.list();

        groups = new TreeSet<Integer>();
        for (String groupIdString : groupFolders) {
            if (NumberUtils.isNumber(groupIdString)) {
                groups.add(Integer.valueOf(groupIdString));
            }//from  w ww . j  a  v  a  2  s.c o  m
        }
    } else {
        groups = Collections.emptyList();
    }

    return groups;
}