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

The following are Jave code examples for showing how to use contains() of the org.apache.commons.lang.StringUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: Hydrograph   File: IntegerOrParameterValidationRule.java   Source Code and License Vote up 7 votes
@Override
public boolean validate(Object object, String propertyName,Map<String,List<FixedWidthGridRow>> inputSchemaMap,
		boolean isJobImported){
	String value = (String) object;
	if(StringUtils.isNotBlank(value)){
		Matcher matcher=Pattern.compile("[\\d]*").matcher(value);
		if((matcher.matches())|| 
			((StringUtils.startsWith(value, "@{") && StringUtils.endsWith(value, "}")) &&
					!StringUtils.contains(value, "@{}"))){
			return true;
		}
		errorMessage = propertyName + " is mandatory";
	}
	errorMessage = propertyName + " is not integer value or valid parameter";
	return false;
}
 
Example 2
Project: EscapeLag   File: AntiSpam.java   Source Code and License Vote up 6 votes
@EventHandler
public void checkSign(SignChangeEvent event) {
	if (ConfigFunction.AntiSpamenable && ConfigFunction.enableAntiDirty) {
		String[] lines = event.getLines();
		for (String line : lines) {
			Player player = event.getPlayer();
			if (AzureAPI.hasPerm(player, "EscapeLag.bypass.Spam")) {
				return;
			}
			for (String each : ConfigFunction.AntiSpamDirtyList) {
				boolean deny = true;
				for (char c : each.toLowerCase().toCharArray()) {
					if (!StringUtils.contains(line, c))
						deny = false;
				}
				if (deny) {
					event.setCancelled(true);
					AzureAPI.log(player, ConfigFunction.AntiSpamDirtyWarnMessage);
				}
			}
		}
	}
}
 
Example 3
Project: EscapeLag   File: AntiSpam.java   Source Code and License Vote up 6 votes
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void checkDirty(AsyncPlayerChatEvent evt) {
	if (ConfigFunction.AntiSpamenable && ConfigFunction.enableAntiDirty) {
		Player player = evt.getPlayer();
		String message = evt.getMessage().toLowerCase();
		if (AzureAPI.hasPerm(player, "EscapeLag.bypass.Spam")) {
			return;
		}

		for (String each : ConfigFunction.AntiSpamDirtyList) {
			boolean deny = true;
			for (char c : each.toLowerCase().toCharArray()) {
				if (!StringUtils.contains(message, c))
					deny = false;
			}
			if (deny) {
				evt.setCancelled(true);
				AzureAPI.log(player, ConfigFunction.AntiSpamDirtyWarnMessage);
			}
		}
	}
}
 
Example 4
Project: sling-org-apache-sling-query   File: JcrQueryBuilder.java   Source Code and License Vote up 6 votes
private static Formula prepareSegmentConditions(String resourceType, String resourceName,
		List<Attribute> attributes) {
	List<Term> conditions = new ArrayList<>();
	if (StringUtils.isNotBlank(resourceType) && !StringUtils.contains(resourceType, ':')) {
		conditions.add(new Atomic(String.format("s.[sling:resourceType] = '%s'", resourceType)));
	}
	if (StringUtils.isNotBlank(resourceName)) {
		conditions.add(new Atomic(String.format("NAME(s) = '%s'", resourceName)));
	}
	if (attributes != null) {
		for (Attribute a : attributes) {
			String attributeCondition = getAttributeCondition(a);
			if (StringUtils.isNotBlank(attributeCondition)) {
				conditions.add(new Atomic(attributeCondition));
			}
		}
	}
	if (conditions.isEmpty()) {
		return null;
	} else {
		return new Formula(Operator.AND, conditions);
	}
}
 
Example 5
Project: formatter   File: FormatUtil.java   Source Code and License Vote up 6 votes
/**
* 
* @Title: isJson 
* @Description: Check if it is JSON string 
* @param @param content
* @param @return 
* @return boolean
* @throws
 */
public static boolean isJson(String json)
{
    if (StringUtils.isEmpty(json))
    {
        return false;
    }

    if (!StringUtils.contains(json, "{"))
    {
        return false;
    }

    JsonParser p = new JsonParser();
    try
    {
        p.parse(json);
    }
    catch(JsonSyntaxException e)
    {
        return false;
    }

    return true;
}
 
Example 6
Project: Yidu   File: CreateSiteMapJob.java   Source Code and License Vote up 6 votes
/**
 * 构造小说阅读页URL
 * 
 * @param chapter
 *            章节信息
 * @return 小说阅读页URL
 */
private String constructURL(TChapter chapter, boolean isCreateMobileSiteMap) {
    String loc = YiDuConstants.yiduConf.getString(YiDuConfig.XML_SITEMAP_READER_URL);
    String uri = YiDuConstants.yiduConf.getString(YiDuConfig.URI);
    if (isCreateMobileSiteMap) {
        uri = YiDuConstants.yiduConf.getString(YiDuConfig.MOBILE_URI);
    }
    int subDir = chapter.getArticleno() / YiDuConstants.SUB_DIR_ARTICLES;
    int articleNo = chapter.getArticleno();
    int chapterNo = chapter.getChapterno();

    if (StringUtils.contains(loc, "{pinyin}")) {
        TArticle article = articleService.getByNo(articleNo);
        loc = loc.replace("{sub_dir}", String.valueOf(subDir)).replace("{article_no}", String.valueOf(articleNo))
                .replace("{chapter_no}", String.valueOf(chapterNo))
                .replace("{pinyin}", String.valueOf(article.getPinyin()));
    } else {
        loc = loc.replace("{sub_dir}", String.valueOf(subDir)).replace("{article_no}", String.valueOf(articleNo))
                .replace("{chapter_no}", String.valueOf(chapterNo));
    }
    if (!uri.endsWith("/") && !loc.startsWith("/")) {
        uri += "/";
    }
    return uri + loc;
}
 
Example 7
Project: Yidu   File: CreateStructuringDataJob.java   Source Code and License Vote up 6 votes
/**
 * 构造小说阅读页URL
 * 
 * @param chapter
 *            章节信息
 * @return 小说阅读页URL
 */
private String constructReaderURL(int articleNo, int chapterNo, boolean isCreateMobileSiteMap) {
    String loc = YiDuConstants.yiduConf.getString(YiDuConfig.XML_SITEMAP_READER_URL);
    String uri = YiDuConstants.yiduConf.getString(YiDuConfig.URI);
    if (isCreateMobileSiteMap) {
        uri = YiDuConstants.yiduConf.getString(YiDuConfig.MOBILE_URI);
    }
    int subDir = articleNo / YiDuConstants.SUB_DIR_ARTICLES;

    if (StringUtils.contains(loc, "{pinyin}")) {
        TArticle article = articleService.getByNo(articleNo);
        loc = loc.replace("{sub_dir}", String.valueOf(subDir)).replace("{article_no}", String.valueOf(articleNo))
                .replace("{chapter_no}", String.valueOf(chapterNo)).replace("{pinyin}", String.valueOf(article.getPinyin()));
    } else {
        loc = loc.replace("{sub_dir}", String.valueOf(subDir)).replace("{article_no}", String.valueOf(articleNo))
                .replace("{chapter_no}", String.valueOf(chapterNo));
    }
    if (!uri.endsWith("/") && !loc.startsWith("/")) {
        uri += "/";
    }
    return uri + loc;
}
 
Example 8
Project: Hydrograph   File: MethodDetails.java   Source Code and License Vote up 5 votes
private void createPlaceHolderFromSource(IMethod iMethod, String className) throws JavaModelException {
	StringBuffer buffer = new StringBuffer(iMethod.getSource());
	int indexOfPlaceHolder = buffer.lastIndexOf("@see");
	if (indexOfPlaceHolder != -1 && iMethod.getParameterNames() != null && iMethod.getParameterNames().length > 0) {
		buffer = buffer.delete(0, indexOfPlaceHolder + 4);
		buffer = buffer.delete(buffer.indexOf("\n")+1, buffer.capacity());
		if(StringUtils.contains(buffer.toString(), className + Constants.DOT+iMethod.getElementName())){
			placeHolder = StringUtils.trim(buffer.toString());
		}
		else
			placeHolder = createDefaultPlaceHolder(iMethod, className);
	} else {
		placeHolder = createDefaultPlaceHolder(iMethod, className);
	}
}
 
Example 9
Project: DBus   File: LogEventConvert.java   Source Code and License Vote up 5 votes
private TableMeta getTableMeta(String dbName, String tbName, boolean useCache) {
    try {
        return tableMetaCache.getTableMeta(dbName, tbName, useCache);
    } catch (Exception e) {
        String message = ExceptionUtils.getRootCauseMessage(e);
        if (filterTableError) {
            if (StringUtils.contains(message, "errorNumber=1146") && StringUtils.contains(message, "doesn't exist")) {
                return null;
            }
        }

        throw new CanalParseException(e);
    }
}
 
Example 10
Project: cas-modules   File: X509CredentialsToPrincipalResolver.java   Source Code and License Vote up 5 votes
public static String getDistinguishedNameField(String certificateSubject, String fieldName) {
   String fieldValue = substringAfter(certificateSubject, fieldName + "=");
   // If serial number contains ',' then it is not the last value
   if (StringUtils.contains(fieldValue, ',')) {
      fieldValue = substringBefore(fieldValue, ",");
   }
   if (log.isDebugEnabled()) {
      log.debug("Parsed " + fieldName + " =" + fieldValue);
   }
   return trimToNull(fieldValue);
}
 
Example 11
Project: kaltura-ce-sakai-extension   File: MediaService.java   Source Code and License Vote up 5 votes
/**
 * Retrieve a media item for a playlist (only if it exists in the playlist)
 * 
 * @param kalturaEntryId the kaltura entry id of this media item
 * @param collection the collction (with playlist) that contains the entry
 * @param populate if true then populate the item with permissions and content
 * @return a populated media item OR null if none is found with the given id in the given collection
 * @throws IllegalArgumentException if the params are invalid
 * @throws SecurityException if the user does not have permissions
 */
public MediaItem getCollectionMediaItem(String kalturaEntryId, MediaCollection collection, boolean populate) {
    if (StringUtils.isEmpty(kalturaEntryId)) {
        throw new IllegalArgumentException("kalturaEntryId must not be null");
    }
    if (collection == null) {
        throw new IllegalArgumentException("collection must not be null");
    }
    KalturaPlaylist playlist = collection.getKalturaPlaylist();
    if (playlist == null) {
        throw new IllegalArgumentException("playlist must not be null");
    }
    // verify the entry is a real one
    KalturaMediaEntry kme = kalturaAPIService.getKalturaItem(kalturaEntryId);
    if (kme == null) {
        throw new RuntimeException("kaltura media entry doesn't exist");
    }
    String collectionId = playlist.id;
    boolean playlistContainsItem = StringUtils.contains(playlist.playlistContent, kalturaEntryId);
    MediaItem mi = null;
    if (playlistContainsItem) {
        /* collection is input now
        String locationId = findLocationFromPlaylist(playlist);
        Map<String, String> plMetadata = kalturaAPIService.getPlaylistMetadataFields(playlist.id).get(collectionId);
        MediaCollection mc = new MediaCollection(playlist, locationId, plMetadata);
        */
        Map<String, String> kmeMetadata = kalturaAPIService.getMetadataForEntry(playlist.id, kalturaEntryId).get(kalturaEntryId);
        mi = new MediaItem(collection, kme, kmeMetadata);
        populateMediaItemData(mi); // fill in the permissions
        if (! canViewMI(mi, collection) ) {
            throw new SecurityException("user (" + external.getCurrentUserId() + ") cannot view item (" + kalturaEntryId + ") in collection ("+collectionId+")");
        }
        if (populate) {
            populateItem(mi);
        }
    }
    return mi;
}
 
Example 12
Project: Hydrograph   File: PreStartActivity.java   Source Code and License Vote up 5 votes
/**
 * Checks whether tool is launched in development mode.
 * 
 * @param argumentsMap
 * @return true if tool is launched in development mode, else returns false
 */
@SuppressWarnings("unchecked")
public static boolean isDevLaunchMode(Map argumentsMap) {
	 logger.debug("Checking whether tool is launched in development mode");
	 for(Entry< Object, String[]> entry:((Map<Object, String[]>)argumentsMap).entrySet()){
			for(String value:entry.getValue()){
				if(StringUtils.contains(value, DOSGI_REQUIRED_JAVA_VERSION_PARAMETER_IN_INI_FILE)){
					return false;
				}
			}
		}
		return true;
	}
 
Example 13
Project: Hydrograph   File: SCPUtility.java   Source Code and License Vote up 5 votes
private Message getErrorMessage(Exception e) {
	if(StringUtils.contains(e.getMessage(), UNKNOWN_HOST_EXCEPTION)){
		return new Message(MessageType.UNKNOWN_HOST, UNKNOWN_HOST_MESSAGE); 
	}else if(StringUtils.contains(e.getMessage(), AUTH_FAIL_EXCEPTION)){
		return new Message(MessageType.INVALID_USERNAME_PASSWORD, AUTHENTICATION_FAILED_MESSAGE); 
	}else{
		return new Message(MessageType.ERROR, GENERAL_ERROR_MESSAGE);
	}
}
 
Example 14
Project: lams   File: Configuration.java   Source Code and License Vote up 5 votes
/**
    * Get contents of lams_configuration and group them using header names as key.
    *
    * @param filter
    *            ITEMS_ALL: include all items; ITEMS_NON_LDAP: include non-ldap items only; ITEMS_ONLY_LDAP: include
    *            ldap-only items.
    * @return
    */
   public HashMap<String, ArrayList<ConfigurationItem>> arrangeItems(int filter) {
List<ConfigurationItem> originalList = Configuration.getAllItems();
HashMap<String, ArrayList<ConfigurationItem>> groupedList = new HashMap<String, ArrayList<ConfigurationItem>>();

for (int i = 0; i < originalList.size(); i++) {
    ConfigurationItem item = originalList.get(i);
    String header = item.getHeaderName();

    switch (filter) {
	case ITEMS_ALL:
	    // all items included
	    break;
	case ITEMS_NON_LDAP:
	    // non-ldap items only
	    if (StringUtils.contains(header, "config.header.ldap")) {
		continue;
	    }
	    break;
	case ITEMS_ONLY_LDAP:
	    // ldap-only items
	    if (!StringUtils.contains(header, "config.header.ldap")) {
		continue;
	    }
	    break;
	default:
	    break;
    }

    if (!groupedList.containsKey(header)) {
	groupedList.put(header, new ArrayList<ConfigurationItem>());
    }
    ArrayList<ConfigurationItem> currentList = groupedList.get(header);
    currentList.add(item);
    groupedList.put(header, currentList);
}

return groupedList;
   }
 
Example 15
Project: Hydrograph   File: ParameterFileManager.java   Source Code and License Vote up 5 votes
private Map<String, String> updatePropertyMap(Map<String, String> parameterMap){
	Map<String,String> map=new  LinkedHashMap<>(parameterMap);
	for(Entry<String, String> entry:parameterMap.entrySet()){
		if(StringUtils.contains(entry.getValue(), ESCAPE_CHAR)){
			map.put(entry.getKey(), StringUtils.replaceChars(entry.getValue(),ESCAPE_CHAR, BACKWARD_SLASH));
		}
	}
	return map;
}
 
Example 16
Project: Hydrograph   File: FTPProtocolSelectionValidator.java   Source Code and License Vote up 5 votes
private boolean validatePort(String text, String propertyName){
	if(StringUtils.isNotBlank(text)){
		Matcher matcher=Pattern.compile("[\\d]*").matcher(text);
		if((matcher.matches())|| 
			((StringUtils.startsWith(text, "@{") && StringUtils.endsWith(text, "}")) &&
					!StringUtils.contains(text, "@{}"))){
			return true;
		}
		errorMessage = propertyName + " is mandatory";
	}
	errorMessage = propertyName + " is not integer value or valid parameter";
	return false;
}
 
Example 17
Project: satisfy   File: PDFWords.java   Source Code and License Vote up 4 votes
private boolean isContaining(String expectedValue, boolean ignoreCase, String content) {
    return ignoreCase ? StringUtils.containsIgnoreCase(content, expectedValue) : StringUtils.contains(content, expectedValue);
}
 
Example 18
Project: Hydrograph   File: ValidateExpressionToolButton.java   Source Code and License Vote up 4 votes
public static Object[] getBuildPathForMethodInvocation() throws JavaModelException, MalformedURLException {
	String transfromJarPath = null;
	Object[] returnObj=new Object[3];
	IJavaProject iJavaProject = JavaCore.create(BuildExpressionEditorDataSturcture.INSTANCE.getCurrentProject());
	List<URL> urlList = new ArrayList<>();
	Properties properties = ConfigFileReader.INSTANCE.getCommonConfigurations();
	for (IPackageFragmentRoot iPackageFragmentRoot : iJavaProject.getAllPackageFragmentRoots()) {
		if (!iPackageFragmentRoot.isExternal()
				|| StringUtils.contains(iPackageFragmentRoot.getElementName(), properties.getProperty(Constants.KEY_TRANSFORMATION_JAR))
				|| StringUtils.contains(iPackageFragmentRoot.getElementName(), Constants.ANTLR_JAR_FILE_NAME)
				|| StringUtils.contains(iPackageFragmentRoot.getElementName(), Constants.BEAN_SHELLJAR_FILE_NAME)
				|| StringUtils.contains(iPackageFragmentRoot.getElementName(), Constants.SL4JLOG)
				|| StringUtils.contains(iPackageFragmentRoot.getElementName(), properties.getProperty(Constants.KEY_EXPRESSION_JAR))) {
			URL url = null;
			if (!iPackageFragmentRoot.isExternal()) {
				url = BuildExpressionEditorDataSturcture.INSTANCE.getCurrentProject()
						.getFile(iPackageFragmentRoot.getPath().removeFirstSegments(1)).getLocation().toFile()
						.toURI().toURL();
				urlList.add(url);
			} else {
				url = iPackageFragmentRoot.getPath().toFile().toURI().toURL();
				urlList.add(url);
			}

			if (!iPackageFragmentRoot.isExternal()
					|| StringUtils.contains(iPackageFragmentRoot.getElementName(), properties.getProperty(Constants.KEY_TRANSFORMATION_JAR))) {
				if (transfromJarPath == null) {
					if (OSValidator.isMac() || OSValidator.isUnix())
						transfromJarPath = url.getPath() + Constants.COLON;
					else
						transfromJarPath = url.getPath() + Constants.SEMICOLON;
				} else {
					if (OSValidator.isMac() || OSValidator.isUnix())
						transfromJarPath = transfromJarPath + url.getPath() + Constants.COLON;
					else
						transfromJarPath = transfromJarPath + url.getPath() + Constants.SEMICOLON;
				}
			}
		}
	}
	
	returnObj[0]=urlList;
	returnObj[1]=transfromJarPath;
	returnObj[2]=getPropertyFilePath(iJavaProject);
	iJavaProject.close();
	return returnObj;
}
 
Example 19
Project: kaltura-ce-sakai-extension   File: KalturaAPIService.java   Source Code and License Vote up 4 votes
/**
 * Decodes the permissions string into a map of values.
 * Keys: containerType, containerId, Owner, Hidden, Reusable, Remixable
 * 
 * @param permissionString the string representation of the permissions
 *      ("site:<siteId>::{<ownerId>}h,S,r" OR "playlist:<playlistId>::{<ownerId>}h,S,r")
 * @param failIfInvalid if true then this will throw an exception if the input string is invalid, otherwise it will return defaults
 * @return Map of permission data OR defaults if input string is invalid
 * @throws IllegalArgumentException if the string decoding fails
 */
protected Map<String, String> decodeMetadataPermissions(String permissionString, boolean failIfInvalid) {
    Map<String, String> decodedPermissions = new HashMap<String, String>(6);
    // check if permissions string is a valid format
    if (StringUtils.isNotEmpty(permissionString) 
            && StringUtils.contains(permissionString, "::{") 
            && (StringUtils.startsWith(permissionString, "site:") || StringUtils.startsWith(permissionString, "playlist:"))) {
        // first find the last "}" in the string (first from the right)
        int braceRight = StringUtils.lastIndexOf(permissionString, '}');
        if (braceRight == -1) {
            throw new IllegalArgumentException("Invalid format- no '}' (e.g. 'site:<site_library_id>::{<ownerId>}h,S,r') for permissions string: "+permissionString);
        }
        // find the last "::{" from the right of the brace
        int braceLeft = StringUtils.lastIndexOf(permissionString, "::{", braceRight);
        if (braceLeft == -1) {
            throw new IllegalArgumentException("Invalid format - no '::{' (e.g. 'site:<site_library_id>::{<ownerId>}h,S,r') for permissions string: "+permissionString);
        }
        // chop the string into the 3 parts dropping the braces and :: separators
        String containerStr = StringUtils.substring(permissionString, 0, braceLeft);
        braceLeft += 2; // shift over to the actual brace
        String ownerId = StringUtils.substring(permissionString, braceLeft+1, braceRight);
        if (StringUtils.isEmpty(ownerId)) {
            throw new IllegalArgumentException("Invalid format - no ownerId (e.g. 'site:<site_library_id>::{<ownerId>}h,S,r') for permissions string: "+permissionString);
        }
        decodedPermissions.put(METADATA_OWNER, ownerId);
        // get the containerId from the first piece
        if (StringUtils.startsWith(containerStr, "site:")) {
            decodedPermissions.put(METADATA_CONTAINER_TYPE, "site");
            decodedPermissions.put(METADATA_CONTAINER_ID, StringUtils.substring(containerStr, 5));
        } else if (StringUtils.startsWith(containerStr, "playlist:")) {
            decodedPermissions.put(METADATA_CONTAINER_TYPE, "playlist");
            decodedPermissions.put(METADATA_CONTAINER_ID, StringUtils.substring(containerStr, 9));
        } else {
            // should never really happen
            throw new IllegalArgumentException("Invalid format - bad prefix (e.g. 'site:<site_library_id>::{<ownerId>}h,S,r') for permissions string: "+permissionString);
        }
        if (StringUtils.isEmpty(decodedPermissions.get(METADATA_CONTAINER_ID))) {
            throw new IllegalArgumentException("Invalid format - no containerId (e.g. 'site:<site_library_id>::{<ownerId>}h,S,r') for permissions string: "+permissionString);
        }
        // split the permissions
        String perms = StringUtils.substring(permissionString, braceRight+1);
        if (StringUtils.isEmpty(perms)) {
            throw new IllegalArgumentException("Invalid format - no perms (e.g. 'site:<site_library_id>::{<ownerId>}h,S,r') for permissions string: "+permissionString);
        }
        // get the permissions ([0] = hidden, [1] = reusable, [2] = remixable)
        String[] permissions = StringUtils.split(perms, ',');
        decodedPermissions.put(METADATA_HIDDEN, permissions[0]);
        decodedPermissions.put(METADATA_REUSABLE, permissions[1]);
        decodedPermissions.put(METADATA_REMIXABLE, permissions[2]);

    } else { // load default metadata
        if (failIfInvalid) {
            throw new IllegalArgumentException("Invalid string format - fails to match basic rules (e.g. not empty, contains '::{' and starts with 'site' or 'playlist') for permissions string: "+permissionString);
        } else {
            decodedPermissions.put(METADATA_CONTAINER_TYPE, "");
            decodedPermissions.put(METADATA_CONTAINER_ID, "");
            decodedPermissions.put(METADATA_OWNER, null);
            decodedPermissions.put(METADATA_HIDDEN, DEFAULT_METADATA_HIDDEN);
            decodedPermissions.put(METADATA_REUSABLE, DEFAULT_METADATA_REUSABLE);
            decodedPermissions.put(METADATA_REMIXABLE, DEFAULT_METADATA_REMIXABLE);
        }
    }
    return decodedPermissions;
}
 
Example 20
Project: Hydrograph   File: Utils.java   Source Code and License Vote up 3 votes
/**
 * 
 * get the file Path according to the Parameter value
 * @param extSchemaPath
 * @param paramValue
 * @param extSchemaPathText
 * @return the file Path according to the Parameter value
 */
public String getParamFilePath(String extSchemaPath, String paramValue){
	String remainingString = "";
     if( !checkParameterValue(extSchemaPath) && StringUtils.contains(paramValue, PARAMETER_NOT_FOUND)){
    	remainingString = extSchemaPath.substring(extSchemaPath.indexOf("}")+1, extSchemaPath.length());
   		}
	return paramValue+remainingString;
}