List of usage examples for org.apache.commons.lang StringUtils contains
public static boolean contains(String str, String searchStr)
Checks if String contains a search String, handling null
.
From source file:eionet.meta.imp.VocabularyImportBaseHandler.java
/** * This method searches for a related concept in database or in cache. * * @param relatedConceptUri/*from w ww . j a v a 2 s . c o m*/ * uri of related concept * @return found concept or null */ protected VocabularyConcept findRelatedConcept(String relatedConceptUri) { VocabularyConcept foundRelatedConcept = null; String relatedConceptIdentifier; if (StringUtils.startsWith(relatedConceptUri, this.folderContextRoot)) { // it is a self reference to a concept in this vocabulary. // if it is in found concept then we are lucky. but it may be not created yet... and also wont be created at all... relatedConceptIdentifier = relatedConceptUri.replace(this.folderContextRoot, ""); if (StringUtils.contains(relatedConceptIdentifier, "/") || !Util.isValidIdentifier(relatedConceptIdentifier)) { return null; } int index = getPositionIn(this.concepts, relatedConceptIdentifier); if (index < this.concepts.size()) { return this.concepts.get(index); } index = getPositionIn(this.toBeUpdatedConcepts, relatedConceptIdentifier); if (index < this.toBeUpdatedConcepts.size()) { return this.toBeUpdatedConcepts.get(index); } // concept not seen yet. index = getPositionIn(this.notSeenConceptsYet, relatedConceptIdentifier); if (index < this.notSeenConceptsYet.size()) { return this.notSeenConceptsYet.get(index); } // so create it foundRelatedConcept = new VocabularyConcept(); foundRelatedConcept.setId(--this.numberOfCreatedConcepts); foundRelatedConcept.setIdentifier(relatedConceptIdentifier); foundRelatedConcept.setStatus(StandardGenericStatus.VALID); foundRelatedConcept.setStatusModified(new Date(System.currentTimeMillis())); foundRelatedConcept.setAcceptedDate(new Date(System.currentTimeMillis())); List<List<DataElement>> newConceptElementAttributes = new ArrayList<List<DataElement>>(); foundRelatedConcept.setElementAttributes(newConceptElementAttributes); this.notSeenConceptsYet.add(foundRelatedConcept); return foundRelatedConcept; } try { // extract related concept base uri and related concept identifier int lastDelimiterIndex = Math.max(relatedConceptUri.lastIndexOf("/"), Math.max(relatedConceptUri.lastIndexOf("#"), relatedConceptUri.lastIndexOf(":"))) + 1; String relatedConceptBaseUri = relatedConceptUri.substring(0, lastDelimiterIndex); relatedConceptIdentifier = relatedConceptUri.substring(lastDelimiterIndex); if (StringUtils.isNotEmpty(relatedConceptBaseUri) && StringUtils.isNotEmpty(relatedConceptIdentifier)) { // check cache first foundRelatedConcept = this.relatedConceptCache.get(relatedConceptUri); // && !this.notFoundRelatedConceptCache.contains(relatedConceptUri) if (foundRelatedConcept == null) { // not found in cache search in database // search for vocabularies with base uri. VocabularyFolder foundVocabularyFolder = null; VocabularyFilter vocabularyFilter = new VocabularyFilter(); vocabularyFilter.setWorkingCopy(false); vocabularyFilter.setUsePaging(false); vocabularyFilter.setBaseUri(relatedConceptBaseUri); // first search for vocabularies, to find correct concept and to make searching faster for concepts VocabularyResult vocabularyResult = this.vocabularyService.searchVocabularies(vocabularyFilter); if (vocabularyResult != null && vocabularyResult.getTotalItems() > 0) { // get the first found item, since base uri kinda unique foundVocabularyFolder = vocabularyResult.getList().get(0); // folder found, so go on for concept search VocabularyConceptFilter filter = new VocabularyConceptFilter(); filter.setUsePaging(false); filter.setIdentifier(relatedConceptIdentifier); filter.setVocabularyFolderId(foundVocabularyFolder.getId()); // search for concepts now VocabularyConceptResult results = this.vocabularyService.searchVocabularyConcepts(filter); // if found more than one, how can system detect which one is searched for! if (results != null && results.getFullListSize() == 1) { foundRelatedConcept = results.getList().get(0); this.relatedConceptCache.put(relatedConceptUri, foundRelatedConcept); } } } } } catch (ServiceException e) { e.printStackTrace(); } return foundRelatedConcept; }
From source file:info.magnolia.jaas.sp.jcr.JCRAuthorizationModule.java
/** * set access control list from a list of roles under the provided content object * @param role under which roles and ACL are defined *///from www . j a va2 s .co m private void setACL(Content role, PrincipalCollection principalList) { try { Iterator it = role.getChildren(ItemType.CONTENTNODE.getSystemName(), "acl*").iterator(); while (it.hasNext()) { Content aclEntry = (Content) it.next(); String name = StringUtils.substringAfter(aclEntry.getName(), "acl_"); ACL acl; String repositoryName; String workspaceName; if (!StringUtils.contains(name, "_")) { workspaceName = ContentRepository.getDefaultWorkspace(StringUtils.substringBefore(name, "_")); repositoryName = name; name += ("_" + workspaceName); // default workspace // must be added to the // name } else { String[] tokens = StringUtils.split(name, "_"); repositoryName = tokens[0]; workspaceName = tokens[1]; } // get the existing acl object if created before with some // other role if (!principalList.contains(name)) { acl = new ACLImpl(); principalList.add(acl); } else { acl = (ACL) principalList.get(name); } acl.setName(name); acl.setRepository(repositoryName); acl.setWorkspace(workspaceName); // add acl Iterator permissionIterator = aclEntry.getChildren().iterator(); while (permissionIterator.hasNext()) { Content map = (Content) permissionIterator.next(); String path = map.getNodeData("path").getString(); UrlPattern p = new SimpleUrlPattern(path); Permission permission = new PermissionImpl(); permission.setPattern(p); permission.setPermissions(map.getNodeData("permissions").getLong()); acl.addPermission(permission); } } } catch (Exception e) { log.error(e.getMessage(), e); } }
From source file:eu.europeana.corelib.search.utils.SearchUtils.java
private static boolean containsNoneSearchOperators(String queryTerm) { return !StringUtils.contains(queryTerm, " AND ") && !StringUtils.contains(queryTerm, " NOT ") && !StringUtils.contains(queryTerm, " OR ") && !StringUtils.contains(queryTerm, "*"); }
From source file:com.cws.esolutions.security.processors.impl.AccountControlProcessorImpl.java
/** * @see com.cws.esolutions.security.processors.interfaces.IAccountControlProcessor#createNewUser(com.cws.esolutions.security.processors.dto.AccountControlRequest) */// w w w . j av a2 s. c om public AccountControlResponse createNewUser(final AccountControlRequest request) throws AccountControlException { final String methodName = IAccountControlProcessor.CNAME + "#createNewUser(final CreateUserRequest createReq) throws AccountControlException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("AccountControlRequest: {}", request); } AccountControlResponse response = new AccountControlResponse(); final RequestHostInfo reqInfo = request.getHostInfo(); final UserAccount reqAccount = request.getRequestor(); final UserAccount userAccount = request.getUserAccount(); final AuthenticationData userSecurity = request.getUserSecurity(); final String newUserSalt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength()); if (DEBUG) { DEBUGGER.debug("Requestor: {}", reqAccount); DEBUGGER.debug("RequestHostInfo: {}", reqInfo); DEBUGGER.debug("UserAccount: {}", userAccount); DEBUGGER.debug("AuthenticationData: {}", userSecurity); } try { // this will require admin and service authorization AccessControlServiceRequest accessRequest = new AccessControlServiceRequest(); accessRequest.setUserAccount(userAccount); accessRequest.setServiceGuid(request.getServiceId()); if (DEBUG) { DEBUGGER.debug("AccessControlServiceRequest: {}", accessRequest); } AccessControlServiceResponse accessResponse = accessControl.isUserAuthorized(accessRequest); if (DEBUG) { DEBUGGER.debug("AccessControlServiceResponse accessResponse: {}", accessResponse); } if (!(accessResponse.getIsUserAuthorized())) { // unauthorized response.setRequestStatus(SecurityRequestStatus.UNAUTHORIZED); // audit try { AuditEntry auditEntry = new AuditEntry(); auditEntry.setHostInfo(reqInfo); auditEntry.setAuditType(AuditType.CREATEUSER); auditEntry.setUserAccount(userAccount); auditEntry.setAuthorized(Boolean.FALSE); auditEntry.setApplicationId(request.getApplicationId()); auditEntry.setApplicationName(request.getApplicationName()); if (DEBUG) { DEBUGGER.debug("AuditEntry: {}", auditEntry); } AuditRequest auditRequest = new AuditRequest(); auditRequest.setAuditEntry(auditEntry); if (DEBUG) { DEBUGGER.debug("AuditRequest: {}", auditRequest); } auditor.auditRequest(auditRequest); } catch (AuditServiceException asx) { ERROR_RECORDER.error(asx.getMessage(), asx); } return response; } String userGuid = UUID.randomUUID().toString(); if (DEBUG) { DEBUGGER.debug("Value: {}", userGuid); } int x = 0; while (true) { if (x == 10) { throw new AccountControlException("Failed to generate a unique user GUID"); } try { userManager.validateUserAccount(userAccount.getUsername(), userGuid); break; } catch (UserManagementException umx) { ERROR_RECORDER.error(umx.getMessage(), umx); if (!(StringUtils.contains(umx.getMessage(), "UUID"))) { response.setRequestStatus(SecurityRequestStatus.FAILURE); return response; } userGuid = UUID.randomUUID().toString(); if (DEBUG) { DEBUGGER.debug("Value: {}", userGuid); } x++; continue; } } // insert the user salt boolean isSaltInserted = userSec.addOrUpdateSalt(userGuid, newUserSalt, SaltType.LOGON.name()); if (DEBUG) { DEBUGGER.debug("isSaltInserted: {}", isSaltInserted); } if (isSaltInserted) { String newPassword = PasswordUtils.encryptText( RandomStringUtils.randomAlphanumeric(secConfig.getPasswordMaxLength()), newUserSalt, secConfig.getAuthAlgorithm(), secConfig.getIterations(), secBean.getConfigData().getSystemConfig().getEncoding()); List<String> accountData = new ArrayList<String>(Arrays.asList(userGuid, userAccount.getUsername(), newPassword, String.valueOf(userAccount.isSuspended()), userAccount.getSurname(), userAccount.getGivenName(), userAccount.getGivenName() + " " + userAccount.getSurname(), userAccount.getEmailAddr())); if (DEBUG) { DEBUGGER.debug("accountData: {}", accountData); } boolean isUserCreated = userManager.addUserAccount(accountData, new ArrayList<String>(Arrays.asList(Arrays.toString(userAccount.getGroups())))); if (DEBUG) { DEBUGGER.debug("isUserCreated: {}", isUserCreated); } if (isUserCreated) { response.setRequestStatus(SecurityRequestStatus.SUCCESS); } else { // failed to add the user to the repository ERROR_RECORDER.error("Failed to add user to the userAccount repository"); response.setRequestStatus(SecurityRequestStatus.FAILURE); } } else { // failed to insert salt ERROR_RECORDER.error("Failed to provision new user: failed to insert the generated salt value"); response.setRequestStatus(SecurityRequestStatus.FAILURE); } } catch (AccountControlException acx) { ERROR_RECORDER.error(acx.getMessage(), acx); throw new AccountControlException(acx.getMessage(), acx); } catch (AccessControlServiceException acx) { ERROR_RECORDER.error(acx.getMessage(), acx); throw new AccountControlException(acx.getMessage(), acx); } catch (UserManagementException umx) { ERROR_RECORDER.error(umx.getMessage(), umx); throw new AccountControlException(umx.getMessage(), umx); } catch (SQLException sqx) { ERROR_RECORDER.error(sqx.getMessage(), sqx); throw new AccountControlException(sqx.getMessage(), sqx); } catch (SecurityException sx) { ERROR_RECORDER.error(sx.getMessage(), sx); throw new AccountControlException(sx.getMessage(), sx); } finally { // audit try { AuditEntry auditEntry = new AuditEntry(); auditEntry.setHostInfo(reqInfo); auditEntry.setAuditType(AuditType.CREATEUSER); auditEntry.setUserAccount(reqAccount); auditEntry.setAuthorized(Boolean.TRUE); auditEntry.setApplicationId(request.getApplicationId()); auditEntry.setApplicationName(request.getApplicationName()); if (DEBUG) { DEBUGGER.debug("AuditEntry: {}", auditEntry); } AuditRequest auditRequest = new AuditRequest(); auditRequest.setAuditEntry(auditEntry); if (DEBUG) { DEBUGGER.debug("AuditRequest: {}", auditRequest); } auditor.auditRequest(auditRequest); } catch (AuditServiceException asx) { ERROR_RECORDER.error(asx.getMessage(), asx); } } return response; }
From source file:com.hangum.tadpole.engine.sql.util.SQLUtil.java
/** * ? Table, column name? ./* w ww. ja v a 2 s . com*/ * * @param userDB * @param name * @return */ public static String makeIdentifierName(UserDBDAO userDB, String name) { boolean isChanged = false; String retStr = name; TadpoleMetaData tmd = TadpoleSQLManager.getDbMetadata(userDB); if (tmd == null) return retStr; // mssql? ? " " []? ? ?. --;; if (userDB.getDBDefine() == DBDefine.MSSQL_8_LE_DEFAULT || userDB.getDBDefine() == DBDefine.MSSQL_DEFAULT) { if (StringUtils.contains(name, "\"")) { return name = String.format("[%s]", name); } } switch (tmd.getSTORE_TYPE()) { // case NONE: // retStr = tableName; // break; case BLANK: if (name.matches(".*\\s.*")) { isChanged = true; retStr = makeFullyTableName(name, tmd.getIdentifierQuoteString()); } break; case LOWCASE_BLANK: if (name.matches(".*[a-z\\s].*")) { isChanged = true; retStr = makeFullyTableName(name, tmd.getIdentifierQuoteString()); } break; case UPPERCASE_BLANK: if (name.matches(".*[A-Z\\s].*")) { isChanged = true; retStr = makeFullyTableName(name, tmd.getIdentifierQuoteString()); } break; } // Is keywords? // schema.tableName if (!isChanged) { String[] arryRetStr = StringUtils.split(retStr, "."); if (arryRetStr.length == 1) { if (StringUtils.containsIgnoreCase("," + tmd.getKeywords() + ",", "," + arryRetStr[0] + ",")) { retStr = tmd.getIdentifierQuoteString() + retStr + tmd.getIdentifierQuoteString(); } } else if (arryRetStr.length > 1) { if (StringUtils.containsIgnoreCase("," + tmd.getKeywords() + ",", "," + arryRetStr[1] + ",")) { retStr = tmd.getIdentifierQuoteString() + retStr + tmd.getIdentifierQuoteString(); } } } // if(logger.isDebugEnabled()) logger.debug("[tmd.getSTORE_TYPE()]" + tmd.getSTORE_TYPE() + "[original]" + tableName + "[retStr = ]" + retStr); return retStr; }
From source file:net.kamhon.ieagle.dao.JdbcDao.java
public <T> void queryForDatagrid(DatagridModel<T> datagridModel, String sql, RowMapper<T> rowMapper, Object[] params) {/*from w ww .j av a2 s. co m*/ Assert.isTrue(StringUtils.isNotBlank(sql), "The sql can not be BLANK!!"); if (CollectionUtil.isNotEmpty(datagridModel.getFilters())) { Assert.doesNotContain(sql, BasicDao.FILTER_PARAMS, "The " + BasicDao.FILTER_PARAMS + " is not found in Query [" + sql + "] if FILTERS is not EMPTY!!"); } Assert.notNull(getNativeDatabaseObject(), "The pagination Datagrid is not supported for your Database!!"); /************************* * END VALIDATION ************************/ // to re-set the sorter.sqlColumn() datagridModel.processBeforeQuery(); String finalQuery = sql; List<Object> finalParams = params != null ? Arrays.asList(params) : new ArrayList<Object>(); if (CollectionUtil.isNotEmpty(datagridModel.getFilters())) { for (Filter filter : datagridModel.getFilters()) { if (filter != null) throw new DataException("The Filter features still not implemented yet"); } } List<Object> countParams = new ArrayList<Object>(finalParams); String countQuery = "SELECT COUNT(*) FROM (" + finalQuery + ") t "; if (!datagridModel.isDisableSort() && CollectionUtil.isNotEmpty(datagridModel.getSorters())) { if (StringUtils.contains(finalQuery.toUpperCase(), "ORDER BY")) { finalQuery += ", "; } else { finalQuery += " ORDER BY "; } for (Iterator<Sorter> iter = datagridModel.getSorters().iterator(); iter.hasNext();) { Sorter sorter = iter.next(); // here different with HibernateDao finalQuery += sorter.getSqlColumn() + " " + sorter.getDirection(); if (iter.hasNext()) { finalQuery += ", "; } } } finalQuery = getNativeDatabaseObject().convertToPaginationSql(finalQuery, datagridModel.getRecordOffset(), datagridModel.getPageSize()); /*log.debug("countParams = " + countParams); log.debug("countQuery = " + countQuery); log.debug("params = " + finalParams); log.debug("finalQuery = " + finalQuery);*/ long count = 0; if (CollectionUtil.isEmpty(countParams)) { count = queryForLong(countQuery); } else { count = queryForLong(countQuery, countParams.toArray()); } List<T> result = null; if (CollectionUtil.isEmpty(finalParams)) { result = (List<T>) query(finalQuery, rowMapper); } else { result = (List<T>) query(finalQuery, rowMapper, finalParams.toArray()); } datagridModel.setRecords(result); datagridModel.setTotalRecords(count); }
From source file:edu.ku.brc.af.ui.db.TextFieldWithQuery.java
/** * Constructor.//from w ww.j a va 2 s . co m */ public TextFieldWithQuery(final DBTableInfo tableInfo, final String keyColumn, final String displayColumns, final String format, final String fieldFormatterName, final String sqlTemplate) { super(); this.tableInfo = tableInfo; this.fieldInfo = tableInfo.getFieldByName(keyColumn); this.displayColumns = displayColumns != null ? displayColumns : keyColumn; this.format = format; this.fieldFormatterName = fieldFormatterName; this.sqlTemplate = sqlTemplate; if (fieldInfo != null && fieldInfo.getFormatter() != null) { uiFieldFormatter = fieldInfo.getFormatter(); } else if (StringUtils.isNotEmpty(fieldFormatterName)) { uiFieldFormatter = UIFieldFormatterMgr.getInstance().getFormatter(fieldFormatterName); } if (StringUtils.contains(keyColumn, ",")) //$NON-NLS-1$ { keyColumns = StringUtils.split(keyColumn, ","); //$NON-NLS-1$ } else { keyColumns = new String[] { keyColumn }; } popupDlgThreshold = AppPreferences.getRemote().getInt("TFQ.POPUPDLD.THRESHOLD", 15); //$NON-NLS-1$ createUI(); }
From source file:net.kamhon.ieagle.dao.Jpa2Dao.java
@SuppressWarnings("unchecked") public void findForDatagrid(DatagridModel<T> datagridModel, String alias, String queryString, String countQueryString, Object... objectArray) { boolean hasCountQueryString = StringUtils.isNotBlank(countQueryString); String countQuery = ""; queryString = convertJpaPositionParams(queryString); Assert.isTrue(StringUtils.isNotBlank(alias), "The alias can not be BLANK!!"); Assert.isTrue(StringUtils.isNotBlank(queryString), "The queryString can not be BLANK!!"); if (CollectionUtil.isNotEmpty(datagridModel.getFilters())) { Assert.doesNotContain(queryString, BasicDao.FILTER_PARAMS, "The " + BasicDao.FILTER_PARAMS + " is not found in Query [" + queryString + "] if FILTERS is not EMPTY!!"); }/*from www .j a v a 2 s . c o m*/ /************************* * END VALIDATION ************************/ String finalQuery = queryString.trim(); List<Object> params = new ArrayList<Object>(); if (objectArray != null) { if (objectArray.length == 1 && objectArray[0] instanceof List) params = (List<Object>) objectArray[0]; else params = Arrays.asList(objectArray); } if (CollectionUtil.isNotEmpty(datagridModel.getFilters())) { for (Filter filter : datagridModel.getFilters()) { if (filter != null) throw new DataException("The Filter features still not implemented yet"); } } List<Object> countParams = new ArrayList<Object>(params); if (hasCountQueryString) countQuery = countQueryString; else { countQuery = "SELECT COUNT(" + alias + ") "; if (finalQuery.toUpperCase().startsWith("SELECT")) { int ind = finalQuery.toUpperCase().indexOf("FROM"); countQuery += finalQuery.substring(ind); } else { countQuery += finalQuery; } } if (!datagridModel.isDisableSort() && CollectionUtil.isNotEmpty(datagridModel.getSorters())) { if (StringUtils.contains(finalQuery.toUpperCase(), "ORDER BY")) { finalQuery += ", "; } else { finalQuery += " ORDER BY "; } for (Iterator<Sorter> iter = datagridModel.getSorters().iterator(); iter.hasNext();) { Sorter sorter = iter.next(); if (StringUtils.isNotBlank(datagridModel.getExtraMapping(sorter.getColumn()))) finalQuery += datagridModel.getExtraMapping(sorter.getColumn()) + " " + sorter.getDirection(); else finalQuery += alias + "." + sorter.getColumn() + " " + sorter.getDirection(); if (iter.hasNext()) { finalQuery += ", "; } } } // log.debug("countParams = " + countParams); // log.debug("countQuery = " + countQuery); // log.debug("params = " + params); // log.debug("finalQuery = " + finalQuery); List<T> result = (List<T>) findBlock(finalQuery, datagridModel.getRecordOffset(), datagridModel.getPageSize(), params.toArray()); datagridModel.setRecords(result); Long count = (Long) this.findUnique(countQuery, countParams.toArray()); datagridModel.setTotalRecords(count); }
From source file:info.magnolia.cms.filters.AggregatorFilter.java
/** * Check if the path *may be* a valid path before calling getItem, in order to avoid annoying logs. * @param handle node handle/* ww w . j a v a 2 s.c om*/ * @return true if the path is invalid */ private boolean isJcrPathValid(String handle) { if (StringUtils.isBlank(handle) || StringUtils.equals(handle, "/")) { // empty path not allowed return false; } if (StringUtils.containsAny(handle, new char[] { ':', '*', '\n' })) { // not allowed chars return false; } if (StringUtils.contains(handle, " /")) { // trailing slash not allowed return false; } return true; }
From source file:eu.europeana.corelib.search.utils.SearchUtils.java
private static boolean isNotFieldQuery(String queryTerm) { return !StringUtils.contains(queryTerm, ":"); }