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

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

Introduction

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

Prototype

public static boolean isEmpty(final CharSequence cs) 

Source Link

Document

Checks if a CharSequence is empty ("") or null.

 StringUtils.isEmpty(null)      = true StringUtils.isEmpty("")        = true StringUtils.isEmpty(" ")       = false StringUtils.isEmpty("bob")     = false StringUtils.isEmpty("  bob  ") = false 

NOTE: This method changed in Lang version 2.0.

Usage

From source file:com.thruzero.common.core.locator.LocatorUtils.java

/**
 * Test the given initParameter and if empty, throw an InitializationException.
 *
 * @param initParameter the parameter value read from the InitializationStrategy.
 * @param sectionName the section the params were read from (used only for error reporting).
 * @param key the parameter key used to read the value (used only for error reporting).
 * @param initStrategy the initialization strategy that was the source of the params (used only for error reporting).
 *//*from ww w  . j a v a 2  s  . c o m*/
public static void assertInitParameterExists(final String initParameter, final String sectionName,
        final String key, final InitializationStrategy initStrategy) {
    if (StringUtils.isEmpty(initParameter)) {
        throw InitializationException.createMissingKeyInitializationException(sectionName, key, initStrategy);
    }
}

From source file:com.microsoft.azure.management.datalake.store.uploader.StringExtensions.java

/**
 * Finds the index in the given buffer of a newline character, either the first or the last (based on the parameters).
 * If a combined newline (\r\n), the index returned is that of the last character in the sequence.
 *
 * @param buffer The buffer to search in.
 * @param startOffset The index of the first byte to start searching at.
 * @param length The number of bytes to search, starting from the given startOffset.
 * @param reverse If true, searches from the startOffset down to the beginning of the buffer. If false, searches upwards.
 * @param encoding Indicates the type of encoding to use for the buffered bytes.
 * @param delimiter Optionally indicates the delimiter to consider as the "new line", which MUST BE a single character. If null, the default is '\\r', '\\n' and '\\r\\n'.
 * @return The index of the closest newline character in the sequence (based on direction) that was found. Returns -1 if not found.
 *///from   w w  w. j  a  va2s  . co m
public static int findNewline(byte[] buffer, int startOffset, int length, boolean reverse, Charset encoding,
        String delimiter) {
    if (buffer.length == 0 || length == 0) {
        return -1;
    }

    // define the bytes per character to use
    int bytesPerChar;
    if (encoding.equals(StandardCharsets.UTF_16) || encoding.equals(StandardCharsets.UTF_16BE)
            || encoding.equals(StandardCharsets.UTF_16LE)) {
        bytesPerChar = 2;
    } else if (encoding.equals(StandardCharsets.US_ASCII) || encoding.equals(StandardCharsets.UTF_8)) {
        bytesPerChar = 1;
    } else {
        throw new IllegalArgumentException(
                "Only the following encodings are allowed: UTF-8, UTF-16, UTF-16BE, UTF16-LE and ASCII");
    }

    if (delimiter != null && !StringUtils.isEmpty(delimiter) && delimiter.length() > 1) {
        throw new IllegalArgumentException(
                "The delimiter must only be a single character or unspecified to represent the CRLF delimiter");
    }

    if (delimiter != null && !StringUtils.isEmpty(delimiter)) {
        // convert the byte array back to a String
        int startOfSegment = reverse ? startOffset - length + 1 : startOffset;
        String bytesToString = new String(buffer, startOfSegment, length, encoding);
        if (!bytesToString.contains(delimiter)) {
            // didn't find the delimiter.
            return -1;
        }

        // the index is returned, which is 0 based, so our loop must include the zero case.
        int numCharsToDelim = reverse ? bytesToString.lastIndexOf(delimiter) : bytesToString.indexOf(delimiter);
        int toReturn = 0;
        for (int i = 0; i <= numCharsToDelim; i++) {
            toReturn += Character.toString(bytesToString.charAt(startOfSegment + i)).getBytes(encoding).length;
        }

        // we get the total number of bytes, but we want to return the index (which starts at 0)
        // so we subtract 1 from the total number of bytes to get the final byte index.
        return toReturn - 1;
    }

    //endOffset is a 'sentinel' value; we use that to figure out when to stop searching
    int endOffset = reverse ? startOffset - length : startOffset + length;

    // if we are starting at the end, we need to move toward the front enough to grab the right number of bytes
    startOffset = reverse ? startOffset - (bytesPerChar - 1) : startOffset;

    if (startOffset < 0 || startOffset >= buffer.length) {
        throw new IndexOutOfBoundsException(
                "Given start offset is outside the bounds of the given buffer. In reverse cases, the start offset is modified to ensure we check the full size of the last character");
    }

    // make sure that the length we are traversing is at least as long as a single character
    if (length < bytesPerChar) {
        throw new IllegalArgumentException(
                "length must be at least as long as the length, in bytes, of a single character");
    }

    if (endOffset < -1 || endOffset > buffer.length) {
        throw new IndexOutOfBoundsException(
                "Given combination of startOffset and length would execute the search outside the bounds of the given buffer.");
    }

    int bufferEndOffset = reverse ? startOffset : startOffset + length;
    int result = -1;
    for (int charPos = startOffset; reverse ? charPos != endOffset
            : charPos + bytesPerChar - 1 < endOffset; charPos = reverse ? charPos - 1 : charPos + 1) {
        char c;
        if (bytesPerChar == 1) {
            c = (char) buffer[charPos];
        } else {
            String temp = new String(buffer, charPos, bytesPerChar, encoding);
            if (StringUtils.isEmpty(temp)) {
                continue;
            } else {
                c = temp.toCharArray()[0];
            }
        }

        if (isNewline(c, delimiter)) {
            result = charPos + bytesPerChar - 1;
            break;
        }
    }

    if ((delimiter == null || StringUtils.isEmpty(delimiter)) && !reverse
            && result < bufferEndOffset - bytesPerChar) {
        char c;
        if (bytesPerChar == 1) {
            c = (char) buffer[result + bytesPerChar];
        } else {
            String temp = new String(buffer, result + 1, bytesPerChar, encoding);
            if (StringUtils.isEmpty(temp)) {
                // this can occur if the number of bytes for characters in the string result in an empty string (an invalid code for the given encoding)
                // in this case, that means that we are done for the default delimiter.
                return result;
            } else {
                c = temp.toCharArray()[0];
            }
        }

        if (isNewline(c, delimiter)) {
            //we originally landed on a \r character; if we have a \r\n character, advance one position to include that
            result += bytesPerChar;
        }
    }

    return result;
}

From source file:com.adguard.commons.utils.ProductVersion.java

public ProductVersion(String version) {
    if (StringUtils.isEmpty(version)) {
        return;//w  ww.  j  a v  a  2s.c  o m
    }

    String[] parts = StringUtils.split(version, ".");

    if (parts.length >= 4) {
        build = parseVersionPart(parts[3]);
    }
    if (parts.length >= 3) {
        revision = parseVersionPart(parts[2]);
    }
    if (parts.length >= 2) {
        minor = parseVersionPart(parts[1]);
    }
    if (parts.length >= 1) {
        major = parseVersionPart(parts[0]);
    }
}

From source file:AIR.Common.Web.WebValueCollectionCorrect.java

public static WebValueCollectionCorrect getInstanceFromString(String strn, boolean urlEncoded) {
    if (StringUtils.isEmpty(strn))
        return null;
    try {//w w w.  j av a2 s. com
        if (urlEncoded)
            strn = UrlEncoderDecoderUtils.decode(strn);
        Map<Object, Object> o = JsonHelper.deserialize(strn, Map.class);

        WebValueCollectionCorrect collection = new WebValueCollectionCorrect();
        for (Map.Entry<Object, Object> entry : o.entrySet()) {
            collection.put(entry.getKey().toString(), entry.getValue());
        }
        return collection;
    } catch (Exception exp) {
        throw new RuntimeException(exp);
    }
}

From source file:com.baifendian.swordfish.webserver.service.LogHelper.java

public LogResult getLog(Integer from, Integer size, String query, String jobId) {
    //  id , ?/*  ww  w  . jav  a2s .co  m*/
    if (StringUtils.isEmpty(jobId)) {
        return LogResult.EMPTY_LOG_RESULT;
    }

    if (from == null) {
        from = 0;
    }

    if (size == null) {
        size = 100;
    }

    long start = System.currentTimeMillis();

    LogResult result = new LogResult();

    try {
        SearchResponse response = search.search(from, size, query, jobId/*, (sort == null) ? true : sort*/);

        if (response != null) {
            if (response.status() == RestStatus.OK) {
                SearchHits searchHits = response.getHits();

                result.setTotal(searchHits.getTotalHits()); // total
                result.setLength(searchHits.getHits().length); // real length
                result.setOffset(from); // offset

                List<String> contents = new ArrayList<>();

                for (SearchHit hit : searchHits.getHits()) {
                    Map<String, Object> fieldMap = hit.getSource();

                    if (fieldMap != null && fieldMap.containsKey("nest_msg")) {
                        String message = fieldMap.get("nest_msg").toString();

                        contents.add(message);
                    } else {
                        contents.add(StringUtils.EMPTY);
                    }
                }

                result.setContent(contents);
            } else {
                logger.error("search status: {}", response.status());
            }
        }
    } catch (IOException e) {
        logger.error("Catch an exception", e);
        return null;
    }

    // 
    result.setTook(System.currentTimeMillis() - start);
    return result;
}

From source file:com.thruzero.common.web.model.container.AbstractPanel.java

public AbstractPanel(String id, String title, String titleLink, String collapseDirection,
        boolean useWhiteChevron, StyleClass headerStyleClass, List<InfoNodeElement> toolbar) {
    this.id = StringUtils.isEmpty(id) ? SimpleIdGenerator.getInstance().getNextIdAsString() : id;
    this.title = title;
    this.titleLink = titleLink;
    this.collapseDirection = collapseDirection;
    this.useWhiteChevron = useWhiteChevron;
    this.headerStyleClass = headerStyleClass;

    if (toolbar != null) {
        this.toolbar.addAll(toolbar);
    }/*from   w  w  w  . ja  v  a  2 s  .c  o  m*/
}

From source file:ip.ui.LearningParamsInputPanel.java

public double getMomentumFactor() throws EmptyInputFieldException {
    String momentumFactorParam = momentumFactorInput.getText();
    if (StringUtils.isEmpty(momentumFactorParam)) {
        throw new EmptyInputFieldException(momentumFactorLabel.getText());
    }//from w  ww  .  j a  v a2 s  .  c om

    return Double.parseDouble(momentumFactorParam);
}

From source file:com.baifendian.swordfish.execserver.common.FunctionUtil.java

/**
 * , ? udf//ww w.j av  a  2s . com
 *
 * @param srcDir ?
 * @param isHdfsFile ?? hdfs 
 */
public static List<String> createFuncs(List<UdfsInfo> udfsInfos, int execId, String nodeName, Logger logger,
        String srcDir, boolean isHdfsFile, SqlEngineType type, ExternalJobType externalJobType)
        throws IOException, InterruptedException {
    //  hive udf jar 
    String hiveUdfJarPath = BaseConfig.getJobHiveUdfJarPath(execId, externalJobType, nodeName);

    // ? udf 
    if (StringUtils.isEmpty(hiveUdfJarPath)) {
        logger.error("Not define hive udf jar path");
        throw new RuntimeException("Hive udf jar base path not defined ");
    }

    List<String> funcList = new ArrayList<>();

    if (CollectionUtils.isNotEmpty(udfsInfos)) {
        Set<String> resources = getFuncResouces(udfsInfos);

        if (CollectionUtils.isNotEmpty(resources)) {
            // adHoc ? hdfs ???
            if (isHdfsFile) {
                copyJars(resources, hiveUdfJarPath, srcDir, logger);
            } else {
                uploadUdfJars(resources, hiveUdfJarPath, srcDir, logger);
            }

            if (SqlEngineType.PHOENIX != type) {
                // Phoenix sql can not add jar
                addJarSql(funcList, resources, hiveUdfJarPath);
            }
        }
    }

    if (SqlEngineType.PHOENIX == type) {
        addPhoenixTempFuncSql(funcList, udfsInfos, hiveUdfJarPath);
    } else {
        addTempFuncSql(funcList, udfsInfos);
    }

    return funcList;
}

From source file:com.ace.console.controller.LoginFormController.java

@RequestMapping(value = { "/{login:login;?.*}" })
public String loginForm(@CurrentUser User user, HttpServletRequest request, ModelMap model) {

    ////  w  w  w  . j av a2s. c  o m
    if (!StringUtils.isEmpty(request.getParameter("logout"))) {
        model.addAttribute(Constants.MESSAGE, messageSource.getMessage("user.logout.success", null, null));
    }

    // @see org.apache.shiro.web.filter.user.SysUserFilter
    if (!StringUtils.isEmpty(request.getParameter("notfound"))) {
        model.addAttribute(Constants.ERROR, messageSource.getMessage("user.notfound", null, null));
    }

    //?
    if (!StringUtils.isEmpty(request.getParameter("forcelogout"))) {
        model.addAttribute(Constants.ERROR, messageSource.getMessage("user.forcelogout", null, null));
    }

    //        //??
    //        if (!StringUtils.isEmpty(request.getParameter("jcaptchaError"))) {
    //            model.addAttribute(Constants.ERROR, messageSource.getMessage("jcaptcha.validate.error", null, null));
    //        }

    // ????
    Exception shiroLoginFailureEx = (Exception) request
            .getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
    if (shiroLoginFailureEx != null) {
        try {
            model.addAttribute(Constants.ERROR,
                    messageSource.getMessage(shiroLoginFailureEx.getMessage(), null, null));
        } catch (Exception ex) {
            logger.error("user login error : ", ex);
            model.addAttribute(Constants.ERROR, messageSource.getMessage("user.unknown.error", null, null));
        }
    }

    //? 
    //isAccessAllowedsubject.isAuthenticated()---->?? ?
    // 
    Subject subject = SecurityUtils.getSubject();
    if (subject != null && subject.isAuthenticated()) {
        subject.logout();
    }

    //??  ?  ???
    if (model.containsAttribute(Constants.ERROR)) {
        model.remove(Constants.MESSAGE);
    }

    return "/login";
}

From source file:com.iksgmbh.sql.pojomemodb.sqlparser.helper.OrderConditionParser.java

public List<OrderCondition> parseConditions(final String orderClause) throws SQLException {
    if (StringUtils.isEmpty(orderClause))
        throw new SQLException("No column defined for order by!");

    String unparsedRest = orderClause;
    if (unparsedRest.startsWith("(")) {
        unparsedRest = StringParseUtil.removeSurroundingPrefixAndPostFix(unparsedRest, "(", ")");
    }/*from w  w w .  j  av a  2s . c  o m*/

    final List<OrderCondition> toReturn = new ArrayList<OrderCondition>();
    InterimParseResult parseResult = null;
    while (unparsedRest.length() > 0) {
        parseResult = StringParseUtil.parseNextValue(unparsedRest, StringParseUtil.COMMA);
        toReturn.add(parseOrderCondition(parseResult.parsedValue));
        unparsedRest = parseResult.unparsedRest;
    }

    return toReturn;
}