Example usage for java.util HashMap size

List of usage examples for java.util HashMap size

Introduction

In this page you can find the example usage for java.util HashMap size.

Prototype

int size

To view the source code for java.util HashMap size.

Click Source Link

Document

The number of key-value mappings contained in this map.

Usage

From source file:com.antelink.sourcesquare.client.scan.SourceSquareFSWalker.java

public synchronized void queryFiles(TreeSet<File> fileSet) throws InterruptedException {
    HashMap<String, String> toAnalyze = new HashMap<String, String>();
    Iterator<File> iterator = fileSet.iterator();
    logger.debug(fileSet.size() + " files to analyze");
    long count = 0;
    long timer = System.currentTimeMillis();
    while (iterator.hasNext()) {

        File file = iterator.next();
        logger.trace("adding analyze file to the pool: " + file.getAbsolutePath());
        try {//  w  ww  .ja  v  a2s  .c o m
            String sha1 = FileAnalyzer.calculateHash("SHA-1", file);
            toAnalyze.put(file.getAbsolutePath(), sha1);
            count++;
        } catch (Exception e) {
            logger.error("skipping files " + file, e);
        }

        if (toAnalyze.size() == this.filePerQuery || System.currentTimeMillis() - timer > COMPUTE_WAIT_TIME) {
            // dispatch analysis
            timer = System.currentTimeMillis();
            analyzeMap(toAnalyze);
            this.filePerQuery = Math.min(MAX_FILE_PER_QUERY, this.filePerQuery * 2);
            logger.trace("new counter: " + count);

        }
    }
    analyzeMap(toAnalyze);

    while (!allProcessDone()) {
        synchronized (this.lock) {
            this.lock.wait();
        }

    }
    this.eventBus.fireEvent(new ScanCompleteEvent(this.levels));

    logger.info("Analysis done " + count);
}

From source file:de.ingrid.iplug.scheduler.FileJobStore.java

public boolean removeJob(SchedulingContext ctxt, String jobName, String groupName)
        throws JobPersistenceException {
    JobDetail job = (JobDetail) this.fJobsByName.get(getFullName(groupName, jobName));
    if (job == null) {
        return false;
    }// w w w.j a  va  2s  .  c o m

    Trigger[] triggers = getTriggersForJob(ctxt, jobName, groupName);
    for (int i = 0; i < triggers.length; i++) {
        removeTrigger(ctxt, triggers[i].getName(), triggers[i].getGroup());
    }

    synchronized (this.fJobsByName) {
        HashMap groupMap = (HashMap) this.fJobsByGroup.get(groupName);
        if (groupMap != null) {
            groupMap.remove(jobName);
            if (groupMap.size() == 0)
                this.fJobsByGroup.remove(groupName);
        }
        this.fJobsByName.remove(job.getFullName());
        this.fBlockedJobs.remove(job);
        this.fSerializer.saveJobs(this.fJobsByName);
    }

    return true;
}

From source file:com.advdb.footballclub.FootBallClub.java

private void createFactMatch(Session session) {
    Transaction transaction = null;// ww  w .  j  ava  2 s . c  o m
    try {
        System.out.println("start createFactMatch.");
        transaction = session.beginTransaction();
        String hqlDC = "from DimCompetition dc";
        List result = session.createQuery(hqlDC).list();
        result.forEach((object) -> {

            DimCompetition dimCompetition = (DimCompetition) object;
            int startYear = dimCompetition.getSeasonStartYear();
            int endYear = dimCompetition.getSeasonEndYear();
            GregorianCalendar cal = randomYear(startYear, endYear);
            //                createDate(session, gregorianCalendar);
            if (dimCompetition.getCompetiotionName().equals(COMPETITION_NAME_ARR[0])
                    || dimCompetition.getCompetiotionName().equals(COMPETITION_NAME_ARR[1])) {

                int times = randomWithRange(1, 7);
                //Random opponent
                String hqlDO = "from DimOpponent do";
                List resultDO = session.createQuery(hqlDO).list();
                HashMap<Integer, Integer> opponentMap = new HashMap<Integer, Integer>();
                int opponentIndex;
                do {

                    opponentIndex = randBetween(0, resultDO.size());
                    if (!opponentMap.containsKey(opponentIndex)) {
                        opponentMap.put(opponentIndex, opponentIndex);
                        generateFactMatch(opponentIndex, cal, dimCompetition.getCompetitionKy(), session);
                        //Random tactic
                        //Random player

                    }
                } while (opponentMap.size() != times);

            } else if (dimCompetition.getCompetiotionName().equals(COMPETITION_NAME_ARR[2])
                    || dimCompetition.getCompetiotionName().equals(COMPETITION_NAME_ARR[3])) {

                //Random opponent
                String hqlDO = "from DimOpponent do";
                List resultDO = session.createQuery(hqlDO).list();
                HashMap<Integer, Integer> opponentMap = new HashMap<Integer, Integer>();
                int opponentIndex;
                do {
                    opponentIndex = randBetween(0, resultDO.size());
                    if (!opponentMap.containsKey(opponentIndex)) {
                        opponentMap.put(opponentIndex, opponentIndex);
                        generateFactMatch(opponentIndex, cal, dimCompetition.getCompetitionKy(), session);

                    }
                } while (opponentMap.size() != 38);

            } else {

            }

        });
        session.flush();
        session.clear();
        //            }
        transaction.commit();
        System.out.println("finish createFactMatch.");
    } catch (HibernateException e) {
        if (transaction != null) {
            transaction.rollback();
        }
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:de.ingrid.iplug.scheduler.FileJobStore.java

public boolean removeTrigger(SchedulingContext ctxt, String triggerName, String groupName)
        throws JobPersistenceException {
    synchronized (this.fTriggersByName) {
        // remove from triggers map
        Trigger trigger = (Trigger) this.fTriggersByName.remove(getFullName(groupName, triggerName));
        if (trigger == null) {
            return false;
        }/*from w w  w  .j a v  a 2 s.  c o  m*/
        this.fSerializer.saveTriggers(this.fTriggersByName);

        // remove from triggers by group
        HashMap grpMap = (HashMap) this.fTriggersByGroup.get(groupName);
        if (grpMap != null) {
            grpMap.remove(triggerName);
            if (grpMap.size() == 0)
                this.fTriggersByGroup.remove(groupName);
        }
        this.fOrderedTriggers.remove(trigger);
        JobDetail jobDetail = retrieveJob(ctxt, trigger.getJobName(), trigger.getJobGroup());

        // remove state
        setTriggerState(ctxt, trigger, Trigger.STATE_NONE);

        if (!jobDetail.isDurable()
                && getTriggersForJob(ctxt, jobDetail.getName(), jobDetail.getGroup()).length == 0) {
            removeJob(ctxt, jobDetail.getName(), jobDetail.getGroup());
        }
    }

    return true;
}

From source file:GitBackend.GitAPI.java

private String getMostRecentCommit(HashMap<String, DateTime> commitMap, DateTime execDate) {
    Iterator it = commitMap.entrySet().iterator();
    Map.Entry<String, DateTime> mostRecentCommit = null;
    System.out.println("Number of commits: " + commitMap.size());
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        DateTime currentCommitDate = (DateTime) pair.getValue();

        if (mostRecentCommit == null && ((DateTime) pair.getValue()).isBefore(execDate)) {
            System.out.println("most recent war null bei vergleich");
            mostRecentCommit = pair;//from   w w  w . j ava2 s .co m
        } else if (currentCommitDate.isBefore(execDate)) {
            System.out.println("Current date is before exec");
            if (currentCommitDate.isAfter(mostRecentCommit.getValue())) {
                System.out.println("Current date is before exec and after the most recent one");
                mostRecentCommit = pair;
            }
        }

    }

    System.out.println(
            "Current most recent:  " + mostRecentCommit.getKey() + " = " + mostRecentCommit.getValue());
    return mostRecentCommit.getKey();

}

From source file:com.logsniffer.event.h2.H2SnifferPersistence.java

@Override
public Map<Log, IncrementData> getIncrementDataByLog(final Sniffer sniffer, final LogSource<?> source)
        throws IOException {
    final List<Log> logs = source.getLogs();
    if (logs.size() > 0) {
        final HashMap<Log, IncrementData> incs = new HashMap<Log, IncrementData>();
        final HashMap<String, Log> logMapping = new HashMap<String, Log>();
        for (final Log log : logs) {
            logMapping.put(log.getPath(), log);
        }/*from w  w  w .  jav a2 s  .  c  o  m*/
        jdbcTemplate.query(
                "SELECT NEXT_POINTER, DATA, LOG FROM SNIFFERS_SCANNER_IDATA WHERE SNIFFER=? AND SOURCE=? AND LOG IN ("
                        + StringUtils.repeat("?", ",", logs.size()) + ") ORDER BY LOG",
                ArrayUtils.addAll(new Object[] { sniffer.getId(), source.getId() },
                        logMapping.keySet().toArray(new Object[logMapping.size()])),
                new RowCallbackHandler() {
                    @Override
                    public void processRow(final ResultSet rs) throws SQLException {
                        final String logPath = rs.getString("LOG");
                        final Log log = logMapping.get(logPath);
                        if (log != null) {
                            final IncrementData data = new IncrementData();
                            data.setData(JSONObject.fromObject(rs.getString("DATA")));
                            try {
                                final String jsonStr = rs.getString("NEXT_POINTER");
                                if (StringUtils.isNotBlank(jsonStr)) {
                                    data.setNextOffset(source.getLogAccess(log).getFromJSON(jsonStr));
                                }
                                incs.put(log, data);
                            } catch (final IOException e) {
                                throw new SQLException("Failed to construct pointer in log: " + log, e);
                            }
                        } else {
                            logger.error("Didn't find log '{}' for selected incrementdata", logPath);
                        }
                    }
                });
        // Create empty entries for not yet persisted
        for (final Log log : logMapping.values()) {
            if (!incs.containsKey(log)) {
                incs.put(log, new IncrementData());
            }
        }
        return incs;
    } else {
        return Collections.emptyMap();
    }
}

From source file:com.glluch.profilesparser.ProfileHtmlReader.java

/**
 * Read an parse a hmtl file which contains a ICT profile. Some parts are extracted 
 * with Jsop and some others from a plain text.
 * @param filename The html file where the profile is stored.
 * @return An ICTProfile read from the html file.
 *//*from  w w w . ja v  a 2 s  .c om*/
@Override
public ICTProfile reader(String filename) {
    ICTProfile res = new ICTProfile();

    try {
        init(filename);

        Element ts = doc.select("h2").first();
        res.setTitle(ts.ownText().trim());

        //Get summary, the text  Mission and KPI
        int i = 0;
        Elements txts = doc.select("h3 + p");
        for (Element text : txts) {
            if (i == 0) {
                res.setSummary(text.ownText());
            }
            if (i == 1) {
                res.setMission(new Mission(text.ownText()));
            }
            if (i == 2) {
                res.setKpi(text.ownText());
            }
            i++;
        }

        //Get Mission Deliverables and tasks
        String acc = StringUtils.substringBetween(allTxt, "Accountable", "Responsible").trim();
        String respon = StringUtils.substringBetween(allTxt, "Responsible", "Contributor").trim();
        String contrib = StringUtils.substringBetween(allTxt, "Contributor", "Main task/s").trim();
        String tks = StringUtils.substringBetween(allTxt, "Main task/s", "KPI area ").trim();

        HashMap<Integer, String> uls = new HashMap<>();
        i = 0;
        if (StringUtils.isNotEmpty(acc)) {
            uls.put(i++, "Accountable");
        }
        if (StringUtils.isNotEmpty(respon)) {
            uls.put(i++, "Responsible");
        }
        if (StringUtils.isNotEmpty(contrib)) {
            uls.put(i++, "Contributor");
        }
        if (StringUtils.isNotEmpty(tks)) {
            uls.put(i++, "Main task/s");
        } //TODO delete else

        //System.out.println(uls.toString());
        Elements html_uls = doc.select("ul");
        if (html_uls.size() != uls.size()) {

            System.out.println("\nERROR in " + res.getTitle() + ", num ul=" + html_uls.size() + ", num_parts="
                    + uls.size());
        }
        i = 0;
        for (Element ul : html_uls) {
            String target = uls.get(i);
            res = place(res, target, ul);
            i++;
        }

        //res.setTasks(tasks);
        //Get Competences
        i = 0;
        Elements cs = doc.select("h4");//the first h4 is not a competence

        ArrayList<String> comps = new ArrayList<>();//all comptences are here but not the levels
        for (Element c : cs) {
            if (i != 0) {
                comps.add(c.ownText());
            }
            i++;
        } //for

        res.setEcfs(foundLevels(comps, allTxt));

        //first p after first h3  h3:eq(0) + p
    } catch (IOException ex) {
        Logger.getLogger(ProfileHtmlReader.class.getName()).log(Level.SEVERE, null, ex);
    }
    return res;
}

From source file:com.xpn.xwiki.user.impl.LDAP.LDAPAuthServiceImpl.java

public Principal authenticate(String ldapusername, String password, XWikiContext context)
        throws XWikiException {
    Principal principal = null;/*from   w w w . j  a va 2  s .  com*/

    // Trim the username to allow users to enter their names with spaces before or after
    String username = (ldapusername == null) ? null : ldapusername.replaceAll(" ", "");

    if ((username == null) || (username.equals("")))
        return null;

    if ((password == null) || (password.trim().equals("")))
        return null;

    if (isSuperAdmin(username)) {
        return authenticateSuperAdmin(password, context);
    }

    // If we have the context then we are using direct mode
    // then we should specify the database
    // This is needed for virtual mode to work
    if (context != null) {
        String susername = username;
        int i = username.indexOf(".");
        if (i != -1)
            susername = username.substring(i + 1);

        String DN = getLDAP_DN(ldapusername, context);

        if (DN != null && DN.length() != 0) {
            if (checkDNPassword(DN, ldapusername, password, context)) {
                principal = GetUserPrincipal(susername, context);
            }
        } else {
            HashMap attributes = new HashMap();
            if (checkUserPassword(ldapusername, password, attributes, context)) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("User authenticated successfully");
                principal = GetUserPrincipal(susername, context);
                if (principal == null && attributes.size() > 0) {
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("Ready to create user from LDAP");

                    // In case of Virtual Wikis, users should be added in the main wiki
                    // if ldap is not configured for the virtual wiki
                    if (context.getWiki().isVirtualMode()) {
                        String db = context.getDatabase();
                        try {
                            // Switch to the main database in case of
                            // virtual and if not local LDAP configuration
                            if (context.getWiki().getXWikiPreference("ldap_server", context) == null || context
                                    .getWiki().getXWikiPreference("ldap_server", context).length() == 0) {
                                context.setDatabase(context.getWiki().getDatabase());
                            }
                            try {
                                CreateUserFromLDAP(attributes, context);
                                LOGGER.debug("Looking for user again " + susername);
                                principal = GetUserPrincipal(susername, context);
                            } catch (Exception e) {
                            }
                        } finally {
                            context.setDatabase(db);
                        }
                    } else {
                        CreateUserFromLDAP(attributes, context);
                        LOGGER.debug("Looking for user again " + susername);
                        principal = GetUserPrincipal(susername, context);
                    }
                    context.getWiki().flushCache(context);
                }
                if (principal == null) {
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("Accept user even without account");
                    principal = new SimplePrincipal("XWiki." + susername);
                }
            }
        }
    }
    return principal;
}

From source file:com.google.gwt.emultest.java.util.HashMapTest.java

/**
 * Test method for 'java.util.HashMap.size()'.
 *///from  w w  w .  j a v a 2 s. c o  m
public void testSize() {
    HashMap<String, String> hashMap = new HashMap<String, String>();
    checkEmptyHashMapAssumptions(hashMap);

    // Test size behavior on put
    assertEquals(hashMap.size(), SIZE_ZERO);
    hashMap.put(KEY_1, VALUE_1);
    assertEquals(hashMap.size(), SIZE_ONE);
    hashMap.put(KEY_2, VALUE_2);
    assertEquals(hashMap.size(), SIZE_TWO);
    hashMap.put(KEY_3, VALUE_3);
    assertEquals(hashMap.size(), SIZE_THREE);

    // Test size behavior on remove
    hashMap.remove(KEY_1);
    assertEquals(hashMap.size(), SIZE_TWO);
    hashMap.remove(KEY_2);
    assertEquals(hashMap.size(), SIZE_ONE);
    hashMap.remove(KEY_3);
    assertEquals(hashMap.size(), SIZE_ZERO);

    // Test size behavior on putAll
    hashMap.put(KEY_1, VALUE_1);
    hashMap.put(KEY_2, VALUE_2);
    hashMap.put(KEY_3, VALUE_3);
    HashMap<String, String> srcMap = new HashMap<String, String>(hashMap);
    hashMap.putAll(srcMap);
    assertEquals(hashMap.size(), SIZE_THREE);

    // Test size behavior on clear
    hashMap.clear();
    assertEquals(hashMap.size(), SIZE_ZERO);
}

From source file:it.baywaylabs.jumpersumo.utility.Finder.java

/**
 * This method returns ordered commands list from HashMap.
 *
 * @param map//from www  . j a  v  a 2  s . c  o  m
 * @return Ordered List of commands to execute.
 */
public List<String> getOrderedExtractedCommands(HashMap<Integer, String> map) {

    List<String> result = new ArrayList<String>();
    if (map.size() != 0) {
        Map<Integer, String> mapSorted = new TreeMap<Integer, String>(map);
        System.out.println("After Sorting:");
        Set set = mapSorted.entrySet();
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            Map.Entry me = (Map.Entry) iterator.next();
            Log.e(TAG, me.getKey() + ": " + me.getValue());
            result.add(me.getValue().toString());
        }
    }
    return result;
}