Example usage for com.google.common.collect ImmutableMap get

List of usage examples for com.google.common.collect ImmutableMap get

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableMap get.

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:org.sonar.web.it.ProfileGenerator.java

static void generate(Orchestrator orchestrator, String language, String repositoryKey,
        ImmutableMap<String, ImmutableMap<String, String>> rulesParameters, Set<String> excluded) {
    try {//w  ww.  ja  va  2s .  c o  m
        StringBuilder sb = new StringBuilder().append("<profile>").append("<name>rules</name>")
                .append("<language>").append(language).append("</language>").append("<alerts>")
                .append("<alert>").append("<metric>blocker_violations</metric>")
                .append("<operator>&gt;</operator>").append("<warning></warning>").append("<error>0</error>")
                .append("</alert>").append("<alert>").append("<metric>info_violations</metric>")
                .append("<operator>&gt;</operator>").append("<warning></warning>").append("<error>0</error>")
                .append("</alert>").append("</alerts>").append("<rules>");

        List<String> ruleKeys = Lists.newArrayList();
        String json = new HttpRequestFactory(orchestrator.getServer().getUrl()).get("/api/rules/search",
                ImmutableMap.<String, Object>of("languages", language, "repositories", repositoryKey, "ps",
                        "1000"));
        @SuppressWarnings("unchecked")
        List<Map> jsonRules = (List<Map>) ((Map) JSONValue.parse(json)).get("rules");
        for (Map jsonRule : jsonRules) {
            String key = (String) jsonRule.get("key");
            ruleKeys.add(key.split(":")[1]);
        }

        for (String key : ruleKeys) {
            if (excluded.contains(key)) {
                continue;
            }
            sb.append("<rule>").append("<repositoryKey>").append(repositoryKey).append("</repositoryKey>")
                    .append("<key>").append(key).append("</key>").append("<priority>INFO</priority>");
            if (rulesParameters.containsKey(key)) {
                sb.append("<parameters>");
                for (Map.Entry<String, String> parameter : rulesParameters.get(key).entrySet()) {
                    sb.append("<parameter>").append("<key>").append(parameter.getKey()).append("</key>")
                            .append("<value>").append(parameter.getValue()).append("</value>")
                            .append("</parameter>");
                }
                sb.append("</parameters>");
            }
            sb.append("</rule>");
        }

        sb.append("</rules>").append("</profile>");

        File file = File.createTempFile("profile", ".xml");
        Files.write(sb, file, Charsets.UTF_8);
        orchestrator.getServer().restoreProfile(FileLocation.of(file));
        file.delete();
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.mycelium.wallet.activity.settings.SettingsActivity.java

@SuppressWarnings("deprecation")
@Override// ww w .  j  ava  2s.c om
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
    _mbwManager = MbwManager.getInstance(SettingsActivity.this.getApplication());
    _ltManager = _mbwManager.getLocalTraderManager();
    // Bitcoin Denomination
    _bitcoinDenomination = (ListPreference) findPreference("bitcoin_denomination");
    _bitcoinDenomination.setTitle(bitcoinDenominationTitle());
    _bitcoinDenomination.setDefaultValue(_mbwManager.getBitcoinDenomination().toString());
    _bitcoinDenomination.setValue(_mbwManager.getBitcoinDenomination().toString());
    CharSequence[] denominations = new CharSequence[] { Denomination.BTC.toString(),
            Denomination.mBTC.toString(), Denomination.uBTC.toString(), Denomination.BITS.toString() };
    _bitcoinDenomination.setEntries(denominations);
    _bitcoinDenomination.setEntryValues(denominations);
    _bitcoinDenomination.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            _mbwManager.setBitcoinDenomination(Denomination.fromString(newValue.toString()));
            _bitcoinDenomination.setTitle(bitcoinDenominationTitle());
            return true;
        }
    });

    // Miner Fee
    _minerFee = (ListPreference) findPreference("miner_fee");
    _minerFee.setTitle(getMinerFeeTitle());
    _minerFee.setSummary(getMinerFeeSummary());
    _minerFee.setValue(_mbwManager.getMinerFee().toString());
    CharSequence[] minerFees = new CharSequence[] { MinerFee.LOWPRIO.toString(), MinerFee.ECONOMIC.toString(),
            MinerFee.NORMAL.toString(), MinerFee.PRIORITY.toString() };
    CharSequence[] minerFeeNames = new CharSequence[] { getString(R.string.miner_fee_lowprio_name),
            getString(R.string.miner_fee_economic_name), getString(R.string.miner_fee_normal_name),
            getString(R.string.miner_fee_priority_name) };
    _minerFee.setEntries(minerFeeNames);
    _minerFee.setEntryValues(minerFees);
    _minerFee.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            _mbwManager.setMinerFee(MinerFee.fromString(newValue.toString()));
            _minerFee.setTitle(getMinerFeeTitle());
            _minerFee.setSummary(getMinerFeeSummary());
            String description = _mbwManager.getMinerFee().getMinerFeeDescription(SettingsActivity.this);
            Utils.showSimpleMessageDialog(SettingsActivity.this, description);
            return true;
        }
    });

    //Block Explorer
    _blockExplorer = (ListPreference) findPreference("block_explorer");
    _blockExplorer.setTitle(getBlockExplorerTitle());
    _blockExplorer.setSummary(getBlockExplorerSummary());
    _blockExplorer.setValue(_mbwManager._blockExplorerManager.getBlockExplorer().getIdentifier());
    CharSequence[] blockExplorerNames = _mbwManager._blockExplorerManager
            .getBlockExplorerNames(_mbwManager._blockExplorerManager.getAllBlockExplorer());
    CharSequence[] blockExplorerValues = _mbwManager._blockExplorerManager.getBlockExplorerIds();
    _blockExplorer.setEntries(blockExplorerNames);
    _blockExplorer.setEntryValues(blockExplorerValues);
    _blockExplorer.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {
            _mbwManager.setBlockExplorer(
                    _mbwManager._blockExplorerManager.getBlockExplorerById(newValue.toString()));
            _blockExplorer.setTitle(getBlockExplorerTitle());
            _blockExplorer.setSummary(getBlockExplorerSummary());
            return true;
        }
    });

    //localcurrency
    _localCurrency = findPreference("local_currency");
    _localCurrency.setOnPreferenceClickListener(localCurrencyClickListener);
    _localCurrency.setTitle(localCurrencyTitle());

    // Exchange Source
    _exchangeSource = (ListPreference) findPreference("exchange_source");
    ExchangeRateManager exchangeManager = _mbwManager.getExchangeRateManager();
    List<String> exchangeSourceNamesList = exchangeManager.getExchangeSourceNames();
    CharSequence[] exchangeNames = exchangeSourceNamesList.toArray(new String[exchangeSourceNamesList.size()]);
    _exchangeSource.setEntries(exchangeNames);
    if (exchangeNames.length == 0) {
        _exchangeSource.setEnabled(false);
    } else {
        String currentName = exchangeManager.getCurrentExchangeSourceName();
        if (currentName == null) {
            currentName = "";
        }
        _exchangeSource.setEntries(exchangeNames);
        _exchangeSource.setEntryValues(exchangeNames);
        _exchangeSource.setDefaultValue(currentName);
        _exchangeSource.setValue(currentName);
    }
    _exchangeSource.setTitle(exchangeSourceTitle());
    _exchangeSource.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            _mbwManager.getExchangeRateManager().setCurrentExchangeSourceName(newValue.toString());
            _exchangeSource.setTitle(exchangeSourceTitle());
            return true;
        }
    });

    ListPreference language = (ListPreference) findPreference(Constants.LANGUAGE_SETTING);
    language.setTitle(getLanguageSettingTitle());
    language.setDefaultValue(Locale.getDefault().getLanguage());
    language.setSummary(_mbwManager.getLanguage());
    language.setValue(_mbwManager.getLanguage());

    ImmutableMap<String, String> languageLookup = loadLanguageLookups();
    language.setSummary(languageLookup.get(_mbwManager.getLanguage()));

    language.setEntries(R.array.languages_desc);
    language.setEntryValues(R.array.languages);
    language.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            String lang = newValue.toString();
            _mbwManager.setLanguage(lang);
            WalletApplication app = (WalletApplication) getApplication();
            app.applyLanguageChange(lang);

            restart();

            return true;
        }
    });

    // Set PIN
    Preference setPin = Preconditions.checkNotNull(findPreference("setPin"));
    setPin.setOnPreferenceClickListener(setPinClickListener);

    // Clear PIN
    updateClearPin();

    // PIN required on startup
    CheckBoxPreference setPinRequiredStartup = (CheckBoxPreference) Preconditions
            .checkNotNull(findPreference("requirePinOnStartup"));
    setPinRequiredStartup.setOnPreferenceChangeListener(setPinOnStartupClickListener);
    setPinRequiredStartup.setChecked(_mbwManager.getPinRequiredOnStartup());

    // Legacy backup function
    Preference legacyBackup = Preconditions.checkNotNull(findPreference("legacyBackup"));
    legacyBackup.setOnPreferenceClickListener(legacyBackupClickListener);

    // Legacy backup function
    Preference legacyBackupVerify = Preconditions.checkNotNull(findPreference("legacyBackupVerify"));
    legacyBackupVerify.setOnPreferenceClickListener(legacyBackupVerifyClickListener);

    // Local Trader
    CheckBoxPreference ltDisable = (CheckBoxPreference) findPreference("ltDisable");
    ltDisable.setChecked(_ltManager.isLocalTraderDisabled());
    ltDisable.setOnPreferenceClickListener(ltDisableLocalTraderClickListener);

    _ltNotificationSound = (CheckBoxPreference) findPreference("ltNotificationSound");
    _ltNotificationSound.setChecked(_ltManager.getPlaySoundOnTradeNotification());
    _ltNotificationSound.setOnPreferenceClickListener(ltNotificationSoundClickListener);

    _ltMilesKilometers = (CheckBoxPreference) findPreference("ltMilesKilometers");
    _ltMilesKilometers.setChecked(_ltManager.useMiles());
    _ltMilesKilometers.setOnPreferenceClickListener(ltMilesKilometersClickListener);

    // show bip44 path
    CheckBoxPreference showBip44Path = (CheckBoxPreference) findPreference("showBip44Path");
    showBip44Path.setChecked(_mbwManager.getMetadataStorage().getShowBip44Path());
    showBip44Path.setOnPreferenceClickListener(showBip44PathClickListener);

    // Socks Proxy
    final ListPreference useTor = Preconditions.checkNotNull((ListPreference) findPreference("useTor"));
    useTor.setTitle(getUseTorTitle());

    useTor.setEntries(new String[] { getString(R.string.use_https), getString(R.string.use_external_tor),
            //            getString(R.string.both),
    });

    useTor.setEntryValues(new String[] { ServerEndpointType.Types.ONLY_HTTPS.toString(),
            ServerEndpointType.Types.ONLY_TOR.toString(),
            //      ServerEndpointType.Types.HTTPS_AND_TOR.toString(),
    });

    useTor.setValue(_mbwManager.getTorMode().toString());

    useTor.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (newValue.equals(ServerEndpointType.Types.ONLY_TOR.toString())) {
                OrbotHelper obh = new OrbotHelper(SettingsActivity.this);
                if (!obh.isOrbotInstalled()) {
                    obh.promptToInstall(SettingsActivity.this);
                }
            }
            _mbwManager.setTorMode(ServerEndpointType.Types.valueOf((String) newValue));
            useTor.setTitle(getUseTorTitle());
            return true;
        }
    });

    CheckBoxPreference ledgerDisableTee = (CheckBoxPreference) findPreference("ledgerDisableTee");
    Preference ledgerSetUnpluggedAID = findPreference("ledgerUnpluggedAID");

    boolean isTeeAvailable = LedgerTransportTEEProxyFactory.isServiceAvailable(this);
    if (isTeeAvailable) {
        ledgerDisableTee.setChecked(_mbwManager.getLedgerManager().getDisableTEE());
        ledgerDisableTee.setOnPreferenceClickListener(onClickLedgerNotificationDisableTee);
    } else {
        PreferenceCategory ledger = (PreferenceCategory) findPreference("ledger");
        ledger.removePreference(ledgerDisableTee);
    }

    ledgerSetUnpluggedAID.setOnPreferenceClickListener(onClickLedgerSetUnpluggedAID);

    applyLocalTraderEnablement();

    initExternalSettings();

    // external Services
    CheckBoxPreference enableCashilaButton = (CheckBoxPreference) findPreference("enableCashilaButton");
    enableCashilaButton.setChecked(_mbwManager.getMetadataStorage().getCashilaIsEnabled());
    enableCashilaButton.setOnPreferenceClickListener(onClickCashilaEnable);
}

From source file:com.google.api.codegen.transformer.ApiMethodTransformer.java

private List<PathTemplateCheckView> generatePathTemplateChecks(MethodTransformerContext context,
        Iterable<FieldConfig> fieldConfigs) {
    List<PathTemplateCheckView> pathTemplateChecks = new ArrayList<>();
    if (!context.getFeatureConfig().enableStringFormatFunctions()) {
        return pathTemplateChecks;
    }/* w  w  w. j av a  2  s . co m*/
    for (FieldConfig fieldConfig : fieldConfigs) {
        if (!fieldConfig.useValidation()) {
            // Don't generate a path template check if fieldConfig is not configured to use validation.
            continue;
        }
        Field field = fieldConfig.getField();
        ImmutableMap<String, String> fieldNamePatterns = context.getMethodConfig().getFieldNamePatterns();
        String entityName = fieldNamePatterns.get(field.getSimpleName());
        if (entityName != null) {
            SingleResourceNameConfig resourceNameConfig = context.getSingleResourceNameConfig(entityName);
            if (resourceNameConfig == null) {
                String methodName = context.getMethod().getSimpleName();
                throw new IllegalStateException("No collection config with id '" + entityName
                        + "' required by configuration for method '" + methodName + "'");
            }
            PathTemplateCheckView.Builder check = PathTemplateCheckView.newBuilder();
            check.pathTemplateName(
                    context.getNamer().getPathTemplateName(context.getInterface(), resourceNameConfig));
            check.paramName(context.getNamer().getVariableName(field));
            check.allowEmptyString(shouldAllowEmpty(context, field));
            check.validationMessageContext(context.getNamer().getApiMethodName(context.getMethod(),
                    context.getMethodConfig().getVisibility()));
            pathTemplateChecks.add(check.build());
        }
    }
    return pathTemplateChecks;
}

From source file:com.google.devtools.build.lib.rules.cpp.FeatureSelection.java

FeatureSelection(ImmutableSet<String> requestedFeatures,
        ImmutableMap<String, CrosstoolSelectable> selectablesByName,
        ImmutableList<CrosstoolSelectable> selectables, ImmutableMultimap<String, CrosstoolSelectable> provides,
        ImmutableMultimap<CrosstoolSelectable, CrosstoolSelectable> implies,
        ImmutableMultimap<CrosstoolSelectable, CrosstoolSelectable> impliedBy,
        ImmutableMultimap<CrosstoolSelectable, ImmutableSet<CrosstoolSelectable>> requires,
        ImmutableMultimap<CrosstoolSelectable, CrosstoolSelectable> requiredBy,
        ImmutableMap<String, ActionConfig> actionConfigsByActionName) {
    ImmutableSet.Builder<CrosstoolSelectable> builder = ImmutableSet.builder();
    for (String name : requestedFeatures) {
        if (selectablesByName.containsKey(name)) {
            builder.add(selectablesByName.get(name));
        }//from   w  w w .ja va  2s .co  m
    }
    this.requestedSelectables = builder.build();
    this.selectables = selectables;
    this.provides = provides;
    this.implies = implies;
    this.impliedBy = impliedBy;
    this.requires = requires;
    this.requiredBy = requiredBy;
    this.actionConfigsByActionName = actionConfigsByActionName;
}

From source file:org.elasticsearch.snapshots.SnapshotShardsService.java

/**
 * Checks if any shards were processed that the new master doesn't know about
 * @param event// w  w  w  . j a  v a 2s.  c om
 */
private void syncShardStatsOnNewMaster(ClusterChangedEvent event) {
    SnapshotsInProgress snapshotsInProgress = event.state().custom(SnapshotsInProgress.TYPE);
    if (snapshotsInProgress == null) {
        return;
    }
    for (SnapshotsInProgress.Entry snapshot : snapshotsInProgress.entries()) {
        if (snapshot.state() == SnapshotsInProgress.State.STARTED
                || snapshot.state() == SnapshotsInProgress.State.ABORTED) {
            Map<ShardId, IndexShardSnapshotStatus> localShards = currentSnapshotShards(snapshot.snapshotId());
            if (localShards != null) {
                ImmutableMap<ShardId, SnapshotsInProgress.ShardSnapshotStatus> masterShards = snapshot.shards();
                for (Map.Entry<ShardId, IndexShardSnapshotStatus> localShard : localShards.entrySet()) {
                    ShardId shardId = localShard.getKey();
                    IndexShardSnapshotStatus localShardStatus = localShard.getValue();
                    SnapshotsInProgress.ShardSnapshotStatus masterShard = masterShards.get(shardId);
                    if (masterShard != null && masterShard.state().completed() == false) {
                        // Master knows about the shard and thinks it has not completed
                        if (localShardStatus.stage() == IndexShardSnapshotStatus.Stage.DONE) {
                            // but we think the shard is done - we need to make new master know that the shard is done
                            logger.debug(
                                    "[{}] new master thinks the shard [{}] is not completed but the shard is done locally, updating status on the master",
                                    snapshot.snapshotId(), shardId);
                            updateIndexShardSnapshotStatus(snapshot.snapshotId(), shardId,
                                    new SnapshotsInProgress.ShardSnapshotStatus(
                                            event.state().nodes().localNodeId(),
                                            SnapshotsInProgress.State.SUCCESS));
                        } else if (localShard.getValue().stage() == IndexShardSnapshotStatus.Stage.FAILURE) {
                            // but we think the shard failed - we need to make new master know that the shard failed
                            logger.debug(
                                    "[{}] new master thinks the shard [{}] is not completed but the shard failed locally, updating status on master",
                                    snapshot.snapshotId(), shardId);
                            updateIndexShardSnapshotStatus(snapshot.snapshotId(), shardId,
                                    new SnapshotsInProgress.ShardSnapshotStatus(
                                            event.state().nodes().localNodeId(),
                                            SnapshotsInProgress.State.FAILED, localShardStatus.failure()));

                        }
                    }
                }
            }
        }
    }
}

From source file:com.facebook.buck.features.apple.project.SchemeGenerator.java

public Path writeScheme() throws IOException {
    Map<PBXTarget, XCScheme.BuildableReference> buildTargetToBuildableReferenceMap = new HashMap<>();

    for (PBXTarget target : Iterables.concat(orderedBuildTargets, orderedBuildTestTargets)) {
        String blueprintName = target.getProductName();
        if (blueprintName == null) {
            blueprintName = target.getName();
        }//w ww .  j  ava 2  s  .  c o m
        Path outputPath = outputDirectory.getParent();
        String buildableReferencePath;
        Path projectPath = Objects.requireNonNull(targetToProjectPathMap.get(target));
        if (outputPath == null) {
            // Root directory project
            buildableReferencePath = projectPath.toString();
        } else {
            buildableReferencePath = outputPath.relativize(projectPath).toString();
        }

        XCScheme.BuildableReference buildableReference = new XCScheme.BuildableReference(buildableReferencePath,
                Objects.requireNonNull(target.getGlobalID()),
                target.getProductReference() != null ? target.getProductReference().getName()
                        : Objects.requireNonNull(target.getProductName()),
                blueprintName);
        buildTargetToBuildableReferenceMap.put(target, buildableReference);
    }

    Optional<XCScheme.BuildableReference> primaryBuildReference = Optional.empty();
    if (primaryTarget.isPresent()) {
        primaryBuildReference = Optional
                .ofNullable(buildTargetToBuildableReferenceMap.get(primaryTarget.get()));
    }

    XCScheme.BuildAction buildAction = new XCScheme.BuildAction(parallelizeBuild,
            additionalCommandsForSchemeAction(SchemeActionType.BUILD,
                    XCScheme.AdditionalActions.PRE_SCHEME_ACTIONS, primaryBuildReference),
            additionalCommandsForSchemeAction(SchemeActionType.BUILD,
                    XCScheme.AdditionalActions.POST_SCHEME_ACTIONS, primaryBuildReference));

    // For aesthetic reasons put all non-test build actions before all test build actions.
    for (PBXTarget target : orderedBuildTargets) {
        addBuildActionForBuildTarget(buildTargetToBuildableReferenceMap.get(target),
                XCScheme.BuildActionEntry.BuildFor.DEFAULT, buildAction);
    }

    for (PBXTarget target : orderedBuildTestTargets) {
        addBuildActionForBuildTarget(buildTargetToBuildableReferenceMap.get(target),
                XCScheme.BuildActionEntry.BuildFor.TEST_ONLY, buildAction);
    }

    ImmutableMap<SchemeActionType, ImmutableMap<String, String>> envVariables = ImmutableMap.of();
    if (environmentVariables.isPresent()) {
        envVariables = environmentVariables.get();
    }

    XCScheme.TestAction testAction = new XCScheme.TestAction(
            Objects.requireNonNull(actionConfigNames.get(SchemeActionType.TEST)),
            Optional.ofNullable(envVariables.get(SchemeActionType.TEST)),
            additionalCommandsForSchemeAction(SchemeActionType.TEST, AdditionalActions.PRE_SCHEME_ACTIONS,
                    primaryBuildReference),
            additionalCommandsForSchemeAction(SchemeActionType.TEST, AdditionalActions.POST_SCHEME_ACTIONS,
                    primaryBuildReference));

    for (PBXTarget target : orderedRunTestTargets) {
        XCScheme.BuildableReference buildableReference = buildTargetToBuildableReferenceMap.get(target);
        XCScheme.TestableReference testableReference = new XCScheme.TestableReference(buildableReference);
        testAction.addTestableReference(testableReference);
    }

    Optional<XCScheme.LaunchAction> launchAction = Optional.empty();
    Optional<XCScheme.ProfileAction> profileAction = Optional.empty();

    if (primaryTarget.isPresent()) {
        XCScheme.BuildableReference primaryBuildableReference = buildTargetToBuildableReferenceMap
                .get(primaryTarget.get());
        if (primaryBuildableReference != null) {
            launchAction = Optional.of(new XCScheme.LaunchAction(primaryBuildableReference,
                    Objects.requireNonNull(actionConfigNames.get(SchemeActionType.LAUNCH)), runnablePath,
                    remoteRunnablePath, watchInterface, launchStyle,
                    Optional.ofNullable(envVariables.get(SchemeActionType.LAUNCH)),
                    additionalCommandsForSchemeAction(SchemeActionType.LAUNCH,
                            AdditionalActions.PRE_SCHEME_ACTIONS, primaryBuildReference),
                    additionalCommandsForSchemeAction(SchemeActionType.LAUNCH,
                            AdditionalActions.POST_SCHEME_ACTIONS, primaryBuildReference),
                    notificationPayloadFile));

            profileAction = Optional.of(new XCScheme.ProfileAction(primaryBuildableReference,
                    Objects.requireNonNull(actionConfigNames.get(SchemeActionType.PROFILE)),
                    Optional.ofNullable(envVariables.get(SchemeActionType.PROFILE)),
                    additionalCommandsForSchemeAction(SchemeActionType.PROFILE,
                            AdditionalActions.PRE_SCHEME_ACTIONS, primaryBuildReference),
                    additionalCommandsForSchemeAction(SchemeActionType.PROFILE,
                            AdditionalActions.POST_SCHEME_ACTIONS, primaryBuildReference)));
        }
    }
    XCScheme.AnalyzeAction analyzeAction = new XCScheme.AnalyzeAction(
            Objects.requireNonNull(actionConfigNames.get(SchemeActionType.ANALYZE)),
            additionalCommandsForSchemeAction(SchemeActionType.ANALYZE, AdditionalActions.PRE_SCHEME_ACTIONS,
                    primaryBuildReference),
            additionalCommandsForSchemeAction(SchemeActionType.ANALYZE, AdditionalActions.POST_SCHEME_ACTIONS,
                    primaryBuildReference));

    XCScheme.ArchiveAction archiveAction = new XCScheme.ArchiveAction(
            Objects.requireNonNull(actionConfigNames.get(SchemeActionType.ARCHIVE)),
            additionalCommandsForSchemeAction(SchemeActionType.ARCHIVE, AdditionalActions.PRE_SCHEME_ACTIONS,
                    primaryBuildReference),
            additionalCommandsForSchemeAction(SchemeActionType.ARCHIVE, AdditionalActions.POST_SCHEME_ACTIONS,
                    primaryBuildReference));

    XCScheme scheme = new XCScheme(schemeName, wasCreatedForAppExtension, Optional.of(buildAction),
            Optional.of(testAction), launchAction, profileAction, Optional.of(analyzeAction),
            Optional.of(archiveAction));
    outputScheme = Optional.of(scheme);

    Path schemeDirectory = outputDirectory.resolve("xcshareddata/xcschemes");
    projectFilesystem.mkdirs(schemeDirectory);
    Path schemePath = schemeDirectory.resolve(schemeName + ".xcscheme");
    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
        serializeScheme(scheme, outputStream);
        String contentsToWrite = outputStream.toString();
        if (MoreProjectFilesystems.fileContentsDiffer(
                new ByteArrayInputStream(contentsToWrite.getBytes(Charsets.UTF_8)), schemePath,
                projectFilesystem)) {
            projectFilesystem.writeContentsToPath(outputStream.toString(), schemePath);
        }
    }
    return schemePath;
}

From source file:com.google.api.codegen.transformer.go.GoGapicSurfaceTransformer.java

@VisibleForTesting
List<RetryConfigDefinitionView> generateRetryConfigDefinitions(InterfaceContext context,
        List<MethodModel> methods) {
    Set<RetryConfigDefinitionView.Name> retryNames = new HashSet<>();
    for (MethodModel method : methods) {
        MethodConfig conf = context.getMethodConfig(method);
        retryNames.add(RetryConfigDefinitionView.Name.create(conf.getRetrySettingsConfigName(),
                conf.getRetryCodesConfigName()));
    }/* w  w  w . j a  v  a  2 s  . c  o m*/

    TreeMap<RetryConfigDefinitionView.Name, RetryConfigDefinitionView> retryDef = new TreeMap<>();
    Map<String, ImmutableSet<String>> retryCodesDef = context.getInterfaceConfig().getRetryCodesDefinition();
    ImmutableMap<String, RetryParamsDefinitionProto> retryParamsDef = context.getInterfaceConfig()
            .getRetrySettingsDefinition();
    for (RetryConfigDefinitionView.Name name : retryNames) {
        ImmutableSet<String> codes = retryCodesDef.get(name.retryCodesConfigName());
        if (codes.isEmpty()) {
            continue;
        }
        List<String> retryCodeNames = new ArrayList<>();
        for (String code : codes) {
            retryCodeNames.add(context.getNamer().getStatusCodeName(code));
        }
        retryDef.put(name, RetryConfigDefinitionView.newBuilder().name(name).retryCodes(retryCodeNames)
                .params(retryParamsDef.get(name.retrySettingsConfigName())).build());
    }
    if (!retryDef.isEmpty()) {
        context.getImportTypeTable().saveNicknameFor("time;;;");
        context.getImportTypeTable().saveNicknameFor("google.golang.org/grpc/codes;;;");
    }
    return new ArrayList<>(retryDef.values());
}

From source file:com.facebook.buck.cli.BuckConfig.java

public ImmutableSet<Pattern> getTempFilePatterns() {
    final ImmutableMap<String, String> projectConfig = getEntriesForSection("project");
    final String tempFilesKey = "temp_files";
    ImmutableSet.Builder<Pattern> builder = ImmutableSet.builder();
    if (projectConfig.containsKey(tempFilesKey)) {
        for (String regex : Splitter.on(',').omitEmptyStrings().trimResults()
                .split(projectConfig.get(tempFilesKey))) {
            builder.add(Pattern.compile(regex));
        }/* w ww. ja v a 2  s  .  c  om*/
    }
    return builder.build();
}

From source file:se.sics.caracaldb.global.LookupTable.java

private Set<Integer> findReplicationSetSizes() {
    Set<Integer> sizes = new TreeSet<Integer>();
    for (Entry<ByteBuffer, ImmutableMap<String, String>> e : schemas.metaData.entrySet()) {
        ByteBuffer id = e.getKey();
        ImmutableMap<String, String> meta = e.getValue();
        String rfS = J6.orDefault(meta.get("rfactor"), "3");
        Integer rf = Integer.parseInt(rfS);
        String forceMasterS = J6.orDefault(meta.get("forceMaster"), "false");
        boolean forceMaster = Boolean.parseBoolean(forceMasterS);
        if (forceMaster) { // they better all have the same rfactor or weird things are going to happen^^
            masterRepSize = rf;//w ww .java2s .  c  o m
        }
        sizes.add(rf);
        if (UnsignedInts.remainder(rf, 2) == 0) {
            BootstrapServer.LOG.warn(
                    "Schema {} uses a replication factor of {}. " + "It is recommended to use uneven factors.",
                    schemas.schemaNames.get(id), rf);
        }
        if (rf < 3) {
            throw new RuntimeException("Replication factor for any schema must be >=3!");
        }
        if (rf > hosts.size()) {
            throw new RuntimeException(
                    "Replication factor for any schema can't be larger than the initial number of hosts!"
                            + "If you think you have enough hosts for rf=" + rf
                            + " consider incrementing the value of caraca.bootThreshold.");
        }

    }
    if (masterRepSize < 0) { // in case there are no forceMaster schemata
        masterRepSize = 3;
    }
    return sizes;
}

From source file:com.facebook.buck.versions.VersionedTargetGraphBuilder.java

/**
 * @return the {@link BuildTarget} to use in the resolved target graph, formed by adding a
 *         flavor generated from the given version selections.
 *///from   www.  ja  va2  s. c om
private Optional<BuildTarget> getTranslateBuildTarget(TargetNode<?, ?> node,
        ImmutableMap<BuildTarget, Version> selectedVersions) {

    BuildTarget originalTarget = node.getBuildTarget();
    node = resolveVersions(node, selectedVersions);
    BuildTarget newTarget = node.getBuildTarget();

    if (TargetGraphVersionTransformations.isVersionPropagator(node)) {
        VersionInfo info = getVersionInfo(node);
        Collection<BuildTarget> versionedDeps = info.getVersionDomain().keySet();
        TreeMap<BuildTarget, Version> versions = new TreeMap<>();
        for (BuildTarget depTarget : versionedDeps) {
            versions.put(depTarget, selectedVersions.get(depTarget));
        }
        if (!versions.isEmpty()) {
            Flavor versionedFlavor = getVersionedFlavor(versions);
            newTarget = node.getBuildTarget().withAppendedFlavors(versionedFlavor);
        }
    }

    return newTarget.equals(originalTarget) ? Optional.empty() : Optional.of(newTarget);
}