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:com.yahoo.messenger.data.notification.json.ResponseList.java

public void unserializeJSON(JSONArray a) throws JSONException {

    Vector v = new Vector();

    //  Mandatory fields

    for (int i = 0; i < a.length(); i++) {

        JSONObject o = a.getJSONObject(i);

        if (o.has("message")) {
            Message c = new Message();
            c.unserializeJSON(o.getJSONObject("message"));
            v.addElement(c);//  w w w.j a v a 2s  .com
        }
        if (o.has("buddyInfo")) {
            BuddyInfo c = new BuddyInfo();
            c.unserializeJSON(o.getJSONObject("buddyInfo"));
            v.addElement(c);
        }
    }

    responses = new Response[v.size()];
    v.copyInto(responses);

}

From source file:edu.umn.cs.spatialHadoop.nasa.StockQuadTree.java

/**
 * Creates a full spatio-temporal hierarchy for a source folder
 * @throws ParseException /*from w ww  .  ja  v a2  s  .c  om*/
 * @throws InterruptedException 
 */
public static void directoryIndexer(final OperationsParams params)
        throws IOException, ParseException, InterruptedException {
    Path inputDir = params.getInputPath();
    FileSystem sourceFs = inputDir.getFileSystem(params);
    final Path sourceDir = inputDir.makeQualified(sourceFs);
    Path destDir = params.getOutputPath();
    final FileSystem destFs = destDir.getFileSystem(params);

    TimeRange timeRange = params.get("time") != null ? new TimeRange(params.get("time")) : null;

    // Create daily indexes that do not exist
    final Path dailyIndexDir = new Path(destDir, "daily");
    FileStatus[] mathcingDays = timeRange == null ? sourceFs.listStatus(inputDir)
            : sourceFs.listStatus(inputDir, timeRange);
    final Vector<Path> sourceFiles = new Vector<Path>();
    for (FileStatus matchingDay : mathcingDays) {
        for (FileStatus matchingTile : sourceFs.listStatus(matchingDay.getPath())) {
            sourceFiles.add(matchingTile.getPath());
        }

    }
    // Shuffle the array for better load balancing across threads
    Collections.shuffle(sourceFiles);
    final String datasetName = params.get("dataset");
    Parallel.forEach(sourceFiles.size(), new RunnableRange<Object>() {
        @Override
        public Object run(int i1, int i2) {
            LOG.info("Worker [" + i1 + "," + i2 + ") started");
            for (int i = i1; i < i2; i++) {
                Path sourceFile = sourceFiles.get(i);
                try {
                    Path relativeSourceFile = makeRelative(sourceDir, sourceFile);
                    Path destFilePath = new Path(dailyIndexDir, relativeSourceFile);
                    if (!destFs.exists(destFilePath)) {
                        LOG.info("Worker [" + i1 + "," + i2 + ") indexing: " + sourceFile.getName());
                        Path tmpFile;
                        do {
                            tmpFile = new Path((int) (Math.random() * 1000000) + ".tmp");
                        } while (destFs.exists(tmpFile));
                        tmpFile = tmpFile.makeQualified(destFs);
                        if (datasetName == null)
                            throw new RuntimeException(
                                    "Please provide the name of dataset you would like to index");
                        AggregateQuadTree.build(params, sourceFile, datasetName, tmpFile);
                        synchronized (destFs) {
                            Path destDir = destFilePath.getParent();
                            if (!destFs.exists(destDir))
                                destFs.mkdirs(destDir);
                        }
                        destFs.rename(tmpFile, destFilePath);
                    }
                } catch (IOException e) {
                    throw new RuntimeException("Error building an index for " + sourceFile, e);
                }
            }
            LOG.info("Worker [" + i1 + "," + i2 + ") finished");
            return null;
        }

    });
    LOG.info("Done generating daily indexes");

    // Merge daily indexes into monthly indexes
    Path monthlyIndexDir = new Path(destDir, "monthly");
    final SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy.MM.dd");
    final SimpleDateFormat monthFormat = new SimpleDateFormat("yyyy.MM");
    mergeIndexes(destFs, dailyIndexDir, monthlyIndexDir, dayFormat, monthFormat, params);
    LOG.info("Done generating monthly indexes");

    // Merge daily indexes into monthly indexes
    Path yearlyIndexDir = new Path(destDir, "yearly");
    final SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
    mergeIndexes(destFs, monthlyIndexDir, yearlyIndexDir, monthFormat, yearFormat, params);
    LOG.info("Done generating yearly indexes");
}

From source file:BugTrackerJFace.java

private void saveBugs(Vector v) {
    // Save bugs to a file.
    DataOutputStream out = null;/*from  w  ww .j  a v  a 2 s  .c  o m*/
    try {
        File file = new File("bugs.dat");

        out = new DataOutputStream(new FileOutputStream(file));

        for (int i = 0; i < v.size(); i++) {
            Bug bug = (Bug) v.elementAt(i);
            out.writeUTF(bug.id);
            out.writeUTF(bug.summary);
            out.writeUTF(bug.assignedTo);
            out.writeBoolean(bug.isSolved);
        }
    } catch (IOException ioe) {
        // Ignore.
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:FileTree3.java

public boolean expand(DefaultMutableTreeNode parent) {
    DefaultMutableTreeNode flag = (DefaultMutableTreeNode) parent.getFirstChild();
    if (flag == null) // No flag
        return false;
    Object obj = flag.getUserObject();
    if (!(obj instanceof Boolean))
        return false; // Already expanded

    parent.removeAllChildren(); // Remove Flag

    File[] files = listFiles();/*from  w w w . ja  v a2s .c o  m*/
    if (files == null)
        return true;

    Vector v = new Vector();

    for (int k = 0; k < files.length; k++) {
        File f = files[k];
        if (!(f.isDirectory()))
            continue;

        FileNode newNode = new FileNode(f);

        boolean isAdded = false;
        for (int i = 0; i < v.size(); i++) {
            FileNode nd = (FileNode) v.elementAt(i);
            if (newNode.compareTo(nd) < 0) {
                v.insertElementAt(newNode, i);
                isAdded = true;
                break;
            }
        }
        if (!isAdded)
            v.addElement(newNode);
    }

    for (int i = 0; i < v.size(); i++) {
        FileNode nd = (FileNode) v.elementAt(i);
        IconData idata = new IconData(FileTree3.ICON_FOLDER, FileTree3.ICON_EXPANDEDFOLDER, nd);
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(idata);
        parent.add(node);

        if (nd.hasSubDirs())
            node.add(new DefaultMutableTreeNode(new Boolean(true)));
    }

    return true;
}

From source file:gov.nih.nci.evs.browser.utils.SimpleSearchUtils.java

public ResolvedConceptReferencesIteratorWrapper search(Vector<String> schemes, Vector<String> versions,
        String matchText, int searchOption, String algorithm) throws LBException {
    System.out.println("search by " + matchText + ", algorithm: " + algorithm);

    if (schemes == null || versions == null)
        return null;
    if (schemes.size() != versions.size())
        return null;
    if (schemes.size() == 0)
        return null;
    if (matchText == null)
        return null;
    if (searchOption != BY_CODE && searchOption != BY_NAME)
        return null;
    if (searchOption != BY_CODE && algorithm == null)
        return null;

    LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService();

    if (lbSvc == null) {
        return null;
    }//from  w w w .  j a v  a2 s . c  o  m

    SearchExtension searchExtension = null;
    try {
        searchExtension = (SearchExtension) lbSvc.getGenericExtension("SearchExtension");
    } catch (Exception e) {
        _logger.warn("SearchExtension is not available.");
        return null;
    }

    Set<CodingSchemeReference> includes = new HashSet();

    for (int i = 0; i < schemes.size(); i++) {
        String scheme = (String) schemes.elementAt(i);
        String version = (String) versions.elementAt(i);
        System.out.println("\t" + scheme + " (" + version + ")");
        CodingSchemeReference ref = new CodingSchemeReference();
        ref.setCodingScheme(scheme);

        if (version != null) {
            CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
            versionOrTag.setVersion(version);
        }
        includes.add(ref);
    }

    ResolvedConceptReferencesIterator iterator = null;
    try {
        iterator = searchExtension.search(matchText, includes, converToMatchAlgorithm(searchOption, algorithm));
        printNumberOfMatches(iterator);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    if (iterator != null) {
        return new ResolvedConceptReferencesIteratorWrapper(iterator);
    }
    return null;
}

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

private String getExtension(Vector outputTypes, String content_type) {
    String ret = "html";
    if (outputTypes == null) {
        return ret;
    }/*w w  w. ja  v  a  2 s. c  o m*/
    if (content_type == null) {
        return ret;
    }

    for (int i = 0; i < outputTypes.size(); i++) {
        Hashtable outType = (Hashtable) outputTypes.get(i);
        if (outType == null) {
            continue;
        }
        if (!outType.containsKey("conv_type") || !outType.containsKey("file_ext")
                || outType.get("conv_type") == null || outType.get("file_ext") == null) {
            continue;
        }
        String typeId = (String) outType.get("conv_type");
        if (!content_type.equalsIgnoreCase(typeId)) {
            continue;
        }
        ret = (String) outType.get("file_ext");
    }

    return ret;
}

From source file:com.duroty.application.files.manager.StoreManager.java

/**
 * DOCUMENT ME!//from  w  w w  . j  a va2  s  .  co  m
 *
 * @param hsession DOCUMENT ME!
 * @param session DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param identity DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param cc DOCUMENT ME!
 * @param bcc DOCUMENT ME!
 * @param subject DOCUMENT ME!
 * @param body DOCUMENT ME!
 * @param attachments DOCUMENT ME!
 * @param isHtml DOCUMENT ME!
 * @param charset DOCUMENT ME!
 * @param headers DOCUMENT ME!
 * @param priority DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public void send(org.hibernate.Session hsession, Session session, String repositoryName, Vector files,
        int label, String charset) throws FilesException {
    ByteArrayInputStream bais = null;
    FileOutputStream fos = null;

    try {
        if ((files == null) || (files.size() <= 0)) {
            return;
        }

        if (charset == null) {
            charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName());
        }

        Users user = getUser(hsession, repositoryName);
        Identity identity = getDefaultIdentity(hsession, user);

        InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName());
        InternetAddress _to = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());

        for (int i = 0; i < files.size(); i++) {
            MultiPartEmail email = email = new MultiPartEmail();
            email.setCharset(charset);

            if (_from != null) {
                email.setFrom(_from.getAddress(), _from.getPersonal());
            }

            if (_returnPath != null) {
                email.addHeader("Return-Path", _returnPath.getAddress());
                email.addHeader("Errors-To", _returnPath.getAddress());
                email.addHeader("X-Errors-To", _returnPath.getAddress());
            }

            if (_replyTo != null) {
                email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal());
            }

            if (_to != null) {
                email.addTo(_to.getAddress(), _to.getPersonal());
            }

            MailPartObj obj = (MailPartObj) files.get(i);

            email.setSubject("Files-System " + obj.getName());

            Date now = new Date();
            email.setSentDate(now);

            File dir = new File(System.getProperty("user.home") + File.separator + "tmp");

            if (!dir.exists()) {
                dir.mkdir();
            }

            File file = new File(dir, obj.getName());

            bais = new ByteArrayInputStream(obj.getAttachent());
            fos = new FileOutputStream(file);
            IOUtils.copy(bais, fos);

            IOUtils.closeQuietly(bais);
            IOUtils.closeQuietly(fos);

            EmailAttachment attachment = new EmailAttachment();
            attachment.setPath(file.getPath());
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setDescription("File Attachment: " + file.getName());
            attachment.setName(file.getName());

            email.attach(attachment);

            String mid = getId();
            email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">");
            email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">");

            email.addHeader("X-DBox", "FILES");

            email.addHeader("X-DRecent", "false");

            //email.setMsg(body);
            email.setMailSession(session);

            email.buildMimeMessage();

            MimeMessage mime = email.getMimeMessage();

            int size = MessageUtilities.getMessageSize(mime);

            if (!controlQuota(hsession, user, size)) {
                throw new MailException("ErrorMessages.mail.quota.exceded");
            }

            messageable.storeMessage(mid, mime, user);
        }
    } catch (FilesException e) {
        throw e;
    } catch (Exception e) {
        throw new FilesException(e);
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();
        throw new FilesException(ex);
    } catch (Throwable e) {
        throw new FilesException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(fos);
    }
}

From source file:edu.ku.brc.specify.tasks.StatsTrackerTask.java

/**
 * @param stats//w w  w  .  j  a  v a2 s.  c om
 */
private void appendCollectingStats(final Vector<NameValuePair> stats) {
    final String ALL_YEAR_CATS = "ALL_YEAR_CATS_STAT";
    final String LAST_COL_YEAR_STAT = "LAST_COL_YEAR_STAT";
    //final String LAST_30_DAYS  = "LAST_30DAYS_STAT"; 

    int currentYear = Calendar.getInstance().get(Calendar.YEAR);

    AppPreferences remotePrefs = AppPreferences.getRemote();
    int lastColYear = remotePrefs.getInt(LAST_COL_YEAR_STAT, -1);
    boolean doAllYears = remotePrefs.getBoolean(ALL_YEAR_CATS, true);

    if (lastColYear != currentYear) // override when it is a new year
    {
        doAllYears = true;
    }

    StringBuilder allYearsSB = new StringBuilder();
    StringBuilder last30DaysSB = new StringBuilder();

    for (Object[] colRow : BasicSQLUtils
            .query("SELECT CollectionID,CollectionName,RegNumber FROM collection")) {
        Integer colId = (Integer) colRow[0];
        String colNm = (String) colRow[1];
        String regNum = (String) colRow[2];

        if (doAllYears) {
            String sql = String.format(
                    "SELECT YR,COUNT(YR) FROM (SELECT YEAR(if (CatalogedDate IS NULL, TimestampCreated, CatalogedDate)) AS YR FROM collectionobject WHERE CollectionMemberID = %d) T1 GROUP BY YR ORDER BY YR",
                    colId);
            collectStatsData(colNm, regNum, sql, allYearsSB);
        }

        // Cataloged by Month for current year
        String tmp = "SELECT MN, COUNT(MN) FROM (SELECT MONTH(DT) MN, YEAR(DT) YR FROM (SELECT if (CatalogedDate IS NULL, TimestampCreated, CatalogedDate) AS DT FROM collectionobject WHERE CollectionMemberID = %d) T1 WHERE YEAR(DT) = %d) T2 GROUP BY MN";
        String sql = String.format(tmp, colId, currentYear);
        collectStatsData(colNm, regNum, sql, last30DaysSB);
    }

    if (doAllYears) {
        addEncodedPair(stats, "catbyyr", allYearsSB.toString());
        remotePrefs.putBoolean(ALL_YEAR_CATS, false);
        remotePrefs.putInt(LAST_COL_YEAR_STAT, currentYear);
    }

    addEncodedPair(stats, "catbymn", last30DaysSB.toString());

    // Audit Information 
    Vector<Object[]> instRresults = BasicSQLUtils.query("SELECT Name, RegNumber FROM institution");
    if (instRresults.size() > 0) {
        Object[] instRow = instRresults.get(0);
        String instName = (String) instRow[0];
        String regNum = (String) instRow[1];

        String[] actionStr = { "ins", "upd", "rmv" };
        for (int action = 0; action < 3; action++) {
            StringBuilder auditSB = new StringBuilder();
            String tmp = "SELECT * FROM (SELECT a.TableNum, Count(a.TableNum) as Cnt FROM spauditlog AS a WHERE a.Action = %d GROUP BY a.TableNum) T1 ORDER BY Cnt DESC";
            String sql = String.format(tmp, action);
            collectStatsData(instName, regNum, sql, auditSB);
            addEncodedPair(stats, "audit_" + actionStr[action], auditSB.toString());
        }
    }
}

From source file:net.sf.jabref.sql.exporter.DatabaseExporter.java

private String getDBName(Vector<Vector<String>> matrix, DBStrings databaseStrings, JabRefFrame frame,
        DBImportExportDialog dialogo) throws Exception {
    String dbName = "";
    if (matrix.size() > 1) {
        if (dialogo.hasDBSelected) {
            dbName = dialogo.selectedDB;
            if ((dialogo.selectedInt == 0) && (!dialogo.removeAction)) {
                dbName = JOptionPane.showInputDialog(dialogo.getDiag(),
                        Localization.lang("Please enter the desired name:"), Localization.lang("SQL Export"),
                        JOptionPane.INFORMATION_MESSAGE);
                if (dbName == null) {
                    getDBName(matrix, databaseStrings, frame,
                            new DBImportExportDialog(frame, matrix, DBImportExportDialog.DialogType.EXPORTER));
                } else {
                    while (!isValidDBName(dbNames, dbName)) {
                        dbName = JOptionPane.showInputDialog(dialogo.getDiag(),
                                Localization.lang("You have entered an invalid or already existent DB name.")
                                        + '\n' + Localization.lang("Please enter the desired name:"),
                                Localization.lang("SQL Export"), JOptionPane.ERROR_MESSAGE);
                    }// w  ww. ja  v  a  2s.  c o m
                }
            }
        }
    } else {
        dbName = JOptionPane.showInputDialog(frame, Localization.lang("Please enter the desired name:"),
                Localization.lang("SQL Export"), JOptionPane.INFORMATION_MESSAGE);
    }
    return dbName;
}

From source file:dao.DirectoryListAuthorQuery.java

/** 
  * This method lists all the authors for a directory
  * @param conn the connection/*from   w  w  w. j a  v  a 2 s .  c om*/
  * @param directoryId the directory id
  * @return HashSet the set that has the list of authors for this directory.
  * @throws BaseDaoException
  * @author Smitha Gudur (smitha@redbasin.com)
  * @version $Revision: 1.1 $
  */

/* Uses tables - directory, diradmin, hdlogin  */
public HashSet run(Connection conn, String directoryid) throws BaseDaoException {

    String sqlQuery = "select distinct CONCAT(hd.fname,' ',hd.lname) AS membername, "
            + "hd.login, hd.loginid, d1.directoryid, d1.dirname from directory d1, "
            + "diradmin d2, hdlogin hd where d2.ownerid=hd.loginid "
            + "and d1.directoryid=d2.directoryid and d1.directoryid=" + directoryid + " order by hd.login ASC";
    logger.info("sqlQuery = " + sqlQuery);
    try {
        PreparedStatement stmt = conn.prepareStatement(sqlQuery);
        ResultSet rs = stmt.executeQuery();
        Vector columnNames = null;
        Directory directory = null;
        HashSet dirSet = new HashSet();

        if (rs != null) {
            // get column names and types from rsmd and save to local array in object
            //DbUtils dbutils = new DbUtils();
            columnNames = dbutils.getColumnNames(rs);
        } else {
            return null;
        }

        while (rs.next()) {
            directory = (Directory) eop.newObject(DbConstants.DIRECTORY);
            for (int j = 0; j < columnNames.size(); j++) {
                directory.setValue((String) columnNames.elementAt(j),
                        (String) rs.getString((String) columnNames.elementAt(j)));
            }
            dirSet.add(directory);
        }
        return dirSet;
    } catch (Exception e) {
        throw new BaseDaoException(
                "Error occured while executing directory moderatorslist run query " + sqlQuery, e);
    }
}