Java Code Examples for com.google.common.collect.ImmutableSet.Builder#build()

The following examples show how to use com.google.common.collect.ImmutableSet.Builder#build() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StandardMessenger.java    From Kettle with GNU General Public License v3.0 6 votes vote down vote up
public Set<PluginMessageListenerRegistration> getIncomingChannelRegistrations(Plugin plugin, String channel) {
    if (plugin == null) {
        throw new IllegalArgumentException("Plugin cannot be null");
    }
    validateChannel(channel);

    synchronized (incomingLock) {
        Set<PluginMessageListenerRegistration> registrations = incomingByPlugin.get(plugin);

        if (registrations != null) {
            Builder<PluginMessageListenerRegistration> builder = ImmutableSet.builder();

            for (PluginMessageListenerRegistration registration : registrations) {
                if (registration.getChannel().equals(channel)) {
                    builder.add(registration);
                }
            }

            return builder.build();
        } else {
            return ImmutableSet.of();
        }
    }
}
 
Example 2
Source File: StandardMessenger.java    From Kettle with GNU General Public License v3.0 6 votes vote down vote up
public Set<String> getIncomingChannels(Plugin plugin) {
    if (plugin == null) {
        throw new IllegalArgumentException("Plugin cannot be null");
    }

    synchronized (incomingLock) {
        Set<PluginMessageListenerRegistration> registrations = incomingByPlugin.get(plugin);

        if (registrations != null) {
            Builder<String> builder = ImmutableSet.builder();

            for (PluginMessageListenerRegistration registration : registrations) {
                builder.add(registration.getChannel());
            }

            return builder.build();
        } else {
            return ImmutableSet.of();
        }
    }
}
 
Example 3
Source File: PacketAddOrUpdateTrain.java    From Signals with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void fromBytes(ByteBuf b){
    trainID = b.readInt();

    int ids = b.readInt();
    PacketBuffer pb = new PacketBuffer(b);
    Builder<UUID> cartIDs = new ImmutableSet.Builder<>();
    for(int i = 0; i < ids; i++) {
        cartIDs.add(pb.readUniqueId());
    }
    this.cartIDs = cartIDs.build();

    int posCount = b.readInt();
    Builder<MCPos> positions = new ImmutableSet.Builder<>();
    for(int i = 0; i < posCount; i++) {
        positions.add(new MCPos(b));
    }
    this.positions = positions.build();
}
 
Example 4
Source File: GssResourceGenerator.java    From gss.gwt with Apache License 2.0 6 votes vote down vote up
private Set<String> getPermutationsConditions(ResourceContext context,
    List<String> permutationAxes) {
  Builder<String> setBuilder = ImmutableSet.builder();
  PropertyOracle oracle = context.getGeneratorContext().getPropertyOracle();

  for (String permutationAxis : permutationAxes) {
    String propValue = null;
    try {
      SelectionProperty selProp = oracle.getSelectionProperty(null,
          permutationAxis);
      propValue = selProp.getCurrentValue();
    } catch (BadPropertyValueException e) {
      try {
        ConfigurationProperty confProp = oracle.getConfigurationProperty(permutationAxis);
        propValue = confProp.getValues().get(0);
      } catch (BadPropertyValueException e1) {
        e1.printStackTrace();
      }
    }

    if (propValue != null) {
      setBuilder.add(permutationAxis + ":" + propValue);
    }
  }
  return setBuilder.build();
}
 
Example 5
Source File: ZooKeeperEndpointGroupTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void curatorDiscovery() throws Throwable {
    final List<Endpoint> sampleEndpoints = ZooKeeperTestUtil.sampleEndpoints(3);
    setCuratorXNodeChildren(sampleEndpoints, 0);
    final ZooKeeperDiscoverySpec spec = ZooKeeperDiscoverySpec.builderForCurator(CURATOR_X_SERVICE_NAME)
                                                              .build();
    final ZooKeeperEndpointGroup endpointGroup = endpointGroup(spec);
    await().untilAsserted(() -> assertThat(endpointGroup.endpoints()).hasSameElementsAs(sampleEndpoints));

    // Add two more nodes.
    final List<Endpoint> extraEndpoints = ZooKeeperTestUtil.sampleEndpoints(2);
    setCuratorXNodeChildren(extraEndpoints, 3);

    // Construct the final expected node list.
    final Builder<Endpoint> builder = ImmutableSet.builder();
    builder.addAll(sampleEndpoints).addAll(extraEndpoints);
    try (CloseableZooKeeper zk = zkInstance.connection()) {
        zk.sync(Z_NODE, (rc, path, ctx) -> {}, null);
    }

    final Set<Endpoint> expected = builder.build();
    await().untilAsserted(() -> assertThat(endpointGroup.endpoints()).hasSameElementsAs(expected));
    disconnectZk(endpointGroup);
}
 
Example 6
Source File: FibImpl.java    From batfish with Apache License 2.0 6 votes vote down vote up
/**
 * Attempt to resolve a RIB route down to an interface route.
 *
 * @param rib {@link GenericRib} for which to do the resolution.
 * @param route {@link AbstractRoute} with a next hop IP to be resolved.
 * @return A map (interface name -&gt; last hop IP -&gt; last taken route) for
 * @throws BatfishException if resolution depth is exceeded (high likelihood of a routing loop) OR
 *     an invalid route in the RIB has been encountered.
 */
@VisibleForTesting
Set<FibEntry> resolveRoute(
    GenericRib<? extends AbstractRouteDecorator> rib, AbstractRoute route) {
  ResolutionTreeNode resolutionRoot = ResolutionTreeNode.root(route);
  buildResolutionTree(
      rib,
      route,
      Route.UNSET_ROUTE_NEXT_HOP_IP,
      new HashSet<>(),
      0,
      Prefix.MAX_PREFIX_LENGTH,
      null,
      resolutionRoot);
  Builder<FibEntry> collector = ImmutableSet.builder();
  collectEntries(resolutionRoot, new Stack<>(), collector);
  return collector.build();
}
 
Example 7
Source File: ImmutableNegotiationResult.java    From ldp4j with Apache License 2.0 6 votes vote down vote up
ImmutableNegotiationResult(final ImmutableVariant variant, ImmutableQuality quality, final ImmutableVariant errorVariant, ImmutableAlternatives alternatives) {
	checkArgument(
		(variant==null && quality==null) ||
		(variant!=null && quality!=null),
		"Variant and quality must be simultaneously defined or not (%s <--> %s)",variant,quality);
	checkNotNull(errorVariant,"Error variant cannot be null");
	checkNotNull(alternatives,"Alternatives cannot be null");
	this.variant=variant;
	this.quality=quality;
	this.errorVariant=errorVariant;
	this.alternatives=alternatives;
	Builder<MediaType> mtBuilder=ImmutableSet.<MediaType>builder();
	Builder<CharacterEncoding> ceBuilder=ImmutableSet.<CharacterEncoding>builder();
	Builder<Language> lBuilder=ImmutableSet.<Language>builder();
	for(Alternative alternative:alternatives) {
		addEntityIfPresent(mtBuilder,alternative.type());
		addEntityIfPresent(ceBuilder,alternative.charset());
		addEntityIfPresent(lBuilder,alternative.language());
	}
	this.mediaTypes=mtBuilder.build();
	this.characterEncodings=ceBuilder.build();
	this.languages=lBuilder.build();
}
 
Example 8
Source File: KeyStatementSupport.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public ImmutableSet<QName> parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
    final Builder<QName> builder = ImmutableSet.builder();
    int tokens = 0;
    for (String keyToken : LIST_KEY_SPLITTER.split(value)) {
        builder.add(StmtContextUtils.parseNodeIdentifier(ctx, keyToken));
        tokens++;
    }

    // Throws NPE on nulls, retains first inserted value, cannot be modified
    final ImmutableSet<QName> ret = builder.build();
    SourceException.throwIf(ret.size() != tokens, ctx.getStatementSourceReference(),
            "Key argument '%s' contains duplicates", value);
    return ret;
}
 
Example 9
Source File: BitsSerializationTest.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
private static ImmutableSet<String> fillBits(final int size) {
    final Builder<String> builder = ImmutableSet.builderWithExpectedSize(size);
    for (int i = 0; i < size; ++i) {
        builder.add(Integer.toHexString(i));
    }
    final ImmutableSet<String> ret = builder.build();
    Assert.assertEquals(size, ret.size());
    return ret;
}
 
Example 10
Source File: CodecsImpl.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
public CodecsImpl(final RIBSupport<?, ?, ?, ?> ribSupport) {
    this.ribSupport = requireNonNull(ribSupport);
    final Builder<Class<? extends BindingObject>> acb = ImmutableSet.builder();
    acb.addAll(ATTRIBUTE_CACHEABLES);
    acb.addAll(this.ribSupport.cacheableAttributeObjects());
    this.cacheableAttributes = acb.build();
}
 
Example 11
Source File: PresentSpotRequestsAndInstances.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
protected Set<RunningInstance> getSpots(Set<RegionAndName> regionAndIds) {
   Builder<RunningInstance> builder = ImmutableSet.<RunningInstance> builder();
   Multimap<String, String> regionToSpotIds = transformValues(index(regionAndIds, regionFunction()), nameFunction());
   for (Map.Entry<String, Collection<String>> entry : regionToSpotIds.asMap().entrySet()) {
      String region = entry.getKey();
      Collection<String> spotIds = entry.getValue();
      logger.trace("looking for spots %s in region %s", spotIds, region);
      builder.addAll(transform(
                               client.getSpotInstanceApi().get().describeSpotInstanceRequestsInRegion(region,
                  toArray(spotIds, String.class)), spotConverter));
   }
   return builder.build();
}
 
Example 12
Source File: PrefixTrieMultiMap.java    From batfish with Apache License 2.0 5 votes vote down vote up
/** @return all elements in the trie. */
@Nonnull
public Set<T> getAllElements() {
  Builder<T> b = ImmutableSet.builder();
  traverseNodes(node -> b.addAll(node._elements));
  return b.build();
}
 
Example 13
Source File: SymbolProto.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public SymbolProto(final Class clazz, final boolean hasSequence, final boolean hasArgs, final int kind,
		final boolean doesNotHaveScope, final FacetProto[] possibleFacets, final String omissible,
		final String[] contextKeywords, final int[] parentKinds, final boolean isRemoteContext,
		final boolean isUniqueInContext, final boolean nameUniqueInContext, final ISymbolConstructor constr,
		final IValidator validator, final SymbolSerializer serializer, final String name, final String plugin) {
	super(name, clazz, plugin);
	factory = DescriptionFactory.getFactory(kind);
	this.validator = validator;
	this.serializer = serializer;
	constructor = constr;
	this.isRemoteContext = isRemoteContext;
	this.hasSequence = hasSequence;
	this.isPrimitive = IKeyword.PRIMITIVE.equals(name);
	this.hasArgs = hasArgs;
	this.omissibleFacet = omissible;
	this.isUniqueInContext = isUniqueInContext;
	this.kind = kind;
	this.isVar = ISymbolKind.Variable.KINDS.contains(kind);
	this.hasScope = !doesNotHaveScope;
	if (possibleFacets != null) {
		final Builder<String> builder = ImmutableSet.builder();
		this.possibleFacets = GamaMapFactory.createUnordered();
		for (final FacetProto f : possibleFacets) {
			this.possibleFacets.put(f.name, f);
			f.setOwner(getTitle());
			if (!f.optional) {
				builder.add(f.name);
			}
		}
		mandatoryFacets = builder.build();
	} else {
		this.possibleFacets = null;
		mandatoryFacets = null;
	}
	this.contextKeywords = ImmutableSet.copyOf(contextKeywords);
	Arrays.fill(this.contextKinds, false);
	for (final int i : parentKinds) {
		contextKinds[i] = true;
	}
}
 
Example 14
Source File: FlowTableConfig.java    From onos with Apache License 2.0 5 votes vote down vote up
public Set<FlowRule> flowtable() {
    JsonNode ents = object.path(ENTRIES);
    if (!ents.isArray()) {

        return ImmutableSet.of();
    }
    ArrayNode entries = (ArrayNode) ents;

    Builder<FlowRule> builder = ImmutableSet.builder();
    entries.forEach(entry -> builder.add(decode(entry, FlowRule.class)));
    return builder.build();
}
 
Example 15
Source File: CraftEnderDragon.java    From Thermos with GNU General Public License v3.0 5 votes vote down vote up
public Set<ComplexEntityPart> getParts() {
    Builder<ComplexEntityPart> builder = ImmutableSet.builder();

    for (EntityDragonPart part : getHandle().dragonPartArray) {
        builder.add((ComplexEntityPart) part.getBukkitEntity());
    }

    return builder.build();
}
 
Example 16
Source File: JdbcAssert.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
static Set<String> toStringSet(ResultSet resultSet) throws SQLException {
  Builder<String> builder = ImmutableSet.builder();
  final List<Ord<String>> columns = columnLabels(resultSet);
  while (resultSet.next()) {
    StringBuilder buf = new StringBuilder();
    for (Ord<String> column : columns) {
      buf.append(column.i == 1 ? "" : "; ").append(column.e).append("=").append(resultSet.getObject(column.i));
    }
    builder.add(buf.toString());
    buf.setLength(0);
  }
  return builder.build();
}
 
Example 17
Source File: CraftEnderDragon.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
public Set<ComplexEntityPart> getParts() {
    Builder<ComplexEntityPart> builder = ImmutableSet.builder();

    for (MultiPartEntityPart part : getHandle().dragonPartArray) {
        builder.add((ComplexEntityPart) part.getBukkitEntity());
    }

    return builder.build();
}
 
Example 18
Source File: Server.java    From armeria with Apache License 2.0 4 votes vote down vote up
private void finishDoStop(CompletableFuture<Void> future) {
    serverChannels.clear();

    if (config.shutdownBlockingTaskExecutorOnStop()) {
        final ScheduledExecutorService executor;
        final ScheduledExecutorService blockingTaskExecutor = config.blockingTaskExecutor();
        if (blockingTaskExecutor instanceof UnstoppableScheduledExecutorService) {
            executor =
                    ((UnstoppableScheduledExecutorService) blockingTaskExecutor).getExecutorService();
        } else {
            executor = blockingTaskExecutor;
        }

        try {
            executor.shutdown();
            while (!executor.isTerminated()) {
                try {
                    executor.awaitTermination(1, TimeUnit.DAYS);
                } catch (InterruptedException ignore) {
                    // Do nothing.
                }
            }
        } catch (Exception e) {
            logger.warn("Failed to shutdown the blockingTaskExecutor: {}", executor, e);
        }
    }

    final Builder<AccessLogWriter> builder = ImmutableSet.builder();
    config.virtualHosts()
          .stream()
          .filter(VirtualHost::shutdownAccessLogWriterOnStop)
          .forEach(virtualHost -> builder.add(virtualHost.accessLogWriter()));
    config.serviceConfigs()
          .stream()
          .filter(ServiceConfig::shutdownAccessLogWriterOnStop)
          .forEach(serviceConfig -> builder.add(serviceConfig.accessLogWriter()));

    final Set<AccessLogWriter> writers = builder.build();
    final List<CompletableFuture<Void>> completionFutures = new ArrayList<>(writers.size());
    writers.forEach(accessLogWriter -> {
        final CompletableFuture<Void> shutdownFuture = accessLogWriter.shutdown();
        shutdownFuture.exceptionally(cause -> {
            logger.warn("Failed to close the {}:", AccessLogWriter.class.getSimpleName(), cause);
            return null;
        });
        completionFutures.add(shutdownFuture);
    });

    CompletableFutures.successfulAsList(completionFutures, cause -> null)
                      .thenRunAsync(() -> future.complete(null), config.startStopExecutor());
}
 
Example 19
Source File: JSONEncoder.java    From arctic-sea with Apache License 2.0 4 votes vote down vote up
public JSONEncoder(Class<? super T> type, EncoderKey... additionalKeys) {
    Builder<EncoderKey> set = ImmutableSet.builder();
    set.add(new JSONEncoderKey(type));
    set.addAll(Arrays.asList(additionalKeys));
    this.encoderKeys = set.build();
}
 
Example 20
Source File: JSONEncoder.java    From arctic-sea with Apache License 2.0 4 votes vote down vote up
public JSONEncoder(EncoderKey... keys) {
    Builder<EncoderKey> set = ImmutableSet.builder();
    set.addAll(Arrays.asList(keys));
    this.encoderKeys = set.build();
}