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

The following examples show how to use com.google.common.collect.ImmutableList.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: AbstractSemanticRegionsFinder.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public List<Pair<ISemanticRegion, ISemanticRegion>> keywordPairs(Keyword kw1, Keyword kw2) {
	Preconditions.checkNotNull(kw1);
	Preconditions.checkNotNull(kw2);
	Preconditions.checkArgument(kw1 != kw2);
	Predicate<ISemanticRegion> p1 = createPredicate(kw1);
	Predicate<ISemanticRegion> p2 = createPredicate(kw2);
	List<ISemanticRegion> all = findAll(Predicates.or(p1, p2));
	Builder<Pair<ISemanticRegion, ISemanticRegion>> result = ImmutableList.builder();
	LinkedList<ISemanticRegion> stack = new LinkedList<ISemanticRegion>();
	for (ISemanticRegion region : all) {
		if (p1.apply(region))
			stack.push(region);
		else if (!stack.isEmpty())
			result.add(Pair.of(stack.pop(), region));
	}
	return result.build();
}
 
Example 2
Source File: RefreshingAddressResolverGroup.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static ImmutableList<DnsRecordType> dnsRecordTypes(ResolvedAddressTypes resolvedAddressTypes) {
    final Builder<DnsRecordType> builder = ImmutableList.builder();
    switch (resolvedAddressTypes) {
        case IPV4_ONLY:
            builder.add(DnsRecordType.A);
            break;
        case IPV4_PREFERRED:
            builder.add(DnsRecordType.A);
            builder.add(DnsRecordType.AAAA);
            break;
        case IPV6_PREFERRED:
            builder.add(DnsRecordType.AAAA);
            builder.add(DnsRecordType.A);
            break;
    }
    return builder.build();
}
 
Example 3
Source File: AnnotationUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Returns all annotations searching from the specified {@code element}. The search range depends on
 * the specified {@link FindOption}s and the specified {@code collectingFilter} decides whether
 * an annotation is collected or not.
 *
 * @param element the {@link AnnotatedElement} to find annotations
 * @param findOptions the options to be applied when retrieving annotations
 * @param collectingFilter the predicate which decides whether the annotation is to be collected or not
 */
static List<Annotation> getAnnotations(AnnotatedElement element, EnumSet<FindOption> findOptions,
                                       Predicate<Annotation> collectingFilter) {
    requireNonNull(element, "element");
    requireNonNull(collectingFilter, "collectingFilter");

    final Builder<Annotation> builder = new Builder<>();

    for (final AnnotatedElement e : resolveTargetElements(element, findOptions)) {
        for (final Annotation annotation : e.getDeclaredAnnotations()) {
            if (findOptions.contains(FindOption.LOOKUP_META_ANNOTATIONS)) {
                getMetaAnnotations(builder, annotation, collectingFilter);
            }
            if (collectingFilter.test(annotation)) {
                builder.add(annotation);
            }
        }
    }
    return builder.build();
}
 
Example 4
Source File: SpreadSensitivityCalculator.java    From Strata with Apache License 2.0 6 votes vote down vote up
private ImmutableList<ResolvedCdsIndexTrade> getBucketCdsIndex(ResolvedCdsIndex product, CreditRatesProvider ratesProvider) {
  CreditDiscountFactors creditCurve =
      ratesProvider.survivalProbabilities(product.getCdsIndexId(), product.getCurrency()).getSurvivalProbabilities();
  int nNodes = creditCurve.getParameterCount();
  Builder<ResolvedCdsIndexTrade> builder = ImmutableList.builder();
  for (int i = 0; i < nNodes; ++i) {
    ParameterMetadata metadata = creditCurve.getParameterMetadata(i);
    ArgChecker.isTrue(metadata instanceof ResolvedTradeParameterMetadata,
        "ParameterMetadata of credit curve must be ResolvedTradeParameterMetadata");
    ResolvedTradeParameterMetadata tradeMetadata = (ResolvedTradeParameterMetadata) metadata;
    ResolvedTrade trade = tradeMetadata.getTrade();
    ArgChecker.isTrue(trade instanceof ResolvedCdsIndexTrade,
        "ResolvedTrade must be ResolvedCdsIndexTrade");
    builder.add((ResolvedCdsIndexTrade) trade);
  }
  return builder.build();
}
 
Example 5
Source File: CentralDogmaConfig.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
private static List<ClientAddressSource> toClientAddressSourceList(
        @Nullable List<String> clientAddressSources,
        boolean useDefaultSources, boolean specifiedProxyProtocol) {
    if (clientAddressSources != null && !clientAddressSources.isEmpty()) {
        return clientAddressSources.stream().map(
                name -> "PROXY_PROTOCOL".equals(name) ? ofProxyProtocol() : ofHeader(name))
                                   .collect(toImmutableList());
    }

    if (useDefaultSources) {
        final Builder<ClientAddressSource> builder = new Builder<>();
        builder.add(ofHeader(HttpHeaderNames.FORWARDED));
        builder.add(ofHeader(HttpHeaderNames.X_FORWARDED_FOR));
        if (specifiedProxyProtocol) {
            builder.add(ofProxyProtocol());
        }
        return builder.build();
    }

    return ImmutableList.of();
}
 
Example 6
Source File: TypeHandle.java    From Mixin with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected static <T extends Element> List<T> getEnclosedElements(TypeElement targetElement, ElementKind... kind) {
    if (kind == null || kind.length < 1) {
        return (List<T>)TypeHandle.getEnclosedElements(targetElement);
    }
    
    if (targetElement == null) {
        return Collections.<T>emptyList();
    }
    
    Builder<T> list = ImmutableList.<T>builder();
    for (Element elem : targetElement.getEnclosedElements()) {
        for (ElementKind ek : kind) {
            if (elem.getKind() == ek) {
                list.add((T)elem);
                break;
            }
        }
    }

    return list.build();
}
 
Example 7
Source File: MockDialect.java    From morf with Apache License 2.0 6 votes vote down vote up
/**
 * @see org.alfasoftware.morf.jdbc.SqlDialect#renameTableStatements(java.lang.String, java.lang.String)
 */
@Override
public Collection<String> renameTableStatements(Table from, Table to) {

  Builder<String> builder = ImmutableList.<String>builder();

  if (!primaryKeysForTable(from).isEmpty()) {
    builder.add(dropPrimaryKeyConstraintStatement(from));
  }

  builder.add("ALTER TABLE " + from.getName() + " RENAME TO " + to.getName());

  if (!primaryKeysForTable(to).isEmpty()) {
    builder.add(addPrimaryKeyConstraintStatement(to, namesOfColumns(primaryKeysForTable(to))));
  }

  return builder.build();
}
 
Example 8
Source File: SwiftCompile.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
public ImmutableList<Step> getBuildSteps(
    BuildContext context, BuildableContext buildableContext) {
  buildableContext.recordArtifact(outputPath);

  Builder<Step> steps = ImmutableList.builder();
  steps.add(
      MkdirStep.of(
          BuildCellRelativePath.fromCellRelativePath(
              context.getBuildCellRootPath(), getProjectFilesystem(), outputPath)));
  swiftFileListPath.map(
      path -> steps.add(makeFileListStep(context.getSourcePathResolver(), path)));
  steps.add(makeCompileStep(context.getSourcePathResolver()));

  if (useModulewrap) {
    steps.add(makeModulewrapStep(context.getSourcePathResolver()));
  }

  return steps.build();
}
 
Example 9
Source File: TemplateRecordConfigurationCreatingConsumer.java    From baleen with Apache License 2.0 6 votes vote down vote up
/**
 * Generate the covered paths, reducing to the lowest depth.
 *
 * @param structureHierarchy the structure hierarchy
 * @param coveredStructures the covered structures
 * @param depth the maximum depth
 * @return list of paths for the covered structures
 */
private List<String> generateCoveredPaths(
    ItemHierarchy<Structure> structureHierarchy, List<Structure> coveredStructures, int depth) {
  LinkedHashSet<String> collect =
      coveredStructures.stream()
          .map(s -> structureHierarchy.getSelectorPath(s).toDepth(depth).toString())
          .collect(Collectors.toCollection(LinkedHashSet::new));

  Builder<String> builder = ImmutableList.<String>builder();
  String parent = collect.iterator().next();
  builder.add(parent);
  for (String path : collect) {
    if (!path.startsWith(parent)) {
      builder.add(path);
      parent = path;
    }
  }

  return builder.build();
}
 
Example 10
Source File: SearchMappingsServiceImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private static Collection<SearchMapping> collectMappings(final Map<String, SearchMappings> searchMappings) {
  final Builder<SearchMapping> builder = ImmutableList.builder();

  // put the default mappings in first
  final SearchMappings defaultMappings = searchMappings.get(DEFAULT);
  if (defaultMappings != null) {
    builder.addAll(defaultMappings.get());
  }

  // add the rest of the mappings
  searchMappings.keySet().stream()
      .filter(key -> !DEFAULT.equals(key))
      .sorted()
      .forEach(key -> builder.addAll(searchMappings.get(key).get()));

  return builder.build();
}
 
Example 11
Source File: GoTestMain.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public ImmutableList<Step> getBuildSteps(
    BuildContext context, BuildableContext buildableContext) {
  buildableContext.recordArtifact(output);
  Builder<Step> steps =
      ImmutableList.<Step>builder()
          .add(
              MkdirStep.of(
                  BuildCellRelativePath.fromCellRelativePath(
                      context.getBuildCellRootPath(),
                      getProjectFilesystem(),
                      output.getParent())));
  FilteredSourceFiles filteredSrcs =
      new FilteredSourceFiles(
          GoCompile.getSourceFiles(testSources, context),
          ImmutableList.of(),
          platform,
          ImmutableList.of(ListType.GoFiles, ListType.TestGoFiles, ListType.XTestGoFiles));
  steps.addAll(filteredSrcs.getFilterSteps());
  steps.add(
      new GoTestMainStep(
          getProjectFilesystem().getRootPath(),
          testMainGen.getEnvironment(context.getSourcePathResolver()),
          testMainGen.getCommandPrefix(context.getSourcePathResolver()),
          coverageMode,
          coverVariables,
          testPackage,
          filteredSrcs,
          output));
  return steps.build();
}
 
Example 12
Source File: AchievementNotifier.java    From stendhal with GNU General Public License v2.0 5 votes vote down vote up
/**
 * gets a list of all Achievements
 *
 * @return list of achievements
 */
public ImmutableList<Achievement> getAchievements() {
	Builder<Achievement> builder = ImmutableList.builder();
	for (List<Achievement> temp : achievements.values()) {
		builder.addAll(temp);
	}
	return builder.build();
}
 
Example 13
Source File: HttpRepositoryService.java    From SquirrelID with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public ImmutableList<Profile> findAllByName(Iterable<String> names) throws IOException, InterruptedException {
    Builder<Profile> builder = ImmutableList.builder();
    for (List<String> partition : Iterables.partition(names, MAX_NAMES_PER_REQUEST)) {
        builder.addAll(query(partition));
    }
    return builder.build();
}
 
Example 14
Source File: AbstractBindingBuilder.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a newly-created {@link Route}s based on the properties of this builder.
 */
final List<Route> buildRouteList() {
    final Builder<Route> builder = ImmutableList.builder();

    if (additionalRoutes.isEmpty()) {
        if (pathBuilders.isEmpty() && routeBuilders.isEmpty()) {
            throw new IllegalStateException(
                    "Should set at least one path that the service is bound to before calling this.");
        }
        if (pathBuilders.isEmpty() && !methods.isEmpty()) {
            throw new IllegalStateException("Should set a path when the methods are set: " + methods);
        }
    }

    if (!pathBuilders.isEmpty()) {
        final Set<HttpMethod> pathMethods = methods.isEmpty() ? HttpMethod.knownMethods() : methods;
        pathBuilders.forEach(pathBuilder -> addRouteBuilder(pathBuilder, pathMethods));
    }

    routeBuilders.forEach((routeBuilder, routeMethods) -> {
        builder.add(routeBuilder.methods(routeMethods)
                                .consumes(consumeTypes)
                                .produces(produceTypes)
                                .matchesParams(paramPredicates)
                                .matchesHeaders(headerPredicates)
                                .build());
    });

    additionalRoutes.forEach(builder::add);

    return builder.build();
}
 
Example 15
Source File: AttachSessionResponse.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Attach session response network constructor
 *
 * @param inNet
 *            network input stream
 * @throws IOException
 *             network error
 */
public AttachSessionResponse(DataInputStream inNet) throws IOException {
    byte[] data = new byte[SIZE];
    inNet.readFully(data, 0, SIZE);
    ByteBuffer bb = ByteBuffer.wrap(data);
    bb.order(ByteOrder.BIG_ENDIAN);
    fStatus = AttachReturnCode.values()[bb.getInt() - 1];
    fStreamsCount = bb.getInt();
    Builder<StreamResponse> streamResponses = ImmutableList.builder();
    for (int i = 0; i < getNbStreams(); i++) {
        streamResponses.add(new StreamResponse(inNet));
    }
    fStreamList = streamResponses.build();

}
 
Example 16
Source File: KernelEventLayoutRequirement.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Build a real requirement from the layout mapping to be matched with a
 * real trace's layout
 *
 * @param layout
 *            The event layout from which to build the requirements.
 * @return The real requirement
 */
public TmfAbstractAnalysisRequirement instanciateRequirements(IKernelAnalysisEventLayout layout) {
    Builder<String> events = new Builder<>();
    for (ILayoutToEventName eventNameLayout : fEventNames) {
        String eventName = eventNameLayout.getEventName(layout);
        if (eventName != null) {
            events.add(eventName);
        }
    }
    return new TmfAnalysisEventRequirement(events.build(), fLevel);
}
 
Example 17
Source File: ArscDumper.java    From android-arscblamer with Apache License 2.0 5 votes vote down vote up
private static List<String> getConfigurationParts(ResourceConfiguration configuration) {
  Map<ResourceConfiguration.Type, String> parts = configuration.toStringParts();
  Builder<String> builder = ImmutableList.builder();
  for (ResourceConfiguration.Type key : ResourceConfiguration.Type.values()) {
    builder.add(parts.containsKey(key) ? parts.get(key) : "");
  }
  return builder.build();
}
 
Example 18
Source File: StringPoolChunk.java    From android-chunk-utils with Apache License 2.0 5 votes vote down vote up
static StringPoolStyle create(ByteBuffer buffer, int offset, StringPoolChunk parent) {
  Builder<StringPoolSpan> spans = ImmutableList.builder();
  int nameIndex = buffer.getInt(offset);
  while (nameIndex != RES_STRING_POOL_SPAN_END) {
    spans.add(StringPoolSpan.create(buffer, offset, parent));
    offset += StringPoolSpan.SPAN_LENGTH;
    nameIndex = buffer.getInt(offset);
  }
  return new AutoValue_StringPoolChunk_StringPoolStyle(spans.build());
}
 
Example 19
Source File: CharsetSelector.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
private ImmutableList<String> getCharsetPreferences() {
	Builder<String> builder=ImmutableList.<String>builder().addAll(CharsetSelector.this.acceptableCharsets);
	if(CharsetSelector.this.mediaType!=null) {
		String mediaTypePreference = CharsetSelector.this.mediaType.getParameters().get(MediaType.CHARSET_PARAMETER);
		if(mediaTypePreference!=null) {
			builder.add(mediaTypePreference);
		}
	}
	return builder.build();
}
 
Example 20
Source File: CrowdGroupsProviderTest.java    From sonar-crowd with GNU Lesser General Public License v3.0 5 votes vote down vote up
private List<Group> makeGroups(int count, int offset) {
  Builder<Group> builder = new Builder<Group>();
  for (int i = 0; i < count; i++) {
    Group group = mock(Group.class);
    when(group.getName()).thenReturn("group" + (offset + i));
    builder.add(group);
  }
  return builder.build();
}