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

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

Introduction

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

Prototype

public static int length(final CharSequence cs) 

Source Link

Document

Gets a CharSequence length or 0 if the CharSequence is null .

Usage

From source file:de.micromata.genome.gwiki.controls.GWikiWeditServiceActionBean.java

public Object onWeditAutocomplete() {
    // {, !, [//w  w  w .ja va  2  s.c  o m
    String format = wikiContext.getRequestParameter("c");
    String querystring = wikiContext.getRequestParameter("q");
    JsonObject resp = null;
    if (StringUtils.length(format) != 1) {
        resp = JsonBuilder.map("ret", 10, "message", "No type given");
    } else {
        JsonArray array = JsonBuilder.array();
        switch (format.charAt(0)) {
        case '!':
            fillImageLinks(querystring, array);
            break;
        case '[':
            fillPageLinks(querystring, array);
            break;
        case '{':
            fillMacroLinks(querystring, array);
            break;

        case 'x':
            array.add(JsonBuilder.map("title", "Erster!", "url", "first"));
            array.add(JsonBuilder.map("title", "Zweiter!", "url", "second"));
            break;
        default:
            resp = JsonBuilder.map("ret", 11, "message", "Unknown type: " + format);
            break;
        }
        if (resp == null) {
            resp = JsonBuilder.map("ret", 0, "list", array);
        }
    }

    return sendResponse(resp);

}

From source file:de.micromata.genome.db.jpa.tabattr.entities.JpaTabAttrBaseDO.java

/**
 * Set the value of the attribute.//from  w  w  w.  ja  va 2  s  . co m
 * 
 * if value is longer than VALUE_MAXLENGHT the string will be split and stored in additional data children entities.
 *
 * @param value the new string data
 */
public void setStringData(String value) {
    List<JpaTabAttrDataBaseDO<?, PK>> data = getData();
    data.clear();
    int maxValLength = getValueMaxLength();
    if (StringUtils.length(value) > maxValLength) {
        this.value = value.substring(0, maxValLength);
        String rest = value.substring(maxValLength);
        int maxDataLength = getMaxDataLength();
        int rowIdx = 0;
        while (rest.length() > 0) {
            String ds = StringUtils.substring(rest, 0, maxDataLength);
            rest = StringUtils.substring(rest, maxDataLength);
            JpaTabAttrDataBaseDO<?, PK> dataDo = createData(ds);
            dataDo.setDatarow(rowIdx++);
            data.add(dataDo);
        }
    } else {
        this.value = value;
    }
}

From source file:controllers.WidgetAdmin.java

private static String isPasswordStrongEnough(String password, String email) {
    if (StringUtils.length(password) < 8) {
        return "Password is too short";
    }/*from w ww.  ja  v a 2  s.  c  om*/
    if (!Pattern.matches("(?=^.{8,}$)((?=.*\\d)|(?=.*\\W+))(?![.\\n])(?=.*[A-Z])(?=.*[a-z]).*$", password)
            && !StringUtils.containsIgnoreCase(email, password)) {
        return "Password must match requirements";
    }

    Set<String> strSet = new HashSet<String>();
    for (String s : password.split("")) {
        if (StringUtils.length(s) > 0) {
            strSet.add(s.toLowerCase());
        }
    }

    if (CollectionUtils.size(strSet) < 3) {
        return "Too many repeating letters";
    }

    if (StringUtils.getLevenshteinDistance(password, email.split("@")[0]) < 5
            || StringUtils.getLevenshteinDistance(password, email.split("@")[1]) < 5) {
        return "Password similar to email";
    }

    return null;
}

From source file:de.micromata.mgc.application.webserver.config.JettyConfigTabController.java

private void createSslValidate(ValContext ctx) {
    File storePath = new File(".");
    if (StringUtils.isNotBlank(sslKeystorePath.getText()) == true) {
        String sp = sslKeystorePath.getText();
        if (sp.contains("/") == false && sp.contains("\\") == false) {
            if (StringUtils.isBlank(sp) == true) {
                storePath = new File(".");
            } else {
                storePath = new File(new File("."), sp);
            }/* w ww  .j a  v  a  2s  .com*/
        } else {
            storePath = new File(sslKeystorePath.getText());
        }
    }
    if (storePath.getParentFile() == null || storePath.getParentFile().exists() == false) {
        ctx.directError("sslKeystorePath", "The parent path doesn't exists: "
                + (storePath.getParentFile() == null ? "null" : storePath.getParentFile().getAbsolutePath()));
        return;
    }
    if (storePath.exists() && storePath.isDirectory() == true) {
        ctx.directError("sslKeystorePath", "Please give an path to file: " + storePath.getAbsolutePath());
        return;
    }
    if (storePath.exists() == true) {
        Alert alert = new Alert(AlertType.CONFIRMATION);
        alert.setTitle("Overwrite keystore");
        //      alert.setHeaderText("Overwrite the existant keystore file?");
        alert.setContentText("Overwrite the existant keystore file?");
        Optional<ButtonType> result = alert.showAndWait();
        if (result.get() != ButtonType.OK) {
            return;
        }
    }
    if (StringUtils.length(sslKeystorePassword.getText()) < 6) {
        ctx.directError("sslKeystorePassword",
                "Please give a password for Keystore password with at least 6 characters");
        return;
    }
    if (StringUtils.isBlank(sslCertAlias.getText()) == true) {
        ctx.directError("sslCertAlias", "Please give a Alias for the key");
        return;
    }
    KeyTool.generateKey(ctx, storePath, sslKeystorePassword.getText(), sslCertAlias.getText());
    Alert alert = new Alert(AlertType.WARNING);
    alert.setTitle("Certificate created");
    alert.setHeaderText(
            "Certificate created. You are using a self signed certificate, which should not be used in production.");
    alert.setContentText(
            "If you open the browser, will will receive a warning, that the certificate is not secure.\n"
                    + "You have to accept the certificate to continue.");
    Optional<ButtonType> result = alert.showAndWait();
}

From source file:gov.nih.nci.caintegrator.web.action.abstractlist.AbstractEditListAction.java

private void validateListName() {
    if (StringUtils.isEmpty(getListName())) {
        addFieldError(LIST_NAME, getText("struts.messages.error.name.required", getArgs("List")));
    } else if (StringUtils.length(getListName()) > LIST_NAME_LENGTH) {
        addFieldError(LIST_NAME, getText("struts.message.error.list.name.length"));
    } else if ((!listOldName.equals(listName) && getAbstractList(listName, isVisibleToOther()) != null)
            || (isVisibleToOther() != isGlobalList()
                    && getAbstractList(listName, isVisibleToOther()) != null)) {
        addFieldError(LIST_NAME,//from ww w .j a v  a2s .co  m
                getText("struts.messages.error.duplicate.name", getArgs("List", getListName())));
        abstractList = getAbstractList(listOldName, isGlobalList());
        setListName(listOldName);
    }
}

From source file:com.alibaba.dubbo.qos.textui.TTable.java

private String getDataFormat(ColumnDefine columnDefine, int width, String data) {
    switch (columnDefine.align) {
    case MIDDLE: {
        final int length = StringUtils.length(data);
        final int diff = width - length;
        final int left = diff / 2;
        return repeat(" ", diff - left) + "%s" + repeat(" ", left);
    }//www.ja  va 2 s  . c  o  m
    case RIGHT: {
        return "%" + width + "s";
    }
    case LEFT:
    default: {
        return "%-" + width + "s";
    }
    }
}

From source file:de.micromata.genome.db.jpa.tabattr.entities.JpaTabMasterBaseDO.java

/**
 * Put attribute internal.//  w  ww.  j  av a 2 s.  co  m
 *
 * @param key the key
 * @param type the type
 * @param encodedString the encoded string
 */
public void putAttributeInternal(String key, Character type, String encodedString) {

    JpaTabAttrBaseDO<M, PK> tabr = getAttributeRow(key);
    Class<?> required = StringUtils.length(encodedString) > JpaTabAttrDataBaseDO.DATA_MAXLENGTH
            ? getAttrEntityWithDataClass()
            : getAttrEntityClass();

    if (tabr != null && required == tabr.getClass()) {
        tabr.setStringData(encodedString);
        tabr.setType(type);
        return;
    }

    if (StringUtils.length(encodedString) > JpaTabAttrDataBaseDO.DATA_MAXLENGTH) {
        putAttributeRow(key, createAttrEntityWithData(key, type, encodedString));
    } else {
        putAttributeRow(key, createAttrEntity(key, type, encodedString));
    }
}

From source file:gtu.jpa.hibernate.Rcdf002eDBUI.java

private void executeBtnActionPerformed(ActionEvent evt) {
    try {//w w w  .j a  v a  2 s  . c om
        final JdbcFastQuery exe = new JdbcFastQuery();
        JdbcFastQuery.debugMode = isDebug.isSelected();
        Log.Setting.NORMAL.apply();
        exe.setOut(new PrintStream(new PrintStreamAdapter("big5") {
            @Override
            public void println(String message) {
                Log.debug(message);
                if (StringUtils.length(logArea.getText()) > 500) {
                    logArea.setText("");
                }
                logArea.append(message + "\n");
            }
        }));
        setTitle(".......");
        Thread thread = new Thread(Thread.currentThread().getThreadGroup(), new Runnable() {
            @Override
            public void run() {
                try {
                    long current = System.currentTimeMillis();
                    exe.execute();
                    current = System.currentTimeMillis() - current;
                    setTitle("xml : ?");
                    JCommonUtil._jOptionPane_showMessageDialog_info(
                            "xml : ?, :" + current + "\n?!");
                    xmlFileText.setText(getBulkFile().getAbsolutePath());
                } catch (Exception ex) {
                    setTitle(":" + ex.getMessage());
                    JCommonUtil.handleException(ex);
                }
            }
        }, "xxxxxxxxxxxxxxxxxcxccx");
        thread.setDaemon(true);
        thread.start();
    } catch (Exception ex) {
        setTitle(":" + ex.getMessage());
        JCommonUtil.handleException(ex);
    }
}

From source file:de.micromata.genome.logging.loghtmlwindow.LogHtmlWindowServlet.java

protected void filter(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String logMessage = req.getParameter("logMessage");
    Integer level = null;//from  w  w  w.ja  v a  2 s .c om
    String logLevel = req.getParameter("logLevel");
    if (StringUtils.isNotBlank(logLevel) == true) {
        level = LogLevel.fromString(logLevel, LogLevel.Note).getLevel();
    }
    String logCategory = req.getParameter("logCategory");

    Timestamp start = null;
    Timestamp end = null;
    List<Pair<String, String>> logAttributes = null;
    String logAttribute1Type = req.getParameter("logAttribute1Type");
    String logAttribute1Value = req.getParameter("logAttribute1Value");
    String logAttribute2Type = req.getParameter("logAttribute2Type");
    String logAttribute2Value = req.getParameter("logAttribute2Value");
    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.US);

    String fromDate = req.getParameter("fromDate");
    String toDate = req.getParameter("toDate");
    if (StringUtils.length(fromDate) == "yyyy-MM-ddTHH:mm:ss.SSSZ".length()) {
        try {
            start = new Timestamp(sd.parse(fromDate).getTime());
        } catch (ParseException ex) {
            LOG.warn("Cannot parse Logging fromDate: " + fromDate + ": " + ex.getMessage());
        }
    }
    if (StringUtils.length(toDate) == "yyyy-MM-ddTHH:mm:ss.SSSZ".length()) {
        try {
            end = new Timestamp(sd.parse(toDate).getTime());
        } catch (ParseException ex) {
            LOG.warn("Cannot parse Logging fromDate: " + toDate + ": " + ex.getMessage());
        }
    }
    if (StringUtils.isNotBlank(logAttribute1Type) && StringUtils.isNotBlank(logAttribute1Value)) {
        logAttributes = new ArrayList<>();
        logAttributes.add(Pair.make(logAttribute1Type, logAttribute1Value));
    }
    if (StringUtils.isNotBlank(logAttribute2Type) && StringUtils.isNotBlank(logAttribute2Value)) {
        if (logAttributes == null) {
            logAttributes = new ArrayList<>();
        }
        logAttributes.add(Pair.make(logAttribute2Type, logAttribute2Value));
    }
    List<OrderBy> orderBy = new ArrayList<>();
    String orderCol = req.getParameter("orderBy");
    if (StringUtils.isNotBlank(orderCol) == true) {
        Boolean desc = Boolean.valueOf(req.getParameter("desc"));
        orderBy.add(new OrderBy(orderCol, desc));
    } else {
        orderBy.add(new OrderBy("modifiedAt", true));
    }
    String startRows = req.getParameter("startRow");
    String maxRows = req.getParameter("maxRow");
    int startRow = NumberUtils.toInt(startRows, 0);
    int maxRow = NumberUtils.toInt(maxRows, 30);
    boolean allAttrs = "true".equals(req.getParameter("allAttrs"));
    JsonArray ret = new JsonArray();
    Logging logging = LoggingServiceManager.get().getLogging();
    logging.selectLogs(start, end, level, logCategory, logMessage, logAttributes, startRow, maxRow, orderBy,
            allAttrs == false, (logEntry) -> {
                ret.add(LogJsonUtils.logEntryToJson(logging, logEntry, allAttrs));
            });
    sendResponse(resp, ret);
}

From source file:alfio.util.Validator.java

public static void validateMaxLength(String value, String fieldName, String errorCode, int maxLength,
        Errors errors) {/*from w  w w. j ava 2  s .c  o  m*/
    if (StringUtils.isNotBlank(value) && StringUtils.length(value) > maxLength) {
        errors.rejectValue(fieldName, errorCode);
    }
}