Java Code Examples for com.google.common.collect.ImmutableMap.Builder

The following examples show how to use com.google.common.collect.ImmutableMap.Builder. These examples are extracted from open source projects. 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 Project: binnavi   Source File: TypeManager.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 2
Source Project: armeria   Source File: AnnotatedBeanFactoryRegistry.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 3
Source Project: Kettle   Source File: CraftMetaBook.java    License: GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example 4
Source Project: deploymentmanager-autogen   Source File: Autogen.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 5
Source Project: tracecompass   Source File: UnknownPacket.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@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;
}
 
Example 6
Source Project: greenbeans   Source File: WebDispatch.java    License: Apache License 2.0 6 votes vote down vote up
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));

}
 
Example 7
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);
		}
	}
}
 
Example 8
Source Project: nexus-public   Source File: FluentBlobsImpl.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@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);
}
 
Example 9
Source Project: onboard   Source File: UserAPIController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取未完成的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();
}
 
Example 10
/**
 * 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());
  }
}
 
Example 11
Source Project: Thermos   Source File: CraftMetaFirework.java    License: GNU General Public License v3.0 5 votes vote down vote up
@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;
}
 
Example 12
/**
 * 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");
}
 
Example 13
Source Project: onboard   Source File: UserAPIController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取完成的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();
}
 
Example 14
Source Project: Kettle   Source File: CraftMetaCharge.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
Builder<String, Object> serialize(Builder<String, Object> builder) {
    super.serialize(builder);

    if (hasEffect()) {
        builder.put(EXPLOSION.BUKKIT, effect);
    }

    return builder;
}
 
Example 15
@Override
Builder<String, Object> serialize(Builder<String, Object> builder) {
    super.serialize(builder);

    serializeEnchantments(enchantments, builder, STORED_ENCHANTMENTS);

    return builder;
}
 
Example 16
Source Project: Kettle   Source File: CraftMetaSkull.java    License: GNU General Public License v3.0 5 votes vote down vote up
@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;
}
 
Example 17
Source Project: Kettle   Source File: CraftMetaFirework.java    License: GNU General Public License v3.0 5 votes vote down vote up
@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;
}
 
Example 18
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));
}
 
Example 19
Source Project: Thermos   Source File: CraftMetaSkull.java    License: GNU General Public License v3.0 5 votes vote down vote up
@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;
}
 
Example 20
Source Project: pandaria   Source File: GraphqlContext.java    License: MIT License 5 votes vote down vote up
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);
    }
}
 
Example 21
Source Project: binnavi   Source File: TypeManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 22
Source Project: nexus-public   Source File: StorageTxImpl.java    License: Eclipse Public License 1.0 5 votes vote down vote up
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();
}
 
Example 23
Source Project: centraldogma   Source File: SamlAuthProperties.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 24
Source Project: pravega   Source File: CheckpointImpl.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 25
Source Project: phoenix   Source File: PhoenixConnection.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 26
Source Project: circus-train   Source File: MetricsListener.java    License: Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 27
Source Project: intellij   Source File: DirectoryStructure.java    License: Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 28
Source Project: canvas-api   Source File: BaseImpl.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 29
Source Project: greenbeans   Source File: WebDispatch.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 30
Source Project: pulsar   Source File: MultiTopicsConsumerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}