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

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

Introduction

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

Prototype

boolean remove(@Nullable Object key, @Nullable Object value);

Source Link

Document

Removes a single key-value pair with the key key and the value value from this multimap, if such exists.

Usage

From source file:com.enonic.cms.core.security.userstore.connector.synchronize.SynchronizeUserStoreJobImpl.java

private List<GroupKey> resolveGroupsToDelete(final Multimap<String, GroupEntity> groupsMapByName,
        final Collection<RemoteGroup> remoteGroups) {
    // Remove all remote groups from groupsMapByName, so that we are only left with groups not existing remote.
    final List<GroupEntity> groupsToRemoveFromMap = new ArrayList<GroupEntity>();
    for (final RemoteGroup remoteGroup : remoteGroups) {
        final Collection<GroupEntity> candidates = groupsMapByName.get(remoteGroup.getId());
        for (final GroupEntity candidate : candidates) {
            if (candidate != null && remoteGroup.getSync().equals(candidate.getSyncValue())) {
                groupsToRemoveFromMap.add(candidate);
            }//w ww  .  java  2s. c  om
        }
    }
    for (final GroupEntity groupToRemoveFromMap : groupsToRemoveFromMap) {
        groupsMapByName.remove(groupToRemoveFromMap.getName(), groupToRemoveFromMap);
    }

    final List<GroupKey> groupsToDelete = new ArrayList<GroupKey>();
    for (final GroupEntity groupToDelete : groupsMapByName.values()) {
        groupsToDelete.add(groupToDelete.getGroupKey());
    }
    return groupsToDelete;
}

From source file:org.wisdom.framework.filters.BalancerFilter.java

/**
 * Callback that can be overridden to customize the header ot the request. This method implements the reverse
 * routing. It updates URLs contained in the headers.
 *
 * @param context the request context/*from w w  w .ja v a 2s.com*/
 * @param headers the current set of headers, that need to be modified
 */
@Override
public void updateHeaders(RequestContext context, Multimap<String, String> headers) {
    if (!proxyPassReverse) {
        return;
    }
    for (Map.Entry<String, String> h : new LinkedHashSet<>(headers.entries())) {
        if (REVERSE_PROXY_HEADERS.contains(h.getKey())) {
            URI location = URI.create(h.getValue()).normalize();
            if (location.isAbsolute() && isBackendLocation(location)) {
                String initial = context.request().uri();
                URI uri = URI.create(initial);
                try {
                    URI newURI = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(),
                            location.getPath(), location.getQuery(), location.getFragment());
                    headers.remove(h.getKey(), h.getValue());
                    headers.put(h.getKey(), newURI.toString());
                } catch (URISyntaxException e) {
                    logger.error("Cannot manipulate the header {} (value={}) to enforce reverse routing",
                            h.getKey(), h.getValue(), e);
                }
            }
        }
    }
}

From source file:io.bazel.rules.closure.webfiles.Webset.java

/**
 * Loads graph of web files from proto manifests.
 *
 * @param manifests set of web rule target proto files in reverse topological order
 * @return set of web files and relationships between them, which could be mutated, although
 *     adding a single key will most likely result in a full rehash
 *//*from ww w  .j av a  2 s.c o m*/
public static Webset load(Map<Path, WebfileManifestInfo> manifests, WebpathInterner interner) {
    int webfileCapacity = 0;
    int unlinkCapacity = 16; // LinkedHashMultimap#DEFAULT_KEY_CAPACITY
    for (WebfileManifestInfo manifest : manifests.values()) {
        webfileCapacity += manifest.getWebfileCount();
        unlinkCapacity = Math.max(unlinkCapacity, manifest.getUnlinkCount());
    }
    Map<Webpath, Webfile> webfiles = Maps.newLinkedHashMapWithExpectedSize(webfileCapacity);
    Multimap<Webpath, Webpath> links = LinkedHashMultimap.create(webfileCapacity, 4);
    Multimap<Webpath, Webpath> unlinks = LinkedHashMultimap.create(unlinkCapacity, 4);
    for (Map.Entry<Path, WebfileManifestInfo> entry : manifests.entrySet()) {
        Path manifestPath = entry.getKey();
        Path zipPath = WebfilesUtils.getIncrementalZipPath(manifestPath);
        WebfileManifestInfo manifest = entry.getValue();
        String label = manifest.getLabel();
        for (WebfileInfo info : manifest.getWebfileList()) {
            Webpath webpath = interner.get(info.getWebpath());
            webfiles.put(webpath, Webfile.create(webpath, zipPath, label, info));
        }
        for (MultimapInfo mapping : manifest.getLinkList()) {
            Webpath from = interner.get(mapping.getKey());
            for (Webpath to : Iterables.transform(mapping.getValueList(), interner)) {
                // When compiling web_library rules, if the strict dependency checking invariant holds
                // true, we can choose to only load adjacent manifests, rather than transitive ones. The
                // adjacent manifests may contain links to transitive web files which will not be in the
                // webfiles map.
                if (webfiles.containsKey(to)) {
                    links.put(from, to);
                    checkArgument(!unlinks.containsEntry(from, to),
                            "Has a use case for resurrected links been discovered? %s -> %s", from, to);
                }
            }
        }
        for (MultimapInfo mapping : manifest.getUnlinkList()) {
            unlinks.putAll(interner.get(mapping.getKey()),
                    Collections2.transform(mapping.getValueList(), interner));
        }
    }
    for (Map.Entry<Webpath, Webpath> entry : unlinks.entries()) {
        links.remove(entry.getKey(), entry.getValue());
    }
    unlinks.clear();
    return new AutoValue_Webset(webfiles, links, interner);
}

From source file:org.eclipse.xtext.ui.refactoring.impl.AbstractReferenceUpdater.java

protected void createReferenceUpdatesForCluster(ElementRenameArguments elementRenameArguments,
        Multimap<URI, IReferenceDescription> resource2references, ResourceSet resourceSet,
        IRefactoringUpdateAcceptor updateAcceptor, StatusWrapper status, IProgressMonitor monitor) {
    SubMonitor progress = SubMonitor.convert(monitor, 100);
    List<URI> unloadableResources = loadReferringResources(resourceSet, resource2references.keySet(), status,
            progress.newChild(10));// w w w  . j a  va2s . co  m
    if (progress.isCanceled()) {
        throw new OperationCanceledException();
    }
    for (URI unloadableResouce : unloadableResources)
        resource2references.removeAll(unloadableResouce);
    List<IReferenceDescription> unresolvableReferences = resolveReferenceProxies(resourceSet,
            resource2references.values(), status, progress.newChild(70));
    if (progress.isCanceled()) {
        throw new OperationCanceledException();
    }
    for (IReferenceDescription unresolvableReference : unresolvableReferences) {
        URI unresolvableReferringResource = unresolvableReference.getSourceEObjectUri().trimFragment();
        resource2references.remove(unresolvableReferringResource, unresolvableReference);
    }
    elementRenameArguments.getRenameStrategy().applyDeclarationChange(elementRenameArguments.getNewName(),
            resourceSet);
    if (progress.isCanceled()) {
        throw new OperationCanceledException();
    }
    createReferenceUpdates(elementRenameArguments, resource2references, resourceSet, updateAcceptor,
            progress.newChild(20));
    if (progress.isCanceled()) {
        throw new OperationCanceledException();
    }
    elementRenameArguments.getRenameStrategy().revertDeclarationChange(resourceSet);
}

From source file:org.eclipse.xtext.xtext.XtextValidator.java

@Check
public void checkRuleName(AbstractRule rule) {
    final Grammar grammar = GrammarUtil.getGrammar(rule);
    Multimap<String, AbstractRule> rules = getAllRules(grammar, rule.getName());
    rules.remove(rule.getName(), rule);
    if (!rules.isEmpty()) {
        TreeSet<String> names = Sets.newTreeSet(rules.keySet());
        if (names.size() == 1) {
            String name = names.first();
            if (name.equals(rule.getName())) {
                final String message = "A rule's name has to be unique.";
                error(message, XtextPackage.Literals.ABSTRACT_RULE__NAME);
                return;
            } else {
                String message = "A rule's name has to be unique even case insensitive.";
                boolean superGrammar = false;
                for (AbstractRule otherRule : rules.get(name)) {
                    if (GrammarUtil.getGrammar(otherRule) != grammar) {
                        message = message + " A used grammar contains another rule '" + name + "'.";
                        superGrammar = true;
                        break;
                    }/*w w  w. ja va  2  s  . c o m*/
                }
                if (!superGrammar)
                    message = message + " This grammar contains another rule '" + name + "'.";
                error(message, XtextPackage.Literals.ABSTRACT_RULE__NAME);
                return;
            }
        } else {
            String message = "A rule's name has to be unique even case insensitive.";
            final StringBuilder builder = new StringBuilder((rule.getName().length() + 4) * names.size() - 2);
            int i = 0;
            for (String name : names) {
                if (builder.length() != 0) {
                    if (i < names.size() - 1)
                        builder.append(", ");
                    else
                        builder.append(" and ");
                }
                i++;
                builder.append("'").append(name).append("'");
            }
            error(message + " The conflicting rules are " + builder + ".",
                    XtextPackage.Literals.ABSTRACT_RULE__NAME);
            return;
        }
    }
    if (SuperCallScope.SUPER.equals(rule.getName())) {
        addIssue("Discouraged rule name 'super'", rule, XtextPackage.Literals.ABSTRACT_RULE__NAME,
                DISCOURAGED_RULE_NAME);
    }
}

From source file:grakn.core.graql.executor.WriteExecutor.java

/**
 * Produce a valid ordering of the properties by using the given dependency information.
 * This method uses a topological sort (Kahn's algorithm) in order to find a valid ordering.
 *//*  w w  w . j  a  v  a2  s  .com*/
private ImmutableList<Writer> sortedWriters() {
    ImmutableList.Builder<Writer> sorted = ImmutableList.builder();

    // invertedDependencies is intended to just be a 'view' on dependencies, so when dependencies is modified
    // we should always also modify invertedDependencies (and vice-versa).
    Multimap<Writer, Writer> dependencies = HashMultimap.create(this.dependencies);
    Multimap<Writer, Writer> invertedDependencies = HashMultimap.create();
    Multimaps.invertFrom(dependencies, invertedDependencies);

    Queue<Writer> writerWithoutDependencies = new ArrayDeque<>(
            Sets.filter(writers, property -> dependencies.get(property).isEmpty()));

    Writer property;

    // Retrieve the next property without any dependencies
    while ((property = writerWithoutDependencies.poll()) != null) {
        sorted.add(property);

        // We copy this into a new list because the underlying collection gets modified during iteration
        Collection<Writer> dependents = Lists.newArrayList(invertedDependencies.get(property));

        for (Writer dependent : dependents) {
            // Because the property has been removed, the dependent no longer needs to depend on it
            dependencies.remove(dependent, property);
            invertedDependencies.remove(property, dependent);

            boolean hasNoDependencies = dependencies.get(dependent).isEmpty();

            if (hasNoDependencies) {
                writerWithoutDependencies.add(dependent);
            }
        }
    }

    if (!dependencies.isEmpty()) {
        // This means there must have been a loop. Pick an arbitrary remaining var to display
        Variable var = dependencies.keys().iterator().next().var();
        throw GraqlSemanticException.insertRecursive(printableRepresentation(var));
    }

    return sorted.build();
}

From source file:jef.database.meta.TableMetadata.java

/**
 * ???//w  w  w.  j  ava  2 s  . co m
 * 
 * @param t
 */
synchronized void setPartition(PartitionTable t) {
    //???setPartitionpkField?
    if (this.pkFields instanceof ArrayList) {
        this.pkFields = Collections.unmodifiableList(this.pkFields);
    }
    if (t == null)
        return;
    effectPartitionKeys = withFunction(t.key());
    if (effectPartitionKeys.length == 0) {
        effectPartitionKeys = null;
        return;
    }
    this.partition = t;
    // ????
    Multimap<String, PartitionFunction> fieldKeyFn = ArrayListMultimap.create();
    for (Entry<PartitionKey, PartitionFunction> entry : getEffectPartitionKeys()) {
        PartitionKey key = entry.getKey();
        String field = key.field();
        if (entry.getValue() instanceof AbstractDateFunction) {
            Collection<PartitionFunction> olds = fieldKeyFn.get(field);
            if (olds != null) {
                for (PartitionFunction<?> old : olds) {
                    if (old instanceof AbstractDateFunction) {
                        int oldLevel = ((AbstractDateFunction) old).getTimeLevel();
                        int level = ((AbstractDateFunction) entry.getValue()).getTimeLevel();// ????
                        if (level < oldLevel) {
                            fieldKeyFn.remove(field, old);
                            break;// ??
                        } else {
                            continue;// ?
                        }
                    }
                }
            }
        }
        fieldKeyFn.put(field, entry.getValue());
    }
    partitionFuncs = fieldKeyFn;
}

From source file:ai.grakn.graql.internal.query.QueryOperationExecutor.java

/**
 * Produce a valid ordering of the properties by using the given dependency information.
 *
 * <p>//w  w w. j a v  a2 s  .  co  m
 *     This method uses a topological sort (Kahn's algorithm) in order to find a valid ordering.
 * </p>
 */
private ImmutableList<VarAndProperty> sortProperties() {
    ImmutableList.Builder<VarAndProperty> sorted = ImmutableList.builder();

    // invertedDependencies is intended to just be a 'view' on dependencies, so when dependencies is modified
    // we should always also modify invertedDependencies (and vice-versa).
    Multimap<VarAndProperty, VarAndProperty> dependencies = HashMultimap.create(this.dependencies);
    Multimap<VarAndProperty, VarAndProperty> invertedDependencies = HashMultimap.create();
    Multimaps.invertFrom(dependencies, invertedDependencies);

    Queue<VarAndProperty> propertiesWithoutDependencies = new ArrayDeque<>(
            Sets.filter(properties, property -> dependencies.get(property).isEmpty()));

    VarAndProperty property;

    // Retrieve the next property without any dependencies
    while ((property = propertiesWithoutDependencies.poll()) != null) {
        sorted.add(property);

        // We copy this into a new list because the underlying collection gets modified during iteration
        Collection<VarAndProperty> dependents = Lists.newArrayList(invertedDependencies.get(property));

        for (VarAndProperty dependent : dependents) {
            // Because the property has been removed, the dependent no longer needs to depend on it
            dependencies.remove(dependent, property);
            invertedDependencies.remove(property, dependent);

            boolean hasNoDependencies = dependencies.get(dependent).isEmpty();

            if (hasNoDependencies) {
                propertiesWithoutDependencies.add(dependent);
            }
        }
    }

    if (!dependencies.isEmpty()) {
        // This means there must have been a loop. Pick an arbitrary remaining var to display
        Var var = dependencies.keys().iterator().next().var();
        throw GraqlQueryException.insertRecursive(printableRepresentation(var));
    }

    return sorted.build();
}

From source file:neon.editor.Editor.java

/**
 * Loads an existing module for editing.
 * /*from  w w w  .j a  v  a  2 s.  c  om*/
 * @param event
 * @throws FileNotFoundException
 * @throws ResourceException 
 */
@Subscribe
private void loadModule(LoadEvent.Load event) throws FileNotFoundException, ResourceException {
    // set the active module id
    File file = event.getFile();
    String module = file.getName();

    // add the parent modules to the file system
    Path path = Paths.get(file.getPath(), module + ".xml");
    try (InputStream in = Files.newInputStream(path)) {
        Element root = new XMLTranslator().translate(in).getRootElement();
        for (Element parent : root.getChild("parents").getChildren()) {
            files.addModule(parent.getText());
        }
    } catch (IOException e) {
        throw new FileNotFoundException("module <" + module + "> not found");
    }

    // keep track of all resources defined in parent modules
    Multimap<String, Card> cards = event.getCards();
    for (String id : resources.listResources("creatures")) {
        Card card = new Card("creatures", id, resources, true);
        cards.put("creatures", card);
    }
    for (String id : resources.listResources("items")) {
        Card card = new Card("items", id, resources, true);
        cards.put("items", card);
    }
    for (String id : resources.listResources("maps")) {
        Card card = new Card("maps", id, resources, true);
        cards.put("maps", card);
    }
    for (String id : resources.listResources("terrain")) {
        Card card = new Card("terrain", id, resources, true);
        cards.put("terrain", card);
    }

    // editing is done in temp, so don't add the actual module folder to the file system
    FileUtils.copyFolder(file.toPath(), Paths.get("temp"));
    config.setActiveModule(resources.getResource(module));

    // keep track of all resources (re)defined in the active module
    for (String id : FileUtils.listFiles(Paths.get("temp", "creatures"))) {
        Card card = new Card("creatures", id.replaceAll(".xml", ""), resources, false);
        if (cards.get("creatures").contains(card)) {
            cards.remove("creatures", card);
            card = new Card("creatures", id.replaceAll(".xml", ""), resources, true);
            card.setRedefined(true);
        }
        cards.put("creatures", card);
    }
    for (String id : FileUtils.listFiles(Paths.get("temp", "items"))) {
        Card card = new Card("items", id.replaceAll(".xml", ""), resources, false);
        if (cards.get("items").contains(card)) {
            cards.remove("items", card);
            card = new Card("items", id.replaceAll(".xml", ""), resources, true);
            card.setRedefined(true);
        }
        cards.put("items", card);
    }
    for (String id : FileUtils.listFiles(Paths.get("temp", "terrain"))) {
        Card card = new Card("terrain", id.replaceAll(".xml", ""), resources, false);
        if (cards.get("terrain").contains(card)) {
            cards.remove("terrain", card);
            card = new Card("terrain", id.replaceAll(".xml", ""), resources, true);
            card.setRedefined(true);
        }
        cards.put("terrain", card);
    }
    for (String id : FileUtils.listFiles(Paths.get("temp", "maps"))) {
        Card card = new Card("maps", id.replaceAll(".xml", ""), resources, false);
        if (cards.get("maps").contains(card)) {
            cards.remove("maps", card);
            card = new Card("maps", id.replaceAll(".xml", ""), resources, true);
            card.setRedefined(true);
        }
        cards.put("maps", card);
    }

    logger.fine("loaded module " + module);
}

From source file:org.eclipse.elk.core.service.DiagramLayoutEngine.java

/**
 * Perform layout on the given workbench part and diagram part. The layout operation is wrapped in a
 * {@link MonitoredOperation} in order to ensure that building the layout graph and applying the layout
 * is both done in the UI thread. In case of a problem a message is shown to the user with the default
 * {@link StatusManager}.//from   w ww.  j ava  2  s. c  o m
 * 
 * <p>{@code workbenchPart} and {@code diagramPart} must not be {@code null} at the same time.</p>
 * 
 * @param workbenchPart
 *            the workbench part for which layout is performed, or {@code null}
 * @param diagramPart
 *            the parent diagram part for which layout is performed, or {@code null} if the whole
 *            diagram shall be layouted
 * @param cancelIndicator
 *            an {@link IElkCancelIndicator} to be evaluated repeatedly during the layout operation,
 *            or {@code null}
 * @param params
 *            layout parameters, or {@code null} to use default values
 * @return the layout mapping used in this operation
 */
public LayoutMapping layout(final IWorkbenchPart workbenchPart, final Object diagramPart,
        final IElkCancelIndicator cancelIndicator, final Parameters params) {
    if (workbenchPart == null && diagramPart == null) {
        throw new NullPointerException();
    }

    final Parameters finalParams = params != null ? params : new Parameters();
    final Maybe<LayoutMapping> layoutMapping = Maybe.create();
    final Pair<IWorkbenchPart, Object> target = Pair.of(workbenchPart, diagramPart);
    final ExecutorService executorService = ElkServicePlugin.getInstance().getExecutorService();
    final MonitoredOperation monitoredOperation = new MonitoredOperation(executorService, cancelIndicator) {

        // First phase: build the layout graph
        @Override
        protected void preUIexec() {
            boolean layoutAncestors = finalParams.getGlobalSettings().getProperty(CoreOptions.LAYOUT_ANCESTORS);
            LayoutMapping mapping;
            if (layoutAncestors && workbenchPart != null) {
                mapping = connector.buildLayoutGraph(workbenchPart, null);
                mapping.setParentElement(diagramPart);
            } else {
                mapping = connector.buildLayoutGraph(workbenchPart, diagramPart);
            }
            layoutMapping.set(mapping);
        }

        // Second phase: execute layout algorithms
        @Override
        protected IStatus execute(final IElkProgressMonitor monitor) {
            if (monitor.isCanceled()) {
                return Status.CANCEL_STATUS;
            }

            LayoutMapping mapping = layoutMapping.get();
            IStatus status;
            if (mapping != null && mapping.getLayoutGraph() != null) {
                // Extract the diagram configuration
                addDiagramConfig(finalParams, mapping);

                // Perform the actual layout
                status = layout(mapping, monitor, finalParams);

                // Stop earlier layout operations that are still running
                if (!monitor.isCanceled()) {
                    stopEarlierOperations(target, getTimestamp());
                }
            } else {
                status = new Status(Status.WARNING, ElkServicePlugin.PLUGIN_ID,
                        "Unable to build the layout graph from the given selection.");
            }

            monitor.done();
            return status;
        }

        // Third phase: apply layout with animation
        @Override
        protected void postUIexec() {
            if (layoutMapping.get() != null) {
                connector.applyLayout(layoutMapping.get(), finalParams.getGlobalSettings());
            }
        }
    };

    Multimap<Pair<IWorkbenchPart, Object>, MonitoredOperation> runningOperations = ElkServicePlugin
            .getInstance().getRunningOperations();
    synchronized (runningOperations) {
        runningOperations.put(target, monitoredOperation);
    }

    try {
        boolean progressBar = finalParams.getGlobalSettings().getProperty(CoreOptions.PROGRESS_BAR);
        if (progressBar) {
            // Perform layout with a progress bar
            monitoredOperation.runMonitored();
        } else {
            // Perform layout without a progress bar
            monitoredOperation.runUnmonitored();
        }
    } finally {
        synchronized (runningOperations) {
            runningOperations.remove(target, monitoredOperation);
        }
    }

    return layoutMapping.get();
}