Example usage for java.util Vector get

List of usage examples for java.util Vector get

Introduction

In this page you can find the example usage for java.util Vector get.

Prototype

public synchronized E get(int index) 

Source Link

Document

Returns the element at the specified position in this Vector.

Usage

From source file:edu.ku.brc.specify.toycode.RegPivot.java

/**
 * @param newTblName/*from  ww w  .  jav a2 s  . co m*/
 * @param stmt
 * @param pStmt
 * @param fillSQL
 * @param secInx
 * @param dbFieldTypes
 * @param dbFieldNames
 * @param inxToName
 * @return
 * @throws SQLException
 */
private int fillRegisterTable(final String newTblName, final Statement stmt, final PreparedStatement pStmt,
        final String fillSQL, final int secInx, final Vector<Integer> dbFieldTypes,
        final Vector<String> dbFieldNames, final HashMap<Integer, String> inxToName) throws SQLException {
    System.out.println("Filling Register Table.");

    int instCnt = 0;

    System.out.println(fillSQL);

    ResultSet rs = stmt.executeQuery(fillSQL);
    ResultSetMetaData rsmd = rs.getMetaData();

    HashMap<String, Integer> nameToIndex = new HashMap<String, Integer>();
    for (int c = 1; c <= rsmd.getColumnCount(); c++) {
        nameToIndex.put(rsmd.getColumnName(c), c);
        System.out.println(c + " - " + rsmd.getColumnName(c));
    }

    //int nameInx = nameToIndex.get("i.Name");
    boolean debug = false;

    String prevRegId = null;

    HashMap<String, HashMap<String, Object>> instHash = new HashMap<String, HashMap<String, Object>>();
    HashMap<String, HashMap<String, Object>> divHash = new HashMap<String, HashMap<String, Object>>();
    HashMap<String, HashMap<String, Object>> dspHash = new HashMap<String, HashMap<String, Object>>();
    HashMap<String, HashMap<String, Object>> colHash = new HashMap<String, HashMap<String, Object>>();

    HashMap<String, Object> nameToVals = new HashMap<String, Object>();

    while (rs.next()) {
        String regId = rs.getString(1);
        if (prevRegId == null)
            prevRegId = regId;

        for (int i = 1; i < secInx; i++) {
            if (debug)
                System.out.println("Put: " + dbFieldNames.get(i - 1) + "  " + dbFieldTypes.get(i - 1) + "  = "
                        + rs.getObject(i));
            nameToVals.put(dbFieldNames.get(i - 1), rs.getObject(i));
        }
        String name = rs.getString(secInx);
        name = StringUtils.replace(name, "(", "_");
        name = StringUtils.replace(name, ")", "_");

        if (name.equals("reg_type")) {
            String strVal = (String) rs.getObject(secInx + 2);
            name = strVal + "_number";

            nameToVals.put(name, regId);
            if (debug)
                System.out.println("Put: " + name + " = " + regId);
        } else {
            Integer intVal = (Integer) rs.getObject(secInx + 1);
            String strVal = (String) rs.getObject(secInx + 2);
            nameToVals.put(name, strVal != null ? strVal : intVal);
            if (debug)
                System.out.println("Put: " + name + " = " + intVal + " / " + strVal);
        }

        if (debug)
            System.out.println("-------------------------------------------");

        if (!prevRegId.equals(regId)) {
            String instNum = (String) nameToVals.get("Institution_number");
            String divNum = (String) nameToVals.get("Division_number");
            String dspNum = (String) nameToVals.get("Discipline_number");
            String colNum = (String) nameToVals.get("Collection_number");

            if (StringUtils.isNotEmpty(instNum)) {
                copyHash(instNum, instHash, nameToVals);
            }

            if (StringUtils.isNotEmpty(divNum)) {
                copyHash(divNum, divHash, nameToVals);
            }

            if (StringUtils.isNotEmpty(dspNum)) {
                copyHash(dspNum, dspHash, nameToVals);
            }

            if (StringUtils.isNotEmpty(colNum)) {
                // 1288612353.83
                String cn = (String) nameToVals.get("Collection_number");
                copyHash(colNum, colHash, nameToVals);
            }

            /*{
            System.err.println("ID is empty:");
            for (String key : nameToVals.keySet())
            {
                System.out.println("--: "+key+" = "+nameToVals.get(key));
            }
            System.err.println("===============");
            }*/
            prevRegId = regId;
            nameToVals.clear();
        }
    }

    writeHash(instHash, 0, pStmt, dbFieldTypes, dbFieldNames, inxToName);
    writeHash(divHash, 1, pStmt, dbFieldTypes, dbFieldNames, inxToName);
    writeHash(dspHash, 2, pStmt, dbFieldTypes, dbFieldNames, inxToName);
    writeHash(colHash, 3, pStmt, dbFieldTypes, dbFieldNames, inxToName);

    String alterSQL = "ALTER TABLE " + newTblName + " ADD Lookup VARCHAR(64) AFTER IP";
    BasicSQLUtils.update(connection, alterSQL);

    alterSQL = "ALTER TABLE " + newTblName + " ADD Country VARCHAR(64) AFTER Lookup";
    BasicSQLUtils.update(connection, alterSQL);

    alterSQL = "ALTER TABLE " + newTblName + " ADD City VARCHAR(64) AFTER Country";
    BasicSQLUtils.update(connection, alterSQL);

    return instCnt;
}

From source file:edu.ku.brc.specify.toycode.mexconabio.AnalysisWithGBIFToGBIF.java

@Override
public void process(final int type, final int options) {
    calcMaxScore();/*from   ww  w  .j a  va2s. c  o m*/

    String gbifSQL = "SELECT DISTINCT id, catalogue_number, genus, species, subspecies, latitude, longitude, country, state_province, collector_name, locality, year, month, day, collector_num ";

    String fromClause1a = "FROM raw WHERE collector_num LIKE ? AND year = ? AND genus = ?";
    String fromClause1b = "FROM raw WHERE collector_num IS NULL AND year = ? AND genus = ?";
    //String fromClause2  = "FROM raw WHERE collector_num IS NULL AND year = ? AND month = ? AND genus = ? AND id <> ?";

    //                        1       2           3        4           5         6          7         8           9               10          11       12    13    14      15
    String postSQL = "FROM raw WHERE collector_num IS NOT NULL GROUP BY collector_num, year, genus";
    String srcSQL = "SELECT id, catalogue_number, genus, species, subspecies, latitude, longitude, country, state_province, collector_name, locality, year, month, day, collector_num "
            + postSQL + " ORDER BY collector_num";

    String grphashSQL = "SELECT name FROM group_hash";

    String gbifgbifInsert = "INSERT INTO gbifgbif (reltype, score, GBIFID, SNIBID) VALUES (?,?,?,?)";

    Statement stmt = null;
    PreparedStatement gStmt1a = null;
    PreparedStatement gStmt1b = null;
    //PreparedStatement gStmt2  = null;
    PreparedStatement gsStmt = null;

    Object[] refRow = new Object[NUM_FIELDS];
    Object[] cmpRow = new Object[NUM_FIELDS];

    long totalRecs = BasicSQLUtils.getCount(dbSrcConn, "SELECT COUNT(*) FROM group_hash");
    long procRecs = 0;
    long startTime = System.currentTimeMillis();
    int secsThreshold = 0;

    String blank = "X?";

    PrintWriter pw = null;
    try {
        pw = new PrintWriter("scoring_gbifgbif.log");

        gStmt1a = dbGBIFConn.prepareStatement(gbifSQL + fromClause1a);
        gStmt1b = dbGBIFConn.prepareStatement(gbifSQL + fromClause1b);

        //gStmt2 = dbGBIFConn.prepareStatement(gbifSQL + fromClause2);
        gsStmt = dbDstConn.prepareStatement(gbifgbifInsert);

        stmt = dbSrcConn.createStatement(ResultSet.FETCH_FORWARD, ResultSet.CONCUR_READ_ONLY);
        stmt.setFetchSize(Integer.MIN_VALUE);

        System.out.println("Starting Query... " + totalRecs);
        pw.println("Starting Query... " + totalRecs);
        System.out.flush();
        pw.flush();

        HashSet<Integer> idHash = new HashSet<Integer>();
        int writeCnt = 0;
        ResultSet rs = stmt.executeQuery(grphashSQL);

        System.out
                .println(String.format("Starting Processing... Total Records %d  Max Score: %d  Threshold: %d",
                        totalRecs, maxScore, thresholdScore));
        pw.println(String.format("Starting Processing... Total Records %d  Max Score: %d  Threshold: %d",
                totalRecs, maxScore, thresholdScore));
        System.out.flush();
        pw.flush();

        Vector<Object[]> group = new Vector<Object[]>();
        ArrayList<Integer> ids = new ArrayList<Integer>();
        while (rs.next()) {
            String[] tokens = StringUtils.split(rs.getString(1), '_');

            String colNum = tokens[0].trim();
            String year = tokens[1].trim();
            String genus = tokens[2].trim();

            if (StringUtils.isEmpty(colNum) || colNum.equals(blank))
                colNum = null;
            if (StringUtils.isEmpty(year) || year.equals(blank))
                year = null;
            if (StringUtils.isEmpty(genus) || genus.equals(blank))
                genus = null;

            PreparedStatement gStmt1;
            if (colNum != null) {
                gStmt1 = gStmt1a;
                gStmt1.setString(1, "%" + colNum + "%");
            } else {
                gStmt1 = gStmt1b;
                gStmt1.setString(1, null);
            }
            gStmt1.setString(2, year);
            gStmt1.setString(3, genus);
            ResultSet gRS = gStmt1.executeQuery();

            ids.clear();
            int maxNonNullTot = -1;
            int maxNonNullInx = -1;
            int inx = 0;
            while (gRS.next()) {

                Object[] row = getRow();
                int cnt = fillRowWithScore(row, gRS);
                if (cnt > maxNonNullTot) {
                    maxNonNullInx = inx;
                    maxNonNullTot = cnt;
                }
                group.add(row);
                ids.add(gRS.getInt(1));
                inx++;
            }
            gRS.close();

            if (inx < 2) {
                for (Object[] r : group) {
                    recycleRow(r);
                }
                group.clear();
                continue;
            }

            System.arraycopy(group.get(maxNonNullInx), 0, refRow, 0, refRow.length);

            Integer srcId = ids.get(maxNonNullInx);

            for (int i = 0; i < group.size(); i++) {
                if (i != maxNonNullInx) {
                    int score = score(refRow, group.get(i));

                    if (score > thresholdScore) {
                        writeCnt++;

                        int gbifID = ids.get(i);
                        gsStmt.setInt(1, 1); // reltype
                        gsStmt.setInt(2, score); // score
                        gsStmt.setInt(3, gbifID);
                        gsStmt.setInt(4, srcId);
                        gsStmt.executeUpdate();

                        idHash.add(gbifID);
                    }
                }
            }

            idHash.clear();

            for (Object[] r : group) {
                recycleRow(r);
            }
            group.clear();

            if (gStmt1 == gStmt1b) {
                continue;
            }

            gStmt1 = gStmt1b;
            gStmt1.setString(1, year);
            gStmt1.setString(2, genus);

            gRS = gStmt1.executeQuery();
            while (gRS.next()) {
                fillRowWithScore(cmpRow, gRS);

                int gbifID = gRS.getInt(1);
                if (gbifID == srcId)
                    continue;

                int score = score(refRow, cmpRow);

                if (score > thresholdScore) {
                    writeCnt++;
                    gsStmt.setInt(1, 1); // reltype
                    gsStmt.setInt(2, score); // score
                    gsStmt.setInt(3, gbifID);
                    gsStmt.setInt(4, srcId);
                    gsStmt.executeUpdate();
                }
            }
            gRS.close();

            procRecs++;
            if (procRecs % 500 == 0) {
                long endTime = System.currentTimeMillis();
                long elapsedTime = endTime - startTime;

                double timePerRecord = (elapsedTime / procRecs);

                double hrsLeft = ((totalRecs - procRecs) * timePerRecord) / HRS;

                int seconds = (int) (elapsedTime / 60000.0);
                if (secsThreshold != seconds) {
                    secsThreshold = seconds;

                    String msg = String.format("Elapsed %8.2f hr.mn   Percent: %6.3f  Hours Left: %8.2f ",
                            ((double) (elapsedTime)) / HRS, 100.0 * ((double) procRecs / (double) totalRecs),
                            hrsLeft);
                    System.out.println(msg);
                    pw.println(msg);
                    pw.flush();
                }
            }
        }
        rs.close();

        System.out.println("Done.");
        pw.println("Done.");

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (stmt != null) {
                stmt.close();
            }
            if (gStmt1a != null) {
                gStmt1a.close();
            }
            if (gStmt1b != null) {
                gStmt1b.close();
            }
            /*if (gStmt2 != null)
            {
            gStmt2.close();
            }*/
        } catch (Exception ex) {

        }
    }
    System.out.println("Done.");
    pw.println("Done.");
    pw.flush();
    pw.close();
}

From source file:webServices.RestServiceImpl.java

public Vector<Layer> parseLayersInfo(String info) {
    Vector<Layer> layersInfo = new Vector<Layer>();
    Vector<String> values = new Vector<String>();

    String val = null;
    String[] data;/*from   w w  w  . jav a2  s.c o  m*/
    String[] attr;
    String[] layerInfo = info.split("\\{\"nam");

    //For each layer
    for (int i = 1; i < layerInfo.length; i++) {
        //Initialize values temp variable
        values = new Vector<String>();
        data = layerInfo[i].split("\\$");

        //Attributes of each layer
        for (int j = 0; j < data.length - 1; j++) {
            attr = data[j].split("\":\"");
            if (attr.length > 1) {
                val = attr[1];
            } else {
                val = "";
            }
            if (val.equalsIgnoreCase("")) {
                values.add(null);
            } else {
                values.add(val);
            }
        }

        /**
         * Fix null values
         */
        if (values.get(10) == null) {
            values.set(10, "");
        }

        if (values.get(9) == null) {
            values.set(9, "");
        }

        if (values.get(8) == null) {
            values.set(8, "");
        }

        if (values.get(7) == null) {
            values.set(7, "");
        }

        Layer temp = new Layer(values.get(0), values.get(1), Boolean.parseBoolean(values.get(2)), values.get(3),
                values.get(4), values.get(5), values.get(6), values.get(7), values.get(8), values.get(9),
                values.get(10), values.get(11), values.get(12));

        layersInfo.add(temp);
    }

    return layersInfo;
}

From source file:org.martus.client.swingui.UiMainWindow.java

public void allFolderContentsHaveChanged() {
    Vector allFolders = getStore().getAllFolders();
    for (int i = 0; i < allFolders.size(); i++) {
        folderContentsHaveChanged((BulletinFolder) allFolders.get(i));
    }/*w  w w  .  j a  v  a  2s  .  com*/
    folderTreeContentsHaveChanged();
    selectSentFolder();
}

From source file:org.smilec.smile.student.CourseList.java

private void scorequestion(Vector<Integer> _rightanswer, Vector<Integer> _myanswer) {

    for (int i = 0; i < _rightanswer.size(); i++) {
        if (_myanswer.get(i) == _rightanswer.get(i))
            my_score.set(i, 1); // right
        else//w w w.  j  a  va2  s . co m
            my_score.set(i, 0); // wrong
    }
}

From source file:org.smilec.smile.student.CourseList.java

private int countrightquestion(Vector<Integer> arr) {
    int revalue = 0;

    for (int i = 0; i < arr.size(); i++) {
        if (arr.get(i) == 1)
            revalue++;/*  w  w w. ja va 2s .  c o m*/
    }

    return revalue;
}

From source file:hu.sztaki.lpds.pgportal.portlets.workflow.EasyWorkflowPortlet.java

/**
 * Detailed displaying of a worflow instance data
 *///from  ww w  .  j a  va 2s. com
public void doInstanceDetails(ActionRequest request, ActionResponse response) throws PortletException {
    String workflow = "" + request.getParameter("workflow");
    doDetails(request, response);
    request.getPortletSession().setAttribute("cworkflow", request.getParameter("workflow"));
    request.getPortletSession().setAttribute("detailsruntime", request.getParameter("rtid"));
    //        System.out.println("!!!!doInstanceDetails rtid:"+request.getParameter("rtid")+" workflow:"+workflow);
    request.setAttribute("rtid", PortalCacheService.getInstance().getUser(request.getRemoteUser())
            .getWorkflow(workflow).getRuntime(request.getParameter("rtid")).getText());
    request.setAttribute("workflow",
            PortalCacheService.getInstance().getUser(request.getRemoteUser()).getWorkflow(workflow));

    if (PortalCacheService.getInstance().getUser(request.getRemoteUser())
            .getWorkflow(request.getParameter("workflow")).getRuntime(request.getParameter("rtid"))
            .getJobsStatus().equals(new Hashtable())) {
        Hashtable prp = new Hashtable();
        Vector v = new Vector();
        prp.put("url", PortalCacheService.getInstance().getUser(request.getRemoteUser())
                .getWorkflow(request.getParameter("workflow")).getWfsID());
        ServiceType st = InformationBase.getI().getService("wfs", "portal", prp, new Vector());
        try {
            PortalWfsClient pc = (PortalWfsClient) Class.forName(st.getClientObject()).newInstance();
            pc.setServiceURL(st.getServiceUrl());
            pc.setServiceID(st.getServiceID());
            ComDataBean cmb = new ComDataBean();
            cmb.setPortalID(PropertyLoader.getInstance().getProperty("service.url"));
            cmb.setUserID(request.getRemoteUser());
            cmb.setWorkflowID(request.getParameter("workflow"));
            cmb.setWorkflowRuntimeID(request.getParameter("rtid"));
            v = pc.getWorkflowInstanceJobs(cmb);
            JobStatusBean tmp;
            for (int i = 0; i < v.size(); i++) {
                tmp = (JobStatusBean) v.get(i);
                PortalCacheService.getInstance().getUser(request.getRemoteUser())
                        .getWorkflow(request.getParameter("workflow")).getRuntime(request.getParameter("rtid"))
                        .addJobbStatus(tmp.getJobID(), "" + tmp.getPID(), "" + tmp.getStatus(),
                                tmp.getResource(), 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    Hashtable jobs = PortalCacheService.getInstance().getUser(request.getRemoteUser())
            .getWorkflow(request.getParameter("workflow")).getRuntime(request.getParameter("rtid"))
            .getCollectionJobsStatus();
    //System.out.println("---doInstanceDetails:"+jobs);
    int sinit = 0;
    int sproc = 0;
    int sfinalok = 0;
    int sfinalerr = 0;
    Enumeration jobskeys = jobs.keys();
    while (jobskeys.hasMoreElements()) {//iterate jobs
        Hashtable job = (Hashtable) jobs.get(jobskeys.nextElement());

        Enumeration jkeys = job.keys();
        while (jkeys.hasMoreElements()) {//paramjobs
            try {
                String jobstatus = "" + jkeys.nextElement();//job statuses from the given gob
                int ijobStatus = Integer.parseInt(jobstatus);
                //System.out.println("jobstatus:"+jobstatus+" job.get(jobstatus):"+job.get(ijobStatus));
                int jobstatusnbr = Integer.parseInt("" + job.get(ijobStatus));//?db

                if (jobstatus.equals("1") || jobstatus.equals("28")) {//init or suspended
                    sinit += jobstatusnbr;
                } else if (jobstatus.equals("6") || jobstatus.equals("21") || jobstatus.equals("25")) {
                    sfinalok += jobstatusnbr;
                } else if (jobstatus.equals("7")) {
                    sfinalerr += jobstatusnbr;
                } else {
                    sproc += jobstatusnbr;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    int sum = sinit + sproc + sfinalok + sfinalerr;
    double psinit = ((double) sinit / sum) * 100;
    java.text.DecimalFormat fmt = new java.text.DecimalFormat("#");
    request.setAttribute("sinit", sinit);
    request.setAttribute("sproc", sproc);
    request.setAttribute("sfinalok", sfinalok);
    request.setAttribute("sfinalerr", sfinalerr);
    request.setAttribute("psinit", fmt.format(((double) sinit / sum) * 100));
    request.setAttribute("psproc", fmt.format(((double) sproc / sum) * 100));
    request.setAttribute("psfinalok", fmt.format(((double) sfinalok / sum) * 100));
    request.setAttribute("psfinalerr", fmt.format(((double) sfinalerr / sum) * 100));
    request.setAttribute("ssum", sum);
    //        System.out.println("---doInstanceDetails:" + sinit + "+" + sproc + "+" + sfinalok+ "+" + sfinalerr+"="+sum+" --- init%:"+psinit+"");

    request.setAttribute("instJobList",
            PortalCacheService.getInstance().getUser(request.getRemoteUser())
                    .getWorkflow(request.getParameter("workflow")).getRuntime(request.getParameter("rtid"))
                    .getCollectionJobsStatus());

}

From source file:edu.ku.brc.specify.tools.l10nios.StrLocalizerAppForiOS.java

/**
 * @param hideExisting// www  . jav a  2 s . com
 * @return
 */
private Locale doChooseLangLocale(final Locale hideLocale) {
    Vector<Locale> locales = new Vector<Locale>();
    Collections.addAll(locales, Locale.getAvailableLocales());

    String[] langs = { "es", "sv", "sq", "fr" };
    Vector<Locale> destLocales = new Vector<Locale>();
    destLocales.add(Locale.GERMAN);
    for (String lang : langs) {
        appendLocale(locales, destLocales, lang);
    }

    Vector<String> localeNames = new Vector<String>();
    for (Locale l : destLocales) {
        localeNames.add(l.getDisplayName());
    }

    ToggleButtonChooserDlg<String> chooser = new ToggleButtonChooserDlg<String>((Frame) null, "CHOOSE_LOCALE",
            localeNames, ToggleButtonChooserPanel.Type.RadioButton);
    chooser.setUseScrollPane(true);
    UIHelper.centerAndShow(chooser);

    if (!chooser.isCancelled()) {
        return destLocales.get(chooser.getSelectedIndex());
    }
    return null;
}

From source file:com.almarsoft.GroundhogReader.lib.NNTPExtended.java

public long[] getGroupArticles(String group, long fromArticle, int limit) throws IOException {

    Vector<Long> list;
    long firstToGet, firstArticle, lastArticle;
    NewsgroupInfo groupInfo = new NewsgroupInfo();

    if (!selectNewsgroup(group, groupInfo))
        return null;

    firstArticle = groupInfo.getFirstArticle();
    lastArticle = groupInfo.getLastArticle();

    if (firstArticle == 0 && lastArticle == 0)
        return new long[0];

    // First sync with this group; see the comment below 
    if (fromArticle == -1)
        firstToGet = firstArticle;//from  w  w  w  .j a v  a2 s .co  m

    else {
        if (fromArticle > lastArticle) { // No new articles
            return new long[0];
        } else {
            firstToGet = fromArticle;
        }
    }

    // Now select the first article and start looping until limit or last article reached
    ArticlePointer art = new ArticlePointer();

    list = new Vector<Long>(limit);

    // FIRST CONNECTION TO THE GROUP
    // If this is the first connection we only want the last "limit" articles from the group, 
    // so we ask for the last message and go backwards until we have "limit" articles or 
    // the first one.
    if (fromArticle == -1) {
        if (!selectArticle(lastArticle, art))
            return new long[0];

        for (int i = 0; i < limit; i++) {
            list.insertElementAt((long) art.articleNumber, 0);

            if (art.articleNumber == firstToGet)
                break;

            if (!selectPreviousArticle(art))
                break;
        }
    }

    // NON-FIRST CONNECTION TO THE GROUP
    // For normal non-first connection we start with the last article we got on the previous session and advance from that
    // until limit or last article reached
    else {
        if (!selectArticle(firstToGet, art))
            return new long[0];

        for (int i = 0; i <= limit; i++) {
            list.add((long) art.articleNumber);

            if (art.articleNumber == lastArticle)
                break;

            if (!selectNextArticle(art))
                break;
        }
    }
    int listSize = list.size();
    long[] articleNumbers = new long[listSize];

    for (int i = 0; i < listSize; i++) {
        articleNumbers[i] = list.get(i);
    }

    return articleNumbers;
}