List of usage examples for com.google.common.collect ImmutableMap containsKey
@Override public boolean containsKey(@Nullable Object key)
From source file:com.google.devtools.build.lib.skyframe.PostConfiguredTargetFunction.java
@Nullable @Override/*from ww w. j a v a 2s . com*/ public SkyValue compute(SkyKey skyKey, Environment env) throws SkyFunctionException, InterruptedException { ImmutableMap<ActionAnalysisMetadata, ConflictException> badActions = PrecomputedValue.BAD_ACTIONS.get(env); ConfiguredTargetValue ctValue = (ConfiguredTargetValue) env .getValue(ConfiguredTargetValue.key((ConfiguredTargetKey) skyKey.argument())); if (env.valuesMissing()) { return null; } for (ActionAnalysisMetadata action : ctValue.getActions()) { if (badActions.containsKey(action)) { throw new ActionConflictFunctionException(badActions.get(action)); } } ConfiguredTarget ct = ctValue.getConfiguredTarget(); TargetAndConfiguration ctgValue = new TargetAndConfiguration(ct.getTarget(), ct.getConfiguration()); ImmutableMap<Label, ConfigMatchingProvider> configConditions = getConfigurableAttributeConditions(ctgValue, env); if (configConditions == null) { return null; } OrderedSetMultimap<Attribute, Dependency> deps; try { BuildConfiguration hostConfiguration = buildViewProvider.getSkyframeBuildView() .getHostConfiguration(ct.getConfiguration()); SkyframeDependencyResolver resolver = buildViewProvider.getSkyframeBuildView() .createDependencyResolver(env); // We don't track root causes here - this function is only invoked for successfully analyzed // targets - as long as we redo the exact same steps here as in ConfiguredTargetFunction, this // can never fail. deps = resolver.dependentNodeMap(ctgValue, hostConfiguration, /*aspect=*/ null, configConditions); if (ct.getConfiguration() != null && ct.getConfiguration().useDynamicConfigurations()) { deps = ConfiguredTargetFunction.getDynamicConfigurations(env, ctgValue, deps, hostConfiguration, ruleClassProvider); } } catch (EvalException e) { throw new PostConfiguredTargetFunctionException(e); } catch (ConfiguredTargetFunction.DependencyEvaluationException e) { throw new PostConfiguredTargetFunctionException(e); } catch (InvalidConfigurationException e) { throw new PostConfiguredTargetFunctionException(e); } env.getValues(Iterables.transform(deps.values(), TO_KEYS)); if (env.valuesMissing()) { return null; } return new PostConfiguredTargetValue(ct); }
From source file:com.facebook.buck.core.cell.AbstractCellConfig.java
/** * Translates the 'cell name'->override map into a 'Path'->override map. * * @param pathMapping a map containing paths to all of the cells we want to query. * @return 'Path'->override map/*from w ww .jav a 2 s.com*/ */ public ImmutableMap<Path, RawConfig> getOverridesByPath(ImmutableMap<CellName, Path> pathMapping) throws InvalidCellOverrideException { ImmutableSet<CellName> relativeNamesOfCellsWithOverrides = FluentIterable.from(getValues().keySet()) .filter(Predicates.not(CellName.ALL_CELLS_SPECIAL_NAME::equals)).toSet(); ImmutableSet.Builder<Path> pathsWithOverrides = ImmutableSet.builder(); for (CellName cellWithOverride : relativeNamesOfCellsWithOverrides) { if (!pathMapping.containsKey(cellWithOverride)) { throw new InvalidCellOverrideException( String.format("Trying to override settings for unknown cell %s", cellWithOverride)); } pathsWithOverrides.add(pathMapping.get(cellWithOverride)); } ImmutableMultimap<Path, CellName> pathToRelativeName = Multimaps.index(pathMapping.keySet(), Functions.forMap(pathMapping)); for (Path pathWithOverrides : pathsWithOverrides.build()) { ImmutableList<CellName> namesForPath = RichStream.from(pathToRelativeName.get(pathWithOverrides)) .filter(name -> name.getLegacyName().isPresent()).toImmutableList(); if (namesForPath.size() > 1) { throw new InvalidCellOverrideException( String.format("Configuration override is ambiguous: cell rooted at %s is reachable " + "as [%s]. Please override the config by placing a .buckconfig.local file in the " + "cell's root folder.", pathWithOverrides, Joiner.on(',').join(namesForPath))); } } Map<Path, RawConfig> overridesByPath = new HashMap<>(); for (Map.Entry<CellName, Path> entry : pathMapping.entrySet()) { CellName cellRelativeName = entry.getKey(); Path cellPath = entry.getValue(); RawConfig configFromOtherRelativeName = overridesByPath.get(cellPath); RawConfig config = getForCell(cellRelativeName); if (configFromOtherRelativeName != null) { // Merge configs RawConfig mergedConfig = RawConfig.builder().putAll(configFromOtherRelativeName).putAll(config) .build(); overridesByPath.put(cellPath, mergedConfig); } else { overridesByPath.put(cellPath, config); } } return ImmutableMap.copyOf(overridesByPath); }
From source file:com.google.template.soy.soyparse.PluginResolver.java
public PluginResolver(Mode mode, ImmutableMap<String, SoyPrintDirective> soyPrintDirectives, ImmutableMap<String, SoyFunction> soyFunctions, ImmutableMap<String, SoySourceFunction> sourceFunctions, ErrorReporter reporter) {//from w w w .j a v a 2 s. c o m this.mode = checkNotNull(mode); this.printDirectives = checkNotNull(soyPrintDirectives); this.reporter = checkNotNull(reporter); for (String illegalName : ILLEGAL_PLUGIN_NAMES) { if (soyFunctions.containsKey(illegalName) || sourceFunctions.containsKey(illegalName)) { reporter.report(SourceLocation.UNKNOWN, PLUGIN_NAME_NOT_ALLOWED, illegalName); } } // Merge the SoyFunctions & SoySourceFunctions. While merging, confirm that we only have // one implementation for each plugin. They can overlap, but impl must be the same. This // indicates a partially migrated plugin. // Also confirm that each SoySourceFunction has a @SoyFunctionSignature, which is required. ImmutableMap.Builder<String, Object> mergedFunctions = ImmutableMap.builder(); for (Map.Entry<String, SoyFunction> entry : soyFunctions.entrySet()) { SoySourceFunction source = sourceFunctions.get(entry.getKey()); if (source != null) { if (source != entry.getValue()) { reporter.report(SourceLocation.UNKNOWN, DIFFERENT_IMPLS_REGISTERED, entry.getKey(), entry.getValue(), source); } } else { // We only insert non-duplicates into the merged map to avoid IllegalArugmentExceptions // building the map. mergedFunctions.put(entry.getKey(), entry.getValue()); } } mergedFunctions.putAll(sourceFunctions); this.functions = mergedFunctions.build(); // Go back over our merged functions and validate all the SoySourceFunction implementations. // We explicitly look *after* merging because SoySourceFunctions might be registered // as SoyFunctions if they also implemented other backends like SoyJsFunction. for (Object function : this.functions.values()) { if (function instanceof SoySourceFunction) { if (!function.getClass().isAnnotationPresent(SoyFunctionSignature.class)) { // Make sure a function sig exists. reporter.report(SourceLocation.UNKNOWN, MISSING_FUNCTION_SIGNATURE, function.getClass().getName()); } else if (function instanceof SoyJavaSourceFunction) { // Also make sure that the applyForJavaSource impl uses a single plugin instance. // We don't support multiple instances. Set<Class<?>> instances = PluginInstanceFinder.find((SoyJavaSourceFunction) function); if (instances.size() > 1) { reporter.report(SourceLocation.UNKNOWN, MULTIPLE_PLUGIN_INSTANCES, function.getClass().getName(), instances); } } } } }
From source file:com.google.template.soy.passes.PluginResolver.java
public PluginResolver(Mode mode, ImmutableMap<String, SoyPrintDirective> soyPrintDirectives, ImmutableMap<String, SoyFunction> soyFunctions, ImmutableMap<String, SoySourceFunction> sourceFunctions, ErrorReporter reporter) {//from w w w.j a v a2s. c o m this.mode = checkNotNull(mode); this.printDirectives = checkNotNull(soyPrintDirectives); this.reporter = checkNotNull(reporter); for (String illegalName : BaseUtils.ILLEGAL_PLUGIN_NAMES) { if (soyFunctions.containsKey(illegalName) || sourceFunctions.containsKey(illegalName)) { reporter.report(SourceLocation.UNKNOWN, PLUGIN_NAME_NOT_ALLOWED, illegalName); } } // Merge the SoyFunctions & SoySourceFunctions. While merging, confirm that we only have // one implementation for each plugin. They can overlap, but impl must be the same. This // indicates a partially migrated plugin. // Also confirm that each SoySourceFunction has a @SoyFunctionSignature, which is required. ImmutableMap.Builder<String, Object> mergedFunctions = ImmutableMap.builder(); for (Map.Entry<String, SoyFunction> entry : soyFunctions.entrySet()) { SoySourceFunction source = sourceFunctions.get(entry.getKey()); if (source != null) { if (source != entry.getValue()) { reporter.report(SourceLocation.UNKNOWN, DIFFERENT_IMPLS_REGISTERED, entry.getKey(), entry.getValue(), source); } } else { // We only insert non-duplicates into the merged map to avoid IllegalArugmentExceptions // building the map. mergedFunctions.put(entry.getKey(), entry.getValue()); } } mergedFunctions.putAll(sourceFunctions); this.functions = mergedFunctions.build(); // Go back over our merged functions and validate all the SoySourceFunction implementations. // We explicitly look *after* merging because SoySourceFunctions might be registered // as SoyFunctions if they also implemented other backends like SoyJsFunction. for (Object function : this.functions.values()) { if (function instanceof SoySourceFunction) { if (!function.getClass().isAnnotationPresent(SoyFunctionSignature.class)) { // Make sure a function sig exists. reporter.report(SourceLocation.UNKNOWN, MISSING_FUNCTION_SIGNATURE, function.getClass().getName()); } else if (function instanceof SoyJavaSourceFunction) { // Also make sure that the applyForJavaSource impl uses a single plugin instance. // We don't support multiple instances. Set<Class<?>> instances = PluginInstanceFinder.find((SoyJavaSourceFunction) function); if (instances.size() > 1) { reporter.report(SourceLocation.UNKNOWN, MULTIPLE_PLUGIN_INSTANCES, function.getClass().getName(), instances); } } } } }
From source file:com.facebook.buck.doctor.UserInput.java
public boolean confirm(String question) throws IOException { ImmutableMap<String, Boolean> supportedResponses = ImmutableMap.of("", true, "y", true, "yes", true, "no", false, "n", false); for (;;) {/* w ww. j a v a2 s . c o m*/ output.println(); output.println(question + " (Y/n)?"); output.flush(); String line = reader.readLine(); // Stdin was closed. if (line == null) { return false; } String response = line.trim().toLowerCase(); if (supportedResponses.containsKey(response)) { return supportedResponses.get(response); } else { output.println("Please answer 'y' or 'n'."); } } }
From source file:com.facebook.buck.config.AbstractCellConfig.java
/** * Translates the 'cell name'->override map into a 'Path'->override map. * @param pathMapping a map containing paths to all of the cells we want to query. * @return 'Path'->override map//from w w w .j a v a 2 s . c o m */ public ImmutableMap<Path, RawConfig> getOverridesByPath(ImmutableMap<RelativeCellName, Path> pathMapping) throws MalformedOverridesException { ImmutableSet<RelativeCellName> relativeNamesOfCellsWithOverrides = FluentIterable.from(getValues().keySet()) .filter(Predicates.not(ALL_CELLS_OVERRIDE::equals)).toSet(); ImmutableSet.Builder<Path> pathsWithOverrides = ImmutableSet.builder(); for (RelativeCellName cellWithOverride : relativeNamesOfCellsWithOverrides) { if (!pathMapping.containsKey(cellWithOverride)) { throw new MalformedOverridesException( String.format("Trying to override settings for unknown cell %s", cellWithOverride)); } pathsWithOverrides.add(pathMapping.get(cellWithOverride)); } ImmutableMultimap<Path, RelativeCellName> pathToRelativeName = Multimaps.index(pathMapping.keySet(), Functions.forMap(pathMapping)); for (Path pathWithOverrides : pathsWithOverrides.build()) { ImmutableCollection<RelativeCellName> namesForPath = pathToRelativeName.get(pathWithOverrides); if (namesForPath.size() > 1) { throw new MalformedOverridesException( String.format("Configuration override is ambiguous: cell rooted at %s is reachable " + "as [%s]. Please override the config by placing a .buckconfig.local file in the " + "cell's root folder.", pathWithOverrides, Joiner.on(',').join(namesForPath))); } } Map<Path, RawConfig> overridesByPath = new HashMap<>(); for (Map.Entry<RelativeCellName, Path> entry : pathMapping.entrySet()) { RelativeCellName cellRelativeName = entry.getKey(); Path cellPath = entry.getValue(); RawConfig configFromOtherRelativeName = overridesByPath.get(cellPath); RawConfig config = getForCell(cellRelativeName); if (configFromOtherRelativeName != null) { Preconditions.checkState(configFromOtherRelativeName.equals(config), "Attempting to create cell %s at %s with conflicting overrides [%s] vs [%s].", cellRelativeName, cellPath, configFromOtherRelativeName, config); } else { overridesByPath.put(cellPath, config); } } return ImmutableMap.copyOf(overridesByPath); }
From source file:org.apache.calcite.rel.rules.AggregateProjectPullUpConstantsRule.java
public void onMatch(RelOptRuleCall call) { final Aggregate aggregate = call.rel(0); final RelNode input = call.rel(1); assert !aggregate.indicator : "predicate ensured no grouping sets"; final int groupCount = aggregate.getGroupCount(); if (groupCount == 1) { // No room for optimization since we cannot convert from non-empty // GROUP BY list to the empty one. return;//from w w w . j a v a 2s.c o m } final RexBuilder rexBuilder = aggregate.getCluster().getRexBuilder(); final RelMetadataQuery mq = RelMetadataQuery.instance(); final RelOptPredicateList predicates = mq.getPulledUpPredicates(aggregate.getInput()); if (predicates == null) { return; } final ImmutableMap<RexNode, RexNode> constants = ReduceExpressionsRule.predicateConstants(RexNode.class, rexBuilder, predicates); final NavigableMap<Integer, RexNode> map = new TreeMap<>(); for (int key : aggregate.getGroupSet()) { final RexInputRef ref = rexBuilder.makeInputRef(aggregate.getInput(), key); if (constants.containsKey(ref)) { map.put(key, constants.get(ref)); } } // None of the group expressions are constant. Nothing to do. if (map.isEmpty()) { return; } if (groupCount == map.size()) { // At least a single item in group by is required. // Otherwise "GROUP BY 1, 2" might be altered to "GROUP BY ()". // Removing of the first element is not optimal here, // however it will allow us to use fast path below (just trim // groupCount). map.remove(map.navigableKeySet().first()); } ImmutableBitSet newGroupSet = aggregate.getGroupSet(); for (int key : map.keySet()) { newGroupSet = newGroupSet.clear(key); } final int newGroupCount = newGroupSet.cardinality(); // If the constants are on the trailing edge of the group list, we just // reduce the group count. final RelBuilder relBuilder = call.builder(); relBuilder.push(input); if (map.navigableKeySet().first() == newGroupCount) { // Clone aggregate calls. final List<AggregateCall> newAggCalls = new ArrayList<>(); for (AggregateCall aggCall : aggregate.getAggCallList()) { newAggCalls.add( aggCall.adaptTo(input, aggCall.getArgList(), aggCall.filterArg, groupCount, newGroupCount)); } relBuilder.aggregate(relBuilder.groupKey(newGroupSet, false, null), newAggCalls); } else { // Create the mapping from old field positions to new field // positions. final Permutation mapping = new Permutation(input.getRowType().getFieldCount()); mapping.identity(); // Ensure that the first positions in the mapping are for the new // group columns. for (int i = 0, groupOrdinal = 0, constOrdinal = newGroupCount; i < groupCount; ++i) { if (map.containsKey(i)) { mapping.set(i, constOrdinal++); } else { mapping.set(i, groupOrdinal++); } } // Adjust aggregate calls for new field positions. final List<AggregateCall> newAggCalls = new ArrayList<>(); for (AggregateCall aggCall : aggregate.getAggCallList()) { final int argCount = aggCall.getArgList().size(); final List<Integer> args = new ArrayList<>(argCount); for (int j = 0; j < argCount; j++) { final Integer arg = aggCall.getArgList().get(j); args.add(mapping.getTarget(arg)); } final int filterArg = aggCall.filterArg < 0 ? aggCall.filterArg : mapping.getTarget(aggCall.filterArg); newAggCalls.add(aggCall.adaptTo(relBuilder.peek(), args, filterArg, groupCount, newGroupCount)); } // Aggregate on projection. relBuilder.aggregate(relBuilder.groupKey(newGroupSet, false, null), newAggCalls); } // Create a projection back again. List<Pair<RexNode, String>> projects = new ArrayList<>(); int source = 0; for (RelDataTypeField field : aggregate.getRowType().getFieldList()) { RexNode expr; final int i = field.getIndex(); if (i >= groupCount) { // Aggregate expressions' names and positions are unchanged. expr = relBuilder.field(i - map.size()); } else if (map.containsKey(i)) { // Re-generate the constant expression in the project. expr = map.get(i); } else { // Project the aggregation expression, in its original // position. expr = relBuilder.field(source); ++source; } projects.add(Pair.of(expr, field.getName())); } relBuilder.project(Pair.left(projects), Pair.right(projects)); // inverse call.transformTo(relBuilder.build()); }
From source file:org.apache.cloudstack.outofbandmanagement.OutOfBandManagementServiceImpl.java
@Override @ActionEvent(eventType = EventTypes.EVENT_HOST_OUTOFBAND_MANAGEMENT_CHANGE_PASSWORD, eventDescription = "updating out-of-band management password") public OutOfBandManagementResponse changeOutOfBandManagementPassword(final Host host, final String newPassword) { checkOutOfBandManagementEnabledByZoneClusterHost(host); if (Strings.isNullOrEmpty(newPassword)) { throw new CloudRuntimeException(String.format( "Cannot change out-of-band management password as provided new-password is null or empty for the host %s.", host.getUuid()));/*from ww w . jav a2 s . com*/ } final OutOfBandManagement outOfBandManagementConfig = outOfBandManagementDao.findByHost(host.getId()); final ImmutableMap<OutOfBandManagement.Option, String> options = getOptions(outOfBandManagementConfig); if (!(options.containsKey(OutOfBandManagement.Option.PASSWORD) && !Strings.isNullOrEmpty(options.get(OutOfBandManagement.Option.PASSWORD)))) { throw new CloudRuntimeException(String.format( "Cannot change out-of-band management password as we've no previously configured password for the host %s.", host.getUuid())); } final OutOfBandManagementDriver driver = getDriver(outOfBandManagementConfig); final OutOfBandManagementDriverChangePasswordCommand changePasswordCmd = new OutOfBandManagementDriverChangePasswordCommand( options, ActionTimeout.valueIn(host.getClusterId()), newPassword); final boolean changePasswordResult = Transaction.execute(new TransactionCallback<Boolean>() { @Override public Boolean doInTransaction(TransactionStatus status) { final OutOfBandManagement updatedOutOfBandManagementConfig = outOfBandManagementDao .findByHost(host.getId()); updatedOutOfBandManagementConfig.setPassword(newPassword); boolean result = outOfBandManagementDao.update(updatedOutOfBandManagementConfig.getId(), (OutOfBandManagementVO) updatedOutOfBandManagementConfig); if (!result) { throw new CloudRuntimeException(String.format( "Failed to change out-of-band management password for host (%s) in the database.", host.getUuid())); } final OutOfBandManagementDriverResponse driverResponse; try { driverResponse = driver.execute(changePasswordCmd); } catch (Exception e) { LOG.error( "Out-of-band management change password failed due to driver error: " + e.getMessage()); throw new CloudRuntimeException(String.format( "Failed to change out-of-band management password for host (%s) due to driver error: %s", host.getUuid(), e.getMessage())); } if (!driverResponse.isSuccess()) { throw new CloudRuntimeException(String.format( "Failed to change out-of-band management password for host (%s) with error: %s", host.getUuid(), driverResponse.getError())); } return result && driverResponse.isSuccess(); } }); final OutOfBandManagementResponse response = new OutOfBandManagementResponse(); response.setSuccess(changePasswordResult); response.setId(host.getUuid()); return response; }
From source file:org.geogig.osm.cli.commands.OSMHistoryImport.java
private void ensureTypesExist(GeogigCLI cli) throws IOException { Repository repo = cli.getGeogig().getRepository(); WorkingTree workingTree = repo.workingTree(); ImmutableMap<String, NodeRef> featureTypeTrees = Maps.uniqueIndex(workingTree.getFeatureTypeTrees(), (nr) -> nr.path());//w ww. j av a2s. c om if (!featureTypeTrees.containsKey(WAY_TYPE_NAME)) { workingTree.createTypeTree(WAY_TYPE_NAME, wayType()); } if (!featureTypeTrees.containsKey(NODE_TYPE_NAME)) { workingTree.createTypeTree(NODE_TYPE_NAME, nodeType()); } repo.command(AddOp.class).call(); }
From source file:com.google.auto.value.processor.AutoAnnotationProcessor.java
private void validateParameters(TypeElement annotationElement, ExecutableElement method, ImmutableMap<String, Member> members, ImmutableMap<String, Parameter> parameters, ImmutableMap<String, AnnotationValue> defaultValues) { boolean error = false; for (String memberName : members.keySet()) { if (!parameters.containsKey(memberName) && !defaultValues.containsKey(memberName)) { reportError(method,/*from w w w . java2 s.c om*/ "@AutoAnnotation method needs a parameter with name '%s' and type %s" + " corresponding to %s.%s, which has no default value", memberName, members.get(memberName).getType(), annotationElement, memberName); error = true; } } if (error) { throw new AbortProcessingException(); } }