下面列出了怎么用com.google.common.collect.ImmutableList.Builder的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public RecordSet getRecordSet(ConnectorTransactionHandle transaction,
ConnectorSession session,
ConnectorSplit split,
ConnectorTableHandle table,
List<? extends ColumnHandle> columns) {
Objects.requireNonNull(split, "partitionChunk is null");
HBaseSplit hBaseSplit = (HBaseSplit) split;
Preconditions.checkArgument(
hBaseSplit.getConnectorId().equals(this.connectorId), "split is not for this connector");
Builder<ColumnHandle> handles = ImmutableList.builder();
for (Object obj : columns) {
HBaseColumnHandle hch = (HBaseColumnHandle) obj;
handles.add(hch);
}
return new HBaseRecordSet(hBaseSplit, handles.build(), this.clientManager);
}
public void createPipelinedCompileStep(
BuildContext context,
ProjectFilesystem projectFilesystem,
JavacPipelineState pipeline,
BuildTarget invokingRule,
Builder<Step> steps) {
boolean generatingCode = !javacOptions.getJavaAnnotationProcessorParams().isEmpty();
if (generatingCode && pipeline.isRunning()) {
steps.add(
SymlinkFileStep.of(
projectFilesystem,
CompilerOutputPaths.getAnnotationPath(
projectFilesystem, JavaAbis.getSourceAbiJar(invokingRule))
.get(),
CompilerOutputPaths.getAnnotationPath(projectFilesystem, invokingRule).get()));
}
steps.add(
new JavacStep(pipeline, invokingRule, context.getSourcePathResolver(), projectFilesystem));
}
/**
* Same as {@link #getAttributePath(String, EntityType)} but adds an id attribute to the path is
* the last element is a reference attribute.
*
* @param queryRuleField query rule field name, e.g. grandparent.parent.child
* @param entityType entity type
* @param expandLabelInsteadOfId expand with label attribute instead of id attribute
* @return attribute path
* @throws UnknownAttributeException if no attribute exists for a query rule field name part
* @throws MolgenisQueryException if query rule field is an invalid attribute path
*/
public static List<Attribute> getAttributePathExpanded(
String queryRuleField, EntityType entityType, boolean expandLabelInsteadOfId) {
List<Attribute> attributePath = getAttributePath(queryRuleField, entityType);
List<Attribute> expandedAttributePath;
Attribute attribute = attributePath.get(attributePath.size() - 1);
if (attribute.hasRefEntity()) {
Attribute expandedAttribute;
if (expandLabelInsteadOfId) {
expandedAttribute = attribute.getRefEntity().getLabelAttribute();
} else {
expandedAttribute = attribute.getRefEntity().getIdAttribute();
}
@SuppressWarnings("UnstableApiUsage")
Builder<Attribute> builder = ImmutableList.builderWithExpectedSize(attributePath.size() + 1);
builder.addAll(attributePath);
builder.add(expandedAttribute);
expandedAttributePath = builder.build();
} else {
expandedAttributePath = attributePath;
}
return expandedAttributePath;
}
@SuppressWarnings("AutoBoxing")
@Test(timeOut = 2000L)
public void frontierIndexDoesNotCauseEndlessLoop()
{
final int expected = 4;
final List<Range<Integer>> ranges = new Builder<Range<Integer>>()
.add(Range.closedOpen(0, 3))
.add(Range.closedOpen(3, 7))
.add(Range.closedOpen(7, 16))
.add(Range.closedOpen(16, 18))
.add(Range.closedOpen(18, 20))
.build();
final LineCounter lineCounter = new LineCounter(ranges);
assertThat(lineCounter.binarySearch(18)).isEqualTo(expected);
}
public static ImmutableSortedSet<BuildRule> getSourceOnlyAbiRules(
ActionGraphBuilder graphBuilder, Iterable<BuildRule> inputs) {
ImmutableSortedSet.Builder<BuildRule> abiRules = ImmutableSortedSet.naturalOrder();
for (BuildRule input : inputs) {
if (input instanceof HasJavaAbi) {
HasJavaAbi hasAbi = (HasJavaAbi) input;
Optional<BuildTarget> abiJarTarget = hasAbi.getSourceOnlyAbiJar();
if (!abiJarTarget.isPresent()) {
abiJarTarget = hasAbi.getAbiJar();
}
if (abiJarTarget.isPresent()) {
BuildRule abiJarRule = graphBuilder.requireRule(abiJarTarget.get());
abiRules.add(abiJarRule);
}
}
}
return abiRules.build();
}
private void validateBuildIdConsoleWithLogLines(
SuperConsoleEventBusListener listener,
TestRenderingConsole renderingConsole,
long timeMs,
ImmutableList<String> lines,
ImmutableList<String> logLines) {
Builder<String> builder =
ImmutableList.builderWithExpectedSize(lines.size() + (printBuildId ? 1 : 0));
if (printBuildId) {
builder.add("Build UUID: 1234-5678");
}
builder.addAll(lines);
validateConsoleWithStdOutAndErr(
listener,
renderingConsole,
timeMs,
builder.build(),
logLines,
Optional.of(""),
Optional.of(""));
}
private ImmutableList<AddPathBestPath> selectBest(final long localAs, final int size, final int limit) {
// Scratch pool of offsets, we set them to true as we use them up.
final boolean[] offsets = new boolean[size];
final Builder<AddPathBestPath> builder = ImmutableList.builderWithExpectedSize(limit);
// This ends up being (limit * size) traversals of offsets[], but that should be fine, as it is a dense array.
// If this ever becomes a problem, we can optimize by having a AddPathSelector which remembers previous state,
// so that we can rewind it. That will allow us to not only skip offset searches, but also recomputing the
// (relatively) costly per-path state from scratch.
for (int search = 0; search < limit; ++search) {
final AddPathSelector selector = new AddPathSelector(localAs);
for (int offset = 0; offset < size; ++offset) {
if (!offsets[offset]) {
processOffset(selector, offset);
}
}
final AddPathBestPath result = selector.result();
LOG.trace("Path {} selected {}", search, result);
builder.add(result);
offsets[result.getOffset()] = true;
}
return builder.build();
}
@Override
public Collection<String> renameTableStatements(Table fromTable, Table toTable) {
String from = fromTable.getName();
String to = toTable.getName();
Builder<String> builder = ImmutableList.<String>builder();
builder.add("IF EXISTS (SELECT 1 FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'" + from + "_version_DF') AND type = (N'D')) exec sp_rename N'" + from + "_version_DF', N'" + to + "_version_DF'");
if (!primaryKeysForTable(fromTable).isEmpty()) {
builder.add("sp_rename N'" + from + "." + from + "_PK', N'" + to + "_PK', N'INDEX'");
}
builder.add("sp_rename N'" + from + "', N'" + to + "'");
return builder.build();
}
/**
* @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 " + schemaNamePrefix() + from.getName() + " RENAME TO " + to.getName());
if (!primaryKeysForTable(to).isEmpty()) {
builder.add(addPrimaryKeyConstraintStatement(to, namesOfColumns(primaryKeysForTable(to))));
}
return builder.build();
}
/**
* @see org.alfasoftware.morf.jdbc.SqlDialect#alterTableAddColumnStatements(org.alfasoftware.morf.metadata.Table, org.alfasoftware.morf.metadata.Column)
*/
@Override
public Collection<String> alterTableAddColumnStatements(Table table, Column column) {
ImmutableList.Builder<String> statements = ImmutableList.builder();
statements.add(
new StringBuilder().append("ALTER TABLE ").append(qualifiedTableName(table)).append(" ADD COLUMN ")
.append(column.getName()).append(' ').append(sqlRepresentationOfColumnType(column, true))
.toString()
);
if (StringUtils.isNotBlank(column.getDefaultValue()) && column.isNullable()) {
statements.add("UPDATE " + table.getName() + " SET " + column.getName() + " = " + getSqlFrom(new FieldLiteral(column.getDefaultValue(), column.getType())));
}
return statements.build();
}
@Override
public List<TransformationStep> toTransformationSteps(
Nat nat,
@Nullable Map<String, AddressBookEntry> addressBookEntryMap,
Ip interfaceIp,
Warnings warnings) {
checkArgument(
nat.getType() == SOURCE || nat.getType() == DESTINATION,
"Interface actions can only be used in source nat and dest nat");
TransformationType type = nat.getType().toTransformationType();
IpField ipField = nat.getType() == SOURCE ? IpField.SOURCE : IpField.DESTINATION;
ImmutableList.Builder<TransformationStep> builder = new Builder<>();
builder.add(new AssignIpAddressFromPool(type, ipField, interfaceIp, interfaceIp));
// PAT is always enabled for interface source NAT
if (type == SOURCE_NAT) {
builder.add(
new AssignPortFromPool(
type, PortField.SOURCE, nat.getDefaultFromPort(), nat.getDefaultToPort()));
}
return builder.build();
}
/**
* @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();
}
private void getContainersFromClassPath(Builder<IContainerHandle> list) {
// We know this is deprecated, it works for LW though, so access directly
URL[] sources = this.getClassPath();
if (sources != null) {
for (URL url : sources) {
try {
URI uri = url.toURI();
MixinServiceAbstract.logger.debug("Scanning {} for mixin tweaker", uri);
if (!"file".equals(uri.getScheme()) || !new File(uri).exists()) {
continue;
}
MainAttributes attributes = MainAttributes.of(uri);
String tweaker = attributes.get(Constants.ManifestAttributes.TWEAKER);
if (MixinServiceLaunchWrapper.MIXIN_TWEAKER_CLASS.equals(tweaker)) {
list.add(new ContainerHandleURI(uri));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
@Override
public List<String> deleteAllIds(final Collection<String> ids) {
if (ids.isEmpty()) {
return ImmutableList.of();
}
final BulkRequestBuilder bulk = client
.prepareBulk()
.setRefreshPolicy(policy.get());
for (final String id : ids) {
bulk.add(client.prepareDelete(index, type, id));
}
final BulkResponse response = bulk.execute().actionGet();
final ImmutableList.Builder<String> builder = ImmutableList.builder();
for (final BulkItemResponse item : response.getItems()) {
builder.add(item.getId());
}
return builder.build();
}
@VisibleForTesting
@Nonnull
static TableMetadata getMetadata() {
Builder<ColumnMetadata> b = ImmutableList.builder();
b.add(
new ColumnMetadata(COL_NODE, Schema.NODE, "Node name", true, false),
new ColumnMetadata(COL_MLAG_ID, Schema.STRING, "MLAG domain ID", true, false),
new ColumnMetadata(COL_MLAG_PEER_ADDRESS, Schema.IP, "Peer's IP address", false, true),
new ColumnMetadata(
COL_MLAG_PEER_INTERFACE,
Schema.INTERFACE,
"Local interface used for MLAG peering",
false,
true),
new ColumnMetadata(
COL_MLAG_LOCAL_INTERFACE,
Schema.INTERFACE,
"Local interface used as source-interface for MLAG peering",
false,
true));
return new TableMetadata(b.build());
}
/**
* Collects the list of {@link AnnotatedElement}s which are to be used to find annotations.
*/
private static List<AnnotatedElement> resolveTargetElements(AnnotatedElement element,
EnumSet<FindOption> findOptions) {
final List<AnnotatedElement> elements;
if (findOptions.contains(FindOption.LOOKUP_SUPER_CLASSES) && element instanceof Class) {
final Class<?> superclass = ((Class<?>) element).getSuperclass();
if ((superclass == null || superclass == Object.class) &&
((Class<?>) element).getInterfaces().length == 0) {
elements = ImmutableList.of(element);
} else {
final Builder<AnnotatedElement> collector = new Builder<>();
collectSuperClasses((Class<?>) element, collector,
findOptions.contains(FindOption.COLLECT_SUPER_CLASSES_FIRST));
elements = collector.build();
}
} else {
elements = ImmutableList.of(element);
}
return elements;
}
@Override
public List<Stmt> getStmts() {
List<Stmt> result = stmts;
if (stmts == null) {
final ImmutableList.Builder<Stmt> builder = ImmutableList.builder();
addClocksNonNegative(builder, getClockVars());
addInvariants(builder, getSourceLocs());
addSync(builder, emitEdge, recvEdge);
addGuards(builder, emitEdge);
addGuards(builder, recvEdge);
addUpdates(builder, emitEdge);
addUpdates(builder, recvEdge);
addInvariants(builder, targetLocs);
if (shouldApplyDelay(getTargetLocs())) {
addDelay(builder, getClockVars());
}
result = builder.build();
stmts = result;
}
return result;
}
private NodeIdentifierWithPredicates readNormalizedNodeWithPredicates() throws IOException {
final QName qname = readQName();
final int count = input.readInt();
switch (count) {
case 0:
return NodeIdentifierWithPredicates.of(qname);
case 1:
return NodeIdentifierWithPredicates.of(qname, readQName(), readObject());
default:
// ImmutableList is used by ImmutableOffsetMapTemplate for lookups, hence we use that.
final Builder<QName> keys = ImmutableList.builderWithExpectedSize(count);
final Object[] values = new Object[count];
for (int i = 0; i < count; i++) {
keys.add(readQName());
values[i] = readObject();
}
return NodeIdentifierWithPredicates.of(qname, ImmutableOffsetMapTemplate.ordered(keys.build())
.instantiateWithValues(values));
}
}
@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();
}
/**
* Returns all annotations of the {@code annotationType} searching from the specified {@code element}.
* The search range depends on the specified {@link FindOption}s.
*
* @param element the {@link AnnotatedElement} to find annotations
* @param annotationType the type of the annotation to find
* @param findOptions the options to be applied when finding annotations
*/
static <T extends Annotation> List<T> find(AnnotatedElement element, Class<T> annotationType,
EnumSet<FindOption> findOptions) {
requireNonNull(element, "element");
requireNonNull(annotationType, "annotationType");
final Builder<T> builder = new Builder<>();
// Repeatable is not a repeatable. So the length of the returning array is 0 or 1.
final Repeatable[] repeatableAnnotations = annotationType.getAnnotationsByType(Repeatable.class);
final Class<? extends Annotation> containerType =
repeatableAnnotations.length > 0 ? repeatableAnnotations[0].value() : null;
for (final AnnotatedElement e : resolveTargetElements(element, findOptions)) {
for (final Annotation annotation : e.getDeclaredAnnotations()) {
if (findOptions.contains(FindOption.LOOKUP_META_ANNOTATIONS)) {
findMetaAnnotations(builder, annotation, annotationType, containerType);
}
collectAnnotations(builder, annotation, annotationType, containerType);
}
}
return builder.build();
}
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();
}
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();
}
@Override
public ImmutableList<Profile> findAllByName(Iterable<String> names) throws IOException, InterruptedException {
CompletionService<List<Profile>> completion = new ExecutorCompletionService<>(executorService);
int count = 0;
for (final List<String> partition : Iterables.partition(names, getEffectiveProfilesPerJob())) {
count++;
completion.submit(() -> resolver.findAllByName(partition));
}
Builder<Profile> builder = ImmutableList.builder();
for (int i = 0; i < count; i++) {
try {
builder.addAll(completion.take().get());
} catch (ExecutionException e) {
if (e.getCause() instanceof IOException) {
throw (IOException) e.getCause();
} else {
throw new RuntimeException("Error occurred during the operation", e);
}
}
}
return builder.build();
}
/**
* Create a palette
*
* @param startingColor
* the source color that will be diluted until it faded to white.
* @param nbColors
* the number of colors to use
* @return the palette provider
*/
public static IPaletteProvider create(RGBAColor startingColor, int nbColors) {
float[] components = startingColor.getHSBA();
float stepBright = (1.0f - components[2]) / nbColors; // brightness steps
float stepSat = (components[1]) / nbColors; // brightness steps
float hue = components[0];
float brightness = 1.0f;
float saturation = 0.0f;
ImmutableList.Builder<RGBAColor> builder = new Builder<>();
for (int i = 0; i < nbColors; i++) {
builder.add(RGBAColor.fromHSBA(hue, saturation, brightness, components[3]));
saturation += stepSat;
brightness -= stepBright;
}
return new SequentialPaletteProvider(builder.build());
}
@Override
public List<Stmt> getStmts() {
List<Stmt> result = stmts;
if (stmts == null) {
final ImmutableList.Builder<Stmt> builder = ImmutableList.builder();
addClocksNonNegative(builder, getClockVars());
addInvariants(builder, getSourceLocs());
addGuards(builder, edge);
addUpdates(builder, edge);
addInvariants(builder, targetLocs);
if (shouldApplyDelay(getTargetLocs())) {
addDelay(builder, getClockVars());
}
result = builder.build();
stmts = result;
}
return result;
}
@VisibleForTesting
static DotnetFramework resolveFramework(FileSystem osFilesystem, FrameworkVersion version) {
Builder<Path> builder = ImmutableList.builder();
for (String dir : version.getDirectories()) {
Path frameworkDir = osFilesystem.getPath(dir);
if (!Files.exists(frameworkDir)) {
throw new HumanReadableException(
String.format("Required dir %s for %s was not found", dir, version));
} else if (!Files.isDirectory(frameworkDir)) {
throw new HumanReadableException(
"Resolved framework directory is not a directory: %s", frameworkDir);
} else {
builder.add(frameworkDir);
}
}
return new DotnetFramework(version, builder.build());
}
/**
* Returns the number of lines created. If the number of lines to be created exceeds the given
* {@code maxLines}, return early and ignore the other lines that were to be rendered. See also
* {@code #renderLinesWithMaybeCompression}.
*
* @param numLinesAlreadyRendered the number of lines already previously rendered; used to
* calculate if {@code maxLines} has been reached
* @param renderer the renderer to use for rendering lines
* @param lines the builder to add the rendered lines to
* @param maxLines the maximum number of lines to render
*/
public int renderLinesWithMaybeTruncation(
int numLinesAlreadyRendered,
MultiStateRenderer renderer,
ImmutableList.Builder<String> lines,
int maxLines) {
int numNewLinesRendered = 0;
for (long id : renderer.getSortedIds(/* sortByTime= */ false)) {
if (numLinesAlreadyRendered + numNewLinesRendered >= maxLines) {
return numNewLinesRendered;
}
lines.add(renderer.renderStatusLine(id));
numNewLinesRendered++;
}
return numNewLinesRendered;
}
@Subscribe
public void testRunStarted(TestRunEvent.Started event) {
boolean set = testRunStarted.compareAndSet(null, event);
Preconditions.checkState(set, "Test run should not start while test run in progress");
ImmutableList.Builder<String> builder = ImmutableList.builder();
testFormatter.runStarted(
builder,
event.isRunAllTests(),
event.getTestSelectorList(),
event.shouldExplainTestSelectorList(),
event.getTargetNames(),
TestResultFormatter.FormatMode.AFTER_TEST_RUN);
synchronized (testReportBuilder) {
testReportBuilder.addAll(builder.build());
}
}
public static List<Endpoint> sampleEndpoints(int count) {
final int[] ports = unusedPorts(count);
final Builder<Endpoint> builder = ImmutableList.builder();
for (int i = 0; i < count; i++) {
builder.add(Endpoint.of("127.0.0.1", ports[i]).withWeight(random.nextInt(10000) + 1));
}
return builder.build();
}
private static HeaderSymlinkTree getHeaderSymlinkTree(
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
ActionGraphBuilder graphBuilder,
CxxPlatform cxxPlatform,
Collection<CxxPreprocessorInput> cxxPreprocessorInputs,
ImmutableMap<Path, SourcePath> headers) {
ImmutableMap.Builder<Path, SourcePath> allHeaders = ImmutableMap.builder();
// scan CxxDeps for headers and add them to allHeaders
HashMap<Path, SourcePath> cxxDepsHeaders = new HashMap<Path, SourcePath>();
cxxPreprocessorInputs.stream()
.flatMap(input -> input.getIncludes().stream())
.filter(header -> header instanceof CxxSymlinkTreeHeaders)
.flatMap(header -> ((CxxSymlinkTreeHeaders) header).getNameToPathMap().entrySet().stream())
.forEach(entry -> cxxDepsHeaders.put(entry.getKey(), entry.getValue()));
allHeaders.putAll(cxxDepsHeaders);
// add headers defined within the cgo_library rule
allHeaders.putAll(headers);
return CxxDescriptionEnhancer.createHeaderSymlinkTree(
buildTarget,
projectFilesystem,
graphBuilder,
cxxPlatform,
allHeaders.build(),
HeaderVisibility.PUBLIC,
true);
}