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

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

Introduction

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

Prototype

boolean put(@Nullable K key, @Nullable V value);

Source Link

Document

Stores a key-value pair in this multimap.

Usage

From source file:com.zimbra.cs.db.DbBlobConsistency.java

public static void export(DbConnection conn, Mailbox mbox, String tableName, String idColName,
        Multimap<Integer, Integer> idRevs, String path) throws ServiceException {
    Set<Integer> mail_itemIds = new HashSet<Integer>();
    Multimap<Integer, Integer> rev_itemIds = HashMultimap.create();
    for (Integer itemId : idRevs.keySet()) {
        Collection<Integer> revs = idRevs.get(itemId);
        for (int rev : revs) {
            if (rev == 0) {
                mail_itemIds.add(itemId);
            } else {
                rev_itemIds.put(itemId, rev);
            }/*from  ww w  .j  a va  2  s .  c o m*/
        }
    }
    PreparedStatement stmt = null;

    if (!(Db.getInstance() instanceof MySQL)) {
        throw ServiceException.INVALID_REQUEST("export is only supported for MySQL", null);
    }
    ZimbraLog.sqltrace.info("Exporting %d items in table %s to %s.", idRevs.size(), tableName, path);

    try {
        StringBuffer sql = new StringBuffer();
        boolean revisionTable = tableName.startsWith(DbMailItem.TABLE_REVISION);
        sql.append("SELECT * FROM ").append(DbMailbox.qualifyTableName(mbox, tableName)).append(" WHERE ")
                .append(DbMailItem.IN_THIS_MAILBOX_AND);

        if (!revisionTable || mail_itemIds.size() > 0) {
            if (mail_itemIds.size() == 0) {
                sql.append(idColName).append(" in ('')");
            } else {
                sql.append(DbUtil.whereIn(idColName, mail_itemIds.size()));
            }
        }
        if (revisionTable) {
            if (mail_itemIds.size() > 0 && rev_itemIds.size() > 0) {
                sql.append(" OR ");
            }
            if (rev_itemIds.size() > 0) {
                sql.append(DbUtil.whereIn(Db.getInstance().concat(idColName, "'-'", "version"),
                        rev_itemIds.size()));
            }
        }
        sql.append(" INTO OUTFILE ?");
        stmt = conn.prepareStatement(sql.toString());
        int pos = 1;
        pos = DbMailItem.setMailboxId(stmt, mbox, pos);
        for (int itemId : mail_itemIds) {
            stmt.setInt(pos++, itemId);
        }

        if (revisionTable) {
            for (Integer itemId : rev_itemIds.keySet()) {
                Collection<Integer> revs = rev_itemIds.get(itemId);
                for (int rev : revs) {
                    stmt.setString(pos++, itemId + "-" + rev);
                }
            }
        }
        stmt.setString(pos++, path);
        stmt.execute();
    } catch (SQLException e) {
        throw ServiceException.FAILURE("exporting table " + tableName + " to " + path, e);
    } finally {
        DbPool.quietCloseStatement(stmt);
    }
}

From source file:com.zimbra.cs.db.DbBlobConsistency.java

public static void delete(DbConnection conn, Mailbox mbox, Multimap<Integer, Integer> idRevs)
        throws ServiceException {
    Set<Integer> mail_itemIds = new HashSet<Integer>();
    Multimap<Integer, Integer> rev_itemIds = HashMultimap.create();
    for (Integer itemId : idRevs.keySet()) {
        Collection<Integer> revs = idRevs.get(itemId);
        for (int rev : revs) {
            if (rev == 0) {
                mail_itemIds.add(itemId);
            } else {
                rev_itemIds.put(itemId, rev);
            }//from  ww  w  .j a  v a2  s. co m
        }
    }

    if (mail_itemIds.size() > 0) {
        PreparedStatement miDumpstmt = null;
        try {
            StringBuffer sql = new StringBuffer();
            sql.append("DELETE FROM ").append(DbMailItem.getMailItemTableName(mbox, true)).append(" WHERE ")
                    .append(DbMailItem.IN_THIS_MAILBOX_AND).append(DbUtil.whereIn("id", mail_itemIds.size()));

            miDumpstmt = conn.prepareStatement(sql.toString());
            int pos = 1;
            pos = DbMailItem.setMailboxId(miDumpstmt, mbox, pos);
            for (int itemId : mail_itemIds) {
                miDumpstmt.setInt(pos++, itemId);
            }
            miDumpstmt.execute();
        } catch (SQLException e) {
            throw ServiceException.FAILURE(
                    "deleting " + idRevs.size() + " item(s): " + DbMailItem.getIdListForLogging(idRevs.keys())
                            + " from " + DbMailItem.TABLE_MAIL_ITEM_DUMPSTER + " table",
                    e);
        } finally {
            DbPool.quietCloseStatement(miDumpstmt);
        }
    }

    if (rev_itemIds.size() > 0) {
        PreparedStatement revDumpstmt = null;
        try {
            StringBuffer sql = new StringBuffer();
            sql.append("DELETE FROM ").append(DbMailItem.getRevisionTableName(mbox, true)).append(" WHERE ")
                    .append(DbMailItem.IN_THIS_MAILBOX_AND).append(DbUtil
                            .whereIn(Db.getInstance().concat("item_id", "'-'", "version"), rev_itemIds.size()));

            revDumpstmt = conn.prepareStatement(sql.toString());
            int pos = 1;
            pos = DbMailItem.setMailboxId(revDumpstmt, mbox, pos);
            for (Integer itemId : rev_itemIds.keySet()) {
                Collection<Integer> revs = rev_itemIds.get(itemId);
                for (int rev : revs) {
                    revDumpstmt.setString(pos++, itemId + "-" + rev);
                }
            }
            revDumpstmt.execute();
        } catch (SQLException e) {
            throw ServiceException.FAILURE(
                    "deleting " + idRevs.size() + " item(s): " + DbMailItem.getIdListForLogging(idRevs.keys())
                            + " from " + DbMailItem.TABLE_REVISION_DUMPSTER + " table",
                    e);
        } finally {
            DbPool.quietCloseStatement(revDumpstmt);
        }
    }
}

From source file:com.eucalyptus.cloudwatch.common.internal.domain.metricdata.MetricManager.java

private static Multimap<Class, MetricEntity> makeMetricMap(Collection<MetricEntity> entities) {
    Multimap<Class, MetricEntity> metricMap = ArrayListMultimap.<Class, MetricEntity>create();
    for (MetricEntity entity : entities) {
        metricMap.put(
                MetricEntityFactory.getClassForEntitiesGet(entity.getMetricType(), entity.getDimensionHash()),
                entity);/* ww  w.  j  av a 2  s.  co  m*/
    }
    return metricMap;
}

From source file:moa2014.MOAH52014.java

public static int principal(int[][] matrizatual) {
    long startTime = System.currentTimeMillis();
    Multimap<Integer, String> open_list = TreeMultimap.create();
    HashMap<String, Estado> processados = new HashMap();

    int h1x = MOAH12014.diferencaMatriz(matrizatual);
    int h2x = MOAH22014.diferencaMatriz(matrizatual);
    int h3x = MOAH32014.diferencaMatriz(matrizatual);

    int difmatrizatual = maior(h1x, h2x, h3x);

    String stringmatriz = transformaMatrizString(matrizatual);
    open_list.put(difmatrizatual, stringmatriz);
    Estado estadoatual = new Estado(matrizatual, 0);
    processados.put(stringmatriz, estadoatual);

    int arvoresgeradas = 0;
    int arvoresprocessadas = 0;

    while (!open_list.isEmpty()) {

        Iterator iterator = open_list.keySet().iterator();

        Integer key = (Integer) iterator.next();
        String matrizatualx1 = open_list.asMap().get(key).iterator().next();
        Estado estadomenor = processados.get(matrizatualx1);
        int altura = estadomenor.getCusto();

        //LOCALIZA O ZERO
        int[] zerot = localizazero(estadomenor.getMatriz());
        int x = zerot[0];
        int y = zerot[1];
        int x0 = x - 1;
        int x1 = x + 1;
        int y0 = y - 1;
        int y1 = y + 1;
        int difmatrizatualx = MOAH32014.diferencaMatriz(estadomenor.getMatriz());
        if (difmatrizatualx == 0) {
            long endTime = System.currentTimeMillis();
            System.out.println("---------------------------------------");
            System.out.println("Arvores Geradas: " + arvoresgeradas);
            System.out.println("Arvores Processadas: " + arvoresprocessadas);
            System.out.println("Quantidade de Movimentos: " + estadomenor.getCusto());
            System.out.println("Tempo de processamento " + (endTime - startTime) + " ms");
            System.out.println("---------------------------------------\n\n");
            return 0;
        }//from w w w.ja  va  2  s . com
        int[][] matrizatualx = estadomenor.getMatriz();
        arvoresprocessadas++;
        if (x0 >= 0) {

            int[][] matriz;
            matriz = copyarray(matrizatualx);
            matriz[x][y] = matrizatualx[x0][y];
            matriz[x0][y] = matrizatualx[x][y];

            String stringmatriz1 = transformaMatrizString(matriz);
            if (!(processados.containsKey(stringmatriz1))) {
                arvoresgeradas++;
                h1x = MOAH12014.diferencaMatriz(matriz);
                h2x = MOAH22014.diferencaMatriz(matriz);
                h3x = MOAH32014.diferencaMatriz(matriz);
                int diferencamatriz = maior(h1x, h2x, h3x);
                int custototal = diferencamatriz + altura + 1;

                Estado estadonovo = new Estado(matriz, altura + 1);
                open_list.put(custototal, stringmatriz1);

                processados.put(stringmatriz1, estadonovo);

            }
        }
        if (x1 <= 3) {
            int[][] matriz;
            matriz = copyarray(matrizatualx);
            matriz[x][y] = matrizatualx[x1][y];
            matriz[x1][y] = matrizatualx[x][y];
            String stringmatriz2 = transformaMatrizString(matriz);

            if (!(processados.containsKey(stringmatriz2))) {
                arvoresgeradas++;
                h1x = MOAH12014.diferencaMatriz(matriz);
                h2x = MOAH22014.diferencaMatriz(matriz);
                h3x = MOAH32014.diferencaMatriz(matriz);
                int diferencamatriz = maior(h1x, h2x, h3x);
                int custototal = diferencamatriz + altura + 1;

                Estado estadonovo = new Estado(matriz, altura + 1);
                open_list.put(custototal, stringmatriz2);

                processados.put(stringmatriz2, estadonovo);

            }
        }
        if (y0 >= 0) {
            int[][] matriz;
            matriz = copyarray(matrizatualx);
            matriz[x][y] = matrizatualx[x][y0];
            matriz[x][y0] = matrizatualx[x][y];
            String stringmatriz3 = transformaMatrizString(matriz);

            if (!(processados.containsKey(stringmatriz3))) {
                arvoresgeradas++;
                h1x = MOAH12014.diferencaMatriz(matriz);
                h2x = MOAH22014.diferencaMatriz(matriz);
                h3x = MOAH32014.diferencaMatriz(matriz);
                int diferencamatriz = maior(h1x, h2x, h3x);
                int custototal = diferencamatriz + altura + 1;

                Estado estadonovo = new Estado(matriz, altura + 1);
                open_list.put(custototal, stringmatriz3);

                processados.put(stringmatriz3, estadonovo);

            }
        }
        if (y1 <= 3) {
            int[][] matriz;
            matriz = copyarray(matrizatualx);
            matriz[x][y] = matrizatualx[x][y1];
            matriz[x][y1] = matrizatualx[x][y];

            String stringmatriz4 = transformaMatrizString(matriz);

            if (!(processados.containsKey(stringmatriz4))) {
                arvoresgeradas++;
                h1x = MOAH12014.diferencaMatriz(matriz);
                h2x = MOAH22014.diferencaMatriz(matriz);
                h3x = MOAH32014.diferencaMatriz(matriz);
                int diferencamatriz = maior(h1x, h2x, h3x);
                int custototal = diferencamatriz + altura + 1;

                Estado estadonovo = new Estado(matriz, altura + 1);
                open_list.put(custototal, stringmatriz4);

                processados.put(stringmatriz4, estadonovo);

            }
        }
        open_list.remove(key, matrizatualx1);
    }
    return 0;

}

From source file:pt.ist.maidSyncher.domain.MaidRoot.java

private static Multimap<DSIObject, SyncEvent> getMultiMapFromSyncEvents(Collection<SyncEvent> syncEvents) {
    Multimap<DSIObject, SyncEvent> multimap = HashMultimap.create();
    for (SyncEvent syncEvent : syncEvents) {
        multimap.put(syncEvent.getDsiElement(), syncEvent);
    }/* ww  w . j  av a2s.  c o  m*/
    return multimap;
}

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

private static QueryOperationExecutor create(Collection<VarPatternAdmin> patterns, GraknTx graph,
        ExecutionType executionType) {/*from  w  w w  .  j a  v  a2 s  . com*/
    ImmutableSet<VarAndProperty> properties = patterns.stream().flatMap(VarAndProperty::fromPattern)
            .collect(toImmutableSet());

    /*
    We build several many-to-many relations, indicated by a `Multimap<X, Y>`. These are used to represent
    the dependencies between properties and variables.
            
    `propDependencies.containsEntry(prop, var)` indicates that the property `prop` cannot be inserted until
    the concept represented by the variable `var` is created.
            
    For example, the property `$x isa $y` depends on the existence of the concept represented by `$y`.
     */
    Multimap<VarAndProperty, Var> propDependencies = HashMultimap.create();

    for (VarAndProperty property : properties) {
        for (Var requiredVar : property.executor(executionType).requiredVars()) {
            propDependencies.put(property, requiredVar);
        }
    }

    /*
    `varDependencies.containsEntry(var, prop)` indicates that the concept represented by the variable `var`
    cannot be created until the property `prop` is inserted.
            
    For example, the concept represented by `$x` will not exist before the property `$x isa $y` is inserted.
     */
    Multimap<Var, VarAndProperty> varDependencies = HashMultimap.create();

    for (VarAndProperty property : properties) {
        for (Var producedVar : property.executor(executionType).producedVars()) {
            varDependencies.put(producedVar, property);
        }
    }

    /*
    Equivalent vars are variables that must represent the same concept as another var.
            
         $X label movie, sub entity;
         $Y label movie;
         $z isa $Y;
            
    In this example, `$z isa $Y` must not be inserted before `$Y` is. However, `$Y` does not have enough
    information to insert on its own. It also needs a super type!
            
    We know `$Y` must represent the same concept as `$X`, because they both share the same label property.
    Therefore, we can share their dependencies, such that:
            
        varDependencies.containsEntry($X, prop) <=> varDependencies.containsEntry($Y, prop)
            
    Therefore:
            
        varDependencies.containsEntry($X, `$X sub entity`) => varDependencies.containsEntry($Y, `$X sub entity`)
            
    Now we know that `$Y` depends on `$X sub entity` as well as `$X label movie`, which is enough information to
    insert the type!
     */

    Partition<Var> equivalentVars = Partition.singletons(Collections.emptyList());

    equivalentProperties(properties).asMap().values().forEach(vars -> {
        // These vars must refer to the same concept, so share their dependencies
        Collection<VarAndProperty> producers = vars.stream().flatMap(var -> varDependencies.get(var).stream())
                .collect(toList());

        Var first = vars.iterator().next();

        vars.forEach(var -> {
            varDependencies.replaceValues(var, producers);
            equivalentVars.merge(first, var);
        });
    });

    /*
    Together, `propDependencies` and `varDependencies` can be composed into a single many-to-many relation:
            
        dependencies = propDependencies  varDependencies
            
    By doing so, we map _directly_ between properties, skipping the vars. For example, if we previously had:
            
        propDependencies.containsEntry(`$x isa $y`, `$y`);         // `$x isa $y` depends on `$y`
        varDependencies.containsEntry(`$y`, `$y label movie`);     // `$y` depends on `$y label movie`
            
    Then it follows that:
            
        dependencies.containsEntry(`$x isa $y`, `$y label movie`); // `$x isa $y` depends on `$y label movie`
            
    The `dependencies` relation contains all the information to decide what order to execute the properties.
     */
    Multimap<VarAndProperty, VarAndProperty> dependencies = composeMultimaps(propDependencies, varDependencies);

    return new QueryOperationExecutor(graph, properties, equivalentVars, ImmutableMultimap.copyOf(dependencies),
            executionType);
}

From source file:ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.java

/**
 * calculates map intersection by doing an intersection on key sets and accumulating the keys
 * @param m1 first operand/*ww  w.ja  v  a2  s  .  c  om*/
 * @param m2 second operand
 * @param <K> map key type
 * @param <V> map value type
 * @return map intersection
 */
public static <K, V> Multimap<K, V> multimapIntersection(Multimap<K, V> m1, Multimap<K, V> m2) {
    Multimap<K, V> intersection = HashMultimap.create();
    Sets.SetView<K> keyIntersection = Sets.intersection(m1.keySet(), m2.keySet());
    Stream.concat(m1.entries().stream(), m2.entries().stream())
            .filter(e -> keyIntersection.contains(e.getKey()))
            .forEach(e -> intersection.put(e.getKey(), e.getValue()));
    return intersection;
}

From source file:org.opencastproject.util.data.Collections.java

/**
 * Partition a list after some predicate <code>group</code> into <code>map</code>.
 *//*from w w  w  .j a v a  2s.  c o m*/
public static <K, V> Multimap<K, V> groupBy(Multimap<K, V> map, List<V> values, Function<V, K> group) {
    for (V value : values) {
        final K key = group.apply(value);
        map.put(key, value);
    }
    return map;
}

From source file:net.myrrix.online.eval.ReconstructionEvaluator.java

private static Multimap<Long, RecommendedItem> readAndCopyDataFiles(File dataDir, File tempDir)
        throws IOException {
    Multimap<Long, RecommendedItem> data = ArrayListMultimap.create();
    for (File dataFile : dataDir.listFiles(new PatternFilenameFilter(".+\\.csv(\\.(zip|gz))?"))) {
        log.info("Reading {}", dataFile);
        int count = 0;
        for (CharSequence line : new FileLineIterable(dataFile)) {
            Iterator<String> parts = COMMA_TAB_SPLIT.split(line).iterator();
            long userID = Long.parseLong(parts.next());
            long itemID = Long.parseLong(parts.next());
            if (parts.hasNext()) {
                String token = parts.next().trim();
                if (!token.isEmpty()) {
                    data.put(userID, new GenericRecommendedItem(itemID, LangUtils.parseFloat(token)));
                }//from w w  w  . j a v a  2s. c o  m
                // Ignore remove lines
            } else {
                data.put(userID, new GenericRecommendedItem(itemID, 1.0f));
            }
            if (++count % 1000000 == 0) {
                log.info("Finished {} lines", count);
            }
        }

        Files.copy(dataFile, new File(tempDir, dataFile.getName()));
    }
    return data;
}

From source file:com.facebook.buck.cli.MissingSymbolsHandler.java

/**
 * Instantiate a MissingSymbolsHandler and wrap it in a listener that calls it on the appropriate
 * events. This is done as part of the global listener setup in Main, and it's the entry point
 * into most of the dependency autodetection code.
 *//*  w w  w . j  a v a  2  s.co  m*/
public static BuckEventListener createListener(ProjectFilesystem projectFilesystem,
        ImmutableSet<Description<?>> descriptions, BuckConfig config, BuckEventBus buckEventBus,
        Console console, JavacOptions javacOptions, ImmutableMap<String, String> environment) {
    final MissingSymbolsHandler missingSymbolsHandler = create(projectFilesystem, descriptions, config,
            buckEventBus, console, javacOptions, environment);

    final Multimap<BuildId, MissingSymbolEvent> missingSymbolEvents = HashMultimap.create();

    BuckEventListener missingSymbolsListener = new BuckEventListener() {
        @Override
        public void outputTrace(BuildId buildId) {
            // If we put {@link #printNeededDependencies} here, it's output won't be visible in buckd.
            // Instead, we listen for BuildEvent.Finished, below.
        }

        @Subscribe
        public void onMissingSymbol(MissingSymbolEvent event) {
            missingSymbolEvents.put(event.getBuildId(), event);
        }

        @Subscribe
        public void onBuildFinished(BuildEvent.Finished event) {
            // Shortcircuit if there aren't any failures.
            if (missingSymbolEvents.get(event.getBuildId()).isEmpty()) {
                return;
            }
            try {
                missingSymbolsHandler.printNeededDependencies(missingSymbolEvents.get(event.getBuildId()));
            } catch (InterruptedException e) {
                LOG.debug(e, "Missing symbols handler did not complete in time.");
            } catch (RuntimeException e) {
                if (e.getCause() instanceof ClosedByInterruptException) {
                    LOG.debug(e.getCause(), "Missing symbols handler did not complete in time.");
                } else {
                    throw e;
                }
            }
            missingSymbolEvents.removeAll(event.getBuildId());
        }
    };

    return missingSymbolsListener;
}