List of usage examples for com.google.common.collect Iterables size
public static int size(Iterable<?> iterable)
From source file:com.metamx.collections.spatial.search.GutmanSearchStrategy.java
public Iterable<ImmutableNode> breadthFirstSearch(Iterable<ImmutableNode> nodes, final Bound bound, int total) { Iterable<ImmutableNode> points = Iterables .concat(Iterables.transform(Iterables.filter(nodes, new Predicate<ImmutableNode>() { @Override/*from w w w .j a v a2 s .co m*/ public boolean apply(ImmutableNode immutableNode) { return immutableNode.isLeaf(); } }), new Function<ImmutableNode, Iterable<ImmutableNode>>() { @Override public Iterable<ImmutableNode> apply(ImmutableNode immutableNode) { return Iterables.filter(immutableNode.getChildren(), new Predicate<ImmutableNode>() { @Override public boolean apply(ImmutableNode immutableNode) { return bound.contains(immutableNode.getMinCoordinates()); } }); } })); Iterable<ImmutableNode> overlappingNodes = Iterables.filter(nodes, new Predicate<ImmutableNode>() { @Override public boolean apply(ImmutableNode immutableNode) { return !immutableNode.isLeaf() && bound.overlaps(immutableNode); } }); int totalPoints = Iterables.size(points); int totalOverlap = Iterables.size(overlappingNodes); if (totalOverlap == 0 || (totalPoints + totalOverlap + total) >= bound.getLimit()) { return Iterables.concat(points, overlappingNodes); } else { return Iterables.concat(points, breadthFirstSearch(Iterables.concat( Iterables.transform(overlappingNodes, new Function<ImmutableNode, Iterable<ImmutableNode>>() { @Override public Iterable<ImmutableNode> apply(ImmutableNode immutableNode) { return immutableNode.getChildren(); } })), bound, totalPoints)); } }
From source file:br.com.davimonteiro.lotus_runtime.probabilisticReach.ProbabilisticReachAlgorithm.java
public int getStatesSize(Iterable<LotusState> states) { // TODO Refactor this Iterables.size(states); List<LotusState> statesL = new ArrayList(); for (LotusState aux : states) { statesL.add(aux);/*from ww w.j a va2 s . c om*/ } int size = statesL.size(); return size; }
From source file:com.metamx.druid.indexer.IndexGeneratorJob.java
public boolean run() { try {/*from w w w . j a v a 2 s.com*/ Job job = new Job(new Configuration(), String.format("%s-index-generator-%s", config.getDataSource(), config.getIntervals())); job.getConfiguration().set("io.sort.record.percent", "0.23"); for (String propName : System.getProperties().stringPropertyNames()) { Configuration conf = job.getConfiguration(); if (propName.startsWith("hadoop.")) { conf.set(propName.substring("hadoop.".length()), System.getProperty(propName)); } } job.setInputFormatClass(TextInputFormat.class); job.setMapperClass(IndexGeneratorMapper.class); job.setMapOutputValueClass(Text.class); SortableBytes.useSortableBytesAsMapOutputKey(job); job.setNumReduceTasks(Iterables.size(config.getAllBuckets())); job.setPartitionerClass(IndexGeneratorPartitioner.class); job.setReducerClass(IndexGeneratorReducer.class); job.setOutputKeyClass(BytesWritable.class); job.setOutputValueClass(Text.class); job.setOutputFormatClass(IndexGeneratorOutputFormat.class); FileOutputFormat.setOutputPath(job, config.makeIntermediatePath()); config.addInputPaths(job); config.intoConfiguration(job); job.setJarByClass(IndexGeneratorJob.class); job.submit(); log.info("Job %s submitted, status available at %s", job.getJobName(), job.getTrackingURL()); boolean success = job.waitForCompletion(true); Counter invalidRowCount = job.getCounters() .findCounter(HadoopDruidIndexerConfig.IndexJobCounters.INVALID_ROW_COUNTER); jobStats.setInvalidRowCount(invalidRowCount.getValue()); return success; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.jnario.compiler.JnarioBatchCompiler.java
@Override protected void generateJavaFiles(ResourceSet resourceSet) { JavaIoFileSystemAccess javaIoFileSystemAccess = javaIoFileSystemAccessProvider.get(); javaIoFileSystemAccess.setOutputPath(outputPath); javaIoFileSystemAccess.setWriteTrace(writeTraceFiles); for (Resource resource : jnarioResources(resourceSet)) { JnarioFile file = filter(resource.getContents(), JnarioFile.class).iterator().next(); for (JnarioTypeDeclaration xtendClass : file.getXtendTypes()) { String packageName = toPath(getPackageName(xtendClass)); for (JvmGenericType type : filter(resource.getContents(), JvmGenericType.class)) { CharSequence generatedType = generator.generateType(type, generatorConfigprovider.get(xtendClass)); String fileName = packageName + type.getSimpleName() + ".java"; javaIoFileSystemAccess.generateFile(fileName, generatedType); }//from w w w . j av a 2s .c o m } } List<EObject> objectsWithClasses = getObjectsWithClasses(jnarioResources(resourceSet)); if (log.isInfoEnabled()) { int size = Iterables.size(objectsWithClasses); if (size == 0) { log.info("No sources to compile in '" + sourcePath + "'"); } else { log.info("Compiling " + size + " source " + (size == 1 ? "file" : "files") + " to " + outputPath); } } for (EObject eObject : objectsWithClasses) { Iterable<JvmDeclaredType> jvmGenericTypes = Iterables .filter(jvmModelAssociations.getJvmElements(eObject), JvmDeclaredType.class); for (JvmDeclaredType jvmType : jvmGenericTypes) { CharSequence generatedType = generator.generateType(jvmType, generatorConfigprovider.get(eObject)); String javaFileName = getJavaFileName(eObject); if (log.isDebugEnabled()) { log.debug("write '" + outputPath + File.separator + javaFileName + "'"); } javaIoFileSystemAccess.generateFile(javaFileName, generatedType); } } }
From source file:com.garyclayburg.persistence.repository.AccountMatcher.java
public User matchAccount(UserAccount scimAccount) { QUser qUser = new QUser("user"); User matchedUser = null;/*w w w . j a va2 s . c o m*/ //default policy matches accounts based on username String instanceName = scimAccount.getInstanceName(); Iterable<User> userList; if (scimAccount.getInstanceName() == null) { // find users that already have a useraccount with specific instancename userList = autoUserRepo.findAll(qUser.userAccounts.any().username.eq(scimAccount.getUsername()) .and(qUser.userAccounts.any().accountType.eq(scimAccount.getAccountType())) .and(qUser.userAccounts.any().instanceName.isNull())); } else { // find users that alredy have a useraccount without a specific instancename userList = autoUserRepo.findAll(qUser.userAccounts.any().username.eq(scimAccount.getUsername()) .and(qUser.userAccounts.any().accountType.eq(scimAccount.getAccountType())) .and(qUser.userAccounts.any().instanceName.eq(instanceName))); } int matchListSize = Iterables.size(userList); if (matchListSize == 1) { matchedUser = Iterables.getFirst(userList, null); // this scimAccount was matched previously to the stored user } else if (matchListSize > 1) { log.error("ERR-102 more than one possible account match for username: " + scimAccount.getUsername()); } else { // execute groovy identity policy on everyone to find match //todo use closure here to pass in groovy policy for creating username as part of user query? List<User> allUsers = autoUserRepo.findAll(); //todo find a more efficient method for this? int matches = 0; for (User oneUser : allUsers) { Map<String, String> generatedAttributes = attributeService.getGeneratedAttributes(oneUser); //convention: attributes named username are used for matching during a recon/sync String username = generatedAttributes.get("username"); log.debug("checking username: {} {} {}", username, oneUser.getFirstname(), oneUser.getLastname()); if (username != null && username.equals(scimAccount.getUsername())) { matches++; if (matchedUser == null) { matchedUser = oneUser; //go with first match } } } log.info("found {} users matching username attribute policy for user {} ", matches, scimAccount.getUsername()); } return matchedUser; }
From source file:org.caleydo.view.domino.internal.tourguide.DataTourGuideDataMode.java
@Override public void addDefaultColumns(RankTableModel table) { addDataDomainRankColumn(table);/*from w w w . j ava2 s. co m*/ final StringRankColumnModel base = new StringRankColumnModel(GLRenderers.drawText("Data Set"), StringRankColumnModel.DEFAULT); table.add(base); base.setWidth(150); base.orderByMe(); table.add( CategoricalRankColumnModel.createSimple(GLRenderers.drawText("Type"), new Function<IRow, String>() { @Override public String apply(IRow input) { return input instanceof DataDomainScoreRow ? "Matrix" : "Numerical"; } }, Arrays.asList("Numerical", "Matrix"))); ImmutableSortedSet.Builder<String> s = ImmutableSortedSet.naturalOrder(); for (IDCategory cat : EntityTypeSelector.findAllUsedIDCategories()) s.add(cat.getCategoryName()); table.add(MultiCategoricalRankColumnModel .createSimple(GLRenderers.drawText("Item Type"), new Function<IRow, Set<String>>() { @Override public Set<String> apply(IRow input) { if (input instanceof DataDomainScoreRow) { IDCategory a = ((DataDomainScoreRow) input).getIdType().getIDCategory(); IDCategory b = ((DataDomainScoreRow) input).getDimensionIdType().getIDCategory(); return ImmutableSet.of(a.getCategoryName(), b.getCategoryName()); } return ImmutableSet.of(((AScoreRow) input).getIdType().getIDCategory().getCategoryName()); } }, s.build(), "").setWidth(150)); table.add(new SizeRankColumnModel("#Records", new Function<IRow, Integer>() { @Override public Integer apply(IRow in) { return ((AScoreRow) in).size(); } }).setWidth(75)); table.add(new SizeRankColumnModel("#Dimensions", new Function<IRow, Integer>() { @Override public Integer apply(IRow in) { return Iterables.size(((AScoreRow) in).getDimensionIDs()); } }).setWidth(75)); }
From source file:org.trimou.engine.segment.SectionSegment.java
@SuppressWarnings("rawtypes") private void processIterable(Appendable appendable, ExecutionContext context, Object value) { Iterable<?> iterable = (Iterable<?>) value; int size = Iterables.size(iterable); if (size < 1) { return;//ww w. ja v a 2 s .c o m } Iterator iterator = iterable.iterator(); int i = 1; while (iterator.hasNext()) { processIteration(appendable, context.setContextObject(new ImmutableIterationMeta(iterationMetaAlias, size, i++)), iterator.next()); } }
From source file:grkvlt.Ec2CleanUp.java
/** * Delete all matching {@link KeyPair}s. *//*from w w w . ja v a 2s .co m*/ public void deleteKeyPairs(KeyPairClient keyPairApi) throws Exception { Set<KeyPair> keys = keyPairApi.describeKeyPairsInRegion(region); Iterable<String> filtered = Iterables.filter(Iterables.transform(keys, new Function<KeyPair, String>() { @Override public String apply(@Nullable KeyPair input) { return input.getKeyName(); } }), Predicates.containsPattern("^" + regexp + "$")); LOG.info("Found {} matching KeyPairs", Iterables.size(filtered)); if (!check) { int deleted = 0; for (String name : filtered) { try { keyPairApi.deleteKeyPairInRegion(region, name); deleted++; } catch (Exception e) { if (e.getMessage() != null && e.getMessage().contains("RequestLimitExceeded")) { Thread.sleep(1000l); // Avoid triggering rate-limiter again } LOG.warn("Error deleting KeyPair '{}': {}", name, e.getMessage()); } } LOG.info("Deleted {} KeyPairs", deleted); } }
From source file:com.vilt.minium.impl.BaseWebElementsImpl.java
public Object invoke(Method method, Object... args) { if (method.isVarArgs()) { args = expandVarArgs(args);// ww w. j ava2s . co m } String expression = computeExpression(this, isAsyncMethod(method), method.getName(), args); if (method.getReturnType() != Object.class && method.getReturnType().isAssignableFrom(this.getClass())) { T webElements = WebElementsFactoryHelper.createExpressionWebElements(factory, myself, expression); return webElements; } else { Object result = null; boolean async = isAsyncMethod(method); Iterable<WebElementsDriver<T>> webDrivers = candidateWebDrivers(); if (method.getReturnType() == Void.TYPE) { for (WebElementsDriver<T> wd : webDrivers) { factory.getInvoker().invokeExpression(wd, async, expression); } } else { if (Iterables.size(webDrivers) == 0) { throw new WebElementsException("The expression has no frame or window to be evaluated to"); } else if (Iterables.size(webDrivers) == 1) { WebElementsDriver<T> wd = Iterables.get(webDrivers, 0); result = factory.getInvoker().invokeExpression(wd, async, expression); } else { String sizeExpression = computeExpression(this, false, "size"); WebElementsDriver<T> webDriverWithResults = null; for (WebElementsDriver<T> wd : webDrivers) { long size = (Long) factory.getInvoker().invokeExpression(wd, async, sizeExpression); if (size > 0) { if (webDriverWithResults == null) { webDriverWithResults = wd; } else { throw new WebElementsException( "Several frames or windows match the same expression, so value cannot be computed"); } } } if (webDriverWithResults != null) { result = factory.getInvoker().invokeExpression(webDriverWithResults, async, expression); } } } if (logger.isDebugEnabled()) { String val; if (method.getReturnType() == Void.TYPE) { val = "void"; } else { val = StringUtils.abbreviate(argToStringFunction.apply(result), 40); if (val.startsWith("'") && !val.endsWith("'")) val += "(...)'"; } logger.debug("[Value: {}] {}", argToStringFunction.apply(result), expression); } // let's handle numbers when return type is int if (method.getReturnType() == Integer.TYPE) { return result == null ? 0 : ((Number) result).intValue(); } else { return result; } } }
From source file:org.eclipse.reqcycle.ocl.utils.OCLUtilities.java
/** * Checks whether an OCL resource contains an operation allowing to retrieve a requirement's attribute * of a given data type. The operation should be named "isX" where "X" is the name * of the data type./*from w w w . j a v a 2 s . co m*/ */ public static IStatus isOperationPresent(final IAttribute attribute, BaseResource resource) { String attributeTypeName = attribute.getName(); if (ecoreToOCLPrimitiveTypes.get(attributeTypeName) == null) { return new Status(IStatus.WARNING, ReqcycleOCLPlugin.PLUGIN_ID, "Type " + attributeTypeName + " cannot be used in OCL."); } if (Iterables.size(getMatchingOperations(attribute, resource)) > 0) { return Status.OK_STATUS; } ; return new Status(IStatus.ERROR, ReqcycleOCLPlugin.PLUGIN_ID, "Required operation : " + OCLUtilities.getOperationRequiredSignature(attribute) + " could not be found."); }