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.mexconabio.MexConvToSQL.java

/**
 * // w  ww .  ja va2s  .c o m
 */
public void convert(final String databaseName, final String tableName, final String srcFileName,
        final String xmlFileName) {
    String[] months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", };
    HashMap<String, Integer> monthHash = new HashMap<String, Integer>();
    for (String mn : months) {
        monthHash.put(mn, monthHash.size() + 1);
    }

    Connection conn = null;
    Statement stmt = null;
    try {
        conn = DriverManager.getConnection(
                "jdbc:mysql://localhost/" + databaseName + "?characterEncoding=UTF-8&autoReconnect=true",
                "root", "root");
        stmt = conn.createStatement();

        FMPCreateTable fmpInfo = new FMPCreateTable(tableName, null, true);
        fmpInfo.process(xmlFileName);

        boolean doCreateTable = true;
        if (doCreateTable) {
            processFieldSizes(fmpInfo, srcFileName);

            PrintWriter pw = new PrintWriter(new File("fields.txt"));
            int i = 0;
            for (FieldDef fd : fmpInfo.getFields()) {
                pw.println(i + " " + fd.getName() + "\t" + fd.getType() + "\t" + fd.isDouble());
                i++;
            }
            pw.close();

            BasicSQLUtils.update(conn, fmpInfo.dropTableStr());

            String sqlCreateTable = fmpInfo.createTableStr();

            BasicSQLUtils.update(conn, sqlCreateTable);

            System.out.println(sqlCreateTable);
        }

        String prepSQL = fmpInfo.getPrepareStmtStr(true, true);
        System.out.println(prepSQL);
        pStmt = conn.prepareStatement(prepSQL);

        Vector<FieldDef> fieldDefs = fmpInfo.getFields();

        int rowCnt = 0;
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(srcFileName)));
        String str = in.readLine();
        str = in.readLine();
        while (str != null) {
            String line = str;
            char sep = '`';
            String sepStr = "";
            for (char c : seps) {
                if (line.indexOf(c) == -1) {
                    sepStr += c;
                    sep = c;
                    break;
                }
            }
            str = StringUtils.replace(str.substring(1, str.length() - 1), "\",\"", sepStr);
            Vector<String> fields = split(str, sep);

            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

            int col = 1;
            int inx = 0;
            for (String fld : fields) {
                String value = fld.trim();
                FieldDef fd = fieldDefs.get(inx);

                switch (fd.getType()) {
                case eText:
                case eMemo: {
                    if (value.length() > 0) {
                        //value = FMPCreateTable.convertFromUTF8(value);
                        if (value.length() <= fd.getMaxSize()) {
                            pStmt.setString(col, value);
                        } else {
                            System.err.println(String.format("The data for `%s` max(%d) is too big %d",
                                    fd.getName(), fd.getMaxSize(), value.length()));
                            pStmt.setString(col, null);
                        }
                    } else {
                        pStmt.setString(col, null);
                    }
                }
                    break;

                case eNumber: {
                    if (StringUtils.isNotEmpty(value)) {
                        String origValue = value;
                        String val = value.charAt(0) == '' ? value.substring(1) : value;
                        val = val.charAt(0) == '-' ? val.substring(1) : val;
                        val = val.indexOf('.') > -1 ? StringUtils.replace(val, ".", "") : val;
                        val = val.indexOf('') > -1 ? StringUtils.replace(val, "", "") : val;

                        if (StringUtils.isNumericSpace(val)) {
                            if (fd.isDouble()) {
                                pStmt.setDouble(col, Double.parseDouble(val));
                            } else {
                                pStmt.setInt(col, Integer.parseInt(val));
                            }
                        } else if (val.startsWith("ca. ")) {
                            pStmt.setInt(col, Integer.parseInt(val.substring(4)));
                        } else if (val.startsWith("ca ")) {
                            pStmt.setInt(col, Integer.parseInt(val.substring(3)));
                        } else {
                            System.err.println(col + " Bad Number val[" + val + "] origValue[" + origValue
                                    + "] " + fieldDefs.get(col - 1).getName());
                            pStmt.setObject(col, null);
                        }
                    } else {
                        pStmt.setDate(col, null);
                    }
                }
                    break;

                case eTime: {
                    Time time = null;
                    try {
                        time = Time.valueOf(value);
                    } catch (Exception ex) {
                    }
                    pStmt.setTime(col, time);
                }
                    break;

                case eDate: {
                    String origValue = value;
                    try {
                        if (StringUtils.isNotEmpty(value) && !value.equals("?") && !value.equals("-")) {
                            int len = value.length();
                            if (len == 8 && value.charAt(1) == '-' && value.charAt(3) == '-') // 0-9-1886
                            {
                                String dayStr = value.substring(0, 1);
                                String monStr = value.substring(2, 3);
                                if (StringUtils.isNumeric(dayStr) && StringUtils.isNumeric(monStr)) {
                                    String year = value.substring(4);
                                    int day = Integer.parseInt(dayStr);
                                    int mon = Integer.parseInt(monStr);
                                    if (day == 0)
                                        day = 1;
                                    if (mon == 0)
                                        mon = 1;

                                    value = String.format("%02d-%02d-%s", day, mon, year);
                                } else {
                                    value = StringUtils.replaceChars(value, '.', ' ');
                                    String[] toks = StringUtils.split(value, ' ');
                                    if (toks.length == 3) {
                                        String dyStr = toks[0];
                                        String mnStr = toks[1];
                                        String yrStr = toks[2];
                                        if (StringUtils.isNumeric(mnStr) && StringUtils.isNumeric(dyStr)
                                                && StringUtils.isNumeric(yrStr)) {
                                            int day = Integer.parseInt(dyStr);
                                            int mon = Integer.parseInt(mnStr);
                                            int year = Integer.parseInt(yrStr);
                                            if (day == 0)
                                                day = 1;
                                            if (mon == 0)
                                                mon = 1;

                                            value = String.format("%02d-%02d-%04d", day, mon, year);
                                        } else {
                                            System.err.println(
                                                    col + " Bad Date#[" + value + "]  [" + origValue + "]\n");
                                        }
                                    } else {
                                        System.err.println(
                                                col + " Bad Date#[" + value + "]  [" + origValue + "]\n");
                                    }
                                }

                            } else if (len == 8 && (value.charAt(3) == '-' || value.charAt(3) == ' ')) // Apr-1886
                            {
                                String monStr = value.substring(0, 3);
                                Integer month = monthHash.get(monStr);
                                String year = value.substring(4);
                                if (month != null && StringUtils.isNumeric(year)) {
                                    value = String.format("01-%02d-%s", month, year);
                                } else {
                                    value = StringUtils.replaceChars(value, '.', ' ');
                                    String[] toks = StringUtils.split(value, ' ');
                                    if (toks.length == 3) {
                                        String dyStr = toks[0];
                                        String mnStr = toks[1];
                                        String yrStr = toks[2];
                                        if (StringUtils.isNumeric(mnStr) && StringUtils.isNumeric(dyStr)
                                                && StringUtils.isNumeric(yrStr)) {
                                            int day = Integer.parseInt(dyStr);
                                            int mon = Integer.parseInt(mnStr);
                                            int yr = Integer.parseInt(yrStr);
                                            if (day == 0)
                                                day = 1;
                                            if (mon == 0)
                                                mon = 1;

                                            value = String.format("%02d-%02d-%04d", day, mon, yr);
                                        } else {
                                            System.err.println(
                                                    col + " Bad Date#[" + value + "]  [" + origValue + "]\n");
                                        }
                                    } else {
                                        System.err.println(
                                                col + " Bad Date#[" + value + "]  [" + origValue + "]\n");
                                    }
                                }

                            } else if ((len == 11 && value.charAt(2) == '-' && value.charAt(6) == '-') || // 10-May-1898
                                    (len == 10 && value.charAt(1) == '-' && value.charAt(5) == '-')) //  7-May-1898
                            {
                                boolean do11 = len == 11;
                                String dayStr = value.substring(0, do11 ? 2 : 1);
                                String monStr = value.substring(do11 ? 3 : 2, do11 ? 6 : 5);

                                Integer month = monthHash.get(monStr);
                                String year = value.substring(do11 ? 7 : 6);
                                if (month != null && StringUtils.isNumeric(dayStr)
                                        && StringUtils.isNumeric(year)) {
                                    int day = Integer.parseInt(dayStr);
                                    if (day == 0)
                                        day = 1;
                                    value = String.format("%02d-%02d-%s", day, month, year);

                                } else {
                                    System.err
                                            .println(col + " Bad Date^[" + value + "]  [" + origValue + "]\n");
                                }
                            } else if (len == 4) {
                                if (StringUtils.isNumeric(value)) {
                                    value = "01-01-" + value;

                                } else if (value.equalsIgnoreCase("s.d.") || value.equalsIgnoreCase("n.d.")
                                        || value.equalsIgnoreCase("s.n.")) {
                                    value = null;
                                }
                            } else if (StringUtils.contains(value, "/")) {
                                value = StringUtils.replace(value, "/", "-");

                            } else if (StringUtils.contains(value, " ")) {
                                value = StringUtils.replace(value, " ", "-");
                            }
                            pStmt.setDate(col,
                                    StringUtils.isNotEmpty(value)
                                            ? new java.sql.Date(sdf.parse(value).getTime())
                                            : null);
                        } else {
                            pStmt.setDate(col, null);
                        }
                    } catch (Exception ex) {
                        System.err.println(col + " Bad Date[" + value + "]  [" + origValue + "]\n" + str);
                        pStmt.setDate(col, null);
                    }
                }
                    break;

                default: {
                    System.err.println("Col: " + col + "  Error - " + fd.getType());
                }
                }
                inx++;
                col++;
            }
            pStmt.execute();
            str = in.readLine();
            rowCnt++;
            if (rowCnt % 1000 == 0) {
                System.out.println(rowCnt);
            }
        }
        in.close();

    } catch (Exception ex) {
        ex.printStackTrace();

    } finally {
        try {
            stmt.close();
            conn.close();
            pStmt.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.clustercontrol.jobmanagement.factory.FullJob.java

public static void initJobMstCache() {
    long startTime = System.currentTimeMillis();
    HashMap<String, Map<String, JobMstEntity>> jobMstCache = new HashMap<String, Map<String, JobMstEntity>>();
    JpaTransactionManager jtm = null;//from  w w w  . j  a  v  a 2  s .  com
    try {
        jtm = new JpaTransactionManager();
        EntityManager em = jtm.getEntityManager();
        em.clear();
        List<JobMstEntity> jobunits = ((HinemosEntityManager) em)
                .createNamedQuery("JobMstEntity.findByParentJobunitIdAndJobId", JobMstEntity.class,
                        ObjectPrivilegeMode.NONE)
                .setParameter("parentJobunitId", CreateJobSession.TOP_JOBUNIT_ID)
                .setParameter("parentJobId", CreateJobSession.TOP_JOB_ID).getResultList();

        for (JobMstEntity jobunit : jobunits) {
            String jobunitId = jobunit.getId().getJobunitId();
            List<JobMstEntity> jobs = ((HinemosEntityManager) em)
                    .createNamedQuery("JobMstEntity.findByJobunitId", JobMstEntity.class,
                            ObjectPrivilegeMode.NONE)
                    .setParameter("jobunitId", jobunitId).getResultList();
            Map<String, JobMstEntity> jobunitMap = new HashMap<String, JobMstEntity>();
            for (JobMstEntity job : jobs) {
                String jobId = job.getId().getJobId();
                jobunitMap.put(jobId, job);
            }
            jobMstCache.put(jobunitId, jobunitMap);
        }
        m_log.info("init jobMstCache " + (System.currentTimeMillis() - startTime) + "ms. size="
                + jobMstCache.size());
        for (Map.Entry<String, Map<String, JobMstEntity>> entry : jobMstCache.entrySet()) {
            m_log.info("jobMstCache key(jobunitId)=" + entry.getKey() + " size=" + entry.getValue().size());
        }

        storeJobMstCache(jobMstCache);
    } finally {
        if (jtm != null) {
            jtm.close();
        }
    }
}

From source file:org.fornax.cartridges.sculptor.framework.drools.DroolsAdvice.java

private void applyCompanyPolicy(HashMap<String, Object> objects, HashMap<String, Object> globals) {
    if (kagent == null) {
        synchronized (DroolsAdvice.class) {
            if (kagent == null) {
                KnowledgeAgent unconfigAgent = KnowledgeAgentFactory.newKnowledgeAgent("CompanyPolicyAgent");
                unconfigAgent.applyChangeSet(ResourceFactory.newClassPathResource(getDroolsRuleSet()));

                ResourceChangeScannerConfiguration sconf = ResourceFactory.getResourceChangeScannerService()
                        .newResourceChangeScannerConfiguration();
                sconf.setProperty("drools.resource.scanner.interval", Integer.toString(getUpdateInterval()));
                ResourceFactory.getResourceChangeScannerService().configure(sconf);
                ResourceFactory.getResourceChangeNotifierService().start();
                ResourceFactory.getResourceChangeScannerService().start();

                kagent = unconfigAgent;/*from   ww w  .  j a  v a  2  s  . c  o m*/
            }
        }
    }

    StatelessKnowledgeSession slSession = kagent.newStatelessKnowledgeSession();
    List<Command<?>> cmds = new ArrayList<Command<?>>();
    if (globals != null && globals.size() > 0) {
        for (Iterator<String> keys = globals.keySet().iterator(); keys.hasNext();) {
            String key = keys.next();
            cmds.add(CommandFactory.newSetGlobal(key, globals.get(key)));
        }
    }

    if (objects != null && objects.size() > 0) {
        for (Iterator<String> keys = objects.keySet().iterator(); keys.hasNext();) {
            String key = keys.next();
            cmds.add(CommandFactory.newInsert(objects.get(key), key));
        }
    }
    // For stateless sesion is automatic
    // cmds.add(CommandFactory.newFireAllRules());

    slSession.execute(CommandFactory.newBatchExecution(cmds));
}

From source file:org.montanafoodhub.base.get.ProducerHub.java

protected HashMap<String, Producer> readFromFile(Context context) {
    HashMap<String, Producer> myProducerMap = new HashMap<String, Producer>();
    try {//from   ww  w.ja va 2  s  . co m
        // getItem the time the file was last changed here
        File myFile = new File(context.getFilesDir() + "/" + fileName);
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        String lastRefreshTSStr = sdf.format(myFile.lastModified());
        Log.w(HubInit.logTag, "Using file (" + fileName + ") last modified on : " + lastRefreshTSStr);
        lastRefreshTS = sdf.getCalendar();

        // create products from the file here
        InputStream inputStream = context.openFileInput(fileName);
        if (inputStream != null) {
            parseCSV(myProducerMap, inputStream);
        }
        inputStream.close();
    } catch (FileNotFoundException e) {
        Log.e(HubInit.logTag, "File  (" + fileName + ") not found: " + e.toString());
    } catch (IOException e) {
        Log.e(HubInit.logTag, "Can not read file  (" + fileName + ") : " + e.toString());
    }
    Log.w(HubInit.logTag, "Number of producers loaded: " + myProducerMap.size());
    return myProducerMap;
}

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

/**
 * Create a scratchversionset from a database record
 * @param resource the dbase resource fetched from the database
 * @param dbase the dbase collection name it was from
 */// w  w  w.  ja  v  a 2s . c o m
public ScratchVersionSet(String resource, String dbase) {
    parseResource(resource);
    if (format.contains("MVD")) {
        MVD mvd = MVDFile.internalise(body);
        HashMap<String, ScratchVersion> map = new HashMap<String, ScratchVersion>();
        String[] all = listVersions(mvd);
        for (short i = 1; i <= mvd.numVersions(); i++) {
            String vid = mvd.getVersionId(i);
            String localLongName = mvd.getLongNameForVersion(i);
            // the ONLY names in memory are upgraded ones
            String layerName = Layers.upgradeLayerName(all, vid);
            int num = ScratchVersion.layerNumber(layerName);
            String shortName = Layers.stripLayer(layerName);
            ScratchVersion sv = map.get(shortName);
            char[] data = mvd.getVersion(i);
            if (sv == null) {
                sv = new ScratchVersion(shortName, localLongName, docid, dbase, null, false);
                sv.addLayer(data, num);
                map.put(shortName, sv);
            } else if (!sv.containsLayer(num))
                sv.addLayer(data, num);
        }
        // convert to list
        list = new ScratchVersion[map.size()];
        Collection<ScratchVersion> coll = map.values();
        coll.toArray(list);
    } else // single version/layer
    {
        if (version1 == null)
            version1 = "/base";
        if (docid != null && body != null) {
            String longName = null;
            if (otherFields.containsKey(JSONKeys.LONGNAME))
                longName = (String) otherFields.get(JSONKeys.LONGNAME);
            if (otherFields.containsKey(JSONKeys.DESCRIPTION))
                longName = (String) otherFields.get(JSONKeys.DESCRIPTION);
            if (longName == null)
                longName = "Version " + version1;
            ScratchVersion sv = new ScratchVersion(version1, longName, docid, dbase, null, false);
            sv.addLayer(body.toCharArray(), Integer.MAX_VALUE);
            appendToList(sv);
        }
    }
}

From source file:edu.utexas.cs.tactex.MarketManagerTest.java

/**
 * Test //from  ww  w  .  j  a  v a 2  s. c o  m
 */
@Test
public void test_initialize() {
    // initialize with arbitrary values

    ReflectionTestUtils.setField(marketManagerService, "marketTotalMwh", 1234.0);
    ReflectionTestUtils.setField(marketManagerService, "marketTotalPayments", 1234.0);
    ReflectionTestUtils.setField(marketManagerService, "lastOrder", null);
    ReflectionTestUtils.setField(marketManagerService, "marketMWh", null);
    ReflectionTestUtils.setField(marketManagerService, "marketPayments", null);
    ReflectionTestUtils.setField(marketManagerService, "predictedUsage", null);
    ReflectionTestUtils.setField(marketManagerService, "actualUsage", null);
    ReflectionTestUtils.setField(marketManagerService, "orderbooks", null);
    ReflectionTestUtils.setField(marketManagerService, "maxTradePrice", 1234);
    ReflectionTestUtils.setField(marketManagerService, "minTradePrice", 1234);
    ReflectionTestUtils.setField(marketManagerService, "supportingBidGroups", null);
    ReflectionTestUtils.setField(marketManagerService, "dpCache2013", null);
    ReflectionTestUtils.setField(marketManagerService, "shortBalanceTransactionsData", null);
    ReflectionTestUtils.setField(marketManagerService, "surplusBalanceTransactionsData", null);

    // initialize should set all fields correctly
    marketManagerService.initialize(brokerContext);

    // get fields from object and verify they are initialized correctly

    double marketTotalMwh = (Double) ReflectionTestUtils.getField(marketManagerService, "marketTotalMwh");
    assertEquals("marketTotalMwh", 0.0, marketTotalMwh, 1e-6);

    double marketTotalPayments = (Double) ReflectionTestUtils.getField(marketManagerService,
            "marketTotalPayments");
    assertEquals("marketTotalPayments", 0.0, marketTotalPayments, 1e-6);

    // map should be initialized to empty
    @SuppressWarnings("unchecked")
    HashMap<Integer, Order> lastOrder = (HashMap<Integer, Order>) ReflectionTestUtils
            .getField(marketManagerService, "lastOrder");
    assertNotNull("lastOrder", lastOrder);
    assertEquals("lastOrder.length", 0, lastOrder.size());

    // arrays are not null, of the right size, and initialized 
    // with 0's
    int usageRecordLength = configuratorFactoryService.CONSTANTS.USAGE_RECORD_LENGTH();
    double[] marketMWh = (double[]) ReflectionTestUtils.getField(marketManagerService, "marketMWh");
    assertNotNull("marketMWh", marketMWh);
    assertEquals("length of marketMWh", usageRecordLength, marketMWh.length);
    assertArrayEquals(new double[usageRecordLength], marketMWh, 1e-6);

    double[] marketPayments = (double[]) ReflectionTestUtils.getField(marketManagerService, "marketPayments");
    assertNotNull("marketPayments", marketPayments);
    assertEquals("length of marketPayments", usageRecordLength, marketPayments.length);
    assertArrayEquals(new double[usageRecordLength], marketPayments, 1e-6);

    double[][] predictedUsage = (double[][]) ReflectionTestUtils.getField(marketManagerService,
            "predictedUsage");
    assertNotNull("predictedUsage", predictedUsage);
    assertEquals("predictedUsage.size", 24, predictedUsage.length);
    for (double[] p : predictedUsage) {
        assertNotNull("predictedUsage[i]", p);
        assertEquals("p.size", 2500, p.length);
        assertEquals("p[i]", (Integer) 0, p[0], 1e-6);
    }

    double[] actualUsage = (double[]) ReflectionTestUtils.getField(marketManagerService, "actualUsage");
    assertNotNull("actualUsage", actualUsage);
    assertEquals("actualUsage.size", 2500, actualUsage.length);
    assertEquals("actualUsage[i]", 0, actualUsage[0], 1e-6);

    @SuppressWarnings("unchecked")
    HashMap<Integer, Orderbook> orderbooks = (HashMap<Integer, Orderbook>) ReflectionTestUtils
            .getField(marketManagerService, "orderbooks");
    assertNotNull("orderbooks", orderbooks);
    assertEquals("orderbooks.length", 0, orderbooks.size());

    double maxTradePrice = (Double) ReflectionTestUtils.getField(marketManagerService, "maxTradePrice");
    assertEquals("maxTradePrice", -Double.MAX_VALUE, maxTradePrice, 1e-6);

    double minTradePrice = (Double) ReflectionTestUtils.getField(marketManagerService, "minTradePrice");
    assertEquals("minTradePrice", Double.MAX_VALUE, minTradePrice, 1e-6);

    @SuppressWarnings("unchecked")
    TreeMap<Integer, TreeMap<Double, Double>> supportingBidGroups = (TreeMap<Integer, TreeMap<Double, Double>>) ReflectionTestUtils
            .getField(marketManagerService, "supportingBidGroups");
    assertNotNull("supportingBidGroups", supportingBidGroups);
    assertEquals("supportingBidGroups.length", 0, supportingBidGroups.size());

    MarketManagerService.DPCache dpCache2013 = (MarketManagerService.DPCache) ReflectionTestUtils
            .getField(marketManagerService, "dpCache2013");
    assertNotNull("dpCache2013", dpCache2013);
    @SuppressWarnings("unchecked")
    ArrayList<Double> bestActions = (ArrayList<Double>) ReflectionTestUtils.getField(dpCache2013,
            "bestActions");
    assertNotNull("dpCache2013.bestActions", bestActions);
    @SuppressWarnings("unchecked")
    ArrayList<Double> stateValues = (ArrayList<Double>) ReflectionTestUtils.getField(dpCache2013,
            "stateValues");
    assertNotNull("dpCache2013.stateValues", stateValues);
    @SuppressWarnings("unchecked")
    HashMap<Integer, Boolean> validTimeslots = (HashMap<Integer, Boolean>) ReflectionTestUtils
            .getField(dpCache2013, "validTimeslots");
    assertNotNull("dpCache2013.validTimeslots", validTimeslots);
    assertEquals("dpCache2013.bestActions", 0, dpCache2013.getBestActions().size());
    assertEquals("dpCache2013.stateValues", 0, dpCache2013.getStateValues().size());
    assertEquals("dpCache2013.valid(ts)", false, dpCache2013.isValid(currentTimeslot.getSerialNumber()));

    // map should be initialized to empty
    @SuppressWarnings("unchecked")
    ArrayList<PriceMwhPair> shortBalanceTransactionsData = (ArrayList<PriceMwhPair>) ReflectionTestUtils
            .getField(marketManagerService, "shortBalanceTransactionsData");
    assertNotNull("shortBalanceTransactionsData", shortBalanceTransactionsData);
    assertEquals("shortBalanceTransactionsData.length", 0, shortBalanceTransactionsData.size());

    @SuppressWarnings("unchecked")
    ArrayList<PriceMwhPair> surplusBalanceTransactionsData = (ArrayList<PriceMwhPair>) ReflectionTestUtils
            .getField(marketManagerService, "surplusBalanceTransactionsData");
    assertNotNull("surplusBalanceTransactionsData", surplusBalanceTransactionsData);
    assertEquals("surplusBalanceTransactionsData.length", 0, surplusBalanceTransactionsData.size());

}

From source file:net.sf.jvifm.ui.shell.QuickRunShell.java

@SuppressWarnings("all")
public TipOption[] getCompletionOptions(String text) {

    HashMap optionMap = new HashMap();
    String[] options = AutoCompleteUtil.getFileCompleteOptions(pwd, text, false);
    addOptions(optionMap, buildPathOptions(options));

    options = AutoCompleteUtil.getBookmarkFileOptions(text);
    addOptions(optionMap, buildPathOptions(options));

    options = AutoCompleteUtil.getExeFileCompleteOptions(text);
    addOptions(optionMap, buildPathOptions(options));

    ArrayList list = new ArrayList();
    Shortcut[] links = AutoCompleteUtil.getShortcutsCompleteList2(text);
    if (links != null) {
        for (int i = 0; i < links.length; i++) {
            TipOption tipOption = new TipOption();
            tipOption.setName(links[i].getName());
            tipOption.setExtraInfo(links[i].getText());
            tipOption.setTipType("shortcut");
            list.add(tipOption);// w w w  . ja  va 2s .co m
        }
    }
    addOptions(optionMap, list);

    TipOption[] result = new TipOption[optionMap.size()];
    int i = 0;
    for (Iterator it = optionMap.values().iterator(); it.hasNext();) {
        result[i++] = (TipOption) it.next();

    }
    return result;
}

From source file:com.globalsight.connector.mindtouch.util.MindTouchHelper.java

/**
 * Put translated properties to MindTouch server page.
 * /*from ww  w.  j av  a  2  s . c o m*/
 * @param tagsTrgFile
 * @param pageInfo
 * @param targetLocale
 */
public void putPageProperties(File propertiesTrgFile, MindTouchPageInfo pageInfo, String sourceLocale,
        String targetLocale) {
    if (!isTargetServerExist(targetLocale) && !mtc.getIsPostToSourceServer()) {
        return;
    }

    CloseableHttpClient httpClient = getHttpClient();
    HttpResponse response = null;
    String path = null;
    String url = null;
    try {
        url = getPutServerUrl(targetLocale);
        path = getNewPath(pageInfo, sourceLocale, targetLocale);
        // To add properties to page, the page must exist. Should ensure the
        // page has been created before this. The loop waiting should not
        // happen actually.
        int count = 0;
        while (count < 5 && getPageInfo(url, path) == null) {
            count++;
            Thread.sleep(1000);
        }

        // Use Etag from target server if exists.
        HashMap<String, String> etagMap = getePropertiesEtagMap(getPageProperties(url, path));
        if (etagMap.size() == 0) {
            etagMap = getePropertiesEtagMap(getPageProperties(mtc.getUrl(), path));
        }

        url += "/@api/deki/pages/=" + path + "/properties";
        HttpPut httpput = getHttpPut(url, targetLocale);

        String content = FileUtil.readFile(propertiesTrgFile, "UTF-8");
        content = getPropertiesContentsXml(content, etagMap);
        StringEntity reqEntity = new StringEntity(content, "UTF-8");
        reqEntity.setContentType("application/xml; charset=UTF-8");
        httpput.setEntity(reqEntity);

        response = httpClient.execute(httpput);

        String entityContent = null;
        if (response.getEntity() != null) {
            entityContent = EntityUtils.toString(response.getEntity());
        }
        if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
            logger.error("Fail to put properties back to MindTouch server for page '" + path + "' : "
                    + entityContent);
        }
    } catch (Exception e) {
        logger.error("Fail to put properties back to MindTouch server for page '" + path + "'.", e);
    } finally {
        consumeQuietly(response);
    }
}

From source file:com.jinglingtec.ijiazu.util.CCPRestSmsSDK.java

/**
 * @param xml//  w ww  . j av a  2s .  c  o  m
 *
 * @return Map
 *
 * @description xml??map
 */
private HashMap<String, Object> xmlToMap(String xml) {
    HashMap<String, Object> map = new HashMap<String, Object>();
    Document doc = null;
    try {
        doc = DocumentHelper.parseText(xml); // XML
        Element rootElt = doc.getRootElement(); // ?
        HashMap<String, Object> hashMap2 = new HashMap<String, Object>();
        for (Iterator i = rootElt.elementIterator(); i.hasNext();) {
            Element e = (Element) i.next();
            if ("statusCode".equals(e.getName()) || "statusMsg".equals(e.getName())) {
                map.put(e.getName(), e.getText());
            } else {
                if ("SubAccount".equals(e.getName()) || "totalCount".equals(e.getName())
                        || "token".equals(e.getName()) || "downUrl".equals(e.getName())) {
                    if (!"SubAccount".equals(e.getName())) {
                        hashMap2.put(e.getName(), e.getText());
                    } else {
                        ArrayList<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String, Object>>();
                        HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                        for (Iterator i2 = e.elementIterator(); i2.hasNext();) {
                            Element e2 = (Element) i2.next();
                            hashMap3.put(e2.getName(), e2.getText());
                            arrayList.add(hashMap3);
                        }
                        hashMap2.put("SubAccount", arrayList);
                    }
                    map.put("data", hashMap2);
                } else {

                    HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                    for (Iterator i2 = e.elementIterator(); i2.hasNext();) {
                        Element e2 = (Element) i2.next();
                        // hashMap2.put(e2.getName(),e2.getText());
                        hashMap3.put(e2.getName(), e2.getText());
                    }
                    if (hashMap3.size() != 0) {
                        hashMap2.put(e.getName(), hashMap3);
                    } else {
                        hashMap2.put(e.getName(), e.getText());
                    }
                    map.put("data", hashMap2);
                }
            }
        }
    } catch (DocumentException e) {
        e.printStackTrace();
        LoggerUtil.error(e.getMessage());
    } catch (Exception e) {
        LoggerUtil.error(e.getMessage());
        e.printStackTrace();
    }
    return map;
}

From source file:com.laxser.blitz.lama.provider.jdbc.JdbcDataAccess.java

private int[] batchUpdate2(String sql, Modifier modifier, List<Map<String, Object>> parametersList) {
    if (parametersList.size() == 0) {
        return new int[0];
    }//w ww . j  a  v  a  2  s.c  o m
    // sql --> args[]
    HashMap<String, List<Object[]>> batches = new HashMap<String, List<Object[]>>();
    // sql --> named args
    HashMap<String, List<Map<String, Object>>> batches2 = new HashMap<String, List<Map<String, Object>>>();
    // sql --> [2,3,6,9] positions of parametersList
    Map<String, List<Integer>> positions = new HashMap<String, List<Integer>>();

    for (int i = 0; i < parametersList.size(); i++) {
        SQLInterpreterResult ir = interpret(sql, modifier, parametersList.get(i));
        List<Object[]> args = batches.get(ir.getSQL());
        List<Integer> position = positions.get(ir.getSQL());
        List<Map<String, Object>> maplist = batches2.get(ir.getSQL());
        if (args == null) {
            args = new LinkedList<Object[]>();
            batches.put(ir.getSQL(), args);
            position = new LinkedList<Integer>();
            positions.put(ir.getSQL(), position);
            maplist = new LinkedList<Map<String, Object>>();
            batches2.put(ir.getSQL(), maplist);
        }
        position.add(i);
        args.add(ir.getParameters());
        maplist.add(parametersList.get(i));
    }
    if (batches.size() == 1) {
        SQLThreadLocal.set(SQLType.WRITE, sql, modifier, parametersList);
        int[] updated = jdbc.batchUpdate(modifier, batches.keySet().iterator().next(),
                batches.values().iterator().next());
        SQLThreadLocal.remove();
        return updated;
    }
    int[] batchUpdated = new int[parametersList.size()];
    for (Map.Entry<String, List<Object[]>> batch : batches.entrySet()) {
        String batchSQL = batch.getKey();
        List<Object[]> values = batch.getValue();
        List<Map<String, Object>> map = batches2.get(batchSQL);
        SQLThreadLocal.set(SQLType.WRITE, sql, modifier, map);
        int[] updated = jdbc.batchUpdate(modifier, batchSQL, values);
        SQLThreadLocal.remove();
        List<Integer> position = positions.get(batchSQL);
        int i = 0;
        for (Integer p : position) {
            batchUpdated[p] = updated[i++];
        }
    }
    return batchUpdated;

}