Example usage for org.apache.commons.collections Bag getCount

List of usage examples for org.apache.commons.collections Bag getCount

Introduction

In this page you can find the example usage for org.apache.commons.collections Bag getCount.

Prototype

int getCount(Object object);

Source Link

Document

Returns the number of occurrences (cardinality) of the given object currently in the bag.

Usage

From source file:annis.sqlgen.TableAccessStrategy.java

public String aliasedTable(String table, int count) {
    if (node != null) {
        // sanity checks
        //         if (table.equals(NODE_ANNOTATION_TABLE) && count > node.getNodeAnnotations().size())
        //            throw new IllegalArgumentException("access to node annotation table out of range: " + count);
        if (table.equals(EDGE_ANNOTATION_TABLE) && count > node.getEdgeAnnotations().size())
            throw new IllegalArgumentException("access to edge annotation table out of range: " + count);
        if (table.equals(NODE_TABLE) && count > 1)
            throw new IllegalArgumentException("access to struct table out of range: " + count);
        if (table.equals(RANK_TABLE) && count > 1)
            throw new IllegalArgumentException("access to rank table out of range: " + count);

        // offset table count for edge annotations if node and edge annotations are the same table
        if (table.equals(EDGE_ANNOTATION_TABLE) && isMaterialized(EDGE_ANNOTATION_TABLE, NODE_ANNOTATION_TABLE))
            count = count + node.getNodeAnnotations().size() - 1;
    }//  w  w  w. j av a  2s  . c om

    if (count == 0) {
        count = 1;
    }

    // compute table counts
    Bag tables = computeSourceTables();

    String aliasedName = tableName(table);
    String aliasCount = node != null ? String.valueOf(node.getId()) : "";
    String countSuffix = tables.getCount(aliasedName) > 1 ? "_" + count : "";

    return aliasedName + aliasCount + countSuffix;
}

From source file:com.discursive.jccook.collections.bag.BagExample.java

private void printAlbums(Bag albumBag) {
    Set albums = albumBag.uniqueSet();
    Iterator albumIterator = albums.iterator();
    while (albumIterator.hasNext()) {
        Album album = (Album) albumIterator.next();
        NumberFormat format = NumberFormat.getInstance();
        format.setMinimumIntegerDigits(3);
        format.setMaximumFractionDigits(0);
        System.out.println("\t" + format.format(albumBag.getCount(album)) + " - " + album.getBand());
    }//www .j  a v a 2  s.  c om
}

From source file:annis.sqlgen.TestTableAccessStrategy.java

private Matcher<Bag> hasTables(final Map<String, Integer> expectedTables) {
    return new TypeSafeMatcher<Bag>() {

        @Override/*from w  w  w.j  av a2 s  . com*/
        public boolean matchesSafely(Bag item) {
            for (String table : expectedTables.keySet()) {
                if (item.getCount(table) != expectedTables.get(table))
                    return false;
            }
            return true;
        }

        public void describeTo(Description description) {
            description.appendValue(expectedTables);
        }

    };
}

From source file:com.otiliouine.flera.analyzer.SuccessionBasedDictionaryAnalyzer.java

public char getMostSucceeds(char precedent) {
    Bag<Succession> successionBag = successionBags.get(precedent);
    if (successionBag == null || successionBag.isEmpty()) {
        throw new RuntimeException("No successors found for the character '" + precedent + "'");
    }//from w  w  w . ja  v  a 2s .  c o  m
    Character mostSucceeds = null;
    int nbrSuccessions = 0;
    for (Succession current : successionBag.uniqueSet()) {
        int currentCount = successionBag.getCount(current);
        if (currentCount > nbrSuccessions) {
            nbrSuccessions = currentCount;
            mostSucceeds = current.successor;
        }
    }
    return mostSucceeds;
}

From source file:com.pureinfo.tgirls.utils.counts.CountsJob.java

public void execute() {
    logger.debug("to process counts.");

    CountsProcess cache = CountsProcess.getInstance();
    Bag bag = new HashBag();
    synchronized (cache) {
        bag.addAll(cache.getBag());/*from  w ww.j a  v a  2s  .c  om*/
        cache.clear();
    }

    ISession session = null;
    try {
        session = LocalContextHelper.currentSession();
        Set<String> bagKeySet = bag.uniqueSet();
        for (Iterator<String> iterator = bagKeySet.iterator(); iterator.hasNext();) {
            String type = null;
            try {
                type = iterator.next();
                Counts counts = new Counts();
                counts.setType(type);
                counts.setCounts(bag.getCount(type));
                counts.setCreateTime();
                session.save(counts);
            } catch (Exception e) {
                logger.error("error when save counts:" + type, e);
            }

        }

    } catch (Exception e) {
        logger.error("error occur.", e);
    } finally {
        bag.clear();
        if (session != null)
            try {
                session.close();
            } catch (Exception e) {
                logger.error("error when close session.", e);
            }
    }

}

From source file:annis.sqlgen.TableAccessStrategy.java

protected Bag computeSourceTables() {
    Bag tables = new HashBag();

    // hack to support table selections for ANNOTATE query
    if (node == null) {
        String[] tableNames = { NODE_TABLE, RANK_TABLE, COMPONENT_TABLE, NODE_ANNOTATION_TABLE,
                EDGE_ANNOTATION_TABLE };
        for (String table : tableNames)
            tables.add(table);/*from ww w. j a v  a  2  s. c o  m*/
        return tables;
    }

    tables.add(tableName(NODE_ANNOTATION_TABLE), node.getNodeAnnotations().size());
    if (node.getNodeAnnotations().isEmpty() && node.getNodeAnnotations().size() > 0)
        tables.add(tableName(NODE_ANNOTATION_TABLE));

    tables.add(tableName(EDGE_ANNOTATION_TABLE), node.getEdgeAnnotations().size());

    if (tables.getCount(tableName(RANK_TABLE)) == 0 && usesRankTable())
        tables.add(tableName(RANK_TABLE));
    if (tables.getCount(tableName(COMPONENT_TABLE)) == 0 && usesRankTable())
        tables.add(tableName(COMPONENT_TABLE));

    if (tables.getCount(tableName(NODE_TABLE)) == 0)
        tables.add(tableName(NODE_TABLE));

    return tables;
}

From source file:io.hops.hopsworks.common.security.CertificateMaterializer.java

private boolean removeLocal(MaterialKey key, String materializationDirectory) {
    Bag materialBag = materializedCerts.get(key);
    if (materialBag != null) {
        materialBag.remove(materializationDirectory, 1);
        if (materialBag.getCount(materializationDirectory) <= 0) {
            scheduleFileRemover(key, materializationDirectory);
        }/* w ww.  jav a 2s. c  om*/
        return true;
    }
    return false;
}

From source file:io.hops.hopsworks.common.security.CertificateMaterializer.java

/**
 * Returns the state of the CertificateMaterializer service
 * The state includes://from   w ww.jav a2 s  .com
 * 1) Identifier of material, materialization directory and number of references for the certificates in the local
 * filesystem
 *
 * 2) Identifier of material, materialization directory and number of references for the certificates in the remote
 * filesystem (HDFS)
 *
 * 3) Identifier of the material that are scheduled to be removed from the local filesystem
 *
 * @return The state of the CertificateMaterializer at that point of time
 */
@SuppressWarnings("unchecked")
public MaterializerState<Map<String, Map<String, Integer>>, Map<String, Map<String, Integer>>, Map<String, Set<String>>, Map<String, Boolean>> getState() {
    MaterializerState<Map<MaterialKey, Bag>, List<RemoteMaterialReferences>, Map<MaterialKey, Map<String, Runnable>>, Map<MaterialKey, ReentrantReadWriteLock>> state = getImmutableState();

    Map<MaterialKey, Bag> localMaterialState = state.getLocalMaterial();

    // <Username, <MaterialPath, NumberOfReferences>>
    Map<String, Map<String, Integer>> simpleLocalMaterialState = new HashMap<>(localMaterialState.size());

    for (Map.Entry<MaterialKey, Bag> entry : localMaterialState.entrySet()) {
        String username = entry.getKey().getExtendedUsername();
        Map<String, Integer> referencesMap = new HashMap<>();
        Bag pathsBag = entry.getValue();
        Set<String> paths = pathsBag.uniqueSet();
        for (String path : paths) {
            referencesMap.put(path, pathsBag.getCount(path));
        }
        simpleLocalMaterialState.put(username, referencesMap);
    }

    List<RemoteMaterialReferences> remoteMaterialState = state.getRemoteMaterial();
    // <Username, <MaterialPath, NumberOfReferences>>
    Map<String, Map<String, Integer>> simpleRemoteMaterialState = new HashMap<>(remoteMaterialState.size());

    for (RemoteMaterialReferences ref : remoteMaterialState) {
        String username = ref.getIdentifier().getUsername();
        Map<String, Integer> references = simpleRemoteMaterialState.get(username);
        if (references == null) {
            references = new HashMap<>();
            references.put(ref.getIdentifier().getPath(), ref.getReferences());
            simpleRemoteMaterialState.put(username, references);
        } else {
            references.put(ref.getIdentifier().getPath(), ref.getReferences());
        }
    }

    Map<MaterialKey, Map<String, Runnable>> fileRemovals = state.getScheduledRemovals();
    // <Username, [MaterialPath]>
    Map<String, Set<String>> simpleScheduledRemovals = new HashMap<>();

    for (Map.Entry<MaterialKey, Map<String, Runnable>> entry : fileRemovals.entrySet()) {
        String username = entry.getKey().getExtendedUsername();
        simpleScheduledRemovals.put(username, entry.getValue().keySet());
    }

    Map<MaterialKey, ReentrantReadWriteLock> materialKeyLocks = state.getMaterialKeyLocks();
    // Username, Locked
    Map<String, Boolean> flatMaterialKeyLocks = new HashMap<>(materialKeyLocks.size());
    for (Map.Entry<MaterialKey, ReentrantReadWriteLock> lock : materialKeyLocks.entrySet()) {
        flatMaterialKeyLocks.put(lock.getKey().getExtendedUsername(), lock.getValue().isWriteLocked());
    }

    return new MaterializerState<>(simpleLocalMaterialState, simpleRemoteMaterialState, simpleScheduledRemovals,
            flatMaterialKeyLocks);
}

From source file:io.hops.hopsworks.common.security.CertificateMaterializer.java

private void materializeLocalInternal(MaterialKey key, String localDirectory) throws IOException {
    Bag materializedDirs = materializedCerts.get(key);
    if (materializedDirs == null) {
        // Check to see if there is any scheduled removal
        // If there is try to cancel it
        // If not possible materialize

        boolean shouldContinue = checkWithScheduledRemovalsLocal(key, localDirectory);
        if (shouldContinue) {
            // First time it was requested to be materialized
            // 1. Get certs fro DB
            CryptoMaterial material = getMaterialFromDatabase(key);
            // 2. Add them to L1 Cache
            materialCache.put(key, material);
            // 3. Write them to local FS
            flushToLocalFileSystem(key, material, localDirectory);
            // 4. Add Directory to Bag and then to materializedCerts
            Bag materialBag = new HashBag();
            String targetDir = localDirectory != null ? localDirectory : transientDir;
            materialBag.add(targetDir, 1);
            materializedCerts.put(key, materialBag);
        }//  w  w  w . j  a v  a2  s. c om
    } else {
        int cardinality = materializedDirs.getCount(localDirectory);
        if (cardinality == 0) {
            // Check to see if there is any scheduled removal
            // If there is try to cancel it
            // If not possible materialize
            boolean shouldContinue = checkWithScheduledRemovalsLocal(key, localDirectory);

            if (shouldContinue) {
                // First time for this directory, but not for the material in general
                // 1. Get byte material from L1 Cache. If not there, something went wrong
                // but fetch them from DB anyways
                CryptoMaterial material = materialCache.get(key);
                if (material == null) {
                    material = getMaterialFromDatabase(key);
                }
                // 2. Flush buffers to local filesystem
                flushToLocalFileSystem(key, material, localDirectory);
                // 3. Increment cardinality
                materializedDirs.add(localDirectory, 1);
            }
        } else {
            // Materialization in this Directory has already been requested
            // 1. Increment cardinality for this Material and Directory
            materializedDirs.add(localDirectory, 1);
        }
    }
}

From source file:org.apache.maven.shared.jar.identification.exposers.TimestampExposer.java

public void expose(JarIdentification identification, JarAnalyzer jarAnalyzer) {
    List entries = jarAnalyzer.getEntries();
    SimpleDateFormat tsformat = new SimpleDateFormat("yyyyMMdd", Locale.US); //$NON-NLS-1$
    Bag timestamps = new HashBag();
    Iterator it = entries.iterator();
    while (it.hasNext()) {
        JarEntry entry = (JarEntry) it.next();
        long time = entry.getTime();
        String timestamp = tsformat.format(new Date(time));
        timestamps.add(timestamp);/*  w w  w  . jav a2 s .  co  m*/
    }

    it = timestamps.iterator();
    String ts = "";
    int tsmax = 0;
    while (it.hasNext()) {
        String timestamp = (String) it.next();
        int count = timestamps.getCount(timestamp);
        if (count > tsmax) {
            ts = timestamp;
            tsmax = count;
        }
    }

    if (StringUtils.isNotEmpty(ts)) {
        identification.addVersion(ts);
    }
}