List of usage examples for com.google.common.collect ImmutableSet iterator
Iterator<E> iterator();
From source file:com.facebook.buck.cli.BuildCommand.java
@Override @SuppressWarnings("PMD.PrematureDeclaration") int runCommandWithOptionsInternal(BuildCommandOptions options) throws IOException { // Set the logger level based on the verbosity option. Verbosity verbosity = console.getVerbosity(); Logging.setLoggingLevelForVerbosity(verbosity); // Create artifact cache to initialize Cassandra connection, if appropriate. ArtifactCache artifactCache = getArtifactCache(); try {/*ww w.j av a 2 s.c o m*/ buildTargets = getBuildTargets(options.getArgumentsFormattedAsBuildTargets()); } catch (NoSuchBuildTargetException e) { console.printBuildFailureWithoutStacktrace(e); return 1; } if (buildTargets.isEmpty()) { console.printBuildFailure("Must specify at least one build target."); // If there are aliases defined in .buckconfig, suggest that the user // build one of them. We show the user only the first 10 aliases. ImmutableSet<String> aliases = options.getBuckConfig().getAliases(); if (!aliases.isEmpty()) { console.getStdErr().println(String.format("Try building one of the following targets:\n%s", Joiner.on(' ').join(Iterators.limit(aliases.iterator(), 10)))); } return 1; } // Post the build started event, setting it to the Parser recorded start time if appropriate. if (getParser().getParseStartTime().isPresent()) { getBuckEventBus().post(BuildEvent.started(buildTargets), getParser().getParseStartTime().get()); } else { getBuckEventBus().post(BuildEvent.started(buildTargets)); } // Parse the build files to create a DependencyGraph. DependencyGraph dependencyGraph; try { dependencyGraph = getParser().parseBuildFilesForTargets(buildTargets, options.getDefaultIncludes(), getBuckEventBus()); } catch (BuildTargetException | BuildFileParseException e) { console.printBuildFailureWithoutStacktrace(e); return 1; } // Create and execute the build. build = options.createBuild(options.getBuckConfig(), dependencyGraph, getProjectFilesystem(), getAndroidDirectoryResolver(), getBuildEngine(), artifactCache, console, getBuckEventBus(), Optional.<TargetDevice>absent(), getCommandRunnerParams().getPlatform()); int exitCode = 0; try { exitCode = executeBuildAndPrintAnyFailuresToConsole(build, console); } finally { build.close(); // Can't use try-with-resources as build is returned by getBuild. } getBuckEventBus().post(BuildEvent.finished(buildTargets, exitCode)); return exitCode; }
From source file:webreduce.indexing.luceneSearcher.java
public List<Dataset> search() throws IOException { List<Dataset> resultList; resultList = new ArrayList<>(); BooleanQuery.Builder finalQueryBuilder = new BooleanQuery.Builder(); BooleanQuery.Builder entityQueryBuilder = new BooleanQuery.Builder(); BooleanQuery.Builder attributeQueryBuilder = new BooleanQuery.Builder(); //gives me queries QueryParser qpa = new QueryParser(ATTRIBUTES_FIELD, new CustomAnalyzer()); QueryParser qpe = new QueryParser(ENTITIES_FIELD, new CustomAnalyzer()); //QueryWrapperFilter queryFilter = new QueryWrapperFilter(query); //CachingWrapperFilter cachingFilter = new CachingWrapperFilter(queryFilter); //CachingWrapperQuery typeFilterR = new CachingWrapperFilter(new TermsFilter(new Term(TABLE_TYPE_FIELD, "RELATION"))); IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(indexDir))); IndexSearcher searcher = new IndexSearcher(reader); QueryBuilder queryBuilder = new QueryBuilder(new CustomAnalyzer()); System.out.println("Attributes: \n" + Arrays.deepToString(attributes)); System.out.println("Entities: \n" + Arrays.deepToString(entities)); //add attributes one by one for (String a : attributes) { Query qa;/*from ww w. j av a2 s. co m*/ try { qa = qpa.parse("\"" + a + "\""); attributeQueryBuilder.add(qa, BooleanClause.Occur.SHOULD); } catch (ParseException ex) { } } //end of for loop //remove null HashSet<String> entitySet; entitySet = new HashSet<>(Arrays.asList(entities)); entitySet.remove(null); entities = entitySet.toArray(new String[entitySet.size()]); System.out.println("Entities after null removal \n" + Arrays.deepToString(entities)); Multiset<Integer> docNoCount; docNoCount = HashMultiset.create(); //Take only top 50 entities; String[] entities50 = new String[50]; System.arraycopy(entities, 0, entities50, 0, 50); System.out.println(Arrays.deepToString(entities50)); for (String e : entities50) { System.out.println(e); if (e == null) { continue; } Query qe; try { qe = qpe.parse(QueryParserBase.escape(e)); //Query qeph = qpe.parse("\"" + QueryParserBase.escape(e) + "\""); finalQueryBuilder.add(qe, BooleanClause.Occur.MUST); //add entities boolean query finalQueryBuilder.add(attributeQueryBuilder.build(), BooleanClause.Occur.MUST); //add attributes query TopDocs td = searcher.search(finalQueryBuilder.build(), numberOfResults * 10); for (ScoreDoc sd : td.scoreDocs) { int docNo = sd.doc; docNoCount.add(docNo); } } catch (ParseException ex) { } System.out.println("Top Doc id: \n" + Multisets.copyHighestCountFirst(docNoCount).entrySet().iterator().next().getElement()); } //Sort the returned docs by their frequency and store it in docNoSorted ImmutableMultiset<Integer> docNoSorted = Multisets.copyHighestCountFirst(docNoCount); //Get the entry set of the frequency ordered document set ImmutableSet<Multiset.Entry<Integer>> entrySet = Multisets.copyHighestCountFirst(docNoCount).entrySet(); //Get the iterator for the sorted entry set UnmodifiableIterator<Multiset.Entry<Integer>> iterator = entrySet.iterator(); int bestDocId = iterator.next().getElement(); System.out.println("first count" + iterator.next()); // Set<Integer> elementSet = docNoSorted.elementSet(); Integer next = elementSet.iterator().next(); System.out.println("Most frequent document id: " + next); int resultSetSize; resultSetSize = docNoSorted.elementSet().size(); System.out.println("Entry Set Size: " + resultSetSize + " Cardinality: " + docNoSorted.size()); Set<Integer> elementSet1 = Multisets.copyHighestCountFirst(docNoSorted).elementSet(); List<Integer> t = new ArrayList<Integer>(elementSet1); List<Integer> subList = t.subList(0, numberOfResults); //ArrayList subArrayList = new ArrayList(subList); Iterator<Integer> subListIterator = subList.iterator(); //we have all the web table doc IDs //We snould take while (subListIterator.hasNext()) { int docID = subListIterator.next(); Document doc; doc = searcher.doc(docID); String jsonString = doc.get("full_result"); Dataset er = Dataset.fromJson(jsonString); resultList.add(er); } return resultList; }
From source file:dagger.internal.codegen.BindingFactory.java
/** * Returns a {@link dagger.model.BindingKind#SUBCOMPONENT_BUILDER} binding declared using {@link * Module#subcomponents()}./* www . j a va 2s. c om*/ */ ProvisionBinding subcomponentCreatorBinding(ImmutableSet<SubcomponentDeclaration> subcomponentDeclarations) { SubcomponentDeclaration subcomponentDeclaration = subcomponentDeclarations.iterator().next(); return ProvisionBinding.builder().contributionType(ContributionType.UNIQUE) .key(subcomponentDeclaration.key()).kind(SUBCOMPONENT_BUILDER).build(); }
From source file:org.dcache.webdav.macaroons.MacaroonRequestHandler.java
private MacaroonContext buildContext(String target, Request request) throws ErrorResponseException { MacaroonContext context = new MacaroonContext(); FsPath userRoot = FsPath.ROOT;//from w ww . j a va 2 s. c om for (LoginAttribute attr : AuthenticationHandler.getLoginAttributes(request)) { if (attr instanceof HomeDirectory) { context.setHome(FsPath.ROOT.resolve(((HomeDirectory) attr).getHome())); } else if (attr instanceof RootDirectory) { userRoot = FsPath.ROOT.resolve(((RootDirectory) attr).getRoot()); } else if (attr instanceof Expiry) { context.updateExpiry(((Expiry) attr).getExpiry()); } else if (attr instanceof DenyActivityRestriction) { context.removeActivities(((DenyActivityRestriction) attr).getDenied()); } else if (attr instanceof PrefixRestriction) { ImmutableSet<FsPath> paths = ((PrefixRestriction) attr).getPrefixes(); if (target.equals("/")) { checkArgument(paths.size() == 1, "Cannot serialise with multiple path restrictions"); context.setPath(paths.iterator().next()); } else { FsPath desiredPath = _pathMapper.asDcachePath(request, target); if (!paths.stream().anyMatch(desiredPath::hasPrefix)) { throw new ErrorResponseException(SC_BAD_REQUEST, "Bad request path: Desired path not within existing path"); } context.setPath(desiredPath); } } else if (attr instanceof Restriction) { throw new ErrorResponseException(SC_BAD_REQUEST, "Cannot serialise restriction " + attr.getClass().getSimpleName()); } else if (attr instanceof MaxUploadSize) { try { context.updateMaxUpload(((MaxUploadSize) attr).getMaximumSize()); } catch (InvalidCaveatException e) { throw new ErrorResponseException(SC_BAD_REQUEST, "Cannot add max-upload: " + e.getMessage()); } } } Subject subject = getSubject(); context.setUid(Subjects.getUid(subject)); context.setGids(Subjects.getGids(subject)); context.setUsername(Subjects.getUserName(subject)); context.setRoot(_pathMapper.effectiveRoot(userRoot, m -> new ErrorResponseException(SC_BAD_REQUEST, m))); if (!target.equals("/") && !context.getPath().isPresent()) { context.setPath(_pathMapper.asDcachePath(request, target)); } return context; }
From source file:eu.eidas.auth.commons.attribute.ImmutableValueMap.java
/** * Returns the first typed value for the given {@link AttributeDefinition} or returns {@code null} if no attribute * in this map matches the given {@link AttributeDefinition}. * * @param attributeDefinition the attribute definition to look up. * @return The first typed value (if any) corresponding to the given {@link AttributeDefinition}. *//* w w w . j a v a 2 s . co m*/ @Nullable public <T> T getFirstValue(@Nonnull AttributeDefinition<T> attributeDefinition) { ImmutableSet<T> values = getValues(attributeDefinition); if (CollectionUtils.isEmpty(values)) { return null; } return values.iterator().next(); }
From source file:com.intelligentsia.dowsers.entity.view.processor.Source.java
/** * Build a new instance of Source./*from www. j ava 2s. c o m*/ * * @param expectedType * expected type of {@link Entity} * @param alias * alias to prefix all attribute name * @param attributeNames * set of attribute name, null parameter meaning is "include all * attributes". */ public Source(final Class<? extends Entity> entityType, final String alias, final ImmutableSet<String> attributeNames) throws NullPointerException { super(); this.entityType = Preconditions.checkNotNull(entityType); this.attributeNames = attributeNames; final StringBuilder builder = new StringBuilder("(source "); if ((alias == null) || "".equals(alias)) { this.alias = ""; builder.append(entityType.getName()); } else { this.alias = alias + "."; builder.append("(").append(entityType.getName()).append(" ").append(alias).append(")"); } if (attributeNames != null) { builder.append(" "); final Iterator<String> iterator = attributeNames.iterator(); while (iterator.hasNext()) { builder.append(iterator.next()).append(" "); } } value = builder.append(")").toString(); }
From source file:com.facebook.buck.ide.intellij.aggregation.AggregationTree.java
private void aggregateModules(AggregationTreeNode parentNode) { if (parentNode.getChildren().isEmpty()) { return;//from w ww.j av a 2 s . co m } AggregationModule nodeModule = parentNode.getModule(); if (nodeModule != null && !nodeModule.getModuleType().canBeAggregated()) { return; } Path moduleBasePath = parentNode.getModuleBasePath(); LOG.info("Aggregating module at %s: %s", moduleBasePath, nodeModule); String aggregationTag; IjModuleType rootModuleType; if (nodeModule == null) { aggregationTag = findBestAggregationTag(parentNode); rootModuleType = null; } else { aggregationTag = nodeModule.getAggregationTag(); rootModuleType = nodeModule.getModuleType(); } ImmutableSet<Path> modulePathsToAggregate; if (aggregationTag == null) { modulePathsToAggregate = parentNode.getChildrenPathsByModuleType(IjModuleType.UNKNOWN_MODULE); if (modulePathsToAggregate.isEmpty()) { return; } rootModuleType = IjModuleType.UNKNOWN_MODULE; } else { modulePathsToAggregate = parentNode.getChildrenPathsByModuleTypeOrTag(IjModuleType.UNKNOWN_MODULE, aggregationTag); if (rootModuleType == null) { rootModuleType = parentNode.getChild(modulePathsToAggregate.iterator().next()).getModule() .getModuleType(); } } ImmutableSet<Path> excludes = findExcludes(parentNode, modulePathsToAggregate); List<AggregationModule> modulesToAggregate = modulePathsToAggregate.stream().map(parentNode::getChild) .map(AggregationTreeNode::getModule).collect(Collectors.toList()); modulePathsToAggregate.forEach(parentNode::removeChild); if (nodeModule == null) { parentNode.setModule(ModuleAggregator.aggregate(moduleBasePath, rootModuleType, aggregationTag == null ? modulesToAggregate.iterator().next().getAggregationTag() : aggregationTag, modulesToAggregate, excludes)); } else { parentNode.setModule(ModuleAggregator.aggregate(nodeModule, modulesToAggregate, excludes)); } LOG.info("Module after aggregation: %s", parentNode.getModule()); }
From source file:com.facebook.buck.features.project.intellij.aggregation.AggregationTree.java
private void aggregateModules(AggregationTreeNode parentNode) { if (parentNode.getChildren().isEmpty()) { return;//from w ww. j a v a2 s . c o m } AggregationModule nodeModule = parentNode.getModule(); if (nodeModule != null && !nodeModule.getModuleType().canBeAggregated(projectConfig)) { return; } Path moduleBasePath = parentNode.getModuleBasePath(); LOG.verbose("Aggregating module at %s: %s", moduleBasePath, nodeModule); String aggregationTag; IjModuleType rootModuleType; if (nodeModule == null) { aggregationTag = findBestAggregationTag(parentNode); rootModuleType = null; } else { aggregationTag = nodeModule.getAggregationTag(); rootModuleType = nodeModule.getModuleType(); } ImmutableSet<Path> modulePathsToAggregate; if (aggregationTag == null) { modulePathsToAggregate = parentNode.getChildrenPathsByModuleType(IjModuleType.UNKNOWN_MODULE); if (modulePathsToAggregate.isEmpty()) { return; } rootModuleType = IjModuleType.UNKNOWN_MODULE; } else { modulePathsToAggregate = parentNode.getChildrenPathsByModuleTypeOrTag(IjModuleType.UNKNOWN_MODULE, aggregationTag); if (rootModuleType == null) { rootModuleType = parentNode.getChild(modulePathsToAggregate.iterator().next()).getModule() .getModuleType(); } } Map<Path, AggregationModule> modulesToAggregate = collectModulesToAggregate(rootModuleType, parentNode, modulePathsToAggregate); modulesToAggregate.keySet().forEach(parentNode::removeChild); if (nodeModule == null) { parentNode.setModule(ModuleAggregator.aggregate(moduleBasePath, rootModuleType, aggregationTag == null ? modulesToAggregate.values().iterator().next().getAggregationTag() : aggregationTag, modulesToAggregate.values())); } else { parentNode.setModule(ModuleAggregator.aggregate(nodeModule, modulesToAggregate.values())); } LOG.verbose("Module after aggregation: %s", parentNode.getModule()); }
From source file:eu.eidas.auth.commons.attribute.ImmutableAttributeMap.java
/** * Returns the first {@link AttributeValue} for the given {@link AttributeDefinition} or returns {@code null} if no * attribute in this map matches the given {@link AttributeDefinition}. * * @param attributeDefinition the attribute definition to look up. * @return The first {@link AttributeValue} (if any) corresponding to the given {@link AttributeDefinition}. *//*from w w w .j a v a2 s.c o m*/ @Nullable public <T> AttributeValue<T> getFirstAttributeValue(@Nonnull AttributeDefinition<T> attributeDefinition) { ImmutableSet<? extends AttributeValue<T>> values = getAttributeValues(attributeDefinition); if (CollectionUtils.isEmpty(values)) { return null; } return values.iterator().next(); }
From source file:com.facebook.buck.android.APKModuleGraph.java
/** * Loop through each of the targets we visited while generating seed modules: * If the are exclusive to that module, add them to that module. If they are not exclusive to * that module, find or create an appropriate shared module and fill out its dependencies * * @param apkModuleGraph the current graph we're building * @param targetToContainingApkModulesMap the targets mapped to the seed targets they are * reachable from *///from ww w. ja v a 2 s .c o m private void generateSharedModules(MutableDirectedGraph<APKModule> apkModuleGraph, HashMultimap<BuildTarget, String> targetToContainingApkModulesMap) { // Sort the targets into APKModuleBuilders based on their seed dependencies final Map<ImmutableSet<String>, APKModule.Builder> combinedModuleHashToModuleMap = new HashMap<>(); for (Map.Entry<BuildTarget, Collection<String>> entry : targetToContainingApkModulesMap.asMap() .entrySet()) { ImmutableSet<String> containingModuleSet = ImmutableSet.copyOf(entry.getValue()); boolean exists = false; for (Map.Entry<ImmutableSet<String>, APKModule.Builder> existingEntry : combinedModuleHashToModuleMap .entrySet()) { if (existingEntry.getKey().equals(containingModuleSet)) { existingEntry.getValue().addBuildTargets(entry.getKey()); exists = true; break; } } if (!exists) { String name = containingModuleSet.size() == 1 ? containingModuleSet.iterator().next() : generateNameFromTarget(entry.getKey()); combinedModuleHashToModuleMap.put(containingModuleSet, APKModule.builder().setName(name).addBuildTargets(entry.getKey())); } } // Find the seed modules and add them to the graph Map<String, APKModule> seedModules = new HashMap<>(); for (Map.Entry<ImmutableSet<String>, APKModule.Builder> entry : combinedModuleHashToModuleMap.entrySet()) { if (entry.getKey().size() == 1) { APKModule seed = entry.getValue().build(); apkModuleGraph.addNode(seed); seedModules.put(entry.getKey().iterator().next(), seed); apkModuleGraph.addEdge(seed, rootAPKModuleSupplier.get()); } } // Find the shared modules and add them to the graph for (Map.Entry<ImmutableSet<String>, APKModule.Builder> entry : combinedModuleHashToModuleMap.entrySet()) { if (entry.getKey().size() > 1) { APKModule shared = entry.getValue().build(); apkModuleGraph.addNode(shared); apkModuleGraph.addEdge(shared, rootAPKModuleSupplier.get()); for (String seedName : entry.getKey()) { apkModuleGraph.addEdge(seedModules.get(seedName), shared); } } } }