Example usage for com.google.common.collect Multimap asMap

List of usage examples for com.google.common.collect Multimap asMap

Introduction

In this page you can find the example usage for com.google.common.collect Multimap asMap.

Prototype

Map<K, Collection<V>> asMap();

Source Link

Document

Returns a view of this multimap as a Map from each distinct key to the nonempty collection of that key's associated values.

Usage

From source file:com.torodb.backend.AbstractReadInterface.java

@SuppressFBWarnings(value = { "OBL_UNSATISFIED_OBLIGATION",
        "ODR_OPEN_DATABASE_RESOURCE" }, justification = "ResultSet is wrapped in a Cursor<Integer>. It's iterated and closed in caller code")
private Cursor<Integer> getCollectionDidsWithFieldsInBatch(DSLContext dsl, MetaDatabase metaDatabase,
        MetaCollection metaCol, MetaDocPart metaDocPart, Multimap<MetaField, KvValue<?>> valuesMultimap)
        throws SQLException {
    @SuppressWarnings("checkstyle:LineLength")
    Provider<Stream<Map.Entry<MetaField, Collection<KvValue<?>>>>> valuesMultimapSortedStreamProvider = () -> valuesMultimap
            .asMap().entrySet().stream()
            .sorted((e1, e2) -> e1.getKey().getIdentifier().compareTo(e2.getKey().getIdentifier()));
    String statement = getReadCollectionDidsWithFieldInStatement(metaDatabase.getIdentifier(),
            metaDocPart.getIdentifier(), valuesMultimapSortedStreamProvider.get()
                    .map(e -> new Tuple2<String, Integer>(e.getKey().getIdentifier(), e.getValue().size())));
    Connection connection = dsl.configuration().connectionProvider().acquire();
    try {/* w  w  w  . j  av  a  2 s.co m*/
        PreparedStatement preparedStatement = connection.prepareStatement(statement);
        int parameterIndex = 1;
        Iterator<Map.Entry<MetaField, Collection<KvValue<?>>>> valuesMultimapSortedIterator = valuesMultimapSortedStreamProvider
                .get().iterator();
        while (valuesMultimapSortedIterator.hasNext()) {
            Map.Entry<MetaField, Collection<KvValue<?>>> valuesMultimapEntry = valuesMultimapSortedIterator
                    .next();
            for (KvValue<?> value : valuesMultimapEntry.getValue()) {
                sqlHelper.setPreparedStatementValue(preparedStatement, parameterIndex,
                        valuesMultimapEntry.getKey().getType(), value);
                parameterIndex++;
            }
        }
        return new DefaultDidCursor(errorHandler, preparedStatement.executeQuery());
    } finally {
        dsl.configuration().connectionProvider().release(connection);
    }
}

From source file:com.haulmont.cuba.core.sys.PersistenceSecurityImpl.java

@Override
@SuppressWarnings("unchecked")
public void restoreFilteredData(Entity entity) {
    MetaClass metaClass = metadata.getClassNN(entity.getClass());
    String storeName = metadataTools.getStoreName(metaClass);
    EntityManager entityManager = persistence.getEntityManager(storeName);

    Multimap<String, Object> filtered = BaseEntityInternalAccess.getFilteredData(entity);
    if (filtered == null) {
        return;/*from   w  ww.  j  a  v a  2s.  c o  m*/
    }

    for (Map.Entry<String, Collection<Object>> entry : filtered.asMap().entrySet()) {
        MetaProperty property = metaClass.getPropertyNN(entry.getKey());
        Collection filteredIds = entry.getValue();

        if (property.getRange().isClass() && CollectionUtils.isNotEmpty(filteredIds)) {
            Class entityClass = property.getRange().asClass().getJavaClass();
            Class propertyClass = property.getJavaType();
            if (Collection.class.isAssignableFrom(propertyClass)) {
                Collection currentCollection = entity.getValue(property.getName());
                if (currentCollection == null) {
                    throw new RowLevelSecurityException(format(
                            "Could not restore an object to currentValue because it is null [%s]. Entity [%s].",
                            property.getName(), metaClass.getName()), metaClass.getName());
                }

                for (Object entityId : filteredIds) {
                    Entity reference = entityManager.getReference((Class<Entity>) entityClass, entityId);
                    //we ignore situations when the currentValue is immutable
                    currentCollection.add(reference);
                }
            } else if (Entity.class.isAssignableFrom(propertyClass)) {
                Object entityId = filteredIds.iterator().next();
                Entity reference = entityManager.getReference((Class<Entity>) entityClass, entityId);
                //we ignore the situation when the field is read-only
                entity.setValue(property.getName(), reference);
            }
        }
    }
}

From source file:com.bigdata.dastor.service.StorageProxy.java

public static void mutateBlocking(List<RowMutation> mutations, ConsistencyLevel consistency_level)
        throws UnavailableException, TimeoutException {
    long startTime = System.nanoTime();
    ArrayList<WriteResponseHandler> responseHandlers = new ArrayList<WriteResponseHandler>();

    RowMutation mostRecentRowMutation = null;
    StorageService ss = StorageService.instance;
    try {//from  w  w w  . jav  a  2s .co  m
        for (RowMutation rm : mutations) {
            mostRecentRowMutation = rm;
            String table = rm.getTable();
            AbstractReplicationStrategy rs = ss.getReplicationStrategy(table);

            List<InetAddress> naturalEndpoints = ss.getNaturalEndpoints(table, rm.key());
            Collection<InetAddress> writeEndpoints = rs.getWriteEndpoints(
                    StorageService.getPartitioner().getToken(rm.key()), table, naturalEndpoints);
            Multimap<InetAddress, InetAddress> hintedEndpoints = rs.getHintedEndpoints(table, writeEndpoints);
            int blockFor = determineBlockFor(writeEndpoints.size(), consistency_level);

            // avoid starting a write we know can't achieve the required consistency
            assureSufficientLiveNodes(blockFor, writeEndpoints, hintedEndpoints, consistency_level);

            // send out the writes, as in mutate() above, but this time with a callback that tracks responses
            final WriteResponseHandler responseHandler = ss.getWriteResponseHandler(blockFor, consistency_level,
                    table);
            responseHandlers.add(responseHandler);
            Message unhintedMessage = null;
            for (Map.Entry<InetAddress, Collection<InetAddress>> entry : hintedEndpoints.asMap().entrySet()) {
                InetAddress destination = entry.getKey();
                Collection<InetAddress> targets = entry.getValue();

                if (targets.size() == 1 && targets.iterator().next().equals(destination)) {
                    // unhinted writes
                    if (destination.equals(FBUtilities.getLocalAddress())) {
                        insertLocalMessage(rm, responseHandler);
                    } else {
                        // belongs on a different server.  send it there.
                        if (unhintedMessage == null) {
                            unhintedMessage = rm.makeRowMutationMessage();
                            MessagingService.instance.addCallback(responseHandler,
                                    unhintedMessage.getMessageId());
                        }
                        if (logger.isDebugEnabled())
                            logger.debug("insert writing key " + rm.key() + " to "
                                    + unhintedMessage.getMessageId() + "@" + destination);
                        MessagingService.instance.sendOneWay(unhintedMessage, destination);
                    }
                } else {
                    // hinted
                    Message hintedMessage = rm.makeRowMutationMessage();
                    for (InetAddress target : targets) {
                        if (!target.equals(destination)) {
                            addHintHeader(hintedMessage, target);
                            if (logger.isDebugEnabled())
                                logger.debug("insert writing key " + rm.key() + " to "
                                        + hintedMessage.getMessageId() + "@" + destination + " for " + target);
                        }
                    }
                    // (non-destination hints are part of the callback and count towards consistency only under CL.ANY)
                    if (writeEndpoints.contains(destination) || consistency_level == ConsistencyLevel.ANY)
                        MessagingService.instance.addCallback(responseHandler, hintedMessage.getMessageId());
                    MessagingService.instance.sendOneWay(hintedMessage, destination);
                }
            }
        }
        // wait for writes.  throws timeoutexception if necessary
        for (WriteResponseHandler responseHandler : responseHandlers) {
            responseHandler.get();
        }
    } catch (IOException e) {
        if (mostRecentRowMutation == null)
            throw new RuntimeException("no mutations were seen but found an error during write anyway", e);
        else
            throw new RuntimeException("error writing key " + mostRecentRowMutation.key(), e);
    } finally {
        writeStats.addNano(System.nanoTime() - startTime);
    }

}

From source file:org.apache.hadoop.hive.ql.exec.tez.SplitGrouper.java

/**
 * group splits for each bucket separately - while evenly filling all the
 * available slots with tasks/*www  .  j a  va  2 s .c o m*/
 */
public Multimap<Integer, InputSplit> group(Configuration conf,
        Multimap<Integer, InputSplit> bucketSplitMultimap, int availableSlots, float waves,
        SplitLocationProvider splitLocationProvider) throws IOException {

    // figure out how many tasks we want for each bucket
    Map<Integer, Integer> bucketTaskMap = estimateBucketSizes(availableSlots, waves,
            bucketSplitMultimap.asMap());

    // allocate map bucket id to grouped splits
    Multimap<Integer, InputSplit> bucketGroupedSplitMultimap = ArrayListMultimap.<Integer, InputSplit>create();

    // use the tez grouper to combine splits once per bucket
    for (int bucketId : bucketSplitMultimap.keySet()) {
        Collection<InputSplit> inputSplitCollection = bucketSplitMultimap.get(bucketId);

        InputSplit[] rawSplits = inputSplitCollection.toArray(new InputSplit[0]);
        InputSplit[] groupedSplits = tezGrouper.getGroupedSplits(conf, rawSplits, bucketTaskMap.get(bucketId),
                HiveInputFormat.class.getName(), new ColumnarSplitSizeEstimator(), splitLocationProvider);

        LOG.info("Original split count is " + rawSplits.length + " grouped split count is "
                + groupedSplits.length + ", for bucket: " + bucketId);

        for (InputSplit inSplit : groupedSplits) {
            bucketGroupedSplitMultimap.put(bucketId, inSplit);
        }
    }

    return bucketGroupedSplitMultimap;
}

From source file:com.github.legman.EventBus.java

/**
 * Unregisters all handler methods on a registered {@code object}.
 *
 * @param object  object whose handler methods should be unregistered.
 * @throws IllegalArgumentException if the object was not previously registered.
 *//*  w ww.j  a va  2  s  . com*/
public void unregister(Object object) {
    Multimap<Class<?>, EventHandler> methodsInListener = finder.findAllHandlers(this, object);
    for (Entry<Class<?>, Collection<EventHandler>> entry : methodsInListener.asMap().entrySet()) {
        Class<?> eventType = entry.getKey();
        Collection<EventHandler> eventMethodsInListener = entry.getValue();

        handlersByTypeLock.writeLock().lock();
        try {
            Set<EventHandler> currentHandlers = handlersByType.get(eventType);
            if (!currentHandlers.containsAll(eventMethodsInListener)) {
                throw new IllegalArgumentException(
                        "missing event handler for an annotated method. Is " + object + " registered?");
            }
            currentHandlers.removeAll(eventMethodsInListener);
        } finally {
            handlersByTypeLock.writeLock().unlock();
        }
    }
}

From source file:com.google.gerrit.server.mail.ChangeEmail.java

/** BCC any user who has starred this change. */
protected void bccStarredBy() {
    if (!NotifyHandling.ALL.equals(notify)) {
        return;/*from ww w.  ja  v  a2 s. c o  m*/
    }

    try {
        // BCC anyone who has starred this change
        // and remove anyone who has ignored this change.
        //
        Multimap<Account.Id, String> stars = args.starredChangesUtil.byChangeFromIndex(change.getId());
        for (Map.Entry<Account.Id, Collection<String>> e : stars.asMap().entrySet()) {
            if (e.getValue().contains(StarredChangesUtil.DEFAULT_LABEL)) {
                super.add(RecipientType.BCC, e.getKey());
            }
            if (e.getValue().contains(StarredChangesUtil.IGNORE_LABEL)) {
                AccountState accountState = args.accountCache.get(e.getKey());
                if (accountState != null) {
                    removeUser(accountState.getAccount());
                }
            }
        }
    } catch (OrmException | NoSuchChangeException err) {
        // Just don't BCC everyone. Better to send a partial message to those
        // we already have queued up then to fail deliver entirely to people
        // who have a lower interest in the change.
        log.warn("Cannot BCC users that starred updated change", err);
    }
}

From source file:com.google.errorprone.bugpatterns.inject.guice.AssistedParameters.java

@Override
public final Description matchMethod(MethodTree constructor, final VisitorState state) {
    if (!IS_CONSTRUCTOR_WITH_INJECT_OR_ASSISTED.matches(constructor, state)) {
        return Description.NO_MATCH;
    }/*ww w  .j a v  a  2 s.  c  om*/

    // Gather @Assisted parameters, partition by type
    MultiMatchResult<VariableTree> assistedParameters = ASSISTED_PARAMETER_MATCHER.multiMatchResult(constructor,
            state);
    if (!assistedParameters.matches()) {
        return Description.NO_MATCH;
    }

    Multimap<Type, VariableTree> parametersByType = partitionParametersByType(
            assistedParameters.matchingNodes(), state);

    // If there's more than one parameter with the same type, they could conflict unless their
    // @Assisted values are different.
    List<ConflictResult> conflicts = new ArrayList<>();
    for (Map.Entry<Type, Collection<VariableTree>> typeAndParameters : parametersByType.asMap().entrySet()) {
        Collection<VariableTree> parametersForThisType = typeAndParameters.getValue();
        if (parametersForThisType.size() < 2) {
            continue;
        }

        // Gather the @Assisted value from each parameter. If any value is repeated amongst the
        // parameters in this type, it's a compile error.
        ImmutableListMultimap<String, VariableTree> keyForAssistedVariable = Multimaps
                .index(parametersForThisType, VALUE_FROM_ASSISTED_ANNOTATION);

        for (Entry<String, List<VariableTree>> assistedValueToParameters : Multimaps
                .asMap(keyForAssistedVariable).entrySet()) {
            if (assistedValueToParameters.getValue().size() > 1) {
                conflicts.add(ConflictResult.create(typeAndParameters.getKey(),
                        assistedValueToParameters.getKey(), assistedValueToParameters.getValue()));
            }
        }
    }

    if (conflicts.isEmpty()) {
        return Description.NO_MATCH;
    }

    return buildDescription(constructor).setMessage(buildErrorMessage(conflicts)).build();
}

From source file:com.b2international.snowowl.snomed.datastore.request.SnomedBulkRequest.java

@Override
public R execute(TransactionContext context) {
    ImmutableList.Builder<SnomedComponentRequest<?>> requests = ImmutableList.builder();
    ImmutableList.Builder<DeleteRequest> deletions = ImmutableList.builder();
    collectNestedRequests(next(), requests, deletions);

    // Prefetch all component IDs mentioned in reference set member creation requests, abort if any of them can not be found
    final Set<String> requiredComponentIds = requests.build().stream()
            .flatMap(request -> request.getRequiredComponentIds(context).stream())
            .filter(componentId -> SnomedTerminologyComponentConstants
                    .getTerminologyComponentIdValueSafe(componentId) != -1L) // just in case filter out invalid component IDs
            .collect(Collectors.toSet());

    final Multimap<Class<? extends CDOObject>, String> componentIdsByType = HashMultimap
            .create(FluentIterable.from(requiredComponentIds).index(this::getCdoType));

    // collect all deleted IDs as well
    deletions.build().stream().map(DeleteRequest::getComponentId)
            .forEach(componentId -> componentIdsByType.put(getCdoType(componentId), componentId));

    try {//from  w w w  .  j av a 2 s  . c o m
        for (final Entry<Class<? extends CDOObject>, Collection<String>> idsForType : componentIdsByType.asMap()
                .entrySet()) {
            context.lookup(idsForType.getValue(), idsForType.getKey());
        }
    } catch (final ComponentNotFoundException e) {
        throw e.toBadRequestException();
    }

    // bind additional caches to the context
    TransactionContext newContext = context.inject().bind(Synonyms.class, new Synonyms(context)).build();

    return next(newContext);
}

From source file:com.haulmont.timesheets.gui.approve.BulkTimeEntriesApprove.java

@Override
public void init(Map<String, Object> params) {
    super.init(params);

    if (securityAssistant.isSuperUser()) {
        timeEntriesDs.setQuery("select e from ts$TimeEntry e "
                + "where e.date >= :component$dateFrom and e.date <= :component$dateTo");
    }/* ww w .j a va 2s  . c o  m*/

    timeEntriesTable.getColumn("overtime")
            .setAggregation(ComponentsHelper.createAggregationInfo(
                    projectsService.getEntityMetaPropertyPath(TimeEntry.class, "overtime"),
                    new TimeEntryOvertimeAggregation()));

    timeEntriesDs.addCollectionChangeListener(e -> {
        Multimap<Map<String, Object>, TimeEntry> map = ArrayListMultimap.create();
        for (TimeEntry item : timeEntriesDs.getItems()) {
            Map<String, Object> key = new TreeMap<>();
            key.put("user", item.getUser());
            key.put("date", item.getDate());
            map.put(key, item);
        }

        for (Map.Entry<Map<String, Object>, Collection<TimeEntry>> entry : map.asMap().entrySet()) {
            BigDecimal thisDaysSummary = BigDecimal.ZERO;
            for (TimeEntry timeEntry : entry.getValue()) {
                thisDaysSummary = thisDaysSummary.add(timeEntry.getTimeInHours());
            }

            for (TimeEntry timeEntry : entry.getValue()) {
                BigDecimal planHoursForDay = workdaysTools.isWorkday(timeEntry.getDate())
                        ? workTimeConfigBean.getWorkHourForDay()
                        : BigDecimal.ZERO;
                BigDecimal overtime = thisDaysSummary.subtract(planHoursForDay);
                timeEntry.setOvertimeInHours(overtime);
            }
        }
    });

    Date previousMonth = DateUtils.addMonths(timeSource.currentTimestamp(), -1);
    dateFrom.setValue(DateUtils.truncate(previousMonth, Calendar.MONTH));
    dateTo.setValue(DateUtils.addDays(DateUtils.truncate(timeSource.currentTimestamp(), Calendar.MONTH), -1));

    approve.addAction(new AbstractAction("approveAll") {
        @Override
        public void actionPerform(Component component) {
            setStatus(timeEntriesDs.getItems(), TimeEntryStatus.APPROVED);
        }
    });

    approve.addAction(new AbstractAction("approveSelected") {
        @Override
        public void actionPerform(Component component) {
            setStatus(timeEntriesTable.getSelected(), TimeEntryStatus.APPROVED);
        }
    });

    reject.addAction(new AbstractAction("rejectAll") {
        @Override
        public void actionPerform(Component component) {
            setStatus(timeEntriesDs.getItems(), TimeEntryStatus.REJECTED);
        }
    });

    reject.addAction(new AbstractAction("rejectSelected") {
        @Override
        public void actionPerform(Component component) {
            setStatus(timeEntriesTable.getSelected(), TimeEntryStatus.REJECTED);
        }
    });

    status.setOptionsList(Arrays.asList(TimeEntryStatus.values()));
    user.setOptionsList(
            projectsService.getManagedUsers(userSession.getCurrentOrSubstitutedUser(), View.MINIMAL));
}

From source file:com.github.naios.wide.framework.internal.storage.server.builder.SQLScope.java

private void buildUpdates(final StringBuilder builder,
        final Multimap<ServerStorageStructure, SQLUpdateInfo> multimap) {
    final SQLMaker sqlMaker = new SQLMaker(sqlBuilder, sqlBuilder.getUpdateConfig());

    // TODO Group updates by key or updates
    final Multimap<String /*changes*/, ServerStorageStructure> changesPerStructure = HashMultimap.create();

    // Build Changeset (updates without key)
    for (final Entry<ServerStorageStructure, Collection<SQLUpdateInfo>> info : multimap.asMap().entrySet())
        changesPerStructure.put(sqlMaker.createUpdateFields(info.getKey(), info.getValue()), info.getKey());

    for (final Entry<String, Collection<ServerStorageStructure>> change : changesPerStructure.asMap()
            .entrySet()) {/*from   ww  w  .ja va  2 s  . c o  m*/
        final String tableName = Iterables.get(change.getValue(), 0).getOwner().getTableName();

        final String keyPart = sqlMaker.createKeyPart(change.getValue());

        builder.append(SQLMaker.createUpdateQuery(tableName, change.getKey(), keyPart));
    }

    if (!multimap.isEmpty())
        builder.append(SQLMaker.NEWLINE);
}