Example usage for com.google.common.collect SetMultimap isEmpty

List of usage examples for com.google.common.collect SetMultimap isEmpty

Introduction

In this page you can find the example usage for com.google.common.collect SetMultimap isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this multimap contains no key-value pairs.

Usage

From source file:de.bund.bfr.knime.openkrise.MyKrisenInterfacesNodeModel.java

/**
  * {@inheritDoc}// www  .j a v  a  2s  . c o  m
  */
 @Override
 protected BufferedDataTable[] execute(final BufferedDataTable[] inData, final ExecutionContext exec)
         throws Exception {
     try (Connection conn = set.isUseExternalDb()
             ? createLocalConnection(KnimeUtils.getFile(removeNameOfDB(set.getDbPath())).getAbsolutePath())
             : DBKernel.getLocalConn(true)) {
         boolean useSerialAsID = !set.isAnonymize() && DeliveryUtils.hasUniqueSerials(conn);
         Map<Integer, String> stationIds = DeliveryUtils.getStationIds(conn, useSerialAsID);
         Map<Integer, String> deliveryIds = DeliveryUtils.getDeliveryIds(conn, useSerialAsID);
         SetMultimap<String, String> warnings = LinkedHashMultimap.create();

         List<Delivery> deliveries = DeliveryUtils.getDeliveries(conn, stationIds, deliveryIds, warnings);
         BufferedDataTable stationTable = getStationTable(conn, stationIds, deliveries, exec, useSerialAsID);
         BufferedDataTable deliveryTable = getDeliveryTable(conn, stationIds, deliveryIds, exec, useSerialAsID);
         BufferedDataTable deliveryConnectionsTable = getDeliveryConnectionsTable(deliveries, deliveryTable,
                 exec);

         if (!warnings.isEmpty()) {
             for (Map.Entry<String, Set<String>> entry : Multimaps.asMap(warnings).entrySet()) {
                 setWarningMessage(entry.getKey() + ":");

                 for (String w : entry.getValue()) {
                     setWarningMessage("\t" + w);
                 }
             }

             setWarningMessage("Look into the console - there are plausibility issues...");
         }

         return new BufferedDataTable[] { stationTable, deliveryTable, deliveryConnectionsTable };
     }
 }

From source file:cpw.mods.fml.common.Loader.java

private void identifyDuplicates(List<ModContainer> mods) {
    TreeMultimap<ModContainer, File> dupsearch = TreeMultimap.create(new ModIdComparator(),
            Ordering.arbitrary());/*  ww  w  . j  a v a 2  s  . co  m*/
    for (ModContainer mc : mods) {
        if (mc.getSource() != null) {
            dupsearch.put(mc, mc.getSource());
        }
    }

    ImmutableMultiset<ModContainer> duplist = Multisets.copyHighestCountFirst(dupsearch.keys());
    SetMultimap<ModContainer, File> dupes = LinkedHashMultimap.create();
    for (Entry<ModContainer> e : duplist.entrySet()) {
        if (e.getCount() > 1) {
            FMLLog.severe("Found a duplicate mod %s at %s", e.getElement().getModId(),
                    dupsearch.get(e.getElement()));
            dupes.putAll(e.getElement(), dupsearch.get(e.getElement()));
        }
    }
    if (!dupes.isEmpty()) {
        throw new DuplicateModsFoundException(dupes);
    }
}

From source file:exm.stc.ic.opt.WaitCoalescer.java

/**
 * Try to push down waits from current block into child blocks
 * @param logger/*  w ww. j  a  v  a 2s  .co  m*/
 * @param fn
 * @param block
 * @param currContext
 * @return
 */
private boolean pushDownWaits(Logger logger, Program prog, Function fn, Block block, ExecContext currContext) {
    SetMultimap<Var, InstOrCont> waitMap = buildWaiterMap(prog, block);

    if (logger.isTraceEnabled()) {
        logger.trace("waitMap keys: " + waitMap.keySet());
    }

    if (waitMap.isEmpty()) {
        // If waitMap is empty, can't push anything down, so just shortcircuit
        return false;
    }
    boolean changed = false;

    HashSet<Continuation> allPushedDown = new HashSet<Continuation>();
    ArrayList<Continuation> contCopy = new ArrayList<Continuation>(block.getContinuations());
    for (Continuation c : contCopy) {
        if (allPushedDown.contains(c)) {
            // Was moved
            continue;
        }
        ExecContext newContext = canPushDownInto(c, currContext);
        if (newContext != null) {
            for (Block innerBlock : c.getBlocks()) {
                StackLite<Continuation> ancestors = new StackLite<Continuation>();
                ancestors.push(c);
                PushDownResult pdRes = pushDownWaitsRec(logger, fn, block, currContext, ancestors, innerBlock,
                        newContext, waitMap);
                changed = changed || pdRes.anyChanges;
                /* The list of continuations might be modified as continuations are
                 * pushed down - track which ones are relocated */
                allPushedDown.addAll(pdRes.relocated);
            }
        }
    }
    return changed;
}

From source file:com.zimbra.cs.mailbox.MailboxIndex.java

private synchronized Collection<Integer> getDeferredIds(Set<MailItem.Type> types) throws ServiceException {
    SetMultimap<MailItem.Type, Integer> ids = getDeferredIds();
    if (ids == null || ids.isEmpty()) {
        return Collections.emptyList();
    } else if (types.isEmpty()) {
        return ImmutableSet.copyOf(ids.values());
    } else {/*from   w  w w .  j a v a 2s .c  o m*/
        ImmutableSet.Builder<Integer> builder = ImmutableSet.builder();
        for (MailItem.Type type : types) {
            Set<Integer> set = ids.get(type);
            if (set != null) {
                builder.addAll(set);
            }
        }
        return builder.build();
    }
}

From source file:com.zimbra.cs.mailbox.MailboxIndex.java

/**
 * Returns the index deferred item count for the types.
 *
 * @param types item types, empty set means all types
 * @return index deferred count/* ww w . j  a v a  2 s .  c o m*/
 */
private int getDeferredCount(Set<MailItem.Type> types) {
    SetMultimap<MailItem.Type, Integer> ids;
    try {
        ids = Multimaps.synchronizedSetMultimap(getDeferredIds());
    } catch (ServiceException e) {
        ZimbraLog.index.error("Failed to query deferred IDs", e);
        return 0;
    }

    if (ids == null || ids.isEmpty()) {
        return 0;
    } else if (types.isEmpty()) {
        return ids.size();
    } else {
        int total = 0;
        for (MailItem.Type type : types) {
            total += ids.get(type).size();
        }
        return total;
    }
}

From source file:eu.esdihumboldt.hale.ui.style.TypeStyleHandler.java

/**
 * @see IHandler#execute(ExecutionEvent)
 *//*from   ww w.  ja va2 s . c  om*/
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    ISelection selection = HandlerUtil.getCurrentSelection(event);

    // collect types and associated data sets
    SetMultimap<DataSet, TypeDefinition> types = HashMultimap.create();
    if (selection instanceof IStructuredSelection && !selection.isEmpty()) {
        for (Object object : ((IStructuredSelection) selection).toArray()) {
            if (object instanceof TypeDefinition) {
                TypeDefinition type = (TypeDefinition) object;
                if (!types.containsValue(type)) {
                    DataSet dataSet = findDataSet(type);
                    types.put(dataSet, type);
                }
            }
            if (object instanceof EntityDefinition) {
                EntityDefinition entityDef = (EntityDefinition) object;
                if (entityDef.getPropertyPath().isEmpty()) {
                    DataSet dataSet = (entityDef.getSchemaSpace() == SchemaSpaceID.SOURCE) ? (DataSet.SOURCE)
                            : (DataSet.TRANSFORMED);
                    types.put(dataSet, entityDef.getType());
                }
            }
            if (object instanceof InstanceReference) {
                InstanceService is = (InstanceService) HandlerUtil.getActiveWorkbenchWindow(event)
                        .getWorkbench().getService(InstanceService.class);
                object = is.getInstance((InstanceReference) object);
            }
            if (object instanceof Instance) {
                Instance instance = (Instance) object;
                types.put(instance.getDataSet(), instance.getDefinition());
            }
        }
    }

    Pair<TypeDefinition, DataSet> typeInfo = null;

    // select a type
    if (types.size() == 1) {
        Entry<DataSet, TypeDefinition> entry = types.entries().iterator().next();
        typeInfo = new Pair<TypeDefinition, DataSet>(entry.getValue(), entry.getKey());
    } else if (!types.isEmpty()) {
        // choose through dialog
        DataSetTypeSelectionDialog dialog = new DataSetTypeSelectionDialog(
                Display.getCurrent().getActiveShell(), "Multiple types: select which to change the style for",
                null, types);
        if (dialog.open() == DataSetTypeSelectionDialog.OK) {
            typeInfo = dialog.getObject();
        }
    }

    if (typeInfo != null) {
        try {
            FeatureStyleDialog dialog = new FeatureStyleDialog(typeInfo.getFirst(), typeInfo.getSecond());
            dialog.setBlockOnOpen(false);
            dialog.open();
        } catch (Exception e) {
            throw new ExecutionException("Could not open style dialog", e);
        }
    }
    return null;
}

From source file:omero.cmd.graphs.DiskUsageI.java

/**
 * Calculate the disk usage of the model objects specified in the request.
 * @return the total usage, in bytes//from ww w .ja v a2  s.  c  o m
 */
private DiskUsageResponse getDiskUsage() {
    final IQuery queryService = helper.getServiceFactory().getQueryService();

    final int batchSize = 256;

    final SetMultimap<String, Long> objectsToProcess = HashMultimap.create();
    final SetMultimap<String, Long> objectsProcessed = HashMultimap.create();
    final Usage usage = new Usage();

    /* original file ID to types that refer to them */
    final SetMultimap<Long, String> typesWithFiles = HashMultimap.create();
    /* original file ID to file ownership and size */
    final Map<Long, OwnershipAndSize> fileSizes = new HashMap<Long, OwnershipAndSize>();

    /* note the objects to process */

    for (final String className : classes) {
        final String hql = "SELECT " + getIdPropertyFor(className) + " FROM " + className;
        for (final Object[] resultRow : queryService.projection(hql, null)) {
            if (resultRow != null) {
                final Long objectId = (Long) resultRow[0];
                objectsToProcess.put(className, objectId);
            }
        }
    }

    for (final Map.Entry<String, List<Long>> objectList : objects.entrySet()) {
        objectsToProcess.putAll(objectList.getKey(), objectList.getValue());

        if (LOGGER.isDebugEnabled()) {
            final List<Long> ids = Lists.newArrayList(objectsToProcess.get(objectList.getKey()));
            Collections.sort(ids);
            LOGGER.debug("size calculator to process " + objectList.getKey() + " " + Joiner.on(", ").join(ids));
        }
    }

    /* check that the objects' class names are valid */

    for (final String className : objectsToProcess.keySet()) {
        getIdPropertyFor(className);
    }

    /* iteratively process objects, descending the model graph */

    while (!objectsToProcess.isEmpty()) {
        /* obtain canonical class name and ID list */
        final Map.Entry<String, Collection<Long>> nextClass = objectsToProcess.asMap().entrySet().iterator()
                .next();
        String className = nextClass.getKey();
        final int lastDot = className.lastIndexOf('.');
        if (lastDot >= 0) {
            className = className.substring(lastDot + 1);
        } else if (className.charAt(0) == '/') {
            className = className.substring(1);
        }
        /* get IDs still to process, and split off a batch of them for this query */
        final Collection<Long> ids = nextClass.getValue();
        ids.removeAll(objectsProcessed.get(className));
        if (ids.isEmpty()) {
            continue;
        }
        final List<Long> idsToQuery = Lists.newArrayList(Iterables.limit(ids, batchSize));
        ids.removeAll(idsToQuery);
        objectsProcessed.putAll(className, idsToQuery);
        final Parameters parameters = new Parameters().addIds(idsToQuery);

        if ("Pixels".equals(className)) {
            /* Pixels may have /OMERO/Pixels/<id> files */
            final String hql = "SELECT id, details.owner.id, details.group.id FROM Pixels WHERE id IN (:ids)";
            for (final Object[] resultRow : queryService.projection(hql, parameters)) {
                if (resultRow != null) {
                    final Long pixelsId = (Long) resultRow[0];
                    final Long ownerId = (Long) resultRow[1];
                    final Long groupId = (Long) resultRow[2];
                    final String pixelsPath = pixelsService.getPixelsPath(pixelsId);
                    usage.bumpTotals().add(ownerId, groupId, className, getFileSize(pixelsPath));
                    usage.bumpTotals().add(ownerId, groupId, className,
                            getFileSize(pixelsPath + PixelsService.PYRAMID_SUFFIX));
                    usage.bumpTotals().add(ownerId, groupId, className, getFileSize(
                            pixelsPath + PixelsService.PYRAMID_SUFFIX + BfPyramidPixelBuffer.PYR_LOCK_EXT));
                }
            }
        } else if ("Thumbnail".equals(className)) {
            /* Thumbnails may have /OMERO/Thumbnails/<id> files */
            final String hql = "SELECT id, details.owner.id, details.group.id FROM Thumbnail WHERE id IN (:ids)";
            for (final Object[] resultRow : queryService.projection(hql, parameters)) {
                if (resultRow != null) {
                    final Long thumbnailId = (Long) resultRow[0];
                    final Long ownerId = (Long) resultRow[1];
                    final Long groupId = (Long) resultRow[2];
                    final String thumbnailPath = thumbnailService.getThumbnailPath(thumbnailId);
                    usage.bumpTotals().add(ownerId, groupId, className, getFileSize(thumbnailPath));
                }
            }
        } else if ("OriginalFile".equals(className)) {
            /* OriginalFiles have their size noted */
            final String hql = "SELECT id, details.owner.id, details.group.id, size FROM OriginalFile WHERE id IN (:ids)";
            for (final Object[] resultRow : queryService.projection(hql, parameters)) {
                if (resultRow != null && resultRow[3] instanceof Long) {
                    final Long fileId = (Long) resultRow[0];
                    final Long ownerId = (Long) resultRow[1];
                    final Long groupId = (Long) resultRow[2];
                    final Long fileSize = (Long) resultRow[3];
                    fileSizes.put(fileId, new OwnershipAndSize(ownerId, groupId, fileSize));
                }
            }
        } else if ("Experimenter".equals(className)) {
            /* for an experimenter, use the list of owned objects */
            for (final String resultClassName : OWNED_OBJECTS) {
                final String hql = "SELECT " + getIdPropertyFor(resultClassName) + " FROM " + resultClassName
                        + " WHERE details.owner.id IN (:ids)";
                for (final Object[] resultRow : queryService.projection(hql, parameters)) {
                    objectsToProcess.put(resultClassName, (Long) resultRow[0]);
                }
            }
        } else if ("ExperimenterGroup".equals(className)) {
            /* for an experimenter group, use the list of owned objects */
            for (final String resultClassName : OWNED_OBJECTS) {
                final String hql = "SELECT " + getIdPropertyFor(resultClassName) + " FROM " + resultClassName
                        + " WHERE details.group.id IN (:ids)";
                for (final Object[] resultRow : queryService.projection(hql, parameters)) {
                    objectsToProcess.put(resultClassName, (Long) resultRow[0]);
                }
            }
        }

        /* follow the next step from here on the model object graph */
        for (final Map.Entry<String, String> query : TRAVERSAL_QUERIES.get(className)) {
            final String resultClassName = query.getKey();
            final String hql = query.getValue();
            for (final Object[] resultRow : queryService.projection(hql, parameters)) {
                if (resultRow != null && resultRow[0] instanceof Long) {
                    final Long resultId = (Long) resultRow[0];
                    objectsToProcess.put(resultClassName, resultId);
                    if ("OriginalFile".equals(resultClassName)) {
                        typesWithFiles.put(resultId, className);
                    }
                }
            }
        }
        if (ANNOTATABLE_OBJECTS.contains(className)) {
            /* also watch for annotations on the current objects */
            final String hql = "SELECT child.id FROM " + className + "AnnotationLink WHERE parent.id IN (:ids)";
            for (final Object[] resultRow : queryService.projection(hql, parameters)) {
                objectsToProcess.put("Annotation", (Long) resultRow[0]);
            }
        }

        if (LOGGER.isDebugEnabled()) {
            Collections.sort(idsToQuery);
            LOGGER.debug("usage is " + usage + " after processing " + className + " "
                    + Joiner.on(", ").join(idsToQuery));
        }
    }

    /* collate file counts and sizes by referer type */
    for (final Map.Entry<Long, OwnershipAndSize> fileIdSize : fileSizes.entrySet()) {
        final Long fileId = fileIdSize.getKey();
        final OwnershipAndSize fileSize = fileIdSize.getValue();
        Set<String> types = typesWithFiles.get(fileId);
        if (types.isEmpty()) {
            types = ImmutableSet.of("OriginalFile");
        }
        usage.bumpTotals();
        for (final String type : types) {
            usage.add(fileSize.owner, fileSize.group, type, fileSize.size);
        }
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("usage is " + usage + " after including " + OriginalFile.class.getSimpleName() + " sizes");
    }

    return usage.getDiskUsageResponse();
}

From source file:ome.services.graphs.GraphTraversal.java

/**
 * Prepare to process the targeted model objects.
 * @return the actual processor for the targeted model objects, to be used by the caller
 * @throws GraphException if the user does not have permission to process the targets or
 * if a cycle is detected in the model object graph
 *//*  w w w  .  j a  v  a2s .c  o  m*/
public PlanExecutor processTargets() throws GraphException {
    if (!progress.contains(Milestone.PLANNED)) {
        throw new IllegalStateException("operation not yet planned");
    }
    final List<Entry<Map<String, Collection<Long>>, Map<String, Collection<Long>>>> toJoinAndDelete = new ArrayList<Entry<Map<String, Collection<Long>>, Map<String, Collection<Long>>>>();
    /* process the targets forward across links */
    while (!planning.blockedBy.isEmpty()) {
        /* determine which objects can be processed in this step */
        final Collection<CI> nowUnblocked = new HashSet<CI>();
        final Iterator<Entry<CI, Set<CI>>> blocks = planning.blockedBy.entrySet().iterator();
        while (blocks.hasNext()) {
            final Entry<CI, Set<CI>> block = blocks.next();
            final CI object = block.getKey();
            if (block.getValue().isEmpty()) {
                blocks.remove();
                nowUnblocked.add(object);
            }
        }
        if (nowUnblocked.isEmpty()) {
            throw new GraphException(
                    "cycle detected among " + Joiner.on(", ").join(planning.blockedBy.keySet()));
        }
        for (final Set<CI> blockers : planning.blockedBy.values()) {
            blockers.removeAll(nowUnblocked);
        }
        final SetMultimap<String, Long> toJoin = HashMultimap.create();
        final SetMultimap<String, Long> toDelete = HashMultimap.create();
        for (final CI object : nowUnblocked) {
            if (planning.included.contains(object)) {
                toJoin.put(object.className, object.id);
            } else {
                toDelete.put(object.className, object.id);
            }
        }
        /* note this group's includes and deletes */
        final Map<String, Collection<Long>> eachToJoin = toJoin.asMap();
        for (final Entry<String, Collection<Long>> oneClassToJoin : eachToJoin.entrySet()) {
            final String className = oneClassToJoin.getKey();
            final Collection<Long> allIds = oneClassToJoin.getValue();
            assertMayBeProcessed(className, allIds);
        }
        final Map<String, Collection<Long>> eachToDelete = toDelete.asMap();
        for (final Entry<String, Collection<Long>> oneClassToDelete : eachToDelete.entrySet()) {
            final String className = oneClassToDelete.getKey();
            final Collection<Long> allIds = oneClassToDelete.getValue();
            assertMayBeDeleted(className, allIds);
        }
        toJoinAndDelete.add(Maps.immutableEntry(eachToJoin, eachToDelete));
    }
    return new PlanExecutor() {
        @Override
        public void execute() throws GraphException {
            if (!progress.contains(Milestone.UNLINKED)) {
                throw new IllegalStateException("model objects not yet unlinked");
            }
            if (progress.contains(Milestone.PROCESSED)) {
                throw new IllegalStateException("model objects already processed");
            }
            /* actually do the noted processing */
            for (final Entry<Map<String, Collection<Long>>, Map<String, Collection<Long>>> next : toJoinAndDelete) {
                final Map<String, Collection<Long>> toJoin = next.getKey();
                final Map<String, Collection<Long>> toDelete = next.getValue();
                /* perform this group's deletes */
                if (!toDelete.isEmpty()) {
                    for (final Entry<String, Collection<Long>> oneClassToDelete : toDelete.entrySet()) {
                        final String className = oneClassToDelete.getKey();
                        final Collection<Long> allIds = oneClassToDelete.getValue();
                        final Collection<Collection<Long>> idGroups;
                        if (OriginalFile.class.getName().equals(className)) {
                            idGroups = ModelObjectSequencer.sortOriginalFileIds(session, allIds);
                        } else {
                            idGroups = Collections.singleton(allIds);
                        }
                        for (final Collection<Long> idGroup : idGroups) {
                            for (final List<Long> ids : Iterables.partition(idGroup, BATCH_SIZE)) {
                                processor.deleteInstances(className, ids);
                            }
                        }
                    }
                }
                /* perform this group's includes */
                if (!toJoin.isEmpty()) {
                    for (final Entry<String, Collection<Long>> oneClassToJoin : toJoin.entrySet()) {
                        final String className = oneClassToJoin.getKey();
                        final Collection<Long> allIds = oneClassToJoin.getValue();
                        for (final List<Long> ids : Iterables.partition(allIds, BATCH_SIZE)) {
                            processor.processInstances(className, ids);
                        }
                    }
                }
            }
            progress.add(Milestone.PROCESSED);
        }
    };
}