Example usage for org.apache.commons.lang StringUtils isWhitespace

List of usage examples for org.apache.commons.lang StringUtils isWhitespace

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils isWhitespace.

Prototype

public static boolean isWhitespace(String str) 

Source Link

Document

Checks if the String contains only whitespace.

Usage

From source file:org.openlegacy.terminal.web.render.support.DefaultElementsProvider.java

@Override
public Element createTextarea(Element rootTag, TerminalField field) {
    Element textarea = createTag(rootTag, HtmlConstants.TEXTAREA);
    if (field != null) {
        populateCommonAttributes(textarea, field);
        if (field.isMultyLine()) {
            int rows = field.getEndPosition().getRow() - field.getPosition().getRow() + 1;
            int columns = field.getEndPosition().getColumn() - field.getPosition().getColumn();
            textarea.setAttribute(HtmlConstants.COLUMNS, String.valueOf(columns));
            textarea.setAttribute(HtmlConstants.STYLE,
                    MessageFormat.format("{0};height:{1}px", textarea.getAttribute(HtmlConstants.STYLE),
                            String.valueOf(getProportionHandler().toHeight(rows + 1) - 5)));
            ;//from   ww w  .  j av  a2  s . c  o m
        } else {
            textarea.setAttribute(HtmlConstants.ROWS, "1");
            textarea.setAttribute(HtmlConstants.COLUMNS, String.valueOf(field.getLength()));
        }
        textarea.setAttribute(HtmlConstants.ONKEYPRESS,
                MessageFormat.format("return (this.value.length <= {0});", field.getLength()));

        if (field.isUppercase() || openLegacyProperties.isUppercaseInput()) {
            textarea.setAttribute(HtmlConstants.STYLE,
                    textarea.getAttribute(HtmlConstants.STYLE) + ";text-transform:uppercase;");
        }

        String value = field.getValue();
        if (!StringUtils.isWhitespace(value)) {
            Text textNode = rootTag.getOwnerDocument().createTextNode(value);
            textarea.appendChild(textNode);
        }

        String fieldName = HtmlNamingUtil.getFieldName(field);
        textarea.setAttribute(HtmlConstants.NAME, fieldName);
    }
    rootTag.appendChild(textarea);
    return textarea;

}

From source file:org.openmrs.api.db.hibernate.HibernateContextDAO.java

/**
 * @see org.openmrs.api.db.ContextDAO#authenticate(java.lang.String, java.lang.String)
 *//*from  ww w  .j  av  a 2  s.c  o m*/
public User authenticate(String login, String password) throws ContextAuthenticationException {

    String errorMsg = "Invalid username and/or password: " + login;

    Session session = sessionFactory.getCurrentSession();

    User candidateUser = null;

    if (login != null) {
        //if username is blank or white space character(s)
        if (StringUtils.isEmpty(login) || StringUtils.isWhitespace(login)) {
            throw new ContextAuthenticationException(errorMsg);
        }

        // loginWithoutDash is used to compare to the system id
        String loginWithDash = login;
        if (login.matches("\\d{2,}")) {
            loginWithDash = login.substring(0, login.length() - 1) + "-" + login.charAt(login.length() - 1);
        }

        try {
            candidateUser = (User) session.createQuery(
                    "from User u where (u.username = ? or u.systemId = ? or u.systemId = ?) and u.retired = '0'")
                    .setString(0, login).setString(1, login).setString(2, loginWithDash).uniqueResult();
        } catch (HibernateException he) {
            log.error("Got hibernate exception while logging in: '" + login + "'", he);
        } catch (Exception e) {
            log.error("Got regular exception while logging in: '" + login + "'", e);
        }
    }

    // only continue if this is a valid username and a nonempty password
    if (candidateUser != null && password != null) {
        if (log.isDebugEnabled()) {
            log.debug("Candidate user id: " + candidateUser.getUserId());
        }

        String lockoutTimeString = candidateUser
                .getUserProperty(OpenmrsConstants.USER_PROPERTY_LOCKOUT_TIMESTAMP, null);
        Long lockoutTime = null;
        if (lockoutTimeString != null && !lockoutTimeString.equals("0")) {
            try {
                // putting this in a try/catch in case the admin decided to put junk into the property
                lockoutTime = Long.valueOf(lockoutTimeString);
            } catch (NumberFormatException e) {
                log.debug("bad value stored in " + OpenmrsConstants.USER_PROPERTY_LOCKOUT_TIMESTAMP
                        + " user property: " + lockoutTimeString);
            }
        }

        // if they've been locked out, don't continue with the authentication
        if (lockoutTime != null) {
            // unlock them after 5 mins, otherwise reset the timestamp
            // to now and make them wait another 5 mins
            if (System.currentTimeMillis() - lockoutTime > 300000) {
                candidateUser.setUserProperty(OpenmrsConstants.USER_PROPERTY_LOGIN_ATTEMPTS, "0");
                candidateUser.removeUserProperty(OpenmrsConstants.USER_PROPERTY_LOCKOUT_TIMESTAMP);
                saveUserProperties(candidateUser);
            } else {
                candidateUser.setUserProperty(OpenmrsConstants.USER_PROPERTY_LOCKOUT_TIMESTAMP,
                        String.valueOf(System.currentTimeMillis()));
                throw new ContextAuthenticationException(
                        "Invalid number of connection attempts. Please try again later.");
            }
        }

        String passwordOnRecord = (String) session
                .createSQLQuery("select password from users where user_id = ?")
                .addScalar("password", StandardBasicTypes.STRING).setInteger(0, candidateUser.getUserId())
                .uniqueResult();

        String saltOnRecord = (String) session.createSQLQuery("select salt from users where user_id = ?")
                .addScalar("salt", StandardBasicTypes.STRING).setInteger(0, candidateUser.getUserId())
                .uniqueResult();

        // if the username and password match, hydrate the user and return it
        if (passwordOnRecord != null && Security.hashMatches(passwordOnRecord, password + saltOnRecord)) {
            // hydrate the user object
            candidateUser.getAllRoles().size();
            candidateUser.getUserProperties().size();
            candidateUser.getPrivileges().size();

            // only clean up if the were some login failures, otherwise all should be clean
            Integer attempts = getUsersLoginAttempts(candidateUser);
            if (attempts > 0) {
                candidateUser.setUserProperty(OpenmrsConstants.USER_PROPERTY_LOGIN_ATTEMPTS, "0");
                candidateUser.removeUserProperty(OpenmrsConstants.USER_PROPERTY_LOCKOUT_TIMESTAMP);
                saveUserProperties(candidateUser);
            }

            // skip out of the method early (instead of throwing the exception)
            // to indicate that this is the valid user
            return candidateUser;
        } else {
            // the user failed the username/password, increment their
            // attempts here and set the "lockout" timestamp if necessary
            Integer attempts = getUsersLoginAttempts(candidateUser);

            attempts++;

            Integer allowedFailedLoginCount = 7;

            try {
                allowedFailedLoginCount = Integer.valueOf(Context.getAdministrationService()
                        .getGlobalProperty(OpenmrsConstants.GP_ALLOWED_FAILED_LOGINS_BEFORE_LOCKOUT).trim());
            } catch (Exception ex) {
                log.error("Unable to convert the global property "
                        + OpenmrsConstants.GP_ALLOWED_FAILED_LOGINS_BEFORE_LOCKOUT
                        + "to a valid integer. Using default value of 7");
            }

            if (attempts > allowedFailedLoginCount) {
                // set the user as locked out at this exact time
                candidateUser.setUserProperty(OpenmrsConstants.USER_PROPERTY_LOCKOUT_TIMESTAMP,
                        String.valueOf(System.currentTimeMillis()));
            } else {
                candidateUser.setUserProperty(OpenmrsConstants.USER_PROPERTY_LOGIN_ATTEMPTS,
                        String.valueOf(attempts));
            }

            saveUserProperties(candidateUser);
        }
    }

    // throw this exception only once in the same place with the same
    // message regardless of username/pw combo entered
    log.info("Failed login attempt (login=" + login + ") - " + errorMsg);
    throw new ContextAuthenticationException(errorMsg);

}

From source file:org.owasp.jbrofuzz.payloads.PayloadsRowListener.java

/**
 * <p>// w w  w.j  a  va  2 s  .  c  om
 * Implemented for each row selected in the payloads table.
 * </p>
 * 
 * @param event
 *            ListSelectionEvent
 */
public void valueChanged(final ListSelectionEvent event) {

    if (event.getValueIsAdjusting()) {
        return;
    }

    String payload;
    final int d = payloadsPanel.payloadsTable.getSelectedRow();
    try {

        payload = (String) payloadsPanel.payloadsTableModel.getValueAt(d, 0);

    } catch (final IndexOutOfBoundsException e) {
        return;
    }

    payloadsPanel.payloadInfoTextArea.setText("\nPayload Length: " + payload.length() + "\n\n" + "Is Numeric? "
            + StringUtils.isNumeric(payload) + "\n\n" + "Is Alpha? " + StringUtils.isAlpha(payload) + "\n\n"
            + "Has whitespaces? " + StringUtils.isWhitespace(payload) + "\n\n");
    payloadsPanel.payloadInfoTextArea.setCaretPosition(0);

}

From source file:org.raml.parser.visitor.YamlDocumentSuggester.java

private int calculateContextColumn(String context) {
    int column = 0;
    while (column < context.length() && StringUtils.isWhitespace(context.charAt(column) + "")) {
        column++;//from   w w  w.j a v a2s.  co m
    }
    return column;
}

From source file:org.seasar.uruma.eclipath.classpath.EclipseClasspath.java

public boolean isWhitespaceText(Node node) {
    if (node.getNodeType() == Node.TEXT_NODE) {
        String text = ((Text) node).getData();
        return StringUtils.isWhitespace(text);
    } else {/*from  www  .  ja v a2 s  . c o m*/
        return false;
    }
}

From source file:org.sonar.ide.idea.utils.IdeaFolderResourceUtils.java

@Nullable
@Override//  w w w.j ava 2s. c  o  m
public String getPackageName(VirtualFile file) {
    PsiDirectory directory = fileManager.findDirectory(file);
    PsiPackage aPackage = directory == null ? null : JavaDirectoryService.getInstance().getPackage(directory);
    if (aPackage.getClasses().length == 0) {
        aPackage = null; //Sonar doesnt support packages without classes - return null package (i.e. use module request)
    }
    String result = aPackage == null ? null : aPackage.getQualifiedName();

    if (StringUtils.isWhitespace(result))
        result = null;
    return result;
}

From source file:org.sonar.ide.intellij.inspection.InspectionUtils.java

private static String getJavaComponentKey(final String moduleKey, final PsiJavaFile file) {
    return ApplicationManager.getApplication().runReadAction(new Computable<String>() {
        @Override/*from   w  ww. j a  v  a  2s .  co m*/
        public String compute() {
            String result = null;
            String packageName = file.getPackageName();
            if (StringUtils.isWhitespace(packageName)) {
                packageName = DEFAULT_PACKAGE_NAME;
            }
            String fileName = StringUtils.substringBeforeLast(file.getName(), ".");
            if (moduleKey != null) {
                result = new StringBuilder().append(moduleKey).append(DELIMITER).append(packageName)
                        .append(PACKAGE_DELIMITER).append(fileName).toString();
            }
            return result;
        }
    });
}

From source file:org.sonar.ide.shared.AbstractResourceUtils.java

/**
 * Returns component key for specified file.
 * Examples://from   ww w  . j a  va 2 s . c o  m
 * <ul>
 * <li>org.example:myproject:[default]</li>
 * <li>org.example:myproject:org.example.mypackage</li>
 * <li>org.example:myproject:[root]<li>
 * <li>org.example:myproject:mydirectory/mysubdirectory</li>
 * </ul>
 *
 * @param file file
 * @return component key or null, if unable to determine
 */
public final String getComponentKey(MODEL file) {
    String result = null;
    String projectKey = getProjectKey(file);
    String componentName;
    if (isJavaFile(file)) {
        componentName = getPackageName(file);
        if (StringUtils.isWhitespace(componentName)) {
            componentName = DEFAULT_PACKAGE_NAME;
        }
    } else {
        componentName = getDirectoryPath(file);
        if (StringUtils.isWhitespace(componentName)) {
            componentName = ROOT;
        }
    }
    if (projectKey != null && componentName != null) {
        result = new StringBuilder().append(projectKey).append(DELIMITER).append(componentName).toString();
    }
    LOG.info("Component key for {} is {}", file, result);
    return result;
}

From source file:org.sonar.plugins.xml.checks.IllegalTabCheck.java

/**
 * Find Illegal tabs in whitespace.//w  w  w  .ja  v a  2 s.c o m
 */
private void findIllegalTabs(Node node) {

    // check whitespace in the node
    for (Node sibling = node.getPreviousSibling(); sibling != null; sibling = sibling.getPreviousSibling()) {
        if (sibling.getNodeType() == Node.TEXT_NODE) {
            String text = sibling.getTextContent();
            if (StringUtils.isWhitespace(text) && StringUtils.contains(text, "\t")) {
                createNewViolation(SaxParser.getLineNumber(sibling));
                break; // one violation for this node is enough
            }
        }
    }

    // check the child elements of the node
    for (Node child = node.getFirstChild(); !validationReady && child != null; child = child.getNextSibling()) {
        switch (child.getNodeType()) {
        case Node.ELEMENT_NODE:
            findIllegalTabs(child);
            break;
        default:
            break;
        }
    }
}

From source file:org.sonar.plugins.xml.checks.IndentCheck.java

/**
 * Collect the indenting whitespace before this node.
 *//*  w ww  .j a v a2  s. c  o m*/
private int collectIndent(Node node) {
    int indent = 0;
    for (Node sibling = node.getPreviousSibling(); sibling != null; sibling = sibling.getPreviousSibling()) {
        switch (sibling.getNodeType()) {
        case Node.COMMENT_NODE:
        case Node.ELEMENT_NODE:
            return indent;
        case Node.TEXT_NODE:
            String text = sibling.getTextContent();
            if (StringUtils.isWhitespace(text)) {
                for (int i = text.length() - 1; i >= 0; i--) {
                    char c = text.charAt(i);
                    switch (c) {
                    case '\n':
                        // newline found, we are done
                        return indent;
                    case '\t':
                        // add tabsize
                        indent += tabSize;
                        break;
                    case ' ':
                        // add one space
                        indent++;
                        break;
                    default:
                        break;
                    }
                }
            } else {
                // non whitespace found, we are done
                return indent;
            }
            break;
        default:
            break;
        }
    }
    return indent;
}