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:edu.ku.brc.specify.toycode.RegAdder.java

/**
 * @param mv//  w  w w .j  a va2  s .  co  m
 */
private void insertReg(final HashMap<String, String> mv) {
    if (mv.size() > 0) {
        /*
        +------------------+-------------+------+-----+---------+----------------+
        | Field            | Type        | Null | Key | Default | Extra          |
        +------------------+-------------+------+-----+---------+----------------+
        | RegisterID       | int(11)     | NO   | PRI | NULL    | auto_increment | 
        | TimestampCreated | datetime    | NO   |     | NULL    |                | 
        | RegNumber        | varchar(32) | YES  | UNI | NULL    |                | 
        | RegType          | varchar(32) | YES  |     | NULL    |                | 
        +------------------+-------------+------+-----+---------+----------------+
        4 rows in set (0.00 sec)
                
        mysql> describe registeritem;
        +----------------+-------------+------+-----+---------+----------------+
        | Field          | Type        | Null | Key | Default | Extra          |
        +----------------+-------------+------+-----+---------+----------------+
        | RegisterItemID | int(11)     | NO   | PRI | NULL    | auto_increment | 
        | Name           | varchar(32) | NO   |     | NULL    |                | 
        | CountAmt       | int(11)     | YES  |     | NULL    |                | 
        | Value          | varchar(64) | YES  |     | NULL    |                | 
        | RegisterID     | int(11)     | NO   | MUL | NULL    |                | 
        +----------------+-------------+------+-----+---------+----------------+
         */
        try {
            String type = mv.get("reg_type");
            String num = mv.get("reg_number");
            String ip = mv.get("ip");

            boolean isNotLocalIP = ip == null || (!ip.startsWith("129.237.201") && !ip.startsWith("24.124"));

            if (StringUtils.isNotEmpty(type) && StringUtils.isNotEmpty(num) && isNotLocalIP) {

                int numRegNum = BasicSQLUtils.getCountAsInt(
                        String.format("SELECT COUNT(*) FROM register WHERE RegNumber = '%s'", num));
                if (numRegNum > 0) {
                    return;
                }

                Timestamp timeStamp = getTimestamp(mv.get("date"));

                if (timeStamp.getTime() < startDate)
                    return;

                regStmt1.setTimestamp(1, timeStamp);
                regStmt1.setString(2, num);
                regStmt1.setString(3, type);
                regStmt1.setString(4, ip);

                //pStmt.toString();

                if (regStmt1.executeUpdate() == 1) {
                    cnt++;
                    if (cnt % 100 == 0) {
                        System.out.println(cnt);
                    }

                    Integer regId = BasicSQLUtils.getInsertedId(regStmt1);
                    for (String key : mv.keySet()) {
                        String value = mv.get(key);
                        regStmt2.setString(1, key);
                        if (!StringUtils.contains(value, ".") && StringUtils.isNumeric(value)
                                && value.length() < 10) {
                            regStmt2.setInt(2, value.isEmpty() ? 0 : Integer.parseInt(value));
                            regStmt2.setNull(3, java.sql.Types.VARCHAR);

                        } else if (value.length() < STR_SIZE + 1) {
                            regStmt2.setNull(2, java.sql.Types.INTEGER);
                            regStmt2.setString(3, value);

                        } else {
                            String v = value.substring(0, STR_SIZE);
                            System.err.println("Error - On line " + lineNo + " Value[" + value
                                    + "] too big trunccating to[" + v + "]");

                            regStmt2.setNull(2, java.sql.Types.INTEGER);
                            regStmt2.setString(3, v);
                        }
                        regStmt2.setInt(4, regId);

                        //System.out.println(pStmt2.toString());

                        int rv = regStmt2.executeUpdate();
                        if (rv != 1) {
                            for (String k : mv.keySet()) {
                                System.out.println("[" + k + "][" + mv.get(k) + "]");
                            }
                            System.err.println("------------------------ Line No: " + lineNo);
                            throw new RuntimeException("Error insert registeritem for Reg Id: " + regId);
                        }
                    }
                } else {
                    throw new RuntimeException("Error insert register for Reg Type: " + type + "  Num: " + num);
                }
            } else if (isNotLocalIP) {
                System.err.println("------------------------ Line No: " + lineNo);
                System.err.println("Error for Reg Type: [" + type + "]  or Num: [" + num + "] is null.");
            }

        } catch (SQLException ex) {
            for (String k : mv.keySet()) {
                System.out.println("[" + k + "][" + mv.get(k) + "]");
            }
            System.err.println("------------------------ Line No: " + lineNo);
            ex.printStackTrace();
        }
    }
}

From source file:GeneticAlgorithm.SystemToSolve.java

public void solve_ODE_model(double[] parameters, String mem_address)
        throws ModelOverdeterminedException, InstantiationException, IllegalAccessException,
        IllegalArgumentException, NoSuchMethodException, XMLStreamException, IOException {

    if (SteadyState_OR_TimeCourse_data == true) { //solve model for steady state values
        for (int i = 0; i < conditions_list.size(); i++) {
            HashMap Enz_Conc_to_Update = conditions_list.get(i).get_proteins_info();
            HashMap BC_true_Met_to_Update = conditions_list.get(i).get_BCTrue_metabolites_info();

            if (BC_true_Met_to_Update.size() > 0) {
                modelreactions.modExtMet(BC_true_Met_to_Update);
                for (Compound compound : Compounds) {
                    if (compound.getBoundaryCondition() == true) {
                        if (BC_true_Met_to_Update.containsKey(compound.getID()) == true) {
                            compound.setConcentration((double) BC_true_Met_to_Update.get(compound.getID()));
                        }/*from   w ww . j  a  v  a  2s  . co m*/
                    }
                }
            }
            if (Enz_Conc_to_Update.size() > 0) {
                modelreactions.modEnzymes(Enz_Conc_to_Update);
                for (ModelReaction rxn : Reactions) {
                    if (Enz_Conc_to_Update.containsKey(rxn.getEnzyme().getID()) == true) {
                        rxn.getEnzyme()
                                .setConcentration((double) Enz_Conc_to_Update.get(rxn.getEnzyme().getID()));
                    }
                }
            }

            String tmpname = mem_address;
            tmpname += "_" + i + ".xml";

            File tmpxml = new File(tmpname);
            if (tmpxml.exists()) {
                String rando = Double.toHexString(RN(0.01, 10) * RN(0.01, 10)).replaceAll("\\.", "_");
                tmpname += rando;
                tmpxml = new File(tmpname);
            }

            if (BC_true_Met_to_Update.size() > 0 || Enz_Conc_to_Update.size() > 0) {
                modelreactions.exportsbml(tmpxml);
                link = tmpname;
            } else {
                link = originallink;
            }

            sosLIBssSolver steadystateresults = new sosLIBssSolver(Compounds, Reactions, parameters, link);

            if (steadystateresults.solveSS() == true) {
                conditions_list.get(i).store_Solved_metmap(steadystateresults.getSolvedMMap());
                conditions_list.get(i).store_Solved_fluxmap(steadystateresults.getSolvedFMap());
                good_OR_bad_solution_forModel = true;
            } else {
                good_OR_bad_solution_forModel = false;
            }
            tmpxml.delete();

        }

    } else { //solve model for time series output/values
        double[] time = data.returnTime();
        double[] parameter = parameters;
        int activeCompNum = 0;
        for (Compound comp : Compounds) {
            if (comp.getBoundaryCondition() == false) {
                activeCompNum++;
            }
        }

        String[] paranames = modelreactions.getParameterNames();
        String[] reactionID = modelreactions.getReactionID();
        String[] variables = new String[activeCompNum];
        String[] reactionID2 = modelreactions.getReactionID2();

        int count = 0;
        for (Compound comp : Compounds) {
            if (comp.getBoundaryCondition() == false) {
                variables[count] = comp.getID();
                count++;
            }
        }

        TCodesolve ode = new TCodesolve(link, variables, getParametersCount(), paranames, reactionID,
                reactionID2);

        double output[][] = ode.runsolver(parameter, time);

        for (int j = 1; j < variables.length + 1 + reactionID2.length; j++) {
            double[] temparray = new double[time.length];
            for (int k = 0; k < time.length; k++) {
                temparray[k] = output[k][j];
            }
            if ((j - 1) < activeCompNum) {
                TCestMetMap.put(variables[j - 1], temparray);
            } else {
                TCestFluxMap.put(reactionID2[j - activeCompNum - 1], temparray);
            }
        }
    }
}

From source file:com.ba.forms.serviceBillForm.BAServiceBillAction.java

public ActionForward baGet(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    logger.info(" get method starts here");
    JSONObject json = new JSONObject();
    BAServiceBillDTO vo = new BAServiceBillDTO();
    try {//from   www  .j  a  va  2  s .com
        logger.info(" get method starts here");
        String serviceId = request.getParameter("search");
        HashMap hashMpServiceBillfItemDet = BAServiceBillFactory.getInstanceOfBAServiceBillFactory()
                .getServiceBillItemDtls(serviceId);
        json.put("exception", "");
        json.put("ServiceBillDets", hashMpServiceBillfItemDet);
        json.put("ServiceBillExit", hashMpServiceBillfItemDet.size());

        //                 logger.warn("strCurrent PageNo ------------->"+objPageCount);

    } 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:de.ingrid.portal.global.UtilsFileHelper.java

public static HashMap<String, String> getInstallVersion(String path, String title) {
    HashMap<String, String> versionMap = new HashMap<String, String>();
    BufferedReader bufferReader;/*  ww  w  . j  a  v  a  2 s.  c  om*/
    try {
        bufferReader = new BufferedReader(new FileReader(path));
        String input = "";
        while ((input = bufferReader.readLine()) != null) {
            if (input.startsWith("Implementation-Build")) {
                String value = input.split(":")[1].trim();
                if (value.length() > 0) {
                    versionMap.put("svn_version", value);
                }
            } else if (input.startsWith("Implementation-Version")) {
                String value = input.split(":")[1].trim();
                if (value.length() > 0) {
                    versionMap.put("project_version", value);
                }
            } else if (input.startsWith("Build-Timestamp")) {
                String value = input.split(":")[1].trim();
                if (value.length() > 0) {
                    Date date = new Date(Long.valueOf(value));
                    versionMap.put("build_time", date.toString());
                }
            }
        }
    } catch (IOException e) {
        log.error("File not found: " + path);
    }

    if (versionMap.size() > 0) {
        versionMap.put("title", title);
    }
    return versionMap;
}

From source file:com.thoughtworks.go.domain.materials.svn.SvnCommandTest.java

@Test
public void shouldGetSvnInfoAndReturnMapOfUrlToUUID() {
    final String svnInfoOutput = "<?xml version=\"1.0\"?>\n" + "<info>\n" + "<entry\n" + "   kind=\"dir\"\n"
            + "   path=\"project1\"\n" + "   revision=\"27\">\n" + "<url>http://localhost/svn/project1</url>\n"
            + "<repository>\n" + "<root>http://localhost/svn/project1</root>\n"
            + "<uuid>b51fe673-20c0-4205-a07b-5deb54bb09f3</uuid>\n" + "</repository>\n" + "<commit\n"
            + "   revision=\"27\">\n" + "<author>anthill</author>\n"
            + "<date>2012-10-18T07:54:06.487895Z</date>\n" + "</commit>\n" + "</entry>\n" + "</info>";
    final SvnMaterial svnMaterial = mock(SvnMaterial.class);
    when(svnMaterial.getUrl()).thenReturn("http://localhost/svn/project1");
    when(svnMaterial.getUserName()).thenReturn("user");
    when(svnMaterial.getPassword()).thenReturn("password");
    final ConsoleResult consoleResult = mock(ConsoleResult.class);
    when(consoleResult.outputAsString()).thenReturn(svnInfoOutput);
    final HashSet<SvnMaterial> svnMaterials = new HashSet<>();
    svnMaterials.add(svnMaterial);//from ww  w.  j a  va2s  .  c o  m
    final SvnCommand spy = spy(subversion);
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            final CommandLine commandLine = (CommandLine) invocation.getArguments()[0];
            assertThat(commandLine.toString(), containsString(
                    "svn info --xml --username user --password ****** http://localhost/svn/project1"));
            return consoleResult;
        }
    }).when(spy).executeCommand(any(CommandLine.class));
    final HashMap<String, String> urlToRemoteUUIDMap = spy.createUrlToRemoteUUIDMap(svnMaterials);
    assertThat(urlToRemoteUUIDMap.size(), is(1));
    assertThat(urlToRemoteUUIDMap.get("http://localhost/svn/project1"),
            is("b51fe673-20c0-4205-a07b-5deb54bb09f3"));
}

From source file:model.plate.ANATestResult.java

public boolean initROI2(ANASampleInfo sampleInfo, boolean enableWatershed, boolean isSample, boolean only488) {

    final HashMap<DiagnosisConstant.ANA_Titer, ANAPillarInfo> pillarInfoList = sampleInfo.getPillarInfoList();
    if (pillarInfoList == null || pillarInfoList.size() != 6) {
        this.warningMessage.add(WarningMessage.WrongSecondPlateLayout.getId());
        return false;
    }/*from   w  w w  .  ja v a  2s .  c o  m*/
    this.signals = new HashMap<>();
    int step = PlateConstants.BIN_SIZE + 1;
    double[] freqs;
    ANA_ROI_Result roiResult;
    double signal;
    for (DiagnosisConstant.ANA_Titer t : pillarInfoList.keySet()) {
        ANAPillarInfo pillar = pillarInfoList.get(t);

        roiResult = null;
        try {
            roiResult = Drone.pillar2ROI(pillar, enableWatershed, only488);
        } catch (ChipInfoException | IOException ex) {
            Logger.getLogger(ANATestResult.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (roiResult == null) {
            System.out.println(plateID + pillar.getPillarID() + " fail to get ROI");
            continue;
        }
        try {
            signal = roiResult.getSignal125();
            if (signal <= 0) {
                System.out.println(plateID + pillar.getPillarID() + " signal=" + signal);
            }
            signals.put(t, signal);
        } catch (main.java.com.imageProcessException.ROIException ex) {
            this.warningMessage.add(WarningMessage.ANAROIResultNotFound.getId());
        }

        if (isSample) {
            freqs = null;
            try {
                freqs = Drone.freq(roiResult);
                if (step > Drone.waddle(freqs)) {
                    this.t4p = t;
                    this.roi = roiResult;
                    this.pillarPosition = pillar.getPillarID(); // PillarPosition is PillarForPatternPosition, not ReportDilutionPosition
                    this.pixelRatio = roiResult.getCellPixelRatio();
                }
            } catch (ROIException ex) {
                Logger.getLogger(ANATestResult.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
        if (isSample && roi == null) {
            this.warningMessage.add(WarningMessage.ANAROIResultNotFound.getId());
            System.out.println(sampleInfo.getSampleBarcode() + " failed to init ROI for pattern recognition");
            System.out.println();
            return false;
        }

    }
    return true;
}

From source file:ru.apertum.qsystem.reports.formirovators.ResponsesDateReport.java

@Override
public String validate(String driverClassName, String url, String username, String password,
        HttpRequest request, HashMap<String, String> params) {
    //   ?  //  www  .  j a  v  a 2 s .  c  om
    QLog.l().logger().trace("?  \"" + params.toString() + "\".");
    if (params.size() == 2) {
        Date sd;
        Date fd;
        Date fd1;
        try {
            sd = Uses.format_dd_MM_yyyy.parse(params.get("sd"));
            fd = Uses.format_dd_MM_yyyy.parse(params.get("ed"));
            fd1 = DateUtils.addDays(Uses.format_dd_MM_yyyy.parse(params.get("ed")), 1);
        } catch (ParseException ex) {
            return "<br>  ! ? ?   (..).";
        }
        if (!sd.after(fd)) {
            paramMap.put("sd", sd);
            paramMap.put("ed", fd);
            paramMap.put("ed1", fd1);
        } else {
            return "<br>  !     ?.";
        }

    } else {
        return "<br>  !";
    }
    return null;// ? 
}

From source file:amie.keys.CombinationsExplorationNew.java

/**
 *
 * @param ruleToExtendWith// w w w .  ja  v a  2s.co m
 * @param ruleToGraphNewFirstLevel
 * @param ruleToGraphNewLastLevel
 * @param kb
 */
private static void discoverConditionalKeysPerLevel(HashMap<Rule, HashSet<String>> ruleToExtendWith,
        HashMap<Rule, GraphNew> ruleToGraphNewFirstLevel, HashMap<Rule, GraphNew> ruleToGraphNewLastLevel) {
    HashMap<Rule, GraphNew> ruleToGraphNewThisLevel = new HashMap<>();
    for (Rule currentRule : ruleToExtendWith.keySet()) {
        for (String conditionProperty : ruleToExtendWith.get(currentRule)) {
            if (Utilities.getRelationIds(currentRule, property2Id).last() > property2Id
                    .get(conditionProperty)) {
                GraphNew graph = ruleToGraphNewLastLevel.get(currentRule);
                GraphNew currentGraphNew = (GraphNew) graph.clone();
                Integer propertyId = property2Id.get(conditionProperty);
                HashSet<Integer> propertiesSet = new HashSet<>();
                propertiesSet.add(propertyId);
                Node node = currentGraphNew.createNode(propertiesSet);
                node.toExplore = false;
                Iterable<Rule> conditions = Utilities.getConditions(currentRule, conditionProperty,
                        (int) support, kb);
                for (Rule conditionRule : conditions) {
                    Rule complementaryRule = getComplementaryRule(conditionRule);
                    if (!ruleToGraphNewFirstLevel.containsKey(complementaryRule)) {
                        // We should never fall in this case
                        for (Rule r : ruleToGraphNewFirstLevel.keySet()) {
                            System.out.println(r.getDatalogBasicRuleString());
                        }
                        System.out.println(complementaryRule.getDatalogBasicRuleString());
                        System.out.println(complementaryRule + " not found in the first level graph");
                    }
                    GraphNew complementaryGraphNew = ruleToGraphNewFirstLevel.get(complementaryRule);
                    GraphNew newGraphNew = (GraphNew) currentGraphNew.clone();
                    HashSet<Integer> conditionProperties = new HashSet<>();
                    conditionProperties.addAll(getRelations(conditionRule, property2Id));
                    conditionProperties.addAll(getRelations(currentRule, property2Id));
                    newGraphNew = mergeGraphNews(newGraphNew, complementaryGraphNew,
                            newGraphNew.topGraphNodes(), conditionProperties);

                    discoverConditionalKeysForComplexConditions(newGraphNew, newGraphNew.topGraphNodes(),
                            conditionRule);
                    ruleToGraphNewThisLevel.put(conditionRule, newGraphNew);
                }
            }
        }
    }
    HashMap<Rule, HashSet<String>> newRuleToExtendWith = new HashMap<>();
    for (Rule conRule : ruleToGraphNewThisLevel.keySet()) {
        GraphNew newGraphNew = ruleToGraphNewThisLevel.get(conRule);
        for (Node node : newGraphNew.topGraphNodes()) {
            HashSet<String> properties = new HashSet<>();
            if (node.toExplore) {
                Iterator<Integer> it = node.set.iterator();
                int prop = it.next();
                String propertyStr = id2Property.get(prop);
                properties.add(propertyStr);
            }
            if (properties.size() != 0) {
                newRuleToExtendWith.put(conRule, properties);
            }
        }
    }

    if (newRuleToExtendWith.size() != 0) {
        discoverConditionalKeysPerLevel(newRuleToExtendWith, ruleToGraphNewFirstLevel, ruleToGraphNewThisLevel);
    }
}

From source file:edu.cornell.mannlib.vedit.controller.BaseEditController.java

protected EditProcessObject createEpo(HttpServletRequest request, boolean forceNew) {
    /* this is actually a bit of a misnomer, because we will reuse an epo
    if an epoKey parameter is passed */
    EditProcessObject epo = null;//from   w ww  . j  a  v  a  2 s  . c  o  m
    HashMap epoHash = getEpoHash(request);
    String existingEpoKey = request.getParameter("_epoKey");
    if (!forceNew && existingEpoKey != null && epoHash.get(existingEpoKey) != null) {
        epo = (EditProcessObject) epoHash.get(existingEpoKey);
        epo.setKey(existingEpoKey);
        epo.setUseRecycledBean(true);
    } else {
        LinkedList epoKeylist = getEpoKeylist(request);
        if (epoHash.size() == MAX_EPOS) {
            try {
                epoHash.remove(epoKeylist.getFirst());
                epoKeylist.removeFirst();
            } catch (Exception e) {
                // see JIRA issue VITRO-340, "Odd exception from backend editing"
                // possible rare concurrency issue here
                log.error("Error removing old EPO", e);
            }
        }
        Random rand = new Random();
        String epoKey = createEpoKey();
        while (epoHash.get(epoKey) != null) {
            epoKey += Integer.toHexString(rand.nextInt());
        }
        epo = new EditProcessObject();
        epoHash.put(epoKey, epo);
        epoKeylist.add(epoKey);
        epo.setKey(epoKey);
        epo.setReferer(
                (forceNew) ? request.getRequestURL().append('?').append(request.getQueryString()).toString()
                        : request.getHeader("Referer"));
        epo.setSession(request.getSession());
    }
    return epo;
}

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

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

    try {//ww w . j av  a2s.co m
        logger.info(" get method starts here");
        String foodId = request.getParameter("search");
        HashMap hashMpFoodBillDet = BAFoodBillFactory.getInstanceOfBAFoodBillFactory().getFoodBillDtls(foodId);
        json.put("exception", "");
        json.put("FoodBillDets", hashMpFoodBillDet);
        json.put("FoodBillExit", hashMpFoodBillDet.size());

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

}