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.jci.utils.CommonUtils.java

/**
 * Gets the header string./*ww w. j  a  v a  2 s . c o m*/
 *
 * @param mapping the mapping
 * @return the header string
 */
public String getHeaderString(HashMap<Integer, String> mapping) {
    StringBuilder line = new StringBuilder();
    for (int i = 0; i < mapping.size(); i++) {
        String str = StringUtils.capitalize(mapping.get(i));
        str = str.substring(0, 1).toUpperCase() + str.substring(1);
        String[] upperStr = str.split("(?<=[a-z])(?=[A-Z])");
        String joined = "#" + String.join(" ", upperStr);
        line.append(joined + "\t");
    }

    return line.toString();
}

From source file:org.impalaframework.extension.mvc.util.RequestModelHelperTest.java

@SuppressWarnings("unchecked")
public void testSetParameters() {
    HttpServletRequest request = createMock(HttpServletRequest.class);
    HashMap model = new HashMap();
    model.put("p2", "2a");
    model.put("p3", null);

    expect(request.getParameterNames())//from   w w w .  j av a 2 s . co  m
            .andReturn(Collections.enumeration(Arrays.asList("p1", "p2", "p3", "p4")));
    expect(request.getParameter("p1")).andReturn("1");
    //expect(request.getParameter("p2")).andReturn("2");
    //expect(request.getParameter("p3")).andReturn("3");
    expect(request.getParameter("p4")).andReturn("");

    replay(request);

    RequestModelHelper.setParameters(request, model);

    assertEquals(4, model.size());
    assertEquals("1", model.get("p1"));
    assertEquals("2a", model.get("p2"));
    assertEquals(null, model.get("p3"));
    assertEquals("", model.get("p4"));

    verify(request);
}

From source file:com.jci.utils.CommonUtils.java

/**
 * Fixed length string./*from   ww  w . j a v  a2s  .c o  m*/
 *
 * @param po the po
 * @param mapping the mapping
 * @return the string builder
 */
public StringBuilder fixedLengthString(HashMap<String, Object> po, HashMap<Integer, String> mapping) {
    StringBuilder line = new StringBuilder();
    int size = mapping.size();
    for (int i = 0; i < size; i++) {
        String azureCoumnName = mapping.get(i);
        if ((size - 1) == i) {
            if (isBlank(String.valueOf(po.get(azureCoumnName)))) {
                line.append("");
            } else {
                line.append((po.get(azureCoumnName)));
            }
        } else {
            if (isBlank(String.valueOf(po.get(azureCoumnName)))) {
                line.append(appendTab(""));
            } else {
                line.append(appendTab(po.get(azureCoumnName)));
            }
        }
    }
    return line;

}

From source file:com.yahoo.ycsb.db.PostgreSQLJsonbClient.java

@Override
public Status update(String tableName, String key, HashMap<String, ByteIterator> values) {
    try {/*from  w  ww.j a v  a 2  s.  c o  m*/
        int numFields = values.size();
        OrderedFieldInfo fieldInfo = getFieldInfo(values);
        StatementType type = new StatementType(StatementType.Type.UPDATE, tableName, 1, "fields",
                getShardIndexByKey(key));
        PreparedStatement updateStatement = cachedStatements.get(type);
        if (updateStatement == null) {
            updateStatement = createAndCacheUpdateStatement(type, key);
        }
        for (Map.Entry<String, String> entry : StringByteIterator.getStringMap(values).entrySet()) {
            updateStatement.setString(1, "{0, " + entry.getKey() + "}");
            updateStatement.setString(2, "\"" + StringEscapeUtils.escapeJson(entry.getValue()) + "\"");
        }
        updateStatement.setString(3, key);
        int result = updateStatement.executeUpdate();
        if (result == 1) {
            return Status.OK;
        }
        return Status.UNEXPECTED_STATE;
    } catch (SQLException e) {
        System.err.println("Error in processing update to table: " + tableName + e);
        return Status.ERROR;
    }
}

From source file:org.mahasen.util.PutUtil.java

/**
 * @param file//  w  ww  .  ja  v a  2s. c  o  m
 * @throws InterruptedException
 * @throws RegistryException
 * @throws PastException
 * @throws IOException
 */
public void secureUpload(File file, Id resourceId) throws InterruptedException, RegistryException,
        PastException, IOException, MahasenConfigurationException, MahasenException {

    // get the IP addresses pool to upload files.
    Vector<String> nodeIpsToPut = getNodeIpsToPut();

    MahasenFileSplitter mahasenFileSplitter = new MahasenFileSplitter();
    mahasenFileSplitter.split(file);
    HashMap<String, String> fileParts = mahasenFileSplitter.getPartNames();

    mahasenResource.addPartNames(fileParts.keySet().toArray(new String[fileParts.size()]));
    Random random = new Random();

    for (String currentPartName : fileParts.keySet()) {
        File splittedFilePart = new File(fileParts.get(currentPartName));
        int randomNumber = random.nextInt(nodeIpsToPut.size());
        String nodeIp = nodeIpsToPut.get(randomNumber);

        try {
            setTrustStore();
            URI uri = null;

            ArrayList<NameValuePair> qparams = new ArrayList<NameValuePair>();
            qparams.add(new BasicNameValuePair("splittedfilename", splittedFilePart.getName()));
            uri = URIUtils.createURI("https", nodeIp + ":" + MahasenConstants.SERVER_PORT, -1,
                    "/mahasen/upload_request_ajaxprocessor.jsp", URLEncodedUtils.format(qparams, "UTF-8"),
                    null);

            MahasenUploadWorker uploadWorker = new MahasenUploadWorker(uri, currentPartName, splittedFilePart,
                    mahasenResource, nodeIp);
            uploadThread = new Thread(uploadWorker);
            uploadWorker.setJobId(jobId);

            //keep track of uploading parts
            AtomicInteger noOfParts = new AtomicInteger(0);
            storedNoOfParts.put(jobId, noOfParts);

            uploadThread.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    final BlockFlag blockFlag = new BlockFlag(true, 6000);
    while (true) {

        AtomicInteger noOfParts = storedNoOfParts.get(jobId);
        if (noOfParts.get() == fileParts.size()) {
            storedNoOfParts.remove(uploadThread.getId());
            System.out.println("uploaded no of parts " + noOfParts + "out of " + fileParts.size() + "going out "
                    + "#####Thread id:" + uploadThread.getId());
            blockFlag.unblock();
            break;
        }

        if (blockFlag.isBlocked()) {
            mahasenManager.getNode().getEnvironment().getTimeSource().sleep(10);
        } else {
            throw new MahasenException("Time out in uploading " + file.getName());
        }
    }

    mahasenManager.insertIntoDHT(resourceId, mahasenResource, false);
    mahasenManager.insertTreeMapIntoDHT(resourceId, mahasenResource, false);

    ReplicateRequestStarter replicateStarter = new ReplicateRequestStarter(mahasenResource);
    Thread replicateThread = new Thread(replicateStarter);
    replicateThread.start();
}

From source file:com.ba.forms.foodBill.BAFoodBillAction.java

public ActionForward betBookingMastDets(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    JSONObject json = new JSONObject();

    try {//from   ww w. j  a  v a2  s  . c  om
        logger.info(" betBookingMastDets method starts here");
        String roomId = request.getParameter("roomId");

        HashMap hashMpReceiptDet = BAFoodBillFactory.getInstanceOfBAFoodBillFactory()
                .getBookingMasterDets(roomId);

        json.put("exception", "");
        json.put("ReceiptDets", hashMpReceiptDet);
        json.put("ReceiptExit", hashMpReceiptDet.size());

    } catch (Exception ex) {
        logger.error("The Exception is  :" + ex);
        ex.printStackTrace();
        json.put("exception", BAHandleAllException.exceptionHandler(ex));
    }
    response.getWriter().write(json.toString());
    return null;

}

From source file:mml.handler.scratch.ScratchVersionSet.java

/**
 * Replace our versions with those in other
 * @param other the other ScratchVersionSet
 *///from w w  w. ja v  a  2 s .  c  o  m
public void upsert(ScratchVersionSet other) {
    HashMap<String, ScratchVersion> map = new HashMap<String, ScratchVersion>();
    for (int i = 0; i < this.list.length; i++) {
        ScratchVersion sv = this.list[i];
        map.put(sv.version, sv);
    }
    for (int i = 0; i < other.list.length; i++) {
        map.put(other.list[i].version, other.list[i]);
    }
    ScratchVersion[] newList = new ScratchVersion[map.size()];
    Collection coll = map.values();
    int i = 0;
    Iterator iter = coll.iterator();
    while (iter.hasNext()) {
        ScratchVersion sv = (ScratchVersion) iter.next();
        newList[i++] = sv;
    }
    this.list = newList;
}

From source file:gridool.db.partitioning.phihash.DBPartitioningJob.java

@Override
public GridTaskResultPolicy result(GridTaskResult result) throws GridException {
    final HashMap<GridNode, MutableLong> processed = result.getResult();
    if (processed == null || processed.isEmpty()) {
        Exception err = result.getException();
        if (err == null) {
            throw new GridException("failed to execute a task: " + result.getTaskId());
        } else {/*from w  w w  .ja  va2s.c o m*/
            throw new GridException("failed to execute a task: " + result.getTaskId(), err);
        }
    }
    if (LOG.isInfoEnabled()) {
        final long elapsed = System.currentTimeMillis() - started;
        final int numNodes = processed.size();
        final long[] counts = new long[numNodes];
        long maxRecords = -1L, minRecords = -1L;
        int i = 0;
        for (final MutableLong e : processed.values()) {
            long v = e.longValue();
            numProcessed += v;
            counts[i++] = v;
            maxRecords = Math.max(v, maxRecords);
            minRecords = (minRecords == -1L) ? v : Math.min(v, minRecords);
        }
        double mean = numProcessed / numNodes;
        double sd = MathUtils.stddev(counts);
        double avg = numProcessed / numNodes;
        float percent = ((float) (sd / mean)) * 100.0f;
        LOG.info("Job executed in " + DateTimeFormatter.formatTime(elapsed)
                + ".\n\tSTDDEV of data distribution in " + numNodes + " nodes: " + sd + " (" + percent
                + "%)\n\tAverage records: " + PrintUtils.formatNumber(avg) + " [ total: " + numProcessed
                + ", max: " + maxRecords + ", min: " + minRecords + " ]");
    } else {
        for (MutableLong e : processed.values()) {
            numProcessed += e.intValue();
        }
    }
    return GridTaskResultPolicy.CONTINUE;
}

From source file:com.uber.hoodie.cli.commands.StatsCommand.java

@CliCommand(value = "stats filesizes", help = "File Sizes. Display summary stats on sizes of files")
public String fileSizeStats(@CliOption(key = {
        "partitionPath" }, help = "regex to select files, eg: 2016/08/02", unspecifiedDefaultValue = "*/*/*") final String globRegex)
        throws IOException {

    FileSystem fs = HoodieCLI.fs;
    String globPath = String.format("%s/%s/*", HoodieCLI.tableMetadata.getBasePath(), globRegex);
    FileStatus[] statuses = fs.globStatus(new Path(globPath));

    // max, min, #small files < 10MB, 50th, avg, 95th
    final int MAX_FILES = 1000000;
    Histogram globalHistogram = new Histogram(new UniformReservoir(MAX_FILES));
    HashMap<String, Histogram> commitHistoMap = new HashMap<String, Histogram>();
    for (FileStatus fileStatus : statuses) {
        String commitTime = FSUtils.getCommitTime(fileStatus.getPath().getName());
        long sz = fileStatus.getLen();
        if (!commitHistoMap.containsKey(commitTime)) {
            commitHistoMap.put(commitTime, new Histogram(new UniformReservoir(MAX_FILES)));
        }// w  w  w . jav  a2 s  .  c  o  m
        commitHistoMap.get(commitTime).update(sz);
        globalHistogram.update(sz);
    }

    String[][] rows = new String[commitHistoMap.size() + 1][];
    int ind = 0;
    for (String commitTime : commitHistoMap.keySet()) {
        Snapshot s = commitHistoMap.get(commitTime).getSnapshot();
        rows[ind++] = printFileSizeHistogram(commitTime, s);
    }
    Snapshot s = globalHistogram.getSnapshot();
    rows[ind++] = printFileSizeHistogram("ALL", s);

    return HoodiePrintHelper.print(
            new String[] { "CommitTime", "Min", "10th", "50th", "avg", "95th", "Max", "NumFiles", "StdDev" },
            rows);
}

From source file:com.microsoft.windowsazure.mobileservices.authentication.LoginManager.java

/**
 * Normalizes the parameters to add it to the Url
 *
 * @param parameters list of the parameters.
 * @return the parameters to add to the url.
 *//*ww  w. j  a  v a 2  s . co m*/
private String normalizeParameters(HashMap<String, String> parameters) {

    String result = "";

    if (parameters != null && parameters.size() > 0) {
        for (Map.Entry<String, String> parameter : parameters.entrySet()) {

            if (result == "") {
                result = "?";
            } else {
                result += "&";
            }

            result += parameter.getKey() + "=" + parameter.getValue();
        }
    }

    return result;
}