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:com.mysql.stresstool.RunnableQueryInsertDR.java

public void run() {

    BufferedReader d = null;/*  ww w . ja v a 2s  . co m*/
    Connection conn = null;

    try {
        if (jdbcUrlMap.get("dbType") != null && !((String) jdbcUrlMap.get("dbType")).equals("MySQL")) {
            conn = DriverManager.getConnection((String) jdbcUrlMap.get("dbType"), "test", "test");
        } else
            conn = DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl"));
    } catch (SQLException ex) {
        ex.printStackTrace();
    }

    if (conn != null) {

        try {

            Statement stmt = null;
            //                ResultSet rs = null;
            //                ResultSet rs2 = null;

            conn.setAutoCommit(false);
            stmt = conn.createStatement();
            stmt.execute("SET AUTOCOMMIT=0");
            long execTime = 0;
            int pkStart = 0;
            int pkEnds = 0;
            int intDeleteInterval = 0;
            int intBlobInterval = 0;
            int intBlobIntervalLimit = StressTool.getNumberFromRandom(4).intValue();
            ThreadInfo thInfo;

            long threadTimeStart = System.currentTimeMillis();
            active = true;

            thInfo = new ThreadInfo();
            thInfo.setId(this.ID);
            thInfo.setType("insert");
            thInfo.setStatusActive(this.isActive());

            StressTool.setInfo(this.ID, thInfo);
            boolean lazy = false;
            int lazyInterval = 0;

            populateLocalInfo(conn);

            for (int repeat = 0; repeat <= repeatNumber; repeat++) {
                String query = null;
                ArrayList insert1 = null;
                ArrayList insert2 = null;
                int pk = 0;

                if (repeat > 0 && lazyInterval < 500) {
                    lazy = true;
                    ++lazyInterval;
                } else {
                    lazy = false;
                    lazyInterval = 0;
                }

                intBlobInterval++;
                //IMPLEMENTING lazy
                Vector v = this.getTablesValues(lazy);

                insert1 = (ArrayList<String>) v.get(0);
                insert2 = (ArrayList<String>) v.get(1);

                //                    System.out.println(insert1);
                //                    System.out.println(insert2);

                //                    pk = ((Integer) v.get(2)).intValue();

                int[] iLine = { 0, 0 };

                //                    pkStart = StressTool.getNumberFromRandom(2147483647).intValue();
                //                    pkEnds = StressTool.getNumberFromRandom(2147483647).intValue();

                try {

                    long timeStart = System.currentTimeMillis();

                    if (this.ignoreBinlog)
                        stmt.execute("SET sql_log_bin=0");
                    stmt.execute("SET GLOBAL max_allowed_packet=1073741824");

                    if (dbType.equals("MySQL") && !engine.toUpperCase().equals("BRIGHTHOUSE"))
                        stmt.execute("BEGIN");
                    else
                        stmt.execute("COMMIT");
                    //                                stmt.execute("SET TRANSACTION NAME 'TEST'");
                    {
                        Iterator<String> it = insert1.iterator();
                        while (it.hasNext()) {
                            stmt.addBatch(it.next());
                        }
                    }

                    if (!this.doSimplePk) {
                        if (intBlobInterval > intBlobIntervalLimit) {
                            Iterator<String> it = insert2.iterator();
                            while (it.hasNext()) {
                                stmt.addBatch(it.next());
                            }
                            intBlobInterval = 0;

                        }
                    }
                    if (debug) {
                        System.out.println("Thread " + thInfo.getId() + " Executing loop "
                                + thInfo.getExecutedLoops() + " QUERY1==" + insert1);
                        System.out.println("Thread " + thInfo.getId() + " Executing loop "
                                + thInfo.getExecutedLoops() + " QUERY2==" + insert2);

                    }

                    iLine = stmt.executeBatch();
                    stmt.clearBatch();
                    //                            System.out.println("Query1 = " + insert1);
                    //                            System.out.println("Query2 = " + insert2);
                    //                            stmt.execute("START TRANSACTION");
                    //                            stmt.execute(insert1);
                    //                            iLine = stmt.executeBatch();
                    //                            conn.commit();
                    long timeEnds = System.currentTimeMillis();
                    execTime = (timeEnds - timeStart);

                } catch (Exception sqle) {
                    conn.rollback();
                    System.out.println("FAILED QUERY1==" + insert1);
                    System.out.println("FAILED QUERY2==" + insert2);
                    sqle.printStackTrace();
                    System.exit(1);
                    //conn.close();
                    //this.setJdbcUrl(jdbcUrl);
                    //System.out.println("Query Insert TH RE-INIZIALIZING");

                } finally {
                    //                           conn.commit();
                    stmt.execute("COMMIT");
                    //                            intDeleteInterval++;
                    if (doLog) {

                        System.out.println("Query Insert TH = " + this.getID() + " Loop N = " + repeat + " "
                                + iLine[0] + "|" + ((iLine.length > 1) ? iLine[1] : 0) + " Exec Time(ms) ="
                                + execTime + " Running = " + repeat + " of " + repeatNumber + " to go ="
                                + (repeatNumber - repeat) + " Using Lazy=" + lazy);
                    }
                }
                thInfo.setExecutedLoops(repeat);
                if (sleepFor > 0 || this.getSleepWrite() > 0) {
                    if (this.getSleepWrite() > 0) {
                        Thread.sleep(getSleepWrite());
                    } else
                        Thread.sleep(sleepFor);
                }

            }

            long threadTimeEnd = System.currentTimeMillis();
            this.executionTime = (threadTimeEnd - threadTimeStart);
            //                this.setExecutionTime(executionTime);
            active = false;
            //                System.out.println("Query Insert TH = " + this.getID() + " COMPLETED!  TOTAL TIME = " + execTime + "(ms) Sec =" + (execTime/1000));

            thInfo.setExecutionTime(executionTime);
            thInfo.setStatusActive(false);
            StressTool.setInfo(this.ID, thInfo);
            return;

        } catch (Exception ex) {
            ex.printStackTrace();
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.server.control.CallMarketEngine.java

/** Rollback all changes made in the current transaction. Dump the updates that
 *  were going to sent to the clients, rollback the server-side offerbook, rollback
 *  the database, and rollback the server-side holdings. Return the rolled back
 *  Update Basket *//*from   w w  w  .j  a va2s.c  o m*/
private UpdateBasket rollback(MarketState marketState, TransactionState transState, UpdateBasket basket) {
    OfferBook offerBook = marketState.getOfferBook();
    int subjectId_db = transState.getOffer().getSubjectId_db();
    int marketId = transState.getMarketId();
    Connection conn = transState.getConn();

    basket.getTradeUpdates().clear();
    basket.getMetricsUpdates().clear();
    basket.getNumOffersUpdates().clear();
    basket.getPriceChartUpdates().clear();
    basket.getTradeUpdates().clear();

    TradeUpdate invalid = new TradeUpdate(subjectId_db, TradeUpdate.INVALID_OFFER_UPDATE);
    invalid.setErrorMsg("Transaction failed for unknown reason -- please try again");
    basket.addTradeUpdate(invalid);

    Vector inverts = transState.getUpdateInverts();
    for (int i = 0; i < inverts.size(); i++) {
        UpdateInvert invert = (UpdateInvert) inverts.get(i);
        offerBook.invertUpdate(invert);
        log.debug(transState.getCode() + ": Server-side offer book ROLLED BACK: "
                + offerBook.getState(invert.market, invert.price, invert.subject));
    }

    Trader[] traders = marketState.getTraders();
    float[] priorCashHoldings = transState.getPriorCashHoldings();
    int[] priorSecHoldings = transState.getPriorSecHoldings();
    int[][] priorPurchases = transState.getPriorPurchases();
    int[][] priorSales = transState.getPriorSales();

    for (int i = 0; i < traders.length; i++) {
        traders[i].setCash(priorCashHoldings[i]);
        traders[i].setHoldings(marketId, priorSecHoldings[i]);
        traders[i].setNumPurchases(marketId, priorPurchases[i]);
        traders[i].setNumSales(marketId, priorSales[i]);
    }
    dbw.rollback(conn);

    return basket;
}

From source file:com.naryx.tagfusion.cfm.xml.ws.javaplatform.DynamicWebServiceStubGenerator.java

private StubInfo.Operation[] findOperations(Parser wsdlParser, Port port) {
    SymbolTable symbolTable = wsdlParser.getSymbolTable();
    BindingEntry bEntry = symbolTable.getBindingEntry(port.getBinding().getQName());
    Set opSet = bEntry.getParameters().keySet();
    Iterator itr = opSet.iterator();

    StubInfo.Operation[] siOps = new StubInfo.Operation[opSet.size()];
    for (int i = 0; itr.hasNext(); i++) {
        // Get the operation and add the parameters
        Operation op = (Operation) itr.next();
        Vector parms = bEntry.getParameters(op).list;

        // Populate the parms
        StubInfo.Parameter[] siParms = new StubInfo.Parameter[parms.size()];
        StubInfo.Operation siOp = new StubInfo.Operation(op.getName(), siParms);
        siOps[i] = siOp;// w w w. j  av  a 2s. co  m
        Iterator tmpItr = parms.iterator();
        for (int j = 0; tmpItr.hasNext(); j++) {
            Parameter p = (Parameter) tmpItr.next();
            siParms[j] = new StubInfo.Parameter(p.getName(), p.isNillable(), p.isOmittable());
        }

        // If there is only 1 parameter and it's a complex object,
        // gather parameter information for its properties.
        if (parms.size() == 1) {
            Vector elems = ((Parameter) parms.get(0)).getType().getContainedElements();
            if (elems != null && !elems.isEmpty()) {
                StubInfo.Parameter[] siSubParms = new StubInfo.Parameter[elems.size()];
                tmpItr = elems.iterator();
                for (int j = 0; tmpItr.hasNext(); j++) {
                    ElementDecl e = (ElementDecl) tmpItr.next();
                    siSubParms[j] = new StubInfo.Parameter(e.getName(), e.getNillable(), e.getMinOccursIs0());
                }
                siOp.setSubParameters(siSubParms);
            }
        }
    }

    // Return the operations
    return siOps;
}

From source file:fr.inrialpes.exmo.align.cli.GroupEval.java

public void printHTML(Vector<Vector<Object>> result, PrintStream writer) {
    // variables for computing iterative harmonic means
    int expected = 0; // expected so far
    int foundVect[]; // found so far
    int correctVect[]; // correct so far
    long timeVect[]; // time so far
    Formatter formatter = new Formatter(writer);

    fsize = format.length();//from www.j a va  2 s  .  c  o m
    // JE: the h-means computation should be put out as well
    // Print the header
    if (embedded != true)
        writer.println("<html><head></head><body>");
    writer.println("<table border='2' frame='sides' rules='groups'>");
    writer.println("<colgroup align='center' />");
    // for each algo <td spancol='2'>name</td>
    for (String m : listAlgo) {
        writer.println("<colgroup align='center' span='" + fsize + "' />");
    }
    // For each file do a
    writer.println("<thead valign='top'><tr><th>algo</th>");
    // for each algo <td spancol='2'>name</td>
    for (String m : listAlgo) {
        writer.println("<th colspan='" + fsize + "'>" + m + "</th>");
    }
    writer.println("</tr></thead><tbody><tr><td>test</td>");
    // for each algo <td>Prec.</td><td>Rec.</td>
    for (String m : listAlgo) {
        for (int i = 0; i < fsize; i++) {
            writer.print("<td>");
            if (format.charAt(i) == 'p') {
                writer.print("Prec.");
            } else if (format.charAt(i) == 'f') {
                writer.print("FMeas.");
            } else if (format.charAt(i) == 'o') {
                writer.print("Over.");
            } else if (format.charAt(i) == 't') {
                writer.print("Time");
            } else if (format.charAt(i) == 'r') {
                writer.print("Rec.");
            }
            writer.println("</td>");
        }
        //writer.println("<td>Prec.</td><td>Rec.</td>");
    }
    writer.println("</tr></tbody><tbody>");
    foundVect = new int[size];
    correctVect = new int[size];
    timeVect = new long[size];
    for (int k = size - 1; k >= 0; k--) {
        foundVect[k] = 0;
        correctVect[k] = 0;
        timeVect[k] = 0;
    }
    // </tr>
    // For each directory <tr>
    boolean colored = false;
    for (Vector<Object> test : result) {
        int nexpected = -1;
        if (colored == true && color != null) {
            colored = false;
            writer.println("<tr bgcolor=\"" + color + "\">");
        } else {
            colored = true;
            writer.println("<tr>");
        }
        ;
        // Print the directory <td>bla</td>
        writer.println("<td>" + (String) test.get(0) + "</td>");
        // For each record print the values <td>bla</td>
        Enumeration<Object> f = test.elements();
        f.nextElement();
        for (int k = 0; f.hasMoreElements(); k++) {
            PRecEvaluator eval = (PRecEvaluator) f.nextElement();
            if (eval != null) {
                // iterative H-means computation
                if (nexpected == -1) {
                    expected += eval.getExpected();
                    nexpected = 0;
                }
                foundVect[k] += eval.getFound();
                correctVect[k] += eval.getCorrect();
                timeVect[k] += eval.getTime();

                for (int i = 0; i < fsize; i++) {
                    writer.print("<td>");
                    if (format.charAt(i) == 'p') {
                        formatter.format("%1.2f", eval.getPrecision());
                    } else if (format.charAt(i) == 'f') {
                        formatter.format("%1.2f", eval.getFmeasure());
                    } else if (format.charAt(i) == 'o') {
                        formatter.format("%1.2f", eval.getOverall());
                    } else if (format.charAt(i) == 't') {
                        if (eval.getTime() == 0) {
                            writer.print("-");
                        } else {
                            formatter.format("%1.2f", eval.getTime());
                        }
                    } else if (format.charAt(i) == 'r') {
                        formatter.format("%1.2f", eval.getRecall());
                    }
                    writer.print("</td>");
                }
            } else {
                for (int i = 0; i < fsize; i++)
                    writer.print("<td>n/a</td>");
            }
        }
        writer.println("</tr>");
    }
    writer.print("<tr bgcolor=\"yellow\"><td>H-mean</td>");
    // Here we are computing a sheer average.
    // While in the column results we print NaN when the returned
    // alignment is empty,
    // here we use the real values, i.e., add 0 to both correctVect and
    // foundVect, so this is OK for computing the average.
    int k = 0;
    // ???
    for (String m : listAlgo) {
        double precision = (double) correctVect[k] / foundVect[k];
        double recall = (double) correctVect[k] / expected;
        for (int i = 0; i < fsize; i++) {
            writer.print("<td>");
            if (format.charAt(i) == 'p') {
                formatter.format("%1.2f", precision);
            } else if (format.charAt(i) == 'f') {
                formatter.format("%1.2f", 2 * precision * recall / (precision + recall));
            } else if (format.charAt(i) == 'o') {
                formatter.format("%1.2f", recall * (2 - (1 / precision)));
            } else if (format.charAt(i) == 't') {
                if (timeVect[k] == 0) {
                    writer.print("-");
                } else {
                    formatter.format("%1.2f", timeVect[k]);
                }
            } else if (format.charAt(i) == 'r') {
                formatter.format("%1.2f", recall);
            }
            writer.println("</td>");
        }
        ;
        k++;
    }
    writer.println("</tr>");
    writer.println("</tbody></table>");
    writer.println("<p><small>n/a: result alignment not provided or not readable<br />");
    writer.println("NaN: division per zero, likely due to empty alignment.</small></p>");
    if (embedded != true)
        writer.println("</body></html>");
}

From source file:gsn.http.A3DWebServiceImpl.java

public String[] getLatestMeteoDataMeasurement(String sensor, String measurement) {

    StringBuilder query = new StringBuilder(
            "select " + measurement + " from " + sensor + " order by timed DESC limit 1 offset 0");
    DataEnumerator result;//from   www.ja  va 2  s  .  co  m
    try {
        result = Main.getStorage(sensor).executeQuery(query, false);
    } catch (SQLException e) {
        logger.error("ERROR IN EXECUTING, query: " + query);
        logger.error(e.getMessage(), e);
        return new String[] { "ERROR IN EXECUTING, query: " + query };
    }

    Vector<String> latestMeteoData = new Vector<String>();

    while (result.hasMoreElements()) {
        StreamElement se = result.nextElement();

        latestMeteoData.add(new StringBuilder("TIMED=" + se.getTimeStamp()).toString());

        for (int i = 0; i < se.getFieldNames().length; i++) {
            //StringBuilder sb = new StringBuilder();
            //sb.append(se.getFieldNames()[i]).append("=");
            String value;
            if (se.getData()[i] != null)
                if (se.getFieldTypes()[i] == DataTypes.BINARY)
                    value = se.getData()[i].toString();
                else
                    value = StringEscapeUtils.escapeXml(se.getData()[i].toString());
            else
                value = "";
            latestMeteoData.add(measurement + "=" + value);
        }
    }
    //result.close();

    String v_latestMeteoData[] = new String[latestMeteoData.size()];
    for (int i = 0; i < latestMeteoData.size(); i++)
        v_latestMeteoData[i] = latestMeteoData.get(i);

    return v_latestMeteoData;
}

From source file:com.mysql.stresstool.RunnableQueryInsertPCH.java

public void run() {

    BufferedReader d = null;//from  w  ww  .j  av  a 2  s  . co  m
    Connection conn = null;

    if (conn == null) {

        try {
            long execTime = 0;
            int pkStart = 0;
            int pkEnds = 0;
            int intDeleteInterval = 0;
            int intBlobInterval = 0;
            int intBlobIntervalLimit = StressTool.getNumberFromRandom(4).intValue();
            ThreadInfo thInfo;

            long threadTimeStart = System.currentTimeMillis();
            active = true;

            thInfo = new ThreadInfo();
            thInfo.setId(this.ID);
            thInfo.setType("insert");
            thInfo.setStatusActive(this.isActive());

            StressTool.setInfo(this.ID, thInfo);
            boolean lazy = false;
            int lazyInterval = 0;

            for (int repeat = 0; repeat <= repeatNumber; repeat++) {

                try {
                    if (conn != null && !conn.isClosed()) {
                        conn.close();
                    }
                    SoftReference sf = new SoftReference(
                            DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl")));
                    conn = (Connection) sf.get();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
                Statement stmt = null;
                //                ResultSet rs = null;
                //                ResultSet rs2 = null;

                conn.setAutoCommit(false);
                stmt = conn.createStatement();
                stmt.execute("SET AUTOCOMMIT=0");
                ResultSet rs = null;
                int ServerId = 0;
                String query = null;
                ArrayList insert1 = null;
                ArrayList insert2 = null;
                int pk = 0;

                {
                    SoftReference sf = new SoftReference(
                            stmt.executeQuery("show global variables like 'SERVER_ID'"));
                    rs = (ResultSet) sf.get();
                }
                rs.next();
                ServerId = rs.getInt(2);

                if (repeat > 0 && lazyInterval < 500) {
                    lazy = true;
                    ++lazyInterval;
                } else {
                    lazy = false;
                    lazyInterval = 0;
                }

                intBlobInterval = StressTool.getNumberFromRandom(10).intValue();
                //               intBlobInterval++;
                //IMPLEMENTING lazy

                Vector v = null;
                {
                    SoftReference sf = new SoftReference(this.getTablesValues(lazy, ServerId));
                    v = (Vector) sf.get();
                }
                insert1 = (ArrayList<String>) v.get(0);
                insert2 = (ArrayList<String>) v.get(1);

                //                    System.out.println(insert1);
                //                    System.out.println(insert2);

                //                    pk = ((Integer) v.get(2)).intValue();

                int[] iLine = { 0, 0 };

                //                    pkStart = StressTool.getNumberFromRandom(2147483647).intValue();
                //                    pkEnds = StressTool.getNumberFromRandom(2147483647).intValue();

                try {

                    long timeStart = System.currentTimeMillis();

                    if (this.ignoreBinlog)
                        stmt.execute("SET sql_log_bin=0");
                    stmt.execute("SET GLOBAL max_allowed_packet=10737418");

                    if (dbType.equals("MySQL") && !engine.toUpperCase().equals("BRIGHTHOUSE"))
                        stmt.execute("BEGIN");
                    else
                        stmt.execute("COMMIT");
                    //                                stmt.execute("SET TRANSACTION NAME 'TEST'");
                    {
                        Iterator<String> it = insert1.iterator();
                        while (it.hasNext()) {
                            stmt.addBatch(it.next());
                        }
                    }

                    if (!this.doSimplePk) {
                        //                      System.out.println("Blob insert value :" + intBlobInterval);
                        if (intBlobInterval > intBlobIntervalLimit) {
                            Iterator<String> it = insert2.iterator();
                            while (it.hasNext()) {
                                stmt.addBatch(it.next());
                            }
                            //                        intBlobInterval=0;

                        }
                    }

                    iLine = stmt.executeBatch();
                    stmt.clearBatch();
                    //                            System.out.println("Query1 = " + insert1);
                    //                            System.out.println("Query2 = " + insert2);
                    //                            stmt.execute("START TRANSACTION");
                    //                            stmt.execute(insert1);
                    //                            iLine = stmt.executeBatch();
                    //                            conn.commit();
                    long timeEnds = System.currentTimeMillis();
                    execTime = (timeEnds - timeStart);

                } catch (Exception sqle) {
                    conn.rollback();
                    if (StressTool.getErrorLogHandler() != null) {
                        StressTool.getErrorLogHandler().appendToFile(("FAILED QUERY1==" + insert1));
                        StressTool.getErrorLogHandler().appendToFile(("FAILED QUERY2==" + insert2));
                        StressTool.getErrorLogHandler().appendToFile(sqle.toString());

                    } else {
                        sqle.printStackTrace();
                        System.out.println("FAILED QUERY1==" + insert1);
                        System.out.println("FAILED QUERY2==" + insert2);
                        sqle.printStackTrace();
                        System.exit(1);
                    }
                    //conn.close();
                    //this.setJdbcUrl(jdbcUrl);
                    //System.out.println("Query Insert TH RE-INIZIALIZING");

                } finally {
                    //                           conn.commit();
                    stmt.execute("COMMIT");
                    rs.close();
                    stmt.close();
                    rs = null;
                    stmt = null;

                    //                            intDeleteInterval++;
                    if (doLog) {

                        System.out.println("Query Insert TH = " + this.getID() + " Loop N = " + repeat + " "
                                + iLine[0] + "|" + ((iLine.length > 1) ? iLine[1] : 0) + " Exec Time(ms) ="
                                + execTime + " Running = " + repeat + " of " + repeatNumber + " to go ="
                                + (repeatNumber - repeat) + " Using Lazy=" + lazy);
                    }
                }
                thInfo.setExecutedLoops(repeat);
                if (sleepFor > 0 || this.getSleepWrite() > 0) {
                    if (this.getSleepWrite() > 0) {
                        Thread.sleep(getSleepWrite());
                    } else
                        Thread.sleep(sleepFor);
                }

                conn.close();
                conn = null;
            }

            long threadTimeEnd = System.currentTimeMillis();
            this.executionTime = (threadTimeEnd - threadTimeStart);
            //                this.setExecutionTime(executionTime);
            active = false;
            //                System.out.println("Query Insert TH = " + this.getID() + " COMPLETED!  TOTAL TIME = " + execTime + "(ms) Sec =" + (execTime/1000));

            thInfo.setExecutionTime(executionTime);
            thInfo.setStatusActive(false);
            StressTool.setInfo(this.ID, thInfo);
            return;

        } catch (Exception ex) {
            if (StressTool.getErrorLogHandler() != null) {
                StressTool.getErrorLogHandler().appendToFile(ex.toString() + "\n");
            } else
                ex.printStackTrace();

            try {
                conn.close();
                conn = null;
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                if (StressTool.getErrorLogHandler() != null) {
                    StressTool.getErrorLogHandler().appendToFile(e.toString() + "\n");
                    conn = null;
                } else
                    e.printStackTrace();
            }
        }

    }

}

From source file:edu.ku.brc.specify.tasks.subpane.wb.ConfigureXLS.java

/**
 * Fills badHeads with indexes for columns that contain data but don't have a header or have an non-string header (because it makes things difficult with HSSF).
 * Fills emptyCols with indexes for columns that are totally empty.
 * Assumes that badHeads and emptyCols are not null and empty.
 * //ww  w  . j a  v  a2  s . c o m
 */
public void checkHeadsAndCols(final HSSFSheet sheet, Vector<Integer> badHeads, Vector<Integer> emptyCols) {
    boolean firstRow = true;
    Vector<Boolean> firstRowCells = new Vector<Boolean>();
    Vector<Boolean> restCells = new Vector<Boolean>();

    // Iterate over each row in the sheet
    Iterator<?> rows = sheet.rowIterator();
    while (rows.hasNext()) {
        HSSFRow row = (HSSFRow) rows.next();
        int maxSize = Math.max(row.getPhysicalNumberOfCells(), row.getLastCellNum());
        for (int col = 0; col < maxSize; col++) {
            if (firstRow) {
                if (row.getCell(col) == null) {
                    firstRowCells.add(false);
                } else if (row.getCell(col).getCellType() == HSSFCell.CELL_TYPE_STRING) {
                    firstRowCells.add(true);
                } else {
                    firstRowCells.add(null);
                }
            } else {
                if (col == restCells.size()) {
                    restCells.add(false);
                }
                if (!restCells.get(col)) {
                    restCells.set(col, row.getCell(col) != null);
                }
            }
        }
        firstRow = false;
    }

    //pad smaller vector with false if necessary.
    while (restCells.size() < firstRowCells.size()) {
        restCells.add(false);
    }
    while (firstRowCells.size() < restCells.size()) {
        firstRowCells.add(false);
    }

    for (int c = 0; c < firstRowCells.size(); c++) {
        if (firstRowCells.get(c) == null || (!firstRowCells.get(c) && restCells.get(c))) {
            badHeads.add(c);
        }
        if (firstRowCells.get(c) != null && !firstRowCells.get(c) && !restCells.get(c)) {
            emptyCols.add(c);
        }
    }
}

From source file:edu.ku.brc.specify.ui.AppBase.java

/**
 * Shows the About dialog.//from w  ww . j  a v  a 2s  .com
 */
public void doAbout() {
    AppContextMgr acm = AppContextMgr.getInstance();
    boolean hasContext = acm.hasContext();

    int baseNumRows = 9;
    String serverName = AppPreferences.getLocalPrefs().get("login.servers_selected", null);
    if (serverName != null) {
        baseNumRows++;
    }

    CellConstraints cc = new CellConstraints();
    PanelBuilder infoPB = new PanelBuilder(new FormLayout("p,6px,f:p:g",
            "p,4px,p,4px," + UIHelper.createDuplicateJGoodiesDef("p", "2px", baseNumRows)));

    JLabel iconLabel = new JLabel(IconManager.getIcon("SpecifyLargeIcon"), SwingConstants.CENTER); //$NON-NLS-1$
    PanelBuilder iconPB = new PanelBuilder(new FormLayout("p", "20px,t:p,f:p:g"));
    iconPB.add(iconLabel, cc.xy(1, 2));

    if (hasContext) {
        DBTableIdMgr tableMgr = DBTableIdMgr.getInstance();
        boolean hasReged = !RegisterSpecify.isAnonymous() && RegisterSpecify.hasInstitutionRegistered();

        int y = 1;
        infoPB.addSeparator(getResourceString("Specify.SYS_INFO"), cc.xyw(1, y, 3));
        y += 2;

        JLabel lbl = UIHelper.createLabel(databaseName);
        infoPB.add(UIHelper.createI18NFormLabel("Specify.DB"), cc.xy(1, y));
        infoPB.add(lbl, cc.xy(3, y));
        y += 2;
        lbl.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    openLocalPrefs();
                }
            }
        });

        infoPB.add(UIHelper.createFormLabel(tableMgr.getTitleForId(Institution.getClassTableId())),
                cc.xy(1, y));
        infoPB.add(lbl = UIHelper.createLabel(acm.getClassObject(Institution.class).getName()), cc.xy(3, y));
        y += 2;
        lbl.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    openRemotePrefs();
                }
            }
        });
        infoPB.add(UIHelper.createFormLabel(tableMgr.getTitleForId(Division.getClassTableId())), cc.xy(1, y));
        infoPB.add(UIHelper.createLabel(acm.getClassObject(Division.class).getName()), cc.xy(3, y));
        y += 2;

        infoPB.add(UIHelper.createFormLabel(tableMgr.getTitleForId(Discipline.getClassTableId())), cc.xy(1, y));
        infoPB.add(UIHelper.createLabel(acm.getClassObject(Discipline.class).getName()), cc.xy(3, y));
        y += 2;

        infoPB.add(UIHelper.createFormLabel(tableMgr.getTitleForId(Collection.getClassTableId())), cc.xy(1, y));
        infoPB.add(UIHelper.createLabel(acm.getClassObject(Collection.class).getCollectionName()), cc.xy(3, y));
        y += 2;

        infoPB.add(UIHelper.createI18NFormLabel("Specify.BLD"), cc.xy(1, y));
        infoPB.add(UIHelper.createLabel(appBuildVersion), cc.xy(3, y));
        y += 2;

        infoPB.add(UIHelper.createI18NFormLabel("Specify.REG"), cc.xy(1, y));
        infoPB.add(UIHelper.createI18NLabel(hasReged ? "Specify.HASREG" : "Specify.NOTREG"), cc.xy(3, y));
        y += 2;

        String isaNumber = RegisterSpecify.getISANumber();
        infoPB.add(UIHelper.createI18NFormLabel("Specify.ISANUM"), cc.xy(1, y));
        infoPB.add(UIHelper.createLabel(StringUtils.isNotEmpty(isaNumber) ? isaNumber : ""), cc.xy(3, y));
        y += 2;

        if (serverName != null) {
            infoPB.add(UIHelper.createI18NFormLabel("Specify.SERVER"), cc.xy(1, y));
            infoPB.add(UIHelper.createLabel(StringUtils.isNotEmpty(serverName) ? serverName : ""), cc.xy(3, y));
            y += 2;
        }

        if (StringUtils.contains(DBConnection.getInstance().getConnectionStr(), "mysql")) {
            Vector<Object[]> list = BasicSQLUtils.query("select version() as ve");
            if (list != null && list.size() > 0) {
                infoPB.add(UIHelper.createFormLabel("MySQL Version"), cc.xy(1, y));
                infoPB.add(UIHelper.createLabel(list.get(0)[0].toString()), cc.xy(3, y));
                y += 2;
            }
        }

        infoPB.add(UIHelper.createFormLabel("Java Version"), cc.xy(1, y));
        infoPB.add(UIHelper.createLabel(System.getProperty("java.version")), cc.xy(3, y));
        y += 2;
    }

    String txt = getAboutText(appName, appVersion);
    JLabel txtLbl = createLabel(txt);
    txtLbl.setFont(UIRegistry.getDefaultFont());

    final JEditorPane txtPane = new JEditorPane("text/html", txt);
    txtPane.setEditable(false);
    txtPane.setBackground(new JPanel().getBackground());

    PanelBuilder pb = new PanelBuilder(new FormLayout("p,20px,f:min(400px;p):g,10px,8px,10px,p:g", "f:p:g"));

    pb.add(iconPB.getPanel(), cc.xy(1, 1));
    pb.add(txtPane, cc.xy(3, 1));
    Color bg = getBackground();

    if (hasContext) {
        pb.add(new VerticalSeparator(bg.darker(), bg.brighter()), cc.xy(5, 1));
        pb.add(infoPB.getPanel(), cc.xy(7, 1));
    }

    pb.setDefaultDialogBorder();

    String title = getResourceString("Specify.ABOUT");//$NON-NLS-1$
    CustomDialog aboutDlg = new CustomDialog(topFrame, title + " " + appName, true, CustomDialog.OK_BTN, //$NON-NLS-1$
            pb.getPanel());
    String okLabel = getResourceString("Specify.CLOSE");//$NON-NLS-1$
    aboutDlg.setOkLabel(okLabel);

    aboutDlg.createUI();
    aboutDlg.pack();

    // for some strange reason I can't get the dialog to size itself correctly
    Dimension size = aboutDlg.getSize();
    size.height += 120;
    aboutDlg.setSize(size);

    txtPane.addHyperlinkListener(new HyperlinkListener() {
        public void hyperlinkUpdate(HyperlinkEvent event) {
            if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                try {
                    AttachmentUtils.openURI(event.getURL().toURI());

                } catch (Exception e) {
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                }
            }
        }
    });

    UIHelper.centerAndShow(aboutDlg);
}

From source file:com.iucosoft.eavertizare.gui.MainJFrame.java

private void jButtonExportPdfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonExportPdfActionPerformed
    Vector element = new Vector();
    for (int i = 0; i < firmeListModel.getSize(); i++) {
        element.add(firmeListModel.getElementAt(i));
    }//w  w w .ja  v  a2  s  .c  om
    final JComboBox<String> combo = new JComboBox<>(element);
    String[] options = { "OK", "Cancel" };
    String title = "Selctati firma!";
    int selection = JOptionPane.showOptionDialog(null, combo, title, JOptionPane.DEFAULT_OPTION,
            JOptionPane.PLAIN_MESSAGE, null, options, element.get(0));
    try {
        if (options[selection].equals("OK")) {
            Object firmaSelectata = combo.getSelectedItem();
            if (firmaSelectata.equals("All firms")) {
                clientiTableModel.refreshModel();
            } else {
                clientiTableModel.refreshModel((String) firmaSelectata);
            }
            Export.toPdf(this, jTableClients, (String) firmaSelectata);
            clientiTableModel.refreshModel();
        }
    } catch (Exception e) {
    }
}

From source file:cm.aptoide.pt.RemoteInSearch.java

@Override
protected void onListItemClick(ListView l, View v, final int position, long id) {

    super.onListItemClick(l, v, position, id);

    Vector<String> tmp_get = db.getApk(apk_lst.get(position).apkid);

    String tmp_path = this.getString(R.string.icons_path) + apk_lst.get(position).apkid;
    File test_icon = new File(tmp_path);

    LayoutInflater li = LayoutInflater.from(this);
    View view = li.inflate(R.layout.alertscroll, null);
    Builder alrt = new AlertDialog.Builder(this).setView(view);
    final AlertDialog p = alrt.create();
    if (test_icon.exists() && test_icon.length() > 0) {
        p.setIcon(new BitmapDrawable(tmp_path));
    } else {//from  w w  w  . ja v a  2 s . c om
        p.setIcon(android.R.drawable.sym_def_app_icon);
    }
    p.setTitle(apk_lst.get(position).name);
    TextView t1 = (TextView) view.findViewById(R.id.n11);
    t1.setText(tmp_get.firstElement());
    TextView t2 = (TextView) view.findViewById(R.id.n22);
    t2.setText(tmp_get.get(1));
    TextView t3 = (TextView) view.findViewById(R.id.n33);
    t3.setText(tmp_get.get(2));
    TextView t4 = (TextView) view.findViewById(R.id.n44);
    t4.setText(tmp_get.get(3));
    TextView t5 = (TextView) view.findViewById(R.id.n55);
    String tmpi = db.getDescript(apk_lst.get(position).apkid);
    if (!(tmpi == null)) {
        t5.setText(tmpi);
    } else {
        t5.setText("No info availale on server. Search market by pressing the button below for more info.");
    }

    p.setButton2("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            return;
        }
    });
    if (tmp_get.get(2).equalsIgnoreCase("\tno\n")) {
        p.setButton(getString(R.string.install), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                p.dismiss();
                new Thread() {
                    public void run() {
                        String apk_pkg = downloadFile(position);
                        if (apk_pkg == null) {
                            Message msg = new Message();
                            msg.arg1 = 1;
                            download_handler.sendMessage(msg);
                            download_error_handler.sendEmptyMessage(0);
                        } else {
                            installApk(apk_pkg, position);
                        }
                    }
                }.start();
            }
        });
        p.setButton3("Search Market", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                p.dismiss();
                Intent intent = new Intent();
                intent.setAction(android.content.Intent.ACTION_VIEW);
                intent.setData(Uri.parse("market://details?id=" + apk_lst.get(position).apkid));
                startActivity(intent);
            }
        });
    } else {
        p.setButton(getString(R.string.rem), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String apk_pkg = apk_lst.get(position).apkid;
                removeApk(apk_pkg, position);
            }
        });
        if (apk_lst.get(position).status == 2) {
            p.setButton3(getString(R.string.update), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    p.dismiss();
                    new Thread() {
                        public void run() {
                            String apk_pkg = downloadFile(position);
                            if (apk_pkg == null) {
                                //Toast.makeText(RemoteInSearch.this, "Could not connect to server!", Toast.LENGTH_LONG).show();
                                Message msg = new Message();
                                msg.arg1 = 1;
                                download_handler.sendMessage(msg);
                                download_error_handler.sendEmptyMessage(0);
                            } else {
                                installApk(apk_pkg, position);
                            }
                        }
                    }.start();
                }
            });
        } else {
            p.setButton3("Search Market", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    p.dismiss();
                    Intent intent = new Intent();
                    intent.setAction(android.content.Intent.ACTION_VIEW);
                    intent.setData(Uri.parse("market://details?id=" + apk_lst.get(position).apkid));
                    startActivity(intent);
                }
            });
        }
    }
    p.show();
}