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.ibm.bi.dml.runtime.util.DataConverter.java

/**
 * NOTE: this method also ensures the specified matrix dimensions
 * /*  ww  w .j a  va  2 s . c o  m*/
 * @param map
 * @return
 */
public static MatrixBlock convertToMatrixBlock(HashMap<MatrixIndexes, Double> map, int rlen, int clen) {
    int nnz = map.size();
    boolean sparse = MatrixBlock.evalSparseFormatInMemory(rlen, clen, nnz);
    MatrixBlock mb = new MatrixBlock(rlen, clen, sparse, nnz);

    // copy map values into new block
    if (sparse) //SPARSE <- cells
    {
        //append cells to sparse target (prevent shifting)
        for (Entry<MatrixIndexes, Double> e : map.entrySet()) {
            MatrixIndexes index = e.getKey();
            double value = e.getValue();
            int rix = (int) index.getRowIndex();
            int cix = (int) index.getColumnIndex();
            if (value != 0 && rix <= rlen && cix <= clen)
                mb.appendValue(rix - 1, cix - 1, value);
        }

        //sort sparse target representation
        mb.sortSparseRows();
    } else //DENSE <- cells
    {
        //directly insert cells into dense target 
        for (Entry<MatrixIndexes, Double> e : map.entrySet()) {
            MatrixIndexes index = e.getKey();
            double value = e.getValue();
            int rix = (int) index.getRowIndex();
            int cix = (int) index.getColumnIndex();
            if (value != 0 && rix <= rlen && cix <= clen)
                mb.quickSetValue(rix - 1, cix - 1, value);
        }
    }

    return mb;
}

From source file:loadTest.loadTestLib.LUtil.java

public static boolean startDockerBuild() throws IOException, InterruptedException {
    if (useDocker) {
        if (runInDockerCluster) {

            HashMap<String, Integer> dockerNodes = getDockerNodes();
            String dockerTar = LUtil.class.getClassLoader().getResource("docker/loadTest.tar").toString()
                    .substring(5);//from w w w  . j  ava 2  s .  c om
            ExecutorService exec = Executors.newFixedThreadPool(dockerNodes.size());

            dockerError = false;
            doneDockers = 0;

            for (Entry<String, Integer> entry : dockerNodes.entrySet()) {
                exec.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String url = entry.getKey() + "/images/vauvenal5/loadtest";
                            URL obj = new URL(url);
                            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                            con.setRequestMethod("DELETE");
                            con.setRequestProperty("force", "true");
                            int responseCode = con.getResponseCode();
                            con.disconnect();

                            url = entry.getKey()
                                    + "/build?t=vauvenal5/loadtest&dockerfile=./loadTest/Dockerfile";
                            obj = new URL(url);
                            con = (HttpURLConnection) obj.openConnection();
                            con.setRequestMethod("POST");
                            con.setRequestProperty("Content-type", "application/tar");
                            con.setDoOutput(true);
                            File file = new File(dockerTar);
                            FileInputStream fileStr = new FileInputStream(file);
                            byte[] b = new byte[(int) file.length()];
                            fileStr.read(b);
                            con.getOutputStream().write(b);
                            con.getOutputStream().flush();
                            con.getOutputStream().close();

                            responseCode = con.getResponseCode();

                            if (responseCode != 200) {
                                dockerError = true;
                            }

                            String msg = "";

                            do {
                                Thread.sleep(5000);
                                msg = "";
                                url = entry.getKey() + "/images/json";
                                obj = new URL(url);
                                HttpURLConnection con2 = (HttpURLConnection) obj.openConnection();
                                con2.setRequestMethod("GET");
                                responseCode = con2.getResponseCode();

                                BufferedReader in = new BufferedReader(
                                        new InputStreamReader(con2.getInputStream()));
                                String line = null;

                                while ((line = in.readLine()) != null) {
                                    msg += line;
                                }

                                con2.disconnect();
                            } while (!msg.contains("vauvenal5/loadtest"));

                            con.disconnect();
                            doneDockers++;
                        } catch (MalformedURLException ex) {
                            dockerError = true;
                        } catch (FileNotFoundException ex) {
                            dockerError = true;
                        } catch (IOException ex) {
                            dockerError = true;
                        } catch (InterruptedException ex) {
                            dockerError = true;
                        }
                    }
                });
            }

            while (doneDockers < dockerNodes.size()) {
                Thread.sleep(5000);
            }

            return !dockerError;
        }

        //get the path and substring the 'file:' from the URI
        String dockerfile = LUtil.class.getClassLoader().getResource("docker/loadTest").toString().substring(5);

        ProcessBuilder processBuilder = new ProcessBuilder("docker", "rmi", "-f", "vauvenal5/loadtest");
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        Process docker = processBuilder.start();

        docker.waitFor();

        processBuilder = new ProcessBuilder("docker", "build", "-t", "vauvenal5/loadtest", dockerfile);
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        Process proc = processBuilder.start();
        return proc.waitFor() == 0;
    }
    return true;
}

From source file:free.yhc.netmbuddy.utils.Utils.java

public static Object[] getSortedKeyOfTimeMap(HashMap<? extends Object, Long> timeMap) {
    TimeElem[] te = new TimeElem[timeMap.size()];
    Object[] vs = timeMap.keySet().toArray(new Object[0]);
    for (int i = 0; i < vs.length; i++)
        te[i] = new TimeElem(vs[i], timeMap.get(vs[i]));
    Arrays.sort(te, sTimeElemComparator);
    Object[] sorted = new Object[vs.length];
    for (int i = 0; i < sorted.length; i++)
        sorted[i] = te[i].v;/*from w  w  w.j a v a  2  s .  com*/

    return sorted;
}

From source file:it.acubelab.smaph.entityfilters.LibSvmEntityFilter.java

private static boolean checkFeatures(HashMap<String, Double> features) {
    if (getOrDefault(features, "is_s1", 0.0) + getOrDefault(features, "is_s2", 0.0)
            + getOrDefault(features, "is_s3", 0.0) + getOrDefault(features, "is_s4", 0.0)
            + getOrDefault(features, "is_s5", 0.0) != 1)
        return false;
    boolean found = false;
    for (String sourcePrefix : new String[] { "s1_", "s2_", "s3_", "s5_" }) {
        int sourceFtrCount = 0;

        for (String ftrName : features.keySet())
            if (ftrName.startsWith(sourcePrefix))
                sourceFtrCount++;//w  w w  . ja va  2  s. c  om

        if (sourcePrefix.equals("s1_"))
            found = sourceFtrCount == 9 && features.size() == sourceFtrCount + 1;
        if (sourcePrefix.equals("s2_"))
            found = sourceFtrCount == 8 && features.size() == sourceFtrCount + 1;
        if (sourcePrefix.equals("s3_"))
            found = sourceFtrCount == 8 && features.size() == sourceFtrCount + 1;
        if (sourcePrefix.equals("s4_"))
            found = sourceFtrCount == 0 && features.size() == sourceFtrCount + 1;
        if (sourcePrefix.equals("s5_"))
            found = sourceFtrCount == 8 && features.size() == sourceFtrCount + 1;

        if (found)
            return true;
    }
    return false;
}

From source file:at.treedb.jslib.JsLib.java

/**
 * Loads an external JavaScript library.
 * //w w  w.j a v  a  2  s  .  com
 * @param dao
 *            {@code DAOiface} (data access object)
 * @param name
 *            library name
 * @param version
 *            optional library version. If this parameter is null the
 *            library with the highest version number will be loaded
 * @return {@code JsLib} object
 * @throws Exception
 */
@SuppressWarnings("resource")
public static synchronized JsLib load(DAOiface dao, String name, String version) throws Exception {
    initJsLib(dao);
    if (jsLibs == null) {
        return null;
    }
    JsLib lib = null;
    synchronized (lockObj) {
        HashMap<Version, JsLib> v = jsLibs.get(name);
        if (v == null) {
            return null;
        }

        if (version != null) {
            lib = v.get(new Version(version));
        } else {
            Version[] array = v.keySet().toArray(new Version[v.size()]);
            Arrays.sort(array);
            // return the library with the highest version number
            lib = v.get(array[array.length - 1]);
        }
    }
    if (lib != null) {
        if (!lib.isExtracted) {
            // load binary archive data
            lib.callbackAfterLoad(dao);
            // detect zip of 7z archive
            MimeType mtype = ContentInfo.getContentInfo(lib.data);
            int totalSize = 0;
            HashMap<String, byte[]> dataMap = null;
            String libName = "jsLib" + lib.getHistId();
            String classPath = lib.getName() + "/java/classes/";
            if (mtype != null) {
                // ZIP archive
                if (mtype.equals(MimeType.ZIP)) {
                    dataMap = new HashMap<String, byte[]>();
                    lib.zipInput = new ZipArchiveInputStream(new ByteArrayInputStream(lib.data));
                    do {
                        ZipArchiveEntry entry = lib.zipInput.getNextZipEntry();
                        if (entry == null) {
                            break;
                        }
                        if (entry.isDirectory()) {
                            continue;
                        }
                        int size = (int) entry.getSize();
                        totalSize += size;
                        byte[] data = new byte[size];
                        lib.zipInput.read(data, 0, size);
                        dataMap.put(entry.getName(), data);
                        if (entry.getName().contains(classPath)) {
                            lib.javaFiles.add(entry.getName());
                        }
                    } while (true);
                    lib.zipInput.close();
                    lib.isExtracted = true;
                    // 7-zip archive
                } else if (mtype.equals(MimeType._7Z)) {
                    dataMap = new HashMap<String, byte[]>();
                    File tempFile = FileStorage.getInstance().createTempFile(libName, ".7z");
                    tempFile.deleteOnExit();
                    Stream.writeByteStream(tempFile, lib.data);
                    lib.sevenZFile = new SevenZFile(tempFile);
                    do {
                        SevenZArchiveEntry entry = lib.sevenZFile.getNextEntry();
                        if (entry == null) {
                            break;
                        }
                        if (entry.isDirectory()) {
                            continue;
                        }
                        int size = (int) entry.getSize();
                        totalSize += size;
                        byte[] data = new byte[size];
                        lib.sevenZFile.read(data, 0, size);
                        dataMap.put(entry.getName(), data);
                        if (entry.getName().contains(classPath)) {
                            lib.javaFiles.add(entry.getName());
                        }

                    } while (true);
                    lib.sevenZFile.close();
                    lib.isExtracted = true;
                }
            }
            if (!lib.isExtracted) {
                throw new Exception("JsLib.load(): No JavaScript archive extracted!");
            }
            // create a buffer for the archive
            byte[] buf = new byte[totalSize];
            int offset = 0;
            // enumerate the archive entries
            for (String n : dataMap.keySet()) {
                byte[] d = dataMap.get(n);
                System.arraycopy(d, 0, buf, offset, d.length);
                lib.archiveMap.put(n, new ArchiveEntry(offset, d.length));
                offset += d.length;
            }
            // create a temporary file containing the extracted archive
            File tempFile = FileStorage.getInstance().createTempFile(libName, ".dump");
            lib.dumpFile = tempFile;
            tempFile.deleteOnExit();
            Stream.writeByteStream(tempFile, buf);
            FileInputStream inFile = new FileInputStream(tempFile);
            // closed by the GC
            lib.inChannel = inFile.getChannel();
            // discard the archive data - free the memory
            lib.data = null;
            dataMap = null;
        }
    }
    return lib;
}

From source file:es.bsc.servicess.ide.editors.deployers.ImageCreation.java

public static String getFullImageDescription(ProjectMetadata prMeta, HashMap<String, ServiceElement> allEls) {
    String[] els = allEls.keySet().toArray(new String[allEls.size()]);
    Map<String, Integer> minCoreInstances = prMeta.getMinElasticity(els);
    Map<String, String> maxConstraints = new HashMap<String, String>();
    Map<String, String> maxResourcesPerMachine = prMeta.getMaxResourcesProperties();
    Map<String, Integer> minCoreInstancesPerMachine = BuildingDeploymentFormPage.getConstraintsElements(els,
            allEls, minCoreInstances, maxResourcesPerMachine, maxConstraints);
    return generateTemplate(maxConstraints);
}

From source file:net.sf.taverna.t2.activities.biomoby.ExecuteAsyncCgiService.java

private static boolean pollAsyncCgiService(String msName, String url, EndpointReference epr, String[] queryIds,
        String[] result) throws MobyException {
    // Needed to remap results
    HashMap<String, Integer> queryMap = new HashMap<String, Integer>();
    for (int qi = 0; qi < queryIds.length; qi++) {
        String queryId = queryIds[qi];
        if (queryId != null)
            queryMap.put(queryId, new Integer(qi));
    }//from w ww  .  j  ava  2  s. c  o  m

    if (queryMap.size() == 0)
        return false;

    // construct the GetMultipleResourceProperties XML
    StringBuffer xml = new StringBuffer();
    xml.append("<wsrf-rp:GetMultipleResourceProperties xmlns:wsrf-rp='" + RESOURCE_PROPERTIES_NS
            + "' xmlns:mobyws='http://biomoby.org/'>");
    for (String q : queryMap.keySet())
        xml.append("<wsrf-rp:ResourceProperty>mobyws:" + STATUS_PREFIX + q + "</wsrf-rp:ResourceProperty>");
    xml.append("</wsrf-rp:GetMultipleResourceProperties>");

    StringBuffer httpheader = new StringBuffer();
    httpheader.append("<moby-wsrf>");
    httpheader.append("<wsa:Action xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">"
            + GET_MULTIPLE_RESOURCE_PROPERTIES_ACTION + "</wsa:Action>");
    httpheader.append(
            "<wsa:To xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsu:Id=\"To\">"
                    + url + "</wsa:To>");
    httpheader.append(
            "<mobyws:ServiceInvocationId xmlns:mobyws=\"http://biomoby.org/\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsa:IsReferenceParameter=\"true\">"
                    + epr.getServiceInvocationId() + "</mobyws:ServiceInvocationId>");
    httpheader.append("</moby-wsrf>");

    AnalysisEvent[] l_ae = null;
    // First, status from queries
    String response = "";
    // construct the Httpclient
    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "jMoby/Taverna2");
    // create the post method
    PostMethod method = new PostMethod(url + "/status");
    // add the moby-wsrf header (with no newlines)
    method.addRequestHeader("moby-wsrf", httpheader.toString().replaceAll("\r\n", ""));

    // put our data in the request
    RequestEntity entity;
    try {
        entity = new StringRequestEntity(xml.toString(), "text/xml", null);
    } catch (UnsupportedEncodingException e) {
        throw new MobyException("Problem posting data to webservice", e);
    }
    method.setRequestEntity(entity);

    // retry up to 10 times
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(10, true));

    // call the method
    try {
        if (client.executeMethod(method) != HttpStatus.SC_OK)
            throw new MobyException("Async HTTP POST service returned code: " + method.getStatusCode() + "\n"
                    + method.getStatusLine() + "\nduring our polling request");
        response = stream2String(method.getResponseBodyAsStream());
    } catch (IOException e) {
        throw new MobyException("Problem reading response from webservice", e);
    } finally {
        // Release current connection to the connection pool once you
        // are
        // done
        method.releaseConnection();
    }

    if (response != null) {
        l_ae = AnalysisEvent.createFromXML(response);
    }

    if (l_ae == null || l_ae.length == 0) {
        new MobyException("Troubles while checking asynchronous MOBY job status from service " + msName);
    }

    ArrayList<String> finishedQueries = new ArrayList<String>();
    // Second, gather those finished queries
    for (int iae = 0; iae < l_ae.length; iae++) {
        AnalysisEvent ae = l_ae[iae];
        if (ae.isCompleted()) {
            String queryId = ae.getQueryId();
            if (!queryMap.containsKey(queryId)) {
                throw new MobyException(
                        "Invalid result queryId on asynchronous MOBY job status fetched from " + msName);
            }
            finishedQueries.add(queryId);
        }
    }

    // Third, let's fetch the results from the finished queries
    if (finishedQueries.size() > 0) {
        String[] resQueryIds = finishedQueries.toArray(new String[0]);
        for (int x = 0; x < resQueryIds.length; x++) {
            // construct the GetMultipleResourceProperties XML
            xml = new StringBuffer();
            xml.append("<wsrf-rp:GetMultipleResourceProperties xmlns:wsrf-rp='" + RESOURCE_PROPERTIES_NS
                    + "' xmlns:mobyws='http://biomoby.org/'>");
            for (String q : resQueryIds)
                xml.append("<wsrf-rp:ResourceProperty>mobyws:" + RESULT_PREFIX + q
                        + "</wsrf-rp:ResourceProperty>");
            xml.append("</wsrf-rp:GetMultipleResourceProperties>");

            httpheader = new StringBuffer();
            httpheader.append("<moby-wsrf>");
            httpheader.append("<wsa:Action xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">"
                    + GET_MULTIPLE_RESOURCE_PROPERTIES_ACTION + "</wsa:Action>");
            httpheader.append(
                    "<wsa:To xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsu:Id=\"To\">"
                            + url + "</wsa:To>");
            httpheader.append(
                    "<mobyws:ServiceInvocationId xmlns:mobyws=\"http://biomoby.org/\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsa:IsReferenceParameter=\"true\">"
                            + epr.getServiceInvocationId() + "</mobyws:ServiceInvocationId>");
            httpheader.append("</moby-wsrf>");
            client = new HttpClient();
            client.getParams().setParameter("http.useragent", "jMoby/Taverna2");
            // create the post method
            method = new PostMethod(url + "/results");
            // add the moby-wsrf header (with no newlines)
            method.addRequestHeader("moby-wsrf", httpheader.toString().replaceAll("\r\n", ""));

            // put our data in the request
            entity = null;
            try {
                entity = new StringRequestEntity(xml.toString(), "text/xml", null);
            } catch (UnsupportedEncodingException e) {
                throw new MobyException("Problem posting data to webservice", e);
            }
            method.setRequestEntity(entity);

            // retry up to 10 times
            client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                    new DefaultHttpMethodRetryHandler(10, true));

            // call the method
            try {
                if (client.executeMethod(method) != HttpStatus.SC_OK)
                    throw new MobyException("Async HTTP POST service returned code: " + method.getStatusCode()
                            + "\n" + method.getStatusLine() + "\nduring our polling request");
                // place the result in the array
                result[x] = stream2String(method.getResponseBodyAsStream());
                // Marking as null
                queryIds[x] = null;
            } catch (IOException e) {
                logger.warn("Problem getting result from webservice\n" + e.getMessage());
            } finally {
                // Release current connection
                method.releaseConnection();
            }
        }

    }
    return finishedQueries.size() != queryMap.size();
}

From source file:com.ibm.bi.dml.runtime.controlprogram.parfor.RemoteParForUtils.java

/**
 * //from w  ww  . j a  v  a 2  s .  co  m
 * @param out
 * @return
 * @throws DMLRuntimeException
 * @throws IOException
 */
public static LocalVariableMap[] getResults(List<Tuple2<Long, String>> out, Log LOG)
        throws DMLRuntimeException {
    HashMap<Long, LocalVariableMap> tmp = new HashMap<Long, LocalVariableMap>();

    int countAll = 0;
    for (Tuple2<Long, String> entry : out) {
        Long key = entry._1();
        String val = entry._2();
        if (!tmp.containsKey(key))
            tmp.put(key, new LocalVariableMap());
        Object[] dat = ProgramConverter.parseDataObject(val);
        tmp.get(key).put((String) dat[0], (Data) dat[1]);
        countAll++;
    }

    if (LOG != null) {
        LOG.debug("Num remote worker results (before deduplication): " + countAll);
        LOG.debug("Num remote worker results: " + tmp.size());
    }

    //create return array
    return tmp.values().toArray(new LocalVariableMap[0]);
}

From source file:gov.jgi.meta.MetaUtils.java

/**
 * see @{link #countSequences(String) countSequences(String)}
 * @param contigFileName the file or directory name
 * @param conf the hadoop configuration object specifiing filesystem
 * @return an integer count of number of sequences found
 * @throws IOException if filesystem has error
 *///from  ww  w .  j a  v a2s. c o m
public static int countSequences(String contigFileName, Configuration conf) throws IOException {
    FileSystem fs = FileSystem.get(conf);
    Path filenamePath = new Path(contigFileName);
    int count = 0;

    if (!fs.exists(filenamePath)) {
        throw new IOException("file not found: " + contigFileName);
    }

    for (Path f : findAllPaths(filenamePath)) {
        FSDataInputStream in = fs.open(f);
        FastaBlockLineReader fblr = new FastaBlockLineReader(in);

        Text key = new Text();
        long length = fs.getFileStatus(f).getLen();
        HashMap<String, String> tmpcontigs = new HashMap<String, String>();
        fblr.readLine(key, tmpcontigs, Integer.MAX_VALUE, (int) length);
        count += tmpcontigs.size();
        in.close();
    }

    return (count);
}

From source file:Main.java

public static String customrequest(String url, HashMap<String, String> params, String method) {
    try {/*from   w  w  w  .  jav a 2  s  .co  m*/

        URL postUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setConnectTimeout(5 * 1000);

        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");

        conn.connect();
        OutputStream out = conn.getOutputStream();
        StringBuilder sb = new StringBuilder();
        if (null != params) {
            int i = params.size();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (i == 1) {
                    sb.append(entry.getKey() + "=" + entry.getValue());
                } else {
                    sb.append(entry.getKey() + "=" + entry.getValue() + "&");
                }

                i--;
            }
        }
        String content = sb.toString();
        out.write(content.getBytes("UTF-8"));
        out.flush();
        out.close();
        InputStream inStream = conn.getInputStream();
        String result = inputStream2String(inStream);
        conn.disconnect();
        return result;
    } catch (Exception e) {
        // TODO: handle exception
    }
    return null;
}