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:org.restlet.test.ext.apispark.conversion.swagger.v2_0.Swagger2TestCase.java

private void compareRwadefPathVariables(Resource savedResource, Resource translatedResource) {
    if (assertBothNull(savedResource.getPathVariables(), translatedResource.getPathVariables())) {
        return;/*from   w ww  .  j  a va2 s  .  c  o  m*/
    }

    ImmutableMap<String, PathVariable> savedPathVariables = Maps.uniqueIndex(savedResource.getPathVariables(),
            new Function<PathVariable, String>() {
                public String apply(PathVariable pathVariable) {
                    return pathVariable.getName();
                }
            });
    ImmutableMap<String, PathVariable> translatedPathVariables = Maps
            .uniqueIndex(translatedResource.getPathVariables(), new Function<PathVariable, String>() {
                public String apply(PathVariable pathVariable) {
                    return pathVariable.getName();
                }
            });

    assertEquals(savedPathVariables.size(), translatedPathVariables.size());
    for (String key1 : savedPathVariables.keySet()) {
        PathVariable savedPathVariable = savedPathVariables.get(key1);
        PathVariable translatedPathVariable = translatedPathVariables.get(key1);
        assertNotNull(savedPathVariable);
        assertNotNull(translatedPathVariable);

        assertEquals(savedPathVariable.getDescription(), translatedPathVariable.getDescription());
        assertEquals(savedPathVariable.getExample(), translatedPathVariable.getExample());
        assertEquals(savedPathVariable.getType(), translatedPathVariable.getType());
        assertEquals(savedPathVariable.isRequired(), translatedPathVariable.isRequired());
    }
}

From source file:org.restlet.test.ext.apispark.conversion.swagger.v2_0.Swagger2TestCase.java

private void compareRwadefQueryParameters(Operation savedOperation, Operation translatedOperation) {
    if (assertBothNull(savedOperation.getQueryParameters(), translatedOperation.getQueryParameters())) {
        return;//  w w w  . j  a  va 2 s .c om
    }

    ImmutableMap<String, QueryParameter> savedQueryParameters = Maps
            .uniqueIndex(savedOperation.getQueryParameters(), new Function<QueryParameter, String>() {
                public String apply(QueryParameter header) {
                    return header.getName();
                }
            });
    ImmutableMap<String, QueryParameter> translatedQueryParameters = Maps
            .uniqueIndex(translatedOperation.getQueryParameters(), new Function<QueryParameter, String>() {
                public String apply(QueryParameter header) {
                    return header.getName();
                }
            });

    assertEquals(savedQueryParameters.size(), translatedQueryParameters.size());
    for (String key : savedQueryParameters.keySet()) {
        QueryParameter savedQueryParameter = savedQueryParameters.get(key);
        QueryParameter translatedQueryParameter = translatedQueryParameters.get(key);
        assertNotNull(savedQueryParameter);
        assertNotNull(translatedQueryParameter);

        assertEquals(savedQueryParameter.getDefaultValue(), translatedQueryParameter.getDefaultValue());
        assertEquals(savedQueryParameter.getDescription(), translatedQueryParameter.getDescription());
        assertEquals(savedQueryParameter.getType(), translatedQueryParameter.getType());
        assertEquals(savedQueryParameter.getExample(), translatedQueryParameter.getExample());
        assertEquals(savedQueryParameter.getSeparator(), translatedQueryParameter.getSeparator());
        assertEquals(savedQueryParameter.isRequired(), translatedQueryParameter.isRequired());
        // TODO: not available in Swagger 2.0
        // assertEquals(savedQueryParameter.isAllowMultiple(), translatedQueryParameter.isAllowMultiple());
        compareStringLists(savedQueryParameter.getEnumeration(), translatedQueryParameter.getEnumeration());
    }
}

From source file:com.google.auto.value.processor.AutoAnnotationProcessor.java

private void processMethod(ExecutableElement method) {
    if (!method.getModifiers().contains(Modifier.STATIC)) {
        throw abortWithError("@AutoAnnotation method must be static", method);
    }//from w  ww . java 2s  .  c  o m

    TypeElement annotationElement = getAnnotationReturnType(method);
    TypeMirror annotationTypeMirror = annotationElement.asType();

    Set<Class<?>> wrapperTypesUsedInCollections = wrapperTypesUsedInCollections(method);

    ImmutableMap<String, ExecutableElement> memberMethods = getMemberMethods(annotationElement);
    Set<TypeMirror> memberTypes = getMemberTypes(memberMethods.values());
    Set<TypeMirror> referencedTypes = getReferencedTypes(annotationTypeMirror, method, memberTypes,
            wrapperTypesUsedInCollections);
    TypeElement methodClass = (TypeElement) method.getEnclosingElement();
    String pkg = TypeSimplifier.packageNameOf(methodClass);
    TypeSimplifier typeSimplifier = new TypeSimplifier(typeUtils, pkg, referencedTypes, annotationTypeMirror);

    AnnotationOutput annotationOutput = new AnnotationOutput(typeSimplifier);
    ImmutableMap<String, AnnotationValue> defaultValues = getDefaultValues(annotationElement);
    ImmutableMap<String, Member> members = getMembers(method, memberMethods, typeSimplifier, annotationOutput);
    ImmutableMap<String, Parameter> parameters = getParameters(annotationElement, method, members,
            typeSimplifier);
    validateParameters(annotationElement, method, members, parameters, defaultValues);

    String generatedClassName = generatedClassName(method);

    AutoAnnotationTemplateVars vars = new AutoAnnotationTemplateVars();
    vars.annotationFullName = annotationElement.toString();
    vars.annotationName = typeSimplifier.simplify(annotationElement.asType());
    vars.className = generatedClassName;
    vars.imports = typeSimplifier.typesToImport();
    vars.generated = typeSimplifier.simplify(getTypeMirror(Generated.class));
    vars.arrays = typeSimplifier.simplify(getTypeMirror(Arrays.class));
    vars.members = members;
    vars.params = parameters;
    vars.pkg = pkg;
    vars.wrapperTypesUsedInCollections = wrapperTypesUsedInCollections;
    vars.gwtCompatible = isGwtCompatible(annotationElement);
    ImmutableMap<String, Integer> invariableHashes = invariableHashes(members, parameters.keySet());
    vars.invariableHashSum = 0;
    for (int h : invariableHashes.values()) {
        vars.invariableHashSum += h;
    }
    vars.invariableHashes = invariableHashes.keySet();
    String text = vars.toText();
    text = Reformatter.fixup(text);
    String fullName = fullyQualifiedName(pkg, generatedClassName);
    writeSourceFile(fullName, text, methodClass);
}

From source file:com.android.build.gradle.tasks.PackageAndroidArtifact.java

@Override
protected void doIncrementalTaskAction(Map<File, FileStatus> changedInputs) throws IOException {
    checkNotNull(changedInputs, "changedInputs == null");

    Set<File> androidResources = new HashSet<>();
    File androidResourceFile = getResourceFile();
    if (androidResourceFile != null) {
        androidResources.add(androidResourceFile);
    }/*from w  w w.ja va2s  .c  o  m*/

    KnownFilesSaveData saveData = KnownFilesSaveData.make(getIncrementalFolder());

    ImmutableMap<RelativeFile, FileStatus> changedDexFiles = getChangedInputs(changedInputs, saveData,
            InputSet.DEX, getDexFolders(), cacheByPath);

    ImmutableMap<RelativeFile, FileStatus> changedJavaResources = getChangedInputs(changedInputs, saveData,
            InputSet.JAVA_RESOURCE, getJavaResourceFiles(), cacheByPath);

    ImmutableMap<RelativeFile, FileStatus> changedAssets = getChangedInputs(changedInputs, saveData,
            InputSet.ASSET, Collections.singleton(getAssets()), cacheByPath);

    ImmutableMap<RelativeFile, FileStatus> changedAndroidResources = getChangedInputs(changedInputs, saveData,
            InputSet.ANDROID_RESOURCE, androidResources, cacheByPath);

    ImmutableMap<RelativeFile, FileStatus> changedNLibs = getChangedInputs(changedInputs, saveData,
            InputSet.NATIVE_RESOURCE, getJniFolders(), cacheByPath);

    doTask(changedDexFiles, changedJavaResources, changedAssets, changedAndroidResources, changedNLibs);

    /*
     * Removed cached versions of deleted zip files because we no longer need to compute diffs.
     */
    changedInputs.keySet().stream().filter(f -> !f.exists()).forEach(f -> {
        try {
            cacheByPath.remove(f);
        } catch (IOException e) {
            throw new IOExceptionWrapper(e);
        }
    });

    /*
     * Update the save data keep files.
     */
    ImmutableMap<RelativeFile, FileStatus> allDex = IncrementalRelativeFileSets
            .fromZipsAndDirectories(getDexFolders());
    ImmutableMap<RelativeFile, FileStatus> allJavaResources = IncrementalRelativeFileSets
            .fromZipsAndDirectories(getJavaResourceFiles());
    ImmutableMap<RelativeFile, FileStatus> allAndroidResources = IncrementalRelativeFileSets
            .fromZipsAndDirectories(androidResources);
    ImmutableMap<RelativeFile, FileStatus> allJniResources = IncrementalRelativeFileSets
            .fromZipsAndDirectories(getJniFolders());

    saveData.setInputSet(allDex.keySet(), InputSet.DEX);
    saveData.setInputSet(allJavaResources.keySet(), InputSet.JAVA_RESOURCE);
    saveData.setInputSet(allAndroidResources.keySet(), InputSet.ANDROID_RESOURCE);
    saveData.setInputSet(allJniResources.keySet(), InputSet.NATIVE_RESOURCE);
    saveData.saveCurrentData();
}

From source file:org.restlet.test.ext.apispark.conversion.swagger.v2_0.Swagger2TestCase.java

private void compareRwadefRepresentations(Contract savedContract, Contract translatedContract) {
    if (assertBothNull(savedContract.getRepresentations(), translatedContract.getRepresentations())) {
        return;//ww w  .  ja  v  a  2  s.c om
    }

    ImmutableMap<String, Representation> savedRepresentations = Maps
            .uniqueIndex(savedContract.getRepresentations(), new Function<Representation, String>() {
                public String apply(Representation representation) {
                    return representation.getName();
                }
            });
    ImmutableMap<String, Representation> translatedRepresentations = Maps
            .uniqueIndex(translatedContract.getRepresentations(), new Function<Representation, String>() {
                public String apply(Representation representation) {
                    return representation.getName();
                }
            });

    assertEquals(savedRepresentations.size(), translatedRepresentations.size());
    for (String key : savedRepresentations.keySet()) {
        Representation savedRepresentation = savedRepresentations.get(key);
        Representation translatedRepresentation = translatedRepresentations.get(key);
        assertNotNull(savedRepresentation);
        assertNotNull(translatedRepresentation);
        assertEquals(savedRepresentation.getDescription(), translatedRepresentation.getDescription());
        assertEquals(savedRepresentation.getExtendedType(), translatedRepresentation.getExtendedType());

        compareStringLists(savedRepresentation.getSections(), translatedRepresentation.getSections());
        compareRwadefProperties(savedRepresentation.getProperties(), translatedRepresentation.getProperties());
    }
}

From source file:org.jclouds.s3.filters.Aws4SignerForChunkedUpload.java

protected HttpRequest sign(HttpRequest request) throws HttpException {
    checkNotNull(request, "request is not ready to sign");
    checkNotNull(request.getEndpoint(), "request is not ready to sign, request.endpoint not present.");

    Payload payload = request.getPayload();
    // chunked upload required content-length.
    Long contentLength = payload.getContentMetadata().getContentLength();

    // check contentLength not null
    checkNotNull(contentLength, "request is not ready to sign, payload contentLength not present.");

    // get host from request endpoint.
    String host = request.getEndpoint().getHost();

    Date date = timestampProvider.get();
    String timestamp = timestampFormat.format(date);
    String datestamp = dateFormat.format(date);

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

    HttpRequest.Builder<?> requestBuilder = request.toBuilder() //
            .removeHeader(AUTHORIZATION) // remove Authorization
            .removeHeader(DATE) // remove Date
            .removeHeader(CONTENT_LENGTH); // remove Content-Length

    ImmutableMap.Builder<String, String> signedHeadersBuilder = ImmutableSortedMap
            .<String, String>naturalOrder();

    // content-encoding
    String contentEncoding = CONTENT_ENCODING_HEADER_AWS_CHUNKED;
    String originalContentEncoding = payload.getContentMetadata().getContentEncoding();
    if (originalContentEncoding != null) {
        contentEncoding += "," + originalContentEncoding;
    }//w w w.j  a  va2 s  . c o m
    requestBuilder.replaceHeader(HttpHeaders.CONTENT_ENCODING, contentEncoding);
    signedHeadersBuilder.put(HttpHeaders.CONTENT_ENCODING.toLowerCase(), contentEncoding);

    // x-amz-decoded-content-length
    requestBuilder.replaceHeader(AMZ_DECODED_CONTENT_LENGTH_HEADER, contentLength.toString());
    signedHeadersBuilder.put(AMZ_DECODED_CONTENT_LENGTH_HEADER.toLowerCase(), contentLength.toString());

    // how big is the overall request stream going to be once we add the signature
    // 'headers' to each chunk?
    long totalLength = calculateChunkedContentLength(contentLength, userDataBlockSize);
    requestBuilder.replaceHeader(CONTENT_LENGTH, Long.toString(totalLength));
    signedHeadersBuilder.put(CONTENT_LENGTH.toLowerCase(), Long.toString(totalLength));

    // Content MD5
    String contentMD5 = request.getFirstHeaderOrNull(CONTENT_MD5);
    if (payload != null) {
        HashCode md5 = payload.getContentMetadata().getContentMD5AsHashCode();
        if (md5 != null) {
            contentMD5 = BaseEncoding.base64().encode(md5.asBytes());
        }
    }
    if (contentMD5 != null) {
        requestBuilder.replaceHeader(CONTENT_MD5, contentMD5);
        signedHeadersBuilder.put(CONTENT_MD5.toLowerCase(), contentMD5);
    }

    // Content Type
    // content-type is not a required signing param. However, examples use this, so we include it to ease testing.
    String contentType = getContentType(request);
    if (!Strings.isNullOrEmpty(contentType)) {
        requestBuilder.replaceHeader(HttpHeaders.CONTENT_TYPE, contentType);
        signedHeadersBuilder.put(HttpHeaders.CONTENT_TYPE.toLowerCase(), contentType);
    } else {
        requestBuilder.removeHeader(HttpHeaders.CONTENT_TYPE);
    }

    // host
    requestBuilder.replaceHeader(HttpHeaders.HOST, host);
    signedHeadersBuilder.put(HttpHeaders.HOST.toLowerCase(), host);

    // user-agent, not a required signing param
    if (request.getHeaders().containsKey(HttpHeaders.USER_AGENT)) {
        signedHeadersBuilder.put(HttpHeaders.USER_AGENT.toLowerCase(),
                request.getFirstHeaderOrNull(HttpHeaders.USER_AGENT));
    }

    // all x-amz-* headers
    appendAmzHeaders(request, signedHeadersBuilder);

    // x-amz-security-token
    Credentials credentials = creds.get();
    if (credentials instanceof SessionCredentials) {
        String token = SessionCredentials.class.cast(credentials).getSessionToken();
        requestBuilder.replaceHeader(AMZ_SECURITY_TOKEN_HEADER, token);
        signedHeadersBuilder.put(AMZ_SECURITY_TOKEN_HEADER.toLowerCase(), token);
    }

    // x-amz-content-sha256
    String contentSha256 = getPayloadHash();
    requestBuilder.replaceHeader(AMZ_CONTENT_SHA256_HEADER, contentSha256);
    signedHeadersBuilder.put(AMZ_CONTENT_SHA256_HEADER.toLowerCase(), contentSha256);

    // put x-amz-date
    requestBuilder.replaceHeader(AMZ_DATE_HEADER, timestamp);
    signedHeadersBuilder.put(AMZ_DATE_HEADER.toLowerCase(), timestamp);

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

    String stringToSign = createStringToSign(request.getMethod(), request.getEndpoint(), signedHeaders,
            timestamp, credentialScope, contentSha256);
    signatureWire.getWireLog().debug("<< " + stringToSign);

    byte[] signatureKey = signatureKey(credentials.credential, datestamp, region, service);

    // init hmacSHA256 processor for seed signature and chunked block signature
    ByteProcessor<byte[]> hmacSHA256;
    try {
        hmacSHA256 = hmacSHA256(crypto, signatureKey);
    } catch (InvalidKeyException e) {
        throw new ChunkedUploadException("invalid key", e);
    }

    // Calculating the Seed Signature
    String signature;
    try {
        signature = hex(readBytes(toInputStream(stringToSign), hmacSHA256));
    } catch (IOException e) {
        throw new ChunkedUploadException("hmac sha256 seed signature error", e);
    }

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

    // replace request payload with chunked upload payload
    ChunkedUploadPayload chunkedPayload = new ChunkedUploadPayload(payload, userDataBlockSize, timestamp,
            credentialScope, hmacSHA256, signature);
    chunkedPayload.getContentMetadata().setContentEncoding(null);

    return requestBuilder.replaceHeader(HttpHeaders.AUTHORIZATION, authorization.toString())
            .payload(chunkedPayload).build();

}

From source file:com.facebook.buck.android.AndroidNativeLibsPackageableGraphEnhancer.java

public AndroidNativeLibsGraphEnhancementResult enhance(AndroidPackageableCollection packageableCollection)
        throws NoSuchBuildTargetException {
    @SuppressWarnings("PMD.PrematureDeclaration")
    AndroidNativeLibsGraphEnhancementResult.Builder resultBuilder = AndroidNativeLibsGraphEnhancementResult
            .builder();/* w ww . j  a  va2 s  . c o  m*/

    ImmutableMultimap<APKModule, NativeLinkable> nativeLinkables = packageableCollection.getNativeLinkables();
    ImmutableMultimap<APKModule, NativeLinkable> nativeLinkablesAssets = packageableCollection
            .getNativeLinkablesAssets();

    if (nativeLibraryMergeMap.isPresent() && !nativeLibraryMergeMap.get().isEmpty()) {
        NativeLibraryMergeEnhancementResult enhancement = NativeLibraryMergeEnhancer.enhance(cxxBuckConfig,
                ruleResolver, pathResolver, ruleFinder, buildRuleParams, nativePlatforms,
                nativeLibraryMergeMap.get(), nativeLibraryMergeGlue, nativeLinkables, nativeLinkablesAssets);
        nativeLinkables = enhancement.getMergedLinkables();
        nativeLinkablesAssets = enhancement.getMergedLinkablesAssets();
        resultBuilder.setSonameMergeMap(enhancement.getSonameMapping());
    }

    // Iterate over all the {@link AndroidNativeLinkable}s from the collector and grab the shared
    // libraries for all the {@link TargetCpuType}s that we care about.  We deposit them into a map
    // of CPU type and SONAME to the shared library path, which the {@link CopyNativeLibraries}
    // rule will use to compose the destination name.
    ImmutableMap.Builder<APKModule, CopyNativeLibraries> moduleMappedCopyNativeLibriesBuilder = ImmutableMap
            .builder();

    boolean hasCopyNativeLibraries = false;
    List<NdkCxxPlatform> platformsWithNativeLibs = new ArrayList<>();
    List<NdkCxxPlatform> platformsWithNativeLibsAssets = new ArrayList<>();

    // Make sure we process the root module last so that we know if any of the module contain
    // libraries that depend on a non-system runtime and add it to the root module if needed.
    ImmutableSet<APKModule> apkModules = FluentIterable.from(apkModuleGraph.getAPKModules())
            .filter(input -> !input.isRootModule()).append(apkModuleGraph.getRootAPKModule()).toSet();

    for (APKModule module : apkModules) {
        ImmutableMap.Builder<Pair<NdkCxxPlatforms.TargetCpuType, String>, SourcePath> nativeLinkableLibsBuilder = ImmutableMap
                .builder();

        ImmutableMap.Builder<Pair<NdkCxxPlatforms.TargetCpuType, String>, SourcePath> nativeLinkableLibsAssetsBuilder = ImmutableMap
                .builder();

        // TODO(andrewjcg): We currently treat an empty set of filters to mean to allow everything.
        // We should fix this by assigning a default list of CPU filters in the descriptions, but
        // until we do, if the set of filters is empty, just build for all available platforms.
        ImmutableSet<NdkCxxPlatforms.TargetCpuType> filters = cpuFilters.isEmpty() ? nativePlatforms.keySet()
                : cpuFilters;
        for (NdkCxxPlatforms.TargetCpuType targetCpuType : filters) {
            NdkCxxPlatform platform = Preconditions.checkNotNull(nativePlatforms.get(targetCpuType),
                    "Unknown platform type " + targetCpuType.toString());

            // Populate nativeLinkableLibs and nativeLinkableLibsAssets with the appropriate entries.
            if (populateMapWithLinkables(nativeLinkables.get(module), nativeLinkableLibsBuilder, targetCpuType,
                    platform) && !platformsWithNativeLibs.contains(platform)) {
                platformsWithNativeLibs.add(platform);
            }
            if (populateMapWithLinkables(nativeLinkablesAssets.get(module), nativeLinkableLibsAssetsBuilder,
                    targetCpuType, platform) && !platformsWithNativeLibsAssets.contains(platform)) {
                platformsWithNativeLibsAssets.add(platform);
            }

            if (module.isRootModule()) {
                // If we're using a C/C++ runtime other than the system one, add it to the APK.
                NdkCxxPlatforms.CxxRuntime cxxRuntime = platform.getCxxRuntime();
                if ((platformsWithNativeLibs.contains(platform)
                        || platformsWithNativeLibsAssets.contains(platform))
                        && !cxxRuntime.equals(NdkCxxPlatforms.CxxRuntime.SYSTEM)) {
                    nativeLinkableLibsBuilder.put(new Pair<>(targetCpuType, cxxRuntime.getSoname()),
                            new PathSourcePath(buildRuleParams.getProjectFilesystem(),
                                    platform.getCxxSharedRuntimePath()));
                }
            }
        }

        ImmutableMap<Pair<NdkCxxPlatforms.TargetCpuType, String>, SourcePath> nativeLinkableLibs = nativeLinkableLibsBuilder
                .build();

        ImmutableMap<Pair<NdkCxxPlatforms.TargetCpuType, String>, SourcePath> nativeLinkableLibsAssets = nativeLinkableLibsAssetsBuilder
                .build();

        if (packageableCollection.getNativeLibsDirectories().get(module).isEmpty()
                && nativeLinkableLibs.isEmpty() && nativeLinkableLibsAssets.isEmpty()) {
            continue;
        }

        if (relinkerMode == RelinkerMode.ENABLED
                && (!nativeLinkableLibs.isEmpty() || !nativeLinkableLibsAssets.isEmpty())) {
            NativeRelinker relinker = new NativeRelinker(
                    buildRuleParams
                            .copyWithExtraDeps(Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>naturalOrder()
                                    .addAll(ruleFinder.filterBuildRuleInputs(nativeLinkableLibs.values()))
                                    .addAll(ruleFinder.filterBuildRuleInputs(nativeLinkableLibsAssets.values()))
                                    .build())),
                    pathResolver, ruleFinder, cxxBuckConfig, nativePlatforms, nativeLinkableLibs,
                    nativeLinkableLibsAssets);

            nativeLinkableLibs = relinker.getRelinkedLibs();
            nativeLinkableLibsAssets = relinker.getRelinkedLibsAssets();
            for (BuildRule rule : relinker.getRules()) {
                ruleResolver.addToIndex(rule);
            }
        }

        ImmutableMap<StripLinkable, StrippedObjectDescription> strippedLibsMap = generateStripRules(
                buildRuleParams, ruleFinder, ruleResolver, originalBuildTarget, nativePlatforms,
                nativeLinkableLibs);
        ImmutableMap<StripLinkable, StrippedObjectDescription> strippedLibsAssetsMap = generateStripRules(
                buildRuleParams, ruleFinder, ruleResolver, originalBuildTarget, nativePlatforms,
                nativeLinkableLibsAssets);

        BuildTarget targetForCopyNativeLibraries = BuildTarget.builder(originalBuildTarget)
                .addFlavors(ImmutableFlavor.of(COPY_NATIVE_LIBS + "_" + module.getName())).build();
        ImmutableSortedSet<BuildRule> nativeLibsRules = BuildRules.toBuildRulesFor(originalBuildTarget,
                ruleResolver, packageableCollection.getNativeLibsTargets().get(module));
        BuildRuleParams paramsForCopyNativeLibraries = buildRuleParams.copyWithChanges(
                targetForCopyNativeLibraries,
                Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>naturalOrder().addAll(nativeLibsRules)
                        .addAll(ruleFinder.filterBuildRuleInputs(
                                packageableCollection.getNativeLibsDirectories().get(module)))
                        .addAll(strippedLibsMap.keySet()).addAll(strippedLibsAssetsMap.keySet()).build()),
                /* extraDeps */ Suppliers.ofInstance(ImmutableSortedSet.of()));
        moduleMappedCopyNativeLibriesBuilder.put(module,
                new CopyNativeLibraries(paramsForCopyNativeLibraries,
                        ImmutableSet.copyOf(packageableCollection.getNativeLibsDirectories().get(module)),
                        ImmutableSet.copyOf(strippedLibsMap.values()),
                        ImmutableSet.copyOf(strippedLibsAssetsMap.values()), cpuFilters, module.getName()));
        hasCopyNativeLibraries = true;
    }
    return resultBuilder.setCopyNativeLibraries(
            hasCopyNativeLibraries ? Optional.of(moduleMappedCopyNativeLibriesBuilder.build())
                    : Optional.empty())
            .build();

}

From source file:dagger.internal.codegen.ComponentHierarchyValidator.java

private void validateSubcomponentMethods(ValidationReport.Builder<?> report,
        ComponentDescriptor componentDescriptor,
        ImmutableMap<TypeElement, TypeElement> existingModuleToOwners) {
    for (Map.Entry<ComponentMethodDescriptor, ComponentDescriptor> subcomponentEntry : componentDescriptor
            .subcomponentsByFactoryMethod().entrySet()) {
        ComponentMethodDescriptor subcomponentMethodDescriptor = subcomponentEntry.getKey();
        ComponentDescriptor subcomponentDescriptor = subcomponentEntry.getValue();
        // validate the way that we create subcomponents
        for (VariableElement factoryMethodParameter : subcomponentMethodDescriptor.methodElement()
                .getParameters()) {/* www .jav a  2 s.com*/
            TypeElement moduleType = MoreTypes.asTypeElement(factoryMethodParameter.asType());
            TypeElement originatingComponent = existingModuleToOwners.get(moduleType);
            if (originatingComponent != null) {
                /* Factory method tries to pass a module that is already present in the parent.
                 * This is an error. */
                report.addError(String.format(
                        "%s is present in %s. A subcomponent cannot use an instance of a "
                                + "module that differs from its parent.",
                        moduleType.getSimpleName(), originatingComponent.getQualifiedName()),
                        factoryMethodParameter);
            }
        }
        validateSubcomponentMethods(report, subcomponentDescriptor,
                new ImmutableMap.Builder<TypeElement, TypeElement>().putAll(existingModuleToOwners)
                        .putAll(Maps.toMap(
                                Sets.difference(subcomponentDescriptor.transitiveModuleTypes(),
                                        existingModuleToOwners.keySet()),
                                constant(subcomponentDescriptor.componentDefinitionType())))
                        .build());
    }
}

From source file:org.locationtech.geogig.storage.postgresql.PGObjectStore.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override/*from   w ww. ja v  a2 s . c  o m*/
public <T extends RevObject> Iterator<T> getAll(Iterable<ObjectId> ids, BulkOpListener listener,
        Class<T> type) {

    checkNotNull(ids, "ids is null");
    checkNotNull(listener, "listener is null");
    checkNotNull(type, "type is null");
    checkState(isOpen(), "Database is closed");
    config.checkRepositoryExists();

    final Set<ObjectId> queryIds = ids instanceof Set ? (Set<ObjectId>) ids : Sets.newHashSet(ids);

    ImmutableMap<ObjectId, byte[]> cached = byteCache.getAllPresent(queryIds);

    Iterator<T> hits = Collections.emptyIterator();
    Iterator<T> stream = Collections.emptyIterator();

    if (!cached.isEmpty()) {

        Map<ObjectId, T> cachedObjects = Maps.transformEntries(cached, (id, bytes) -> {
            RevObject o = encoder.decode(id, bytes);
            if (type.isAssignableFrom(o.getClass())) {
                listener.found(id, Integer.valueOf(bytes.length));
                return type.cast(o);
            }
            listener.notFound(id);
            return null;
        });

        hits = Iterators.filter(cachedObjects.values().iterator(), Predicates.notNull());
    }
    if (queryIds.size() > cached.size()) {
        Set<ObjectId> misses = Sets.difference(queryIds, cached.keySet());
        stream = new GetAllIterator(dataSource, misses.iterator(), type, listener, this);
    }

    return Iterators.concat(hits, stream);
}

From source file:com.android.build.gradle.tasks.PackageAndroidArtifact.java

@Override
protected void doFullTaskAction() throws IOException {
    /*//www .j  a  v  a  2s  .c o m
     * Clear the cache to make sure we have do not do an incremental build.
     */
    cacheByPath.clear();

    /*
     * Also clear the intermediate build directory. We don't know if anything is in there and
     * since this is a full build, we don't want to get any interference from previous state.
     */
    FileUtils.deleteDirectoryContents(getIncrementalFolder());

    Set<File> androidResources = new HashSet<>();
    File androidResourceFile = getResourceFile();
    if (androidResourceFile != null) {
        androidResources.add(androidResourceFile);
    }

    /*
     * Additionally, make sure we have no previous package, if it exists.
     */
    getOutputFile().delete();

    ImmutableMap<RelativeFile, FileStatus> updatedDex = IncrementalRelativeFileSets
            .fromZipsAndDirectories(getDexFolders());
    ImmutableMap<RelativeFile, FileStatus> updatedJavaResources = IncrementalRelativeFileSets
            .fromZipsAndDirectories(getJavaResourceFiles());
    ImmutableMap<RelativeFile, FileStatus> updatedAssets = IncrementalRelativeFileSets
            .fromZipsAndDirectories(Collections.singleton(getAssets()));
    ImmutableMap<RelativeFile, FileStatus> updatedAndroidResources = IncrementalRelativeFileSets
            .fromZipsAndDirectories(androidResources);
    ImmutableMap<RelativeFile, FileStatus> updatedJniResources = IncrementalRelativeFileSets
            .fromZipsAndDirectories(getJniFolders());

    doTask(updatedDex, updatedJavaResources, updatedAssets, updatedAndroidResources, updatedJniResources);

    /*
     * Update the known files.
     */
    KnownFilesSaveData saveData = KnownFilesSaveData.make(getIncrementalFolder());
    saveData.setInputSet(updatedDex.keySet(), InputSet.DEX);
    saveData.setInputSet(updatedJavaResources.keySet(), InputSet.JAVA_RESOURCE);
    saveData.setInputSet(updatedAssets.keySet(), InputSet.ASSET);
    saveData.setInputSet(updatedAndroidResources.keySet(), InputSet.ANDROID_RESOURCE);
    saveData.setInputSet(updatedJniResources.keySet(), InputSet.NATIVE_RESOURCE);
    saveData.saveCurrentData();
}