Example usage for com.google.common.collect Multimaps newSortedSetMultimap

List of usage examples for com.google.common.collect Multimaps newSortedSetMultimap

Introduction

In this page you can find the example usage for com.google.common.collect Multimaps newSortedSetMultimap.

Prototype

public static <K, V> SortedSetMultimap<K, V> newSortedSetMultimap(Map<K, Collection<V>> map,
        final Supplier<? extends SortedSet<V>> factory) 

Source Link

Document

Creates a new SortedSetMultimap that uses the provided map and factory.

Usage

From source file:org.terasology.documentation.ApiScraper.java

/**
 * @param args (ignored)//from www  .ja v a2  s  . c  o  m
 * @throws Exception if the module environment cannot be loaded
 */
public static void main(String[] args) throws Exception {
    ModuleManager moduleManager = ModuleManagerFactory.create();
    ModuleEnvironment environment = moduleManager.getEnvironment();
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    SortedSetMultimap<String, String> sortedApi = Multimaps.newSortedSetMultimap(new HashMap<>(), TreeSet::new);

    for (Class<?> apiClass : environment.getTypesAnnotatedWith(API.class)) {
        //System.out.println("Processing: " + apiClass);
        boolean isPackage = apiClass.isSynthetic();
        URL location;
        String category;
        String apiPackage = "";
        if (isPackage) {
            apiPackage = apiClass.getPackage().getName();
            location = classLoader.getResource(apiPackage.replace('.', '/'));
        } else {

            location = apiClass.getResource('/' + apiClass.getName().replace('.', '/') + ".class");
        }

        if (location == null) {
            System.out.println("Failed to get a class/package location, skipping " + apiClass);
            continue;
        }

        switch (location.getProtocol()) {
        case "jar":

            // Find out what jar it came from and consider that the category
            String categoryFragment = location.getPath();
            //System.out.println("category fragment as path: " + categoryFragment);
            int bang = categoryFragment.lastIndexOf("!");
            int hyphen = categoryFragment.lastIndexOf("-", bang);
            int slash = categoryFragment.lastIndexOf("/", hyphen);
            category = categoryFragment.substring(slash + 1, hyphen);
            //System.out.println("category fragment pared down: " + category);

            if (isPackage) {
                //System.out.println("Jar-based Package: " + apiPackage + ", came from " + location);
                sortedApi.put(category, apiPackage + " (PACKAGE)");
            } else {
                //System.out.println("Jar-based Class: " + apiClass + ", came from " + location);
                sortedApi.put(category,
                        apiClass.getName() + (apiClass.isInterface() ? " (INTERFACE)" : " (CLASS)"));
            }

            break;

        case "file":

            // If file based we know it is local so organize it like that
            category = "terasology engine";

            if (isPackage) {
                //System.out.println("Local Package: " + apiPackage + ", came from " + location);
                sortedApi.put(category, apiPackage + " (PACKAGE)");
            } else {
                //System.out.println("Local Class: " + apiClass + ", came from " + location);
                sortedApi.put(category,
                        apiClass.getName() + (apiClass.isInterface() ? " (INTERFACE)" : " (CLASS)"));
            }

            break;

        default:
            System.out.println("Unknown protocol for: " + apiClass + ", came from " + location);
        }
    }
    sortedApi.putAll("external", ExternalApiWhitelist.CLASSES.stream()
            .map(clazz -> clazz.getName() + " (CLASS)").collect(Collectors.toSet()));
    sortedApi.putAll("external", ExternalApiWhitelist.PACKAGES.stream().map(packagee -> packagee + " (PACKAGE)")
            .collect(Collectors.toSet()));

    System.out.println("# Modding API:\n");
    for (String key : sortedApi.keySet()) {
        System.out.println("## " + key + "\n");
        for (String value : sortedApi.get(key)) {
            System.out.println("* " + value);
        }
        System.out.println("");
    }
}

From source file:org.eclipse.ziggurat.inject.BindingManager.java

@SuppressWarnings("unchecked")
public static void registerBindings() {
    Map<Class, Collection<PriorityClass>> map = new HashMap<Class, Collection<PriorityClass>>();
    Supplier<SortedSet<PriorityClass>> factory = new Supplier<SortedSet<PriorityClass>>() {

        @Override//from w  w w.  j  a  va 2s. c o  m
        public SortedSet<PriorityClass> get() {
            SortedSet<PriorityClass> sorted = new TreeSet<PriorityClass>(new Comparator<PriorityClass>() {
                @Override
                public int compare(PriorityClass o1, PriorityClass o2) {
                    int result = new Integer(o1.priority).compareTo(o2.priority);
                    if (result == 0 && !o1.equals(o2)) {
                        result = -1;
                    }
                    return result;
                }
            });
            return sorted;
        }
    };
    SortedSetMultimap<Class, PriorityClass> multi = Multimaps.newSortedSetMultimap(map, factory);
    IConfigurationElement[] elements = Platform.getExtensionRegistry()
            .getConfigurationElementsFor(ZigguratInject.PLUGIN_ID, EXT_POINT);
    for (IConfigurationElement e : elements) {
        String theInterface = e.getAttribute("interface");
        String theImpl = e.getAttribute("impl");
        String name = e.getAttribute("name");
        Class theInterfaceC = loadClass(e, theInterface);
        Class theImplC = loadClass(e, theImpl);
        int priority = 0;
        String prio = e.getAttribute("priority");
        if (prio != null && prio.length() > 0) {
            try {
                priority = Integer.parseInt(prio);
            } catch (NumberFormatException ex) {
            }
        }
        if (theInterfaceC != null && theImplC != null && theInterfaceC.isAssignableFrom(theImplC)) {
            PriorityClass priorityClass = new PriorityClass();
            priorityClass.aClass = theImplC;
            priorityClass.priority = priority;
            priorityClass.name = name;
            multi.put(theInterfaceC, priorityClass);
        }
    }
    for (Class c : multi.keys()) {
        PriorityClass last = null;
        // for each priority class if name is present a binding is created with the given name
        for (PriorityClass pc : multi.get(c)) {
            if (pc.name != null && pc.name.length() > 0) {
                InjectorFactory.getDefault().addBinding(c).implementedBy(pc.aClass).named(pc.name);
            }
            last = pc;
        }
        if (last != null) {
            // the binding by default is made by a class with no name
            InjectorFactory.getDefault().addBinding(c).implementedBy(last.aClass);
        }
    }

}

From source file:com.dontocsata.xmltv.db.DataStorage.java

public DataStorage() {
    channels = new HashMap<>();
    xmlTvPrograms = new ArrayList<>();
    services = new HashMap<>();
    series = new HashMap<>();
    seasons = new HashMap<>();
    idProgramMap = new HashMap<>();
    channelProgramMap = Multimaps.newSortedSetMultimap(new HashMap<>(), TreeSet::new);
}

From source file:org.pentaho.big.data.api.cluster.service.locator.impl.NamedClusterServiceLocatorImpl.java

public NamedClusterServiceLocatorImpl(ClusterInitializer clusterInitializer) {
    this.clusterInitializer = clusterInitializer;
    readWriteLock = new ReentrantReadWriteLock();
    serviceFactoryMap = Multimaps.newSortedSetMultimap(
            new HashMap<Class<?>, Collection<ServiceFactoryAndRanking<?>>>(),
            new Supplier<SortedSet<ServiceFactoryAndRanking<?>>>() {
                @Override/*w  w w  . jav  a 2s. c  om*/
                public SortedSet<ServiceFactoryAndRanking<?>> get() {
                    return new TreeSet<>(new Comparator<ServiceFactoryAndRanking<?>>() {
                        @Override
                        public int compare(ServiceFactoryAndRanking<?> o1, ServiceFactoryAndRanking<?> o2) {
                            if (o1.ranking == o2.ranking) {
                                return o1.namedClusterServiceFactory.toString()
                                        .compareTo(o2.namedClusterServiceFactory.toString());
                            }
                            return o2.ranking - o1.ranking;
                        }
                    });
                }
            });
}

From source file:com.dontocsata.xmltv.db.DataStorage.java

public DataStorage(DB db) {
    channels = db.createHashMap("channels").makeOrGet();
    xmlTvPrograms = db.createHashSet("xmlTvPrograms").makeOrGet();
    services = db.createHashMap("services").makeOrGet();
    series = db.createHashMap("series").makeOrGet();
    seasons = db.createHashMap("seasons").makeOrGet();
    idProgramMap = db.createHashMap("idProgramMap").makeOrGet();
    channelProgramMap = Multimaps.newSortedSetMultimap(db.createHashMap("channelProgramMap").makeOrGet(),
            TreeSet::new);
}

From source file:org.eclipse.osee.orcs.script.dsl.OsFieldEnum.java

private static <K, V> SortedSetMultimap<K, V> newSetMultimap(final Comparator<V> comparator) {
    Map<K, Collection<V>> map = Maps.newLinkedHashMap();
    return Multimaps.newSortedSetMultimap(map, new Supplier<SortedSet<V>>() {
        @Override//  ww w .j  a  v a2  s. c o m
        public SortedSet<V> get() {
            return Sets.newTreeSet(comparator);
        }
    });
}

From source file:com.palantir.atlasdb.transaction.impl.SerializableTransaction.java

private void verifyRows(Transaction ro) {
    for (String table : rowsRead.keySet()) {
        final ConcurrentNavigableMap<Cell, byte[]> readsForTable = getReadsForTable(table);
        Multimap<ColumnSelection, byte[]> map = Multimaps.newSortedSetMultimap(
                Maps.<ColumnSelection, Collection<byte[]>>newHashMap(), new Supplier<SortedSet<byte[]>>() {
                    @Override//from   w ww.  ja v  a2 s  .  c  om
                    public TreeSet<byte[]> get() {
                        return Sets.newTreeSet(UnsignedBytes.lexicographicalComparator());
                    }
                });
        for (RowRead r : rowsRead.get(table)) {
            map.putAll(r.cols, r.rows);
        }
        for (final ColumnSelection cols : map.keySet()) {
            for (List<byte[]> batch : Iterables.partition(map.get(cols), 1000)) {
                SortedMap<byte[], RowResult<byte[]>> currentRows = ro.getRows(table, batch, cols);
                for (byte[] row : batch) {
                    RowResult<byte[]> currentRow = currentRows.get(row);
                    Map<Cell, byte[]> orignalReads = readsForTable
                            .tailMap(Cells.createSmallestCellForRow(row), true)
                            .headMap(Cells.createLargestCellForRow(row), true);

                    // We want to filter out all our reads to just the set that matches our column selection.
                    orignalReads = Maps.filterKeys(orignalReads, new Predicate<Cell>() {
                        @Override
                        public boolean apply(Cell input) {
                            return cols.contains(input.getColumnName());
                        }
                    });

                    if (writesByTable.get(table) != null) {
                        // We don't want to verify any reads that we wrote to cause we will just read our own values.
                        // NB: We filter our write set out here because our normal SI checking handles this case to ensure the value hasn't changed.
                        orignalReads = Maps.filterKeys(orignalReads,
                                Predicates.not(Predicates.in(writesByTable.get(table).keySet())));
                    }

                    if (currentRow == null && orignalReads.isEmpty()) {
                        continue;
                    }

                    if (currentRow == null) {
                        throw TransactionSerializableConflictException.create(table, getTimestamp(),
                                System.currentTimeMillis() - timeCreated);
                    }

                    Map<Cell, byte[]> currentCells = Maps2.fromEntries(currentRow.getCells());
                    if (writesByTable.get(table) != null) {
                        // We don't want to verify any reads that we wrote to cause we will just read our own values.
                        // NB: We filter our write set out here because our normal SI checking handles this case to ensure the value hasn't changed.
                        currentCells = Maps.filterKeys(currentCells,
                                Predicates.not(Predicates.in(writesByTable.get(table).keySet())));
                    }
                    if (!areMapsEqual(orignalReads, currentCells)) {
                        throw TransactionSerializableConflictException.create(table, getTimestamp(),
                                System.currentTimeMillis() - timeCreated);
                    }
                }
            }
        }

    }
}