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:br.com.scalasoft.alvaro.weather.FetchWeatherTask.java

String[] convertContentValuesToUXFormat(Vector<ContentValues> cvv) {
    // return strings to keep UI functional for now
    String[] resultStrs = new String[cvv.size()];
    for (int i = 0; i < cvv.size(); i++) {
        ContentValues weatherValues = cvv.elementAt(i);
        String highAndLow = formatHighLows(weatherValues.getAsDouble(WeatherEntry.COLUMN_MAX_TEMP),
                weatherValues.getAsDouble(WeatherEntry.COLUMN_MIN_TEMP));
        resultStrs[i] = getReadableDateString(weatherValues.getAsLong(WeatherEntry.COLUMN_DATE)) + " - "
                + weatherValues.getAsString(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC) + " - "
                + highAndLow;/*from  w  ww.  ja v  a  2  s. co m*/
    }
    return resultStrs;
}

From source file:dao.PblogSearchBizAwareQuery.java

/**
 * This method lists all the results for the search text from pblogs
 * @param conn the connection/*from www .  j  a  v a 2 s.  c o m*/
 * @param sString - search text
 * @param bid - bid
 * @return HashSet the set that has the list of search result
 * @throws BaseDaoException - when error occurs
 **/
public HashSet run(Connection conn, String sString, String bid) throws BaseDaoException {

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

    ResultSet rs = null;
    StringBuffer sb = new StringBuffer(
            "select hdlogin.loginid, hdlogin.login, hdlogin.fname, lname, LEFT(message, 160) as info, entrydate, tid, hits, hdlogin.bid, business.bsearch from business, hdlogin left join pblogtopics on hdlogin.loginid=pblogtopics.pblogid left join pblog on hdlogin.loginid=pblog.loginid where business.bid=hdlogin.bid and (");
    ArrayList columns = new ArrayList();
    columns.add("topic");
    columns.add("message");
    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;
        Blog pblog = null;
        HashSet pendingSet = new HashSet();

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

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

From source file:dao.PblogSearchQuery.java

/**
 * This method lists all the results for the search text from pblogs
 * @param conn the connection/*from ww w  .java 2  s. co  m*/
 * @param sString
 * @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, hdlogin.login, hdlogin.fname, lname, LEFT(message, 160) as info, entrydate, usertags, pblogtopics.tid as ptid, hits from hdlogin left join pblogtopics on hdlogin.loginid=pblogtopics.pblogid left join pblogtags on pblogtopics.tid=pblogtags.tid left join pblog on hdlogin.loginid=pblog.loginid where ");

    // StringBuffer sb = new StringBuffer("select 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("topic");
    columns.add("message");
    columns.add("usertags");
    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;
        Blog pblog = null;
        HashSet pendingSet = new HashSet();

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

        while (rs.next()) {
            pblog = (Blog) eop.newObject(DbConstants.BLOG);
            for (int j = 0; j < columnNames.size(); j++) {
                if (((String) (columnNames.elementAt(j))).equalsIgnoreCase("entrydate")) {
                    try {
                        pblog.setValue("entrydate",
                                GlobalConst.dncalendar.getDisplayDate(rs.getTimestamp("entrydate")));
                        logger.info("entrydate" + rs.getTimestamp("entrydate"));
                    } catch (ParseException e) {
                        throw new BaseDaoException(
                                "could not parse the date for entrydate in PblogSearchQuery()"
                                        + rs.getTimestamp("entrydate"),
                                e);
                    }
                } else {
                    pblog.setValue((String) columnNames.elementAt(j),
                            (String) rs.getString((String) columnNames.elementAt(j)));
                }
            }
            pendingSet.add(pblog);
        }
        return pendingSet;
    } catch (Exception e) {
        throw new BaseDaoException("Error occured while executing search in pblog run query ", e);
    }
}

From source file:net.sf.jabref.exporter.layout.LayoutEntry.java

public LayoutEntry(StringInt si, final String classPrefix_) {
    type = si.i;//w w w  .  ja  va 2  s .c  o m
    classPrefix = classPrefix_;

    if (type == LayoutHelper.IS_LAYOUT_TEXT) {
        text = si.s;
    } else if (type == LayoutHelper.IS_SIMPLE_FIELD) {
        text = si.s.trim();
    } else if ((type == LayoutHelper.IS_FIELD_START) || (type == LayoutHelper.IS_FIELD_END)) {
        // Do nothing
    } else if (type == LayoutHelper.IS_OPTION_FIELD) {
        Vector<String> v = new Vector<>();
        WSITools.tokenize(v, si.s, "\n");

        if (v.size() == 1) {
            text = v.get(0);
        } else {
            text = v.get(0).trim();

            option = LayoutEntry.getOptionalLayout(v.get(1), classPrefix);
            // See if there was an undefined formatter:
            for (LayoutFormatter anOption : option) {
                if (anOption instanceof NotFoundFormatter) {
                    String notFound = ((NotFoundFormatter) anOption).getNotFound();

                    if (invalidFormatter == null) {
                        invalidFormatter = new ArrayList<>();
                    }
                    invalidFormatter.add(notFound);
                }
            }

        }
    }
}

From source file:com.bt.aloha.sipstone.GenGraph.java

public Map<String, List<Double>> readFile(String fileName) {
    File f = new File(fileName);
    HashMap<String, List<Double>> ret = new HashMap<String, List<Double>>();
    try {//from   ww  w .jav  a 2s  . co m
        BufferedReader br = new BufferedReader(new FileReader(f));
        String line;
        List<String> headers = null;
        Vector<String> lines = new Vector<String>();
        while (null != (line = br.readLine())) {
            lines.add(line);
        }
        // last two lines are not needed
        lines.remove(1);
        lines.remove(1);
        lines.remove(lines.size() - 1);
        for (int row = 0; row < lines.size(); row++) {
            line = lines.get(row);
            System.out.println(line);
            if (row == 0) {
                headers = populateMapWithHeaders(ret, line);
            } else {
                populateMapWithData(ret, line, headers);
            }
        }
    } catch (FileNotFoundException e) {
        throw new IllegalArgumentException("Unable to open " + fileName);
    } catch (IOException e) {
        throw new IllegalArgumentException("Unable to read " + fileName);
    }
    return ret;
}

From source file:net.sf.ginp.commands.UploadConfig.java

/**
 *  Handle admin request to upload an new configuration file.
 *
 * @param  model   Description of the Parameter
 * @param  params  Description of the Parameter
 *//*from  w  w w .j  a  v a2s .  c o m*/
public final void action(final GinpModel model, final Vector params) {
    // Check we do not have a state of bad config.
    if (Configuration.configOK()) {
        return;
    }

    File confFile = new File(Configuration.getConfigfilelocation());

    // check that file is not there.
    if (confFile.exists()) {
        log.error("Config File there but NOT OK.  Fix it or remove it.");

        return;
    }

    for (int i = 0; i < params.size(); i++) {
        CommandParameter param = (CommandParameter) params.get(i);
        log.debug(param.getName() + " = " + param.getValue());

        if (param.getName().equals("configfile")) {
            try {
                InputStream is = (InputStream) param.getObject();
                InputStreamReader isr = new InputStreamReader(is);
                FileWriter fw = new FileWriter(confFile);
                int b = isr.read();

                while (b != -1) {
                    fw.write(b);
                    b = isr.read();
                }

                fw.flush();
            } catch (Exception ex) {
                log.error("Error writing Config File from upload stream.", ex);
            }
        }
    }

    if (Configuration.configOK()) {
        log.info("Uploaded valid Config");
    }

    model.setUserName("admin");
    model.setCurrentPage("setup2.jsp");
}

From source file:dao.VisitTrafficCityCountryQuery.java

/**
 * This method lists all the results for the geotarget text from directories
 * @param conn the connection/*from   w  ww. j ava 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 List run(Connection conn, String ipAddress) throws BaseDaoException {

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

    List ip = GlobalConst.httputil.parseIP4(ipAddress);
    StringBuffer iptable = new StringBuffer("ip4_");
    iptable.append(ip.get(0));

    int b = new Integer((String) ip.get(1)).intValue();
    int c = new Integer((String) ip.get(2)).intValue();

    Statement stmt = null;
    ResultSet rs = null;

    /*        String sb = select c3.b, c3.c, c1.name, c2.name as country, c1.state from geodb.cityByCountry c1, geodb.ip4_192 c3 left join geodb.countries c2 on c3.country=c2.id where b=(select substring_index(substring_index(kailash.visittraffic.ipaddress,'.',-3), '.', 1) as visitb from kailash.visittraffic) and c=0 limit 10; */

    String sb = "select state from cityByCountry as geo, " + iptable.toString() + " as iptable where b=" + b
            + " and c=" + c
            + " and geo.country=iptable.country and geo.city=iptable.city and (geo.state like '%New York%' or geo.state like '%California%') limit 1";

    /*
    "b" = select substring_index(substring_index(ipaddress, '.', -3), '.', 1) from visittraffic limit 3;
    "c" = select substring_index(substring_index(ipaddress, '.', -2), '.', 1) from visittraffic limit 3;
            
    iptable= select c4.ipaddress, CONCAT("ip_4",(substring_index(substring_index(c4.ipaddress,'.', 1), '.',1))) as iptable from kailash.visittraffic c4 ;
    */
    try {
        stmt = conn.createStatement();
        if (stmt == null) {
            return null;
        }

        rs = stmt.executeQuery(sb);

        Vector columnNames = null;
        Userpage userpage = null;
        List pendingList = new ArrayList();

        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++) {
                userpage.setValue((String) columnNames.elementAt(j),
                        (String) rs.getString((String) columnNames.elementAt(j)));
            }
            pendingList.add(userpage);
        }
        return pendingList;
    } catch (Exception e) {
        throw new BaseDaoException("Error occured while executing geotarget run query ", e);
    }
}

From source file:com.sonaive.v2ex.ui.debug.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 w w . j a  v  a 2s  .  com
@Override
protected void onHandleIntent(Intent workIntent) {

    BroadcastNotifier mBroadcaster = new BroadcastNotifier(this);
    // 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[] { ModiDates._ID, ModiDates.MODI_DATE };

    // 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(ModiDates.CONTENT_URI, 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()) {

                long storedModifiedDate = cursor.getLong(cursor.getColumnIndex(ModiDates.MODI_DATE));

                /*
                 * 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();

                localPicasaPullParser.parseXml(localURLConnection.getInputStream(), mBroadcaster);

                // 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(PicasaImages.CONTENT_URI, imageValuesArray);

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

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

                if (newMetadataRetrieved) {

                    // No previous metadata existed, so insert the data
                    getContentResolver().insert(ModiDates.CONTENT_URI, dateValues);
                } else {

                    // Previous metadata existed, so update it.
                    getContentResolver().update(ModiDates.CONTENT_URI, dateValues,
                            ModiDates._ID + "=" + cursor.getString(cursor.getColumnIndex(ModiDates._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:com.xpn.xwiki.plugin.calendar.CalendarData.java

/**
 * List populating method. It iterates the CalendarEvent objects stored in the given document and creates Java
 * wrappers that can be used by the Calendar plugin.
 * //from w  w  w .j  ava 2 s .  c  o m
 * @param doc The source document, populated with CalendarEvent objects.
 * @param defaultUser The username to be used ig objects do not have a User field.
 * @throws XWikiException
 */
public void addCalendarData(XWikiDocument doc, String defaultUser, XWikiContext context) throws XWikiException {
    if (doc == null) {
        return;
    }

    if (!context.getWiki().getRightService().hasAccessLevel("view", context.getUser(), doc.getFullName(),
            context)) {
        return;
    }

    if (defaultUser == null) {
        BaseObject bobj = doc.getObject("XWiki.XWikiUsers");
        if (bobj == null) {
            defaultUser = doc.getCreator();
        } else {
            defaultUser = doc.getFullName();
        }
    }

    String defaultDescription = "";
    String defaultURL = "";
    defaultDescription = "[" + doc.getDisplayTitle(context) + ">" + doc.getFullName() + "]";
    defaultURL = doc.getURL("view", context);

    Vector bobjs = doc.getObjects("XWiki.CalendarEvent");
    if (bobjs != null) {
        for (int i = 0; i < bobjs.size(); ++i) {
            try {
                BaseObject bobj = (BaseObject) bobjs.get(i);
                String user = "";
                try {
                    user = (String) ((StringProperty) bobj.get("user")).getValue();
                } catch (Exception e) {
                }

                String description = "";
                try {
                    description = (String) ((LargeStringProperty) bobj.get("description")).getValue();
                } catch (Exception e) {
                }

                String title = "";
                try {
                    title = (String) ((StringProperty) bobj.get("title")).getValue();
                } catch (Exception e) {
                }
                if (StringUtils.isBlank(title)) {
                    title = doc.getDisplayTitle(context);
                }

                String url = "";
                try {
                    url = (String) ((StringProperty) bobj.get("url")).getValue();
                } catch (Exception e) {
                }

                String location = "";
                try {
                    location = (String) ((StringProperty) bobj.get("location")).getValue();
                } catch (Exception e) {
                }

                List category = null;
                try {
                    category = (List) ((StringListProperty) bobj.get("category")).getValue();
                } catch (Exception e) {
                }

                Date dateStart = null;
                try {
                    dateStart = (Date) ((DateProperty) bobj.get("startDate")).getValue();
                } catch (Exception e) {
                }

                Date dateEnd = null;
                try {
                    dateEnd = (Date) ((DateProperty) bobj.get("endDate")).getValue();
                } catch (Exception e) {
                }

                if ((user == null) || user.equals("")) {
                    user = defaultUser;
                }

                if (dateStart == null) {
                    dateStart = dateEnd;
                }
                if (dateEnd == null) {
                    dateEnd = dateStart;
                }

                if ((dateStart == null) || (dateEnd == null)) {
                    continue;
                }

                if (dateStart.getTime() > dateEnd.getTime()) {
                    Date dateTemp = dateStart;
                    dateStart = dateEnd;
                    dateEnd = dateTemp;
                }

                if ((description == null) || description.equals("")) {
                    description = defaultDescription;
                }

                if ((url == null) || url.equals("")) {
                    url = defaultURL;
                }

                Calendar cdateStart = Calendar.getInstance();
                cdateStart.setTime(dateStart);
                Calendar cdateEnd = Calendar.getInstance();
                cdateEnd.setTime(dateEnd);
                addCalendarData(new CalendarEvent(cdateStart, cdateEnd, user, description, title, category, url,
                        location));
            } catch (Exception e) {
                // Let's continue in case of failure
                e.printStackTrace();
            }
        }
    }
}

From source file:gsn.http.A3DWebServiceImpl.java

public String[] getSensorLocation(String sensor) {

    VSensorConfig sensorConfig = Mappings.getVSensorConfig(sensor);
    Vector<String> sensorLocation = new Vector<String>();
    for (KeyValue df : sensorConfig.getAddressing())
        sensorLocation/* w w w. java  2 s  .  co m*/
                .add(StringEscapeUtils.escapeXml(df.getKey().toString()) + "=" + df.getValue().toString());

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

    return v_sensorLocation;

}