Java Code Examples for com.google.common.collect.ImmutableListMultimap

The following are top voted examples for showing how to use com.google.common.collect.ImmutableListMultimap. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: HardVox   File: TaskManager.java   View source code 6 votes vote down vote up
public void runTasks() {
    Multimaps.asMap(ImmutableListMultimap.copyOf(taskQueue)).values().forEach(tasks -> {
        int size = tasks.size();
        while (size > 0) {
            int last = size - 1;
            Task<?> current = tasks.get(last);
            if (current.done()) {
                taskQueue.get(current.getClass()).remove(last);
                size--;
                continue;
            }
            current.tick();
            return;
        }
    });
}
 
Example 2
Project: camunda-task-dispatcher   File: TaskProcessorRegistryImplTest.java   View source code 6 votes vote down vote up
@Test
public void testProcess() {
    String taskName = "task";
    JavaUtils.setFieldWithoutCheckedException(
            ReflectionUtils.findField(TaskProcessorRegistryImpl.class, "taskProcessorMap")
            , registry
            , ImmutableListMultimap.builder()
                                   .put(taskName, Pair.of(Objects.class, taskProcessor))
                                   .build()
    );

    registry.process(taskName, "some body");

    Mockito.verify(taskMapper, Mockito.atLeastOnce()).map(Mockito.anyString(), Mockito.any());
    Mockito.verify(taskProcessor, Mockito.atLeastOnce()).process(Mockito.any());
}
 
Example 3
Project: rejoiner   File: ProtoRegistry.java   View source code 6 votes vote down vote up
/** Applies the supplied modifications to the GraphQLTypes. */
private static BiMap<String, GraphQLType> modifyTypes(
    BiMap<String, GraphQLType> mapping,
    ImmutableListMultimap<String, TypeModification> modifications) {
  BiMap<String, GraphQLType> result = HashBiMap.create(mapping.size());
  for (String key : mapping.keySet()) {
    if (mapping.get(key) instanceof GraphQLObjectType) {
      GraphQLObjectType val = (GraphQLObjectType) mapping.get(key);
      if (modifications.containsKey(key)) {
        for (TypeModification modification : modifications.get(key)) {
          val = modification.apply(val);
        }
      }
      result.put(key, val);
    } else {
      result.put(key, mapping.get(key));
    }
  }
  return result;
}
 
Example 4
Project: guava-mock   File: MediaType.java   View source code 6 votes vote down vote up
/**
 * <em>Replaces</em> all parameters with the given attribute with a single parameter with the
 * given value. If multiple parameters with the same attributes are necessary use
 * {@link #withParameters}. Prefer {@link #withCharset} for setting the {@code charset} parameter
 * when using a {@link Charset} object.
 *
 * @throws IllegalArgumentException if either {@code attribute} or {@code value} is invalid
 */
public MediaType withParameter(String attribute, String value) {
  checkNotNull(attribute);
  checkNotNull(value);
  String normalizedAttribute = normalizeToken(attribute);
  ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
  for (Entry<String, String> entry : parameters.entries()) {
    String key = entry.getKey();
    if (!normalizedAttribute.equals(key)) {
      builder.put(key, entry.getValue());
    }
  }
  builder.put(normalizedAttribute, normalizeParameterValue(normalizedAttribute, value));
  MediaType mediaType = new MediaType(type, subtype, builder.build());
  // if the attribute isn't charset, we can just inherit the current parsedCharset
  if (!normalizedAttribute.equals(CHARSET_ATTRIBUTE)) {
    mediaType.parsedCharset = this.parsedCharset;
  }
  // Return one of the constants if the media type is a known type.
  return MoreObjects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
}
 
Example 5
Project: guava-mock   File: MediaType.java   View source code 6 votes vote down vote up
private static MediaType create(
    String type, String subtype, Multimap<String, String> parameters) {
  checkNotNull(type);
  checkNotNull(subtype);
  checkNotNull(parameters);
  String normalizedType = normalizeToken(type);
  String normalizedSubtype = normalizeToken(subtype);
  checkArgument(
      !WILDCARD.equals(normalizedType) || WILDCARD.equals(normalizedSubtype),
      "A wildcard type cannot be used with a non-wildcard subtype");
  ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
  for (Entry<String, String> entry : parameters.entries()) {
    String attribute = normalizeToken(entry.getKey());
    builder.put(attribute, normalizeParameterValue(attribute, entry.getValue()));
  }
  MediaType mediaType = new MediaType(normalizedType, normalizedSubtype, builder.build());
  // Return one of the constants if the media type is a known type.
  return MoreObjects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
}
 
Example 6
Project: Equella   File: ItemDaoImpl.java   View source code 6 votes vote down vote up
@Override
@Transactional(propagation = Propagation.MANDATORY)
public ListMultimap<Item, Attachment> getAttachmentsForItems(Collection<Item> items)
{
	if( items.isEmpty() )
	{
		return ImmutableListMultimap.of();
	}
	List<Attachment> attachments = getHibernateTemplate().findByNamedParam(
		"select a from Item i join i.attachments a where i in (:items) order by index(a) ASC", "items", items);
	ListMultimap<Item, Attachment> multiMap = ArrayListMultimap.create();
	for( Attachment attachment : attachments )
	{
		multiMap.put(attachment.getItem(), attachment);
	}
	return multiMap;
}
 
Example 7
Project: Equella   File: ItemDaoImpl.java   View source code 6 votes vote down vote up
@Override
@Transactional(propagation = Propagation.MANDATORY)
public ListMultimap<Long, Attachment> getAttachmentsForItemIds(Collection<Long> ids)
{
	if( ids.isEmpty() )
	{
		return ImmutableListMultimap.of();
	}
	List<Object[]> attachments = getHibernateTemplate().findByNamedParam(
		"select a, i.id from Item i join i.attachments a where i.id in (:items) order by index(a) ASC", "items",
		ids);
	ListMultimap<Long, Attachment> multiMap = ArrayListMultimap.create();
	for( Object[] attachmentRow : attachments )
	{
		multiMap.put((Long) attachmentRow[1], (Attachment) attachmentRow[0]);
	}
	return multiMap;
}
 
Example 8
Project: Equella   File: ItemDaoImpl.java   View source code 6 votes vote down vote up
@Override
@Transactional(propagation = Propagation.MANDATORY)
public ListMultimap<Long, HistoryEvent> getHistoryForItemIds(Collection<Long> ids)
{
	if( ids.isEmpty() )
	{
		return ImmutableListMultimap.of();
	}
	List<Object[]> history = getHibernateTemplate().findByNamedParam(
		"select h, i.id from Item i join i.history h where i.id in (:items) order by index(h)", "items", ids);
	ListMultimap<Long, HistoryEvent> multiMap = ArrayListMultimap.create();
	for( Object[] historyRow : history )
	{
		multiMap.put((Long) historyRow[1], (HistoryEvent) historyRow[0]);
	}
	return multiMap;
}
 
Example 9
Project: Equella   File: ItemDaoImpl.java   View source code 6 votes vote down vote up
@Override
@Transactional(propagation = Propagation.MANDATORY)
public ListMultimap<Long, ItemNavigationNode> getNavigationNodesForItemIds(Collection<Long> ids)
{
	if( ids.isEmpty() )
	{
		return ImmutableListMultimap.of();
	}
	List<Object[]> node = getHibernateTemplate().findByNamedParam(
		"select n, i.id from ItemNavigationNode n join n.item i where i.id in (:items) order by n.index ASC",
		"items", ids);
	ListMultimap<Long, ItemNavigationNode> multiMap = ArrayListMultimap.create();
	for( Object[] nodeRow : node )
	{
		multiMap.put((Long) nodeRow[1], (ItemNavigationNode) nodeRow[0]);
	}
	return multiMap;
}
 
Example 10
Project: Equella   File: ItemDaoImpl.java   View source code 6 votes vote down vote up
@Override
public ListMultimap<Long, DrmAcceptance> getDrmAcceptancesForItemIds(Collection<Long> itemIds)
{
	if( itemIds.isEmpty() )
	{
		return ImmutableListMultimap.of();
	}
	final List<Object[]> drmAcceptances = getHibernateTemplate().findByNamedParam(
		"select d, item.id from DrmAcceptance d where item.id in (:items) order by d.date DESC", "items", itemIds);
	final ListMultimap<Long, DrmAcceptance> multiMap = ArrayListMultimap.create();
	for( Object[] asseptRow : drmAcceptances )
	{
		multiMap.put((Long) asseptRow[1], (DrmAcceptance) asseptRow[0]);
	}
	return multiMap;
}
 
Example 11
Project: Equella   File: ItemCommentDaoImpl.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
@Transactional(propagation = Propagation.MANDATORY)
public Multimap<Long, Comment> getCommentsForItems(Collection<Long> itemIds)
{
	if( itemIds.isEmpty() )
	{
		return ImmutableListMultimap.of();
	}
	List<Object[]> attachments = getHibernateTemplate()
		.findByNamedParam("select c, i.id from Item i join i.comments c where i.id in (:items)", "items", itemIds);
	ListMultimap<Long, Comment> multiMap = ArrayListMultimap.create();
	for( Object[] attachmentRow : attachments )
	{
		multiMap.put((Long) attachmentRow[1], (Comment) attachmentRow[0]);
	}
	return multiMap;
}
 
Example 12
Project: googles-monorepo-demo   File: MediaType.java   View source code 6 votes vote down vote up
/**
 * <em>Replaces</em> all parameters with the given attribute with a single parameter with the
 * given value. If multiple parameters with the same attributes are necessary use
 * {@link #withParameters}. Prefer {@link #withCharset} for setting the {@code charset} parameter
 * when using a {@link Charset} object.
 *
 * @throws IllegalArgumentException if either {@code attribute} or {@code value} is invalid
 */
public MediaType withParameter(String attribute, String value) {
  checkNotNull(attribute);
  checkNotNull(value);
  String normalizedAttribute = normalizeToken(attribute);
  ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
  for (Entry<String, String> entry : parameters.entries()) {
    String key = entry.getKey();
    if (!normalizedAttribute.equals(key)) {
      builder.put(key, entry.getValue());
    }
  }
  builder.put(normalizedAttribute, normalizeParameterValue(normalizedAttribute, value));
  MediaType mediaType = new MediaType(type, subtype, builder.build());
  // Return one of the constants if the media type is a known type.
  return MoreObjects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
}
 
Example 13
Project: googles-monorepo-demo   File: MediaType.java   View source code 6 votes vote down vote up
private static MediaType create(
    String type, String subtype, Multimap<String, String> parameters) {
  checkNotNull(type);
  checkNotNull(subtype);
  checkNotNull(parameters);
  String normalizedType = normalizeToken(type);
  String normalizedSubtype = normalizeToken(subtype);
  checkArgument(
      !WILDCARD.equals(normalizedType) || WILDCARD.equals(normalizedSubtype),
      "A wildcard type cannot be used with a non-wildcard subtype");
  ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
  for (Entry<String, String> entry : parameters.entries()) {
    String attribute = normalizeToken(entry.getKey());
    builder.put(attribute, normalizeParameterValue(attribute, entry.getValue()));
  }
  MediaType mediaType = new MediaType(normalizedType, normalizedSubtype, builder.build());
  // Return one of the constants if the media type is a known type.
  return MoreObjects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
}
 
Example 14
Project: clearwsd   File: TsvResourceInitializer.java   View source code 6 votes vote down vote up
@Override
public MultimapResource<K> get() {
    ListMultimap<String, String> multimap = ArrayListMultimap.create();
    MultimapResource<K> resource = new MultimapResource<>(key);
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(path.openStream()))) {
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            if (line.trim().isEmpty()) {
                continue;
            }
            List<String> fields = Arrays.asList(line.split("\t"));
            apply(fields, multimap);
        }
    } catch (Exception e) {
        throw new RuntimeException("Error initializing TSV resource.", e);
    }
    resource.multimap(ImmutableListMultimap.copyOf(multimap));
    resource.mappingFunction(mappingFunction);
    return resource;
}
 
Example 15
Project: nomulus   File: RequestModule.java   View source code 6 votes vote down vote up
/**
 * Provides an immutable representation of the servlet request parameters.
 *
 * <p>This performs a shallow copy of the {@code Map<String, String[]>} data structure from the
 * servlets API, each time this is provided. This is almost certainly less expensive than the
 * thread synchronization expense of {@link javax.inject.Singleton @Singleton}.
 *
 * <p><b>Note:</b> If a parameter is specified without a value, e.g. {@code /foo?lol} then an
 * empty string value is assumed, since Guava's multimap doesn't permit {@code null} mappings.
 *
 * @see HttpServletRequest#getParameterMap()
 */
@Provides
@ParameterMap
static ImmutableListMultimap<String, String> provideParameterMap(HttpServletRequest req) {
  ImmutableListMultimap.Builder<String, String> params = new ImmutableListMultimap.Builder<>();
  @SuppressWarnings("unchecked")  // Safe by specification.
  Map<String, String[]> original = req.getParameterMap();
  for (Map.Entry<String, String[]> param : original.entrySet()) {
    if (param.getValue().length == 0) {
      params.put(param.getKey(), "");
    } else {
      params.putAll(param.getKey(), param.getValue());
    }
  }
  return params.build();
}
 
Example 16
Project: finances   File: GroupedDetailImportContextTest.java   View source code 6 votes vote down vote up
@Test
public void populatesTransaction() throws Exception {
    final ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes());
    final Payee payee = new Payee();
    final Account account = new Account();
    Security security = new Security();
    when(importFile.getAccount()).thenReturn(account);
    when(importFile.parse(inputStream)).thenReturn(singletonList(
            ImmutableListMultimap.of(dateField, "01/15/1990", payeeField, PAYEE_NAME, securityField, SECURITY_NAME)));
    ImportContext context = new GroupedDetailImportContext(importFile, payeeMapper, securityMapper, categoryMapper);
    when(payeeMapper.get(PAYEE_NAME)).thenReturn(payee);
    when(securityMapper.get(SECURITY_NAME)).thenReturn(security);

    List<Transaction> transactions = context.parseTransactions(inputStream);

    assertThat(transactions).hasSize(1);
    assertThat(transactions.get(0).getAccount()).isSameAs(account);
    assertThat(transactions.get(0).getDate()).isEqualTo(new SimpleDateFormat("yyyy/MM/dd").parse("1990/01/15"));
    assertThat(transactions.get(0).getPayee()).isSameAs(payee);
    assertThat(transactions.get(0).getSecurity()).isSameAs(security);
}
 
Example 17
Project: finances   File: GroupedDetailImportContextTest.java   View source code 6 votes vote down vote up
@Test
public void populatesDetail() throws Exception {
    final ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes());
    final TransactionCategory category = new TransactionCategory();
    when(importFile.parse(inputStream)).thenReturn(singletonList(
            ImmutableListMultimap.of(amountField, "10", categoryField, CATEGORY_CODE, sharesField, "1")));
    ImportContext context = new GroupedDetailImportContext(importFile, payeeMapper, securityMapper, categoryMapper);
    when(categoryMapper.get(CATEGORY_CODE)).thenReturn(category);

    List<Transaction> transactions = context.parseTransactions(inputStream);

    assertThat(transactions).hasSize(1);
    assertThat(transactions.get(0).getDetails()).hasSize(1);
    assertThat(transactions.get(0).getDetails().get(0).getCategory()).isSameAs(category);
    assertThat(transactions.get(0).getDetails().get(0).getAmount().toString()).isEqualTo("10");
    assertThat(transactions.get(0).getDetails().get(0).getAssetQuantity().toString()).isEqualTo("-1");
}
 
Example 18
Project: finances   File: GroupedDetailImportContextTest.java   View source code 6 votes vote down vote up
@Test
public void mergesDetailsForCategory() throws Exception {
    final ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes());
    final TransactionCategory category = new TransactionCategory(CATEGORY_CODE);
    when(importFile.parse(inputStream)).thenReturn(Arrays.asList(
            ImmutableListMultimap.of(dateField, "01/15/1990", amountField, "10", categoryField, CATEGORY_CODE, sharesField, "2"),
            ImmutableListMultimap.of(dateField, "01/15/1990", amountField, "1", categoryField, CATEGORY_CODE, sharesField, "20")));
    ImportContext context = new GroupedDetailImportContext(importFile, payeeMapper, securityMapper, categoryMapper);
    when(categoryMapper.get(CATEGORY_CODE)).thenReturn(category);

    List<Transaction> transactions = context.parseTransactions(inputStream);

    assertThat(transactions).hasSize(1);
    assertThat(transactions.get(0).getDetails()).hasSize(1);
    assertThat(transactions.get(0).getDetails().get(0).getCategory()).isSameAs(category);
    assertThat(transactions.get(0).getDetails().get(0).getAmount().toString()).isEqualTo("11");
    assertThat(transactions.get(0).getDetails().get(0).getAssetQuantity().toString()).isEqualTo("-22");
}
 
Example 19
Project: finances   File: GroupedDetailImportContextTest.java   View source code 6 votes vote down vote up
@Test
public void mergesDetailsForTransfer() throws Exception {
    final ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes());
    final Account transferAccount = new Account(-1L, "transfer account");
    when(importFile.parse(inputStream)).thenReturn(Arrays.asList(
            ImmutableListMultimap.of(dateField, "01/15/1990", amountField, "10", transferField, TRANSFER_ACCOUNT),
            ImmutableListMultimap.of(dateField, "01/15/1990", amountField, "1", transferField, TRANSFER_ACCOUNT)));
    ImportContext context = new GroupedDetailImportContext(importFile, payeeMapper, securityMapper, categoryMapper);
    when(importFile.getTransferAccount(TRANSFER_ACCOUNT)).thenReturn(transferAccount);

    List<Transaction> transactions = context.parseTransactions(inputStream);

    assertThat(transactions).hasSize(1);
    assertThat(transactions.get(0).getDetails()).hasSize(1);
    assertThat(transactions.get(0).getDetails().get(0).getCategory()).isNull();
    assertThat(transactions.get(0).getDetails().get(0).getTransferAccount()).isSameAs(transferAccount);
    assertThat(transactions.get(0).getDetails().get(0).getAmount().toString()).isEqualTo("11");
}
 
Example 20
Project: finances   File: SingleDetailImportContextTest.java   View source code 6 votes vote down vote up
@Test
public void populatesTransaction() throws Exception {
    final ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes());
    final Payee payee = new Payee();
    final Account account = new Account();
    when(importFile.getAccount()).thenReturn(account);
    when(importFile.parse(inputStream)).thenReturn(singletonList(ImmutableListMultimap.of(dateField, "01/15/1990", payeeField, PAYEE_NAME)));
    ImportContext context = new SingleDetailImportContext(importFile, payeeMapper, securityMapper, categoryMapper);
    when(payeeMapper.get(PAYEE_NAME)).thenReturn(payee);

    List<Transaction> transactions = context.parseTransactions(inputStream);

    assertThat(transactions).hasSize(1);
    assertThat(transactions.get(0).getAccount()).isSameAs(account);
    assertThat(transactions.get(0).getDate()).isEqualTo(new SimpleDateFormat("yyyy/MM/dd").parse("1990/01/15"));
    assertThat(transactions.get(0).getPayee()).isSameAs(payee);
}
 
Example 21
Project: finances   File: SingleDetailImportContextTest.java   View source code 6 votes vote down vote up
@Test
public void populatesDetail() throws Exception {
    final ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes());
    final TransactionCategory category = new TransactionCategory();
    when(importFile.parse(inputStream)).thenReturn(singletonList(
            ImmutableListMultimap.of(amountField, "10", categoryField, CATEGORY_CODE, sharesField, "5")));
    ImportContext context = new SingleDetailImportContext(importFile, payeeMapper, securityMapper, categoryMapper);
    when(categoryMapper.get(CATEGORY_CODE)).thenReturn(category);

    List<Transaction> transactions = context.parseTransactions(inputStream);

    assertThat(transactions).hasSize(1);
    assertThat(transactions.get(0).getDetails()).hasSize(1);
    assertThat(transactions.get(0).getDetails().get(0).getCategory()).isSameAs(category);
    assertThat(transactions.get(0).getDetails().get(0).getAmount().toString()).isEqualTo("10");
    assertThat(transactions.get(0).getDetails().get(0).getAssetQuantity().toString()).isEqualTo("-5");
}
 
Example 22
Project: finances   File: SingleDetailImportContextTest.java   View source code 6 votes vote down vote up
@Test
public void negatesAmountBasedOnCategory() throws Exception {
    final ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes());
    final TransactionCategory category = new TransactionCategory();
    when(importFile.parse(inputStream)).thenReturn(singletonList(
            ImmutableListMultimap.of(amountField, "10", categoryField, CATEGORY_CODE, sharesField, "5")));
    ImportContext context = new SingleDetailImportContext(importFile, payeeMapper, securityMapper, categoryMapper);
    when(categoryMapper.get(CATEGORY_CODE)).thenReturn(category);
    when(importFile.isNegate(category)).thenReturn(true);

    List<Transaction> transactions = context.parseTransactions(inputStream);

    assertThat(transactions).hasSize(1);
    assertThat(transactions.get(0).getDetails()).hasSize(1);
    assertThat(transactions.get(0).getDetails().get(0).getCategory()).isSameAs(category);
    assertThat(transactions.get(0).getDetails().get(0).getAmount().toString()).isEqualTo("-10");
    assertThat(transactions.get(0).getDetails().get(0).getAssetQuantity().toString()).isEqualTo("5");
}
 
Example 23
Project: finances   File: SingleDetailImportContextTest.java   View source code 6 votes vote down vote up
@Test
public void excludesZeroAssetQuantity() throws Exception {
    final ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes());
    final TransactionCategory category = new TransactionCategory();
    when(importFile.parse(inputStream)).thenReturn(singletonList(ImmutableListMultimap.of(amountField, "10", categoryField, CATEGORY_CODE, sharesField, "0.0")));
    ImportContext context = new SingleDetailImportContext(importFile, payeeMapper, securityMapper, categoryMapper);
    when(categoryMapper.get(CATEGORY_CODE)).thenReturn(category);

    List<Transaction> transactions = context.parseTransactions(inputStream);

    assertThat(transactions).hasSize(1);
    assertThat(transactions.get(0).getDetails()).hasSize(1);
    assertThat(transactions.get(0).getDetails().get(0).getCategory()).isSameAs(category);
    assertThat(transactions.get(0).getDetails().get(0).getAmount().compareTo(BigDecimal.TEN)).isEqualTo(0);
    assertThat(transactions.get(0).getDetails().get(0).getAssetQuantity()).isNull();
}
 
Example 24
Project: finances   File: SingleDetailImportContextTest.java   View source code 6 votes vote down vote up
@Test
public void populatesTransfer() throws Exception {
    final ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes());
    final TransactionCategory category = new TransactionCategory();
    final Account transferAccount = new Account();
    when(importFile.parse(inputStream)).thenReturn(singletonList(ImmutableListMultimap.of(amountField, "10", categoryField, TRANSFER_ACCOUNT)));
    when(importFile.getTransferAccount(TRANSFER_ACCOUNT)).thenReturn(transferAccount);
    SingleDetailImportContext context = new SingleDetailImportContext(importFile, payeeMapper, securityMapper, categoryMapper);
    when(categoryMapper.get(CATEGORY_CODE)).thenReturn(category);

    List<Transaction> transactions = context.parseTransactions(inputStream);

    assertThat(transactions).hasSize(1);
    assertThat(transactions.get(0).getDetails()).hasSize(1);
    assertThat(transactions.get(0).getDetails().get(0).getAmount().compareTo(BigDecimal.TEN)).isEqualTo(0);
    assertThat(transactions.get(0).getDetails().get(0).getCategory()).isNull();
    assertThat(transactions.get(0).getDetails().get(0).getRelatedDetail().getTransaction().getAccount()).isSameAs(transferAccount);
}
 
Example 25
Project: greenbeans   File: EntityReferences.java   View source code 6 votes vote down vote up
private static ListMultimap<String, String> readEntityReferences() {
	ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
	try {
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				EntityReferences.class.getResourceAsStream("entity-references.txt"), Charsets.UTF_8)); //$NON-NLS-1$
		try {
			Splitter splitter = Splitter.on(CharMatcher.WHITESPACE).trimResults().omitEmptyStrings();

			String line;
			while ((line = reader.readLine()) != null) {
				List<String> lineItems = splitter.splitToList(line);
				checkState(lineItems.size() > 1);
				for (int x = 1; x < lineItems.size(); ++x) {
					builder.put(lineItems.get(0), lineItems.get(x));
				}
			}
		} finally {
			reader.close();
		}
	} catch (IOException e) {
		throw Throwables.propagate(e);
	}
	return builder.build();
}
 
Example 26
Project: metasfresh-webui-api   File: PickingHuRowsRepository.java   View source code 6 votes vote down vote up
private ListMultimap<Integer, PickedHUEditorRow> retrievePickedHUsIndexedByPickingSlotId(@NonNull final List<I_M_Picking_Candidate> pickingCandidates)
{
	final Map<Integer, PickedHUEditorRow> huId2huRow = new HashMap<>();

	final Builder<Integer, PickedHUEditorRow> builder = ImmutableListMultimap.builder();

	for (final I_M_Picking_Candidate pickingCandidate : pickingCandidates)
	{
		final int huId = pickingCandidate.getM_HU_ID();
		if (huId2huRow.containsKey(huId))
		{
			continue;
		}

		final HUEditorRow huEditorRow = huEditorRepo.retrieveForHUId(huId);
		final boolean pickingCandidateProcessed = isPickingCandidateProcessed(pickingCandidate);
		final PickedHUEditorRow row = new PickedHUEditorRow(huEditorRow, pickingCandidateProcessed);

		huId2huRow.put(huId, row);

		builder.put(pickingCandidate.getM_PickingSlot_ID(), row);
	}

	return builder.build();
}
 
Example 27
Project: metasfresh-webui-api   File: MenuTree.java   View source code 6 votes vote down vote up
private MenuTree(final long version, final MenuNode rootNode)
{
	super();
	this.version = version;
	Preconditions.checkNotNull(rootNode, "rootNode");
	this.rootNode = rootNode;

	final ImmutableMap.Builder<String, MenuNode> nodesByIdBuilder = ImmutableMap.builder();
	final ImmutableListMultimap.Builder<ArrayKey, MenuNode> nodesByTypeAndElementIdBuilder = ImmutableListMultimap.builder();
	final ImmutableListMultimap.Builder<String, MenuNode> nodesByMainTableNameBuilder = ImmutableListMultimap.builder();
	rootNode.iterate(node -> {
		nodesByIdBuilder.put(node.getId(), node);
		nodesByTypeAndElementIdBuilder.put(mkTypeAndElementIdKey(node.getType(), node.getElementId()), node);

		final String mainTableName = node.getMainTableName();
		if (mainTableName != null)
		{
			nodesByMainTableNameBuilder.put(mainTableName, node);
		}
	});
	nodesById = nodesByIdBuilder.build();
	nodesByTypeAndElementId = nodesByTypeAndElementIdBuilder.build();
	nodesByMainTableName = nodesByMainTableNameBuilder.build();
}
 
Example 28
Project: schemaorg-java   File: JsonLdSerializer.java   View source code 6 votes vote down vote up
/**
 * Scans through the property names and property values of the 'value' object to determine if
 * any type or property in goog namespace is used. Then writes the context URL accordingly.
 * Assumes that there are only core and goog namespaces.
 */
private void writeContextUrl(JsonWriter out, Thing value) throws IOException {
  Queue<Thing> queue = new LinkedList<>();
  queue.add(value);
  while (!queue.isEmpty()) {
    ImmutableListMultimap<String, ValueType> properties =
        ((SchemaOrgTypeImpl) queue.poll()).getAllProperties();
    for (Entry<String, ValueType> entry : properties.entries()) {
      ValueType propertyValue = entry.getValue();
      if (propertyValue.getClass().getName().startsWith(GOOG_PACKAGE)
          || entry.getKey().startsWith(GOOG_NAMESPACE)) {
        out.value(GOOG_NAMESPACE);
        return;
      }
      if (propertyValue instanceof Thing && !(propertyValue instanceof Enumeration)) {
        queue.add((Thing) propertyValue);
      }
    }
  }
  out.value(CORE_NAMESPACE);
}
 
Example 29
Project: endpoints-java   File: SwaggerGenerator.java   View source code 6 votes vote down vote up
private Swagger writeSwagger(Iterable<ApiConfig> configs, SwaggerContext context,
    GenerationContext genCtx)
    throws ApiConfigException {
  ImmutableListMultimap<ApiKey, ? extends ApiConfig> configsByKey = FluentIterable.from(configs)
      .index(CONFIG_TO_ROOTLESS_KEY);
  Swagger swagger = new Swagger()
      .produces("application/json")
      .consumes("application/json")
      .scheme(context.scheme)
      .host(context.hostname)
      .basePath(context.basePath)
      .info(new Info()
          .title(context.hostname)
          .version(context.docVersion));
  for (ApiKey apiKey : configsByKey.keySet()) {
    writeApi(apiKey, configsByKey.get(apiKey), swagger, genCtx);
  }
  writeQuotaDefinitions(swagger, genCtx);
  return swagger;
}
 
Example 30
Project: endpoints-java   File: MethodHierarchyReader.java   View source code 6 votes vote down vote up
/**
 * Recursively builds a map from method_names to methods.  Method types will be resolved as much
 * as possible using {@code serviceType}.
 *
 * @param serviceType is the class object being inspected for service methods
 */
private void buildServiceMethods(
    ImmutableListMultimap.Builder<EndpointMethod.ResolvedSignature, EndpointMethod> builder,
    TypeToken<?> serviceType) {
  for (TypeToken<?> typeToken : serviceType.getTypes().classes()) {
    Class<?> serviceClass = typeToken.getRawType();
    if (Object.class.equals(serviceClass)) {
      return;
    }
    for (Method method : serviceClass.getDeclaredMethods()) {
      if (!isServiceMethod(method)) {
        continue;
      }

      EndpointMethod currentMethod = EndpointMethod.create(endpointClass, method, typeToken);
      builder.put(currentMethod.getResolvedMethodSignature(), currentMethod);
    }
  }
}
 
Example 31
Project: codebuff   File: MediaType.java   View source code 6 votes vote down vote up
/**
 * <em>Replaces</em> all parameters with the given attribute with a single parameter with the
 * given value. If multiple parameters with the same attributes are necessary use
 * {@link #withParameters}. Prefer {@link #withCharset} for setting the {@code charset} parameter
 * when using a {@link Charset} object.
 *
 * @throws IllegalArgumentException if either {@code attribute} or {@code value} is invalid
 */


public MediaType withParameter(String attribute, String value) {
  checkNotNull(attribute);
  checkNotNull(value);
  String normalizedAttribute = normalizeToken(attribute);
  ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
  for (Entry<String, String> entry : parameters.entries()) {
    String key = entry.getKey();
    if (!normalizedAttribute.equals(key)) {
      builder.put(key, entry.getValue());
    }
  }
  builder.put(normalizedAttribute, normalizeParameterValue(normalizedAttribute, value));
  MediaType mediaType = new MediaType(type, subtype, builder.build());
  // Return one of the constants if the media type is a known type.
  return MoreObjects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
}
 
Example 32
Project: codebuff   File: MediaType.java   View source code 6 votes vote down vote up
private static MediaType create(String type, String subtype, Multimap<String, String> parameters) {
  checkNotNull(type);
  checkNotNull(subtype);
  checkNotNull(parameters);
  String normalizedType = normalizeToken(type);
  String normalizedSubtype = normalizeToken(subtype);
  checkArgument(!WILDCARD.equals(normalizedType) || WILDCARD.equals(normalizedSubtype),
                "A wildcard type cannot be used with a non-wildcard subtype");
  ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
  for (Entry<String, String> entry : parameters.entries()) {
    String attribute = normalizeToken(entry.getKey());
    builder.put(attribute, normalizeParameterValue(attribute, entry.getValue()));
  }
  MediaType mediaType = new MediaType(normalizedType, normalizedSubtype, builder.build());
  // Return one of the constants if the media type is a known type.
  return MoreObjects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
}
 
Example 33
Project: codebuff   File: MediaType.java   View source code 6 votes vote down vote up
/**
 * <em>Replaces</em> all parameters with the given attribute with a single parameter with the
 * given value. If multiple parameters with the same attributes are necessary use
 * {@link #withParameters}. Prefer {@link #withCharset} for setting the {@code charset} parameter
 * when using a {@link Charset} object.
 *
 * @throws IllegalArgumentException if either {@code attribute} or {@code value} is invalid
 */


public MediaType withParameter(String attribute, String value) {
  checkNotNull(attribute);
  checkNotNull(value);
  String normalizedAttribute = normalizeToken(attribute);
  ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
  for (Entry<String, String> entry : parameters.entries()) {
    String key = entry.getKey();
    if (!normalizedAttribute.equals(key)) {
      builder.put(key, entry.getValue());
    }
  }
  builder.put(normalizedAttribute, normalizeParameterValue(normalizedAttribute, value));
  MediaType mediaType = new MediaType(type, subtype, builder.build());
  // Return one of the constants if the media type is a known type.
  return MoreObjects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
}
 
Example 34
Project: codebuff   File: MediaType.java   View source code 6 votes vote down vote up
private static MediaType create(String type, String subtype, Multimap<String, String> parameters) {
  checkNotNull(type);
  checkNotNull(subtype);
  checkNotNull(parameters);
  String normalizedType = normalizeToken(type);
  String normalizedSubtype = normalizeToken(subtype);
  checkArgument(!WILDCARD.equals(normalizedType) || WILDCARD.equals(normalizedSubtype),
                "A wildcard type cannot be used with a non-wildcard subtype");
  ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
  for (Entry<String, String> entry : parameters.entries()) {
    String attribute = normalizeToken(entry.getKey());
    builder.put(attribute, normalizeParameterValue(attribute, entry.getValue()));
  }
  MediaType mediaType = new MediaType(normalizedType, normalizedSubtype, builder.build());
  // Return one of the constants if the media type is a known type.
  return MoreObjects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
}
 
Example 35
Project: codebuff   File: MediaType.java   View source code 6 votes vote down vote up
/**
 * <em>Replaces</em> all parameters with the given attribute with a single parameter with the
 * given value. If multiple parameters with the same attributes are necessary use
 * {@link #withParameters}. Prefer {@link #withCharset} for setting the {@code charset} parameter
 * when using a {@link Charset} object.
 *
 * @throws IllegalArgumentException if either {@code attribute} or {@code value} is invalid
 */


public MediaType withParameter(String attribute, String value) {
  checkNotNull(attribute);
  checkNotNull(value);
  String normalizedAttribute = normalizeToken(attribute);
  ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
  for (Entry<String, String> entry : parameters.entries()) {
    String key = entry.getKey();
    if (!normalizedAttribute.equals(key)) {
      builder.put(key, entry.getValue());
    }
  }
  builder.put(normalizedAttribute, normalizeParameterValue(normalizedAttribute, value));
  MediaType mediaType = new MediaType(type, subtype, builder.build());
  // Return one of the constants if the media type is a known type.
  return MoreObjects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
}
 
Example 36
Project: codebuff   File: MediaType.java   View source code 6 votes vote down vote up
private static MediaType create(String type, String subtype, Multimap<String, String> parameters) {
  checkNotNull(type);
  checkNotNull(subtype);
  checkNotNull(parameters);
  String normalizedType = normalizeToken(type);
  String normalizedSubtype = normalizeToken(subtype);
  checkArgument(
    !WILDCARD.equals(normalizedType) || WILDCARD.equals(normalizedSubtype),
    "A wildcard type cannot be used with a non-wildcard subtype");
  ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
  for (Entry<String, String> entry : parameters.entries()) {
    String attribute = normalizeToken(entry.getKey());
    builder.put(attribute, normalizeParameterValue(attribute, entry.getValue()));
  }
  MediaType mediaType = new MediaType(normalizedType, normalizedSubtype, builder.build());
  // Return one of the constants if the media type is a known type.
  return MoreObjects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
}
 
Example 37
Project: codebuff   File: MediaType.java   View source code 6 votes vote down vote up
/**
 * <em>Replaces</em> all parameters with the given attribute with a single parameter with the
 * given value. If multiple parameters with the same attributes are necessary use
 * {@link #withParameters}. Prefer {@link #withCharset} for setting the {@code charset} parameter
 * when using a {@link Charset} object.
 *
 * @throws IllegalArgumentException if either {@code attribute} or {@code value} is invalid
 */


public MediaType withParameter(String attribute, String value) {
  checkNotNull(attribute);
  checkNotNull(value);
  String normalizedAttribute = normalizeToken(attribute);
  ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
  for (Entry<String, String> entry : parameters.entries()) {
    String key = entry.getKey();
    if (!normalizedAttribute.equals(key)) {
      builder.put(key, entry.getValue());
    }
  }
  builder.put(normalizedAttribute, normalizeParameterValue(normalizedAttribute, value));
  MediaType mediaType = new MediaType(type, subtype, builder.build());
  // Return one of the constants if the media type is a known type.
  return MoreObjects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
}
 
Example 38
Project: codebuff   File: MediaType.java   View source code 6 votes vote down vote up
private static MediaType create(String type, String subtype, Multimap<String, String> parameters) {
  checkNotNull(type);
  checkNotNull(subtype);
  checkNotNull(parameters);
  String normalizedType = normalizeToken(type);
  String normalizedSubtype = normalizeToken(subtype);
  checkArgument(!WILDCARD.equals(normalizedType) || WILDCARD.equals(normalizedSubtype),
                "A wildcard type cannot be used with a non-wildcard subtype");
  ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
  for (Entry<String, String> entry : parameters.entries()) {
    String attribute = normalizeToken(entry.getKey());
    builder.put(attribute, normalizeParameterValue(attribute, entry.getValue()));
  }
  MediaType mediaType = new MediaType(normalizedType, normalizedSubtype, builder.build());
  // Return one of the constants if the media type is a known type.
  return MoreObjects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
}
 
Example 39
Project: codebuff   File: MediaType.java   View source code 6 votes vote down vote up
/**
 * <em>Replaces</em> all parameters with the given attribute with a single parameter with the
 * given value. If multiple parameters with the same attributes are necessary use
 * {@link #withParameters}. Prefer {@link #withCharset} for setting the {@code charset} parameter
 * when using a {@link Charset} object.
 *
 * @throws IllegalArgumentException if either {@code attribute} or {@code value} is invalid
 */
public MediaType withParameter(String attribute, String value) {
  checkNotNull(attribute);
  checkNotNull(value);
  String normalizedAttribute = normalizeToken(attribute);
  ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
  for (Entry<String, String> entry : parameters.entries()) {
    String key = entry.getKey();
    if (!normalizedAttribute.equals(key)) {
      builder.put(key, entry.getValue());
    }
  }
  builder.put(normalizedAttribute, normalizeParameterValue(normalizedAttribute, value));
  MediaType mediaType = new MediaType(type, subtype, builder.build());
  // Return one of the constants if the media type is a known type.
  return MoreObjects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
}
 
Example 40
Project: codebuff   File: MediaType.java   View source code 6 votes vote down vote up
private static MediaType create(
    String type, String subtype, Multimap<String, String> parameters) {
  checkNotNull(type);
  checkNotNull(subtype);
  checkNotNull(parameters);
  String normalizedType = normalizeToken(type);
  String normalizedSubtype = normalizeToken(subtype);
  checkArgument(
      !WILDCARD.equals(normalizedType) || WILDCARD.equals(normalizedSubtype),
      "A wildcard type cannot be used with a non-wildcard subtype");
  ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
  for (Entry<String, String> entry : parameters.entries()) {
    String attribute = normalizeToken(entry.getKey());
    builder.put(attribute, normalizeParameterValue(attribute, entry.getValue()));
  }
  MediaType mediaType = new MediaType(normalizedType, normalizedSubtype, builder.build());
  // Return one of the constants if the media type is a known type.
  return MoreObjects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
}