下面列出了怎么用com.google.common.collect.ImmutableMap.Builder的API类实例代码及写法,或者点击链接到github查看源代码。
private static ImmutableList<TypeMember> determineMembersToUpdate(final BaseType baseType,
final Set<BaseType> affectedTypes) {
final ImmutableList.Builder<TypeMember> builder = ImmutableList.<TypeMember>builder();
boolean includeMember = false;
for (TypeMember member : baseType) {
if (affectedTypes.contains(member.getBaseType())) {
// All members after the first one whose base type is contained in affectedTypes need
// to be updated.
if (!includeMember) {
includeMember = true;
}
}
if (includeMember) {
builder.add(member);
}
}
return builder.build();
}
private static Map<Field, AnnotatedValueResolver> findFields(
List<AnnotatedValueResolver> constructorAnnotatedResolvers,
Map<Method, List<AnnotatedValueResolver>> methods,
BeanFactoryId beanFactoryId, List<RequestObjectResolver> objectResolvers) {
final Set<AnnotatedValueResolver> uniques = uniqueResolverSet();
uniques.addAll(constructorAnnotatedResolvers);
methods.values().forEach(uniques::addAll);
final Builder<Field, AnnotatedValueResolver> builder = ImmutableMap.builder();
final Set<Field> fields = getAllFields(beanFactoryId.type);
for (final Field field : fields) {
final List<RequestConverter> converters =
AnnotationUtil.findDeclared(field, RequestConverter.class);
final AnnotatedValueResolver resolver =
AnnotatedValueResolver.ofBeanField(field, beanFactoryId.pathParams,
addToFirstIfExists(objectResolvers, converters));
if (resolver != null) {
if (uniques.add(resolver)) {
builder.put(field, resolver);
} else {
warnDuplicateResolver(resolver, field.toGenericString());
}
}
}
return builder.build();
}
@Override
Builder<String, Object> serialize(Builder<String, Object> builder) {
super.serialize(builder);
if (hasTitle()) {
builder.put(BOOK_TITLE.BUKKIT, title);
}
if (hasAuthor()) {
builder.put(BOOK_AUTHOR.BUKKIT, author);
}
if (hasPages()) {
List<String> pagesString = new ArrayList<String>();
for (ITextComponent comp : pages) {
pagesString.add(CraftChatMessage.fromComponent(comp));
}
builder.put(BOOK_PAGES.BUKKIT, pagesString);
}
if (generation != null) {
builder.put(GENERATION.BUKKIT, generation);
}
return builder;
}
private Builder<String, Object> makeTemplateParams(
DeploymentPackageInput input, ImageInfo imageInfo) {
Builder<String, Object> params = ImmutableMap.builder();
params.put("solutionId", input.getSolutionId());
if (!input.getPartnerId().isEmpty()) {
params.put("partnerId", input.getPartnerId());
}
if (input.hasPartnerInfo()) {
params.put("partnerInfo", input.getPartnerInfo());
}
if (input.hasSolutionInfo()) {
params.put("solutionInfo", input.getSolutionInfo());
}
if (!Strings.isNullOrEmpty(input.getSpec().getVersion())) {
params.put("templateVersion", input.getSpec().getVersion());
}
params.put("descriptionYaml", makeDescriptionYaml(input, imageInfo));
return params;
}
@Override
public Map<String, String> getFields() {
Map<String, String> map = fFields;
if (map == null) {
byte[] array = Arrays.copyOfRange(fPayload.array(), fPayload.arrayOffset(), fPayload.arrayOffset() + fPayload.limit());
Builder<String, String> builder = ImmutableMap.<@NonNull String, @NonNull String> builder()
.put("Binary", ConversionHelper.bytesToHex(array, true)); //$NON-NLS-1$
try {
String s = new String(array, "UTF-8"); //$NON-NLS-1$
builder.put("Character", s); //$NON-NLS-1$
} catch (UnsupportedEncodingException e) {
// Do nothing. The string won't be added to the map anyway.
}
fFields = builder.build();
return fFields;
}
return map;
}
private void introspectWebServiceMethod(Builder<WebPath, Handler> builder, String httpMethod, String basePath,
Object webService, Method method) {
String path = basePath;
Path methodPath = method.getAnnotation(Path.class);
if (methodPath != null) {
path = Joiner.on("/").join(Arrays.asList(basePath, methodPath.value()));
}
path = CharMatcher.is('/').collapseFrom(path, '/');
WebPath webPath = new WebPath(httpMethod, path);
logger.log(Level.FINEST, format("HTTP {0} {1} -> {2}.{3}", httpMethod, path,
webService.getClass().getSimpleName(), method.getName()));
builder.put(webPath, new Handler(webService, method));
}
protected void createUserData(EObject eObject, ImmutableMap.Builder<String, String> userData) {
if (eObject instanceof JvmDeclaredType) {
userData.put(SIGNATURE_HASH_KEY, hashProvider.getHash((JvmDeclaredType) eObject));
if (eObject.eContainer() != null) {
userData.put(IS_NESTED_TYPE, Boolean.TRUE.toString());
}
}
if (eObject instanceof JvmGenericType) {
JvmGenericType genericType = (JvmGenericType) eObject;
if (genericType.isInterface())
userData.put(IS_INTERFACE, Boolean.TRUE.toString());
if (!genericType.getTypeParameters().isEmpty()) {
String result = "<";
for (Iterator<JvmTypeParameter> iterator = genericType.getTypeParameters().iterator(); iterator.hasNext();) {
JvmTypeParameter type = iterator.next();
result += type.getSimpleName();
if (iterator.hasNext()) {
result += ",";
}
}
result +=">";
userData.put(TYPE_PARAMETERS, result);
}
}
}
@Override
public TempBlob ingest(final InputStream in,
@Nullable final String contentType,
final Iterable<HashAlgorithm> hashing)
{
Optional<ClientInfo> clientInfo = facet.clientInfo();
Builder<String, String> tempHeaders = ImmutableMap.builder();
tempHeaders.put(TEMPORARY_BLOB_HEADER, "");
tempHeaders.put(REPO_NAME_HEADER, facet.repository().getName());
tempHeaders.put(BLOB_NAME_HEADER, "temp");
tempHeaders.put(CREATED_BY_HEADER, clientInfo.map(ClientInfo::getUserid).orElse("system"));
tempHeaders.put(CREATED_BY_IP_HEADER, clientInfo.map(ClientInfo::getRemoteIP).orElse("system"));
tempHeaders.put(CONTENT_TYPE_HEADER, ofNullable(contentType).orElse(APPLICATION_OCTET_STREAM));
MultiHashingInputStream hashingStream = new MultiHashingInputStream(hashing, in);
Blob blob = facet.stores().blobStore.create(hashingStream, tempHeaders.build());
return new TempBlob(blob, hashingStream.hashes(), true, facet.stores().blobStore);
}
/**
* 获取未完成的todos
*
* @param companyId
* @param userId
* @param model
* @return
*/
@RequestMapping(value = "/{companyId}/user/{userId}/open_todos", method = RequestMethod.GET)
@Interceptors({ CompanyMemberRequired.class, UserChecking.class })
@ResponseBody
public Map<String, Object> viewUserOpenTodos(@PathVariable int companyId, @PathVariable int userId, Model model) {
Builder<String, Object> builder = ImmutableMap.builder();
Map<Integer, String> projectIdToName = getProjectIdAndNameByCompanyId(companyId);
builder.put("projectsName", projectIdToName);
List<Integer> projectList = getProjectListOfCurrentUser(companyId);
List<Todolist> todolists = todoService.getOpenTodosByUser(userId, projectList);
List<TodolistDTO> todolistDto = Lists.transform(todolists, TodolistTransform.TODOLIST_DTO_ALL_FUNCTION);
builder.put("uncompletedTodos", todolistDto);
Map<Integer, List<User>> users = userService.getAllProjectUsersInCompany(companyId);
Map<Integer, List<UserDTO>> userDtos = makeUserUncompletedTodosMapSerilizable(users);
builder.put("userDtos", userDtos);
UserDTO userDto = UserTransform.userToUserDTO(userService.getById(userId));
builder.put("user", userDto);
return builder.build();
}
/**
* Set expectations on the mocks, with a typical set of checks.
*/
private void mockValidatorsWithChecks() {
when(mockCheckValidatorRegistry.getValidators()).thenReturn(mockValidators);
for (int validator = 0; NUM_VALIDATORS > validator; ++validator) {
final Builder<String, String> builder = ImmutableMap.<String, String> builder();
for (int check = 0; NUM_CHECKS_PER_VALIDATOR > check; ++check) {
builder.put(ISSUE_CODES[validator][check], LABELS[validator][check]);
}
when(mockValidators.get(validator).getIssueCodeToLabelMap()).thenReturn(builder.build());
}
}
@Override
Builder<String, Object> serialize(Builder<String, Object> builder) {
super.serialize(builder);
if (hasEffects()) {
builder.put(EXPLOSIONS.BUKKIT, ImmutableList.copyOf(effects));
}
if (hasPower()) {
builder.put(FLIGHT.BUKKIT, power);
}
return builder;
}
/**
* Throws an {@code UnsupportedOperationException}.
*
* @since 19.0
* @deprecated Unsupported by ImmutableSortedMap.Builder.
*/
@CanIgnoreReturnValue
@Beta
@Override
@Deprecated
public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
throw new UnsupportedOperationException("Not available on ImmutableSortedMap.Builder");
}
/**
* 获取完成的steps
*
* @param companyId
* @param userId
* @param until
* @return
*/
@RequestMapping(value = "/{companyId}/user/{userId}/completedSteps", method = RequestMethod.GET)
@Interceptors({ CompanyMemberRequired.class, UserChecking.class })
@ResponseBody
public Map<String, Object> viewUserCompletedSteps(@PathVariable int companyId, @PathVariable int userId,
@RequestParam(value = "until", required = false) @DateTimeFormat(iso = ISO.DATE) Date until) {
Builder<String, Object> builder = ImmutableMap.builder();
DateTime dt = until == null ? new DateTime() : new DateTime(until);
until = dt.withTime(0, 0, 0, 0).plusDays(1).plusMillis(-1).toDate();
List<Integer> projectList = getProjectListOfCurrentUser(companyId);
TreeMap<Date, Map<Integer, List<Step>>> map = stepService.getCompletedStepsGroupByDateByUser(companyId, userId,
projectList, until, PER_PAGE);
TreeMap<String, Map<Integer, List<StepDTO>>> mapDTO = makeUserCompletedStepsMapSerilizable(map);
builder.put("completedSteps", mapDTO);
Map<Integer, String> projectIdToName = getProjectIdAndNameByCompanyId(companyId);
builder.put("projectsName", projectIdToName);
boolean hasNext = false;
if (map != null && map.size() > 0) {
Date newUntil = new DateTime(map.firstKey()).withTime(0, 0, 0, 0).plusMillis(-1).toDate();
TreeMap<Date, Map<Integer, List<Bug>>> nextMap = bugService.getCompletedBugsGroupByDateByUser(companyId,
userId, projectList, newUntil, PER_PAGE);
hasNext = nextMap.size() > 0;
builder.put("nextPage", dtf.print(new DateTime(newUntil)));
}
builder.put("hasNext", hasNext);
return builder.build();
}
@Override
Builder<String, Object> serialize(Builder<String, Object> builder) {
super.serialize(builder);
if (hasEffect()) {
builder.put(EXPLOSION.BUKKIT, effect);
}
return builder;
}
@Override
Builder<String, Object> serialize(Builder<String, Object> builder) {
super.serialize(builder);
serializeEnchantments(enchantments, builder, STORED_ENCHANTMENTS);
return builder;
}
@Override
Builder<String, Object> serialize(Builder<String, Object> builder) {
super.serialize(builder);
if (hasOwner()) {
return builder.put(SKULL_OWNER.BUKKIT, this.profile.getName());
}
return builder;
}
@Override
Builder<String, Object> serialize(Builder<String, Object> builder) {
super.serialize(builder);
if (hasEffects()) {
builder.put(EXPLOSIONS.BUKKIT, ImmutableList.copyOf(effects));
}
if (hasPower()) {
builder.put(FLIGHT.BUKKIT, power);
}
return builder;
}
public static <T> void maybePut(final Builder<String, String> builder,
final T t,
final Function<T, String> f,
final String key)
{
Optional.of(t).map(f).ifPresent(v -> builder.put(key, v));
}
@Override
Builder<String, Object> serialize(Builder<String, Object> builder) {
super.serialize(builder);
if (hasOwner()) {
return builder.put(SKULL_OWNER.BUKKIT, this.profile.getName());
}
return builder;
}
public String request() {
try {
Builder<String, String> builder = ImmutableMap.<String, String>builder()
.put("query", this.query);
variables.ifPresent(variables -> builder.put("variables", variables));
operationName.ifPresent(operationName -> builder.put("operationName", operationName));
return toJsonString(builder.build());
} catch (JsonProcessingException exception) {
throw new RuntimeException(exception.getMessage(), exception);
}
}
private ImmutableMap<BaseType, Integer> captureTypeSizes() {
final Builder<BaseType, Integer> builder = ImmutableMap.<BaseType, Integer>builder();
for (BaseType baseType : typeSystem.getTypes()) {
builder.put(baseType, baseType.getBitSize());
}
return builder.build();
}
private Map<String, String> buildStorageHeaders(final String blobName,
@Nullable final Supplier<InputStream> streamSupplier,
@Nullable final Map<String, String> headers,
@Nullable final String declaredContentType,
final boolean skipContentVerification) throws IOException
{
checkArgument(
!skipContentVerification || !Strings2.isBlank(declaredContentType),
"skipContentVerification set true but no declaredContentType provided"
);
Builder<String, String> storageHeaders = ImmutableMap.builder();
storageHeaders.put(Bucket.REPO_NAME_HEADER, repositoryName);
storageHeaders.put(BlobStore.BLOB_NAME_HEADER, blobName);
storageHeaders.put(BlobStore.CREATED_BY_HEADER, createdBy);
storageHeaders.put(BlobStore.CREATED_BY_IP_HEADER, createdByIp);
if (!skipContentVerification) {
storageHeaders.put(
BlobStore.CONTENT_TYPE_HEADER,
determineContentType(streamSupplier, blobName, declaredContentType)
);
}
else {
storageHeaders.put(BlobStore.CONTENT_TYPE_HEADER, declaredContentType);
}
if (headers != null) {
storageHeaders.putAll(headers);
}
return storageHeaders.build();
}
private static Map<String, String> sanitizePasswords(@Nullable Map<String, String> keyPasswords) {
if (keyPasswords == null) {
return ImmutableMap.of();
}
final ImmutableMap.Builder<String, String> builder = new Builder<>();
keyPasswords.forEach((key, password) -> builder.put(key, firstNonNull(password, "")));
return builder.build();
}
CheckpointImpl(String name, Map<Segment, Long> segmentPositions) {
this.name = name;
Map<Stream, ImmutableMap.Builder<Segment, Long>> streamPositions = new HashMap<>();
for (Entry<Segment, Long> position : segmentPositions.entrySet()) {
streamPositions.computeIfAbsent(position.getKey().getStream(),
k -> new ImmutableMap.Builder<Segment, Long>())
.put(position);
}
ImmutableMap.Builder<Stream, StreamCut> positionBuilder = ImmutableMap.builder();
for (Entry<Stream, Builder<Segment, Long>> streamPosition : streamPositions.entrySet()) {
positionBuilder.put(streamPosition.getKey(),
new StreamCutImpl(streamPosition.getKey(), streamPosition.getValue().build()));
}
this.positions = positionBuilder.build();
}
private ImmutableMap<String, String> getImmutableCustomTracingAnnotations() {
Builder<String, String> result = ImmutableMap.builder();
result.putAll(JDBCUtil.getAnnotations(url, info));
if (getSCN() != null) {
result.put(PhoenixRuntime.CURRENT_SCN_ATTRIB, getSCN().toString());
}
if (getTenantId() != null) {
result.put(PhoenixRuntime.TENANT_ID_ATTRIB, getTenantId().getString());
}
return result.build();
}
private void sendMetrics(CompletionCode completionCode, String target, Metrics metrics) {
Builder<String, Long> builder = ImmutableMap.builder();
builder.put(replicationTime(target));
builder.put(completionCode(target, completionCode));
if (metrics != null) {
builder.put(bytesReplicated(target, metrics));
for (Entry<String, Long> metric : metrics.getMetrics().entrySet()) {
builder.put(DotJoiner.join(target, metric.getKey()), metric.getValue());
}
}
metricSender.send(builder.build());
}
private static DirectoryStructure computeRootDirectoryStructure(
Project project,
WorkspaceRoot workspaceRoot,
ProjectViewSet projectViewSet,
AtomicBoolean cancelled)
throws ExecutionException, InterruptedException {
FileOperationProvider fileOperationProvider = FileOperationProvider.getInstance();
ImportRoots importRoots =
ImportRoots.builder(workspaceRoot, Blaze.getBuildSystem(project))
.add(projectViewSet)
.build();
Collection<WorkspacePath> rootDirectories = importRoots.rootDirectories();
Set<WorkspacePath> excludeDirectories = importRoots.excludeDirectories();
List<ListenableFuture<PathStructurePair>> futures =
Lists.newArrayListWithExpectedSize(rootDirectories.size());
for (WorkspacePath rootDirectory : rootDirectories) {
futures.add(
walkDirectoryStructure(
workspaceRoot,
excludeDirectories,
fileOperationProvider,
FetchExecutor.EXECUTOR,
rootDirectory,
cancelled));
}
ImmutableMap.Builder<WorkspacePath, DirectoryStructure> result = ImmutableMap.builder();
for (PathStructurePair pair : Futures.allAsList(futures).get()) {
if (pair != null) {
result.put(pair.path, pair.directoryStructure);
}
}
return new DirectoryStructure(result.build());
}
/**
* Returns URL parameters after removing any that have an empty list in them.
* For optional list arguments, we pass an empty list to the API method. This generates
* an entry like includes[]= with no value. This function strips them out so we only
* pass parameters to Canvas that have a value to send along.
*/
private Map<String, List<String>> stripEmptyParams(Map<String, List<String>> parameters) {
Builder<String, List<String>> paramsBuilder = ImmutableMap.<String, List<String>>builder();
for (Map.Entry<String, List<String>> entry : parameters.entrySet()) {
if(entry.getValue() != null && !entry.getValue().isEmpty()) {
paramsBuilder.put(entry.getKey(), entry.getValue());
}
}
return paramsBuilder.build();
}
private Map<WebPath, Handler> createPathToHandler(Injector injector) {
ImmutableMap.Builder<WebPath, Handler> builder = ImmutableMap.builder();
Map<Key<?>, Binding<?>> bindings = injector.getBindings();
for (Entry<Key<?>, Binding<?>> entry : bindings.entrySet()) {
Key<?> key = entry.getKey();
if (isWebService(key)) {
introspectWebService(builder, entry.getValue());
}
}
return builder.build();
}
@Override
public CompletableFuture<MessageId> getLastMessageIdAsync() {
CompletableFuture<MessageId> returnFuture = new CompletableFuture<>();
Map<String, CompletableFuture<MessageId>> messageIdFutures = consumers.entrySet().stream()
.map(entry -> Pair.of(entry.getKey(),entry.getValue().getLastMessageIdAsync()))
.collect(Collectors.toMap(Pair::getKey, Pair::getValue));
CompletableFuture
.allOf(messageIdFutures.entrySet().stream().map(Map.Entry::getValue).toArray(CompletableFuture<?>[]::new))
.whenComplete((ignore, ex) -> {
Builder<String, MessageId> builder = ImmutableMap.builder();
messageIdFutures.forEach((key, future) -> {
MessageId messageId;
try {
messageId = future.get();
} catch(Exception e) {
log.warn("[{}] Exception when topic {} getLastMessageId.", key, e);
messageId = MessageId.earliest;
}
builder.put(key, messageId);
});
returnFuture.complete(new MultiMessageIdImpl(builder.build()));
});
return returnFuture;
}