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

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

Introduction

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

Prototype

public ImmutableSet<K> keySet() 

Source Link

Usage

From source file:com.facebook.buck.util.config.Config.java

private HashCode computeOrderIndependentHashCode() {
    ImmutableMap<String, ImmutableMap<String, String>> rawValues = rawConfig.getValues();
    ImmutableSortedMap.Builder<String, ImmutableSortedMap<String, String>> expanded = ImmutableSortedMap
            .naturalOrder();//from ww  w .  j  a v  a  2 s. c o m
    for (String section : rawValues.keySet()) {
        expanded.put(section, ImmutableSortedMap.copyOf(get(section)));
    }

    ImmutableSortedMap<String, ImmutableSortedMap<String, String>> sortedConfigMap = expanded.build();

    Hasher hasher = Hashing.sha256().newHasher();
    for (Entry<String, ImmutableSortedMap<String, String>> entry : sortedConfigMap.entrySet()) {
        hasher.putString(entry.getKey(), StandardCharsets.UTF_8);
        for (Entry<String, String> nestedEntry : entry.getValue().entrySet()) {
            hasher.putString(nestedEntry.getKey(), StandardCharsets.UTF_8);
            hasher.putString(nestedEntry.getValue(), StandardCharsets.UTF_8);
        }
    }

    return hasher.hash();
}

From source file:google.registry.flows.domain.DomainCheckFlow.java

/** Handle the fee check extension. */
private ImmutableList<? extends ResponseExtension> getResponseExtensions(
        ImmutableMap<String, InternetDomainName> domainNames, DateTime now) throws EppException {
    FeeCheckCommandExtension<?, ?> feeCheck = eppInput.getSingleExtension(FeeCheckCommandExtension.class);
    if (feeCheck == null) {
        return ImmutableList.of(); // No fee checks were requested.
    }//from ww  w .  j a v a  2 s .  co  m
    ImmutableList.Builder<FeeCheckResponseExtensionItem> responseItems = new ImmutableList.Builder<>();
    for (FeeCheckCommandExtensionItem feeCheckItem : feeCheck.getItems()) {
        for (String domainName : getDomainNamesToCheckForFee(feeCheckItem, domainNames.keySet())) {
            FeeCheckResponseExtensionItem.Builder<?> builder = feeCheckItem.createResponseBuilder();
            handleFeeRequest(feeCheckItem, builder, domainNames.get(domainName), feeCheck.getCurrency(), now,
                    pricingLogic);
            responseItems.add(builder.setDomainNameIfSupported(domainName).build());
        }
    }
    return ImmutableList.of(feeCheck.createResponse(responseItems.build()));
}

From source file:com.google.devtools.build.lib.rules.genquery.GenQuery.java

@Nullable
private byte[] executeQuery(RuleContext ruleContext, QueryOptions queryOptions, Set<Target> scope, String query)
        throws InterruptedException {
    SkyFunction.Environment env = ruleContext.getAnalysisEnvironment().getSkyframeEnv();
    Pair<ImmutableMap<PackageIdentifier, Package>, ImmutableMap<Label, Target>> closureInfo;
    try {/*from   w  w w.j a v a 2  s. c om*/
        closureInfo = constructPackageMap(env, scope);
        if (closureInfo == null) {
            return null;
        }
    } catch (BrokenQueryScopeException e) {
        ruleContext.ruleError(e.getMessage());
        return null;
    }

    ImmutableMap<PackageIdentifier, Package> packageMap = closureInfo.first;
    ImmutableMap<Label, Target> validTargetsMap = closureInfo.second;
    PackageProvider packageProvider = new PreloadedMapPackageProvider(packageMap, validTargetsMap);
    TargetPatternEvaluator evaluator = new SkyframeEnvTargetPatternEvaluator(env);
    Predicate<Label> labelFilter = Predicates.in(validTargetsMap.keySet());

    return doQuery(queryOptions, packageProvider, labelFilter, evaluator, query, ruleContext);
}

From source file:org.commoncrawl.mapred.ec2.parser.ParserMapper.java

private static void safeAppendLinksFromFeed(JsonObject feedOrItemObj,
        ImmutableMap<String, String> validLinkTypes, List<FeedLink> feedMetaLinks, List links)
        throws IOException {
    for (Object link : links) {
        com.sun.syndication.feed.atom.Link linkObj = (com.sun.syndication.feed.atom.Link) link;
        if (linkObj.getHref() != null && linkObj.getRel() != null) {

            String canonicalHref = canonicalizeURL(linkObj.getHref());

            if (canonicalHref == null) {
                LOG.error("Failed to Canoniclize Link URL:" + linkObj.getHref());
            } else {
                if (validLinkTypes.keySet().contains(linkObj.getRel())) {
                    JsonObject jsonLink = new JsonObject();
                    FeedLink metaLink = new FeedLink();

                    safeSetString(jsonLink, "type", linkObj.getType());
                    if (linkObj.getType() != null)
                        metaLink.setType(linkObj.getType());
                    safeSetString(jsonLink, "href", canonicalHref);
                    if (linkObj.getHref() != null)
                        metaLink.setHref(canonicalHref);
                    safeSetString(jsonLink, "rel", linkObj.getRel());
                    if (linkObj.getRel() != null)
                        metaLink.setRel(linkObj.getRel());

                    safeSetString(jsonLink, "title", linkObj.getTitle());
                    if (linkObj.getTitle() != null)
                        metaLink.setTitle(linkObj.getTitle());

                    feedMetaLinks.add(metaLink);

                    String linkName = validLinkTypes.get(linkObj.getRel());

                    JsonElement existing = feedOrItemObj.get(linkName);
                    if (existing != null) {
                        JsonArray array = null;
                        if (!existing.isJsonArray()) {
                            array = new JsonArray();
                            array.add(existing);
                            feedOrItemObj.remove(linkName);
                            feedOrItemObj.add(linkName, array);
                        } else {
                            array = existing.getAsJsonArray();
                        }/*w  w  w.ja  va  2s .c o  m*/
                        array.add(jsonLink);
                    } else {
                        feedOrItemObj.add(linkName, jsonLink);
                    }
                }
            }
        }
    }
}

From source file:com.facebook.buck.artifact_cache.SQLiteArtifactCache.java

private ListenableFuture<Void> storeMetadata(ArtifactInfo info) {
    ImmutableMap<String, String> metadata = info.getMetadata();

    // verify that all metadata keys are valid
    for (String key : metadata.keySet()) {
        if (!BuildInfo.METADATA_KEYS.contains(key)
                && !key.equals(TwoLevelArtifactCacheDecorator.METADATA_KEY)) {
            throw new HumanReadableException("Metadata contained unexpected key: [%s]", key);
        }// ww  w.ja v a2  s  .com
    }

    try {
        db.storeMetadata(info.getRuleKeys(), marshalMetadata(metadata));
    } catch (IOException | SQLException e) {
        LOG.warn(e, "Metadata store(%s) error", info.getRuleKeys());
    }

    return Futures.immediateFuture(null);
}

From source file:com.facebook.buck.artifact_cache.AbstractAsynchronousCache.java

private void doMultiCheck(ImmutableMap<RuleKey, ClaimedFetchRequest> ruleKeyToRequest) {
    try {//from  w ww . j  a  va 2  s.c o  m
        ImmutableMap<RuleKey, CacheResult> ruleKeyToResult = multiContainsImpl(ruleKeyToRequest.keySet())
                .getCacheResults();
        for (Map.Entry<RuleKey, CacheResult> result : ruleKeyToResult.entrySet()) {
            CacheResult cacheResult = result.getValue();
            ClaimedFetchRequest claimedFetchRequest = ruleKeyToRequest.get(result.getKey());
            if (claimedFetchRequest == null) {
                LOG.verbose("Recived cache result for not requested rule key.");
                continue;
            }
            if (!cacheResult.getType().isSuccess()) {
                // If rule key is not present in the cache, there is no point in trying to download
                // it.
                claimedFetchRequest.setResult(cacheResult);
            } else {
                // Otherwise reschedule it. It will be added to the fetch queue and it will be picked
                // by fetching thread.
                claimedFetchRequest.reschedule();
            }
        }
    } catch (IOException e) {
        String msg = String.format("multicheck(<%s>): %s: %s", Joiner.on(", ").join(ruleKeyToRequest.keySet()),
                e.getClass().getName(), e.getMessage());
        // Some of these might already be fulfilled. That's fine, this set() call will just be
        // ignored.
        for (ClaimedFetchRequest request : ruleKeyToRequest.values()) {
            request.setResult(CacheResult.error(name, mode, msg));
        }
    }
}

From source file:org.jclouds.aws.filters.FormSignerV4.java

@Override
public HttpRequest filter(HttpRequest request) throws HttpException {
    checkArgument(request.getHeaders().containsKey(HOST), "request is not ready to sign; host not present");
    String host = request.getFirstHeaderOrNull(HOST);
    String form = request.getPayload().getRawContent().toString();
    Multimap<String, String> decodedParams = queryParser().apply(form);
    checkArgument(decodedParams.containsKey(ACTION), "request is not ready to sign; Action not present %s",
            form);/* w  ww . j a va 2s. c om*/

    String timestamp = iso8601Timestamp.get();
    String datestamp = timestamp.substring(0, 8);

    String service = serviceAndRegion.service();
    String region = serviceAndRegion.region(host);
    String credentialScope = Joiner.on('/').join(datestamp, region, service, "aws4_request");

    // content-type is not a required signing param. However, examples use this, so we include it to ease testing.
    ImmutableMap.Builder<String, String> signedHeadersBuilder = ImmutableMap.<String, String>builder() //
            .put("content-type", request.getPayload().getContentMetadata().getContentType()) //
            .put("host", host) //
            .put("x-amz-date", timestamp);

    HttpRequest.Builder<?> requestBuilder = request.toBuilder() //
            .removeHeader(AUTHORIZATION) //
            .replaceHeader("X-Amz-Date", timestamp);

    if (!decodedParams.containsKey(VERSION)) {
        requestBuilder.addFormParam(VERSION, apiVersion);
    }

    Credentials credentials = creds.get();

    if (credentials instanceof SessionCredentials) {
        String token = SessionCredentials.class.cast(credentials).getSessionToken();
        requestBuilder.replaceHeader("X-Amz-Security-Token", token);
        signedHeadersBuilder.put("x-amz-security-token", token);
    }

    ImmutableMap<String, String> signedHeaders = signedHeadersBuilder.build();

    String stringToSign = createStringToSign(requestBuilder.build(), signedHeaders, credentialScope);
    byte[] signatureKey = signatureKey(credentials.credential, datestamp, region, service);
    String signature = base16().lowerCase().encode(hmacSHA256(stringToSign, signatureKey));

    StringBuilder authorization = new StringBuilder("AWS4-HMAC-SHA256 ");
    authorization.append("Credential=").append(credentials.identity).append('/').append(credentialScope)
            .append(", ");
    authorization.append("SignedHeaders=").append(Joiner.on(';').join(signedHeaders.keySet())).append(", ");
    authorization.append("Signature=").append(signature);

    return requestBuilder.addHeader(AUTHORIZATION, authorization.toString()).build();
}

From source file:eu.eidas.auth.commons.attribute.ImmutableAttributeMap.java

/**
 * Returns all the {@link AttributeDefinition}s in the map matching the given friendly name or returns {@code null}
 * if no attribute in this map matches the given {@link AttributeDefinition}.
 *
 * @param friendlyName the attribute friendly name to look up.
 * @return all the {@link AttributeDefinition}s in the map matching the given friendly name or returns {@code null}
 * when there is no match.//from w ww.j a va2  s  . c  o m
 */
@Nullable
public ImmutableSet<AttributeDefinition<?>> getDefinitionsByFriendlyName(@Nonnull String friendlyName) {
    ImmutableMap<AttributeDefinition<?>, ImmutableSet<? extends AttributeValue<?>>> subMap = friendlyNameMap
            .get(friendlyName);
    if (null == subMap) {
        return null;
    }
    return subMap.keySet();
}

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());
    };/* w  w w  .j  av  a  2 s  .  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:edu.harvard.med.screensaver.service.cherrypicks.CherryPickRequestAllocator.java

/**
 * @return the set of <i>unfulfillable</i> cherry picks
 * @throws DataModelViolationException if the source wells for the labCherryPicks contain duplicates
 *//* w ww .j  av  a2 s . c  o  m*/
@Transactional
public Set<LabCherryPick> allocate(Collection<LabCherryPick> labCherryPicks) {
    Set<LabCherryPick> unfulfillableLabCherryPicks = new HashSet<LabCherryPick>();
    if (labCherryPicks.size() == 0) {
        return unfulfillableLabCherryPicks;
    }

    try {
        final ImmutableMap<Well, LabCherryPick> well2lcp = Maps.uniqueIndex(labCherryPicks,
                new Function<LabCherryPick, Well>() {
                    public Well apply(LabCherryPick lcp) {
                        return lcp.getSourceWell();
                    }
                });
        CherryPickRequest cherryPickRequest = labCherryPicks.iterator().next().getCherryPickRequest();
        Map<Well, Set<Copy>> copyCandidatesForWells = findCopyCandidatesForWells(well2lcp.keySet(),
                cherryPickRequest.getTransferVolumePerWellApproved());
        // remove unfulfillable wells now, as they would force the minimum copy set to always be empty
        Set<Well> unfulfillableWells = removeUnfulfillableWells(copyCandidatesForWells);
        assert Sets.intersection(unfulfillableWells, copyCandidatesForWells.keySet()).isEmpty();
        Set<Copy> minimumCopySetForWells = findMinimumCopySetForWells(copyCandidatesForWells);
        if (log.isDebugEnabled()) {
            log.debug("using minimum copy set: " + minimumCopySetForWells);
        }
        for (LabCherryPick labCherryPick : labCherryPicks) {
            if (!unfulfillableWells.contains(labCherryPick.getSourceWell())) {
                Set<Copy> copyCandidatesForWell = copyCandidatesForWells.get(labCherryPick.getSourceWell());
                Set<Copy> copyCandidatesForWellAndPlate = Sets.intersection(minimumCopySetForWells,
                        copyCandidatesForWell);
                if (log.isDebugEnabled()) {
                    log.debug("copy candidates for well " + copyCandidatesForWell);
                    log.debug("copy candidates for well and plate " + copyCandidatesForWellAndPlate);
                }
                assert !copyCandidatesForWellAndPlate
                        .isEmpty() : "algorithm for determining minimum set of copies is incorrect";
                Copy selectedCopy = Collections.min(copyCandidatesForWellAndPlate);
                labCherryPick.setAllocated(selectedCopy);
                if (log.isDebugEnabled()) {
                    log.debug("volume for " + labCherryPick + " allocated from " + selectedCopy);
                }
            }
        }

        Iterable<LabCherryPick> unfulfillableLCPsIter = Iterables.transform(unfulfillableWells,
                new Function<Well, LabCherryPick>() {
                    public LabCherryPick apply(Well well) {
                        return well2lcp.get(well);
                    }
                });
        HashSet<LabCherryPick> unfulfillableLCPs = Sets.newHashSet(unfulfillableLCPsIter);
        if (log.isDebugEnabled()) {
            log.debug("unfulfillable lab cherry picks: " + unfulfillableLCPs);
        }
        return unfulfillableLCPs;
    } catch (IllegalArgumentException e) {
        //  We do not allow requests for allocation of
        //  multiple lab cherry picks that have the same source well. This is critical,
        //  since multiple allocations of the same source well could result in
        //  overdrawing reagent from the source well. This is due to the fact that
        //  remaining well volume checking is based upon the remaining well volumes as
        //  recorded in the database, and the implementation, above, does not currently handle
        //  the case where two or more reservations are being made from the same source
        //  well (though, it could be made to do so).
        throw new BusinessRuleViolationException(
                "cannot allocate lab cherry picks if source wells are not unique");
    }
}