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

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

Introduction

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

Prototype

public static int length(String str) 

Source Link

Document

Gets a String's length or 0 if the String is null.

Usage

From source file:com.atlassian.jira.web.action.admin.EditApplicationProperties.java

protected void doValidation() {
    if (!TextUtils.stringSet(title)) {
        addError("title", getText("admin.errors.you.must.set.an.application.title"));
    }//from ww w  .j  a  v  a 2  s.c o  m

    if (StringUtils.length(title) > 255) {
        addError("title", getText("admin.errors.invalid.length.of.an.application.title"));
    }

    if (!UrlValidator.isValid(baseURL)) {
        addError("baseURL", getText("admin.errors.you.must.set.a.valid.base.url"));
    }

    if (!TextUtils.stringSet(emailFromHeaderFormat)) {
        addError("emailFromHeaderFormat", getText("admin.errors.you.must.set.a.valid.email.from.header"));
    }

    if (!TextUtils.stringSet(language)) {
        addError("language", getText("admin.errors.invalid.language.selected"));
    }

    // JRA-15966. Mode = Public and External User Management is an invalid combination.
    if (mode != null && mode.equalsIgnoreCase("public") && externalUM) {
        // Current JSP page does not allow errors to be shown for the radio button options, but just showing the
        // message on the mode setting is adequate.
        addError("mode", getText("admin.errors.invalid.mode.externalUM.combination"));
    }

    if (isSystemAdministrator()) {
        validateMimeForSysadmin();
    } else {
        if (StringUtils.isNotBlank(ieMimeSniffer)) {
            log.warn(getLoggedInUser().getName()
                    + " attempted to set Internet Explorer MIME setting without sysadmin permission");
            ieMimeSniffer = null;
        }
    }
    if (TextUtils.stringSet(maximumAuthenticationAttemptsAllowed)) {
        // is it a number
        try {
            final long maxAttemptsAllowed = Long.parseLong(maximumAuthenticationAttemptsAllowed);
            if (maxAttemptsAllowed <= 0) {
                addError("maximumAuthenticationAttemptsAllowed",
                        getText("admin.generalconfiguration.maximum.authentication.attempts.allowed.is.zero"));
            }
        } catch (NumberFormatException e) {
            addError("maximumAuthenticationAttemptsAllowed",
                    getText("admin.generalconfiguration.maximum.authentication.attempts.allowed.notanumber",
                            maximumAuthenticationAttemptsAllowed));
        }

    }
    if (TextUtils.stringSet(maximumLengthProjectNames)) {
        // is it a number
        try {
            final long maxProjectNameLength = Integer.parseInt(maximumLengthProjectNames);
            if (maxProjectNameLength <= 1) {
                addError("maximumLengthProjectNames",
                        getText("admin.generalconfiguration.maximum.length.project.names.is.too.small"));
            } else if (maxProjectNameLength > 150) {
                addError("maximumLengthProjectNames",
                        getText("admin.generalconfiguration.maximum.length.project.names.is.too.large"));
            }
        } catch (NumberFormatException e) {
            addError("maximumLengthProjectKeys",
                    getText("admin.generalconfiguration.maximum.length.project.names.notanumber",
                            maximumLengthProjectNames));
        }

    } else {
        // no content, set to default length
        maximumLengthProjectNames = String.valueOf(ProjectService.DEFAULT_NAME_LENGTH);
    }
    if (TextUtils.stringSet(maximumLengthProjectKeys)) {
        // is it a number
        try {
            final long maxProjectKeyLength = Integer.parseInt(maximumLengthProjectKeys);
            if (maxProjectKeyLength <= 1) {
                addError("maximumLengthProjectKeys",
                        getText("admin.generalconfiguration.maximum.length.project.keys.is.too.small"));
            } else if (maxProjectKeyLength > 255) {
                addError("maximumLengthProjectKeys",
                        getText("admin.generalconfiguration.maximum.length.project.keys.is.too.large"));
            }
        } catch (NumberFormatException e) {
            addError("maximumLengthProjectKeys",
                    getText("admin.generalconfiguration.maximum.length.project.keys.notanumber",
                            maximumLengthProjectKeys));
        }

    }
    if (contactAdministratorsMessage != null && contactAdministratorsMessage.length() > 2000) {
        addErrorMessage(getText("admin.generalconfiguration.contact.administrators.message.too.long"));
    }
    if (!defaultLocale.equals(JiraLocaleUtils.DEFAULT_LOCALE_ID)) {
        ErrorCollection errors = new SimpleErrorCollection();
        localeManager.validateUserLocale(getLoggedInUser(), defaultLocale, errors);
        if (errors.hasAnyErrors()) {
            addError("defaultLocale", errors.getErrors().get("userLocale"));
        }
    }
}

From source file:mitm.common.security.ca.CSVRequestConverter.java

/**
 * Converts the CSV to a list of RequestParameters. The first row should contain the column order. The CSV is 
 * considered to be US-ASCII encoded unless a Byte Ordering Mark (BOM) is used. 
 *  /*from  w w  w.j a  v  a  2  s  .c  o m*/
 * 
 * The following columns are supported:
 * 
 * EMAIL, ORGANISATION, COMMONNAME, FIRSTNAME, LASTNAME
 * 
 * Multiple aliases for the columns are available and names are case insensitive.
 * 
 * EMAIL        : [email, e]
 * ORGANISATION : [organisation, org, o]
 * COMMONNAME   : [commonname, cn]
 * FIRSTNAME    : [firstname, fn, givenname, gn]
 * LASTNAME     : [lastname, ln, surname, sn]
 * 
 * NOTE: all other fields, or fields that are not specified in the CSV, of the returned RequestParameters are 
 * NOT set.
 */
public List<RequestParameters> convertCSV(InputStream csv) throws IOException, RequestConverterException {
    Check.notNull(csv, "csv");

    foundEmails = new HashSet<String>();

    CSVReader reader = new CSVReader(new UnicodeReader(csv, CharacterEncoding.US_ASCII));

    readHeader(reader);

    checkRequiredColumns();

    List<RequestParameters> result = new LinkedList<RequestParameters>();

    String[] line;

    int currentLine = 0;

    while ((line = reader.readNext()) != null) {
        currentLine++;

        if (currentLine > maxLines) {
            throw new RequestConverterException("Maximum number of lines exceeded (" + maxLines + ").");
        }

        if (line == null || (line.length == 1 && StringUtils.isBlank(line[0]))) {
            /*
             * Skip empty lines 
             */
            continue;
        }

        if (line.length != columnOrder.length) {
            throw new RequestConverterException("Line " + currentLine + " does not contain the correct "
                    + "number of columns: " + StringUtils.join(line, ", "));
        }

        RequestParameters request = new RequestParametersImpl();

        X500PrincipalBuilder subjectBuilder = new X500PrincipalBuilder();

        for (int column = 0; column < line.length; column++) {
            String value = StringUtils.trim(line[column]);

            /*
             * Length sanity check
             */
            if (StringUtils.length(value) > maxValueLength) {
                throw new RequestConverterException("The column value " + StringUtils.defaultString(value)
                        + " at line " + currentLine + " and column " + column + " exceeds the maximum number of"
                        + " characters (" + maxValueLength + ").");
            }

            switch (columnOrder[column]) {
            case EMAIL:
                setEmail(value, request, subjectBuilder, column, currentLine);
                break;
            case ORGANISATION:
                subjectBuilder.setOrganisation(value);
                break;
            case COMMONNAME:
                setCommonName(value, subjectBuilder, column, currentLine);
                break;
            case FIRSTNAME:
                subjectBuilder.setGivenName(value);
                break;
            case LASTNAME:
                subjectBuilder.setSurname(value);
                break;

            default:
                throw new RequestConverterException("Unsupported column " + columnOrder[column]);
            }

            request.setSubject(subjectBuilder.buildPrincipal());
        }

        result.add(request);
    }

    return result;
}

From source file:com.ibm.asset.trails.action.ShowConfirmation.java

@Override
public void validate() {
    // Find which button was pressed by finding the method name that was
    // called//from   ww w.j av  a 2 s .  c  om
    Map<String, Object> lmParameter = ActionContext.getContext().getParameters();
    Set<String> lsParameterKey = lmParameter.keySet();
    Iterator<String> liParameterKey = lsParameterKey.iterator();
    String lsKey = null;
    String lsMethod = null;

    if (recon.getReconcileType().getId() == 1) {
        List<Report> lReport = new ArrayList<Report>();
        lReport.add(new Report("License baseline", "licenseBaseline"));
        setReportList(lReport);
    }

    while (liParameterKey.hasNext()) {
        lsKey = liParameterKey.next();

        if (lsKey.startsWith("method:")) {
            lsMethod = lsKey.substring(7);
        }
    }

    if (recon.getReconcileType().getId() == 3 || recon.getReconcileType().getId() == 4
            || recon.getReconcileType().getId() == 10 || recon.getReconcileType().getId() == 11
            || recon.getReconcileType().getId() == 13) {
        if (StringUtils.isBlank(comments)) {
            addFieldError("comments", "You must enter a comment, less than 255 characters");
        } else if (StringUtils.length(comments) > 255) {
            addFieldError("comments", "comment must be less than 255 characters");
        }
    }

    else if (recon.getReconcileType().getId() == 1) {
        if (lsMethod != null && lsMethod.equalsIgnoreCase("addAvailableLicenses")) {
            if (availableLicenseId == null || availableLicenseId.length == 0) {
                addFieldError("availableLicenseId", "You must select at least one available license");
            } else {
                if (hasSameCapacityType(availableLicenseId, getRecon().getLicenseList()) == false) {
                    addFieldError("availableLicenseId",
                            "You have selected two or more licenses with different capacity types. Please ensure that all selected licenses have the same capacity type");
                }
            }
        } else if (lsMethod != null && lsMethod.equalsIgnoreCase("deleteSelectedLicenses")) {
            if (selectedLicenseId == null || selectedLicenseId.length == 0) {
                addFieldError("selectedLicenseId", "You must select as least one selected license");
            }
        } else {
            if (getRecon().getLicenseList() == null || getRecon().getLicenseList().isEmpty()) {
                addFieldError("licenseId", "You must select at least one license");
            } else if (per.equalsIgnoreCase("PVU") && !isAllPvuLicenses()) {
                addFieldError("licenseId",
                        "You must select license(s) with a Capacity type of PROCESSOR VALUE UNIT");
            } else if (per.equalsIgnoreCase("PROCESSOR") && !isValidProcessor()) {
                addFieldError("per", "LPAR proc must be active and greater than zero");
            } else if ((per.equalsIgnoreCase("HWGARTMIPS") || per.equalsIgnoreCase("LPARGARTMIPS")
                    || per.equalsIgnoreCase("HWLSPRMIPS") || per.equalsIgnoreCase("LPARLSPRMIPS")
                    || per.equalsIgnoreCase("HWMSU") || per.equalsIgnoreCase("LPARMSU"))
                    && !isAllGSLMLicenses(per)) {
                addFieldError("licenseId", "You must select license(s) with a Capacity type of Mainframes");
            }
            if (StringUtils.isBlank(maxLicenses)
                    && !(per.equalsIgnoreCase("PVU") || per.equalsIgnoreCase("HWGARTMIPS")
                            || per.equalsIgnoreCase("LPARGARTMIPS") || per.equalsIgnoreCase("HWLSPRMIPS")
                            || per.equalsIgnoreCase("LPARLSPRMIPS") || per.equalsIgnoreCase("HWMSU")
                            || per.equalsIgnoreCase("LPARMSU") || per.equalsIgnoreCase("HWIFL"))) {
                addFieldError("maxLicenses",
                        "You must enter the number of license to apply for each LPAR or processor");
            } else if (!(per.equalsIgnoreCase("PVU") || per.equalsIgnoreCase("HWGARTMIPS")
                    || per.equalsIgnoreCase("LPARGARTMIPS") || per.equalsIgnoreCase("HWLSPRMIPS")
                    || per.equalsIgnoreCase("LPARLSPRMIPS") || per.equalsIgnoreCase("HWMSU")
                    || per.equalsIgnoreCase("LPARMSU") || per.equalsIgnoreCase("HWIFL"))
                    && (!StringUtils.isNumeric(maxLicenses) || Integer.valueOf(maxLicenses).intValue() < 1)) {
                addFieldError("maxLicenses", "Number of licenses must be an integer greater than zero");
            }
            if (StringUtils.isBlank(per)) {
                addFieldError("per", "You must enter an allocation methodology");
            }
        }

    }
    if ((recon.getReconcileType().getId() == 1 || recon.getReconcileType().getId() == 13
            || recon.getReconcileType().getId() == 14) && (!manual || !automated)) {
        list = recon.getList();
        if (list != null && list.size() > 0) {
            boolean manualMessage = false;
            boolean automatedMessage = false;
            for (int i = 0; i < list.size(); i++) {
                ReconWorkspace rw = list.get(i);
                if (rw.getReconcileTypeId() != null) {
                    ReconcileType rt = reconWorkspaceService.findReconcileType(rw.getReconcileTypeId());
                    if (rt.isManual()) {
                        if (!manualMessage && !manual) {
                            addFieldError("manual",
                                    "You must check \"Overwrite manual reconciliations\" option");
                            manualMessage = true;
                        }
                    } else {
                        if (!automatedMessage && !automated) {
                            addFieldError("automated",
                                    "You must check \"Overwrite automated reconciliations\" option");
                            automatedMessage = true;
                        }
                    }
                }
                if (manualMessage && automatedMessage)
                    break;
            }
        }
    }

    if (hasFieldErrors() || (recon.getReconcileType().getId() == 1 && lsMethod != null
            && (lsMethod.equalsIgnoreCase("addAvailableLicenses")
                    || lsMethod.equalsIgnoreCase("deleteSelectedLicenses")))) {
        if (recon.getReconcileType().getId() == 1) {
            List<LicenseFilter> filterlist = (List<LicenseFilter>) ActionContext.getContext().getSession()
                    .get("filters");

            licenseService.freePoolWithParentPaginatedList(getData(), getUserSession().getAccount(),
                    getStartIndex(), getData().getObjectsPerPage(), getSort(), getDir(), filterlist);
        }

        list = recon.getList();
    }
}

From source file:com.prowidesoftware.swift.model.SwiftMessageUtils.java

/**
 * Helper method to retrieve all sequences starting with 15X where X is the letterOption parameter.
 * Field 15a is used as a boundary for sequences, so the letter option correspond to a subsequence name.
 * @param block the content to split into subsequences
 * @param letterOption a letter option for the field boundary
 * @return found subsequences or an empty list if field 15 is not found
 * @since 7.7/*w  w w. j a v  a  2 s .  c  o m*/
 */
public static List<SwiftTagListBlock> splitByField15(final SwiftTagListBlock block, final String letterOption) {
    Validate.notNull(letterOption);
    Validate.isTrue(StringUtils.length(letterOption) == 1, "letter option must be only one character");
    final List<SwiftTagListBlock> result = new ArrayList<SwiftTagListBlock>();
    if (block != null) {
        SwiftTagListBlock currentList = null;
        for (final Tag t : block.getTags()) {
            if (t.getNumber() == 15) {
                final String letter = t.getLetterOption();
                if (letter != null && letter.length() == 1) {
                    if (letter.equals(letterOption)) {
                        final SwiftTagListBlock thisList = new SwiftTagListBlock();
                        result.add(thisList);
                        currentList = thisList;
                    } else {
                        currentList = null;
                    }
                }
            }
            if (currentList != null) {
                currentList.append(t);
            }
        }
    }
    return result;
}

From source file:com.ufnet.ws.service.UserService.java

/**
 * cardChangePWD/*w  w  w. ja va2s.  co m*/
 * @param request
 * @return
 */
public int cardChangePWD(CardChangePWDRequest request) {
    // Request && Validation
    String userId = request.getUserId();
    if (StringUtils.isBlank(userId)) {
        log.error("userid[" + userId + "] is blank.");
        return 0;
    }
    UserInfo userInfo = userInfoRepository.select(userId);
    if (userInfo == null) {
        log.error("userid[" + userId + "] not exists.");
        return -1;
    }
    String destPwd = request.getDestPwd();
    if (StringUtils.isBlank(userId)) {
        log.error("destpwd[" + destPwd + "] is blank.");
        return 0;
    }
    if (StringUtils.length(destPwd) > SimpleConstants.PASSWORD_MAX_LENGTH) {
        log.error("destpwd[" + destPwd + "] over " + SimpleConstants.PASSWORD_MAX_LENGTH + ".");
        return 0;
    }
    // Process
    int returnCode = 1;
    try {
        UserInfo data = new UserInfo();
        data.setLoginName(userId);
        data.setPassword(destPwd);
        userInfoRepository.update(data);
    } catch (Exception e) {
        returnCode = 0;
        log.error(ExceptionUtils.getStackTrace(e));
    }
    return returnCode;
}

From source file:com.evozon.evoportal.my_account.validator.UserAccountValidation.java

private boolean isCNPContentValid(ActionRequest actionRequest) {
    boolean isValid = true;
    String cnp = ParamUtil.getString(actionRequest, MyAccountConstants.USER_CNP);

    if (StringUtils.length(cnp) != CNP_LENGTH) {
        SessionErrors.add(actionRequest, "cnp-invalid-length-error");
        isValid = false;/*from w w  w.  ja v a2s.c  om*/
    }

    if (!isNumericInput(cnp)) {
        SessionErrors.add(actionRequest, "cnp-invalid-characters-error");
        isValid = false;
    }

    return isValid;
}

From source file:com.zb.jcseg.util.WordUnionUtils.java

private static void handleSingleWord(List<String> splitWordsList, String candidate, String singleWord) {
    MagicWordResult result = isNeedAddDualWord(candidate, singleWord);
    if (result.isSuccess()) {
        addStr2List(splitWordsList, candidate);
        addStr2List(splitWordsList, result.getWord());
    } else {/*from w w  w  . j  a v  a  2  s .c om*/
        if (StringUtils.length(singleWord) <= 1) {
            // TODO zxc????
            addStr2List(splitWordsList, candidate);
            addStr2List(splitWordsList, singleWord);
            // candidate = candidate + singleWord;
            // addStr2List(splitWordsList, candidate);
        } else {
            addStr2List(splitWordsList, candidate);
            addStr2List(splitWordsList, singleWord);
        }
    }
}

From source file:com.hangum.tadpole.preference.ui.UserInfoPerference.java

@Override
public boolean performOk() {
    if (!TadpoleApplicationContextManager.isPersonOperationType()) {
        String pass = textPassword.getText().trim();
        String rePass = textRePassword.getText().trim();
        String useOTP = btnGetOptCode.getSelection() ? "YES" : "NO"; //$NON-NLS-1$ //$NON-NLS-2$
        String otpSecretKey = textSecretKey.getText();

        if (StringUtils.length(pass) < 5) {
            MessageDialog.openWarning(getShell(), Messages.get().Warning, Messages.get().UserInfoPerference_14);
            textPassword.setFocus();/*from  w ww. j a va 2s  .c o  m*/
            return false;
        }

        if (pass.equals("")) { //$NON-NLS-1$
            MessageDialog.openWarning(getShell(), Messages.get().Warning, Messages.get().UserInfoPerference_17);
            textPassword.setFocus();
            return false;
        } else if (!pass.equals(rePass)) {
            MessageDialog.openWarning(getShell(), Messages.get().Warning, Messages.get().UserInfoPerference_6);
            textPassword.setFocus();
            return false;
        } else if (btnGetOptCode.getSelection()) {
            if ("".equals(textOTPCode.getText())) { //$NON-NLS-1$
                MessageDialog.openWarning(getShell(), Messages.get().Warning,
                        Messages.get().UserInfoPerference_15); //$NON-NLS-1$
                textOTPCode.setFocus();
                return false;
            } else if (!GoogleAuthManager.getInstance().isValidate(otpSecretKey,
                    NumberUtils.toInt(textOTPCode.getText()))) {
                MessageDialog.openWarning(getShell(), Messages.get().Warning,
                        Messages.get().UserInfoPerference_16); //$NON-NLS-1$
                textOTPCode.setFocus();
                return false;
            }
        }
        // Password double check
        boolean isPasswordUpdated = !pass.equals(SessionManager.getPassword());

        UserDAO user = new UserDAO();
        user.setSeq(SessionManager.getUserSeq());
        user.setPasswd(pass);

        user.setUse_otp(useOTP);
        user.setOtp_secret(otpSecretKey);

        try {
            if (isPasswordUpdated) {
                TadpoleSystem_UserQuery.updateUserPassword(user);
                SessionManager.updateSessionAttribute(SessionManager.NAME.LOGIN_PASSWORD.toString(),
                        user.getPasswd());
            }

            TadpoleSystem_UserQuery.updateUserOTPCode(user);
            SessionManager.updateSessionAttribute(SessionManager.NAME.USE_OTP.toString(), useOTP);
            SessionManager.updateSessionAttribute(SessionManager.NAME.OTP_SECRET_KEY.toString(), otpSecretKey);

            //fix https://github.com/hangum/TadpoleForDBTools/issues/243
            SessionManager.setPassword(user.getPasswd());
        } catch (Exception e) {
            logger.error("password change", e); //$NON-NLS-1$
            MessageDialog.openError(getShell(), Messages.get().Error, e.getMessage()); //$NON-NLS-1$

            return false;
        }
    }

    return super.performOk();
}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopSearchField.java

protected void handleSearch(final String newFilter) {
    clearSearchVariants();/*  w  w  w  . ja  v a2s . c  om*/

    String filterForDs = newFilter;
    if (mode == Mode.LOWER_CASE) {
        filterForDs = StringUtils.lowerCase(newFilter);
    } else if (mode == Mode.UPPER_CASE) {
        filterForDs = StringUtils.upperCase(newFilter);
    }

    if (escapeValueForLike && StringUtils.isNotEmpty(filterForDs)) {
        filterForDs = QueryUtils.escapeForLike(filterForDs);
    }

    if (!isRequired() && StringUtils.isEmpty(filterForDs)) {
        if (optionsDatasource.getState() == Datasource.State.VALID) {
            optionsDatasource.clear();
        }

        setValue(null);
        updateOptionsDsItem();
        return;
    }

    if (StringUtils.length(filterForDs) >= minSearchStringLength) {
        optionsDatasource
                .refresh(Collections.singletonMap(SearchField.SEARCH_STRING_PARAM, (Object) filterForDs));

        if (optionsDatasource.getState() == Datasource.State.VALID) {
            if (optionsDatasource.size() == 0) {
                if (searchNotifications != null)
                    searchNotifications.notFoundSuggestions(newFilter);
            } else if (optionsDatasource.size() == 1) {
                setValue(optionsDatasource.getItems().iterator().next());
                updateOptionsDsItem();
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        updateComponent(getValue());
                    }
                });
            } else {
                initSearchVariants();
                comboBox.showSearchPopup();
            }
        }
    } else {
        if (optionsDatasource.getState() == Datasource.State.VALID) {
            optionsDatasource.clear();
        }

        if (searchNotifications != null && StringUtils.length(filterForDs) > 0) {
            searchNotifications.needMinSearchStringLength(newFilter, minSearchStringLength);
        }
    }
}

From source file:com.zb.jcseg.util.WordUnionUtils.java

public static boolean isContainSingleWord(String w) {
    if (StringUtils.length(w) <= 0) {
        return false;
    }/*from www .  ja  v a 2s  .  c o m*/
    for (String s : Single_Words) {
        if (StringUtils.contains(w, s)) {
            return true;
        }
    }
    return false;
}