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.fatminds.cmis.AlfrescoCmisHelper.java

public static JsonNode getJsonNodeFromHttpGetResponse(String proto, String host, int port, String user,
        String pass, String path, HashMap params) throws ClientProtocolException, IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    try {//w w w.ja va2 s.co m
        client.getCredentialsProvider().setCredentials(new AuthScope(host, port),
                new UsernamePasswordCredentials(user, pass));
        String paramStr = "";
        if (params != null && params.size() > 0) {
            Iterator<String> iter = params.keySet().iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                //get.getParams().setParameter(key, params.get(key));
                if (!paramStr.equals("")) {
                    paramStr += "&";
                }
                paramStr += key + "=" + params.get(key);
            }
        }

        if (!paramStr.equals("")) {
            path += "?" + URLEncoder.encode(paramStr, "UTF-8").replace("+", "%20");
        }
        HttpGet get = new HttpGet(proto + host + ":" + port + path);
        log.info("Getting JsonNode for " + get.toString());
        HttpResponse resp = client.execute(get);
        if (resp.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Get failed, can't build JsonNode because: " + resp.getStatusLine().getReasonPhrase());
        }
        org.apache.http.HttpEntity entity = resp.getEntity();
        return mapper.readValue(entity.getContent(), JsonNode.class);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:edu.illinois.cs.cogcomp.transliteration.WikiTransliteration.java

/**
 * This does no normalization, but interns the string in each production.
 * @param counts/*from  w  w  w  .ja va2s  . co  m*/
 * @param internTable
 * @return
 */
public static HashMap<Production, Double> InternProductions(HashMap<Production, Double> counts,
        InternDictionary<String> internTable) {
    HashMap<Production, Double> result = new HashMap<>(counts.size());

    for (Production key : counts.keySet()) {
        Double value = counts.get(key);
        result.put(new Production(internTable.Intern(key.getFirst()), internTable.Intern(key.getSecond()),
                key.getOrigin()), value);
    }

    return result;
}

From source file:com.vmware.qe.framework.datadriven.utils.XMLUtil.java

/**
 * Finds all the children node whose tag names are in tags ArrayList. For example to get <one>
 * and <two> in Vector of Node from the following XML node : <parent> <one> something </one>
 * <two> something </two> <three> something </three> </parent> you pass <parent> node along with
 * this list {"one","two"}//w  w  w . j  a va  2 s .  c  om
 * 
 * @param parentNode : parentNode to lookup into for tags
 * @param tags : list of tags to be found among parentNode children
 * @return map of <NodeName, Node> that is found based on tags given in tags arrayList
 */
public static HashMap<String, Node> getChildrenByTagNames(Node parentNode, ArrayList<String> tags) {
    HashMap<String, Node> resultList = new HashMap<String, Node>();
    String tagFromList = null;
    Node foundNode = null;
    if (tags.size() > 0 || parentNode != null) {
        for (int tagNo = 0; tagNo < tags.size(); tagNo++) {
            tagFromList = tags.get(tagNo).toString();
            foundNode = XMLUtil.getInnerNodeByTagName(parentNode, tagFromList);
            if (!resultList.containsKey(tagFromList)) {
                resultList.put(tagFromList, foundNode);
            }
        }
    }
    return resultList.size() == 0 ? null : resultList;
}

From source file:edu.berkeley.sparrow.examples.BackendBenchmarkProfiler.java

/**
 * Run an experiment which launches tasks at {@code arrivalRate} for {@code durationMs}
 * seconds and waits for all tasks to finish. Return a {@link DescriptiveStatistics}
 * object which contains stats about the distribution of task finish times. Tasks
 * are executed in a thread pool which contains at least {@code corePoolSize} threads
 * and grows up to {@code maxPoolSize} threads (growing whenever a new task arrives
 * and all existing threads are used). /*from  w ww  .ja v  a2 s  . co  m*/
 * 
 * Setting {@code maxPoolSize} to a very large number enacts time sharing, while
 * setting it equal to {@code corePoolSize} creates a fixed size task pool.
 * 
 * The derivative of task finishes is tracked by bucketing tasks at the granularity
 * {@code bucketSize}. If it is detected that task finishes are increasing in an 
 * unbounded fashion (i.e. infinite queuing is occuring) a {@link RuntimeException} 
 * is thrown.
 */
public static void runExperiment(double arrivalRate, int corePoolSize, int maxPoolSize, long bucketSize,
        long durationMs, DescriptiveStatistics runTimes, DescriptiveStatistics waitTimes) {
    long startTime = System.currentTimeMillis();
    long keepAliveTime = 10;
    Random r = new Random();
    BlockingQueue<Runnable> runQueue = new LinkedBlockingQueue<Runnable>();
    ExecutorService threadPool = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime,
            TimeUnit.MILLISECONDS, runQueue);
    if (maxPoolSize == Integer.MAX_VALUE) {
        threadPool = Executors.newCachedThreadPool();
    }

    // run times indexed by bucketing interval
    HashMap<Long, List<Long>> bucketedRunTimes = new HashMap<Long, List<Long>>();
    // wait times indexed by bucketing interval
    HashMap<Long, List<Long>> bucketedWaitTimes = new HashMap<Long, List<Long>>();

    /*
     * This is a little tricky. 
     * 
     * We want to generate inter-arrival delays according to the arrival rate specified.
     * The simplest option would be to generate an arrival delay and then sleep() for it
     * before launching each task. This has in issue, however: sleep() might wait 
     * several ms longer than we ask it to. When task arrival rates get really fast, 
     * i.e. one task every 10 ms, sleeping an additional few ms will mean we launch 
     * tasks at a much lower rate than requested.
     * 
     * Instead, we keep track of task launches in a way that does not depend on how long
     * sleep() actually takes. We still might have tasks launch slightly after their
     * scheduled launch time, but we will not systematically "fall behind" due to
     * compounding time lost during sleep()'s;
     */
    long currTime = startTime;
    while (true) {
        long delay = (long) (generateInterarrivalDelay(r, arrivalRate) * 1000);

        // When should the next task launch, based on when the last task was scheduled
        // to launch.
        long nextTime = currTime + delay;

        // Diff gives how long we should wait for the next scheduled task. The difference 
        // may be negative if our last sleep() lasted too long relative to the inter-arrival
        // delay based on the last scheduled launch, so we round up to 0 in that case. 
        long diff = Math.max(0, nextTime - System.currentTimeMillis());
        currTime = nextTime;
        if (diff > 0) {
            try {
                Thread.sleep(diff);
            } catch (InterruptedException e) {
                System.err.println("Unexpected interruption!");
                System.exit(1);
            }
        }
        threadPool.submit((new BenchmarkRunnable(bucketedRunTimes, bucketedWaitTimes, bucketSize)));
        if (System.currentTimeMillis() > startTime + durationMs) {
            break;
        }
    }
    threadPool.shutdown();
    try {
        threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e1) {
        System.err.println("Unexpected interruption!");
        System.exit(1);
    }
    List<Long> times = new ArrayList<Long>(bucketedRunTimes.keySet());
    Collections.sort(times);
    HashMap<Long, DescriptiveStatistics> bucketStats = new HashMap<Long, DescriptiveStatistics>();

    // Remove first and last buckets since they will not be completely full to do
    // discretization. 
    times.remove(0);
    times.remove(times.size() - 1);

    for (Long time : times) {
        DescriptiveStatistics stats = new DescriptiveStatistics();
        List<Long> list = bucketedRunTimes.get(time);
        for (Long l : list) {
            stats.addValue(l);
            runTimes.addValue(l);
        }
        bucketStats.put(time, stats);

        List<Long> waitList = bucketedWaitTimes.get(time);
        for (Long l : waitList) {
            waitTimes.addValue(l);
        }
    }
    int size = bucketStats.size();
    if (size >= 2) {
        DescriptiveStatistics first = bucketStats.get(times.get(0));
        DescriptiveStatistics last = bucketStats.get(times.get(times.size() - 1));
        double increase = last.getPercentile(50) / first.getPercentile(50);
        // A simple heuristic, if the median runtime went up by five from the first to 
        // last complete bucket, we assume we are seeing unbounded growth
        if (increase > 5.0) {
            throw new RuntimeException(
                    "Queue not in steady state: " + last.getMean() + " vs " + first.getMean());
        }
    }
}

From source file:cd.go.authentication.ldap.executor.GetPluginIconExecutorTest.java

@Test
public void rendersIconInBase64() throws Exception {
    GoPluginApiResponse response = new GetPluginIconExecutor().execute();
    HashMap<String, String> hashMap = new Gson().fromJson(response.responseBody(), HashMap.class);
    assertThat(hashMap.size(), is(2));
    assertThat(hashMap.get("content_type"), is("image/png"));
    assertThat(Util.readResourceBytes("/gocd_72_72_icon.png"), is(Base64.decodeBase64(hashMap.get("data"))));
}

From source file:cd.go.contrib.elasticagents.docker.executors.GetPluginSettingsIconExecutorTest.java

@Test
public void rendersIconInBase64() throws Exception {
    GoPluginApiResponse response = new GetPluginSettingsIconExecutor().execute();
    HashMap<String, String> hashMap = new Gson().fromJson(response.responseBody(), HashMap.class);
    assertThat(hashMap.size(), is(2));
    assertThat(hashMap.get("content_type"), is("image/svg+xml"));
    assertThat(Util.readResourceBytes("/docker-plain.svg"), is(Base64.decodeBase64(hashMap.get("data"))));
}

From source file:cd.go.contrib.elasticagents.dockerswarm.elasticagent.executors.GetPluginSettingsIconExecutorTest.java

@Test
public void rendersIconInBase64() throws Exception {
    GoPluginApiResponse response = new GetPluginSettingsIconExecutor().execute();
    HashMap<String, String> hashMap = new Gson().fromJson(response.responseBody(), HashMap.class);
    assertThat(hashMap.size(), is(2));
    assertThat(hashMap.get("content-type"), is("image/png"));
    assertThat(Util.readResourceBytes("/docker-swarm.png"), is(Base64.decodeBase64(hashMap.get("data"))));
}

From source file:com.clustercontrol.repository.util.FacilityTreeCache.java

/** ? */
public static synchronized void refresh() {
    JpaTransactionManager jtm = new JpaTransactionManager();
    if (!jtm.isNestedEm()) {
        m_log.warn("refresh() : transactioin has not been begined.");
        jtm.close();//from   w  w w  .j  a v  a  2 s. c om
        return;
    }

    try {
        _lock.writeLock();

        /*
         * FacilityInfoMap ?
         */
        long startTime = HinemosTime.currentTimeMillis();
        new JpaTransactionManager().getEntityManager().clear();

        // FacilityInfo?FacilityTreeItem????????????
        HashMap<String, FacilityInfo> facilityInfoMap = createFacilityInfoMap();
        if (facilityInfoMap == null) {
            return;
        }
        long infoMapRefreshTime = HinemosTime.currentTimeMillis() - startTime;
        m_log.info("refresh() : FacilityInfoMap(Cache) " + infoMapRefreshTime + "ms. size="
                + facilityInfoMap.size());

        /*
         * FacilityTreeItem ?
         */
        startTime = HinemosTime.currentTimeMillis();
        FacilityTreeItem facilityTreeItem = createFacilityTreeItem(facilityInfoMap);
        if (facilityTreeItem == null) {
            return;
        }
        long treeItemRefreshTime = HinemosTime.currentTimeMillis() - startTime;
        m_log.info("refresh() : FacilityTreeItem(Cache) " + treeItemRefreshTime + "ms");

        //FacilityTreeItemMap?
        startTime = HinemosTime.currentTimeMillis();
        HashMap<String, ArrayList<FacilityTreeItem>> facilityTreeItemMap = createFacilityTreeItemMap(
                facilityInfoMap, facilityTreeItem);
        long treeItemMapRefreshTime = HinemosTime.currentTimeMillis() - startTime;
        m_log.info("refresh() : FacilityTreeItemMap(Cache) " + treeItemMapRefreshTime + "ms");

        storeFacilityCache(facilityInfoMap);
        storeFacilityTreeRootCache(facilityTreeItem);
        storeFacilityTreeItemCache(facilityTreeItemMap);
    } finally {
        _lock.writeUnlock();
    }
}

From source file:at.tuwien.ifs.somtoolbox.data.InputDataWriter.java

/** Writes the class information to a file in SOMLib format. */
public static void writeAsSOMLib(HashMap<String, String> classInfo, HashSet<String> classNames, String fileName)
        throws IOException, SOMLibFileFormatException {
    ArrayList<String> classNamesList = new ArrayList<String>(classNames);
    Collections.sort(classNamesList);

    PrintWriter writer = FileUtils.openFileForWriting("SOMLib class info", fileName);
    writer.println("$TYPE class_information");

    writer.println("$NUM_CLASSES " + classNames.size());
    writer.println("$CLASS_NAMES " + StringUtils.toString(classNamesList, "", "", " "));
    writer.println("$XDIM 2");
    writer.println("$YDIM " + classInfo.size());
    for (String key : classInfo.keySet()) {
        writer.println(key + " " + classNamesList.indexOf(classInfo.get(key)));
    }//from   www.  ja va  2  s .  c o  m

    writer.flush();
    writer.close();
}

From source file:mysoft.sonar.plugins.web.check.StyleAttributeRegExpCheck.java

@Override
public void startElement(TagNode node) {
    HashMap<String, String> styles = GetStyles(node);
    if (styles.size() <= 0)
        return;/*from   w ww . j ava2s .  c  om*/

    CheckStyleRules(node, styles);
}