List of usage examples for com.google.common.collect ImmutableSet isEmpty
boolean isEmpty();
From source file:com.google.caliper.runner.ExperimentingCaliperRun.java
@Override public void run() throws InvalidBenchmarkException { ImmutableSet<Experiment> allExperiments = selector.selectExperiments(); // TODO(lukes): move this standard-out handling into the ConsoleOutput class? stdout.println("Experiment selection: "); stdout.println(" Benchmark Methods: " + FluentIterable.from(allExperiments).transform(new Function<Experiment, String>() { @Override/* www.j av a 2 s.com*/ public String apply(Experiment experiment) { return experiment.instrumentation().benchmarkMethod().getName(); } }).toSet()); stdout.println(" Instruments: " + FluentIterable.from(selector.instruments()).transform(new Function<Instrument, String>() { @Override public String apply(Instrument instrument) { return instrument.name(); } })); stdout.println(" User parameters: " + selector.userParameters()); stdout.println(" Virtual machines: " + FluentIterable.from(selector.vms()).transform(new Function<VirtualMachine, String>() { @Override public String apply(VirtualMachine vm) { return vm.name; } })); stdout.println(" Selection type: " + selector.selectionType()); stdout.println(); if (allExperiments.isEmpty()) { throw new InvalidBenchmarkException( "There were no experiments to be performed for the class %s using the instruments %s", benchmarkClass.benchmarkClass().getSimpleName(), instruments); } stdout.format("This selection yields %s experiments.%n", allExperiments.size()); stdout.flush(); // always dry run first. ImmutableSet<Experiment> experimentsToRun = dryRun(allExperiments); if (experimentsToRun.size() != allExperiments.size()) { stdout.format("%d experiments were skipped.%n", allExperiments.size() - experimentsToRun.size()); } if (experimentsToRun.isEmpty()) { throw new InvalidBenchmarkException("All experiments were skipped."); } if (options.dryRun()) { return; } stdout.flush(); int totalTrials = experimentsToRun.size() * options.trialsPerScenario(); Stopwatch stopwatch = Stopwatch.createStarted(); List<ScheduledTrial> trials = createScheduledTrials(experimentsToRun, totalTrials); final ListeningExecutorService executor = executorProvider.get(); List<ListenableFuture<TrialResult>> pendingTrials = scheduleTrials(trials, executor); ConsoleOutput output = new ConsoleOutput(stdout, totalTrials, stopwatch); try { // Process results as they complete. for (ListenableFuture<TrialResult> trialFuture : inCompletionOrder(pendingTrials)) { try { TrialResult result = trialFuture.get(); output.processTrial(result); for (ResultProcessor resultProcessor : resultProcessors) { resultProcessor.processTrial(result.getTrial()); } } catch (ExecutionException e) { if (e.getCause() instanceof TrialFailureException) { output.processFailedTrial((TrialFailureException) e.getCause()); } else { for (ListenableFuture<?> toCancel : pendingTrials) { toCancel.cancel(true); } throw Throwables.propagate(e.getCause()); } } catch (InterruptedException e) { // be responsive to interruption, cancel outstanding work and exit for (ListenableFuture<?> toCancel : pendingTrials) { // N.B. TrialRunLoop is responsive to interruption. toCancel.cancel(true); } throw new RuntimeException(e); } } } finally { executor.shutdown(); output.close(); } for (ResultProcessor resultProcessor : resultProcessors) { try { resultProcessor.close(); } catch (IOException e) { logger.log(WARNING, "Could not close a result processor: " + resultProcessor, e); } } }
From source file:com.google.javascript.jscomp.newtypes.JSTypeCreatorFromJSDoc.java
private void handleConstructorAnnotation(String functionName, Node funNode, RawNominalType constructorType, NominalType parentClass, ImmutableSet<NominalType> implementedIntfs, DeclaredTypeRegistry registry, FunctionTypeBuilder builder) {// w ww. j a v a2s. c o m String className = constructorType.toString(); NominalType builtinObject = registry.getCommonTypes().getObjectType(); if (parentClass == null && !functionName.equals("Object")) { parentClass = builtinObject; } if (parentClass != null) { if (!constructorType.addSuperClass(parentClass)) { warnings.add(JSError.make(funNode, INHERITANCE_CYCLE, className)); } else if (parentClass != builtinObject) { if (constructorType.isStruct() && !parentClass.isStruct()) { warnings.add(JSError.make(funNode, CONFLICTING_SHAPE_TYPE, "struct", className)); } else if (constructorType.isDict() && !parentClass.isDict()) { warnings.add(JSError.make(funNode, CONFLICTING_SHAPE_TYPE, "dict", className)); } } } if (constructorType.isDict() && !implementedIntfs.isEmpty()) { warnings.add(JSError.make(funNode, DICT_IMPLEMENTS_INTERF, className)); } boolean noCycles = constructorType.addInterfaces(implementedIntfs); Preconditions.checkState(noCycles); builder.addNominalType(constructorType.getAsNominalType()); }
From source file:org.sosy_lab.cpachecker.core.algorithm.BMCAlgorithm.java
@Override public boolean run(final ReachedSet pReachedSet) throws CPAException, InterruptedException { final ReachedSet reachedSet = pReachedSet; CFANode initialLocation = extractLocation(reachedSet.getFirstState()); invariantGenerator.start(initialLocation); try {/* w w w .j a v a 2s. c o m*/ logger.log(Level.INFO, "Creating formula for program"); boolean soundInner; try (ProverEnvironment prover = solver.newProverEnvironmentWithModelGeneration(); @SuppressWarnings("resource") KInductionProver kInductionProver = induction ? new KInductionProver() : null) { ImmutableSet<BooleanFormula> potentialInvariants = null; Set<CFAEdge> relevantAssumeEdges = null; ImmutableSet<CFANode> targetLocations = null; do { shutdownNotifier.shutdownIfNecessary(); if (induction) { if (targetLocations == null) { targetLocations = kInductionProver.getCurrentPotentialTargetLocations(); } if (targetLocations != null && targetLocations.isEmpty()) { logger.log(Level.INFO, "Invariant generation found no target states."); invariantGenerator.cancel(); for (AbstractState waitlistState : new ArrayList<>(pReachedSet.getWaitlist())) { pReachedSet.removeOnlyFromWaitlist(waitlistState); } return true; } } soundInner = unroll(reachedSet); if (from(reachedSet).skip(1) // first state of reached is always an abstraction state, so skip it .transform(toState(PredicateAbstractState.class)).anyMatch(FILTER_ABSTRACTION_STATES)) { logger.log(Level.WARNING, "BMC algorithm does not work with abstractions. Could not check for satisfiability!"); return soundInner; } // first check safety boolean safe = checkTargetStates(reachedSet, prover); logger.log(Level.FINER, "Program is safe?:", safe); if (!safe) { createErrorPath(reachedSet, prover); } prover.pop(); // remove program formula from solver stack if (!safe) { return soundInner; } else if (addInvariantsByInduction && induction && !kInductionProver.isTrivial()) { if (targetLocations != null) { if (relevantAssumeEdges == null || kInductionProver.haveCurrentPotentialTargetLocationsChanged()) { relevantAssumeEdges = getRelevantAssumeEdges(pReachedSet, targetLocations); } if (potentialInvariants != null) { potentialInvariants = from(potentialInvariants) .filter(not(in(kInductionProver.knownLoopHeadInvariants))).toSet(); } potentialInvariants = guessLoopHeadInvariants(reachedSet, relevantAssumeEdges, prover, kInductionProver.getLoop(), potentialInvariants); potentialInvariants = kInductionProver .setPotentialLoopHeadInvariants(potentialInvariants); } } // second check soundness boolean sound = false; // verify soundness, but don't bother if we are unsound anyway or we have found a bug if (soundInner && safe) { // check bounding assertions sound = checkBoundingAssertions(reachedSet, prover); // try to prove program safety via induction if (induction) { sound = sound || kInductionProver.check(); } if (sound) { return true; } } } while (soundInner && adjustConditions()); } return false; } finally { invariantGenerator.cancel(); if (reachedSet != pReachedSet) { pReachedSet.clear(); ReachedSetUtils.addReachedStatesToOtherReached(reachedSet, pReachedSet); } } }
From source file:com.palantir.atlasdb.transaction.impl.SnapshotTransaction.java
/** * @param commitLocksToken// w ww.ja v a 2 s. c om * @return set of locks that could not be refreshed */ private Set<LockRefreshToken> refreshExternalAndCommitLocks(@Nullable LockRefreshToken commitLocksToken) { ImmutableSet<LockRefreshToken> toRefresh; if (commitLocksToken == null) { toRefresh = externalLocksTokens; } else { toRefresh = ImmutableSet.<LockRefreshToken>builder().addAll(externalLocksTokens).add(commitLocksToken) .build(); } if (toRefresh.isEmpty()) { return ImmutableSet.of(); } return Sets.difference(toRefresh, lockService.refreshLockRefreshTokens(toRefresh)).immutableCopy(); }
From source file:com.qubole.quark.planner.parser.SqlQueryParser.java
public SqlQueryParserResult parse(String sql) throws SQLException { DataSourceSchema dataSource = this.context.getDefaultDataSource(); final AtomicBoolean foundNonQuarkScan = new AtomicBoolean(false); final ImmutableSet.Builder<DataSourceSchema> dsBuilder = new ImmutableSet.Builder<>(); try {/*w w w .j a v a2s . c o m*/ final SqlKind kind = getSqlParser(sql).parseQuery().getKind(); SqlQueryParserResult result = new SqlQueryParserResult(stripNamespace(sql, dataSource), dataSource, kind, null, false); RelNode relNode = parseInternal(sql); final RelVisitor relVisitor = new RelVisitor() { @Override public void visit(RelNode node, int ordinal, RelNode parent) { if (node instanceof QuarkViewScan) { visitQuarkViewScan((QuarkViewScan) node); } else if (node instanceof QuarkTileScan) { visitQuarkTileScan((QuarkTileScan) node); } else if (node instanceof TableScan) { visitNonQuarkScan((TableScan) node); } super.visit(node, ordinal, parent); } private void visitNonQuarkScan(TableScan node) { foundNonQuarkScan.set(true); final String schemaName = node.getTable().getQualifiedName().get(0); CalciteSchema schema = CalciteSchema.from(getRootSchma()).getSubSchema(schemaName, false); dsBuilder.addAll(getDrivers(schema)); } private void visitQuarkTileScan(QuarkTileScan node) { QuarkTile quarkTile = node.getQuarkTile(); CalciteCatalogReader calciteCatalogReader = new CalciteCatalogReader( CalciteSchema.from(getRootSchma()), false, context.getDefaultSchemaPath(), getTypeFactory()); CalciteSchema tileSchema = calciteCatalogReader.getTable(quarkTile.tableName) .unwrap(CalciteSchema.class); dsBuilder.addAll(getDrivers(tileSchema)); } private void visitQuarkViewScan(QuarkViewScan node) { QuarkTable table = node.getQuarkTable(); if (table instanceof QuarkViewTable) { final CalciteSchema tableSchema = ((QuarkViewTable) table).getBackupTableSchema(); dsBuilder.addAll(getDrivers(tableSchema)); } } private ImmutableSet<DataSourceSchema> getDrivers(CalciteSchema tableSchema) { final ImmutableSet.Builder<DataSourceSchema> dsBuilder = new ImmutableSet.Builder<>(); SchemaPlus tableSchemaPlus = tableSchema.plus(); while (tableSchemaPlus != null) { Schema schema = CalciteSchema.from(tableSchemaPlus).schema; if (schema instanceof DataSourceSchema) { dsBuilder.add((DataSourceSchema) schema); } tableSchemaPlus = tableSchemaPlus.getParentSchema(); } return dsBuilder.build(); } }; relVisitor.go(relNode); ImmutableSet<DataSourceSchema> dataSources = dsBuilder.build(); if (!foundNonQuarkScan.get() && dataSources.size() == 1) { /** * Check if query is completely optimized for a data source */ final DataSourceSchema newDataSource = dataSources.asList().get(0); final SqlDialect dialect = newDataSource.getDataSource().getSqlDialect(); final String parsedSql = getParsedSql(relNode, dialect); result = new SqlQueryParserResult(parsedSql, newDataSource, kind, relNode, true); } else if (foundNonQuarkScan.get() && dataSources.size() == 1) { /** * Check if its not optimized */ final DataSourceSchema newDataSource = dataSources.asList().get(0); final String stripNamespace = stripNamespace(sql, newDataSource); result = new SqlQueryParserResult(stripNamespace, newDataSource, kind, relNode, true); } else if (this.context.isUnitTestMode()) { String parsedSql = getParsedSql(relNode, new SqlDialect(SqlDialect.DatabaseProduct.UNKNOWN, "UNKNOWN", null, true)); result = new SqlQueryParserResult(parsedSql, null, kind, relNode, true); } else if (dataSources.size() > 1) { /** * Check if it's partially optimized, i.e., tablescans of multiple datasources * are found in RelNode. We currently donot support multiple datasources. */ throw new SQLException("Federation between data sources is not allowed", "0A001"); } else if (dataSources.isEmpty()) { throw new SQLException("No dataSource found for query", "3D001"); } return result; } catch (SQLException e) { throw e; } catch (Exception e) { throw new SQLException(e); } }
From source file:org.apache.hadoop.hive.druid.DruidStorageHandler.java
public void publishSegments(Table table, boolean overwrite) throws MetaException { if (MetaStoreUtils.isExternalTable(table)) { return;/*from www . ja v a 2 s. c o m*/ } Lifecycle lifecycle = new Lifecycle(); LOG.info("Committing table {} to the druid metastore", table.getDbName()); final Path tableDir = getSegmentDescriptorDir(); try { List<DataSegment> segmentList = DruidStorageHandlerUtils.getPublishedSegments(tableDir, getConf()); LOG.info("Found {} segments under path {}", segmentList.size(), tableDir); final String dataSourceName = table.getParameters().get(Constants.DRUID_DATA_SOURCE); final String segmentDirectory = table.getParameters().get(Constants.DRUID_SEGMENT_DIRECTORY) != null ? table.getParameters().get(Constants.DRUID_SEGMENT_DIRECTORY) : HiveConf.getVar(getConf(), HiveConf.ConfVars.DRUID_SEGMENT_DIRECTORY); DruidStorageHandlerUtils.publishSegments(connector, druidMetadataStorageTablesConfig, dataSourceName, segmentList, overwrite, segmentDirectory, getConf() ); final String coordinatorAddress = HiveConf.getVar(getConf(), HiveConf.ConfVars.HIVE_DRUID_COORDINATOR_DEFAULT_ADDRESS); int maxTries = HiveConf.getIntVar(getConf(), HiveConf.ConfVars.HIVE_DRUID_MAX_TRIES); LOG.info("checking load status from coordinator {}", coordinatorAddress); String coordinatorResponse = null; try { coordinatorResponse = RetryUtils.retry(new Callable<String>() { @Override public String call() throws Exception { return DruidStorageHandlerUtils.getURL(getHttpClient(), new URL(String.format("http://%s/status", coordinatorAddress))); } }, new Predicate<Throwable>() { @Override public boolean apply(@Nullable Throwable input) { return input instanceof IOException; } }, maxTries); } catch (Exception e) { console.printInfo("Will skip waiting for data loading"); return; } if (Strings.isNullOrEmpty(coordinatorResponse)) { console.printInfo("Will skip waiting for data loading"); return; } console.printInfo(String.format("Waiting for the loading of [%s] segments", segmentList.size())); long passiveWaitTimeMs = HiveConf.getLongVar(getConf(), HiveConf.ConfVars.HIVE_DRUID_PASSIVE_WAIT_TIME); ImmutableSet<URL> setOfUrls = FluentIterable.from(segmentList) .transform(new Function<DataSegment, URL>() { @Override public URL apply(DataSegment dataSegment) { try { //Need to make sure that we are using UTC since most of the druid cluster use UTC by default return new URL( String.format("http://%s/druid/coordinator/v1/datasources/%s/segments/%s", coordinatorAddress, dataSourceName, DataSegment.makeDataSegmentIdentifier(dataSegment.getDataSource(), new DateTime(dataSegment.getInterval().getStartMillis(), DateTimeZone.UTC), new DateTime(dataSegment.getInterval().getEndMillis(), DateTimeZone.UTC), dataSegment.getVersion(), dataSegment.getShardSpec()))); } catch (MalformedURLException e) { Throwables.propagate(e); } return null; } }).toSet(); int numRetries = 0; while (numRetries++ < maxTries && !setOfUrls.isEmpty()) { setOfUrls = ImmutableSet.copyOf(Sets.filter(setOfUrls, new Predicate<URL>() { @Override public boolean apply(URL input) { try { String result = DruidStorageHandlerUtils.getURL(getHttpClient(), input); LOG.debug("Checking segment {} response is {}", input, result); return Strings.isNullOrEmpty(result); } catch (IOException e) { LOG.error(String.format("Error while checking URL [%s]", input), e); return true; } } })); try { if (!setOfUrls.isEmpty()) { Thread.sleep(passiveWaitTimeMs); } } catch (InterruptedException e) { Thread.interrupted(); Throwables.propagate(e); } } if (!setOfUrls.isEmpty()) { // We are not Throwing an exception since it might be a transient issue that is blocking loading console.printError( String.format("Wait time exhausted and we have [%s] out of [%s] segments not loaded yet", setOfUrls.size(), segmentList.size())); } } catch (IOException e) { LOG.error("Exception while commit", e); Throwables.propagate(e); } finally { cleanWorkingDir(); lifecycle.stop(); } }
From source file:com.facebook.buck.android.AndroidBinaryRule.java
private ResourceDirectoriesFromAapt addAaptPackageSteps(ImmutableList.Builder<Step> steps, final AndroidTransitiveDependencies transitiveDependencies, final AndroidDexTransitiveDependencies dexTransitiveDependencies) { final Set<String> rDotJavaPackages = transitiveDependencies.rDotJavaPackages; final FilterResourcesStep filterResourcesStep; final ImmutableSet<String> resDirectories; if (requiresResourceFilter()) { filterResourcesStep = createFilterResourcesStep(transitiveDependencies.resDirectories); resDirectories = filterResourcesStep.getOutputResourceDirs(); steps.add(filterResourcesStep);/*from w w w . ja v a2 s. co m*/ } else { filterResourcesStep = null; resDirectories = transitiveDependencies.resDirectories; } // Extract the resources from third-party jars. // TODO(mbolin): The results of this should be cached between runs. String extractedResourcesDir = getBinPath("__resources__%s__"); steps.add(new MakeCleanDirectoryStep(extractedResourcesDir)); steps.add(new ExtractResourcesStep(dexTransitiveDependencies.pathsToThirdPartyJars, extractedResourcesDir)); // Create the R.java files. Their compiled versions must be included in classes.dex. // TODO(mbolin): Skip this step if the transitive set of AndroidResourceRules is cached. if (!resDirectories.isEmpty()) { UberRDotJavaUtil.generateRDotJavaFiles(resDirectories, rDotJavaPackages, getBuildTarget(), steps); if (isStoreStringsAsAssets()) { Path tmpStringsDirPath = getPathForTmpStringAssetsDirectory(); steps.add(new MakeCleanDirectoryStep(tmpStringsDirPath)); steps.add(new CompileStringsStep(filterResourcesStep, Paths.get(UberRDotJavaUtil.getPathToGeneratedRDotJavaSrcFiles(getBuildTarget())), tmpStringsDirPath)); } } // Copy the transitive closure of files in assets to a single directory, if any. Step collectAssets = new Step() { @Override public int execute(ExecutionContext context) { // This must be done in a Command because the files and directories that are specified may // not exist at the time this Command is created because the previous Commands have not run // yet. ImmutableList.Builder<Step> commands = ImmutableList.builder(); try { createAllAssetsDirectory(transitiveDependencies.assetsDirectories, commands, new DefaultDirectoryTraverser()); } catch (IOException e) { context.logError(e, "Error creating all assets directory in %s.", getBuildTarget()); return 1; } for (Step command : commands.build()) { int exitCode = command.execute(context); if (exitCode != 0) { throw new HumanReadableException("Error running " + command.getDescription(context)); } } return 0; } @Override public String getShortName() { return "symlink_assets"; } @Override public String getDescription(ExecutionContext context) { return getShortName(); } }; steps.add(collectAssets); // Copy the transitive closure of files in native_libs to a single directory, if any. ImmutableSet<String> nativeLibraryDirectories; if (!transitiveDependencies.nativeLibsDirectories.isEmpty()) { ImmutableSet.Builder<String> nativeLibraryDirectoriesBuilder = ImmutableSet.builder(); String pathForNativeLibs = getPathForNativeLibs(); String libSubdirectory = pathForNativeLibs + "/lib"; nativeLibraryDirectoriesBuilder.add(libSubdirectory); steps.add(new MakeCleanDirectoryStep(libSubdirectory)); for (String nativeLibDir : transitiveDependencies.nativeLibsDirectories) { copyNativeLibrary(nativeLibDir, libSubdirectory, steps); } nativeLibraryDirectories = nativeLibraryDirectoriesBuilder.build(); } else { nativeLibraryDirectories = ImmutableSet.of(); } Optional<String> assetsDirectory; if (transitiveDependencies.assetsDirectories.isEmpty() && transitiveDependencies.nativeLibAssetsDirectories.isEmpty() && !isStoreStringsAsAssets()) { assetsDirectory = Optional.absent(); } else { assetsDirectory = Optional.of(getPathToAllAssetsDirectory()); } if (!transitiveDependencies.nativeLibAssetsDirectories.isEmpty()) { String nativeLibAssetsDir = assetsDirectory.get() + "/lib"; steps.add(new MakeCleanDirectoryStep(nativeLibAssetsDir)); for (String nativeLibDir : transitiveDependencies.nativeLibAssetsDirectories) { copyNativeLibrary(nativeLibDir, nativeLibAssetsDir, steps); } } if (isStoreStringsAsAssets()) { Path stringAssetsDir = Paths.get(assetsDirectory.get()).resolve("strings"); steps.add(new MakeCleanDirectoryStep(stringAssetsDir)); steps.add( new CopyStep(getPathForTmpStringAssetsDirectory(), stringAssetsDir, /* shouldRecurse */ true)); } steps.add(new MkdirStep(outputGenDirectory)); if (!canSkipAaptResourcePackaging()) { AaptStep aaptCommand = new AaptStep(getAndroidManifestXml(), resDirectories, assetsDirectory, getResourceApkPath(), ImmutableSet.of(extractedResourcesDir), packageType.isCrunchPngFiles()); steps.add(aaptCommand); } ResourceDirectoriesFromAapt resourceDirectoriesFromAapt = new ResourceDirectoriesFromAapt(resDirectories, nativeLibraryDirectories); return resourceDirectoriesFromAapt; }
From source file:dagger2.internal.codegen.ComponentGenerator.java
private void initializeFrameworkTypes(BindingGraph input, ClassWriter componentWriter, ConstructorWriter constructorWriter, Optional<ClassName> builderName, Map<TypeElement, MemberSelect> componentContributionFields, ImmutableMap<BindingKey, MemberSelect> memberSelectSnippets, ImmutableMap<ContributionBinding, Snippet> parentMultibindingContributionSnippets, ImmutableMap<ContributionBinding, Snippet> multibindingContributionSnippets) throws AssertionError { List<List<BindingKey>> partitions = Lists.partition(input.resolvedBindings().keySet().asList(), 100); for (int i = 0; i < partitions.size(); i++) { MethodWriter initializeMethod = componentWriter.addMethod(VoidName.VOID, "initialize" + ((i == 0) ? "" : i)); initializeMethod.body();//from www. j av a 2 s .co m initializeMethod.addModifiers(PRIVATE); if (builderName.isPresent()) { initializeMethod.addParameter(builderName.get(), "builder").addModifiers(FINAL); constructorWriter.body().addSnippet("%s(builder);", initializeMethod.name()); } else { constructorWriter.body().addSnippet("%s();", initializeMethod.name()); } for (BindingKey bindingKey : partitions.get(i)) { Snippet memberSelectSnippet = memberSelectSnippets.get(bindingKey) .getSnippetFor(componentWriter.name()); ResolvedBindings resolvedBindings = input.resolvedBindings().get(bindingKey); switch (bindingKey.kind()) { case CONTRIBUTION: ImmutableSet<? extends ContributionBinding> bindings = resolvedBindings.contributionBindings(); switch (ContributionBinding.bindingTypeFor(bindings)) { case SET: boolean hasOnlyProvisions = Iterables.all(bindings, Predicates.instanceOf(ProvisionBinding.class)); ImmutableList.Builder<Snippet> parameterSnippets = ImmutableList.builder(); for (ContributionBinding binding : bindings) { if (multibindingContributionSnippets.containsKey(binding)) { Snippet initializeSnippet = initializeFactoryForContributionBinding(binding, input, componentWriter.name(), componentContributionFields, memberSelectSnippets); Snippet snippet = multibindingContributionSnippets.get(binding); initializeMethod.body().addSnippet("this.%s = %s;", snippet, initializeSnippet); parameterSnippets.add(snippet); } else if (parentMultibindingContributionSnippets.containsKey(binding)) { parameterSnippets.add(parentMultibindingContributionSnippets.get(binding)); } else { throw new IllegalStateException(binding + " was not found in"); } } Snippet initializeSetSnippet = Snippet.format("%s.create(%s)", hasOnlyProvisions ? ClassName.fromClass(SetFactory.class) : ClassName.fromClass(SetProducer.class), Snippet.makeParametersSnippet(parameterSnippets.build())); initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet, initializeSetSnippet); break; case MAP: if (Sets.filter(bindings, Predicates.instanceOf(ProductionBinding.class)).isEmpty()) { @SuppressWarnings("unchecked") // checked by the instanceof filter above ImmutableSet<ProvisionBinding> provisionBindings = (ImmutableSet<ProvisionBinding>) bindings; for (ProvisionBinding provisionBinding : provisionBindings) { if (!isNonProviderMap(provisionBinding) && multibindingContributionSnippets.containsKey(provisionBinding)) { Snippet snippet = multibindingContributionSnippets.get(provisionBinding); initializeMethod.body().addSnippet("this.%s = %s;", snippet, initializeFactoryForProvisionBinding(provisionBinding, componentWriter.name(), input.componentDescriptor().dependencyMethodIndex(), componentContributionFields, memberSelectSnippets)); } } if (!provisionBindings.isEmpty()) { Snippet initializeMapSnippet = initializeMapBinding(componentWriter.name(), memberSelectSnippets, new ImmutableMap.Builder<ContributionBinding, Snippet>() .putAll(parentMultibindingContributionSnippets) .putAll(multibindingContributionSnippets).build(), provisionBindings); initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet, initializeMapSnippet); } } else { // TODO(user): Implement producer map bindings. throw new IllegalStateException("producer map bindings not implemented yet"); } break; case UNIQUE: if (!resolvedBindings.ownedContributionBindings().isEmpty()) { ContributionBinding binding = Iterables.getOnlyElement(bindings); if (binding instanceof ProvisionBinding) { ProvisionBinding provisionBinding = (ProvisionBinding) binding; if (!provisionBinding.factoryCreationStrategy().equals(ENUM_INSTANCE) || provisionBinding.scope().isPresent()) { initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet, initializeFactoryForProvisionBinding(provisionBinding, componentWriter.name(), input.componentDescriptor().dependencyMethodIndex(), componentContributionFields, memberSelectSnippets)); } } else if (binding instanceof ProductionBinding) { ProductionBinding productionBinding = (ProductionBinding) binding; initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet, initializeFactoryForProductionBinding(productionBinding, input, componentWriter.name(), input.componentDescriptor().dependencyMethodIndex(), componentContributionFields, memberSelectSnippets)); } else { throw new AssertionError(); } } break; default: throw new IllegalStateException(); } break; case MEMBERS_INJECTION: MembersInjectionBinding binding = Iterables .getOnlyElement(resolvedBindings.membersInjectionBindings()); if (!binding.injectionStrategy().equals(MembersInjectionBinding.Strategy.NO_OP)) { initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet, initializeMembersInjectorForBinding(componentWriter.name(), binding, memberSelectSnippets)); } break; default: throw new AssertionError(); } } } }
From source file:com.facebook.buck.apple.project_generator.WorkspaceAndProjectGenerator.java
public WorkspaceAndProjectGenerator(Cell cell, TargetGraph projectGraph, XcodeWorkspaceConfigDescription.Arg workspaceArguments, BuildTarget workspaceBuildTarget, Set<ProjectGenerator.Option> projectGeneratorOptions, boolean combinedProject, boolean buildWithBuck, ImmutableList<String> buildWithBuckFlags, ImmutableSet<UnflavoredBuildTarget> focusModules, boolean parallelizeBuild, ExecutableFinder executableFinder, ImmutableMap<String, String> environment, FlavorDomain<CxxPlatform> cxxPlatforms, CxxPlatform defaultCxxPlatform, String buildFileName, Function<TargetNode<?, ?>, SourcePathResolver> sourcePathResolverForNode, BuckEventBus buckEventBus, HalideBuckConfig halideBuckConfig, CxxBuckConfig cxxBuckConfig, AppleConfig appleConfig, SwiftBuckConfig swiftBuckConfig) { this.rootCell = cell; this.projectGraph = projectGraph; this.dependenciesCache = new AppleDependenciesCache(projectGraph); this.workspaceArguments = workspaceArguments; this.workspaceBuildTarget = workspaceBuildTarget; this.projectGeneratorOptions = ImmutableSet.copyOf(projectGeneratorOptions); this.combinedProject = combinedProject; this.buildWithBuck = buildWithBuck; this.buildWithBuckFlags = buildWithBuckFlags; this.parallelizeBuild = parallelizeBuild; this.executableFinder = executableFinder; this.environment = environment; this.cxxPlatforms = cxxPlatforms; this.defaultCxxPlatform = defaultCxxPlatform; this.buildFileName = buildFileName; this.sourcePathResolverForNode = sourcePathResolverForNode; this.buckEventBus = buckEventBus; this.swiftBuckConfig = swiftBuckConfig; this.combinedProjectGenerator = Optional.empty(); this.halideBuckConfig = halideBuckConfig; this.cxxBuckConfig = cxxBuckConfig; this.appleConfig = appleConfig; ImmutableSet.Builder<UnflavoredBuildTarget> builder = ImmutableSet.builder(); builder.addAll(focusModules);// w ww . ja v a 2s.co m // Add the main target only if focusModules is actually used. if (!focusModules.isEmpty() && workspaceArguments.srcTarget.isPresent()) { builder.add(workspaceArguments.srcTarget.get().getUnflavoredBuildTarget()); } this.focusModules = builder.build(); }
From source file:com.facebook.buck.java.intellij.Project.java
/** * Walks the dependencies of a build rule and adds the appropriate DependentModules to the * specified dependencies collection. All library dependencies will be added before any module * dependencies. See {@code ProjectTest#testThatJarsAreListedBeforeModules()} for details on why * this behavior is important./* www .jav a 2 s. c om*/ */ @SuppressWarnings("PMD.LooseCoupling") private void walkRuleAndAdd(final BuildRule rule, final boolean isForTests, final LinkedHashSet<SerializableDependentModule> dependencies, @Nullable final BuildRule srcTarget) { final Path basePathForRule = rule.getBuildTarget().getBasePath(); new AbstractBreadthFirstTraversal<BuildRule>(rule.getDeps()) { private final LinkedHashSet<SerializableDependentModule> librariesToAdd = Sets.newLinkedHashSet(); private final LinkedHashSet<SerializableDependentModule> modulesToAdd = Sets.newLinkedHashSet(); @Override public ImmutableSet<BuildRule> visit(BuildRule dep) { ImmutableSet<BuildRule> depsToVisit; if (rule.getProperties().is(PACKAGING) || dep instanceof AndroidResource || dep == rule) { depsToVisit = dep.getDeps(); } else if (dep.getProperties().is(LIBRARY) && dep instanceof ExportDependencies) { depsToVisit = ((ExportDependencies) dep).getExportedDeps(); } else { depsToVisit = ImmutableSet.of(); } // Special Case: If we are traversing the test_target and we encounter a library rule in the // same package that is not the src_target, then we should traverse the deps. Consider the // following build file: // // android_library( // name = 'lib', // srcs = glob(['*.java'], excludes = ['*Test.java']), // deps = [ // # LOTS OF DEPS // ], // ) // // java_test( // name = 'test', // srcs = glob(['*Test.java']), // deps = [ // ':lib', // # MOAR DEPS // ], // ) // // project_config( // test_target = ':test', // ) // // Note that the only source folder for this IntelliJ module is the current directory. Thus, // the current directory should be treated as a source folder with test sources, but it // should contain the union of :lib and :test's deps as dependent modules. if (isForTests && depsToVisit.isEmpty() && dep.getBuildTarget().getBasePath().equals(basePathForRule) && !dep.equals(srcTarget)) { depsToVisit = dep.getDeps(); } SerializableDependentModule dependentModule; if (androidAars.contains(dep)) { AndroidPrebuiltAar aar = androidAars.getParentAar(dep); dependentModule = SerializableDependentModule.newLibrary(aar.getBuildTarget(), getIntellijNameForAar(aar)); } else if (dep instanceof PrebuiltJar) { libraryJars.add(dep); String libraryName = getIntellijNameForRule(dep); dependentModule = SerializableDependentModule.newLibrary(dep.getBuildTarget(), libraryName); } else if (dep instanceof AndroidPrebuiltAar) { androidAars.add((AndroidPrebuiltAar) dep); String libraryName = getIntellijNameForAar(dep); dependentModule = SerializableDependentModule.newLibrary(dep.getBuildTarget(), libraryName); } else if ((dep instanceof CxxLibrary) || (dep instanceof NdkLibrary) || (dep instanceof JavaLibrary) || (dep instanceof AndroidResource)) { String moduleName = getIntellijNameForRule(dep); dependentModule = SerializableDependentModule.newModule(dep.getBuildTarget(), moduleName); } else { return depsToVisit; } if (librariesToAdd.contains(dependentModule) || modulesToAdd.contains(dependentModule)) { return depsToVisit; } if (isForTests) { dependentModule.scope = "TEST"; } else { // If the dependentModule has already been added in the "TEST" scope, then it should be // removed and then re-added using the current (compile) scope. String currentScope = dependentModule.scope; dependentModule.scope = "TEST"; if (dependencies.contains(dependentModule)) { dependencies.remove(dependentModule); } dependentModule.scope = currentScope; } // Slate the module for addition to the dependencies collection. Modules are added to // dependencies collection once the traversal is complete in the onComplete() method. if (dependentModule.isLibrary()) { librariesToAdd.add(dependentModule); } else { modulesToAdd.add(dependentModule); } return depsToVisit; } @Override protected void onComplete() { dependencies.addAll(librariesToAdd); dependencies.addAll(modulesToAdd); } }.start(); }