Example usage for java.util Vector size

List of usage examples for java.util Vector size

Introduction

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

Prototype

public synchronized int size() 

Source Link

Document

Returns the number of components in this vector.

Usage

From source file:admin.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w ww .j av  a2 s. c om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    response.setContentType("application/json;charset=UTF-8");
    String id = "";
    String nama = "";
    String email = "";
    String link = "";
    String admin = "";
    String icw = "";
    try {
        JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
        id = userAccount.get("id").toString();
        nama = userAccount.get("name").toString();
        email = userAccount.get("email").toString();
        link = userAccount.get("link").toString();
        admin = userAccount.get("admin").toString();
        icw = userAccount.get("icw").toString();
    } catch (Exception ex1) {
    }
    if (admin.equalsIgnoreCase("Y")) {
        try (PrintWriter out = response.getWriter()) {
            Vector dataPosisi = new Vector();
            dataPosisi.addElement("Menteri");
            dataPosisi.addElement("Pejabat Setingkat Menteri");
            dataPosisi.addElement("Duta Besar");
            JSONArray obj1 = new JSONArray();
            for (int i = 0; i < dataPosisi.size(); i++) {
                String FilterKey = "", FilterValue = "";
                String key = "posisi",
                        keyValue = dataPosisi.get(i).toString().toLowerCase().replaceAll(" ", "");
                String table = "posisi";
                DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
                //Filter linkFilter = new FilterPredicate(FilterKey, FilterOperator.EQUAL, FilterValue);
                Key AlasanStarCalonKey = KeyFactory.createKey(key, keyValue);
                Query query = new Query(table, AlasanStarCalonKey);
                PreparedQuery pq = datastore.prepare(query);
                JSONArray obj11 = new JSONArray();
                getData(obj11, table, key, keyValue, dataPosisi.get(i).toString(),
                        Query.SortDirection.ASCENDING);
                LinkedHashMap record = new LinkedHashMap();
                record.put("posisi", keyValue);
                record.put("nama", dataPosisi.get(i).toString());
                record.put("child", obj11);
                obj1.add(record);
            }
            out.print(JSONValue.toJSONString(obj1));
            out.flush();
        }
    }
}

From source file:eionet.gdem.qa.XQueryService.java

/**
 * Request from XML/RPC client Stores the source files and starts a job in the workqueue.
 *
 * @param files - Structure with XMLschemas as a keys and values are list of XML Files
 * @return Hashtable result: Structure with JOB ids as a keys and source files as values
 *//*from   ww  w.jav  a  2s. c  om*/
public Vector analyzeXMLFiles(Hashtable files) throws GDEMException {

    Vector result = new Vector();

    if (files == null) {
        return result;
    }

    Enumeration _schemas = files.keys();
    while (_schemas.hasMoreElements()) {
        String _schema = _schemas.nextElement().toString();
        Vector _files = (Vector) files.get(_schema);
        if (Utils.isNullVector(_files)) {
            continue;
        }

        for (int i = 0; i < _files.size(); i++) {
            String _file = (String) _files.get(i);
            analyzeXMLFiles(_schema, _file, result);
        }
    }
    return result;
}

From source file:com.example.android.threadsample.RSSPullService.java

/**
 * In an IntentService, onHandleIntent is run on a background thread.  As it
 * runs, it broadcasts its current status using the LocalBroadcastManager.
 * @param workIntent The Intent that starts the IntentService. This Intent contains the
 * URL of the web site from which the RSS parser gets data.
 *///from w  ww . j  a v  a 2 s . c  o  m
@Override
protected void onHandleIntent(Intent workIntent) {
    // Gets a URL to read from the incoming Intent's "data" value
    String localUrlString = workIntent.getDataString();

    // Creates a projection to use in querying the modification date table in the provider.
    final String[] dateProjection = new String[] { DataProviderContract.ROW_ID,
            DataProviderContract.DATA_DATE_COLUMN };

    // A URL that's local to this method
    URL localURL;

    // A cursor that's local to this method.
    Cursor cursor = null;

    /*
     * A block that tries to connect to the Picasa featured picture URL passed as the "data"
     * value in the incoming Intent. The block throws exceptions (see the end of the block).
     */
    try {

        // Convert the incoming data string to a URL.
        localURL = new URL(localUrlString);

        /*
         * Tries to open a connection to the URL. If an IO error occurs, this throws an
         * IOException
         */
        URLConnection localURLConnection = localURL.openConnection();

        // If the connection is an HTTP connection, continue
        if ((localURLConnection instanceof HttpURLConnection)) {

            // Broadcasts an Intent indicating that processing has started.
            mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_STARTED);

            // Casts the connection to a HTTP connection
            HttpURLConnection localHttpURLConnection = (HttpURLConnection) localURLConnection;

            // Sets the user agent for this request.
            localHttpURLConnection.setRequestProperty("User-Agent", Constants.USER_AGENT);

            /*
             * Queries the content provider to see if this URL was read previously, and when.
             * The content provider throws an exception if the URI is invalid.
             */
            cursor = getContentResolver().query(DataProviderContract.DATE_TABLE_CONTENTURI, dateProjection,
                    null, null, null);

            // Flag to indicate that new metadata was retrieved
            boolean newMetadataRetrieved;

            /*
             * Tests to see if the table contains a modification date for the URL
             */
            if (null != cursor && cursor.moveToFirst()) {

                // Find the URL's last modified date in the content provider
                long storedModifiedDate = cursor
                        .getLong(cursor.getColumnIndex(DataProviderContract.DATA_DATE_COLUMN));

                /*
                 * If the modified date isn't 0, sets another request property to ensure that
                 * data is only downloaded if it has changed since the last recorded
                 * modification date. Formats the date according to the RFC1123 format.
                 */
                if (0 != storedModifiedDate) {
                    localHttpURLConnection.setRequestProperty("If-Modified-Since",
                            org.apache.http.impl.cookie.DateUtils.formatDate(new Date(storedModifiedDate),
                                    org.apache.http.impl.cookie.DateUtils.PATTERN_RFC1123));
                }

                // Marks that new metadata does not need to be retrieved
                newMetadataRetrieved = false;

            } else {

                /*
                 * No modification date was found for the URL, so newmetadata has to be
                 * retrieved.
                 */
                newMetadataRetrieved = true;

            }

            // Reports that the service is about to connect to the RSS feed
            mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_CONNECTING);

            // Gets a response code from the RSS server
            int responseCode = localHttpURLConnection.getResponseCode();

            switch (responseCode) {

            // If the response is OK
            case HttpStatus.SC_OK:

                // Gets the last modified data for the URL
                long lastModifiedDate = localHttpURLConnection.getLastModified();

                // Reports that the service is parsing
                mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_PARSING);

                /*
                 * Instantiates a pull parser and uses it to parse XML from the RSS feed.
                 * The mBroadcaster argument send a broadcaster utility object to the
                 * parser.
                 */
                RSSPullParser localPicasaPullParser = new RSSPullParser();

                try {
                    localPicasaPullParser.parseXml(localURLConnection.getInputStream(), mBroadcaster);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                // Reports that the service is now writing data to the content provider.
                mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_WRITING);

                // Gets image data from the parser
                Vector<ContentValues> imageValues = localPicasaPullParser.getImages();

                // Stores the number of images
                int imageVectorSize = imageValues.size();

                // Creates one ContentValues for each image
                ContentValues[] imageValuesArray = new ContentValues[imageVectorSize];

                imageValuesArray = imageValues.toArray(imageValuesArray);

                /*
                 * Stores the image data in the content provider. The content provider
                 * throws an exception if the URI is invalid.
                 */
                getContentResolver().bulkInsert(DataProviderContract.PICTUREURL_TABLE_CONTENTURI,
                        imageValuesArray);

                // Creates another ContentValues for storing date information
                ContentValues dateValues = new ContentValues();

                // Adds the URL's last modified date to the ContentValues
                dateValues.put(DataProviderContract.DATA_DATE_COLUMN, lastModifiedDate);

                if (newMetadataRetrieved) {

                    // No previous metadata existed, so insert the data
                    getContentResolver().insert(DataProviderContract.DATE_TABLE_CONTENTURI, dateValues);

                } else {

                    // Previous metadata existed, so update it.
                    getContentResolver().update(DataProviderContract.DATE_TABLE_CONTENTURI, dateValues,
                            DataProviderContract.ROW_ID + "="
                                    + cursor.getString(cursor.getColumnIndex(DataProviderContract.ROW_ID)),
                            null);
                }
                break;

            }

            // Reports that the feed retrieval is complete.
            mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_COMPLETE);
        }

        // Handles possible exceptions
    } catch (MalformedURLException localMalformedURLException) {

        localMalformedURLException.printStackTrace();

    } catch (IOException localIOException) {

        localIOException.printStackTrace();

    } catch (XmlPullParserException localXmlPullParserException) {

        localXmlPullParserException.printStackTrace();

    } finally {

        // If an exception occurred, close the cursor to prevent memory leaks.
        if (null != cursor) {
            cursor.close();
        }
    }
}

From source file:dao.UserSearchQuery.java

/**
 * This method lists all the results for the search text from directories
 * @param conn the connection/*w ww .j av  a  2  s . co m*/
 * @param collabrumId the collabrumid
 * @return HashSet the set that has the list of moderators for these collabrums.
 * @throws BaseDaoException - when error occurs
 **/
public HashSet run(Connection conn, String sString) throws BaseDaoException {

    if ((RegexStrUtil.isNull(sString) || conn == null)) {
        return null;
    }

    ResultSet rs = null;
    StringBuffer sb = new StringBuffer(
            "select hdlogin.loginid, login, fname, lname, hits, membersince, LEFT(description, 160) as info from hdlogin left join usertab on hdlogin.loginid=usertab.loginid left join yourkeywords on hdlogin.loginid=yourkeywords.loginid left join mykeywords on hdlogin.loginid=mykeywords.loginid where ");

    ArrayList columns = new ArrayList();
    columns.add("login");
    columns.add("email");
    columns.add("description");
    columns.add("fname");
    columns.add("lname");
    columns.add("interests");
    columns.add("yourkeyword");
    columns.add("keyword");
    //columns.add("industry");
    columns.add("city");
    sb.append(sqlSearch.getConstraint(columns, sString));
    sb.append(" group by login order by hits DESC");
    logger.info("search query string" + sb.toString());

    try {
        PreparedStatement stmt = conn.prepareStatement(sb.toString());
        rs = stmt.executeQuery();

        Vector columnNames = null;
        Userpage userpage = null;
        HashSet pendingSet = new HashSet();

        if (rs != null) {
            columnNames = dbutils.getColumnNames(rs);
        } else {
            return null;
        }

        while (rs.next()) {
            userpage = (Userpage) eop.newObject(DbConstants.USER_PAGE);
            for (int j = 0; j < columnNames.size(); j++) {
                if (((String) (columnNames.elementAt(j))).equalsIgnoreCase("membersince")) {
                    try {
                        userpage.setValue(DbConstants.DATE,
                                GlobalConst.dncalendar.getDisplayDate(rs.getTimestamp("membersince")));
                    } catch (ParseException e) {
                        throw new BaseDaoException(
                                "could not parse the date for membersince in UserSearchQuery()"
                                        + rs.getTimestamp("membersince"),
                                e);
                    }
                } else {
                    userpage.setValue((String) columnNames.elementAt(j),
                            (String) rs.getString((String) columnNames.elementAt(j)));
                }
            }
            pendingSet.add(userpage);
        }
        return pendingSet;
    } catch (Exception e) {
        throw new BaseDaoException(
                "Error occured while executing search in userpage run query " + sb.toString(), e);
    }
}

From source file:dao.UserSearchBizAwareQuery.java

/**
 * This method lists all the results for the search text from directories
 * @param conn the connection//from   w w w  .j a  v a  2  s . com
 * @param collabrumId the collabrumid
 * @return HashSet the set that has the list of moderators for these collabrums.
 * @throws BaseDaoException - when error occurs
 **/
public HashSet run(Connection conn, String sString, String bid) throws BaseDaoException {

    if (RegexStrUtil.isNull(sString) || conn == null || RegexStrUtil.isNull(bid)) {
        return null;
    }

    ResultSet rs = null;
    //StringBuffer sb = new StringBuffer("select distinct c2.login, c2.fname, c2.lname, c1.hits, c1.membersince, LEFT(c1.description, 160) as info from usertab c1 left outer join hdlogin c2 on c1.loginid=c2.loginid where "); 

    StringBuffer sb = new StringBuffer(
            "select login, fname, lname, hits, membersince, LEFT(description, 160) as info, hdlogin.bid, bsearch from business, hdlogin left join usertab on hdlogin.loginid=usertab.loginid left join yourkeywords on hdlogin.loginid=yourkeywords.loginid left join mykeywords on hdlogin.loginid=mykeywords.loginid where business.bid=hdlogin.bid and (");

    ArrayList columns = new ArrayList();
    columns.add("description");
    columns.add("fname");
    columns.add("lname");
    columns.add("interests");
    columns.add("yourkeyword");
    columns.add("keyword");
    //columns.add("industry");
    columns.add("city");
    sb.append(sqlSearch.getConstraint(columns, sString));
    sb.append(") group by login order by hits DESC");
    logger.info("search query string" + sb.toString());

    try {
        PreparedStatement stmt = conn.prepareStatement(sb.toString());
        rs = stmt.executeQuery();

        Vector columnNames = null;
        Userpage userpage = null;
        HashSet pendingSet = new HashSet();

        if (rs != null) {
            columnNames = dbutils.getColumnNames(rs);
        } else {
            return null;
        }

        while (rs.next()) {
            userpage = (Userpage) eop.newObject(DbConstants.USER_PAGE);
            for (int j = 0; j < columnNames.size(); j++) {
                if (((String) (columnNames.elementAt(j))).equalsIgnoreCase("membersince")
                        && (rs.getTimestamp("membersince") != null)) {
                    try {
                        userpage.setValue(DbConstants.DATE,
                                GlobalConst.dncalendar.getDisplayDate(rs.getTimestamp("membersince")));
                    } catch (ParseException e) {
                        throw new BaseDaoException(
                                "could not parse the date for membersince in UserSearchBizAwareQuery()"
                                        + rs.getTimestamp("membersince"),
                                e);
                    }
                } else {
                    userpage.setValue((String) columnNames.elementAt(j),
                            (String) rs.getString((String) columnNames.elementAt(j)));
                }
            }
            pendingSet.add(userpage);
        }
        return pendingSet;
    } catch (Exception e) {
        throw new BaseDaoException(
                "Error occured while executing search in userpage run query " + sb.toString(), e);
    }
}

From source file:net.nosleep.superanalyzer.analysis.views.GenreView.java

private void refreshDataset() {
    Hashtable genres = _analysis.getHash(Analysis.KIND_GENRE);

    Vector items = new Vector();
    Enumeration e = genres.keys();
    while (e.hasMoreElements()) {
        String genreName = (String) e.nextElement();
        Genre genre = (Genre) genres.get(genreName);
        items.add(new GenreItem(genreName, genre.getStats().getTrackCount()));
    }/*  w w w.j av a2  s.  c  o m*/

    Collections.sort(items, new GenreItemComparator());

    for (int i = 0; i < items.size(); i++) {
        GenreItem item = (GenreItem) items.elementAt(i);

        _dataset.addValue(item.Count, Misc.getString("GENRE"), item.GenreName);
    }
}

From source file:ch.algotrader.adapter.ib.DefaultIBOrderMessageFactory.java

@Override
public Order createOrderMessage(SimpleOrder order, Contract contract) {

    com.ib.client.Order ibOrder = new com.ib.client.Order();
    ibOrder.m_totalQuantity = (int) order.getQuantity();
    ibOrder.m_action = IBUtil.getIBSide(order.getSide());
    ibOrder.m_orderType = IBUtil.getIBOrderType(order);
    ibOrder.m_transmit = true;/*from w w  w .  ja  va2 s  .c o m*/

    // overwrite the default exchange (defined by SecurityFamily) in case a different exchange is defined on the order
    if (order.getExchange() != null) {
        contract.m_exchange = order.getExchange().getIbCode();
    }

    // handle a potentially defined account
    if (order.getAccount().getExtAccount() != null) {

        ibOrder.m_account = order.getAccount().getExtAccount();

        // handling for financial advisor account groups
    } else if (order.getAccount().getExtAccountGroup() != null) {

        ibOrder.m_faGroup = order.getAccount().getExtAccountGroup();
        ibOrder.m_faMethod = this.iBConfig.getFaMethod();

        //            long existingQuantity = 0;
        //            for (Position position : order.getSecurity().getPositions()) {
        //                existingQuantity += position.getQuantity();
        //            }
        //
        //            // evaluate weather the transaction is opening or closing
        //            boolean opening = false;
        //            if (existingQuantity > 0 && Side.SELL.equals(order.getSide())) {
        //                opening = false;
        //            } else if (existingQuantity <= 0 && Side.SELL.equals(order.getSide())) {
        //                opening = true;
        //            } else if (existingQuantity < 0 && Side.BUY.equals(order.getSide())) {
        //                opening = false;
        //            } else if (existingQuantity >= 0 && Side.BUY.equals(order.getSide())) {
        //                opening = true;
        //            }
        //
        //            ibOrder.m_faGroup = order.getAccount().getExtAccountGroup();
        //
        //            if (opening) {
        //
        //                // open by specifying the actual quantity
        //                ibOrder.m_faMethod = this.faOpenMethod;
        //
        //            } else {
        //
        //                // reduce by percentage
        //                ibOrder.m_faMethod = "PctChange";
        //                ibOrder.m_totalQuantity = 0; // bacause the order is percent based
        //                ibOrder.m_faPercentage = "-" + Math.abs(order.getQuantity() * 100 / (existingQuantity - order.getQuantity()));
        //            }

        // handling for financial advisor allocation profiles
    } else if (order.getAccount().getExtAllocationProfile() != null) {

        ibOrder.m_faProfile = order.getAccount().getExtAllocationProfile();
    }

    // add clearing information
    if (order.getAccount().getExtClearingAccount() != null) {
        ibOrder.m_clearingAccount = order.getAccount().getExtClearingAccount();
        ibOrder.m_clearingIntent = "Away";
    }

    //set the limit price if order is a limit order or stop limit order
    if (order instanceof LimitOrderI) {
        LimitOrderI limitOrder = (LimitOrderI) order;
        ibOrder.m_lmtPrice = PriceUtil.denormalizePrice(order, limitOrder.getLimit());
    }

    //set the stop price if order is a stop order or stop limit order
    if (order instanceof StopOrderI) {
        StopOrderI stopOrder = (StopOrderI) order;
        ibOrder.m_auxPrice = PriceUtil.denormalizePrice(order, stopOrder.getStop());
    }

    // set Time-In-Force (ATC are set as order types LOC and MOC)
    if (order.getTif() != null && !TIF.ATC.equals(order.getTif())) {
        ibOrder.m_tif = order.getTif().name();

        // set the TIF-Date
        if (order.getTifDateTime() != null) {
            ibOrder.m_goodTillDate = format.format(DateTimeLegacy.toLocalDateTime(order.getTifDateTime()));
        }
    }

    // separate properties that correspond to IB Order fields from the rest
    Map<String, OrderProperty> propertiesMap = new HashMap<>(order.getOrderProperties());
    for (Field field : FieldUtil.getAllFields(ibOrder.getClass())) {
        String name = field.getName().substring(2);
        OrderProperty orderProperty = propertiesMap.get(name);
        if (orderProperty != null && OrderPropertyType.IB.equals(orderProperty.getType())) {
            try {
                Object value = this.convertUtils.convert(orderProperty.getValue(), field.getType());
                field.set(ibOrder, value);
            } catch (IllegalAccessException e) {
                throw new ServiceException(e.getMessage(), e);
            }
            propertiesMap.remove(name);
        }
    }

    // add remaining params as AlgoParams
    Vector<TagValue> params = new Vector<>();
    for (OrderProperty orderProperty : propertiesMap.values()) {
        if (OrderPropertyType.IB.equals(orderProperty.getType())) {
            params.add(new TagValue(orderProperty.getName(), orderProperty.getValue()));
        }
    }

    if (params.size() > 0) {
        ibOrder.m_algoParams = params;
    }

    return ibOrder;
}

From source file:edu.ku.brc.af.core.expresssearch.QueryForIdResultsSQL.java

public String getSQL(final String searchTermArg, final Vector<Integer> ids) {
    if (StringUtils.isNotEmpty(overrideSQL)) {
        return overrideSQL;
    }//from   ww w. java2 s .  c o m

    Vector<Integer> tempIds = ids == null ? recIds : ids;
    // else
    StringBuilder idsStr = new StringBuilder(recIds.size() * 8);
    for (int i = 0; i < tempIds.size(); i++) {
        if (i > 0)
            idsStr.append(',');
        idsStr.append(tempIds.elementAt(i).toString());
    }

    String sqlStr;
    if (getJoinColTableId() != null) {
        String joinIdName = null;
        for (ERTIJoinColInfo jci : tableInfo.getJoins()) {
            if (joinColTableId == jci.getJoinTableIdAsInt()) {
                joinIdName = jci.getColName();
            }
        }

        String critiera = (tableInfo.isFieldNameOnlyForSQL() ? StringUtils.substringAfterLast(joinIdName, ".") //$NON-NLS-1$
                : joinIdName) + " in (" + idsStr.toString() + ")"; //$NON-NLS-1$ //$NON-NLS-2$

        //System.out.println("["+critiera+"]");
        sqlStr = String.format(tableInfo.getViewSql(), new Object[] { joinIdName, critiera });
        //System.out.println("["+sqlStr+"]");
        sqlStr = QueryAdjusterForDomain.getInstance().adjustSQL(sqlStr);

    } else {
        String vsql = getTableInfo().getViewSql();
        sqlStr = idsStr.length() > 0 ? vsql.replace("%s", idsStr.toString()) : vsql; //$NON-NLS-1$
    }
    return sqlStr;
}

From source file:com.greenpepper.server.rpc.xmlrpc.XmlRpcDataMarshaller.java

/**
 * <p>toExecution.</p>//  ww w. ja v a  2  s .  c o m
 *
 * @param xmlRpcParameters a {@link java.util.Vector} object.
 * @return a {@link com.greenpepper.server.domain.Execution} object.
 */
public static Execution toExecution(Vector<Object> xmlRpcParameters) {
    Execution execution = new Execution();
    execution.setResults(toNullIfEmpty((String) xmlRpcParameters.get(EXECUTION_RESULTS_IDX)));
    execution.setExecutionErrorId(toNullIfEmpty((String) xmlRpcParameters.get(EXECUTION_ERRORID_IDX)));
    execution.setFailures((Integer) xmlRpcParameters.get(EXECUTION_FAILIURES_IDX));
    execution.setErrors((Integer) xmlRpcParameters.get(EXECUTION_ERRORS_IDX));
    execution.setSuccess((Integer) xmlRpcParameters.get(EXECUTION_SUCCESS_IDX));
    execution.setIgnored((Integer) xmlRpcParameters.get(EXECUTION_IGNORED_IDX));
    FormatedDate date = new FormatedDate((String) xmlRpcParameters.get(EXECUTION_EXECUTION_DATE_IDX));
    execution.setExecutionDate(date.asTimestamp());
    if (xmlRpcParameters.size() >= EXECUTION_LOGS_OUT_IDX) {
        execution.setStdoutLogs(toNullIfEmpty((String) xmlRpcParameters.get(EXECUTION_LOGS_OUT_IDX)));
    }
    if (xmlRpcParameters.size() >= EXECUTION_LOGS_ERR_IDX) {
        execution.setStderrLogs(toNullIfEmpty((String) xmlRpcParameters.get(EXECUTION_LOGS_ERR_IDX)));
    }
    return execution;
}

From source file:edu.ku.brc.specify.config.FixDBAfterLogin.java

/**
 * //from   w w w.  j a  va  2  s .  c om
 */
public static void fixGTPTreeDefParents() {
    int fixed = 0;
    String updateSQL = "UPDATE geologictimeperiodtreedefitem SET ParentItemID=? WHERE GeologicTimePeriodTreeDefItemID=?";

    Connection conn = DBConnection.getInstance().getConnection();
    PreparedStatement pStmt = null;
    try {
        pStmt = conn.prepareStatement(updateSQL);

        Vector<Integer> gtpTreeDefIds = BasicSQLUtils.queryForInts(
                "SELECT GeologicTimePeriodTreeDefID FROM geologictimeperiodtreedef ORDER BY GeologicTimePeriodTreeDefID");
        for (Integer defId : gtpTreeDefIds) {
            String sql = String.format(
                    "SELECT COUNT(*) FROM geologictimeperiodtreedefitem WHERE ParentItemID IS NULL AND GeologicTimePeriodTreeDefID=%d",
                    defId);
            if (BasicSQLUtils.getCount(sql) == 1)
                continue;

            sql = String.format(
                    "SELECT GeologicTimePeriodTreeDefItemID FROM geologictimeperiodtreedefitem WHERE GeologicTimePeriodTreeDefID=%d ORDER BY RankID",
                    defId);
            Vector<Integer> gtpTreeDefItemIds = BasicSQLUtils.queryForInts(sql);
            Vector<Integer> parentIds = new Vector<Integer>();
            parentIds.add(-1);

            for (int i = 1; i < gtpTreeDefItemIds.size(); ++i) {
                parentIds.add(gtpTreeDefItemIds.get(i - 1));
            }

            fixed = 0;
            for (int i = 1; i < gtpTreeDefItemIds.size(); ++i) {
                log.debug(String.format("Node: %d  -> Parent: %d", gtpTreeDefItemIds.get(i), parentIds.get(i)));
                pStmt.setInt(1, parentIds.get(i));
                pStmt.setInt(2, gtpTreeDefItemIds.get(i));
                int rv = pStmt.executeUpdate();
                if (rv != 1) {
                    log.error("Error updating GTP TreeDef Item PArent");
                }
                fixed++;
            }
            log.debug(String.format("Fixed %d/%d", fixed, gtpTreeDefItemIds.size() - 1));
        }

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

    } finally {
        try {
            if (pStmt != null)
                pStmt.close();
        } catch (SQLException e) {
        }
    }
}