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

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

Introduction

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

Prototype

Set<K> keySet();

Source Link

Document

Returns a view collection of all distinct keys contained in this multimap.

Usage

From source file:com.zimbra.cs.mailbox.acl.AclPushTask.java

public static synchronized void doWork() {
    if (!supported)
        return;//from  w  w w .j  av  a2 s . c  om
    ZimbraLog.misc.debug("Starting pending ACL push");

    Multimap<Integer, List<Integer>> currentItemIdsProcessed = ArrayListMultimap.create();

    try {
        Date now = new Date();
        Multimap<Integer, Integer> mboxIdToItemIds = DbPendingAclPush.getEntries(now);

        for (int mboxId : mboxIdToItemIds.keySet()) {
            Mailbox mbox;
            List<Integer> itemsProcessed = new ArrayList<Integer>();
            try {
                mbox = MailboxManager.getInstance().getMailboxById(mboxId);
            } catch (ServiceException e) {
                ZimbraLog.misc.info("Exception occurred while getting mailbox for id %s during ACL push",
                        mboxId, e);
                continue;
            }
            Collection<Integer> itemIds = mboxIdToItemIds.get(mboxId);
            MailItem[] items = null;
            try {
                items = mbox.getItemById(null, itemIds, MailItem.Type.UNKNOWN);
            } catch (MailServiceException.NoSuchItemException e) {
                // one or more folders no longer exist
                if (itemIds.size() > 1) {
                    List<MailItem> itemList = new ArrayList<MailItem>();
                    for (int itemId : itemIds) {
                        try {
                            itemList.add(mbox.getItemById(null, itemId, MailItem.Type.UNKNOWN));
                        } catch (MailServiceException.NoSuchItemException ignored) {
                        }
                    }
                    items = itemList.toArray(new MailItem[itemList.size()]);
                }
            }

            Account account = mbox.getAccount();
            String[] existingSharedItems = account.getSharedItem();
            Set<String> updatedSharedItems = new HashSet<String>();

            for (String sharedItem : existingSharedItems) {
                ShareInfoData shareData = AclPushSerializer.deserialize(sharedItem);

                if (!itemIds.contains(shareData.getItemId())) {
                    updatedSharedItems.add(sharedItem);
                }
            }

            if (items != null) {
                for (MailItem item : items) {
                    if (item == null) {
                        continue;
                    }
                    // for now push the Folder grants to LDAP
                    if (!(item instanceof Folder)) {
                        continue;
                    }
                    ACL acl = item.getACL();
                    if (acl == null) {
                        continue;
                    }
                    for (ACL.Grant grant : acl.getGrants()) {
                        updatedSharedItems.add(AclPushSerializer.serialize(item, grant));
                    }
                    itemsProcessed.add(item.getId());
                    currentItemIdsProcessed.put(mboxId, itemsProcessed);
                }
            }
            account.setSharedItem(updatedSharedItems.toArray(new String[updatedSharedItems.size()]));
        } // for
        DbPendingAclPush.deleteEntries(now);

    } catch (ServiceException e) {
        ZimbraLog.misc.warn("Error during ACL push task", e);

    } catch (Throwable t) { //don't let exceptions kill the timer
        try {

            // We ran into runtime exception, so we want to delete records from ACL 
            // table for processed records.
            deleteDbAclEntryForProcessedItems(currentItemIdsProcessed);
        } catch (ServiceException e) {
            ZimbraLog.misc.warn("Error during ACL push task and deleting ACL push entry.");
        }
        ZimbraLog.misc.warn("Error during ACL push task", t);
    }
    ZimbraLog.misc.debug("Finished pending ACL push");
}

From source file:prm4jeval.dataanalysis.AnalysisResultsTableWriter.java

/**
 * @param mmap//from   w ww.j ava  2 s. c om
 *            key -> {measurements}
 * @return key -> (mean, ci/2)
 */
private final static Map<String, Tuple<Double, Double>> toConfidenceIntervalMap(Multimap<String, Double> mmap) {
    final Map<String, Tuple<Double, Double>> result = new HashMap<String, Tuple<Double, Double>>();
    for (String key : mmap.keySet()) {
        final ConfidenceInterval confidenceInterval = new ConfidenceInterval(confidenceLevel);
        for (Double measurement : mmap.get(key)) {
            confidenceInterval.addMeasurement(measurement);
        }
        result.put(key, Tuple.tuple(confidenceInterval.getMean(), confidenceInterval.getWidth() / 2));
    }
    return result;
}

From source file:prm4j.spec.finite.FiniteParametricProperty.java

private static <A, B> Multimap<B, A> reverseSetMultimap(Multimap<A, B> multiMap) {
    SetMultimap<B, A> reversedSetMultimap = HashMultimap.create();
    for (A a : multiMap.keySet()) {
        for (B b : multiMap.get(a)) {
            reversedSetMultimap.put(b, a);
        }//from w  w  w. ja  v  a 2 s.  c  o m
    }
    return reversedSetMultimap;
}

From source file:com.forerunnergames.tools.common.Utils.java

/**
 * Finds the key from its associated value in a multiMap.
 *
 * @param value/*from www .  j a  v a  2 s.co m*/
 *          The value whose key is to be searched for.
 * @param multiMap
 *          The multiMap to search in.
 *
 * @return The key, if found; Integer.MIN_VALUE otherwise.
 */
public static int findKeyFromValue(final int value, Multimap<Integer, Integer> multiMap) {
    Arguments.checkIsNotNull(value, "value");
    Arguments.checkIsNotNull(multiMap, "multiMap");

    boolean foundKey = false;

    java.util.Iterator<Integer> keyIterator = multiMap.keySet().iterator();

    Integer boxedKey = Integer.MIN_VALUE;
    Integer boxedValue = Integer.valueOf(value);

    while (keyIterator.hasNext() && !foundKey) {
        boxedKey = keyIterator.next();

        if (multiMap.containsEntry(boxedKey, boxedValue))
            foundKey = true;
    }

    assert foundKey;

    return boxedKey;
}

From source file:org.jclouds.http.utils.ModifyRequest.java

@SuppressWarnings("unchecked")
public static <R extends HttpRequest> R replaceHeaders(R request, Multimap<String, String> headers) {
    Multimap<String, String> newHeaders = LinkedHashMultimap
            .create(checkNotNull(request, "request").getHeaders());
    for (String header : headers.keySet())
        newHeaders.replaceValues(header, headers.get(header));
    return (R) request.toBuilder().headers(newHeaders).build();
}

From source file:org.eclipse.sirius.diagram.sequence.business.internal.ordering.RefreshOrderingHelper.java

private static void minimizeEventEnds(List<EventEnd> result,
        Multimap<EObject, SingleEventEnd> semanticEndToSingleEventEnds) {
    for (EObject semanticEnd : semanticEndToSingleEventEnds.keySet()) {
        Collection<SingleEventEnd> sees = semanticEndToSingleEventEnds.get(semanticEnd);
        if (sees.isEmpty()) {
            continue;
        }//from  w  w w . j av a 2 s .co  m

        if (sees.size() == 1) {
            result.add(sees.iterator().next());
        } else {
            CompoundEventEnd cee = OrderingFactory.eINSTANCE.createCompoundEventEnd();
            cee.setSemanticEnd(semanticEnd);

            if (sees.size() == 2 && RefreshOrderingHelper.countEvents(sees) == 1) {
                // start first
                Iterables.addAll(cee.getEventEnds(), Iterables.filter(sees, EventEndHelper.IS_START));
                Iterables.addAll(cee.getEventEnds(),
                        Iterables.filter(sees, Predicates.not(EventEndHelper.IS_START)));
            } else {
                // end first
                Iterables.addAll(cee.getEventEnds(),
                        Iterables.filter(sees, Predicates.not(EventEndHelper.IS_START)));
                Iterables.addAll(cee.getEventEnds(), Iterables.filter(sees, EventEndHelper.IS_START));
            }
            result.add(cee);
        }
    }
}

From source file:com.isotrol.impe3.core.impl.RequestParamsFactory.java

/**
 * Returns the collection of request parameters from a multimap object.
 * @param map Multimap./*from  ww  w . j  a  v a 2  s. c o  m*/
 * @return The request query parameters.
 */
public static RequestParams of(Multimap<String, String> map) {
    if (map == null || map.isEmpty()) {
        return EMPTY;
    }
    final ImmutableMultimap.Builder<CaseIgnoringString, String> builder = ImmutableMultimap.builder();
    for (String key : map.keySet()) {
        final CaseIgnoringString cis = CaseIgnoringString.valueOf(key);
        builder.putAll(cis, map.get(key));
    }
    return new Immutable(builder.build());
}

From source file:org.ambraproject.wombat.config.site.SiteSet.java

/**
 * Build a map representing the one-to-one relationship between journal keys and journal names.
 * <p/>//from   w w  w.  j  av a  2  s  . c o  m
 * As a side effect, validates that the relationship actually is one-to-one -- that is, that multiple sites have the
 * same journal key if and only if they have the same journal name. It is easier to obey this constraint if the {@code
 * journalKey} and {@code journalName} config values are always set in the {@code journal.yaml} or {@code
 * journal.json} file of the same theme, which should be a parent of all themes belonging to that journal.
 *
 * @param sites the set of all sites being served
 * @return a map between journal keys and journal names
 * @throws IllegalArgumentException if two sites with the same journal key have unequal journal names or if two sites
 *                                  with the same journal name have unequal journal keys
 */
private static ImmutableBiMap<String, String> buildJournalKeysToNames(Set<Site> sites) {
    Multimap<String, Site> keysToSites = groupByJournalKey(sites);
    BiMap<String, String> keysToNames = HashBiMap.create(keysToSites.keySet().size());
    for (Map.Entry<String, Collection<Site>> entry : keysToSites.asMap().entrySet()) {
        String journalKey = entry.getKey();
        Iterator<Site> siteIterator = entry.getValue().iterator();
        String journalName = siteIterator.next().getJournalName();
        while (siteIterator.hasNext()) {
            String nextJournalName = siteIterator.next().getJournalName();
            if (!journalName.equals(nextJournalName)) {
                String message = String.format("Inconsistent journal names with key=%s: %s; %s", journalKey,
                        journalName, nextJournalName);
                throw new IllegalArgumentException(message);
            }
        }

        if (keysToNames.containsValue(journalName)) {
            String message = String.format("Overloaded journal name (%s) for keys: %s; %s", journalName,
                    journalKey, keysToNames.inverse().get(journalName));
            throw new IllegalArgumentException(message);
        }
        keysToNames.put(journalKey, journalName);
    }
    return ImmutableBiMap.copyOf(keysToNames);
}

From source file:org.corpus_tools.graphannis.SaltExport.java

public static SDocumentGraph map(API.NodeVector orig) {
    SDocumentGraph g = SaltFactory.createSDocumentGraph();

    // convert the vector to a map
    Map<Long, API.Node> nodesByID = new LinkedHashMap<>();
    for (long i = 0; i < orig.size(); i++) {
        nodesByID.put(orig.get(i).id(), orig.get(i));
    }/*from   w ww.  j  av  a 2  s . c  om*/

    // create all new nodes
    Map<Long, SNode> newNodesByID = new LinkedHashMap<>();
    for (Map.Entry<Long, API.Node> entry : nodesByID.entrySet()) {
        API.Node v = entry.getValue();
        SNode n = mapNode(v);
        newNodesByID.put(entry.getKey(), n);
    }
    // add them to the graph
    newNodesByID.values().stream().forEach(n -> g.addNode(n));

    // create and add all edges
    nodesByID.values().forEach((n) -> {
        for (long i = 0; i < n.outgoingEdges().size(); i++) {
            mapAndAddEdge(g, n, n.outgoingEdges().get(i), newNodesByID);
        }
    });

    // find all chains of SOrderRelations and reconstruct the texts belonging to them
    Multimap<String, SNode> orderRoots = g.getRootsByRelationType(SALT_TYPE.SORDER_RELATION);
    orderRoots.keySet().forEach((name) -> {
        ArrayList<SNode> roots = new ArrayList<>(orderRoots.get(name));
        if (SaltUtil.SALT_NULL_VALUE.equals(name)) {
            name = null;
        }
        recreateText(name, roots, g);
    });

    addNodeLayers(g);

    return g;
}

From source file:it.osm.gtfs.command.GTFSGenerateRoutesDiff.java

public static void run() throws ParserConfigurationException, SAXException, IOException {
    List<Stop> osmStops = OSMParser
            .readOSMStops(GTFSImportSetting.getInstance().getOSMPath() + GTFSImportSetting.OSM_STOP_FILE_NAME);
    Map<String, Stop> osmstopsGTFSId = OSMParser.applyGTFSIndex(osmStops);
    Map<String, Stop> osmstopsOsmID = OSMParser.applyOSMIndex(osmStops);
    List<Relation> osmRels = OSMParser.readOSMRelations(
            new File(GTFSImportSetting.getInstance().getOSMPath() + GTFSImportSetting.OSM_RELATIONS_FILE_NAME),
            osmstopsOsmID);/*w w  w .ja  v a  2 s  .  c  o  m*/

    Map<String, Route> routes = GTFSParser.readRoutes(
            GTFSImportSetting.getInstance().getGTFSPath() + GTFSImportSetting.GTFS_ROUTES_FILE_NAME);
    Map<String, StopsList> stopTimes = GTFSParser.readStopTimes(
            GTFSImportSetting.getInstance().getGTFSPath() + GTFSImportSetting.GTFS_STOP_TIME_FILE_NAME,
            osmstopsGTFSId);
    List<Trip> trips = GTFSParser.readTrips(
            GTFSImportSetting.getInstance().getGTFSPath() + GTFSImportSetting.GTFS_TRIPS_FILE_NAME, routes,
            stopTimes);

    //looking from mapping gtfs trip into existing osm relations
    Set<Relation> osmRelationNotFoundInGTFS = new HashSet<Relation>(osmRels);
    Set<Relation> osmRelationFoundInGTFS = new HashSet<Relation>();
    List<Trip> tripsNotFoundInOSM = new LinkedList<Trip>();

    Multimap<String, Trip> grouppedTrips = GTFSParser.groupTrip(trips, routes, stopTimes);
    Set<String> keys = new TreeSet<String>(grouppedTrips.keySet());
    Map<Relation, Affinity> affinities = new HashMap<Relation, GTFSGenerateRoutesDiff.Affinity>();

    for (String k : keys) {
        Collection<Trip> allTrips = grouppedTrips.get(k);
        Set<Trip> uniqueTrips = new HashSet<Trip>(allTrips);

        for (Trip trip : uniqueTrips) {
            Route route = routes.get(trip.getRoute().getId());
            StopsList s = stopTimes.get(trip.getTripID());
            if (GTFSImportSetting.getInstance().getPlugin().isValidTrip(allTrips, uniqueTrips, trip, s)) {
                if (GTFSImportSetting.getInstance().getPlugin().isValidRoute(route)) {
                    Relation found = null;
                    for (Relation relation : osmRels) {
                        if (relation.equalsStops(s)
                                || GTFSImportSetting.getInstance().getPlugin().isRelationSameAs(relation, s)) {
                            if (found != null) {
                                osmRelationNotFoundInGTFS.remove(found);
                                osmRelationFoundInGTFS.add(found);
                            }
                            found = relation;
                        }
                        int affinity = relation.getStopsAffinity(s);
                        Affinity oldAff = affinities.get(relation);
                        if (oldAff == null) {
                            oldAff = new Affinity();
                            oldAff.trip = trip;
                            oldAff.affinity = affinity;
                            affinities.put(relation, oldAff);
                        } else if (oldAff.affinity < affinity) {
                            oldAff.trip = trip;
                            oldAff.affinity = affinity;
                        }
                    }
                    if (found != null) {
                        osmRelationNotFoundInGTFS.remove(found);
                        osmRelationFoundInGTFS.add(found);
                    } else {
                        tripsNotFoundInOSM.add(trip);
                        System.err.println("Warning tripid: " + trip.getTripID() + " (" + trip.getName()
                                + ") not found in OSM, detail below.");
                        System.err.println("Detail: shapeid" + trip.getShapeID() + " shortname: "
                                + route.getShortName() + " longname:" + route.getLongName());
                    }
                } else {
                    System.err.println(
                            "Warning tripid: " + trip.getTripID() + " skipped (invalidated route by plugin).");
                }
            } else {
                System.err.println(
                        "Warning tripid: " + trip.getTripID() + " skipped (invalidated trip by plugin).");
            }
        }
    }

    System.out.println("---");
    for (Relation r : osmRelationFoundInGTFS) {
        System.out.println("Relation " + r.getId() + " (" + r.getName() + ") matched in GTFS ");
    }
    System.out.println("---");
    for (Trip t : tripsNotFoundInOSM) {
        System.out.println("Trip " + t.getTripID() + " (" + routes.get(t.getRoute().getId()).getShortName()
                + " - " + t.getName() + ") not found in OSM ");
        StopsList stopGTFS = stopTimes.get(t.getTripID());
        System.out.println("Progressivo \tGTFS\tOSM");
        for (long f = 1; f <= stopGTFS.getStops().size(); f++) {
            Stop gtfs = stopGTFS.getStops().get(new Long(f));
            System.out
                    .println("Stop # " + f + "\t" + ((gtfs != null) ? gtfs.getCode() : "-") + "\t" + "-" + "*");
        }
    }
    System.out.println("---");
    for (Relation r : osmRelationNotFoundInGTFS) {
        System.out.println("---");
        Affinity affinityGTFS = affinities.get(r);
        System.out.println("Relation " + r.getId() + " (" + r.getName() + ") NOT matched in GTFS ");
        System.out.println("Best match (" + affinityGTFS.affinity + "): id: " + affinityGTFS.trip.getTripID()
                + " " + routes.get(affinityGTFS.trip.getRoute().getId()).getShortName() + " "
                + affinityGTFS.trip.getName());
        StopsList stopGTFS = stopTimes.get(affinityGTFS.trip.getTripID());
        StopsList stopOSM = r;
        long max = Math.max(stopGTFS.getStops().size(), stopOSM.getStops().size());
        System.out.println("Progressivo \tGTFS\tOSM");
        for (long f = 1; f <= max; f++) {
            Stop gtfs = stopGTFS.getStops().get(new Long(f));
            Stop osm = stopOSM.getStops().get(new Long(f));
            try {
                System.out.println("Stop # " + f + "\t" + ((gtfs != null) ? gtfs.getCode() : "-") + "\t"
                        + ((osm != null) ? osm.getCode() : "-")
                        + ((gtfs != null) && (osm != null) && gtfs.getCode().equals(osm.getCode()) ? "" : "*")
                        + "\t" + ((osm != null) ? osm.getName() : "-"));
            } catch (Exception e) {
                System.out.println("Stop # " + f + "\t-\r-");
            }
        }
    }
    System.out.println("---");
    System.out.println("Relation in OSM matched in GTFS: " + osmRelationFoundInGTFS.size());
    System.out.println("Relation in OSM not matched in GTFS: " + osmRelationNotFoundInGTFS.size());
    System.out.println("Trips in GTFS not matched in OSM: " + tripsNotFoundInOSM.size());
    System.out.println("---");
}