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

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

Introduction

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

Prototype

Collection<V> get(@Nullable K key);

Source Link

Document

Returns a view collection of the values associated with key in this multimap, if any.

Usage

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);/*from   ww  w  . java 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("---");
}

From source file:com.android.tools.idea.editors.theme.attributes.AttributesGrouper.java

@NotNull
private static List<TableLabel> generateLabelsForType(@NotNull final List<EditedStyleItem> source,
        @NotNull final List<EditedStyleItem> sink) {
    // ArrayListMultimap is used to ensure the elements stay sorted
    final Multimap<Group, EditedStyleItem> classes = ArrayListMultimap.create();

    for (final EditedStyleItem item : source) {
        final String name = item.getName();
        classes.put(Group.getGroupFromName(name), item);
    }//from  www .  j a va 2s .c o m

    final List<TableLabel> labels = new ArrayList<TableLabel>();
    int offset = 0;
    for (Group group : Group.values()) {
        Collection<EditedStyleItem> elements = classes.get(group);

        boolean addHeader = !elements.isEmpty();
        if (addHeader && group == Group.OTHER) {
            // Adding "Everything else" label only in case when there are at least one other label,
            // because having "Everything else" as the only label present looks quite silly
            addHeader = offset != 0;
        }
        if (addHeader) {
            labels.add(new TableLabel(group.name, offset));
        }

        sink.addAll(elements);

        offset += elements.size();
    }

    return labels;
}

From source file:org.caleydo.view.domino.internal.NodeDataItem.java

public static void update(final Set<NodeGroup> mouseOvers, final Set<NodeGroup> selections) {
    final NodeDataItem i = instance;
    if (i == null)
        return;//from   w ww  .  j  a va 2s  . c  om
    Set<NodeGroup> toShow = selections;
    if (!mouseOvers.isEmpty()) {
        toShow = mouseOvers;
    }

    String text;
    if (toShow.isEmpty()) {
        text = "No Selection";
    } else {
        Multimap<Node, NodeGroup> nodes = HashMultimap.create();
        for (NodeGroup group : toShow) {
            Node n = group.getNode();
            nodes.put(n, group);
        }
        StringBuilder b = new StringBuilder();
        for (ILabeled node : ImmutableSortedSet.orderedBy(Labels.BY_LABEL).addAll(nodes.keySet()).build()) {
            Node n = (Node) node;
            addNodeInfos(b, n, nodes.get(n));
            b.append('\n');
        }
        b.setLength(b.length() - 1);
        text = b.toString();
    }

    final String t = text;
    Display.getDefault().asyncExec(new Runnable() {
        @Override
        public void run() {
            i.updateImpl(t);
        }
    });
}

From source file:com.torodb.torod.db.postgresql.meta.routines.DeleteDocuments.java

public static int execute(Configuration configuration, CollectionSchema colSchema,
        Multimap<DocStructure, Integer> didsByStructure) throws SQLException {
    TableProvider tableProvider = new TableProvider(colSchema);

    DSLContext dsl = DSL.using(configuration);

    Set<SubDocTable> tables = Sets.newHashSet();
    for (DocStructure structure : didsByStructure.keySet()) {
        tables.clear();/* w  w w.j  a  va  2s .c o  m*/
        structure.accept(tableProvider, tables);

        executeDeleteSubDocuments(dsl, tables, didsByStructure.get(structure));
    }

    Set<Integer> dids = Sets.newHashSet(didsByStructure.values());
    return executeDeleteRoots(dsl, colSchema, dids);
}

From source file:org.apache.bigtop.itest.hbase.system.Scanner.java

public static int doScan(HTable table, int val) throws IOException, InterruptedException {
    Scan s = new Scan();
    byte[] start = {};
    byte[] stop = {};
    byte[] value = Bytes.toBytes(String.format("%010d", val));
    s.setStartRow(start);/*from  w  w  w  . j av a  2  s  .  c  om*/
    s.setStopRow(stop);
    SingleColumnValueFilter filter = new SingleColumnValueFilter(Bytes.toBytes("f1"), Bytes.toBytes("qual"),
            CompareOp.EQUAL, value);
    s.setFilter(filter);

    // Keep track of gathered elements.
    Multimap<String, String> mm = ArrayListMultimap.create();

    // Counts
    int cnt = 0;
    long i = 0;
    ResultScanner rs = table.getScanner(s);
    for (Result r : rs) {
        if (r.getRow() == null) {
            continue;
        }

        NavigableMap<byte[], NavigableMap<byte[], NavigableMap<Long, byte[]>>> columnFamilyMap = r.getMap();

        // Output time to show if flush related.
        String k = Bytes.toStringBinary(r.getRow());
        if (mm.get(k).size() >= 1) {
            System.out.println("Duplicate rowkey " + k);
            LOG.error("Duplicate rowkey " + k);
        }

        mm.put(Bytes.toStringBinary(r.getRow()), i + ": " + r);
        cnt++;
        i++;
    }

    System.out.println("scan items counted: " + cnt + " for scan " + s.toString() + " with filter f1:qual == "
            + Bytes.toString(value));

    // Print out dupes.
    int dupes = 0;
    for (Entry<String, Collection<String>> e : mm.asMap().entrySet()) {
        if (e.getValue().size() > 1) {
            dupes++;
            System.out.print("Row " + e.getKey() + " had time stamps: ");
            String[] tss = e.getValue().toArray(new String[0]);
            System.out.println(Arrays.toString(tss));
        }
    }

    return dupes;
}

From source file:com.googlesource.gerrit.plugins.findowners.OwnersValidator.java

private static void checkEmails(List<CommitValidationMessage> messages, Emails emails,
        Map<String, Set<String>> email2lines, boolean verbose) {
    List<String> owners = new ArrayList<>(email2lines.keySet());
    if (verbose) {
        for (String owner : owners) {
            add(messages, "owner: " + owner, false);
        }//from   www.ja v  a 2  s  . c  o  m
    }
    if (emails == null || owners.isEmpty()) {
        return;
    }
    String[] ownerEmailsAsArray = new String[owners.size()];
    owners.toArray(ownerEmailsAsArray);
    try {
        Multimap<String, Account.Id> email2ids = emails.getAccountsFor(ownerEmailsAsArray);
        for (String owner : ownerEmailsAsArray) {
            boolean wrongEmail = (email2ids == null);
            if (!wrongEmail) {
                try {
                    Collection<Account.Id> ids = email2ids.get(owner);
                    wrongEmail = (ids == null || ids.isEmpty());
                } catch (Exception e) {
                    wrongEmail = true;
                }
            }
            if (wrongEmail) {
                String locations = String.join(" ", email2lines.get(owner));
                add(messages, "unknown: " + owner + " at " + locations, true);
            }
        }
    } catch (Exception e) {
        add(messages, "checkEmails failed.", true);
    }
}

From source file:org.sonar.server.permission.ws.template.TemplateUsersAction.java

private static WsPermissions.UsersWsResponse buildResponse(List<UserDto> users,
        List<PermissionTemplateUserDto> permissionTemplateUsers, Paging paging) {
    Multimap<Integer, String> permissionsByUserId = TreeMultimap.create();
    permissionTemplateUsers.forEach(userPermission -> permissionsByUserId.put(userPermission.getUserId(),
            userPermission.getPermission()));

    UsersWsResponse.Builder responseBuilder = UsersWsResponse.newBuilder();
    users.forEach(user -> {/* w  ww .  j  av  a2  s .  c  o m*/
        WsPermissions.User.Builder userResponse = responseBuilder.addUsersBuilder().setLogin(user.getLogin())
                .addAllPermissions(permissionsByUserId.get(user.getId()));
        setNullable(user.getEmail(), userResponse::setEmail);
        setNullable(user.getName(), userResponse::setName);
    });
    responseBuilder.getPagingBuilder().setPageIndex(paging.pageIndex()).setPageSize(paging.pageSize())
            .setTotal(paging.total()).build();
    return responseBuilder.build();
}

From source file:com.google.testing.testify.risk.frontend.server.util.DataRequestDocumentGenerator.java

/**
 * Returns an XML document describing the data requests.
 *//* www . j  a  va2 s . c  o m*/
public static String generateDocument(List<DataRequest> allDataRequests) {
    try {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document document = docBuilder.newDocument();

        Element documentRoot = document.createElement("TestAnalytics");
        document.appendChild(documentRoot);

        // Group all requests by their parent project.
        Multimap<Long, DataRequest> requestsByProject = getRequestsByProject(allDataRequests);
        for (Long projectId : requestsByProject.keySet()) {
            Element projectElement = document.createElement("DataRequests");
            projectElement.setAttribute("ProjectID", Long.toString(projectId));
            documentRoot.appendChild(projectElement);

            // Group project requests by data source.
            Collection<DataRequest> projectRequests = requestsByProject.get(projectId);
            Multimap<String, DataRequest> requestsBySource = getRequestsByDataSource(projectRequests);
            for (String sourceName : requestsBySource.keySet()) {
                Element dataSourceElement = document.createElement("DataRequest");
                dataSourceElement.setAttribute("Type", sourceName);
                projectElement.appendChild(dataSourceElement);

                // Write out the configuration parameter strings for the data source.
                for (DataRequest request : requestsBySource.get(sourceName)) {
                    for (DataRequestOption option : request.getDataRequestOptions()) {
                        Element dataSourceParameter = document.createElement("Parameter");
                        dataSourceParameter.setAttribute("Name", option.getName());
                        dataSourceParameter.appendChild(document.createTextNode(option.getValue()));
                        dataSourceElement.appendChild(dataSourceParameter);
                    }
                }
            }
        }

        // Now dump the document in memory to a string.
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        DOMSource source = new DOMSource(document);
        StreamResult result = new javax.xml.transform.stream.StreamResult(new StringWriter());

        transformer.transform(source, result);
        return result.getWriter().toString();
        // COV_NF_START
    } catch (TransformerConfigurationException tce) {
        return "Error in transformer configuration.";
    } catch (TransformerException te) {
        return "Error transforming document.";
    } catch (ParserConfigurationException pce) {
        return "Error in parser configuration.";
    }
    // COV_NF_END
}

From source file:com.eucalyptus.util.dns.DnsResolvers.java

@SuppressWarnings("unchecked")
private static void addRRset(Name name, final Message response, Record[] records, final int section) {
    final Multimap<RequestType, Record> rrsets = LinkedHashMultimap.create();
    for (Record r : records) {
        RequestType type = RequestType.typeOf(r.getType());
        rrsets.get(type).addAll(Collections2.filter(Arrays.asList(records), type));
    }//from  w w  w  .  j  av  a  2  s .  com
    Predicate<Record> checkNewRecord = new Predicate<Record>() {

        @Override
        public boolean apply(Record input) {
            for (int s = 1; s <= section; s++) {
                if (response.findRecord(input, s)) {
                    return false;
                }
            }
            return true;
        }
    };
    if (rrsets.containsKey(RequestType.CNAME)) {
        for (Record cnames : Iterables.filter(rrsets.removeAll(RequestType.CNAME), checkNewRecord)) {
            response.addRecord(cnames, section);
        }
    }
    for (Record sectionRecord : Iterables.filter(rrsets.values(), checkNewRecord)) {
        response.addRecord(sectionRecord, section);
    }
}

From source file:org.sonar.server.permission.ws.UsersAction.java

private static UsersWsResponse buildResponse(List<UserDto> users, List<UserPermissionDto> userPermissions,
        Paging paging) {// w  w w.  ja  va 2  s .com
    Multimap<Integer, String> permissionsByUserId = TreeMultimap.create();
    userPermissions.forEach(userPermission -> permissionsByUserId.put(userPermission.getUserId(),
            userPermission.getPermission()));

    UsersWsResponse.Builder response = UsersWsResponse.newBuilder();
    users.forEach(user -> {
        WsPermissions.User.Builder userResponse = response.addUsersBuilder().setLogin(user.getLogin())
                .addAllPermissions(permissionsByUserId.get(user.getId()));
        setNullable(user.getEmail(), userResponse::setEmail);
        setNullable(user.getName(), userResponse::setName);
    });

    response.getPagingBuilder().setPageIndex(paging.pageIndex()).setPageSize(paging.pageSize())
            .setTotal(paging.total()).build();

    return response.build();
}