Java Code Examples for org.apache.commons.lang.StringUtils#contains()

The following examples show how to use org.apache.commons.lang.StringUtils#contains() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: azure-devops-intellij   File: UrlHelper.java    License: MIT License 6 votes vote down vote up
public static boolean isSshGitRemoteUrl(final String gitRemoteUrl) {
    if (isGitRemoteUrl(gitRemoteUrl) && isTeamServicesUrl(gitRemoteUrl)) {
        if (StringUtils.startsWithIgnoreCase(gitRemoteUrl, "https://") ||
                StringUtils.startsWithIgnoreCase(gitRemoteUrl, "http://")) {
            return false;
        }

        if (StringUtils.startsWithIgnoreCase(gitRemoteUrl, "ssh://")) {
            return true;
        }

        // check for @ in url - team project name, repo name, collection name and account name don't allow @
        // E.g of valid url formats:
        // ssh://[email protected]:22/Collection/_git/Repo
        // [email protected]:22/Collection/_git/Repo
        if (StringUtils.contains(gitRemoteUrl, "@")) {
            return true;
        }
    }
    return false;
}
 
Example 2
public void testAllLookupableHelperServicesArePrototypes() throws Exception {
    List<String> failingBeans = new ArrayList<String>();

    Map<String,LookupableHelperService> beans = SpringContext.getBeansOfType(LookupableHelperService.class);
    Map<String,LookupableHelperService> beans2 = SpringContext.getBeansOfType(LookupableHelperService.class);

    for ( String beanName : beans.keySet() ) {
        BeanDefinition beanDef = SpringContext.applicationContext.getBeanFactory().getBeanDefinition(beanName);
        // skip entries in the rice import files or in testing files
        if ( StringUtils.contains( beanDef.getResourceDescription(), "spring-kfs-imported-rice-beans.xml" )
                || StringUtils.contains( beanDef.getResourceDescription(), "-test.xml" ) ) {
            continue;
        }
        if ( ProxyUtils.getTargetIfProxied( beans.get(beanName) ).equals(ProxyUtils.getTargetIfProxied( beans2.get(beanName) )) ) {
            failingBeans.add( "\n *** " + beanName + " is a singleton and should not be. (" + beanDef.getResourceDescription() + ")" );
        }
    }
    assertEquals( "Beans Failing Non-Singleton check: " + failingBeans, 0, failingBeans.size() );
}
 
Example 3
Source Project: canal-1.1.3   File: LogEventConvert.java    License: Apache License 2.0 6 votes vote down vote up
private TableMeta getTableMeta(String dbName, String tbName, boolean useCache, EntryPosition position) {
    try {
        return tableMetaCache.getTableMeta(dbName, tbName, useCache, position);
    } catch (Throwable e) {
        String message = ExceptionUtils.getRootCauseMessage(e);
        if (filterTableError) {
            if (StringUtils.contains(message, "errorNumber=1146") && StringUtils.contains(message, "doesn't exist")) {
                return null;
            } else if (StringUtils.contains(message, "errorNumber=1142")
                       && StringUtils.contains(message, "command denied")) {
                return null;
            }
        }

        throw new CanalParseException(e);
    }
}
 
Example 4
Source Project: sonar-ruby-plugin   File: ClassCountParser.java    License: MIT License 6 votes vote down vote up
public static int countClasses(File file) {
    int numClasses = 0;
    LineIterator iterator = null;
    try {
        iterator = FileUtils.lineIterator(file);

        while (iterator.hasNext()) {
            String line = iterator.nextLine();
            if (StringUtils.contains(line.trim(), "class ")) {
                numClasses++;
            }
        }
    } catch (IOException e) {
        LOG.error("Error determining class count for file " + file, e);
    } finally {
        LineIterator.closeQuietly(iterator);
    }

    return numClasses;
}
 
Example 5
public DefaultDatabaseModuleCfg(YMP owner) throws Exception {
    this.owner = owner;
    //
    IConfigReader _moduleCfg = MapSafeConfigReader.bind(owner.getConfig().getModuleConfigs(IDatabase.MODULE_NAME));
    //
    this.dataSourceDefaultName = _moduleCfg.getString(DS_DEFAULT_NAME, IConfig.DEFAULT_STR);
    //
    this.dataSourceCfgMetas = new HashMap<String, DataSourceCfgMeta>();
    String _dsNameStr = _moduleCfg.getString(DS_NAME_LIST, IConfig.DEFAULT_STR);
    if (StringUtils.contains(_dsNameStr, this.dataSourceDefaultName)) {
        String[] _dsNameList = StringUtils.split(_dsNameStr, "|");
        for (String _dsName : _dsNameList) {
            DataSourceCfgMeta _meta = __doParserDataSourceCfgMeta(_dsName, _moduleCfg.getMap("ds." + _dsName + "."));
            if (_meta != null) {
                this.dataSourceCfgMetas.put(_dsName, _meta);
            }
        }
    } else {
        throw new IllegalArgumentException("The default datasource name does not match");
    }
}
 
Example 6
Source Project: tddl5   File: Version.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 根据jar包的路径,找到对应的版本号
 */
public static String getVerionByPath(String file) {
    if (file != null && file.length() > 0 && StringUtils.contains(file, ".jar")) {
        int index = StringUtils.indexOf(file, ".jar");
        file = file.substring(0, index);
        int i = file.lastIndexOf('/');
        if (i >= 0) {
            file = file.substring(i + 1);
        }
        i = file.indexOf("-");
        if (i >= 0) {
            file = file.substring(i + 1);
        }
        while (file.length() > 0 && !Character.isDigit(file.charAt(0))) {
            i = file.indexOf("-");
            if (i >= 0) {
                file = file.substring(i + 1);
            } else {
                break;
            }
        }
        return file;
    } else {
        return null;
    }
}
 
Example 7
/**
 * Adds to the criteria object based on query characters given
 */
protected void addStringRangeCriteria(String propertyName, String propertyValue, boolean caseInsensitive, Predicates criteria) {
    try {
        if (StringUtils.contains(propertyValue, SearchOperator.BETWEEN.op())) {
            String[] rangeValues = StringUtils.split(propertyValue, SearchOperator.BETWEEN.op());
            if (rangeValues.length < 2) {
	throw new IllegalArgumentException("Improper syntax of BETWEEN operator in " + propertyName);
}

            addBetween(criteria, propertyName, rangeValues[0], rangeValues[1], caseInsensitive);
        } else if (propertyValue.startsWith(SearchOperator.GREATER_THAN_EQUAL.op())) {
            addGreaterThanOrEqual(criteria, propertyName, LookupUtils.scrubQueryCharacters(propertyValue), caseInsensitive);
        } else if (propertyValue.startsWith(SearchOperator.LESS_THAN_EQUAL.op())) {
            addLessThanOrEqual(criteria, propertyName, LookupUtils.scrubQueryCharacters(propertyValue), caseInsensitive);
        } else if (propertyValue.startsWith(SearchOperator.GREATER_THAN.op())) {
            addGreaterThan(criteria, propertyName, LookupUtils.scrubQueryCharacters(propertyValue), caseInsensitive);
        } else if (propertyValue.startsWith(SearchOperator.LESS_THAN.op())) {
            addLessThan(criteria, propertyName, LookupUtils.scrubQueryCharacters(propertyValue), caseInsensitive);
        } else {
            addEqual(criteria, propertyName, LookupUtils.scrubQueryCharacters(propertyValue), caseInsensitive);
        }
    } catch (IllegalArgumentException ex) {
        GlobalVariables.getMessageMap().putError("lookupCriteria[" + propertyName + "]", RiceKeyConstants.ERROR_BETWEEN_SYNTAX, propertyName);
    }
}
 
Example 8
/**
 * Returns the prefix of a nested attribute name, or the empty string if the attribute name is not nested.
 *
 * @param attributeName
 * @return everything BEFORE the last "." character in attributeName
 */
public static String getNestedAttributePrefix(String attributeName) {
    String prefix = "";

    if (StringUtils.contains(attributeName, ".")) {
        prefix = StringUtils.substringBeforeLast(attributeName, ".");
    }

    return prefix;
}
 
Example 9
Source Project: ymate-platform-v2   File: RuntimeUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param origin 原始字符串
 * @return 替换${root}、${user.dir}和${user.home}环境变量
 */
public static String replaceEnvVariable(String origin) {
    if ((origin = StringUtils.trimToNull(origin)) != null) {
        String _defaultPath = getRootPath();
        if (StringUtils.contains(origin, "${root}")) {
            origin = ExpressionUtils.bind(origin).set("root", _defaultPath).getResult();
        } else if (StringUtils.contains(origin, "${user.dir}")) {
            origin = ExpressionUtils.bind(origin).set("user.dir", System.getProperty("user.dir", _defaultPath)).getResult();
        } else if (StringUtils.contains(origin, "${user.home}")) {
            origin = ExpressionUtils.bind(origin).set("user.home", System.getProperty("user.home", _defaultPath)).getResult();
        }
    }
    return origin;
}
 
Example 10
Source Project: sofa-acts   File: ObjectUnitProperty.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param fieldName
 * @param fieldType
 * @param flagCode
 * @param referedValue
 * @return
 */
protected Object generateSimpleProperty(String fieldName, Class<?> fieldType, String flagCode,
                                        Object referedValue) {
    Object fieldValue = null;
    if (referedValue == null || StringUtils.isBlank(String.valueOf(referedValue))) {
        return fieldValue;
    }

    if (StringUtils.contains(String.valueOf(referedValue), "BigDecimal.csv")) {
        referedValue = "0.01";
    }

    switch (UnitFlagEnum.getByCode(flagCode)) {
        case F:
            return FileUtil.readFile(FileUtil.getRelativePath(String.valueOf(referedValue),
                this.targetCSVPath));
        case D:
        case C:
        case Y:
            return objectTypeManager.getSimpleObject(fieldType, String.valueOf(referedValue),
                fieldName, fieldType.getName());
        default:
            Assert.fail(this.keyPath + "." + fieldName + "cant't create object, current flag:"
                        + flagCode);
            break;
    }
    return fieldValue;
}
 
Example 11
/**
 * Validates the given value exist for the attribute. SECURITY_ATTRIBUTE_METADATA_MAP maps the attribute to the business object class and primitive key field need to do the
 * existence search.
 * 
 * @param attributeName name of attribute for value
 * @param attributeValue the value to validate
 * @param errorKeyPrefix prefix for error key if the value does not exist
 * @return boolean true if the value exist, false if it does not
 */
public static boolean validateAttributeValue(String attributeName, String attributeValue, String errorKeyPrefix) {
    boolean isValid = true;

    if (!SecConstants.SECURITY_ATTRIBUTE_METADATA_MAP.containsKey(attributeName)) {
        return isValid;
    }
    SecurityAttributeMetadata attributeMetadata = (SecurityAttributeMetadata) SecConstants.SECURITY_ATTRIBUTE_METADATA_MAP.get(attributeName);

    String[] attributeValues;
    if (StringUtils.contains(attributeValue, SecConstants.SecurityValueSpecialCharacters.MULTI_VALUE_SEPERATION_CHARACTER)) {
        attributeValues = StringUtils.split(attributeValue, SecConstants.SecurityValueSpecialCharacters.MULTI_VALUE_SEPERATION_CHARACTER);
    }
    else {
        attributeValues = new String[1];
        attributeValues[0] = attributeValue;
    }

    for (int i = 0; i < attributeValues.length; i++) {
        if (!StringUtils.contains(attributeValues[i], SecConstants.SecurityValueSpecialCharacters.WILDCARD_CHARACTER)) {
            Map<String, String> searchValues = new HashMap<String, String>();
            searchValues.put(attributeMetadata.getAttributeField(), attributeValues[i]);

            int matches = SpringContext.getBean(BusinessObjectService.class).countMatching(attributeMetadata.getAttributeClass(), searchValues);
            if (matches <= 0) {
                GlobalVariables.getMessageMap().putError(errorKeyPrefix + SecPropertyConstants.ATTRIBUTE_VALUE, SecKeyConstants.ERROR_ATTRIBUTE_VALUE_EXISTENCE, attributeValues[i], attributeName);
                isValid = false;
            }
        }
    }

    return isValid;
}
 
Example 12
Source Project: DesignPatterns   File: AssertUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void assertValidString(String str, boolean isJsonFormat) {
    if (StringUtils.isEmpty(str)) {
        return;
    }
    for (char c : str.toCharArray()) {
        if (StringUtils.contains(INVALID_CHARS, c)) {
            throw new BusinessValidationException("Invalid characters input.");
        }
    }
}
 
Example 13
protected void testRoleLinkFieldDefault() throws Exception {
    jGrowl("-- testRoleLinkFieldDefault");
    WebElement exampleDiv = navigateToExample(DEMO_PAGE_ID1);
    assertTextPresent(DEMO_PAGE_HEADER1);

    WebElement field = findElement(By.cssSelector(UIF_LINK_CSS_SELECTOR), exampleDiv);
    List<WebElement> links = exampleDiv.findElements(By.className(UIF_LINK_CLASSNAME));
    assertEquals("Number of expected role field links not found on page.", 2, links.size());

    for ( WebElement link : links) {
        String href =  link.getAttribute(HREF_ATTRIBUTE);
        if ( !StringUtils.contains(href, INQUIRY)) {
            fail("Inquiry not found in link.");
        }

        if ( !(StringUtils.contains(href, ROLE_INQUIRY_KEY_ID1) ||
                (StringUtils.contains(href, ROLE_INQUIRY_KEY_NAMESPACECODE2) &&
                        StringUtils.contains(href, ROLE_INQUIRY_KEY_NAME2)))) {
            fail("Role inquiry keys not found in href.");
        }

        String linkText = link.getText();
        if ( !(StringUtils.contains(linkText, ROLE_LINKTEXT1) ||
               StringUtils.contains(linkText, ROLE_LINKTEXT2))) {
            fail("Role names in linkText not found");
        }
    }

    field = findElement(By.linkText(ROLE_LINKTEXT1), exampleDiv);
    verifyLinkDataItem(field, LABEL_ROLE_NAME, ROLE_NAME1);

    field = findElement(By.linkText(ROLE_LINKTEXT2), exampleDiv);
    verifyLinkDataItem(field, LABEL_ROLE_NAME, ROLE_NAME2);
}
 
Example 14
@Override
public boolean check(Map<String, Object> param) {
    target = param.get("target").toString();
    crawlerPage.getRequest().setUrl(target.concat(payload));
    fetcher.run(crawlerPage);
    String text = crawlerPage.getResponse().getStatus().getContentString();
    if (StringUtils.contains(text,"PHP Version"))
    {
        r.add("存在漏洞"+target.concat(payload));
        return true;
    }
    return false;
}
 
Example 15
/**
 * Determines if a given string could represent a nested attribute of an object.
 *
 * @param attributeName
 * @return true if the attribute is nested
 */
public static boolean isNestedAttribute(String attributeName) {
    boolean isNested = false;

    if (StringUtils.contains(attributeName, ".")) {
        isNested = true;
    }

    return isNested;
}
 
Example 16
private void extractPages() {
	if (isPageRange()) {
		String[] pagesArray = getPages().split(PAGES_SEPARATOR);
		for (String pageItem : pagesArray) {
			if (!StringUtils.isBlank(pageItem)) {
				if (StringUtils.contains(pageItem, PAGE_RANGE_SEPARATOR)) {
					extractPageRange(pageItem);
				} else {
					getPagesList().add(Integer.parseInt(StringUtils.trim(pageItem)));
				}
			}
		}		
	}
	fixPagesForLayout();
}
 
Example 17
/**
 * Executes the http request and parses the returned stream.
 */
private void executeRequest(Weather weather, String url, LocationConfig locationConfig) throws Exception {
    try {
        logger.trace("{}[{}]: request : {}", getProviderName(), locationConfig.getLocationId(), url);

        String response = StringUtils.trimToEmpty(HttpUtil.executeUrl("GET", url, 15000));

        /**
         * special handling because of identical current and forecast json structure
         * if 'url' contains "forecast" replace data key with forecast
         */
        if ((weather.getProvider() == ProviderName.WEATHERBIT) && StringUtils.contains(url, "forecast/daily")) {
            // replace data with forecast
            response = StringUtils.replace(response, "data", "forecast");
        }

        if (logger.isTraceEnabled()) {
            response = StringUtils.remove(response, "\n");
            response = StringUtils.trim(response);
            logger.trace("{}[{}]: response: {}", getProviderName(), locationConfig.getLocationId(), response);
        }

        if (!response.isEmpty()) {
            parser.parseInto(response, weather);
        }

        // special handling because of bad OpenWeatherMap json structure
        if (weather.getProvider() == ProviderName.OPENWEATHERMAP && weather.getResponseCode() != null
                && weather.getResponseCode() == 200) {
            weather.setError(null);
        }

        if (!weather.hasError() && response.isEmpty()) {
            weather.setError("Error: response is empty!");
        }

        if (weather.hasError()) {
            logger.error("{}[{}]: Can't retrieve weather data: {}", getProviderName(),
                    locationConfig.getLocationId(), weather.getError());
        } else {
            setLastUpdate(weather);
        }
    } catch (Exception ex) {
        logger.error(getProviderName() + ": " + ex.getMessage());
        weather.setError(ex.getClass().getSimpleName() + ": " + ex.getMessage());
        throw ex;
    }
}
 
Example 18
/**
 * @param printBusinessObjectValues indicates whether the bo values should be printed before the message
 * @see org.kuali.kfs.sys.service.ReportWriterService#writeError(java.lang.Class, org.kuali.kfs.sys.Message)
 */
public void writeError(BusinessObject businessObject, Message message, boolean printBusinessObjectValues) {
    // Check if we need to write a new table header. We do this if it hasn't been written before or if the businessObject
    // changed
    if (newPage || businessObjectClass == null || !businessObjectClass.getName().equals(businessObject.getClass().getName())) {
        if (businessObjectClass == null) {
            // If we didn't write the header before, write it with a subTitle
            this.writeSubTitle(errorSubTitle);
        }
        else if (!businessObjectClass.getName().equals(businessObject.getClass().getName())) {
            // If it changed push a newline in for neater formatting
            this.writeNewLines(1);
        }

        this.writeErrorHeader(businessObject);
        newPage = false;
        businessObjectClass = businessObject.getClass();
    }

    // Get business object formatter that will be used
    BusinessObjectReportHelper businessObjectReportHelper = getBusinessObjectReportHelper(businessObject);

    // Print the values of the businessObject per formatting determined by writeErrorHeader
    List<Object> formatterArgs = new ArrayList<Object>();
    if (printBusinessObjectValues) {
        formatterArgs.addAll(businessObjectReportHelper.getValues(businessObject));
    }
    else {
        formatterArgs.addAll(businessObjectReportHelper.getBlankValues(businessObject));
    }

    // write rest of message on new line(s) if it was cut off
    int maxMessageLength = Integer.parseInt(StringUtils.substringBefore(StringUtils.substringAfterLast(errorFormat, "%-"), "s"));
    String messageToPrint = message.getMessage();

    boolean firstMessageLine = true;
    while (messageToPrint.length() > 0 && StringUtils.isNotBlank(messageToPrint)) {
        if (!firstMessageLine) {
            formatterArgs = new ArrayList<Object>();
            formatterArgs.addAll(businessObjectReportHelper.getBlankValues(businessObject));
        }
        else {
            firstMessageLine = false;
        }

        messageToPrint =  StringUtils.trim(messageToPrint);
        String messageLine = messageToPrint;
        if (messageLine.length() > maxMessageLength) {
            messageLine = StringUtils.substring(messageLine, 0, maxMessageLength);
            if (StringUtils.contains(messageLine, " ")) {
                messageLine = StringUtils.substringBeforeLast(messageLine, " ");
            }
        }

        formatterArgs.add(new Message(messageLine, message.getType()));
        this.writeFormattedMessageLine(errorFormat, formatterArgs.toArray());

        messageToPrint = StringUtils.removeStart(messageToPrint, messageLine);
    }
}
 
Example 19
Source Project: symphonyx   File: FileUploadServlet.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    if (QN_ENABLED) {
        return;
    }

    final LatkeBeanManager beanManager = Lifecycle.getBeanManager();
    final UserQueryService userQueryService = beanManager.getReference(UserQueryService.class);
    final UserMgmtService userMgmtService = beanManager.getReference(UserMgmtService.class);
    final OptionQueryService optionQueryService = beanManager.getReference(OptionQueryService.class);

    try {
        final JSONObject option = optionQueryService.getOption(Option.ID_C_MISC_ALLOW_ANONYMOUS_VIEW);
        if (!"0".equals(option.optString(Option.OPTION_VALUE))) {
            if (null == userQueryService.getCurrentUser(req) && !userMgmtService.tryLogInWithCookie(req, resp)) {
                final String referer = req.getHeader("Referer");
                if (!StringUtils.contains(referer, "fangstar.net")) {
                    final String authorization = req.getHeader("Authorization");

                    LOGGER.debug("Referer [" + referer + "], Authorization [" + authorization + "]");

                    if (!StringUtils.contains(authorization, "Basic ")) {
                        resp.sendError(HttpServletResponse.SC_FORBIDDEN);

                        return;
                    } else {
                        String usernamePwd = StringUtils.substringAfter(authorization, "Basic ");
                        usernamePwd = Base64.decodeToString(usernamePwd);

                        final String username = usernamePwd.split(":")[0];
                        final String password = usernamePwd.split(":")[1];

                        if (!StringUtils.equals(username, Symphonys.get("http.basic.auth.username"))
                                || !StringUtils.equals(password, Symphonys.get("http.basic.auth.password"))) {
                            resp.sendError(HttpServletResponse.SC_FORBIDDEN);

                            return;
                        }
                    }
                }
            }
        }
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Gets file failed", e);

        resp.sendError(HttpServletResponse.SC_FORBIDDEN);

        return;
    }

    final String uri = req.getRequestURI();
    String key = uri.substring("/upload/".length());
    key = StringUtils.substringBeforeLast(key, "-64.jpg"); // Erase Qiniu template
    key = StringUtils.substringBeforeLast(key, "-260.jpg"); // Erase Qiniu template

    String path = UPLOAD_DIR + key;

    if (!FileUtil.isExistingFile(new File(path))) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);

        return;
    }

    final byte[] data = IOUtils.toByteArray(new FileInputStream(path));

    final String ifNoneMatch = req.getHeader("If-None-Match");
    final String etag = "\"" + MD5.hash(new String(data)) + "\"";

    resp.addHeader("Cache-Control", "public, max-age=31536000");
    resp.addHeader("ETag", etag);
    resp.setHeader("Server", "Latke Static Server (v" + SymphonyServletListener.VERSION + ")");

    if (etag.equals(ifNoneMatch)) {
        resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);

        return;
    }

    final OutputStream output = resp.getOutputStream();
    IOUtils.write(data, output);
    output.flush();

    IOUtils.closeQuietly(output);
}
 
Example 20
/**
 * Whether a question with a given ID has already been asked
 * 
 * @param id the ID of the question, an arbitrary value, but must be consistent
 * @return
 */
public boolean hasAsked(String id) {
    return StringUtils.contains(event.getQuestionContext(), id);
}