List of usage examples for com.google.common.collect ImmutableMap entrySet
public final ImmutableSet<Entry<K, V>> entrySet()
From source file:com.android.tools.idea.npw.assetstudio.ui.ConfigureIconPanel.java
private void initializeListenersAndBindings() { final BoolProperty trimmed = new SelectedProperty(myTrimmedRadioButton); final IntProperty paddingPercent = new SliderValueProperty(myPaddingSlider); final StringProperty paddingValueString = new TextProperty(myPaddingValueLabel); myGeneralBindings.bind(paddingValueString, new FormatExpression("%d %%", paddingPercent)); myIgnoreForegroundColor = new SelectedProperty(myImageRadioButton); myForegroundColor = new OptionalToValuePropertyAdapter<>(new ColorProperty(myForegroundColorPanel)); myBackgroundColor = new OptionalToValuePropertyAdapter<>(new ColorProperty(myBackgroundColorPanel)); myCropped = new SelectedProperty(myCropRadioButton); myDogEared = new SelectedProperty(myDogEarRadioButton); myTheme = new OptionalToValuePropertyAdapter<>(new SelectedItemProperty<>(myThemeComboBox)); myThemeColor = new OptionalToValuePropertyAdapter<>(new ColorProperty(myCustomThemeColorPanel)); myShape = new OptionalToValuePropertyAdapter<>(new SelectedItemProperty<>(myShapeComboBox)); updateBindingsAndUiForActiveIconType(); ActionListener radioSelectedListener = e -> { JRadioButton source = ((JRadioButton) e.getSource()); AssetComponent assetComponent = myAssetPanelMap.get(source); myActiveAsset.set(assetComponent.getAsset()); };/*from w w w . ja v a2s . c om*/ myClipartRadioButton.addActionListener(radioSelectedListener); myImageRadioButton.addActionListener(radioSelectedListener); myTextRadioButton.addActionListener(radioSelectedListener); // If any of our underlying asset panels change, we should pass that on to anyone listening to // us as well. ActionListener assetPanelListener = e -> fireAssetListeners(); for (AssetComponent assetComponent : myAssetPanelMap.values()) { assetComponent.addAssetListener(assetPanelListener); } final Runnable onAssetModified = this::fireAssetListeners; myListeners.listenAll(trimmed, paddingPercent, myForegroundColor, myBackgroundColor, myCropped, myDogEared, myTheme, myThemeColor, myShape).with(onAssetModified); myListeners.listenAndFire(myActiveAsset, sender -> { myActiveAssetBindings.releaseAll(); myActiveAssetBindings.bindTwoWay(trimmed, myActiveAsset.get().trimmed()); myActiveAssetBindings.bindTwoWay(paddingPercent, myActiveAsset.get().paddingPercent()); myActiveAssetBindings.bindTwoWay(myForegroundColor, myActiveAsset.get().color()); getIconGenerator().sourceAsset().setValue(myActiveAsset.get()); onAssetModified.run(); }); ObservableBool isLauncherIcon = new BoolValueProperty(myIconType.equals(AndroidIconType.LAUNCHER)); ObservableBool isActionBarIcon = new BoolValueProperty(myIconType.equals(AndroidIconType.ACTIONBAR)); ObservableBool isCustomTheme = myTheme.isEqualTo(ActionBarIconGenerator.Theme.CUSTOM); ObservableValue<Boolean> isClipartOrText = myActiveAsset.transform( asset -> myClipartAssetButton.getAsset() == asset || myTextAssetEditor.getAsset() == asset); ObservableBool supportsEffects = new BooleanExpression(myShape) { @NotNull @Override public Boolean get() { GraphicGenerator.Shape shape = myShape.get(); switch (shape) { case SQUARE: case VRECT: case HRECT: return true; default: return false; } } }; /** * Hook up a bunch of UI <- boolean expressions, so that when certain conditions are met, * various components show/hide. This also requires refreshing the panel explicitly, as * otherwise Swing doesn't realize it should trigger a relayout. */ ImmutableMap.Builder<BoolProperty, ObservableBool> layoutPropertiesBuilder = ImmutableMap.builder(); layoutPropertiesBuilder.put(new VisibleProperty(myImageAssetRowPanel), new SelectedProperty(myImageRadioButton)); layoutPropertiesBuilder.put(new VisibleProperty(myClipartAssetRowPanel), new SelectedProperty(myClipartRadioButton)); layoutPropertiesBuilder.put(new VisibleProperty(myTextAssetRowPanel), new SelectedProperty(myTextRadioButton)); layoutPropertiesBuilder.put(new VisibleProperty(myForegroundRowPanel), isLauncherIcon.and(isClipartOrText)); layoutPropertiesBuilder.put(new VisibleProperty(myBackgroundRowPanel), isLauncherIcon); layoutPropertiesBuilder.put(new VisibleProperty(myScalingRowPanel), isLauncherIcon); layoutPropertiesBuilder.put(new VisibleProperty(myShapeRowPanel), isLauncherIcon); layoutPropertiesBuilder.put(new VisibleProperty(myEffectRowPanel), isLauncherIcon); layoutPropertiesBuilder.put(new EnabledProperty(myDogEarRadioButton), supportsEffects); layoutPropertiesBuilder.put(new VisibleProperty(myThemeRowPanel), isActionBarIcon); layoutPropertiesBuilder.put(new VisibleProperty(myCustomThemeRowPanel), isActionBarIcon.and(isCustomTheme)); ImmutableMap<BoolProperty, ObservableBool> layoutProperties = layoutPropertiesBuilder.build(); for (Map.Entry<BoolProperty, ObservableBool> e : layoutProperties.entrySet()) { // Initialize everything off, as this makes sure the frame that uses this panel won't start // REALLY LARGE by default. e.getKey().set(false); myGeneralBindings.bind(e.getKey(), e.getValue()); } myListeners.listenAll(layoutProperties.keySet()) .with(() -> SwingUtilities.updateComponentTreeUI(myAllOptionsPanel)); }
From source file:com.facebook.buck.parser.DaemonicCellState.java
void invalidateIfBuckConfigHasChanged(Cell cell, Path buildFile) { try (AutoCloseableLock writeLock = rawAndComputedNodesLock.writeLock()) { // TODO(mzlee): Check whether usedConfigs includes the buildFileName ImmutableMap<String, ImmutableMap<String, Optional<String>>> usedConfigs = buildFileConfigs .get(buildFile);/*from w w w. ja v a2s . c o m*/ if (usedConfigs == null) { // TODO(mzlee): Figure out when/how we can safely update this this.cell = cell; return; } for (Map.Entry<String, ImmutableMap<String, Optional<String>>> keyEnt : usedConfigs.entrySet()) { for (Map.Entry<String, Optional<String>> valueEnt : keyEnt.getValue().entrySet()) { Optional<String> value = cell.getBuckConfig().getValue(keyEnt.getKey(), valueEnt.getKey()); if (!value.equals(valueEnt.getValue())) { invalidatePath(buildFile); this.cell = cell; return; } } } } }
From source file:com.facebook.buck.thrift.ThriftCxxEnhancer.java
private CxxHeadersAndSources getThriftHeaderSourceSpec(BuildRuleParams params, ThriftConstructorArg args, ImmutableMap<String, ThriftSource> sources) { ImmutableMap.Builder<String, SourceWithFlags> cxxSourcesBuilder = ImmutableMap.builder(); ImmutableMap.Builder<String, SourcePath> headersBuilder = ImmutableMap.builder(); for (ImmutableMap.Entry<String, ThriftSource> ent : sources.entrySet()) { final String thriftName = ent.getKey(); final ThriftSource source = ent.getValue(); final Path outputDir = source.getOutputDir(); for (String partialName : getGeneratedSources(params.getBuildTarget(), args, thriftName, source.getServices())) { String name = ThriftCompiler.resolveLanguageDir(getLanguage(), partialName); String extension = Files.getFileExtension(name); if (CxxCompilables.SOURCE_EXTENSIONS.contains(extension)) { cxxSourcesBuilder.put(name, SourceWithFlags.of(new BuildTargetSourcePath(source.getCompileRule().getBuildTarget(), outputDir.resolve(name)))); } else if (CxxCompilables.HEADER_EXTENSIONS.contains(extension)) { headersBuilder.put(name, new BuildTargetSourcePath(source.getCompileRule().getBuildTarget(), outputDir.resolve(name))); } else { throw new HumanReadableException( String.format("%s: unexpected extension for \"%s\"", params.getBuildTarget(), name)); }// www . j a va 2 s . com } } return new CxxHeadersAndSources(headersBuilder.build(), cxxSourcesBuilder.build()); }
From source file:com.opengamma.strata.pricer.fxopt.ImpliedTrinomialTreeFxSingleBarrierOptionProductPricer.java
/** * Calculates the present value sensitivity of the FX barrier option product. * <p>// w w w .ja va 2 s . c o m * The present value sensitivity of the product is the sensitivity of {@link #presentValue} to * the underlying curve parameters. * <p> * The sensitivity is computed by bump and re-price. * * @param option the option product * @param ratesProvider the rates provider * @param volatilities the Black volatility provider * @param baseTreeData the trinomial tree data * @return the present value of the product */ public CurrencyParameterSensitivities presentValueSensitivityRates(ResolvedFxSingleBarrierOption option, RatesProvider ratesProvider, BlackFxOptionVolatilities volatilities, RecombiningTrinomialTreeData baseTreeData) { ArgChecker.isTrue(baseTreeData.getNumberOfSteps() == calibrator.getNumberOfSteps(), "the number of steps mismatch between pricer and trinomial tree data"); double shift = 1.0e-5; CurrencyAmount pvBase = presentValue(option, ratesProvider, volatilities, baseTreeData); ResolvedFxVanillaOption underlyingOption = option.getUnderlyingOption(); ResolvedFxSingle underlyingFx = underlyingOption.getUnderlying(); CurrencyPair currencyPair = underlyingFx.getCurrencyPair(); ImmutableRatesProvider immRatesProvider = ratesProvider.toImmutableRatesProvider(); ImmutableMap<Currency, Curve> baseCurves = immRatesProvider.getDiscountCurves(); CurrencyParameterSensitivities result = CurrencyParameterSensitivities.empty(); for (Entry<Currency, Curve> entry : baseCurves.entrySet()) { if (currencyPair.contains(entry.getKey())) { Curve curve = entry.getValue(); int nParams = curve.getParameterCount(); DoubleArray sensitivity = DoubleArray.of(nParams, i -> { Curve dscBumped = curve.withParameter(i, curve.getParameter(i) + shift); Map<Currency, Curve> mapBumped = new HashMap<>(baseCurves); mapBumped.put(entry.getKey(), dscBumped); ImmutableRatesProvider providerDscBumped = immRatesProvider.toBuilder() .discountCurves(mapBumped).build(); double pvBumped = presentValue(option, providerDscBumped, volatilities).getAmount(); return (pvBumped - pvBase.getAmount()) / shift; }); result = result.combinedWith(curve.createParameterSensitivity(pvBase.getCurrency(), sensitivity)); } } return result; }
From source file:org.dcache.webdav.transfer.CopyFilter.java
public void setOidClientIds(ImmutableMap<String, String> clientIds) { checkArgument(clientIds.entrySet().stream().allMatch(e -> CharMatcher.ASCII.matchesAllOf(e.getValue())), "Client Ids must be ASCII Characters only"); _clientIds = clientIds;/* w w w .j ava 2 s . c o m*/ }
From source file:org.dcache.webdav.transfer.CopyFilter.java
public void setOidClientSecrets(ImmutableMap<String, String> clientSecrets) { checkArgument(clientSecrets.entrySet().stream().allMatch(e -> CharMatcher.ASCII.matchesAllOf(e.getValue())), "Client Secrets must be ASCII Characters only"); _clientSecrets = clientSecrets;//from ww w .j av a 2 s. c o m }
From source file:com.facebook.buck.doctor.DoctorReportHelper.java
public DoctorEndpointResponse uploadRequest(DoctorEndpointRequest request) { if (!doctorConfig.getEndpointUrl().isPresent()) { String errorMsg = String.format( "Doctor endpoint URL is not set. Please set [%s] %s on your .buckconfig", DoctorConfig.DOCTOR_SECTION, DoctorConfig.URL_FIELD); return createErrorDoctorEndpointResponse(errorMsg); }//from www. j a va2s .co m byte[] requestJson; try { requestJson = objectMapper.writeValueAsBytes(request); } catch (JsonProcessingException e) { return createErrorDoctorEndpointResponse( "Failed to encode request to JSON. " + "Reason: " + e.getMessage()); } OkHttpClient httpClient = new OkHttpClient.Builder() .connectTimeout(doctorConfig.getHttpTimeoutMs(), TimeUnit.MILLISECONDS) .readTimeout(doctorConfig.getHttpTimeoutMs(), TimeUnit.MILLISECONDS) .writeTimeout(doctorConfig.getHttpTimeoutMs(), TimeUnit.MILLISECONDS).build(); Response httpResponse; try { RequestBody requestBody; ImmutableMap<String, String> extraArgs = doctorConfig.getExtraRequestArgs(); if (extraArgs.isEmpty()) { requestBody = RequestBody.create(JSON, requestJson); } else { FormBody.Builder formBody = new FormBody.Builder(); formBody.add("data", new String(requestJson)); for (Map.Entry<String, String> entry : extraArgs.entrySet()) { formBody.add(entry.getKey(), entry.getValue()); } requestBody = formBody.build(); } Request httpRequest = new Request.Builder().url(doctorConfig.getEndpointUrl().get()).post(requestBody) .build(); httpResponse = httpClient.newCall(httpRequest).execute(); } catch (IOException e) { return createErrorDoctorEndpointResponse("Failed to perform the request to " + doctorConfig.getEndpointUrl().get() + ". Reason: " + e.getMessage()); } try { if (httpResponse.isSuccessful()) { String body = new String(httpResponse.body().bytes(), Charsets.UTF_8); return objectMapper.readValue(body, DoctorEndpointResponse.class); } return createErrorDoctorEndpointResponse("Request was not successful."); } catch (JsonProcessingException e) { return createErrorDoctorEndpointResponse(String.format(DECODE_FAIL_TEMPLATE, e.getMessage())); } catch (IOException e) { return createErrorDoctorEndpointResponse(String.format(DECODE_FAIL_TEMPLATE, e.getMessage())); } }
From source file:com.google.devtools.build.android.desugar.Desugar.java
/** * Desugar the classes that are generated on the fly when we are desugaring the classes in the * specified inputs./*from w ww . j a v a 2 s . c o m*/ */ private void desugarAndWriteDumpedLambdaClassesToOutput(OutputFileProvider outputFileProvider, ClassLoader loader, ClassReaderFactory readerFactory, Builder<String> interfaceLambdaMethodCollector) throws IOException { ImmutableSet<String> interfaceLambdaMethods = interfaceLambdaMethodCollector.build(); checkState(!allowDefaultMethods || interfaceLambdaMethods.isEmpty(), "Desugaring with default methods enabled moved interface lambdas"); // Write out the lambda classes we generated along the way ImmutableMap<Path, LambdaInfo> lambdaClasses = lambdas.drain(); checkState(!options.onlyDesugarJavac9ForLint || lambdaClasses.isEmpty(), "There should be no lambda classes generated: %s", lambdaClasses.keySet()); for (Map.Entry<Path, LambdaInfo> lambdaClass : lambdaClasses.entrySet()) { try (InputStream bytecode = Files.newInputStream(dumpDirectory.resolve(lambdaClass.getKey()))) { ClassReader reader = rewriter.reader(bytecode); UnprefixingClassWriter writer = rewriter.writer(ClassWriter.COMPUTE_MAXS /*for invoking bridges*/); ClassVisitor visitor = createClassVisitorsForDumpedLambdaClasses(loader, readerFactory, interfaceLambdaMethods, lambdaClass.getValue(), writer); reader.accept(visitor, 0); String filename = rewriter.unprefix(lambdaClass.getValue().desiredInternalName()) + ".class"; outputFileProvider.write(filename, writer.toByteArray()); } } }
From source file:net.oneandone.troilus.UDTValueMapper.java
@SuppressWarnings("unchecked") public <K, V> ImmutableMap<K, V> fromUdtValues(final DataType keyDatatype, final DataType valueDatatype, ImmutableMap<?, ?> udtValues, Class<K> keystype, Class<V> valuesType) { Map<K, V> elements = Maps.newHashMap(); for (Entry<?, ?> entry : udtValues.entrySet()) { K keyElement;/*from www .j a v a 2 s .co m*/ if (keystype.isAssignableFrom(entry.getKey().getClass())) { keyElement = (K) entry.getKey(); } else { final UDTValue keyUdtValue = (UDTValue) entry.getKey(); PropertiesSource propsSource = new PropertiesSource() { @Override public <E> Optional<E> read(String name, Class<?> clazz1) { return read(name, clazz1, Object.class); } @Override public <T> Optional<T> read(String name, Class<?> clazz1, Class<?> clazz2) { return Optional.fromNullable((T) fromUdtValue(((UserType) keyDatatype).getFieldType(name), keyUdtValue, clazz1, clazz2, name)); } }; keyElement = beanMapper.fromValues(keystype, propsSource, ImmutableSet.<String>of()); } V valueElement; if (valuesType.isAssignableFrom(entry.getValue().getClass())) { valueElement = (V) entry.getValue(); } else { final UDTValue valueUdtValue = (UDTValue) entry.getValue(); PropertiesSource propsSource = new PropertiesSource() { @Override public <E> Optional<E> read(String name, Class<?> clazz1) { return read(name, clazz1, Object.class); } @Override public <T> Optional<T> read(String name, Class<?> clazz1, Class<?> clazz2) { return Optional.fromNullable((T) fromUdtValue(((UserType) valueDatatype).getFieldType(name), valueUdtValue, clazz1, clazz2, name)); } }; valueElement = beanMapper.fromValues(valuesType, propsSource, ImmutableSet.<String>of()); } elements.put(keyElement, valueElement); } return ImmutableMap.copyOf(elements); }
From source file:com.facebook.buck.rules.modern.builders.IsolatedBuildableBuilder.java
@SuppressWarnings("PMD.EmptyCatchBlock") IsolatedBuildableBuilder(Path workRoot, Path projectRoot) throws IOException { Path canonicalWorkRoot = workRoot.toRealPath().normalize(); Path canonicalProjectRoot = canonicalWorkRoot.resolve(projectRoot).normalize(); this.dataRoot = workRoot.resolve("__data__"); PluginManager pluginManager = BuckPluginManagerFactory.createPluginManager(); this.classFinder = (name) -> { try {//from w w w . j a va 2 s.co m return Class.forName(name); } catch (ClassNotFoundException e) { for (PluginWrapper plugin : pluginManager.getPlugins()) { try { return plugin.getPluginClassLoader().loadClass(name); } catch (ClassNotFoundException e1) { // ignored } } throw new BuckUncheckedExecutionException(e, "When looking up class %s.", name); } }; // Setup filesystemCell and buck config. Config config = Configs.createDefaultConfig(canonicalProjectRoot); ProjectFilesystemFactory projectFilesystemFactory = new DefaultProjectFilesystemFactory(); // Root filesystemCell doesn't require embedded buck-out info. ProjectFilesystem filesystem = projectFilesystemFactory.createProjectFilesystem(canonicalProjectRoot, config); Architecture architecture = Architecture.detect(); Platform platform = Platform.detect(); ImmutableMap<String, String> clientEnvironment = EnvVariablesProvider.getSystemEnv(); DefaultCellPathResolver cellPathResolver = DefaultCellPathResolver.of(filesystem.getRootPath(), config); UnconfiguredBuildTargetFactory buildTargetFactory = new ParsingUnconfiguredBuildTargetFactory(); BuckConfig buckConfig = new BuckConfig(config, filesystem, architecture, platform, clientEnvironment, buildTargetName -> buildTargetFactory.create(cellPathResolver, buildTargetName)); BuckModuleManager moduleManager = new DefaultBuckModuleManager(pluginManager, new BuckModuleJarHashProvider()); Console console = createConsole(); ProcessExecutor processExecutor = new DefaultProcessExecutor(console); ExecutableFinder executableFinder = new ExecutableFinder(); ToolchainProviderFactory toolchainProviderFactory = new DefaultToolchainProviderFactory(pluginManager, clientEnvironment, processExecutor, executableFinder); CellProvider cellProvider = LocalCellProviderFactory.create(filesystem, buckConfig, CellConfig.of(), cellPathResolver.getPathMapping(), cellPathResolver, moduleManager, toolchainProviderFactory, projectFilesystemFactory, buildTargetFactory); this.filesystemFunction = (cellName) -> cellProvider .getCellByPath(cellPathResolver.getCellPath(cellName).get()).getFilesystem(); JavaPackageFinder javaPackageFinder = buckConfig.getView(JavaBuckConfig.class) .createDefaultJavaPackageFinder(); this.eventBus = createEventBus(console); this.executionContext = ExecutionContext.of(console, eventBus, platform, clientEnvironment, javaPackageFinder, ImmutableMap.of(), Optional.empty(), Optional.empty(), Optional.empty(), cellPathResolver, canonicalProjectRoot, processExecutor, projectFilesystemFactory); this.buildContext = BuildContext.builder().setSourcePathResolver(new AbstractSourcePathResolver() { @Override protected ProjectFilesystem getBuildTargetSourcePathFilesystem(BuildTargetSourcePath sourcePath) { Preconditions.checkState(sourcePath instanceof ExplicitBuildTargetSourcePath); BuildTarget target = sourcePath.getTarget(); return filesystemFunction.apply(target.getCell()); } @Override protected SourcePath resolveDefaultBuildTargetSourcePath( DefaultBuildTargetSourcePath targetSourcePath) { throw new IllegalStateException( "Cannot resolve DefaultBuildTargetSourcePaths when running with an isolated strategy. " + "These should have been resolved to the underlying ExplicitBuildTargetSourcePath already."); } @Override public String getSourcePathName(BuildTarget target, SourcePath sourcePath) { throw new IllegalStateException( "Cannot resolve SourcePath names during build when running with an isolated strategy."); } }).setBuildCellRootPath(canonicalProjectRoot).setEventBus(eventBus).setJavaPackageFinder(javaPackageFinder) .setShouldDeleteTemporaries(buckConfig.getView(BuildBuckConfig.class).getShouldDeleteTemporaries()) .build(); this.toolchainProviderFunction = cellName -> cellProvider .getCellByPath(cellPathResolver.getCellPath(cellName).get()).getToolchainProvider(); RichStream.from(cellPathResolver.getCellPaths().keySet()).forEachThrowing(name -> { // Sadly, some things assume this exists and writes to it. ProjectFilesystem fs = filesystemFunction.apply(Optional.of(name)); BuckPaths configuredPaths = fs.getBuckPaths(); fs.mkdirs(configuredPaths.getTmpDir()); fs.mkdirs(configuredPaths.getBuckOut()); fs.deleteFileAtPathIfExists(configuredPaths.getProjectRootDir()); fs.writeContentsToPath(fs.getRootPath().toString(), configuredPaths.getProjectRootDir()); if (!configuredPaths.getConfiguredBuckOut().equals(configuredPaths.getBuckOut()) && buckConfig.getView(BuildBuckConfig.class).getBuckOutCompatLink() && Platform.detect() != Platform.WINDOWS) { BuckPaths unconfiguredPaths = configuredPaths.withConfiguredBuckOut(configuredPaths.getBuckOut()); ImmutableMap<Path, Path> paths = ImmutableMap.of(unconfiguredPaths.getGenDir(), configuredPaths.getGenDir(), unconfiguredPaths.getScratchDir(), configuredPaths.getScratchDir()); for (Map.Entry<Path, Path> entry : paths.entrySet()) { try { filesystem.createSymLink(entry.getKey(), entry.getKey().getParent().relativize(entry.getValue()), /* force */ false); } catch (FileAlreadyExistsException e) { // Verify that the symlink is valid then continue gracefully if (!filesystem.readSymLink(entry.getKey()) .equals(entry.getKey().getParent().relativize(entry.getValue()))) { throw e; } } } } }); }