Example usage for com.google.common.collect ImmutableSet isEmpty

List of usage examples for com.google.common.collect ImmutableSet isEmpty

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableSet isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this set contains no elements.

Usage

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

/**
 * Adds an error if an {@link IntoMap @IntoMap} or {@code MAP} method doesn't have exactly one
 * {@link MapKey @MapKey} annotation, or if a method that is neither {@link IntoMap @IntoMap} nor
 * {@code MAP} has any.//from   w w w . j a v a2  s.c o  m
 */
protected void checkMapKeys(ValidationReport.Builder<ExecutableElement> builder) {
    if (!allowsMultibindings.allowsMultibindings()) {
        return;
    }
    ImmutableSet<? extends AnnotationMirror> mapKeys = getMapKeys(builder.getSubject());
    if (ContributionType.fromBindingMethod(builder.getSubject()).equals(ContributionType.MAP)) {
        switch (mapKeys.size()) {
        case 0:
            builder.addError(formatErrorMessage(BINDING_METHOD_WITH_NO_MAP_KEY));
            break;
        case 1:
            break;
        default:
            builder.addError(formatErrorMessage(BINDING_METHOD_WITH_MULTIPLE_MAP_KEYS));
            break;
        }
    } else if (!mapKeys.isEmpty()) {
        builder.addError(formatErrorMessage(BINDING_METHOD_NOT_MAP_HAS_MAP_KEY));
    }
}

From source file:com.google.javascript.jscomp.newtypes.JSTypeCreatorFromJSDoc.java

private void handleInterfaceAnnotation(JSDocInfo jsdoc, String functionName, Node funNode,
        RawNominalType constructorType, ImmutableSet<NominalType> implementedIntfs,
        ImmutableList<String> typeParameters, DeclaredTypeRegistry registry, FunctionTypeBuilder builder) {
    if (!implementedIntfs.isEmpty()) {
        warnings.add(JSError.make(funNode, CONFLICTING_IMPLEMENTED_TYPE, functionName));
    }//w ww  .  j  a  v  a 2 s .  c om
    boolean noCycles = constructorType.addInterfaces(getExtendedInterfaces(jsdoc, registry, typeParameters));
    if (!noCycles) {
        warnings.add(JSError.make(funNode, INHERITANCE_CYCLE, constructorType.toString()));
    }
    builder.addNominalType(constructorType.getAsNominalType());
}

From source file:org.androidtransfuse.analysis.ManualSuperGenerator.java

@Override
public void schedule(final ComponentBuilder builder, final ComponentDescriptor descriptor) {

    builder.add(registrationMethod, GenerationPhase.POSTINJECTION, new ComponentMethodGenerator() {
        @Override//w  w  w.j a  va2s. c  o  m
        public void generate(MethodDescriptor methodDescriptor, JBlock block) {
            ImmutableSet<ManualSuperAspect.Method> methods = FluentIterable
                    .from(builder.getExpressionMap().keySet())
                    .transformAndConcat(new Function<InjectionNode, Set<ManualSuperAspect.Method>>() {
                        @Override
                        public Set<ManualSuperAspect.Method> apply(InjectionNode injectionNode) {
                            if (injectionNode.containsAspect(ManualSuperAspect.class)) {
                                ManualSuperAspect aspect = injectionNode.getAspect(ManualSuperAspect.class);
                                return aspect.getMethods();
                            }
                            return ImmutableSet.of();
                        }
                    }).toSet();

            try {
                if (!methods.isEmpty()) {
                    JDefinedClass superClass = builder.getDefinedClass()._class(JMod.PUBLIC,
                            SUPER_CALLER_CLASS_NAME);

                    builder.getDefinedClass().field(JMod.PUBLIC, superClass, SUPER_NAME,
                            JExpr._new(superClass));

                    for (ManualSuperAspect.Method method : methods) {
                        ASTMethod astMethod = astElementFactory.findMethod(descriptor.getType(),
                                method.getName(),
                                method.getParameters().toArray(new ASTType[method.getParameters().size()]));

                        if (astMethod != null) {
                            writeSuperCallingMethod(builder.getDefinedClass(), superClass, astMethod);
                        }
                        //todo: validation?
                    }
                }
            } catch (JClassAlreadyExistsException e) {
                throw new TransfuseAnalysisException("SUPER Class already exists", e);
            }
        }

        private void writeSuperCallingMethod(JDefinedClass target, JDefinedClass superClass,
                ASTMethod astMethod) {
            JMethod superCallingMethod = superClass.method(JMod.PUBLIC,
                    generationUtil.ref(astMethod.getReturnType()), astMethod.getName());

            JBlock body = superCallingMethod.body();
            JInvocation invocation = target.staticRef("super").invoke(astMethod.getName());
            if (astMethod.getReturnType() == ASTVoidType.VOID) {
                body.add(invocation);
            } else {
                body._return(invocation);
            }

            for (ASTParameter parameter : astMethod.getParameters()) {
                JVar param = superCallingMethod.param(generationUtil.ref(parameter.getASTType()),
                        namer.generateName(parameter.getASTType()));
                invocation.arg(param);
            }
        }
    });

}

From source file:com.google.devtools.build.lib.flags.InvocationPolicyEnforcer.java

/**
 * Applies this OptionsPolicyEnforcer's policy to the given OptionsParser.
 *
 * @param parser The OptionsParser to enforce policy on.
 * @param command The current blaze command, for flag policies that apply to only specific
 *     commands. Such policies will be enforced only if they contain this command or a command
 *     they inherit from/*from w ww  . j  ava 2 s . c om*/
 * @throws OptionsParsingException if any flag policy is invalid.
 */
public void enforce(OptionsParser parser, @Nullable String command) throws OptionsParsingException {
    if (invocationPolicy == null || invocationPolicy.getFlagPoliciesCount() == 0) {
        return;
    }

    ImmutableSet<String> commandAndParentCommands = command == null ? ImmutableSet.<String>of()
            : CommandNameCache.CommandNameCacheInstance.INSTANCE.get(command);
    for (FlagPolicy flagPolicy : invocationPolicy.getFlagPoliciesList()) {
        String flagName = flagPolicy.getFlagName();

        // Skip the flag policy if it doesn't apply to this command. If the commands list is empty,
        // then the policy applies to all commands.
        if (!flagPolicy.getCommandsList().isEmpty() && !commandAndParentCommands.isEmpty()) {
            boolean flagApplies = false;
            for (String policyCommand : flagPolicy.getCommandsList()) {
                if (commandAndParentCommands.contains(policyCommand)) {
                    flagApplies = true;
                    break;
                }
            }
            if (!flagApplies) {
                continue;
            }
        }

        OptionValueDescription valueDescription;
        try {
            valueDescription = parser.getOptionValueDescription(flagName);
        } catch (IllegalArgumentException e) {
            // This flag doesn't exist. We are deliberately lenient if the flag policy has a flag
            // we don't know about. This is for better future proofing so that as new flags are added,
            // new policies can use the new flags without worrying about older versions of Bazel.
            log.info(String.format("Flag '%s' specified by invocation policy does not exist", flagName));
            continue;
        }

        OptionDescription optionDescription = parser.getOptionDescription(flagName);
        // getOptionDescription() will return null if the option does not exist, however
        // getOptionValueDescription() above would have thrown an IllegalArgumentException if that
        // were the case.
        Verify.verifyNotNull(optionDescription);

        switch (flagPolicy.getOperationCase()) {
        case SET_VALUE:
            applySetValueOperation(parser, flagPolicy, flagName, valueDescription, optionDescription);
            break;

        case USE_DEFAULT:
            applyUseDefaultOperation(parser, "UseDefault", flagName);
            break;

        case ALLOW_VALUES:
            AllowValues allowValues = flagPolicy.getAllowValues();
            FilterValueOperation.ALLOW_VALUE_OPERATION.apply(parser, allowValues.getAllowedValuesList(),
                    allowValues.hasNewValue() ? allowValues.getNewValue() : null, allowValues.hasUseDefault(),
                    flagName, valueDescription, optionDescription);
            break;

        case DISALLOW_VALUES:
            DisallowValues disallowValues = flagPolicy.getDisallowValues();
            FilterValueOperation.DISALLOW_VALUE_OPERATION.apply(parser,
                    disallowValues.getDisallowedValuesList(),
                    disallowValues.hasNewValue() ? disallowValues.getNewValue() : null,
                    disallowValues.hasUseDefault(), flagName, valueDescription, optionDescription);
            break;

        case OPERATION_NOT_SET:
            throw new OptionsParsingException(
                    String.format("Flag policy for flag '%s' does not " + "have an operation", flagName));

        default:
            log.warning(String.format("Unknown operation '%s' from invocation policy for flag '%s'",
                    flagPolicy.getOperationCase(), flagName));
            break;
        }
    }
}

From source file:dagger2.internal.codegen.BindingGraphValidator.java

/**
 * Validates that the set of bindings resolved is consistent with the type of the binding, and
 * returns true if the bindings are valid.
 *//*from   w  w  w. j  a  v  a  2  s.  c  o m*/
private boolean validateResolvedBinding(Deque<ResolvedRequest> path, ResolvedBindings resolvedBinding,
        Builder<BindingGraph> reportBuilder) {
    if (resolvedBinding.bindings().isEmpty()) {
        reportMissingBinding(path, reportBuilder);
        return false;
    }

    ImmutableSet.Builder<ProvisionBinding> provisionBindingsBuilder = ImmutableSet.builder();
    ImmutableSet.Builder<ProductionBinding> productionBindingsBuilder = ImmutableSet.builder();
    ImmutableSet.Builder<MembersInjectionBinding> membersInjectionBindingsBuilder = ImmutableSet.builder();
    for (Binding binding : resolvedBinding.bindings()) {
        if (binding instanceof ProvisionBinding) {
            provisionBindingsBuilder.add((ProvisionBinding) binding);
        }
        if (binding instanceof ProductionBinding) {
            productionBindingsBuilder.add((ProductionBinding) binding);
        }
        if (binding instanceof MembersInjectionBinding) {
            membersInjectionBindingsBuilder.add((MembersInjectionBinding) binding);
        }
    }
    ImmutableSet<ProvisionBinding> provisionBindings = provisionBindingsBuilder.build();
    ImmutableSet<ProductionBinding> productionBindings = productionBindingsBuilder.build();
    ImmutableSet<MembersInjectionBinding> membersInjectionBindings = membersInjectionBindingsBuilder.build();

    switch (resolvedBinding.bindingKey().kind()) {
    case CONTRIBUTION:
        if (!membersInjectionBindings.isEmpty()) {
            throw new IllegalArgumentException(
                    "contribution binding keys should never have members injection bindings");
        }
        Set<ContributionBinding> combined = Sets.union(provisionBindings, productionBindings);
        if (!validateNullability(path.peek().request(), combined, reportBuilder)) {
            return false;
        }
        if (!productionBindings.isEmpty() && doesPathRequireProvisionOnly(path)) {
            reportProviderMayNotDependOnProducer(path, reportBuilder);
            return false;
        }
        if ((provisionBindings.size() + productionBindings.size()) <= 1) {
            return true;
        }
        ImmutableListMultimap<BindingType, ContributionBinding> bindingsByType = ContributionBinding
                .bindingTypesFor(Iterables.<ContributionBinding>concat(provisionBindings, productionBindings));
        if (bindingsByType.keySet().size() > 1) {
            reportMultipleBindingTypes(path, reportBuilder);
            return false;
        } else if (getOnlyElement(bindingsByType.keySet()).equals(BindingType.UNIQUE)) {
            reportDuplicateBindings(path, reportBuilder);
            return false;
        }
        break;
    case MEMBERS_INJECTION:
        if (!provisionBindings.isEmpty() || !productionBindings.isEmpty()) {
            throw new IllegalArgumentException(
                    "members injection binding keys should never have contribution bindings");
        }
        if (membersInjectionBindings.size() > 1) {
            reportDuplicateBindings(path, reportBuilder);
            return false;
        }
        if (membersInjectionBindings.size() == 1) {
            MembersInjectionBinding binding = getOnlyElement(membersInjectionBindings);
            if (!validateMembersInjectionBinding(binding, path, reportBuilder)) {
                return false;
            }
        }
        break;
    default:
        throw new AssertionError();
    }
    return true;
}

From source file:google.registry.rdap.RdapJsonFormatter.java

/**
 * Creates a JSON object for a {@link HostResource}.
 *
 * @param hostResource the host resource object from which the JSON object should be created
 * @param isTopLevel if true, the top-level boilerplate will be added
 * @param linkBase the URL base to be used when creating links
 * @param whoisServer the fully-qualified domain name of the WHOIS server to be listed in the
 *        port43 field; if null, port43 is not added to the object
 * @param now the as-date/*  ww w .  j  a v a  2  s  .  com*/
 * @param outputDataType whether to generate full or summary data
 */
ImmutableMap<String, Object> makeRdapJsonForHost(HostResource hostResource, boolean isTopLevel,
        @Nullable String linkBase, @Nullable String whoisServer, DateTime now, OutputDataType outputDataType) {
    ImmutableMap.Builder<String, Object> jsonBuilder = new ImmutableMap.Builder<>();
    jsonBuilder.put("objectClassName", "nameserver");
    jsonBuilder.put("handle", hostResource.getRepoId());
    jsonBuilder.put("ldhName", hostResource.getFullyQualifiedHostName());
    // Only include the unicodeName field if there are unicode characters.
    if (hasUnicodeComponents(hostResource.getFullyQualifiedHostName())) {
        jsonBuilder.put("unicodeName", Idn.toUnicode(hostResource.getFullyQualifiedHostName()));
    }
    jsonBuilder.put("status", makeStatusValueList(hostResource.getStatusValues()));
    jsonBuilder.put("links",
            ImmutableList.of(makeLink("nameserver", hostResource.getFullyQualifiedHostName(), linkBase)));
    List<ImmutableMap<String, Object>> remarks;
    // If we are outputting all data (not just summary data), also add events taken from the history
    // entries. If we are outputting summary data, instead add a remark indicating that fact.
    if (outputDataType == OutputDataType.SUMMARY) {
        remarks = ImmutableList.of(RdapIcannStandardInformation.SUMMARY_DATA_REMARK);
    } else {
        remarks = ImmutableList.of();
        ImmutableList<Object> events = makeEvents(hostResource, now);
        if (!events.isEmpty()) {
            jsonBuilder.put("events", events);
        }
    }
    ImmutableSet<InetAddress> inetAddresses = hostResource.getInetAddresses();
    if (!inetAddresses.isEmpty()) {
        ImmutableList.Builder<String> v4AddressesBuilder = new ImmutableList.Builder<>();
        ImmutableList.Builder<String> v6AddressesBuilder = new ImmutableList.Builder<>();
        for (InetAddress inetAddress : inetAddresses) {
            if (inetAddress instanceof Inet4Address) {
                v4AddressesBuilder.add(InetAddresses.toAddrString(inetAddress));
            } else if (inetAddress instanceof Inet6Address) {
                v6AddressesBuilder.add(InetAddresses.toAddrString(inetAddress));
            }
        }
        ImmutableMap.Builder<String, ImmutableList<String>> ipAddressesBuilder = new ImmutableMap.Builder<>();
        ImmutableList<String> v4Addresses = v4AddressesBuilder.build();
        if (!v4Addresses.isEmpty()) {
            ipAddressesBuilder.put("v4", Ordering.natural().immutableSortedCopy(v4Addresses));
        }
        ImmutableList<String> v6Addresses = v6AddressesBuilder.build();
        if (!v6Addresses.isEmpty()) {
            ipAddressesBuilder.put("v6", Ordering.natural().immutableSortedCopy(v6Addresses));
        }
        ImmutableMap<String, ImmutableList<String>> ipAddresses = ipAddressesBuilder.build();
        if (!ipAddresses.isEmpty()) {
            jsonBuilder.put("ipAddresses", ipAddressesBuilder.build());
        }
    }
    if (whoisServer != null) {
        jsonBuilder.put("port43", whoisServer);
    }
    if (isTopLevel) {
        addTopLevelEntries(jsonBuilder, BoilerplateType.NAMESERVER, remarks,
                ImmutableList.<ImmutableMap<String, Object>>of(), linkBase);
    } else if (!remarks.isEmpty()) {
        jsonBuilder.put(REMARKS, remarks);
    }
    return jsonBuilder.build();
}

From source file:dagger2.internal.codegen.ModuleValidator.java

private void validateModuleVisibility(final TypeElement moduleElement,
        final ValidationReport.Builder<?> reportBuilder) {
    Visibility moduleVisibility = Visibility.ofElement(moduleElement);
    if (moduleVisibility.equals(PRIVATE)) {
        reportBuilder.addItem("Modules cannot be private.", moduleElement);
    } else if (effectiveVisibilityOfElement(moduleElement).equals(PRIVATE)) {
        reportBuilder.addItem("Modules cannot be enclosed in private types.", moduleElement);
    }//  w  w  w.j  av  a  2  s.c  o m

    switch (moduleElement.getNestingKind()) {
    case ANONYMOUS:
        throw new IllegalStateException("Can't apply @Module to an anonymous class");
    case LOCAL:
        throw new IllegalStateException("Local classes shouldn't show up in the processor");
    case MEMBER:
    case TOP_LEVEL:
        if (moduleVisibility.equals(PUBLIC)) {
            ImmutableSet<Element> nonPublicModules = FluentIterable
                    .from(getModuleIncludes(getAnnotationMirror(moduleElement, moduleClass).get()))
                    .transform(new Function<TypeMirror, Element>() {
                        @Override
                        public Element apply(TypeMirror input) {
                            return types.asElement(input);
                        }
                    }).filter(new Predicate<Element>() {
                        @Override
                        public boolean apply(Element input) {
                            return effectiveVisibilityOfElement(input).compareTo(PUBLIC) < 0;
                        }
                    }).toSet();
            if (!nonPublicModules.isEmpty()) {
                reportBuilder.addItem(String.format(
                        "This module is public, but it includes non-public "
                                + "(or effectively non-public) modules. "
                                + "Either reduce the visibility of this module or make %s public.",
                        formatListForErrorMessage(nonPublicModules.asList())), moduleElement);
            }
        }
        break;
    default:
        throw new AssertionError();
    }
}

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

@Override
public ImmutableList<Step> getBuildSteps(BuildContext context, BuildableContext buildableContext) {
    ImmutableList.Builder<Step> stepsBuilder = ImmutableList.builder();

    stepsBuilder.add(new MakeCleanDirectoryStep(getProjectFilesystem(), bundleRoot));

    Path resourcesDestinationPath = bundleRoot.resolve(this.destinations.getResourcesPath());
    if (assetCatalog.isPresent()) {
        stepsBuilder.add(new MkdirStep(getProjectFilesystem(), resourcesDestinationPath));
        Path bundleDir = assetCatalog.get().getOutputDir();
        stepsBuilder.add(CopyStep.forDirectory(getProjectFilesystem(), bundleDir, resourcesDestinationPath,
                CopyStep.DirectoryMode.CONTENTS_ONLY));
    }//from w w  w.  j a va 2 s .c  om

    if (coreDataModel.isPresent()) {
        stepsBuilder.add(new MkdirStep(getProjectFilesystem(), resourcesDestinationPath));
        stepsBuilder.add(CopyStep.forDirectory(getProjectFilesystem(), coreDataModel.get().getOutputDir(),
                resourcesDestinationPath, CopyStep.DirectoryMode.CONTENTS_ONLY));
    }

    if (sceneKitAssets.isPresent()) {
        stepsBuilder.add(new MkdirStep(getProjectFilesystem(), resourcesDestinationPath));
        stepsBuilder.add(CopyStep.forDirectory(getProjectFilesystem(), sceneKitAssets.get().getPathToOutput(),
                resourcesDestinationPath, CopyStep.DirectoryMode.CONTENTS_ONLY));
    }

    Path metadataPath = getMetadataPath();

    Path infoPlistInputPath = context.getSourcePathResolver().getAbsolutePath(infoPlist);
    Path infoPlistSubstitutionTempPath = BuildTargets.getScratchPath(getProjectFilesystem(), getBuildTarget(),
            "%s.plist");
    Path infoPlistOutputPath = metadataPath.resolve("Info.plist");

    stepsBuilder.add(new MkdirStep(getProjectFilesystem(), metadataPath),
            // TODO(bhamiltoncx): This is only appropriate for .app bundles.
            new WriteFileStep(getProjectFilesystem(), "APPLWRUN", metadataPath.resolve("PkgInfo"),
                    /* executable */ false),
            new MkdirStep(getProjectFilesystem(), infoPlistSubstitutionTempPath.getParent()),
            new FindAndReplaceStep(getProjectFilesystem(), infoPlistInputPath, infoPlistSubstitutionTempPath,
                    InfoPlistSubstitution.createVariableExpansionFunction(withDefaults(infoPlistSubstitutions,
                            ImmutableMap.of("EXECUTABLE_NAME", binaryName, "PRODUCT_NAME", binaryName)))),
            new PlistProcessStep(getProjectFilesystem(), infoPlistSubstitutionTempPath,
                    assetCatalog.isPresent() ? Optional.of(assetCatalog.get().getOutputPlist())
                            : Optional.empty(),
                    infoPlistOutputPath, getInfoPlistAdditionalKeys(), getInfoPlistOverrideKeys(),
                    PlistProcessStep.OutputFormat.BINARY));

    if (hasBinary) {
        appendCopyBinarySteps(stepsBuilder);
        appendCopyDsymStep(stepsBuilder, buildableContext);
    }

    if (!Iterables.isEmpty(Iterables.concat(resources.getResourceDirs(),
            resources.getDirsContainingResourceDirs(), resources.getResourceFiles()))) {
        stepsBuilder.add(new MkdirStep(getProjectFilesystem(), resourcesDestinationPath));
        for (SourcePath dir : resources.getResourceDirs()) {
            stepsBuilder.add(CopyStep.forDirectory(getProjectFilesystem(),
                    context.getSourcePathResolver().getAbsolutePath(dir), resourcesDestinationPath,
                    CopyStep.DirectoryMode.DIRECTORY_AND_CONTENTS));
        }
        for (SourcePath dir : resources.getDirsContainingResourceDirs()) {
            stepsBuilder.add(CopyStep.forDirectory(getProjectFilesystem(),
                    context.getSourcePathResolver().getAbsolutePath(dir), resourcesDestinationPath,
                    CopyStep.DirectoryMode.CONTENTS_ONLY));
        }
        for (SourcePath file : resources.getResourceFiles()) {
            // TODO(shs96c): Check that this work cross-cell
            Path resolvedFilePath = context.getSourcePathResolver().getRelativePath(file);
            Path destinationPath = resourcesDestinationPath.resolve(resolvedFilePath.getFileName());
            addResourceProcessingSteps(context.getSourcePathResolver(), resolvedFilePath, destinationPath,
                    stepsBuilder);
        }
    }

    ImmutableList.Builder<Path> codeSignOnCopyPathsBuilder = ImmutableList.builder();

    addStepsToCopyExtensionBundlesDependencies(context.getSourcePathResolver(), stepsBuilder,
            codeSignOnCopyPathsBuilder);

    for (SourcePath variantSourcePath : resources.getResourceVariantFiles()) {
        // TODO(shs96c): Ensure this works cross-cell, as relative path begins with "buck-out"
        Path variantFilePath = context.getSourcePathResolver().getRelativePath(variantSourcePath);

        Path variantDirectory = variantFilePath.getParent();
        if (variantDirectory == null || !variantDirectory.toString().endsWith(".lproj")) {
            throw new HumanReadableException(
                    "Variant files have to be in a directory with name ending in '.lproj', "
                            + "but '%s' is not.",
                    variantFilePath);
        }

        Path bundleVariantDestinationPath = resourcesDestinationPath.resolve(variantDirectory.getFileName());
        stepsBuilder.add(new MkdirStep(getProjectFilesystem(), bundleVariantDestinationPath));

        Path destinationPath = bundleVariantDestinationPath.resolve(variantFilePath.getFileName());
        addResourceProcessingSteps(context.getSourcePathResolver(), variantFilePath, destinationPath,
                stepsBuilder);
    }

    if (!frameworks.isEmpty()) {
        Path frameworksDestinationPath = bundleRoot.resolve(this.destinations.getFrameworksPath());
        stepsBuilder.add(new MkdirStep(getProjectFilesystem(), frameworksDestinationPath));
        for (SourcePath framework : frameworks) {
            Path srcPath = context.getSourcePathResolver().getAbsolutePath(framework);
            stepsBuilder.add(CopyStep.forDirectory(getProjectFilesystem(), srcPath, frameworksDestinationPath,
                    CopyStep.DirectoryMode.DIRECTORY_AND_CONTENTS));
            codeSignOnCopyPathsBuilder.add(frameworksDestinationPath.resolve(srcPath.getFileName()));
        }
    }

    if (needCodeSign()) {
        Optional<Path> signingEntitlementsTempPath;
        Supplier<CodeSignIdentity> codeSignIdentitySupplier;

        if (adHocCodeSignIsSufficient()) {
            signingEntitlementsTempPath = Optional.empty();
            codeSignIdentitySupplier = () -> CodeSignIdentity.AD_HOC;
        } else {
            // Copy the .mobileprovision file if the platform requires it, and sign the executable.
            Optional<Path> entitlementsPlist = Optional.empty();
            final Path srcRoot = getProjectFilesystem().getRootPath().resolve(getBuildTarget().getBasePath());
            Optional<String> entitlementsPlistString = InfoPlistSubstitution.getVariableExpansionForPlatform(
                    CODE_SIGN_ENTITLEMENTS, platformName, withDefaults(infoPlistSubstitutions,
                            ImmutableMap.of("SOURCE_ROOT", srcRoot.toString(), "SRCROOT", srcRoot.toString())));
            if (entitlementsPlistString.isPresent()) {
                entitlementsPlist = Optional.of(srcRoot.resolve(Paths.get(entitlementsPlistString.get())));
            }

            signingEntitlementsTempPath = Optional
                    .of(BuildTargets.getScratchPath(getProjectFilesystem(), getBuildTarget(), "%s.xcent"));

            final Path dryRunResultPath = bundleRoot.resolve(PP_DRY_RUN_RESULT_FILE);

            final ProvisioningProfileCopyStep provisioningProfileCopyStep = new ProvisioningProfileCopyStep(
                    getProjectFilesystem(), infoPlistOutputPath, Optional.empty(), // Provisioning profile UUID -- find automatically.
                    entitlementsPlist, provisioningProfileStore,
                    resourcesDestinationPath.resolve("embedded.mobileprovision"),
                    dryRunCodeSigning ? bundleRoot.resolve(CODE_SIGN_DRY_RUN_ENTITLEMENTS_FILE)
                            : signingEntitlementsTempPath.get(),
                    codeSignIdentityStore,
                    dryRunCodeSigning ? Optional.of(dryRunResultPath) : Optional.empty());
            stepsBuilder.add(provisioningProfileCopyStep);

            codeSignIdentitySupplier = () -> {
                // Using getUnchecked here because the previous step should already throw if exception
                // occurred, and this supplier would never be evaluated.
                Optional<ProvisioningProfileMetadata> selectedProfile = Futures
                        .getUnchecked(provisioningProfileCopyStep.getSelectedProvisioningProfileFuture());

                if (!selectedProfile.isPresent()) {
                    // This should only happen in dry-run codesign mode (since otherwise an exception
                    // would have been thrown already.)  Still, we need to return *something*.
                    Preconditions.checkState(dryRunCodeSigning);
                    return CodeSignIdentity.AD_HOC;
                }

                ImmutableSet<HashCode> fingerprints = selectedProfile.get()
                        .getDeveloperCertificateFingerprints();
                if (fingerprints.isEmpty()) {
                    // No constraints, pick an arbitrary identity.
                    // If no identities are available, use an ad-hoc identity.
                    return Iterables.getFirst(codeSignIdentityStore.getIdentities(), CodeSignIdentity.AD_HOC);
                }
                for (CodeSignIdentity identity : codeSignIdentityStore.getIdentities()) {
                    if (identity.getFingerprint().isPresent()
                            && fingerprints.contains(identity.getFingerprint().get())) {
                        return identity;
                    }
                }

                throw new HumanReadableException(
                        "No code sign identity available for provisioning profile: %s\n"
                                + "Profile requires an identity with one of the following SHA1 fingerprints "
                                + "available in your keychain: \n  %s",
                        selectedProfile.get().getProfilePath(), Joiner.on("\n  ").join(fingerprints));
            };
        }

        addSwiftStdlibStepIfNeeded(context.getSourcePathResolver(), bundleRoot.resolve(Paths.get("Frameworks")),
                dryRunCodeSigning ? Optional.<Supplier<CodeSignIdentity>>empty()
                        : Optional.of(codeSignIdentitySupplier),
                stepsBuilder, false /* is for packaging? */
        );

        for (Path codeSignOnCopyPath : codeSignOnCopyPathsBuilder.build()) {
            stepsBuilder.add(new CodeSignStep(getProjectFilesystem(), context.getSourcePathResolver(),
                    codeSignOnCopyPath, Optional.empty(), codeSignIdentitySupplier, codesignAllocatePath,
                    dryRunCodeSigning ? Optional.of(codeSignOnCopyPath.resolve(CODE_SIGN_DRY_RUN_ARGS_FILE))
                            : Optional.empty()));
        }

        stepsBuilder.add(new CodeSignStep(getProjectFilesystem(), context.getSourcePathResolver(), bundleRoot,
                signingEntitlementsTempPath, codeSignIdentitySupplier, codesignAllocatePath,
                dryRunCodeSigning ? Optional.of(bundleRoot.resolve(CODE_SIGN_DRY_RUN_ARGS_FILE))
                        : Optional.empty()));
    } else {
        addSwiftStdlibStepIfNeeded(context.getSourcePathResolver(), bundleRoot.resolve(Paths.get("Frameworks")),
                Optional.<Supplier<CodeSignIdentity>>empty(), stepsBuilder, false /* is for packaging? */
        );
    }

    // Ensure the bundle directory is archived so we can fetch it later.
    buildableContext.recordArtifact(getPathToOutput());

    return stepsBuilder.build();
}

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

/** Run xcode specific project generation actions. */
private ExitCode runXcodeProjectGenerator(TargetGraphAndTargets targetGraphAndTargets,
        ImmutableSet<BuildTarget> passedInTargetsSet,
        Optional<ImmutableMap<BuildTarget, TargetNode<?>>> sharedLibraryToBundle)
        throws IOException, InterruptedException {
    ExitCode exitCode = ExitCode.SUCCESS;
    AppleConfig appleConfig = buckConfig.getView(AppleConfig.class);
    ProjectGeneratorOptions options = ProjectGeneratorOptions.builder().setShouldGenerateReadOnlyFiles(readOnly)
            .setShouldIncludeTests(isWithTests(buckConfig))
            .setShouldIncludeDependenciesTests(isWithDependenciesTests(buckConfig))
            .setShouldUseHeaderMaps(appleConfig.shouldUseHeaderMapsInXcodeProject())
            .setShouldUseAbsoluteHeaderMapPaths(absoluteHeaderMapPaths)
            .setShouldMergeHeaderMaps(appleConfig.shouldMergeHeaderMapsInXcodeProject())
            .setShouldAddLinkedLibrariesAsFlags(appleConfig.shouldAddLinkedLibrariesAsFlags())
            .setShouldForceLoadLinkWholeLibraries(appleConfig.shouldAddLinkerFlagsForLinkWholeLibraries())
            .setShouldGenerateHeaderSymlinkTreesOnly(appleConfig.shouldGenerateHeaderSymlinkTreesOnly())
            .setShouldGenerateMissingUmbrellaHeader(appleConfig.shouldGenerateMissingUmbrellaHeaders())
            .setShouldUseShortNamesForTargets(true).setShouldCreateDirectoryStructure(combinedProject)
            .setShouldGenerateProjectSchemes(createProjectSchemes).build();

    LOG.debug("Xcode project generation: Generates workspaces for targets");

    ImmutableSet<BuildTarget> requiredBuildTargets = generateWorkspacesForTargets(buckEventBus, pluginManager,
            cell, buckConfig, ruleKeyConfiguration, executorService, targetGraphAndTargets, passedInTargetsSet,
            options, appleCxxFlavors, getFocusModules(), new HashMap<>(), combinedProject, outputPresenter,
            sharedLibraryToBundle);/*  w  w w . j a  va 2s .c  o m*/
    if (!requiredBuildTargets.isEmpty()) {
        ImmutableMultimap<Path, String> cellPathToCellName = cell.getCellPathResolver().getCellPaths()
                .asMultimap().inverse();
        ImmutableList<String> arguments = RichStream.from(requiredBuildTargets).map(target -> {
            if (!target.getCellPath().equals(cell.getRoot())) {
                Optional<String> cellName = cellPathToCellName.get(target.getCellPath()).stream().findAny();
                if (cellName.isPresent()) {
                    return target.withUnflavoredBuildTarget(ImmutableUnflavoredBuildTarget
                            .of(target.getCellPath(), cellName, target.getBaseName(), target.getShortName()));
                } else {
                    throw new IllegalStateException(
                            "Failed to find cell name for cell path while constructing parameters to "
                                    + "build dependencies for project generation. " + "Build target: " + target
                                    + " cell path: " + target.getCellPath());
                }
            } else {
                return target;
            }
        }).map(Object::toString).toImmutableList();
        exitCode = buildRunner.apply(arguments);
    }
    return exitCode;
}

From source file:org.projectbuendia.client.user.UserManager.java

/**
 * Called when users are retrieved from the server, in order to send events and update user
 * state as necessary.//from   w ww  .  jav a2s  .  c  om
 */
private void onUsersSynced(Set<User> syncedUsers) throws UserSyncException {
    if (syncedUsers == null || syncedUsers.isEmpty()) {
        throw new UserSyncException("Set of users retrieved from server is null or empty.");
    }

    ImmutableSet<User> addedUsers = ImmutableSet.copyOf(Sets.difference(syncedUsers, mKnownUsers));
    ImmutableSet<User> deletedUsers = ImmutableSet.copyOf(Sets.difference(mKnownUsers, syncedUsers));

    mKnownUsers.clear();
    mKnownUsers.addAll(syncedUsers);
    mEventBus.post(new KnownUsersSyncedEvent(addedUsers, deletedUsers));

    if (mActiveUser != null && deletedUsers.contains(mActiveUser)) {
        // TODO: Potentially clear mActiveUser here.
        mEventBus.post(new ActiveUserUnsetEvent(mActiveUser, ActiveUserUnsetEvent.REASON_USER_DELETED));
    }

    // If at least one user was added or deleted, the set of known users has changed.
    if (!addedUsers.isEmpty() || !deletedUsers.isEmpty()) {
        setDirty(true);
    }
}