下面列出了com.google.common.collect.ImmutableMap#Builder ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private <K> Map<K, FixedLengthSliceInput> readSmallDiskRanges(Map<K, DiskRange> diskRanges)
throws IOException
{
if (diskRanges.isEmpty()) {
return ImmutableMap.of();
}
Iterable<DiskRange> mergedRanges = mergeAdjacentDiskRanges(diskRanges.values(), maxMergeDistance, maxBufferSize);
// read ranges
Map<DiskRange, byte[]> buffers = new LinkedHashMap<>();
for (DiskRange mergedRange : mergedRanges) {
// read full range in one request
byte[] buffer = new byte[mergedRange.getLength()];
readFully(mergedRange.getOffset(), buffer);
buffers.put(mergedRange, buffer);
}
ImmutableMap.Builder<K, FixedLengthSliceInput> slices = ImmutableMap.builder();
for (Entry<K, DiskRange> entry : diskRanges.entrySet()) {
slices.put(entry.getKey(), getDiskRangeSlice(entry.getValue(), buffers).getInput());
}
return slices.build();
}
private ImmutableMap<Field, Boolean> parameterFieldsFromFields(Class<?> clazz) {
Field[] fields = clazz.getDeclaredFields();
ImmutableMap.Builder<Field, Boolean> fieldsBuilder =
ImmutableMap.builderWithExpectedSize(fields.length);
Field ignoredField = null;
for (Field field : fields) {
field.setAccessible(true);
// static fields can be ignored and volatile fields are used for handling lazy field states.
if (Modifier.isStatic(field.getModifiers()) || Modifier.isVolatile(field.getModifiers())) {
ignoredField = field;
continue;
}
boolean isLazy = ignoredField != null && ignoredField.getName().endsWith("LAZY_INIT_BIT");
fieldsBuilder.put(field, isLazy);
}
return fieldsBuilder.build();
}
@Override
public SnapshotsInProgress readFrom(StreamInput in) throws IOException {
Entry[] entries = new Entry[in.readVInt()];
for (int i = 0; i < entries.length; i++) {
SnapshotId snapshotId = SnapshotId.readSnapshotId(in);
boolean includeGlobalState = in.readBoolean();
State state = State.fromValue(in.readByte());
int indices = in.readVInt();
List<String> indexBuilder = new ArrayList<>();
for (int j = 0; j < indices; j++) {
indexBuilder.add(in.readString());
}
long startTime = in.readLong();
ImmutableMap.Builder<ShardId, ShardSnapshotStatus> builder = ImmutableMap.builder();
int shards = in.readVInt();
for (int j = 0; j < shards; j++) {
ShardId shardId = ShardId.readShardId(in);
String nodeId = in.readOptionalString();
State shardState = State.fromValue(in.readByte());
builder.put(shardId, new ShardSnapshotStatus(nodeId, shardState));
}
entries[i] = new Entry(snapshotId, includeGlobalState, state, Collections.unmodifiableList(indexBuilder), startTime, builder.build());
}
return new SnapshotsInProgress(entries);
}
public static ImmutableMap<String, Method> getServiceMethods(String serviceName) {
ImmutableMap<String, Method> methodMap = serviceMethodsMap.get(serviceName);
if (methodMap == null) {
synchronized (ProviderInfoRepository.class) {
methodMap = serviceMethodsMap.get(serviceName);
if (methodMap == null) {
Class interfaceClazz = serviceIfaceMap.get(serviceName);
ImmutableMap.Builder<String, Method> methodMapBuilder = ImmutableMap.builder();
for (Method method : interfaceClazz.getMethods()) {
methodMapBuilder.put(MethodUtil.generateMethodSignatureNoIfacePrefix(method), method);
}
methodMap = methodMapBuilder.build();
serviceMethodsMap.putIfAbsent(serviceName, methodMap);
}
}
}
return methodMap;
}
/**
* Return a map with the Cursor and scope for each key in the keyMap. If the key from the keyMap
* does not have an existing cursor, create a new cursor with a default cursorTime of the first of
* next month.
*/
private ImmutableMap<Cursor, String> defaultNullCursorsToNextMonthAndAddToMap(
Map<Key<Cursor>, Registry> keyMap, CursorType type, Map<Key<Cursor>, Cursor> cursorMap) {
ImmutableMap.Builder<Cursor, String> cursors = new ImmutableMap.Builder<>();
keyMap.forEach(
(key, registry) -> {
// Cursor time is defaulted to the first of next month since a new tld will not yet have a
// report staged for upload.
Cursor cursor =
cursorMap.getOrDefault(
key,
Cursor.create(
type,
clock.nowUtc().withDayOfMonth(1).withTimeAtStartOfDay().plusMonths(1),
registry));
if (!cursorMap.containsValue(cursor)) {
tm().transact(() -> ofy().save().entity(cursor));
}
cursors.put(cursor, registry.getTldStr());
});
loadAndCompareAll(cursors.build(), type);
return cursors.build();
}
/**
* Evaluate the script and return true if this job should be forced to execute via agent, false if it should be
* forced to execute in embedded mode, null if the script decides not explicitly flag this job for one or the other
* execution mode.
*
* @param jobRequest the job request
* @return An optional boolean value
* @throws ScriptNotConfiguredException if the script is not yet successfully loaded and compiled
* @throws ScriptExecutionException if the script evaluation produces an error
*/
public Optional<Boolean> forceAgentExecution(
final JobRequest jobRequest
) throws ScriptNotConfiguredException, ScriptExecutionException {
final ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
try {
builder.put(JOB_REQUEST_BINDING, this.objectMapper.writeValueAsString(jobRequest));
} catch (final JsonProcessingException e) {
throw new ScriptExecutionException("Failed to convert parameter: " + JOB_REQUEST_BINDING, e);
}
final Map<String, Object> scriptParameters = builder.build();
final Object scriptOutput = this.evaluateScript(scriptParameters);
log.debug("Execution mode selector returned: {} for job request: {}", scriptOutput, jobRequest);
if (scriptOutput == null) {
return Optional.empty();
} else if (scriptOutput instanceof Boolean) {
return Optional.of((Boolean) scriptOutput);
}
throw new ScriptExecutionException("Script returned unexpected value: " + scriptOutput);
}
/**
* @return A mapping from each breakdown type to inner maps. These inner maps map from the
* categories for that breakdown type to confusion matrices for only that category.
*/
public static <SignatureType, ProvenanceType>
ImmutableMap<String, BrokenDownProvenancedConfusionMatrix<SignatureType, ProvenanceType>>
computeBreakdowns(
ProvenancedConfusionMatrix<ProvenanceType> corpusConfusionMatrix,
Map<String, Function<? super ProvenanceType, SignatureType>> breakdowns,
Ordering<SignatureType> resultKeyOrdering) {
final ImmutableMap.Builder<String, BrokenDownProvenancedConfusionMatrix<SignatureType, ProvenanceType>>
printModes =
ImmutableMap.builder();
for (final Map.Entry<String, Function<? super ProvenanceType, SignatureType>> breakdownEntry : breakdowns
.entrySet()) {
printModes.put(breakdownEntry.getKey(),
corpusConfusionMatrix.breakdown(breakdownEntry.getValue(),
resultKeyOrdering));
}
return printModes.build();
}
/**
* Builds a map of all store impls using the provided factory.
* @param impls a set of implementations of the storeCreationFunction.
* @param factory StoreBuildingFactory for building KVStore implementations.
* @return a map of all kv store impls with the provided factory.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static ImmutableMap<Class<? extends StoreCreationFunction<?, ?, ?>>, KVStore<?, ?>> buildStores(
Set<Class<? extends StoreCreationFunction>> impls, StoreBuildingFactory factory) {
ImmutableMap.Builder builder = ImmutableMap.<Class<? extends StoreCreationFunction<?, ?, ?>>, KVStore<?, ?>>builder();
for(Class<? extends StoreCreationFunction> functionClass : impls) {
try {
final KVStore<?, ?> store = functionClass.newInstance().build(factory);
builder.put(functionClass, store);
} catch (Exception e) {
logger.warn("Unable to load StoreCreationFunction {}", functionClass.getSimpleName(), e);
}
}
final ImmutableMap<Class<? extends StoreCreationFunction<?, ?, ?>>, KVStore<?, ?>> map = builder.build();
logger.debug("Loaded the following StoreCreationFunctions: {}.", map.keySet());
return map;
}
private static Map<String, Object> mapOf(Annotation annotation, Class<?> annotatedClass, ClassesByTypeName importedClasses) {
ImmutableMap.Builder<String, Object> result = ImmutableMap.builder();
for (Method method : annotation.annotationType().getDeclaredMethods()) {
result.put(method.getName(), get(annotation, annotatedClass, method.getName(), importedClasses));
}
return result.build();
}
private static ImmutableMap<TokenKind, BuildToken> createMap() {
ImmutableMap.Builder<TokenKind, BuildToken> builder = ImmutableMap.builder();
for (TokenKind kind : TokenKind.values()) {
builder.put(kind, new BuildToken(kind));
}
return builder.build();
}
/**
* Helper method to create map of key, value pairs, the value is a Java type object.
* @param args
* @return
*/
@VisibleForTesting
public void createStorageOptionsMap(final SqlNodeList args) {
if (args == null || args.size() == 0) {
return;
}
final ImmutableMap.Builder<String, Object> storageOptions = ImmutableMap.builder();
for (SqlNode operand : args) {
if (operand.getKind() != SqlKind.ARGUMENT_ASSIGNMENT) {
throw UserException.unsupportedError()
.message("Unsupported argument type. Only assignment arguments (param => value) are supported.")
.build(logger);
}
final List<SqlNode> operandList = ((SqlCall) operand).getOperandList();
final String name = ((SqlIdentifier) operandList.get(1)).getSimple();
SqlNode literal = operandList.get(0);
if (!(literal instanceof SqlLiteral)) {
throw UserException.unsupportedError()
.message("Only literals are accepted for storage option values")
.build(logger);
}
Object value = ((SqlLiteral)literal).getValue();
if (value instanceof NlsString) {
value = ((NlsString)value).getValue();
}
storageOptions.put(name, value);
}
this.storageOptionsMap = storageOptions.build();
}
private void defineTestMethods() throws Exception {
ImmutableMap.Builder<String, Object> env = ImmutableMap.builder();
Starlark.addMethods(env, this);
for (Map.Entry<String, Object> entry : env.build().entrySet()) {
ev.update(entry.getKey(), entry.getValue());
}
}
public Map<String, String> getFieldValuesMap() {
if (fieldValuesMap == null) {
synchronized (this) {
if (fieldValuesMap == null) {
ImmutableMap.Builder<String, String> fieldMapBuilder = ImmutableMap.builder();
fieldMapBuilder.put("customer", customer);
fieldMapBuilder.put("distanceView", distanceView);
fieldValuesMap = fieldMapBuilder.build();
}
}
}
return fieldValuesMap;
}
public Map<String, String> getFieldValuesMap() {
if (fieldValuesMap == null) {
synchronized (this) {
if (fieldValuesMap == null) {
ImmutableMap.Builder<String, String> fieldMapBuilder = ImmutableMap.builder();
fieldMapBuilder.put("customer", customer);
fieldMapBuilder.put("campaign", campaign);
fieldValuesMap = fieldMapBuilder.build();
}
}
}
return fieldValuesMap;
}
public TypeUtil(ParserEnvironment env, ElementUtil elementUtil) {
this.javacElements = env.elementUtilities();
this.javacTypes = env.typeUtilities();
this.elementUtil = elementUtil;
javaObject = javacElements.getTypeElement("java.lang.Object");
javaString = javacElements.getTypeElement("java.lang.String");
javaClass = javacElements.getTypeElement("java.lang.Class");
javaNumber = javacElements.getTypeElement("java.lang.Number");
javaThrowable = javacElements.getTypeElement("java.lang.Throwable");
TypeElement javaCloneable = javacElements.getTypeElement("java.lang.Cloneable");
ImmutableMap.Builder<TypeElement, TypeElement> typeMapBuilder =
ImmutableMap.<TypeElement, TypeElement>builder()
.put(javaObject, NS_OBJECT)
.put(javaString, NS_STRING)
.put(javaClass, IOS_CLASS)
.put(javaNumber, NS_NUMBER)
.put(javaCloneable, NS_COPYING);
TypeElement typeNSException = javacElements.getTypeElement("com.google.j2objc.NSException");
TypeElement typeNSFastEnumeration =
javacElements.getTypeElement("com.google.j2objc.NSFastEnumeration");
// Types could be null if the user is not using jre_emul.jar as the boot path.
if (typeNSException != null) {
typeMapBuilder.put(typeNSException, NS_EXCEPTION);
}
if (typeNSFastEnumeration != null) {
typeMapBuilder.put(typeNSFastEnumeration, NS_FASTENUMERATION);
}
javaToObjcTypeMap = typeMapBuilder.build();
}
private static void init(ImmutableMap.Builder<AbstractElement, String> builder, Bug381381TestLanguageGrammarAccess grammarAccess) {
builder.put(grammarAccess.getCopyFieldNameToVariableStmtAccess().getGroup(), "rule__CopyFieldNameToVariableStmt__Group__0");
builder.put(grammarAccess.getCopyFieldNameToVariableStmtAccess().getGroup_1_0(), "rule__CopyFieldNameToVariableStmt__Group_1_0__0");
builder.put(grammarAccess.getCopyFieldNameToVariableStmtAccess().getGroup_1_1(), "rule__CopyFieldNameToVariableStmt__Group_1_1__0");
builder.put(grammarAccess.getCopyFieldNameToVariableStmtAccess().getGroup_1_2(), "rule__CopyFieldNameToVariableStmt__Group_1_2__0");
builder.put(grammarAccess.getModelAccess().getStmtAssignment(), "rule__Model__StmtAssignment");
builder.put(grammarAccess.getCopyFieldNameToVariableStmtAccess().getLineAssignment_1_0_4(), "rule__CopyFieldNameToVariableStmt__LineAssignment_1_0_4");
builder.put(grammarAccess.getCopyFieldNameToVariableStmtAccess().getColumnAssignment_1_0_6(), "rule__CopyFieldNameToVariableStmt__ColumnAssignment_1_0_6");
builder.put(grammarAccess.getCopyFieldNameToVariableStmtAccess().getNameAssignment_1_1_3(), "rule__CopyFieldNameToVariableStmt__NameAssignment_1_1_3");
builder.put(grammarAccess.getCopyFieldNameToVariableStmtAccess().getUnorderedGroup_1(), "rule__CopyFieldNameToVariableStmt__UnorderedGroup_1");
}
private ImmutableMap.Builder<String, Object> dqlPlanNode(AbstractProjectionsPhase phase, ImmutableMap.Builder<String, Object> b) {
if (phase.hasProjections()) {
b.put("projections", projections(phase.projections()));
}
return b;
}
@Inject
public NameMappings(Bug348199TestLanguageGrammarAccess grammarAccess) {
ImmutableMap.Builder<AbstractElement, String> builder = ImmutableMap.builder();
init(builder, grammarAccess);
this.mappings = builder.build();
}
@Inject
public NameMappings(PartialContentAssistTestLanguageGrammarAccess grammarAccess) {
ImmutableMap.Builder<AbstractElement, String> builder = ImmutableMap.builder();
init(builder, grammarAccess);
this.mappings = builder.build();
}
private RelationPlan createAnalyzePlan(Analysis analysis, Analyze analyzeStatement)
{
TableHandle targetTable = analysis.getAnalyzeTarget().get();
// Plan table scan
Map<String, ColumnHandle> columnHandles = metadata.getColumnHandles(session, targetTable);
ImmutableList.Builder<Symbol> tableScanOutputs = ImmutableList.builder();
ImmutableMap.Builder<Symbol, ColumnHandle> symbolToColumnHandle = ImmutableMap.builder();
ImmutableMap.Builder<String, Symbol> columnNameToSymbol = ImmutableMap.builder();
TableMetadata tableMetadata = metadata.getTableMetadata(session, targetTable);
for (ColumnMetadata column : tableMetadata.getColumns()) {
Symbol symbol = symbolAllocator.newSymbol(column.getName(), column.getType());
tableScanOutputs.add(symbol);
symbolToColumnHandle.put(symbol, columnHandles.get(column.getName()));
columnNameToSymbol.put(column.getName(), symbol);
}
TableStatisticsMetadata tableStatisticsMetadata = metadata.getStatisticsCollectionMetadata(
session,
targetTable.getCatalogName().getCatalogName(),
tableMetadata.getMetadata());
TableStatisticAggregation tableStatisticAggregation = statisticsAggregationPlanner.createStatisticsAggregation(tableStatisticsMetadata, columnNameToSymbol.build());
StatisticAggregations statisticAggregations = tableStatisticAggregation.getAggregations();
List<Symbol> groupingSymbols = statisticAggregations.getGroupingSymbols();
PlanNode planNode = new StatisticsWriterNode(
idAllocator.getNextId(),
new AggregationNode(
idAllocator.getNextId(),
TableScanNode.newInstance(idAllocator.getNextId(), targetTable, tableScanOutputs.build(), symbolToColumnHandle.build()),
statisticAggregations.getAggregations(),
singleGroupingSet(groupingSymbols),
ImmutableList.of(),
AggregationNode.Step.SINGLE,
Optional.empty(),
Optional.empty()),
new StatisticsWriterNode.WriteStatisticsReference(targetTable),
symbolAllocator.newSymbol("rows", BIGINT),
tableStatisticsMetadata.getTableStatistics().contains(ROW_COUNT),
tableStatisticAggregation.getDescriptor());
return new RelationPlan(planNode, analysis.getScope(analyzeStatement), planNode.getOutputSymbols());
}