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

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

Introduction

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

Prototype

public final ImmutableSet<Entry<K, V>> entrySet() 

Source Link

Usage

From source file:com.facebook.buck.zip.ZipDirectoryWithMaxDeflateStep.java

@Override
public int execute(ExecutionContext context) {
    ProjectFilesystem filesystem = context.getProjectFilesystem();
    File inputDirectory = filesystem.getFileForRelativePath(inputDirectoryPath);
    Preconditions.checkState(inputDirectory.exists() && inputDirectory.isDirectory(), "%s must be a directory.",
            inputDirectoryPath);//from   w  w  w. j a v  a  2  s  .  com

    try {
        ImmutableMap.Builder<File, ZipEntry> zipEntriesBuilder = ImmutableMap.builder();
        addDirectoryToZipEntryList(inputDirectory, "", zipEntriesBuilder);
        ImmutableMap<File, ZipEntry> zipEntries = zipEntriesBuilder.build();

        if (!zipEntries.isEmpty()) {
            File outputZipFile = filesystem.getFileForRelativePath(outputZipPath);
            try (CustomZipOutputStream outputStream = ZipOutputStreams.newOutputStream(outputZipFile)) {
                for (Map.Entry<File, ZipEntry> zipEntry : zipEntries.entrySet()) {
                    outputStream.putNextEntry(zipEntry.getValue());
                    ByteStreams.copy(Files.newInputStreamSupplier(zipEntry.getKey()), outputStream);
                    outputStream.closeEntry();
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace(context.getStdErr());
        return 1;
    }
    return 0;
}

From source file:com.facebook.buck.parser.DaemonicCellState.java

Optional<MapDifference<String, String>> invalidateIfEnvHasChanged(Cell cell, Path buildFile) {
    try (AutoCloseableLock writeLock = rawAndComputedNodesLock.writeLock()) {
        // Invalidate if env vars have changed.
        ImmutableMap<String, Optional<String>> usedEnv = buildFileEnv.get(buildFile);
        if (usedEnv == null) {
            this.cell = cell;
            return Optional.empty();
        }/* w  w w  .  j  a va  2  s . c  o m*/
        for (Map.Entry<String, Optional<String>> ent : usedEnv.entrySet()) {
            Optional<String> value = Optional
                    .ofNullable(cell.getBuckConfig().getEnvironment().get(ent.getKey()));
            if (!value.equals(ent.getValue())) {
                invalidatePath(buildFile);
                this.cell = cell;
                return Optional.of(Maps.difference(
                        value.map(v -> ImmutableMap.of(ent.getKey(), v)).orElse(ImmutableMap.of()),
                        ent.getValue().map(v -> ImmutableMap.of(ent.getKey(), v)).orElse(ImmutableMap.of())));
            }
        }
        return Optional.empty();
    }
}

From source file:com.addthis.hydra.job.web.resources.GroupsResource.java

private Map<String, List<MinimalJob>> generateUsageOutput(Comparator<MinimalJob> comparator, String group,
        String creator, String owner, int limit) {
    ImmutableMap<String, ImmutableList<MinimalJob>> data = diskUsage;
    Map<String, List<MinimalJob>> result = new HashMap<>();
    for (Map.Entry<String, ImmutableList<MinimalJob>> entry : data.entrySet()) {
        List<MinimalJob> list = new ArrayList<>(entry.getValue());
        Collections.sort(list, comparator);
        result.put(entry.getKey(), list);
    }/* w  w w.ja  v a 2s . co m*/
    filterByGroup(result, group);
    filterByCreator(result, creator);
    filterByOwner(result, owner);
    filterByLimit(result, limit);
    return result;
}

From source file:com.spectralogic.dsbrowser.gui.services.tasks.Ds3PutJob.java

@Override
public void executeJob() throws Exception {
    final boolean metadata = settings.getFilePropertiesSettings().isFilePropertiesEnabled();
    final boolean hasPriority = !Guard.isStringNullOrEmpty(jobPriority);
    final Instant jobStartInstant = Instant.now();
    final String startJobDate = dateTimeUtils.nowAsString();
    final String jobInitiateTitleMessage = buildJobInitiatedTitleMessage(startJobDate, ds3Client);
    final String transferringMessage = buildTransferringMessage(resourceBundle);

    LOG.info(resourceBundle.getString("putJobStarted"));
    updateTitle(resourceBundle.getString("blackPearlHealth"));

    if (!CheckNetwork.isReachable(ds3Client)) {
        hostNotAvailable();//ww  w.  j  av  a2 s  . c om
        return;
    }
    updateTitle(jobInitiateTitleMessage);
    updateMessage(transferringMessage);

    final ImmutableMap.Builder<String, Path> fileMapBuilder = ImmutableMap.builder();
    final ImmutableMap.Builder<String, Path> folderMapBuilder = ImmutableMap.builder();
    final ImmutableMap.Builder<String, Path> fileMapperBuilder = ImmutableMap.builder();
    files.forEach(
            pair -> buildMaps(fileMapBuilder, folderMapBuilder, pair, loggingService, targetDir, delimiter));
    final ImmutableMap<String, Path> fileMap = fileMapBuilder.build();
    final ImmutableMap<String, Path> folderMap = folderMapBuilder.build();
    fileMapperBuilder.putAll(fileMap);
    fileMapperBuilder.putAll(folderMap);
    final ImmutableMap<String, Path> fileMapper = fileMapperBuilder.build();
    final ImmutableList<Ds3Object> objects = fileMapper.entrySet().stream().map(this::buildDs3Object)
            .filter(Optional::isPresent).map(Optional::get).collect(GuavaCollectors.immutableList());
    if (objects.isEmpty()) {
        loggingService.logMessage("Job was empty, not sending", LogType.INFO);
        return;
    }
    this.job = Ds3ClientHelpers.wrap(ds3Client).startWriteJob(bucket, objects);
    final long totalJobSize = getTotalJobSize();

    job.withMaxParallelRequests(maximumNumberOfParallelThreads);

    ParseJobInterruptionMap.saveValuesToFiles(jobInterruptionStore, fileMap, folderMap,
            ds3Client.getConnectionDetails().getEndpoint(), this.getJobId(), totalJobSize, targetDir,
            dateTimeUtils, PUT, bucket);

    updateMessage(StringBuilderUtil
            .transferringTotalJobString(FileSizeFormat.getFileSizeType(totalJobSize), targetDirectory)
            .toString());

    if (hasPriority) {
        ds3Client.modifyJobSpectraS3(
                new ModifyJobSpectraS3Request(job.getJobId()).withPriority(Priority.valueOf(jobPriority)));
    }

    if (metadata) {
        LOG.info("Registering metadata access Implementation");
        job.withMetadata(new MetadataAccessImpl(fileMapper));
    }

    addWaitingForChunkListener(totalJobSize, bucket + StringConstants.DOUBLE_SLASH + targetDir);
    final AtomicLong totalSent = addDataTransferListener(totalJobSize);
    job.attachObjectCompletedListener(
            obj -> updateGuiOnComplete(startJobDate, jobStartInstant, totalJobSize, totalSent, obj));

    job.transfer(file -> FileChannel.open(PathUtil.resolveForSymbolic(fileMapper.get(file)),
            StandardOpenOption.READ));

    final Disposable d = waitForPermanentStorageTransfer(totalJobSize).observeOn(JavaFxScheduler.platform())
            .doOnComplete(() -> {
                LOG.info("Job transferred to permanent storage location");

                final String newDate = dateTimeUtils.nowAsString();
                loggingService
                        .logMessage(StringBuilderUtil
                                .jobSuccessfullyTransferredString(PUT,
                                        FileSizeFormat.getFileSizeType(totalJobSize), bucket + "\\" + targetDir,
                                        newDate, resourceBundle.getString("permanentStorageLocation"), false)
                                .toString(), LogType.SUCCESS);

                Ds3PanelService.throttledRefresh(remoteDestination);
                ParseJobInterruptionMap.removeJobID(jobInterruptionStore, this.getJobId().toString(),
                        ds3Client.getConnectionDetails().getEndpoint(), deepStorageBrowserPresenter,
                        loggingService);
            }).subscribe();
    while (!d.isDisposed()) {
        Thread.sleep(1000);
    }
}

From source file:com.facebook.buck.haskell.HaskellGhciDescription.java

@Override
public BuildRule createBuildRule(TargetGraph targetGraph, BuildTarget buildTarget,
        final ProjectFilesystem projectFilesystem, BuildRuleParams params, final BuildRuleResolver resolver,
        final CellPathResolver cellPathResolver, HaskellGhciDescriptionArg args)
        throws NoSuchBuildTargetException {

    CxxPlatform cxxPlatform = cxxPlatforms.getValue(buildTarget).orElse(defaultCxxPlatform);
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
    SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);

    ImmutableSet.Builder<BuildRule> depsBuilder = ImmutableSet.builder();
    depsBuilder.addAll(CxxDeps.builder().addDeps(args.getDeps()).addPlatformDeps(args.getPlatformDeps()).build()
            .get(resolver, cxxPlatform));
    ImmutableSet<BuildRule> deps = depsBuilder.build();

    ImmutableSet.Builder<HaskellPackage> haskellPackages = ImmutableSet.builder();
    ImmutableSet.Builder<HaskellPackage> prebuiltHaskellPackages = ImmutableSet.builder();
    ImmutableSet.Builder<HaskellPackage> firstOrderHaskellPackages = ImmutableSet.builder();
    AbstractBreadthFirstThrowingTraversal<BuildRule, NoSuchBuildTargetException> haskellVisitor = new AbstractBreadthFirstThrowingTraversal<BuildRule, NoSuchBuildTargetException>(
            deps) {/*from  ww w . j a v a2s .  c o m*/
        @Override
        public ImmutableSet<BuildRule> visit(BuildRule rule) throws NoSuchBuildTargetException {
            ImmutableSet.Builder<BuildRule> traverse = ImmutableSet.builder();
            if (rule instanceof HaskellLibrary || rule instanceof PrebuiltHaskellLibrary) {
                HaskellCompileInput ci = ((HaskellCompileDep) rule).getCompileInput(cxxPlatform,
                        Linker.LinkableDepType.STATIC, args.getEnableProfiling());

                if (params.getBuildDeps().contains(rule)) {
                    firstOrderHaskellPackages.addAll(ci.getPackages());
                }

                if (rule instanceof HaskellLibrary) {
                    haskellPackages.addAll(ci.getPackages());
                    traverse.addAll(rule.getBuildDeps());
                } else if (rule instanceof PrebuiltHaskellLibrary) {
                    prebuiltHaskellPackages.addAll(ci.getPackages());
                    traverse.addAll(rule.getBuildDeps());
                }
            }

            return traverse.build();
        }
    };
    haskellVisitor.start();

    ImmutableSet.Builder<NativeLinkable> nativeLinkables = ImmutableSet.builder();
    AbstractBreadthFirstThrowingTraversal<BuildRule, NoSuchBuildTargetException> cxxVisitor = new AbstractBreadthFirstThrowingTraversal<BuildRule, NoSuchBuildTargetException>(
            deps) {
        @Override
        public ImmutableSet<BuildRule> visit(BuildRule rule) throws NoSuchBuildTargetException {
            ImmutableSet.Builder<BuildRule> traverse = ImmutableSet.builder();
            if (rule instanceof CxxLibrary) {
                nativeLinkables.add((NativeLinkable) rule);
            } else if (rule instanceof PrebuiltCxxLibrary) {
                nativeLinkables.add((NativeLinkable) rule);
            } else if (rule instanceof HaskellLibrary || rule instanceof PrebuiltHaskellLibrary) {
                for (NativeLinkable nl : ((NativeLinkable) rule)
                        .getNativeLinkableExportedDepsForPlatform(cxxPlatform)) {
                    traverse.add((BuildRule) nl);
                }
            }

            return traverse.build();
        }
    };
    cxxVisitor.start();

    ImmutableList<NativeLinkable> sortedNativeLinkables = getSortedNativeLinkables(cxxPlatform,
            nativeLinkables.build());

    BuildRule omnibusSharedObject = requireOmnibusSharedObject(buildTarget, projectFilesystem, resolver,
            cxxPlatform, sortedNativeLinkables);

    ImmutableSortedMap.Builder<String, SourcePath> solibs = ImmutableSortedMap.naturalOrder();
    for (NativeLinkable nativeLinkable : sortedNativeLinkables) {
        if (isPrebuiltSO(nativeLinkable, cxxPlatform)) {
            ImmutableMap<String, SourcePath> sharedObjects = nativeLinkable.getSharedLibraries(cxxPlatform);
            for (Map.Entry<String, SourcePath> ent : sharedObjects.entrySet()) {
                if (ent.getValue() instanceof PathSourcePath) {
                    solibs.put(ent.getKey(), ent.getValue());
                }
            }
        }
    }

    HaskellSources srcs = HaskellSources.from(buildTarget, resolver, pathResolver, ruleFinder, cxxPlatform,
            "srcs", args.getSrcs());

    return resolver.addToIndex(HaskellGhciRule.from(buildTarget, projectFilesystem, params, resolver, srcs,
            args.getCompilerFlags(), args.getGhciBinDep(), args.getGhciInit(), omnibusSharedObject,
            solibs.build(), firstOrderHaskellPackages.build(), haskellPackages.build(),
            prebuiltHaskellPackages.build(), args.getEnableProfiling(), haskellConfig.getGhciScriptTemplate(),
            haskellConfig.getGhciBinutils(), haskellConfig.getGhciGhc(), haskellConfig.getGhciLib(),
            haskellConfig.getGhciCxx(), haskellConfig.getGhciCc(), haskellConfig.getGhciCpp()));
}

From source file:org.dcache.webdav.transfer.CredentialServiceClient.java

public StaticOpenIdCredential getDelegatedCredential(String token,
        ImmutableMap<String, OpenIdClientSecret> clientSecrets)
        throws InterruptedException, ErrorResponseException {
    HttpClient client = HttpClientBuilder.create().build();
    List<String> failures = new ArrayList<>();
    for (Map.Entry<String, OpenIdClientSecret> entry : clientSecrets.entrySet()) {
        String host = entry.getKey();
        String id = entry.getValue().getId();
        String secret = entry.getValue().getSecret();

        try {//from ww w .j  a  v a 2s .co m
            JSONObject json = delegateOpenIdCredential(client, buildRequest(token, host, id, secret));

            return createOidcCredential(host, id, secret, json);
        } catch (AuthenticationException | IOException | JSONException e) {
            failures.add(String.format("[%s -> %s]", host, e.toString()));
        }
    }

    LOGGER.warn("OIDC delegation failed: {}", failures.stream().collect(Collectors.joining(", ")));
    throw new ErrorResponseException(Status.SC_INTERNAL_SERVER_ERROR,
            "Error performing OpenId-Connect delegation");

}

From source file:com.facebook.buck.apple.ProvisioningProfileStore.java

public Optional<ProvisioningProfileMetadata> getBestProvisioningProfile(String bundleID,
        Optional<ImmutableMap<String, NSObject>> entitlements,
        Optional<? extends Iterable<CodeSignIdentity>> identities) {
    final Optional<String> prefix;
    if (entitlements.isPresent()) {
        prefix = ProvisioningProfileMetadata.prefixFromEntitlements(entitlements.get());
    } else {//from  ww  w.  ja v a  2 s .  c om
        prefix = Optional.empty();
    }

    int bestMatchLength = -1;
    Optional<ProvisioningProfileMetadata> bestMatch = Optional.empty();

    for (ProvisioningProfileMetadata profile : getProvisioningProfiles()) {
        if (profile.getExpirationDate().after(new Date())) {
            Pair<String, String> appID = profile.getAppID();

            LOG.debug("Looking at provisioning profile " + profile.getUUID() + "," + appID.toString());

            if (!prefix.isPresent() || prefix.get().equals(appID.getFirst())) {
                String profileBundleID = appID.getSecond();
                boolean match;
                if (profileBundleID.endsWith("*")) {
                    // Chop the ending * if wildcard.
                    profileBundleID = profileBundleID.substring(0, profileBundleID.length() - 1);
                    match = bundleID.startsWith(profileBundleID);
                } else {
                    match = (bundleID.equals(profileBundleID));
                }

                if (!match) {
                    LOG.debug("Ignoring non-matching ID for profile " + profile.getUUID());
                }

                // Match against other keys of the entitlements.  Otherwise, we could potentially select
                // a profile that doesn't have all the needed entitlements, causing a error when
                // installing to device.
                //
                // For example: get-task-allow, aps-environment, etc.
                if (match && entitlements.isPresent()) {
                    ImmutableMap<String, NSObject> entitlementsDict = entitlements.get();
                    ImmutableMap<String, NSObject> profileEntitlements = profile.getEntitlements();
                    for (Entry<String, NSObject> entry : entitlementsDict.entrySet()) {
                        if (!(entry.getKey().equals("keychain-access-groups")
                                || entry.getKey().equals("application-identifier")
                                || entry.getKey().equals("com.apple.developer.associated-domains")
                                || matchesOrArrayIsSubsetOf(entry.getValue(),
                                        profileEntitlements.get(entry.getKey())))) {
                            match = false;
                            LOG.debug("Ignoring profile " + profile.getUUID() + " with mismatched entitlement "
                                    + entry.getKey() + "; value is " + profileEntitlements.get(entry.getKey())
                                    + " but expected " + entry.getValue());
                            break;
                        }
                    }
                }

                // Reject any certificate which we know we can't sign with the supplied identities.
                ImmutableSet<HashCode> validFingerprints = profile.getDeveloperCertificateFingerprints();
                if (match && identities.isPresent() && !validFingerprints.isEmpty()) {
                    match = false;
                    for (CodeSignIdentity identity : identities.get()) {
                        Optional<HashCode> fingerprint = identity.getFingerprint();
                        if (fingerprint.isPresent() && validFingerprints.contains(fingerprint.get())) {
                            match = true;
                            break;
                        }
                    }

                    if (!match) {
                        LOG.debug("Ignoring profile " + profile.getUUID()
                                + " because it can't be signed with any valid identity in the current keychain.");
                    }
                }

                if (match && profileBundleID.length() > bestMatchLength) {
                    bestMatchLength = profileBundleID.length();
                    bestMatch = Optional.of(profile);
                }
            }
        } else {
            LOG.debug("Ignoring expired profile " + profile.getUUID());
        }
    }

    LOG.debug("Found provisioning profile " + bestMatch.toString());
    return bestMatch;
}

From source file:com.google.errorprone.bugpatterns.InconsistentCapitalization.java

@Override
public Description matchClass(ClassTree tree, VisitorState state) {
    ImmutableSet<Symbol> fields = FieldScanner.findFields(tree);

    if (fields.isEmpty()) {
        return Description.NO_MATCH;
    }//from w  w  w . j a v a  2 s.com

    ImmutableMap<String, Symbol> fieldNamesMap = fields.stream()
            .collect(toImmutableMap(symbol -> Ascii.toLowerCase(symbol.toString()), x -> x, (x, y) -> x));
    ImmutableMap<TreePath, Symbol> matchedParameters = MatchingParametersScanner
            .findMatchingParameters(fieldNamesMap, state.getPath());

    if (matchedParameters.isEmpty()) {
        return Description.NO_MATCH;
    }

    for (Entry<TreePath, Symbol> entry : matchedParameters.entrySet()) {
        TreePath parameterPath = entry.getKey();
        Symbol field = entry.getValue();
        String fieldName = field.getSimpleName().toString();
        VariableTree parameterTree = (VariableTree) parameterPath.getLeaf();
        SuggestedFix.Builder fix = SuggestedFix.builder()
                .merge(SuggestedFixes.renameVariable(parameterTree, fieldName, state));

        if (parameterPath.getParentPath() != null) {
            String qualifiedName = getExplicitQualification(parameterPath, tree, state) + field.getSimpleName();
            // If the field was accessed in a non-qualified way, by renaming the parameter this may
            // cause clashes with it. Thus, it is required to qualify all uses of the field within the
            // parameter's scope just in case.
            parameterPath.getParentPath().getLeaf().accept(new TreeScanner<Void, Void>() {
                @Override
                public Void visitIdentifier(IdentifierTree tree, Void unused) {
                    if (field.equals(ASTHelpers.getSymbol(tree))) {
                        fix.replace(tree, qualifiedName);
                    }
                    return null;
                }
            }, null);
        }
        state.reportMatch(
                buildDescription(parameterPath.getLeaf())
                        .setMessage(String.format(
                                "Found the field '%s' with the same name as the parameter '%s' but with "
                                        + "different capitalization.",
                                fieldName, ((VariableTree) parameterPath.getLeaf()).getName()))
                        .addFix(fix.build()).build());
    }

    return Description.NO_MATCH;
}

From source file:google.registry.flows.FlowTestCase.java

/**
 * Helper to facilitate comparison of maps of GracePeriods to BillingEvents.  This takes a map of
 * GracePeriods to BillingEvents and returns a map of the same entries that ignores the keys
 * on the grace periods and the IDs on the billing events (by setting them all to the same dummy
 * values), since they will vary between instantiations even when the other data is the same.
 *//*from   w w  w  . j  a va2  s .  co  m*/
private ImmutableMap<GracePeriod, BillingEvent> canonicalizeGracePeriods(
        ImmutableMap<GracePeriod, ? extends BillingEvent> gracePeriods) {
    ImmutableMap.Builder<GracePeriod, BillingEvent> builder = new ImmutableMap.Builder<>();
    for (Map.Entry<GracePeriod, ? extends BillingEvent> entry : gracePeriods.entrySet()) {
        builder.put(GRACE_PERIOD_KEY_STRIPPER.apply(entry.getKey()),
                BILLING_EVENT_ID_STRIPPER.apply(entry.getValue()));
    }
    return builder.build();
}

From source file:com.facebook.buck.android.exopackage.ExopackageInstaller.java

private void installMetadata(ImmutableMap<Path, String> metadataToInstall) throws Exception {
    try (Closer closer = Closer.create()) {
        Map<Path, Path> filesToInstall = new HashMap<>();
        for (Map.Entry<Path, String> entry : metadataToInstall.entrySet()) {
            NamedTemporaryFile temp = closer.register(new NamedTemporaryFile("metadata", "tmp"));
            com.google.common.io.Files.write(entry.getValue().getBytes(Charsets.UTF_8), temp.get().toFile());
            filesToInstall.put(entry.getKey(), temp.get());
        }/*from ww  w  .  ja  v  a2  s  . co m*/
        installFiles("metadata", ImmutableMap.copyOf(filesToInstall));
    }
}