Java Code Examples for com.google.common.collect.ArrayListMultimap.create()

The following are Jave code examples for showing how to use create() of the com.google.common.collect.ArrayListMultimap class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: dremio-oss   File: RoundRobinOperator.java   View Source Code Vote up 6 votes
public RoundRobinOperator(TunnelProvider tunnelProvider, OperatorContext context, RoundRobinSender config) throws OutOfMemoryException {
  super(config);
  this.config = config;
  this.allocator = context.getAllocator();
  this.handle = context.getFragmentHandle();
  this.stats = context.getStats();

  List<MinorFragmentEndpoint> destinations = config.getDestinations();
  final ArrayListMultimap<NodeEndpoint, Integer> dests = ArrayListMultimap.create();
  for(MinorFragmentEndpoint destination : destinations) {
    dests.put(destination.getEndpoint(), destination.getId());
  }

  this.tunnels = new ArrayList<>();
  this.minorFragments = new ArrayList<>();
  for(final NodeEndpoint ep : dests.keySet()){
    List<Integer> minorsList= dests.get(ep);
    minorFragments.add(minorsList);
    tunnels.add(tunnelProvider.getExecTunnel(ep));
  }

  int destCount = dests.keySet().size();
  this.currentTunnelsIndex = ThreadLocalRandom.current().nextInt(destCount);
  this.currentMinorFragmentsIndex = ThreadLocalRandom.current().nextInt(minorFragments.get(currentTunnelsIndex).size());
}
 
Example 2
Project: guava-beta-checker   File: TestCompiler.java   View Source Code Vote up 6 votes
/**
 * Asserts that the given diagnostics contain errors with a message containing "[CheckerName]"
 * on the given lines of the given file. If there should be multiple errors on a line, the line
 * number must appear multiple times. There may not be any errors in any other file.
 */
public void assertErrorsOnLines(String file,
    List<Diagnostic<? extends JavaFileObject>> diagnostics, long... lines) {
  ListMultimap<String, Long> actualErrors = ArrayListMultimap.create();
  for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
    String message = diagnostic.getMessage(Locale.US);

    // The source may be null, e.g. for diagnostics about command-line flags
    assertNotNull(message, diagnostic.getSource());
    String sourceName = diagnostic.getSource().getName();

    assertEquals(
        "unexpected error in source file " + sourceName + ": " + message,
        file, sourceName);

    actualErrors.put(diagnostic.getSource().getName(), diagnostic.getLineNumber());

    // any errors from the compiler that are not related to this checker should fail
    assertThat(message).contains("[" + checker.getAnnotation(BugPattern.class).name() + "]");
  }

  assertEquals(
      ImmutableMultiset.copyOf(Longs.asList(lines)),
      ImmutableMultiset.copyOf(actualErrors.get(file)));
}
 
Example 3
Project: Reer   File: TaskDetailPrinter.java   View Source Code Vote up 6 votes
private ListMultimap<Class, Task> groupTasksByType(List<Task> tasks) {
    final Set<Class> taskTypes = new TreeSet<Class>(new Comparator<Class>() {
        public int compare(Class o1, Class o2) {
            return o1.getSimpleName().compareTo(o2.getSimpleName());
        }
    });
    taskTypes.addAll(collect(tasks, new Transformer<Class, Task>() {
        public Class transform(Task original) {
            return getDeclaredTaskType(original);
        }
    }));

    ListMultimap<Class, Task> tasksGroupedByType = ArrayListMultimap.create();
    for (final Class taskType : taskTypes) {
        tasksGroupedByType.putAll(taskType, filter(tasks, new Spec<Task>() {
            public boolean isSatisfiedBy(Task element) {
                return getDeclaredTaskType(element).equals(taskType);
            }
        }));
    }
    return tasksGroupedByType;
}
 
Example 4
Project: clearwsd   File: TsvResourceInitializer.java   View Source Code Vote up 6 votes
@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 5
Project: Equella   File: TLEAclManagerImpl.java   View Source Code Vote up 6 votes
@Override
@Transactional
public ListMultimap<String, AccessEntry> getExistingEntriesForVirtualNodes(Node... nodes)
{
	Collection<Integer> priorities = Lists.newArrayList();
	for( Node node : nodes )
	{
		if( !node.isVirtual() )
		{
			throw new IllegalArgumentException("Not a virtual node");
		}
		priorities.add(node.getOverridePriority());
		priorities.add(-node.getOverridePriority());
	}
	List<AccessEntry> entries = aclDao.getVirtualAccessEntries(priorities);
	ArrayListMultimap<String, AccessEntry> map = ArrayListMultimap.create();
	for( AccessEntry accessEntry : entries )
	{
		map.put(accessEntry.getTargetObject() + Integer.toString(Math.abs(accessEntry.getAclPriority())),
			accessEntry);
	}
	return map;
}
 
Example 6
Project: ditb   File: AccessControlLists.java   View Source Code Vote up 6 votes
/**
 * Reads user permission assignments stored in the <code>l:</code> column
 * family of the first table row in <code>_acl_</code>.
 *
 * <p>
 * See {@link AccessControlLists class documentation} for the key structure
 * used for storage.
 * </p>
 */
static ListMultimap<String, TablePermission> getPermissions(Configuration conf,
    byte[] entryName) throws IOException {
  if (entryName == null) entryName = ACL_GLOBAL_NAME;

  // for normal user tables, we just read the table row from _acl_
  ListMultimap<String, TablePermission> perms = ArrayListMultimap.create();
  // TODO: Pass in a Connection rather than create one each time.
  try (Connection connection = ConnectionFactory.createConnection(conf)) {
    try (Table table = connection.getTable(ACL_TABLE_NAME)) {
      Get get = new Get(entryName);
      get.addFamily(ACL_LIST_FAMILY);
      Result row = table.get(get);
      if (!row.isEmpty()) {
        perms = parsePermissions(entryName, row);
      } else {
        LOG.info("No permissions found in " + ACL_TABLE_NAME + " for acl entry "
            + Bytes.toString(entryName));
      }
    }
  }

  return perms;
}
 
Example 7
Project: OperatieBRP   File: ElementHelper.java   View Source Code Vote up 6 votes
private void mapSorteerAttributen() {
    final Map<Integer, GroepElement> objectSorteerGroepTemp = Maps.newHashMap();
    final ArrayListMultimap<GroepElement, AttribuutElement> sorteerElementenVoorGroep = ArrayListMultimap.create();
    for (final AttribuutElement attribuutElement : idAttribuutMap.values()) {
        if (attribuutElement.getElement().getElementWaarde().getSorteervolgorde() != null) {
            objectSorteerGroepTemp.put(attribuutElement.getObjectType(), idGroepMap.get(attribuutElement.getGroepId()));
            sorteerElementenVoorGroep.put(idGroepMap.get(attribuutElement.getGroepId()), attribuutElement);
        }
    }
    objectSorteerGroepMap = ImmutableMap.copyOf(objectSorteerGroepTemp);
    final Map<GroepElement, List<AttribuutElement>> gesorteerdeElementenVoorGroepTemp = new HashMap<>();

    for (GroepElement groepElement : sorteerElementenVoorGroep.keySet()) {
        final List<AttribuutElement> sorteerAttributen = sorteerElementenVoorGroep.get(groepElement);
        sorteerAttributen.sort(
                Comparator.comparing(o -> o.getElement().getElementWaarde().getSorteervolgorde()));
        gesorteerdeElementenVoorGroepTemp.put(groepElement, sorteerAttributen);
    }
    sorteerAttributenVoorGroep = ImmutableMap.copyOf(gesorteerdeElementenVoorGroepTemp);
}
 
Example 8
Project: fpm   File: HsnpDbf.java   View Source Code Vote up 6 votes
private static ArrayListMultimap<Long, Speed> loadHsnp(String filename) {
    File file = new File(filename);
    ArrayListMultimap<Long, Speed> speeds = ArrayListMultimap.create();
    if (!file.exists()) {
        log.info("File not found : {}", file.getAbsolutePath());
        return speeds;
    }

    log.info("Reading HSNP {}", file);
    try (DbfReader reader = new DbfReader(file)) {
        DbfRow row;
        while ((row = reader.nextRow()) != null) {
            Speed speed = parse(row);
            speeds.put(speed.getId(), speed);
        }
    }
    log.info("Loaded {} speed profile", speeds.size());
    return speeds;
}
 
Example 9
Project: QDrill   File: BroadcastSenderRootExec.java   View Source Code Vote up 5 votes
public BroadcastSenderRootExec(FragmentContext context,
                               RecordBatch incoming,
                               BroadcastSender config) throws OutOfMemoryException {
  super(context, context.newOperatorContext(config, null, false), config);
  this.ok = true;
  this.incoming = incoming;
  this.config = config;
  this.handle = context.getHandle();
  List<MinorFragmentEndpoint> destinations = config.getDestinations();
  ArrayListMultimap<DrillbitEndpoint, Integer> dests = ArrayListMultimap.create();

  for(MinorFragmentEndpoint destination : destinations) {
    dests.put(destination.getEndpoint(), destination.getId());
  }

  int destCount = dests.keySet().size();
  int i = 0;

  this.tunnels = new AccountingDataTunnel[destCount];
  this.receivingMinorFragments = new int[destCount][];
  for(final DrillbitEndpoint ep : dests.keySet()){
    List<Integer> minorsList= dests.get(ep);
    int[] minorsArray = new int[minorsList.size()];
    int x = 0;
    for(Integer m : minorsList){
      minorsArray[x++] = m;
    }
    receivingMinorFragments[i] = minorsArray;
    tunnels[i] = context.getDataTunnel(ep);
    i++;
  }
}
 
Example 10
Project: Reer   File: ComponentAttributeMatcher.java   View Source Code Vote up 5 votes
private List<HasAttributes> selectClosestMatches(List<HasAttributes> fullMatches) {
    Set<Attribute<?>> requestedAttributes = consumerAttributesContainer.keySet();
    // if there's more than one compatible match, prefer the closest. However there's a catch.
    // We need to look at all candidates globally, and select the closest match for each attribute
    // then see if there's a non-empty intersection.
    List<HasAttributes> remainingMatches = Lists.newArrayList(fullMatches);
    List<HasAttributes> best = Lists.newArrayListWithCapacity(fullMatches.size());
    final ListMultimap<AttributeValue<Object>, HasAttributes> candidatesByValue = ArrayListMultimap.create();
    for (Attribute<?> attribute : requestedAttributes) {
        Object requestedValue = consumerAttributesContainer.getAttribute(attribute);
        for (HasAttributes match : fullMatches) {
            Map<Attribute<Object>, AttributeValue<Object>> matchedAttributes = matchDetails.get(match).matchesByAttribute;
            candidatesByValue.put(matchedAttributes.get(attribute), match);
        }
        final AttributeValue<Object> requested = AttributeValue.of(requestedValue);
        disambiguate(remainingMatches, candidatesByValue, requested, consumerAttributeSchema.getMatchingStrategy(attribute), best);
        if (remainingMatches.isEmpty()) {
            // the intersection is empty, so we cannot choose
            return fullMatches;
        }
        candidatesByValue.clear();
        best.clear();
    }
    if (!remainingMatches.isEmpty()) {
        // there's a subset (or not) of best matches
        return remainingMatches;
    }
    return null;
}
 
Example 11
Project: abhot   File: RemoteDatastore.java   View Source Code Vote up 5 votes
private Multimap<DataPointKey, DataPoint> createNewMap()
{
	Multimap<DataPointKey, DataPoint> ret;
	synchronized (m_mapLock)
	{
		ret = m_dataPointMultimap;

		m_dataPointMultimap = ArrayListMultimap.<DataPointKey, DataPoint>create();
	}

	return ret;
}
 
Example 12
Project: dremio-oss   File: BroadcastOperator.java   View Source Code Vote up 5 votes
public BroadcastOperator(TunnelProvider tunnelProvider, OperatorContext context, BroadcastSender config) throws OutOfMemoryException {
  super(config);
  this.config = config;
  this.context = context;
  this.handle = context.getFragmentHandle();
  this.stats = context.getStats();

  final List<MinorFragmentEndpoint> destinations = config.getDestinations();
  final ArrayListMultimap<NodeEndpoint, Integer> dests = ArrayListMultimap.create();

  for(MinorFragmentEndpoint destination : destinations) {
    dests.put(destination.getEndpoint(), destination.getId());
  }

  int destCount = dests.keySet().size();
  int i = 0;

  this.tunnels = new AccountingExecTunnel[destCount];
  this.receivingMinorFragments = new int[destCount][];
  for(final NodeEndpoint ep : dests.keySet()){
    List<Integer> minorsList= dests.get(ep);
    int[] minorsArray = new int[minorsList.size()];
    int x = 0;
    for(Integer m : minorsList){
      minorsArray[x++] = m;
    }
    receivingMinorFragments[i] = minorsArray;
    tunnels[i] = tunnelProvider.getExecTunnel(ep);
    i++;
  }
}
 
Example 13
Project: dremio-oss   File: AbstractMuxExchange.java   View Source Code Vote up 5 votes
protected void createSenderReceiverMapping() {
  if (isSenderReceiverMappingCreated) {
    return;
  }

  senderToReceiverMapping = Maps.newHashMap();
  receiverToSenderMapping = ArrayListMultimap.create();

  // Find the list of sender fragment ids assigned to each SabotNode endpoint.
  ArrayListMultimap<NodeEndpoint, Integer> endpointSenderList = ArrayListMultimap.create();

  int senderFragmentId = 0;
  for(NodeEndpoint senderLocation : senderLocations) {
    endpointSenderList.put(senderLocation, senderFragmentId);
    senderFragmentId++;
  }

  int receiverFragmentId = 0;
  for(NodeEndpoint receiverLocation : receiverLocations) {
    List<Integer> senderFragmentIds = endpointSenderList.get(receiverLocation);

    for(Integer senderId : senderFragmentIds) {
      senderToReceiverMapping.put(senderId, new MinorFragmentEndpoint(receiverFragmentId, receiverLocation));

      receiverToSenderMapping.put(receiverFragmentId,
          new MinorFragmentEndpoint(senderId, senderLocations.get(senderId)));
    }
    receiverFragmentId++;
  }

  isSenderReceiverMappingCreated = true;
}
 
Example 14
Project: grammaticus   File: ComplexGrammaticalForm.java   View Source Code Vote up 5 votes
/**
 * For possessive languages, it makes sense to keep an enum map around for that
 */
public static <A extends NounForm> EnumMap<LanguagePossessive,NounFormMap<A>> getPossessiveSpecificMap(Collection<? extends A> forms) {
    Multimap<LanguagePossessive,A> mm = ArrayListMultimap.create();
    for (A form : forms) {
        mm.put(form.getPossessive(), form);
    }
    EnumMap<LanguagePossessive,NounFormMap<A>> result = new EnumMap<LanguagePossessive,NounFormMap<A>>(LanguagePossessive.class);
    for (LanguagePossessive poss : LanguagePossessive.values()) {
        result.put(poss, new NounFormMap<A>(mm.get(poss)));
    }
    return result;
}
 
Example 15
Project: Reer   File: DefaultStructBindingsStore.java   View Source Code Vote up 4 votes
private static <T> Set<StructMethodBinding> collectMethodBindings(StructBindingExtractionContext<T> extractionContext, Map<String, Multimap<PropertyAccessorType, StructMethodBinding>> propertyBindings) {
    Collection<WeaklyTypeReferencingMethod<?, ?>> implementedMethods = collectImplementedMethods(extractionContext.getImplementedSchemas());
    Map<Wrapper<Method>, WeaklyTypeReferencingMethod<?, ?>> publicViewImplMethods = collectPublicViewImplMethods(extractionContext.getPublicSchema());
    Map<Wrapper<Method>, WeaklyTypeReferencingMethod<?, ?>> delegateMethods = collectDelegateMethods(extractionContext.getDelegateSchema());

    ImmutableSet.Builder<StructMethodBinding> methodBindingsBuilder = ImmutableSet.builder();
    for (WeaklyTypeReferencingMethod<?, ?> weakImplementedMethod : implementedMethods) {
        Method implementedMethod = weakImplementedMethod.getMethod();
        PropertyAccessorType accessorType = PropertyAccessorType.of(implementedMethod);

        Wrapper<Method> methodKey = SIGNATURE_EQUIVALENCE.wrap(implementedMethod);
        WeaklyTypeReferencingMethod<?, ?> weakDelegateImplMethod = delegateMethods.get(methodKey);
        WeaklyTypeReferencingMethod<?, ?> weakPublicImplMethod = publicViewImplMethods.get(methodKey);
        if (weakDelegateImplMethod != null && weakPublicImplMethod != null) {
            extractionContext.add(weakImplementedMethod, String.format("it is both implemented by the view '%s' and the delegate type '%s'",
                extractionContext.getPublicSchema().getType().getDisplayName(),
                extractionContext.getDelegateSchema().getType().getDisplayName()));
        }

        String propertyName = accessorType == null ? null : accessorType.propertyNameFor(implementedMethod);

        StructMethodBinding binding;
        if (!Modifier.isAbstract(implementedMethod.getModifiers())) {
            binding = new DirectMethodBinding(weakImplementedMethod, accessorType);
        } else if (weakPublicImplMethod != null) {
            binding = new BridgeMethodBinding(weakImplementedMethod, weakPublicImplMethod, accessorType);
        } else if (weakDelegateImplMethod != null) {
            binding = new DelegateMethodBinding(weakImplementedMethod, weakDelegateImplMethod, accessorType);
        } else if (propertyName != null) {
            binding = new ManagedPropertyMethodBinding(weakImplementedMethod, propertyName, accessorType);
        } else {
            handleNoMethodImplementation(extractionContext, weakImplementedMethod);
            continue;
        }
        methodBindingsBuilder.add(binding);

        if (accessorType != null) {
            Multimap<PropertyAccessorType, StructMethodBinding> accessorBindings = propertyBindings.get(propertyName);
            if (accessorBindings == null) {
                accessorBindings = ArrayListMultimap.create();
                propertyBindings.put(propertyName, accessorBindings);
            }
            accessorBindings.put(accessorType, binding);
        }
    }
    return methodBindingsBuilder.build();
}
 
Example 16
Project: hadoop   File: MaxRunningAppsEnforcer.java   View Source Code Vote up 4 votes
public MaxRunningAppsEnforcer(FairScheduler scheduler) {
  this.scheduler = scheduler;
  this.usersNumRunnableApps = new HashMap<String, Integer>();
  this.usersNonRunnableApps = ArrayListMultimap.create();
}
 
Example 17
Project: Equella   File: ItemServiceImpl.java   View Source Code Vote up 4 votes
@Override
public void updateMetadataBasedSecurity(PropBagEx itemxml, Item item)
{
	Workflow workflow = item.getItemDefinition().getWorkflow();
	WorkflowTaskDynamicTarget itemTask = new WorkflowTaskDynamicTarget(item.getId());

	List<TargetListEntry> entries = acquireTargetListEntries(workflow, itemxml, item);

	TargetList targetList = new TargetList();
	targetList.setPartial(true);
	targetList.setEntries(entries);
	aclManager.setTargetList(Node.WORKFLOW_TASK, itemTask, targetList);

	setItemMetadataSecurityTargets(itemxml, item);

	// Dynamic ACLs
	List<DynamicMetadataRule> dynamicMetadataRules = item.getItemDefinition().getDynamicMetadataRules();

	if( !Check.isEmpty(dynamicMetadataRules) )
	{
		// Map of Lists<Privilege, List<Pair<Grant/Revoke, UserID>>>
		Multimap<String, Pair<Boolean, String>> privMultimap = ArrayListMultimap.create();

		for( DynamicMetadataRule rule : dynamicMetadataRules )
		{
			List<String> ids = Lists.newArrayList(itemxml.getNodeList(rule.getPath()));

			for( String id : ids )
			{
				for( TargetListEntry tle : rule.getTargetList().getEntries() )
				{
					privMultimap.put(tle.getPrivilege(), new Pair<Boolean, String>(tle.isGranted(),
						SecurityConstants.getRecipient(SecurityConstants.getRecipientType(rule.getType()), id)));
				}
			}
		}

		List<TargetListEntry> tlEntries = Lists.newArrayList();

		// Create target list
		for( String privilege : privMultimap.keySet() )
		{
			Collection<Pair<Boolean, String>> listOfGrants = privMultimap.get(privilege);

			if( !Check.isEmpty(listOfGrants) )
			{
				getTargetListEntriesFromGrants(tlEntries, listOfGrants, privilege);
			}
		}
		TargetList dynaMetaTargetList = new TargetList(tlEntries);

		aclManager.setTargetList(Node.DYNAMIC_ITEM_METADATA, new ItemDynamicMetadataTarget(item),
			dynaMetaTargetList);
	}
	else
	{
		aclManager.setTargetList(Node.DYNAMIC_ITEM_METADATA, new ItemDynamicMetadataTarget(item), null);
	}
}
 
Example 18
Project: Equella   File: TermServiceImpl.java   View Source Code Vote up 4 votes
@Override
public void doImport(final Taxonomy taxonomy, final SubTemporaryFile termFolder, Institution institution,
	ConverterParams params)
{
	final List<String> termFiles = xmlHelper.getXmlFileListOrdered(termFolder);

	final DefaultMessageCallback part1message = new DefaultMessageCallback(
		 resources.key("converter.readingterms.progressmessage"));
	params.setMessageCallback(part1message);
	part1message.setTotal(termFiles.size());
	part1message.setType(resources.getString("type.terms"));
	part1message.setCurrent(0);

	// build a GIANT hash map
	final Multimap<WrappedTerm, WrappedTerm> childTermMap = ArrayListMultimap.create();
	final Map<String, WrappedTerm> valueTermMap = new HashMap<String, WrappedTerm>();
	final Map<Long, WrappedTerm> idTermMap = new HashMap<Long, WrappedTerm>();
	final WrappedTerm nullTerm = new WrappedTerm(null, null);

	for( String termFile : termFiles )
	{
		final Term term = xmlHelper.readXmlFile(termFolder, termFile);

		// We first check to see if we've already imported a node with the
		// same full path. This can happen with old data where root-level
		// nodes could be duplicated. idTermMap contains all the duplicate
		// ids, but maps them to the same object representing the first
		// duplicate term that was imported. All child terms of all
		// duplicates will then get the same parent.
		WrappedTerm wrappedTerm = valueTermMap.get(term.getFullValue());
		if( wrappedTerm == null )
		{
			term.setTaxonomy(taxonomy);

			// This ensures the value hash is set correctly, especially if
			// we're updating from 5.1 or earlier where the hash didn't
			// exist.
			term.setValue(term.getValue());

			// Term object has a (persisted) UUID property
			if( Check.isEmpty(term.getUuid()) )
			{
				term.setUuid(UUID.randomUUID().toString());
			}
			// Note that pt only has the id field during institution imports
			final Term pt = term.getParent();
			final WrappedTerm parentWT = pt == null ? nullTerm : idTermMap.get(pt.getId());

			wrappedTerm = new WrappedTerm(term, parentWT);
			addToChildTermMap(childTermMap, parentWT, wrappedTerm);

			valueTermMap.put(wrappedTerm.getTerm().getFullValue(), wrappedTerm);
		}
		idTermMap.put(term.getId(), wrappedTerm);

		part1message.incrementCurrent();
	}

	final DefaultMessageCallback part2message = new DefaultMessageCallback(resources.key("converter.savingterms.progressmessage"));
	params.setMessageCallback(part2message);
	part2message.setTotal(termFiles.size());
	part2message.setType(resources.getString("type.terms"));
	part2message.setCurrent(0);

	// save the terms
	doInTransaction(new Runnable()
	{
		@Override
		public void run()
		{
			processTermChildren(nullTerm, childTermMap, part2message);
		}
	});
}
 
Example 19
Project: Equella   File: InstitutionServiceImpl.java   View Source Code Vote up 4 votes
private synchronized void setAllInstitutions(Map<Long, InstitutionStatus> map)
{
	allInstitutions = ImmutableMap.copyOf(map);

	Multimap<Long, Institution> newlyAvailable = ArrayListMultimap.create();
	Multimap<Long, Institution> newlyUnavailable = ArrayListMultimap.create(availableInstitutions);
	Builder<Long, Institution> availableBuilder = ImmutableMultimap.builder();
	ImmutableMap.Builder<Long, Long> schemaBuilder = ImmutableMap.builder();
	ImmutableMap.Builder<Long, Institution> instBuilder = ImmutableMap.builder();
	for( Entry<Long, InstitutionStatus> entry : allInstitutions.entrySet() )
	{
		InstitutionStatus instStatus = entry.getValue();
		Institution institution = instStatus.getInstitution();
		Long schemaId = instStatus.getSchemaId();
		if( instStatus.isValid() && institution.isEnabled() )
		{
			availableBuilder.put(schemaId, institution);
			if( !newlyUnavailable.remove(schemaId, institution) )
			{
				newlyAvailable.put(schemaId, institution);
			}
		}
		long uniqueId = institution.getUniqueId();
		schemaBuilder.put(uniqueId, schemaId);
		instBuilder.put(uniqueId, institution);
	}

	availableInstitutions = availableBuilder.build();
	schemaMap = schemaBuilder.build();
	instMap = instBuilder.build();

	if( !newlyAvailable.isEmpty() )
	{
		eventService.publishApplicationEvent(new InstitutionEvent(InstitutionEventType.AVAILABLE, newlyAvailable));
	}

	if( !newlyUnavailable.isEmpty() )
	{
		eventService
				.publishApplicationEvent(new InstitutionEvent(InstitutionEventType.UNAVAILABLE, newlyUnavailable));
	}
}
 
Example 20
Project: mqtt-topic-dispatcher   File: TopicDispatcher.java   View Source Code Vote up 4 votes
/** Constructor */
public TopicDispatcher() {
    _exactMatchHanders = ArrayListMultimap.create(16, 2);
    _hierarchicallyMatcher = new HierarchicallyTopicMatcher<>();
}