List of usage examples for org.apache.commons.collections4 CollectionUtils isNotEmpty
public static boolean isNotEmpty(final Collection<?> coll)
From source file:org.craftercms.studio.impl.v1.service.dependency.DependencyServiceImpl.java
@Override public Set<String> getItemsDependingOn(String site, String path, int depth) throws SiteNotFoundException, ContentNotFoundException, ServiceException { // Check if site exists if (!siteService.exists(site)) { throw new SiteNotFoundException(); }/*from w w w . jav a 2 s . c om*/ // Check if content exists if (!contentService.contentExists(site, path)) { throw new ContentNotFoundException(); } logger.debug("Get items depending on content " + path + " for site " + site); Set<String> toRet = new HashSet<String>(); Set<String> paths = new HashSet<String>(); paths.add(path); if (depth < 0) { do { List<String> deps = getItemsDependingOnFromDB(site, paths); toRet.addAll(deps); paths.clear(); paths.addAll(deps); } while (!CollectionUtils.isNotEmpty(paths)); } else { int d = depth; while (d-- > 0) { List<String> deps = getItemsDependingOnFromDB(site, paths); toRet.addAll(deps); paths.clear(); paths.addAll(deps); } } return toRet; }
From source file:org.craftercms.studio.impl.v1.service.dependency.DependencyServiceImpl.java
private Set<String> getContentTypeFilteredDeleteDependencies(String site, Set<String> paths) { Set<String> toRet = new HashSet<String>(); List<String> deps = getItemDependenciesFromDB(site, paths); for (String dep : deps) { ContentItemTO item = contentService.getContentItem(site, dep, 0); List<DeleteDependencyConfigTO> deleteDependencyConfigList = servicesConfig .getDeleteDependencyPatterns(site, item.getContentType()); if (CollectionUtils.isNotEmpty(deleteDependencyConfigList)) { for (DeleteDependencyConfigTO deleteDependencyConfig : deleteDependencyConfigList) { if (dep.matches(deleteDependencyConfig.getPattern())) { toRet.add(dep);/*from w w w. j av a 2 s.c o m*/ break; } } } } return toRet; }
From source file:org.craftercms.studio.impl.v1.service.dependency.RegexDependencyResolver.java
@Override public Map<String, Set<String>> resolve(String site, String path) { Map<String, Set<String>> toRet = new HashMap<String, Set<String>>(); try {/*from www. java2s.c om*/ DependencyResolverConfigTO config = getConfiguraion(site); if (config != null) { String content = contentService.getContentAsString(site, path); if (content != null) { Map<String, DependencyResolverConfigTO.ItemType> itemTypes = config.getItemTypes(); if (itemTypes != null) { for (Map.Entry<String, DependencyResolverConfigTO.ItemType> entry : itemTypes.entrySet()) { DependencyResolverConfigTO.ItemType itemType = entry.getValue(); List<String> includes = itemType.getIncludes(); if (ContentUtils.matchesPatterns(path, includes)) { Map<String, DependencyResolverConfigTO.DependencyType> dependencyTypes = itemType .getDependencyTypes(); for (Map.Entry<String, DependencyResolverConfigTO.DependencyType> dependencyTypeEntry : dependencyTypes .entrySet()) { Set<String> extractedPaths = new HashSet<String>(); DependencyResolverConfigTO.DependencyType dependencyType = dependencyTypeEntry .getValue(); List<DependencyResolverConfigTO.DependencyExtractionPattern> extractionPatterns = dependencyType .getIncludes(); for (DependencyResolverConfigTO.DependencyExtractionPattern extractionPattern : extractionPatterns) { Pattern pattern = Pattern.compile(extractionPattern.getFindRegex()); Matcher matcher = pattern.matcher(content); while (matcher.find()) { String matchedPath = matcher.group(); if (CollectionUtils.isNotEmpty(extractionPattern.getTransforms())) { for (DependencyResolverConfigTO.DependencyExtractionTransform transform : extractionPattern .getTransforms()) { Pattern find = Pattern.compile(transform.getMatch()); Matcher replaceMatcher = find.matcher(matchedPath); matchedPath = replaceMatcher.replaceAll(transform.getReplace()); } } if (contentService.contentExists(site, matchedPath)) { extractedPaths.add(matchedPath); } else { String message = "Found reference to " + matchedPath + " in content at " + path + " but content does not exist in referenced path for site " + site + ".\n" + "Regular expression for extracting dependencies matched " + "string, and after applying transformation rules to get value " + "for dependency path, that dependency path was not found in" + " site repository as a content."; logger.debug(message); } } } toRet.put(dependencyType.getName(), extractedPaths); } } } } } else { logger.error("Failed to extract dependencies. Content not found for site: " + site + ", path: " + path); } } else { String configLocation = getConfigLocation(site); logger.error("Failed to load Dependency Resolver configuration. Verify that configuration exists" + " and it is valid XML file: " + configLocation); } } catch (Exception exc) { logger.error("Unexcpected error resolving dependencies for site: " + site + " path: " + path); } return toRet; }
From source file:org.craftercms.studio.impl.v1.web.security.access.StudioAbstractAccessDecisionVoter.java
protected boolean isSiteMember(User currentUser, String userParam) { try {//from w w w .ja v a 2 s. c om int total1 = siteService.getSitesPerUserTotal(userParam); List<SiteFeed> sitesFeed1 = siteService.getSitesPerUser(userParam, 0, total1); int total2 = siteService.getSitesPerUserTotal(currentUser.getUsername()); List<SiteFeed> sitesFeed2 = siteService.getSitesPerUser(currentUser.getUsername(), 0, total2); Set<String> sites1 = new HashSet<String>(); Set<String> sites2 = new HashSet<String>(); for (SiteFeed site : sitesFeed1) { sites1.add(site.getSiteId()); } for (SiteFeed site : sitesFeed2) { sites2.add(site.getSiteId()); } Collection intersection = CollectionUtils.intersection(sites1, sites2); return CollectionUtils.isNotEmpty(intersection); } catch (UserNotFoundException e) { logger.info("User is not site member", e); return false; } }
From source file:org.craftercms.studio.impl.v1.web.security.access.StudioAbstractAccessDecisionVoter.java
protected boolean isAdmin(User user) { Set<String> userGroups = securityProvider.getUserGroups(user.getUsername()); boolean toRet = false; if (CollectionUtils.isNotEmpty(userGroups)) { for (String group : userGroups) { if (StringUtils.equalsIgnoreCase(group, studioConfiguration.getProperty(SECURITY_GLOBAL_ADMIN_GROUP))) { toRet = true;/* www . jav a2 s . c o m*/ break; } } } return toRet; }
From source file:org.dspace.app.rest.link.search.SearchFacetEntryHalLinkFactory.java
@Override protected void addLinks(SearchFacetEntryResource halResource, Pageable pageable, LinkedList<Link> list) throws Exception { SearchFacetEntryRest facetData = halResource.getFacetData(); DiscoveryResultsRest searchData = halResource.getSearchData(); String query = searchData == null ? null : searchData.getQuery(); String dsoType = searchData == null ? null : searchData.getDsoType(); String scope = searchData == null ? null : searchData.getScope(); UriComponentsBuilder uriBuilder = uriBuilder( getMethodOn().getFacetValues(facetData.getName(), null, query, dsoType, scope, null, null)); addFilterParams(uriBuilder, searchData); //If our rest data contains a list of values, construct the page links. Otherwise, only add a self link if (CollectionUtils.isNotEmpty(facetData.getValues())) { PageImpl page = new PageImpl<>(facetData.getValues(), new PageRequest(0, facetData.getFacetLimit()), facetData.getValues().size() + (BooleanUtils.isTrue(facetData.isHasMore()) ? 1 : 0)); halResource.setPageHeader(new EmbeddedPageHeader(uriBuilder, page, false)); } else {/*from www. j ava 2 s. com*/ list.add(buildLink(Link.REL_SELF, uriBuilder.build().toUriString())); } }
From source file:org.dspace.content.RelationshipServiceImpl.java
@Override public void update(Context context, List<Relationship> relationships) throws SQLException, AuthorizeException { if (CollectionUtils.isNotEmpty(relationships)) { for (Relationship relationship : relationships) { if (authorizeService.authorizeActionBoolean(context, relationship.getLeftItem(), Constants.WRITE) || authorizeService.authorizeActionBoolean(context, relationship.getRightItem(), Constants.WRITE)) { if (isRelationshipValidToCreate(context, relationship)) { relationshipDAO.save(context, relationship); }//from ww w . j a v a 2 s. c o m } else { throw new AuthorizeException("You do not have write rights on this relationship's items"); } } } }
From source file:org.duniter.elasticsearch.service.DocStatService.java
public void computeStats() { // Skip if empty if (CollectionUtils.isEmpty(statDefs)) return;// w w w. j a v a 2s .c om int bulkSize = pluginSettings.getIndexBulkSize(); long now = System.currentTimeMillis() / 1000; BulkRequestBuilder bulkRequest = client.prepareBulk(); DocStat stat = new DocStat(); stat.setTime(now); int counter = 0; for (StatDef statDef : statDefs) { long count = docStatDao.countDoc(statDef.index, statDef.type); // Update stat properties (resue existing obj) stat.setIndex(statDef.index); stat.setIndexType(statDef.type); stat.setCount(count); // Call compute listeners if any if (CollectionUtils.isNotEmpty(statDef.listeners)) { statDef.listeners.forEach(l -> l.onCompute(stat)); } // Add insertion into bulk IndexRequestBuilder request = docStatDao.prepareIndex(stat); bulkRequest.add(request); counter++; // Flush the bulk if not empty if ((counter % bulkSize) == 0) { client.flushBulk(bulkRequest); bulkRequest = client.prepareBulk(); } } // last flush if ((counter % bulkSize) != 0) { client.flushBulk(bulkRequest); } }
From source file:org.efaps.admin.datamodel.attributetype.CompanyLinkType.java
/** * {@inheritDoc}//from www. jav a 2 s .c o m */ @Override public Object readValue(final Attribute _attribute, final List<Object> _objectList) throws EFapsException { Object ret = null; if (CollectionUtils.isNotEmpty(_objectList)) { final Object obj = _objectList.get(0); if (obj != null) { long id = 0; if (obj instanceof Number) { id = ((Number) obj).longValue(); } else if (obj != null) { id = Long.parseLong(obj.toString()); } ret = Company.get(id); } } return ret; }
From source file:org.efaps.admin.index.Indexer.java
/** * Index or reindex a given list of instances. The given instances m,ust be * all of the same type!//w w w. j a v a2s.c om * * @param _context the _context * @param _instances the instances * @throws EFapsException the e faps exception */ public static void index(final IndexContext _context, final List<Instance> _instances) throws EFapsException { if (CollectionUtils.isNotEmpty(_instances)) { final Company currentCompany = Context.getThreadContext().getCompany(); final String currentLanguage = Context.getThreadContext().getLanguage(); Context.getThreadContext().setCompany(Company.get(_context.getCompanyId())); Context.getThreadContext().setLanguage(_context.getLanguage()); final IndexWriterConfig config = new IndexWriterConfig(_context.getAnalyzer()); try (IndexWriter writer = new IndexWriter(_context.getDirectory(), config); TaxonomyWriter taxonomyWriter = new DirectoryTaxonomyWriter(_context.getTaxonomyDirectory());) { final IndexDefinition def = IndexDefinition.get(_instances.get(0).getType().getUUID()); final MultiPrintQuery multi = new MultiPrintQuery(_instances); for (final IndexField field : def.getFields()) { multi.addSelect(field.getSelect()); } Attribute createdAttr = null; if (!_instances.get(0).getType().getAttributes(CreatedType.class).isEmpty()) { createdAttr = _instances.get(0).getType().getAttributes(CreatedType.class).iterator().next(); multi.addAttribute(createdAttr); } multi.addMsgPhrase(def.getMsgPhrase()); multi.executeWithoutAccessCheck(); while (multi.next()) { final String oid = multi.getCurrentInstance().getOid(); final String type = multi.getCurrentInstance().getType().getLabel(); final DateTime created; if (createdAttr == null) { created = new DateTime(); } else { created = multi.getAttribute(createdAttr); } final Document doc = new Document(); doc.add(new FacetField(Dimension.DIMTYPE.name(), type)); doc.add(new FacetField(Dimension.DIMCREATED.name(), String.valueOf(created.getYear()), String.format("%02d", created.getMonthOfYear()))); doc.add(new StringField(Key.OID.name(), oid, Store.YES)); doc.add(new TextField(DBProperties.getProperty("index.Type"), type, Store.YES)); doc.add(new NumericDocValuesField(Key.CREATED.name(), created.getMillis())); doc.add(new StringField(Key.CREATEDSTR.name(), DateTools.dateToString(created.toDate(), DateTools.Resolution.DAY), Store.NO)); final StringBuilder allBldr = new StringBuilder().append(type).append(" "); for (final IndexField field : def.getFields()) { final String name = DBProperties.getProperty(field.getKey()); Object value = multi.getSelect(field.getSelect()); if (value != null) { if (StringUtils.isNoneEmpty(field.getTransform())) { final Class<?> clazz = Class.forName(field.getTransform(), false, EFapsClassLoader.getInstance()); final ITransformer transformer = (ITransformer) clazz.newInstance(); value = transformer.transform(value); } switch (field.getFieldType()) { case LONG: long val = 0; if (value instanceof String) { val = NumberUtils.toLong((String) value); } else if (value instanceof Number) { val = ((Number) value).longValue(); } doc.add(new LongField(name, val, Store.YES)); allBldr.append(value).append(" "); break; case SEARCHLONG: long val2 = 0; if (value instanceof String) { val2 = NumberUtils.toLong((String) value); } else if (value instanceof Number) { val2 = ((Number) value).longValue(); } doc.add(new LongField(name, val2, Store.NO)); allBldr.append(value).append(" "); break; case STRING: doc.add(new StringField(name, String.valueOf(value), Store.YES)); allBldr.append(value).append(" "); break; case SEARCHSTRING: doc.add(new StringField(name, String.valueOf(value), Store.NO)); allBldr.append(value).append(" "); break; case TEXT: doc.add(new TextField(name, String.valueOf(value), Store.YES)); allBldr.append(value).append(" "); break; case SEARCHTEXT: doc.add(new TextField(name, String.valueOf(value), Store.NO)); allBldr.append(value).append(" "); break; case STORED: doc.add(new StoredField(name, String.valueOf(value))); allBldr.append(value).append(" "); break; default: break; } } } doc.add(new StoredField(Key.MSGPHRASE.name(), multi.getMsgPhrase(def.getMsgPhrase()))); doc.add(new TextField(Key.ALL.name(), allBldr.toString(), Store.NO)); writer.updateDocument(new Term(Key.OID.name(), oid), Index.getFacetsConfig().build(taxonomyWriter, doc)); LOG.debug("Add Document: {}", doc); } writer.close(); taxonomyWriter.close(); } catch (final IOException | ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw new EFapsException(Indexer.class, "IOException", e); } finally { Context.getThreadContext().setCompany(currentCompany); Context.getThreadContext().setLanguage(currentLanguage); } } }