Example usage for com.google.common.collect ImmutableSet.Builder addAll

List of usage examples for com.google.common.collect ImmutableSet.Builder addAll

Introduction

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

Prototype

boolean addAll(Collection<? extends E> c);

Source Link

Document

Adds all of the elements in the specified collection to this set if they're not already present (optional operation).

Usage

From source file:io.soliton.shapeshifter.NamedSchema.java

/**
 * Returns a schema that will not ignore the given field names for
 * serialization and parsing purposes.//w  w w.  j av a  2  s.c  o  m
 *
 * @param names the names of the fields to ignore
 */
public NamedSchema skip(String... names) {
    Preconditions.checkNotNull(names);
    for (String name : names) {
        Preconditions.checkArgument(has(name));
    }
    ImmutableSet.Builder<String> skippedCopy = ImmutableSet.builder();
    skippedCopy.addAll(skippedFields);
    skippedCopy.add(names);
    return new NamedSchema(descriptor, name, skippedCopy.build(), constants, enumCaseFormat, substitutions,
            transforms, mappings, descriptions, subObjectSchemas, formats, treatLongsAsStrings);
}

From source file:org.killbill.billing.plugin.simpletax.SimpleTaxPlugin.java

/**
 * Lists all invoice of account as {@linkplain ImmutableSet immutable set},
 * including the passed {@code newInvoice} that is the new invoice being
 * currently created./*from   w ww.j a  v a2 s.  c om*/
 * <p>
 * This implementation is indifferent to the persistence status of the
 * passed {@code newInvoice}. Persisted and not persisted invoices are
 * supported. This is a consequence of the workaround implemented to solve
 * the <a href="https://github.com/killbill/killbill/issues/265">issue
 * #265</a>.
 *
 * @param newInvoice
 *            The new invoice that is being created, which might have
 *            already been saved or not.
 * @param tenantCtx
 *            The context in which this code is running.
 * @return A new immutable set of all invoices for the account, including
 *         the new one being created. Never {@code null}, and guaranteed not
 *         having any {@code null} elements.
 */
private Set<Invoice> allInvoicesOfAccount(Account account, Invoice newInvoice, TenantContext tenantCtx) {
    ImmutableSet.Builder<Invoice> builder = ImmutableSet.builder();
    builder.addAll(getInvoicesByAccountId(account.getId(), tenantCtx));

    // Workaround for https://github.com/killbill/killbill/issues/265
    builder.add(newInvoice);

    return builder.build();
}

From source file:org.apache.hadoop.hive.ql.exec.SentryGrantRevokeTask.java

private int processShowGrantDDL(HiveConf conf, LogHelper console, SentryPolicyServiceClient sentryClient,
        String subject, String server, ShowGrantDesc desc) throws SentryUserException {
    PrincipalDesc principalDesc = desc.getPrincipalDesc();
    PrivilegeObjectDesc hiveObjectDesc = desc.getHiveObj();
    String principalName = principalDesc.getName();
    Set<TSentryPrivilege> privileges;

    try {/*from  w ww  . jav a  2s  .  co  m*/
        if (principalDesc.getType() != PrincipalType.ROLE) {
            String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principalDesc.getType();
            throw new HiveException(msg);
        }

        if (hiveObjectDesc == null) {
            privileges = sentryClient.listPrivilegesByRoleName(subject, principalName, null);
        } else {
            SentryHivePrivilegeObjectDesc privSubjectDesc = toSentryHivePrivilegeObjectDesc(hiveObjectDesc);
            List<Authorizable> authorizableHeirarchy = toAuthorizable(privSubjectDesc);
            if (privSubjectDesc.getColumns() != null && !privSubjectDesc.getColumns().isEmpty()) {
                List<List<Authorizable>> ps = parseColumnToAuthorizable(authorizableHeirarchy, privSubjectDesc);
                ImmutableSet.Builder<TSentryPrivilege> pbuilder = new ImmutableSet.Builder<TSentryPrivilege>();
                for (List<Authorizable> p : ps) {
                    pbuilder.addAll(sentryClient.listPrivilegesByRoleName(subject, principalName, p));
                }
                privileges = pbuilder.build();
            } else {
                privileges = sentryClient.listPrivilegesByRoleName(subject, principalName,
                        authorizableHeirarchy);
            }
        }
        writeToFile(writeGrantInfo(privileges, principalName), desc.getResFile());
        return RETURN_CODE_SUCCESS;
    } catch (IOException e) {
        String msg = "IO Error in show grant " + e.getMessage();
        LOG.info(msg, e);
        console.printError(msg);
        return RETURN_CODE_FAILURE;
    } catch (HiveException e) {
        String msg = "Error in show grant operation, error message " + e.getMessage();
        LOG.warn(msg, e);
        console.printError(msg);
        return RETURN_CODE_FAILURE;
    }
}

From source file:com.outerspacecat.cassandra.StaticSeededCluster.java

/**
 * Creates a new cluster./*  w ww .  j av  a2  s  .  c  o m*/
 * 
 * @param name the name of the cluster. Must be non {@code null}.
 * @param keyspace the name of the keyspace to use for auto-discovering nodes.
 *        Must be non {@code null}.
 * @param timeout the timeout in to use in milliseconds for both establishing
 *        a connection and for reading and writing data. Will be used for both
 *        contacting seeds and obtaining connections from discovered nodes.
 *        Must be &gt;= 0. 0 indicates an infinite timeout.
 * @param maxConnectionsPerNode the maximum number of connections allowed to
 *        each node. Must be &gt;= 0.
 * @param idleTimeout the amount of time in seconds before an unused
 *        connection is considered idle. Must be &gt;= 0.
 * @param seeds the seeds to use. Must be non {@code null}, contain at least
 *        one element, and all elements must be non {@code null}.
 * @param port the port to use for both contacting seeds and obtaining
 *        connections to nodes. Must be &gt;= 1 and &lt;= 65535.
 */
public StaticSeededCluster(final CharSequence name, final CharSequence keyspace, final int timeout,
        final int maxConnectionsPerNode, final int idleTimeout, final Iterable<InetAddress> seeds,
        final int port) {
    Preconditions.checkNotNull(name, "name required");
    Preconditions.checkNotNull(keyspace, "keyspace required");
    Preconditions.checkArgument(timeout >= 0, "timeout must be >= 0");
    Preconditions.checkArgument(maxConnectionsPerNode >= 0, "maxConnectionsPerNode must be >= 0");
    Preconditions.checkArgument(idleTimeout >= 0, "idleTimeout must be >= 0");
    Preconditions.checkNotNull(seeds, "seeds required");
    Preconditions.checkArgument(seeds.iterator().hasNext(), "seeds must be non empty");
    Preconditions.checkArgument(port >= 1 && port <= 65535, "port must be >=1 and <= 65535");

    final AtomicReference<ImmutableSet<String>> oldHosts = new AtomicReference<>();

    exec.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            for (InetAddress addr : seeds) {
                ImmutableSet.Builder<String> hostsBuilder = ImmutableSet.builder();

                TSocket sock = new TSocket(addr.getHostAddress(), port, timeout);
                TTransport tr = new TFramedTransport(sock);

                try {
                    tr.open();
                } catch (TTransportException e) {
                    continue;
                }

                Cassandra.Client client = new Cassandra.Client(new TBinaryProtocol(tr));

                try {
                    for (TokenRange range : client.describe_ring(keyspace.toString()))
                        hostsBuilder.addAll(range.getEndpoints());
                } catch (TException | InvalidRequestException e) {
                    continue;
                }

                List<ConfiguredConnectionPoolDataSource<CassandraConnection>> dataSources = new ArrayList<>();

                ImmutableSet<String> hosts = hostsBuilder.build();
                if (hosts.equals(oldHosts.get()))
                    return;
                oldHosts.set(hosts);

                for (String host : hosts)
                    dataSources
                            .add(DataSources.configure(host,
                                    new ThriftCassandraConnectionPoolDataSource(
                                            new InetSocketAddress(host, port), timeout),
                                    maxConnectionsPerNode, idleTimeout, 1));

                ConnectionPool<CassandraConnection> pool = new ConnectionPool<>(name, dataSources);

                poolLock.lock();
                try {
                    StaticSeededCluster.this.pool = pool;
                    poolInitialized.signalAll();
                } finally {
                    poolLock.unlock();
                }

                Deque<HasConnectionPool.PoolChangedListener<CassandraConnection>> listeners = null;
                listenersLock.lock();
                try {
                    listeners = Queues.newArrayDeque(StaticSeededCluster.this.listeners);
                } finally {
                    listenersLock.unlock();
                }
                for (HasConnectionPool.PoolChangedListener<CassandraConnection> l : listeners)
                    l.poolChanged(StaticSeededCluster.this);
            }
        }
    }, 0L, DEFAULT_REFRESH_PERIOD, TimeUnit.SECONDS);
}

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

/**
 * Validates the given component subject. Also validates any referenced subcomponents that aren't
 * already included in the {@code validatedSubcomponents} set.
 *//*  w w w  .ja  v a  2  s  . co m*/
public ComponentValidationReport validate(final TypeElement subject,
        Set<? extends Element> validatedSubcomponents, Set<? extends Element> validatedSubcomponentBuilders) {
    ValidationReport.Builder<TypeElement> builder = ValidationReport.Builder.about(subject);

    if (!subject.getKind().equals(INTERFACE)
            && !(subject.getKind().equals(CLASS) && subject.getModifiers().contains(ABSTRACT))) {
        builder.addItem(String.format("@%s may only be applied to an interface or abstract class",
                componentType.annotationType().getSimpleName()), subject);
    }

    ImmutableList<DeclaredType> builders = enclosedBuilders(subject, componentType.builderAnnotationType());
    if (builders.size() > 1) {
        builder.addItem(String.format(ErrorMessages.builderMsgsFor(componentType).moreThanOne(), builders),
                subject);
    }

    DeclaredType subjectType = MoreTypes.asDeclared(subject.asType());

    // TODO(gak): This should use Util.findLocalAndInheritedMethods, otherwise
    // it can return a logical method multiple times (including overrides, etc.)
    List<? extends Element> members = elements.getAllMembers(subject);
    Multimap<Element, ExecutableElement> referencedSubcomponents = LinkedHashMultimap.create();
    for (ExecutableElement method : ElementFilter.methodsIn(members)) {
        if (method.getModifiers().contains(ABSTRACT)) {
            ExecutableType resolvedMethod = MoreTypes.asExecutable(types.asMemberOf(subjectType, method));
            List<? extends TypeMirror> parameterTypes = resolvedMethod.getParameterTypes();
            List<? extends VariableElement> parameters = method.getParameters();
            TypeMirror returnType = resolvedMethod.getReturnType();

            // abstract methods are ones we have to implement, so they each need to be validated
            // first, check the return type.  if it's a subcomponent, validate that method as such.
            Optional<AnnotationMirror> subcomponentAnnotation = checkForAnnotation(returnType,
                    Subcomponent.class);
            Optional<AnnotationMirror> subcomponentBuilderAnnotation = checkForAnnotation(returnType,
                    Subcomponent.Builder.class);
            if (subcomponentAnnotation.isPresent()) {
                referencedSubcomponents.put(MoreTypes.asElement(returnType), method);
                validateSubcomponentMethod(builder, method, parameters, parameterTypes, returnType,
                        subcomponentAnnotation);
            } else if (subcomponentBuilderAnnotation.isPresent()) {
                referencedSubcomponents.put(MoreTypes.asElement(returnType).getEnclosingElement(), method);
                validateSubcomponentBuilderMethod(builder, method, parameters, returnType,
                        validatedSubcomponentBuilders);
            } else {
                // if it's not a subcomponent...
                switch (parameters.size()) {
                case 0:
                    // no parameters means that it is a provision method
                    // basically, there are no restrictions here.  \o/
                    break;
                case 1:
                    // one parameter means that it's a members injection method
                    TypeMirror onlyParameter = Iterables.getOnlyElement(parameterTypes);
                    if (!(returnType.getKind().equals(VOID) || types.isSameType(returnType, onlyParameter))) {
                        builder.addItem("Members injection methods may only return the injected type or void.",
                                method);
                    }
                    break;
                default:
                    // this isn't any method that we know how to implement...
                    builder.addItem(
                            "This method isn't a valid provision method, members injection method or "
                                    + "subcomponent factory method. Dagger cannot implement this method",
                            method);
                    break;
                }
            }
        }
    }

    for (Map.Entry<Element, Collection<ExecutableElement>> entry : referencedSubcomponents.asMap().entrySet()) {
        if (entry.getValue().size() > 1) {
            builder.addItem(String.format(
                    ErrorMessages.SubcomponentBuilderMessages.INSTANCE.moreThanOneRefToSubcomponent(),
                    entry.getKey(), entry.getValue()), subject);
        }
    }

    AnnotationMirror componentMirror = getAnnotationMirror(subject, componentType.annotationType()).get();
    ImmutableList<TypeMirror> moduleTypes = getComponentModules(componentMirror);
    moduleValidator.validateReferencedModules(subject, builder, moduleTypes);

    // Make sure we validate any subcomponents we're referencing, unless we know we validated
    // them already in this pass.
    // TODO(sameb): If subcomponents refer to each other and both aren't in
    //              'validatedSubcomponents' (e.g, both aren't compiled in this pass),
    //              then this can loop forever.
    ImmutableSet.Builder<Element> allSubcomponents = ImmutableSet.<Element>builder()
            .addAll(referencedSubcomponents.keySet());
    for (Element subcomponent : Sets.difference(referencedSubcomponents.keySet(), validatedSubcomponents)) {
        ComponentValidationReport subreport = subcomponentValidator.validate(MoreElements.asType(subcomponent),
                validatedSubcomponents, validatedSubcomponentBuilders);
        builder.addItems(subreport.report().items());
        allSubcomponents.addAll(subreport.referencedSubcomponents());
    }

    return new AutoValue_ComponentValidator_ComponentValidationReport(allSubcomponents.build(),
            builder.build());
}

From source file:com.facebook.presto.metadata.MetadataManager.java

@Override
public List<String> listSchemaNames(Session session, String catalogName) {
    checkCatalogName(catalogName);/*from   ww w  . ja v a2s.co  m*/
    ImmutableSet.Builder<String> schemaNames = ImmutableSet.builder();
    for (ConnectorMetadataEntry entry : allConnectorsFor(catalogName)) {
        schemaNames.addAll(entry.getMetadata().listSchemaNames(session.toConnectorSession(entry.getCatalog())));
    }
    return ImmutableList.copyOf(schemaNames.build());
}

From source file:com.addthis.hydra.job.spawn.search.JobSearcher.java

private Set<TextLocation> getMatchedAliasLocations(IncludeLocations macroIncludeLocations) {
    Predicate<String> predicate = pattern.asPredicate();
    ImmutableSet.Builder<TextLocation> results = ImmutableSet.builder();
    for (String dep : macroIncludeLocations.dependencies()) {
        // dep may be an alias or a macro - macroIncludeLocations may contain both because both are denoted using
        // %{...}%. For an alias, check if any of its values match the search pattern.
        List<String> jobIds = aliases.get(dep);
        if (jobIds != null) {
            for (String jobId : jobIds) {
                if (predicate.test(jobId)) {
                    results.addAll(macroIncludeLocations.locationsFor(dep));
                    break;
                }//  w  ww .  jav  a  2s .c om
            }
        }
    }

    return results.build();
}

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

@Override
public <A extends Arg, U> Optional<U> createMetadata(BuildTarget buildTarget, BuildRuleResolver resolver,
        A args, Class<U> metadataClass) throws NoSuchBuildTargetException {
    if (!metadataClass.isAssignableFrom(FrameworkDependencies.class)
            || !buildTarget.getFlavors().contains(AppleDescriptions.FRAMEWORK_FLAVOR)) {
        CxxLibraryDescription.Arg delegateArg = delegate.createUnpopulatedConstructorArg();
        AppleDescriptions.populateCxxLibraryDescriptionArg(
                new SourcePathResolver(new SourcePathRuleFinder(resolver)), delegateArg, args, buildTarget);
        return delegate.createMetadata(buildTarget, resolver, delegateArg, metadataClass);
    }//w  w  w.j ava  2s. c om
    Optional<Flavor> cxxPlatformFlavor = delegate.getCxxPlatforms().getFlavor(buildTarget);
    Preconditions.checkState(cxxPlatformFlavor.isPresent(), "Could not find cxx platform in:\n%s",
            Joiner.on(", ").join(buildTarget.getFlavors()));
    ImmutableSet.Builder<SourcePath> sourcePaths = ImmutableSet.builder();
    for (BuildTarget dep : args.deps) {
        Optional<FrameworkDependencies> frameworks = resolver
                .requireMetadata(BuildTarget.builder(dep).addFlavors(AppleDescriptions.FRAMEWORK_FLAVOR)
                        .addFlavors(AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR)
                        .addFlavors(cxxPlatformFlavor.get()).build(), FrameworkDependencies.class);
        if (frameworks.isPresent()) {
            sourcePaths.addAll(frameworks.get().getSourcePaths());
        }
    }
    // Not all parts of Buck use require yet, so require the rule here so it's available in the
    // resolver for the parts that don't.
    resolver.requireRule(buildTarget);
    sourcePaths.add(new BuildTargetSourcePath(buildTarget));
    return Optional.of(metadataClass.cast(FrameworkDependencies.of(sourcePaths.build())));
}

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

/**
 * Validates the given component subject. Also validates any referenced subcomponents that aren't
 * already included in the {@code validatedSubcomponents} set.
 *//*from   w w  w.  j  a  v  a 2 s .co m*/
public ComponentValidationReport validate(final TypeElement subject,
        Set<? extends Element> validatedSubcomponents, Set<? extends Element> validatedSubcomponentBuilders) {
    ValidationReport.Builder<TypeElement> builder = ValidationReport.about(subject);

    ComponentDescriptor.Kind componentKind = ComponentDescriptor.Kind.forAnnotatedElement(subject).get();

    if (!subject.getKind().equals(INTERFACE)
            && !(subject.getKind().equals(CLASS) && subject.getModifiers().contains(ABSTRACT))) {
        builder.addError(String.format("@%s may only be applied to an interface or abstract class",
                componentKind.annotationType().getSimpleName()), subject);
    }

    ImmutableList<DeclaredType> builders = enclosedBuilders(subject, componentKind.builderAnnotationType());

    if (builders.isEmpty()) {
        final String subjectName = subject.getQualifiedName().toString();
        builder.addError(
                String.format(ErrorMessages.builderMsgsFor(componentKind).noBuilderPresent(), subjectName));
    }

    if (builders.size() > 1) {
        builder.addError(String.format(ErrorMessages.builderMsgsFor(componentKind).moreThanOne(), builders),
                subject);
    }

    Optional<AnnotationMirror> reusableAnnotation = getAnnotationMirror(subject, Reusable.class);
    if (reusableAnnotation.isPresent()) {
        builder.addError(COMPONENT_ANNOTATED_REUSABLE, subject, reusableAnnotation.get());
    }

    DeclaredType subjectType = MoreTypes.asDeclared(subject.asType());

    SetMultimap<Element, ExecutableElement> referencedSubcomponents = LinkedHashMultimap.create();
    getLocalAndInheritedMethods(subject, types, elements).stream()
            .filter(method -> method.getModifiers().contains(ABSTRACT)).forEachOrdered(method -> {
                ExecutableType resolvedMethod = asExecutable(types.asMemberOf(subjectType, method));
                List<? extends TypeMirror> parameterTypes = resolvedMethod.getParameterTypes();
                List<? extends VariableElement> parameters = method.getParameters();
                TypeMirror returnType = resolvedMethod.getReturnType();

                // abstract methods are ones we have to implement, so they each need to be validated
                // first, check the return type. if it's a subcomponent, validate that method as such.
                Optional<AnnotationMirror> subcomponentAnnotation = checkForAnnotations(returnType,
                        FluentIterable.from(componentKind.subcomponentKinds()).transform(Kind::annotationType)
                                .toSet());
                Optional<AnnotationMirror> subcomponentBuilderAnnotation = checkForAnnotations(returnType,
                        FluentIterable.from(componentKind.subcomponentKinds())
                                .transform(Kind::builderAnnotationType).toSet());
                if (subcomponentAnnotation.isPresent()) {
                    referencedSubcomponents.put(MoreTypes.asElement(returnType), method);
                    validateSubcomponentMethod(builder,
                            ComponentDescriptor.Kind.forAnnotatedElement(MoreTypes.asTypeElement(returnType))
                                    .get(),
                            method, parameters, parameterTypes, returnType, subcomponentAnnotation);
                } else if (subcomponentBuilderAnnotation.isPresent()) {
                    referencedSubcomponents.put(MoreTypes.asElement(returnType).getEnclosingElement(), method);
                    validateSubcomponentBuilderMethod(builder, method, parameters, returnType,
                            validatedSubcomponentBuilders);
                } else {
                    // if it's not a subcomponent...
                    switch (parameters.size()) {
                    case 0:
                        // no parameters means that it is a provision method
                        // basically, there are no restrictions here.  \o/
                        break;
                    case 1:
                        // one parameter means that it's a members injection method
                        TypeMirror onlyParameter = Iterables.getOnlyElement(parameterTypes);
                        if (!(returnType.getKind().equals(VOID)
                                || types.isSameType(returnType, onlyParameter))) {
                            builder.addError(
                                    "Members injection methods may only return the injected type or void.",
                                    method);
                        }
                        break;
                    default:
                        // this isn't any method that we know how to implement...
                        builder.addError(
                                "This method isn't a valid provision method, members injection method or "
                                        + "subcomponent factory method. Dagger cannot implement this method",
                                method);
                        break;
                    }
                }
            });

    Maps.filterValues(referencedSubcomponents.asMap(), methods -> methods.size() > 1)
            .forEach((subcomponent,
                    methods) -> builder.addError(String.format(
                            ErrorMessages.SubcomponentBuilderMessages.INSTANCE.moreThanOneRefToSubcomponent(),
                            subcomponent, methods), subject));

    AnnotationMirror componentMirror = getAnnotationMirror(subject, componentKind.annotationType()).get();
    if (componentKind.isTopLevel()) {
        validateComponentDependencies(builder, getComponentDependencies(componentMirror));
    }
    builder.addSubreport(
            moduleValidator.validateReferencedModules(subject, componentMirror, componentKind.moduleKinds()));

    // Make sure we validate any subcomponents we're referencing, unless we know we validated
    // them already in this pass.
    // TODO(sameb): If subcomponents refer to each other and both aren't in
    //              'validatedSubcomponents' (e.g, both aren't compiled in this pass),
    //              then this can loop forever.
    ImmutableSet.Builder<Element> allSubcomponents = ImmutableSet.<Element>builder()
            .addAll(referencedSubcomponents.keySet());
    for (Element subcomponent : Sets.difference(referencedSubcomponents.keySet(), validatedSubcomponents)) {
        ComponentValidationReport subreport = subcomponentValidator.validate(MoreElements.asType(subcomponent),
                validatedSubcomponents, validatedSubcomponentBuilders);
        builder.addItems(subreport.report().items());
        allSubcomponents.addAll(subreport.referencedSubcomponents());
    }

    return new AutoValue_ComponentValidator_ComponentValidationReport(allSubcomponents.build(),
            builder.build());
}

From source file:com.github.jsdossier.TypeRegistry.java

/**
 * Returns the interfaces implemented by the given type. If the type is itself an interface, this
 * will return its super types.//ww  w.j  a va  2 s.  com
 */
public ImmutableSet<JSType> getImplementedTypes(NominalType nominalType) {
    JSType type = nominalType.getJsType();
    ImmutableSet.Builder<JSType> builder = ImmutableSet.builder();
    if (type.isConstructor()) {
        for (JSType jsType : getTypeHierarchy(type)) {
            if (jsType.getJSDocInfo() != null) {
                for (JSTypeExpression expr : jsType.getJSDocInfo().getImplementedInterfaces()) {
                    builder.add(evaluate(expr));
                }
            } else if (jsType.isInstanceType()) {
                NominalType resolved = resolve(jsType);
                if (resolved != null && resolved != nominalType) {
                    builder.addAll(getImplementedTypes(resolved));
                }
            }
        }
    } else if (type.isInterface() && nominalType.getJsdoc() != null) {
        builder.addAll(getExtendedInterfaces(nominalType.getJsdoc().getInfo()));
    }
    return builder.build();
}