Example usage for com.google.common.collect BiMap size

List of usage examples for com.google.common.collect BiMap size

Introduction

In this page you can find the example usage for com.google.common.collect BiMap size.

Prototype

int size();

Source Link

Document

Returns the number of key-value mappings in this map.

Usage

From source file:org.sosy_lab.cpachecker.util.octagon.OctagonIntManager.java

@Override
public String print(Octagon oct, BiMap<Integer, MemoryLocation> map) {
    StringBuilder str = new StringBuilder();
    int dimension = dimension(oct);
    long pointer = oct.getOctId();
    str.append("Octagon (id: " + pointer + ") (dimension: " + dimension + ")\n");
    if (isEmpty(oct)) {
        str.append("[Empty]\n");
        return str.toString();
    }// w ww.jav a2  s  .  co  m

    NumArray lower = init_num_t(1);
    NumArray upper = init_num_t(1);

    for (int i = 0; i < map.size(); i++) {
        str.append(" ").append(map.get(i)).append(" -> [");
        J_get_bounds(oct.getOctId(), i, upper.getArray(), lower.getArray());
        if (J_num_infty(lower.getArray(), 0)) {
            str.append("-INFINITY, ");
        } else {
            str.append(J_num_get_int(lower.getArray(), 0) * -1).append(", ");
        }
        if (J_num_infty(upper.getArray(), 0)) {
            str.append("INFINITY]\n");
        } else {
            str.append(J_num_get_int(upper.getArray(), 0)).append("]\n");
        }
    }
    J_num_clear_n(lower.getArray(), 1);
    J_num_clear_n(upper.getArray(), 1);
    return str.toString();
}

From source file:ca.wumbo.wdl.database.LogEventSubmitter.java

/**
 * Checks that the game ID and players are valid before committing them.
 * If not, an exception will be thrown.//from   w ww  . j  ava2  s  .c o  m
 * 
 * @param dbGameId
 *       The ID to check.
 *       
 * @param idToPlayerMap
 *       The ID to players to check.
 * 
 * @throws SQLException
 *       If the database has an error submitting statements. 
 * 
 * @throws MissingGameInDatabaseException
 *       If the game is missing from the database.
 */
private void checkDatabaseValues(int dbGameId, BiMap<Integer, String> idToPlayerMap) throws SQLException {
    assert dbGameId >= 0;
    assert idToPlayerMap != null;
    assert idToPlayerMap.size() > 0;

    // Check that the game exists.
    if (!hasRowsFromQuery("SELECT COUNT(*) FROM `wdl`.`games` WHERE game_id = " + dbGameId)) {
        throw new MissingGameInDatabaseException("Game " + dbGameId + " already exists in the database.");
    }
    log.debug("Game {} exists in the database, proceeding to add data.", dbGameId);

    // Check if player numbers are valid and in the database.
    int idCount = -1;
    try (Statement stmt = connection.createStatement()) {
        // Convert all the numbers to a string so we can join it to the query.
        ArrayList<String> stringNumbers = new ArrayList<>();
        idToPlayerMap.keySet().stream().forEach(i -> stringNumbers.add(Integer.toString(i)));
        String query = "SELECT COUNT(*) FROM `wdl`.`players` WHERE player_id = "
                + String.join(" OR player_id = ", stringNumbers);
        log.trace("Looking for players: {}", query);
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {
            idCount = rs.getInt("COUNT(*)");
        }
    } catch (SQLException e) {
        log.error("Error trying to find if a player ID is in the database.", e);
        throw e;
    }

    // If we are missing any players, error out.
    if (idCount != idToPlayerMap.size()) {
        log.error(
                "Missing some player from the database, got {} counted players but expected {} (from idToNameMap).",
                idCount, idToPlayerMap.size());
        throw new SQLException("Unexpected player count size: " + idCount + " vs " + idToPlayerMap.size());
    }
}

From source file:ca.wumbo.wdl.database.LogEventSubmitter.java

/**
 * Checks if the demo places for the games are present in the table, and if
 * they are not, it creates them. This is needed since we want to preseve the
 * player demos if the database has to be wiped, without losing the data
 * of who uploaded it or if it was not uploaded... etc. <br>
 * <br>/*from   w w  w . java  2  s  .  co m*/
 * Note that the game ID should be legitimate by the time this is reached,
 * operating on a non-existing game ID will likely yield SQLExceptions.
 * 
 * @param dbGameId
 *       The game ID in the database.
 * 
 * @param idToPlayerMap
 *       The ID to player map. 
 * 
 * @throws SQLException
 *       If the database has trouble being accessed. 
 */
private void createDemoEntriesIfNotPresent(int dbGameId, BiMap<Integer, String> idToPlayerMap)
        throws SQLException {
    assert dbGameId >= 0;
    assert idToPlayerMap != null;
    assert idToPlayerMap.size() > 0;

    // Find all the players who already have a demo entry present.
    Set<Integer> idsWithoutDemos = new HashSet<>();
    idToPlayerMap.keySet().forEach(idsWithoutDemos::add);
    String query = "SELECT fk_player_id FROM `wdl`.`demos` " + "WHERE fk_game_id = " + dbGameId;
    try (Statement stmt = connection.createStatement()) {
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {
            Integer id = rs.getInt("fk_player_id");
            if (idsWithoutDemos.contains(id)) {
                idsWithoutDemos.remove(id);
            }
        }
    } catch (SQLException e) {
        log.error("Error searching for players who may have a demo present.", e);
        throw e;
    }

    // For all the players who do not have a demo entry, make one.
    ArrayList<String> queries = new ArrayList<>();
    idsWithoutDemos.forEach(id -> {
        final String queryInsert = "INSERT INTO `wdl`.`demos`(fk_game_id, fk_player_id) VALUES (" + dbGameId
                + "," + id.intValue() + ")";
        log.trace(">>> {}", queryInsert);
        queries.add(queryInsert);
    });

    // Submit the queries now.
    log.debug("Executing game addition queries for {} players.", queries.size());
    try (Statement stmt = connection.createStatement()) {
        for (String queryStr : queries) {
            log.trace(">>> {}", queryStr);
            stmt.addBatch(queryStr);
        }
        stmt.executeBatch();
    } catch (SQLException e) {
        log.error("Error creating demo entries.", e);
        throw e;
    }
}

From source file:ca.wumbo.wdl.database.LogEventSubmitter.java

/**
 * Adds all the data to insert into the database into the statement in a
 * batch format such that at the end of everything, the commands can all
 * be sent as one.//from  w  ww  . j  a  va2  s  .c  om
 * 
 * @param rp
 *       The stat round parser to extract events from.
 * 
 * @param idToPlayerMap
 *       A map of id to player names that will be used for matching log
 *       names to a player. 
 * 
 * @param roundId
 *       The round ID of the event data.
 * 
 * @param redTeamId
 *       The ID of the red team.
 * 
 * @throws SQLException
 *       If there is any exception calling the query or the database fails
 *       to create the necessary rows.
 */
private void pushEventsBatch(RoundParser rp, BiMap<Integer, String> idToPlayerMap, int roundId, int redTeamId,
        int blueTeamId) throws SQLException {
    assert rp != null;
    assert idToPlayerMap != null;
    assert idToPlayerMap.size() > 0;
    assert roundId >= 0;
    assert redTeamId >= 0;
    assert blueTeamId >= 0;

    try (Statement stmt = connection.createStatement()) {
        int eventLogId = -1;

        // Put in the header and remember the event log ID.
        String query = rp.getHeaderData().getSqlInsertionQuery("wdl", "event_logs", roundId, redTeamId,
                blueTeamId);
        log.trace(">>> {}", query);
        stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
        ResultSet rs = stmt.getGeneratedKeys();
        if (!rs.next()) {
            throw new SQLException(
                    "Unexpected end of result set, should have gotten back the key for the event log ID.");
        }
        eventLogId = rs.getInt(1);
        log.trace("Event log ID retrieved: {}", eventLogId);
        if (eventLogId == -1) {
            throw new SQLException("Commit did not yield an event log.");
        }

        // Everything from now on in can go into a single batch command.
        // Put in the players.
        log.debug("Inserting players into event player table.");
        BiMap<String, Integer> playerToIdMap = idToPlayerMap.inverse();
        log.trace("PlayerToIdMap = {}", playerToIdMap.toString());
        for (Player player : rp.getPlayers()) {
            // Getting the player ID shouldn't fail because we've checked
            // previously to make sure the player name and ID are valid.
            String playerLogName = player.getName();
            int playerId = playerToIdMap.get(playerLogName);
            int colorNumber = player.getTeam().ordinal();
            String insertQuery = String.format("INSERT INTO `%s`.`%s`(%s) VALUES(%d, %d, \"%s\", %d)", "wdl",
                    "event_players", "fk_event_log_id, fk_player_id, player_log_name, color_number", eventLogId,
                    playerId, playerLogName, colorNumber);
            log.trace(">>> {}", insertQuery);
            stmt.addBatch(insertQuery);
        }
        log.debug("Committing player queries...");
        stmt.executeBatch();
        log.debug("Committed player batch events.");

        // Put in the events.
        log.debug("Inserting events into event table.");
        for (Event e : rp.getEvents()) {
            String queryStr = e.getSqlInsertionQuery("wdl", "events", idToPlayerMap.inverse(), eventLogId);
            log.trace(">>> {}", queryStr);
            stmt.addBatch(queryStr);
        }

        // Everything is in, deploy it now.
        log.debug("Committing event queries...");
        stmt.executeBatch();
        log.debug("All event query events done.");
    }
}

From source file:uk.ac.ebi.mdk.ui.render.reaction.ReactionRenderer.java

/**
 * Draws a transport uniporter reaction//  w w  w  . j  a  v a  2 s  .  c o m
 *
 * @param rxn
 *
 * @return
 */
public ImageIcon renderUniporterReaction(AbstractReaction<MetabolicParticipantImplementation> rxn) {

    BiMap<CompartmentalisedParticipant<Metabolite, ?, Compartment>, CompartmentalisedParticipant<Metabolite, ?, Compartment>> mapping = TransportReactionUtil
            .getMappings(rxn);

    CompartmentalisedParticipant<Metabolite, ?, Compartment> left = mapping.keySet().iterator().next();
    CompartmentalisedParticipant<Metabolite, ?, Compartment> right = mapping.get(left);

    int n = mapping.size();

    int width = (n * 128) + (128); // arrow
    int height = 128;

    BufferedImage base = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
    Graphics2D g2 = (Graphics2D) base.getGraphics();
    g2.setColor(Color.WHITE);
    g2.fill(new Rectangle(0, 0, width, height));

    drawMolecule(g2, new Rectangle(0, 0, 128, 128), (MetabolicParticipantImplementation) left);

    drawCompartmentSeperator(g2, new Rectangle(128, 0, 128, 128));

    drawArrow(g2, new Rectangle(128, 0, 128, 128), (Direction) rxn.getDirection(), 1.25f);

    drawMolecule(g2, new Rectangle(256, 0, 128, 128), (MetabolicParticipantImplementation) right);

    g2.dispose();

    return new ImageIcon(base);

}

From source file:ca.wumbo.wdl.database.LogEventSubmitter.java

/**
 * Takes a parser log and pushes all the data into the database.
 * /*from  w ww. java2 s.  com*/
 * @param dbGameId
 *       The ID of the primary key for the game table.
 * 
 * @param parser
 *       The parser to push the events in with.
 * 
 * @param idToPlayerMap
 *       A bi-directional map of ID to players.
 * 
 * @param redTeamId
 *       The team ID in the database for the red team.
 * 
 * @param blueTeamId
 *       The team ID in the database for the blue team.
 * 
 * @throws MissingGameInDatabaseException
 *       If the game is missing from the database.
 * 
 * @throws SQLException
 *       If any exceptions occur while pushing data to the database, or this
 *       is called on a closed connection.
 * 
 * @throws NullPointerException
 *       If any argument is null.
 * 
 * @throws IllegalArgumentException
 *       If the database game id is negative, or the map is empty, or if the
 *       team numbers are negative.
 */
public void pushEventsToDatabase(int dbGameId, Parser parser, BiMap<Integer, String> idToPlayerMap,
        int redTeamId, int blueTeamId) throws SQLException {
    checkArgument(dbGameId >= 0);
    checkNotNull(parser);
    checkNotNull(idToPlayerMap);
    checkArgument(idToPlayerMap.size() > 0);
    checkArgument(redTeamId >= 0);
    checkArgument(blueTeamId >= 0);
    log.info("Pushing game to database for id {}.", dbGameId);

    // Remember this location before the transaction.
    log.trace("Creating savepoint.");
    Savepoint savePoint = connection.setSavepoint(TRANSACTION_SAVEPOINT);

    // We have to make sure we are putting in valid foreign keys.
    log.debug("Checking database values for game id {}.", dbGameId);
    try {
        checkDatabaseValues(dbGameId, idToPlayerMap);
    } catch (SQLException | MissingGameInDatabaseException e) {
        log.error("Error checking database values.", e);
        connection.rollback(savePoint);
        throw e;
    }

    // Create a demo entry if one does not exist for the players.
    log.debug("Creating demos if they are not present in the database.");
    try {
        createDemoEntriesIfNotPresent(dbGameId, idToPlayerMap);
    } catch (SQLException e) {
        log.error("Error creating demos.", e);
        connection.rollback(savePoint);
        throw e;
    }

    // Now that the integrity is verified, we need to create the rounds and
    // remember those IDs for committing each round. This should have been
    // cleaned up if the rounds were removed, so it will error if there are
    // any rounds detected that should not be there.
    ArrayList<Integer> roundIds = null;
    int numRounds = parser.getRoundParsers().size();
    try {
        roundIds = createRoundsOrError(dbGameId, parser, numRounds);
        log.trace("Round IDs: {}", roundIds.toString());
    } catch (SQLException e) {
        log.error("Error creating demos.", e);
        connection.rollback(savePoint);
        throw e;
    }

    // Go through the information and put in the many statements to push.
    try {
        for (int roundIndex = 0; roundIndex < numRounds; roundIndex++) {
            RoundParser rp = parser.getRoundParsers().get(roundIndex);
            int roundId = roundIds.get(roundIndex);
            log.trace("Committing round {} from parser to event database.", roundId);
            pushEventsBatch(rp, idToPlayerMap, roundId, redTeamId, blueTeamId);
        }
    } catch (SQLException e) {
        log.error("Error adding events to the database when trying to push.", e);
        log.error("Likely have malformed round columns that need to manually be deleted.");
        connection.rollback(savePoint);
        throw e;
    }

    log.info("Events pushed to database successfully.");
}

From source file:seeit3d.base.ui.ide.view.MappingViewComposite.java

private void updateComponents(List<Container> containers) {
    cleanComposites();// w w w  .  jav  a  2 s  .  c o  m

    scrollerComposite = new ScrolledComposite(this,
            SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.DOUBLE_BUFFERED);
    rootComposite = new Composite(scrollerComposite, SWT.DOUBLE_BUFFERED);
    scrollerComposite.setContent(rootComposite);

    GridLayout mappingLayout = new GridLayout(2 + VisualProperty.values().length, true);
    rootComposite.setLayout(mappingLayout);

    updateCurrentGranularityLevelFromContainers(containers);

    List<MetricCalculator> metricsInformation = buildMetricsInformation(containers);
    BiMap<MetricCalculator, VisualProperty> currentMapping = buildCurrentMapping(containers);

    removeAlreadyMappedMetrics(metricsInformation, currentMapping);
    updateCurrentMappingAndVisualProperties(containers, currentMapping);
    updateColorScales();
    updateRelationshipsGenerator(containers);
    updateMetricsFromContainers(containers, metricsInformation, currentMapping.size());

    rootComposite.pack(true);
    this.layout(true, true);

}

From source file:ca.wumbo.wdl.parser.events.Event.java

/**
 * Gets the insertion query statement for this event.
 * /*  w  w w  .j  a  v a 2s .co m*/
 * @param database
 *       The database this belongs to. This should not be empty.
 * 
 * @param table
 *       The table for this event.
 * 
 * @param nameToPlayerIdMap
 *       The name to player ID map.
 * @param eventLogId 
 * 
 * @return
 *       A query statement that can be issued to the database.
 * 
 * @throws NullPointerException
 *       If any argument is null.
 * 
 * @throws IllegalArgumentException
 *       If any string or table has zero characters/elements, or the log id
 *       is negative.
 * 
 * @throws RuntimeException
 *       If neither an activator nor target ID can be found (both parts
 *       of the query for the ID's would be 'NULL').
 */
public String getSqlInsertionQuery(String database, String table, BiMap<String, Integer> nameToPlayerIdMap,
        int eventLogId) {
    checkNotNull(database);
    checkNotNull(table);
    checkNotNull(nameToPlayerIdMap);
    checkArgument(database.length() > 0);
    checkArgument(table.length() > 0);
    checkArgument(nameToPlayerIdMap.size() > 0);
    checkArgument(eventLogId >= 0);

    String tblArgs = "fk_event_log_id, type, nfk_activator_player_id, nfk_target_player_id, "
            + "gametic, activator_x, activator_y, activator_z, "
            + "target_x, target_y, target_z, arg0, arg1, arg2";
    String valueArgs = "%d, %d, %s, %s, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d";
    String activatorIdOrNullSqlStr = activator != null && nameToPlayerIdMap.containsKey(activator.getName())
            ? Integer.toString(nameToPlayerIdMap.get(activator.getName()))
            : "NULL";
    String targetIdOrNullSqlStr = target.isPresent() && nameToPlayerIdMap.containsKey(target.get().getName())
            ? Integer.toString(nameToPlayerIdMap.get(target.get().getName()))
            : "NULL";

    // If both are null, something is critically wrong.
    if (activatorIdOrNullSqlStr.equals("NULL") && targetIdOrNullSqlStr.equals("NULL")) {
        throw new RuntimeException(
                "Both activator and target are 'NULL', malformed event or corrupt name to ID map.");
    }

    return String.format("INSERT INTO `%s`.`%s`(%s) VALUES(" + valueArgs + ")", database, table, tblArgs,
            eventLogId, getEventTypeNumber(), activatorIdOrNullSqlStr, targetIdOrNullSqlStr, getGametic(),
            getActivatorX(), getActivatorY(), getActivatorZ(), getTargetX(), getTargetY(), getTargetZ(),
            getArg0(), getArg1(), getArg2());
}

From source file:io.prestosql.sql.planner.NodePartitioningManager.java

public NodePartitionMap getNodePartitioningMap(Session session, PartitioningHandle partitioningHandle) {
    requireNonNull(session, "session is null");
    requireNonNull(partitioningHandle, "partitioningHandle is null");

    if (partitioningHandle.getConnectorHandle() instanceof SystemPartitioningHandle) {
        return ((SystemPartitioningHandle) partitioningHandle.getConnectorHandle()).getNodePartitionMap(session,
                nodeScheduler);/*from  www.j  a  v a  2s. c  o m*/
    }

    ConnectorId connectorId = partitioningHandle.getConnectorId()
            .orElseThrow(() -> new IllegalArgumentException(
                    "No connector ID for partitioning handle: " + partitioningHandle));
    ConnectorNodePartitioningProvider partitioningProvider = partitioningProviders.get(connectorId);
    checkArgument(partitioningProvider != null, "No partitioning provider for connector %s", connectorId);

    ConnectorBucketNodeMap connectorBucketNodeMap = getConnectorBucketNodeMap(session, partitioningHandle);
    // safety check for crazy partitioning
    checkArgument(connectorBucketNodeMap.getBucketCount() < 1_000_000, "Too many buckets in partitioning: %s",
            connectorBucketNodeMap.getBucketCount());

    List<Node> bucketToNode;
    if (connectorBucketNodeMap.hasFixedMapping()) {
        bucketToNode = connectorBucketNodeMap.getFixedMapping();
    } else {
        bucketToNode = createArbitraryBucketToNode(nodeScheduler.createNodeSelector(connectorId).allNodes(),
                connectorBucketNodeMap.getBucketCount());
    }

    int[] bucketToPartition = new int[connectorBucketNodeMap.getBucketCount()];
    BiMap<Node, Integer> nodeToPartition = HashBiMap.create();
    int nextPartitionId = 0;
    for (int bucket = 0; bucket < bucketToNode.size(); bucket++) {
        Node node = bucketToNode.get(bucket);
        Integer partitionId = nodeToPartition.get(node);
        if (partitionId == null) {
            partitionId = nextPartitionId++;
            nodeToPartition.put(node, partitionId);
        }
        bucketToPartition[bucket] = partitionId;
    }

    List<Node> partitionToNode = IntStream.range(0, nodeToPartition.size())
            .mapToObj(partitionId -> nodeToPartition.inverse().get(partitionId)).collect(toImmutableList());

    return new NodePartitionMap(partitionToNode, bucketToPartition,
            getSplitToBucket(session, partitioningHandle));
}

From source file:com.torodb.torod.db.postgresql.query.QueryEvaluator.java

@Nonnull
private Map<Integer, DatabaseQuery> createDatabaseQueryByStructure(@Nullable QueryCriteria criteria,
        DSLContext dsl) {//from   w  ww.j a  va 2s  .co m

    Map<Integer, DatabaseQuery> result;

    if (criteria == null) {
        BiMap<Integer, DocStructure> allStructures = colSchema.getStructuresCache().getAllStructures();
        result = Maps.newHashMapWithExpectedSize(allStructures.size());

        for (Integer sid : colSchema.getStructuresCache().getAllStructures().keySet()) {
            result.put(sid, SelectAllDatabaseQuery.getInstance());
        }
    } else {
        Multimap<Integer, QueryCriteria> candidateStructures = QueryStructureFilter.filterStructures(colSchema,
                criteria);

        if (candidateStructures.isEmpty()) {
            result = Collections.emptyMap();
        } else {
            result = Maps.newHashMapWithExpectedSize(candidateStructures.size());

            for (Map.Entry<Integer, QueryCriteria> entry : candidateStructures.entries()) {
                Integer sid = entry.getKey();
                DocStructure rootStructure = colSchema.getStructuresCache().getStructure(sid);

                DatabaseQuery databaseQuery = createDatabaseQuery(entry.getValue(), sid, rootStructure, dsl);
                if (!(databaseQuery instanceof FalseDatabaseQuery)) {
                    result.put(sid, databaseQuery);
                }
            }
        }
    }

    return result;
}