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

The following examples show how to use com.google.common.collect.ImmutableMap.Builder. 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: AnnotatedBeanFactoryRegistry.java    From armeria with 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 #2
Source File: CraftMetaBook.java    From Kettle with 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 #3
Source File: UnknownPacket.java    From tracecompass with 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 #4
Source File: TypeManager.java    From binnavi with 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 #5
Source File: Autogen.java    From deploymentmanager-autogen with 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 #6
Source File: WebDispatch.java    From greenbeans with 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
Source File: JvmTypesResourceDescriptionStrategy.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
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 File: FluentBlobsImpl.java    From nexus-public with 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 File: UserAPIController.java    From onboard with 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
Source File: CraftMetaCharge.java    From Thermos with 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 #11
Source File: StructDefinition.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Definition getDefinition(String fieldName) {
    if (fDefinitionsMap == null) {
        /* Build the definitions map */
        Builder<String, Definition> mapBuilder = new ImmutableMap.Builder<>();
        for (int i = 0; i < fFieldNames.size(); i++) {
            if (fDefinitions[i] != null) {
                mapBuilder.put(fFieldNames.get(i), fDefinitions[i]);
            }
        }
        fDefinitionsMap = mapBuilder.build();
    }
    return fDefinitionsMap.get(fieldName);
}
 
Example #12
Source File: CraftMetaEnchantedBook.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
@Override
Builder<String, Object> serialize(Builder<String, Object> builder) {
    super.serialize(builder);

    serializeEnchantments(enchantments, builder, STORED_ENCHANTMENTS);

    return builder;
}
 
Example #13
Source File: ImmutableSortedMap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Associates {@code key} with {@code value} in the built map. Duplicate
 * keys, according to the comparator (which might be the keys' natural
 * order), are not allowed, and will cause {@link #build} to fail.
 */
@CanIgnoreReturnValue
@Override
public Builder<K, V> put(K key, V value) {
  super.put(key, value);
  return this;
}
 
Example #14
Source File: StorageTxImpl.java    From nexus-public with 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 #15
Source File: ImmutableSortedMap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 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 #16
Source File: SamlAuthProperties.java    From centraldogma with 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 #17
Source File: CraftMetaCharge.java    From Kettle with 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 #18
Source File: CheckpointImpl.java    From pravega with 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 #19
Source File: AnnotatedBeanFactoryRegistry.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static Map<Method, List<AnnotatedValueResolver>> findMethods(
        List<AnnotatedValueResolver> constructorAnnotatedResolvers,
        BeanFactoryId beanFactoryId, List<RequestObjectResolver> objectResolvers) {
    final Set<AnnotatedValueResolver> uniques = uniqueResolverSet();
    uniques.addAll(constructorAnnotatedResolvers);

    final Builder<Method, List<AnnotatedValueResolver>> methodsBuilder = ImmutableMap.builder();
    final Set<Method> methods = getAllMethods(beanFactoryId.type);
    for (final Method method : methods) {
        final List<RequestConverter> converters =
                AnnotationUtil.findDeclared(method, RequestConverter.class);
        try {
            final List<AnnotatedValueResolver> resolvers =
                    AnnotatedValueResolver.ofBeanConstructorOrMethod(
                            method, beanFactoryId.pathParams,
                            addToFirstIfExists(objectResolvers, converters));
            if (!resolvers.isEmpty()) {
                boolean redundant = false;
                for (AnnotatedValueResolver resolver : resolvers) {
                    if (!uniques.add(resolver)) {
                        redundant = true;
                        warnDuplicateResolver(resolver, method.toGenericString());
                    }
                }
                if (redundant && resolvers.size() == 1) {
                    // Prevent redundant injection only when the size of parameter is 1.
                    // If the method contains more than 2 parameters and if one of them is used redundantly,
                    // we'd better to inject the method rather than ignore it.
                    continue;
                }
                methodsBuilder.put(method, resolvers);
            }
        } catch (NoAnnotatedParameterException ignored) {
            // There's no annotated parameters in the method.
        }
    }
    return methodsBuilder.build();
}
 
Example #20
Source File: PhoenixConnection.java    From phoenix with 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 #21
Source File: MetricsListener.java    From circus-train with 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 #22
Source File: DirectoryStructure.java    From intellij with 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 #23
Source File: BaseImpl.java    From canvas-api with 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 #24
Source File: WebDispatch.java    From greenbeans with 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 #25
Source File: MultiTopicsConsumerImpl.java    From pulsar with 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;
}
 
Example #26
Source File: SamlService.java    From armeria with Apache License 2.0 5 votes vote down vote up
SamlService(SamlServiceProvider sp) {
    this.sp = requireNonNull(sp, "sp");
    portConfigHolder = sp.portConfigAutoFiller();

    final ImmutableMap.Builder<String, SamlServiceFunction> builder = new Builder<>();
    sp.acsConfigs().forEach(
            cfg -> builder.put(cfg.endpoint().uri().getPath(),
                               new SamlAssertionConsumerFunction(cfg,
                                                                 sp.entityId(),
                                                                 sp.idpConfigs(),
                                                                 sp.defaultIdpConfig(),
                                                                 sp.requestIdManager(),
                                                                 sp.ssoHandler())));
    sp.sloEndpoints().forEach(
            cfg -> builder.put(cfg.uri().getPath(),
                               new SamlSingleLogoutFunction(cfg,
                                                            sp.entityId(),
                                                            sp.signingCredential(),
                                                            sp.signatureAlgorithm(),
                                                            sp.idpConfigs(),
                                                            sp.defaultIdpConfig(),
                                                            sp.requestIdManager(),
                                                            sp.sloHandler())));
    final Route route = sp.metadataRoute();
    if (route.pathType() == RoutePathType.EXACT) {
        builder.put(route.paths().get(0),
                    new SamlMetadataServiceFunction(sp.entityId(),
                                                    sp.signingCredential(),
                                                    sp.encryptionCredential(),
                                                    sp.idpConfigs(),
                                                    sp.acsConfigs(),
                                                    sp.sloEndpoints()));
    }
    serviceMap = builder.build();
    routes = serviceMap.keySet()
                       .stream()
                       .map(path -> Route.builder().exact(path).build())
                       .collect(toImmutableSet());
}
 
Example #27
Source File: ImmutableSortedMap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 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 #28
Source File: TypeManager.java    From binnavi with Apache License 2.0 5 votes vote down vote up
private static ImmutableMap<BaseType, Integer> captureTypeSizesState(
    final Set<BaseType> baseTypes) {
  final Builder<BaseType, Integer> builder = ImmutableMap.<BaseType, Integer>builder();
  for (BaseType baseType : baseTypes) {
    if (baseType.getCategory() != BaseTypeCategory.FUNCTION_PROTOTYPE) {
      builder.put(baseType, baseType.getBitSize());
    }
  }
  return builder.build();
}
 
Example #29
Source File: ImmutableSortedMapDeserializer.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected Builder<Object, Object> createBuilder() {
    // Not quite sure what to do with sorting/ordering; may require better
    // support either via annotations, or via custom serialization (bean
    // style that includes ordering aspects)
    @SuppressWarnings("rawtypes")
    ImmutableSortedMap.Builder<?, Object> naturalOrder = ImmutableSortedMap.<Comparable, Object>naturalOrder();
    ImmutableSortedMap.Builder<Object, Object> builder = (ImmutableSortedMap.Builder<Object, Object>) naturalOrder;
    return builder;
}
 
Example #30
Source File: UserAPIController.java    From onboard with Apache License 2.0 5 votes vote down vote up
/**
 * 看一个人完成的所有todo
 * 
 * @param companyId
 * @param userId
 * @param model
 * @return
 */
@RequestMapping(value = "/{companyId}/user/{userId}/completed_todos", method = RequestMethod.GET)
@Interceptors({ CompanyMemberRequired.class, UserChecking.class })
@ResponseBody
public Map<String, Object> viewUserCompletedTodos(@PathVariable int companyId, @PathVariable int userId,
        @RequestParam(value = "until", required = false) @DateTimeFormat(iso = ISO.DATE) Date until, Model model) {
    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, List<Todolist>> map = todoService.getCompletedTodolistsGroupByDateByUser(companyId, userId,
            projectList, until, PER_PAGE);
    TreeMap<String, List<TodolistDTO>> mapDTO = makeUserCompletedTodosMapSerilizable(map);
    builder.put("completedTodos", 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.lastKey()).withTime(0, 0, 0, 0).plusMillis(-1).toDate();

        TreeMap<Date, List<Todolist>> nextMap = todoService.getCompletedTodolistsGroupByDateByUser(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();
}