Example usage for java.util Vector add

List of usage examples for java.util Vector add

Introduction

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

Prototype

public synchronized boolean add(E e) 

Source Link

Document

Appends the specified element to the end of this Vector.

Usage

From source file:edu.cornell.med.icb.geo.tools.MicroarrayTrainEvaluate.java

public static void filterColumns(final Table result, final Set<String> keepSet) {
    final Vector<String> toRemove = new Vector<String>();
    for (int i = 0; i < result.getColumnNumber(); i++) {

        final String identifier = result.getIdentifier(i);
        if (!keepSet.contains(identifier)) {
            toRemove.add(identifier);
        }/*  w ww . j  a v a2 s. c om*/
    }
    for (final String columnIdf : toRemove) {
        try {
            result.removeColumn(columnIdf);
        } catch (InvalidColumnException e) {
            e.printStackTrace();
            assert false : e;
        }
    }

}

From source file:com.symbian.driver.remoting.packaging.build.PackageBuilder.java

/**
 * @param directory/*from w  w  w . ja  va2s  . c  o m*/
 * @param filter
 * @param recurse
 * @return
 */
public static Collection<File> listFiles(File directory, FilenameFilter filter, boolean recurse) {
    // List of files / directories
    Vector<File> files = new Vector<File>();

    // Get files / directories in the directory
    File[] entries = directory.listFiles();

    // Go over entries
    for (int i = 0; i < entries.length; i++) {
        File entry = entries[i];

        // If there is no filter or the filter accepts the
        // file / directory, add it to the list
        if (filter == null || filter.accept(directory, entry.getName())) {
            files.add(entry);
        }

        // If the file is a directory and the recurse flag
        // is set, recurse into the directory
        if (recurse && entry.isDirectory()) {
            files.addAll(listFiles(entry, filter, recurse));
        }
    }

    // Return collection of files
    return files;
}

From source file:mzmatch.util.Tool.java

/**
 * /*from w  w w.  j a v  a  2s  .  co  m*/
 * 
 * @param pckgname
 * @return
 * @throws ClassNotFoundException
 */
public static Vector<Class<? extends Object>> getAllClasses(String pckgname) throws ClassNotFoundException {
    Vector<Class<? extends Object>> classes = new Vector<Class<? extends Object>>();

    // load the current package
    ClassLoader cld = Thread.currentThread().getContextClassLoader();
    if (cld == null)
        throw new ClassNotFoundException("Can't get class loader.");

    String path = pckgname.replace('.', '/');
    URL resource = cld.getResource(path);
    if (resource == null)
        throw new ClassNotFoundException("No resource for " + path);

    // parse the directory
    File directory = new File(resource.getFile());
    if (directory.isDirectory() && directory.exists()) {
        for (File f : directory.listFiles()) {
            if (f.getName().endsWith(".class"))
                classes.add(Class.forName(pckgname + '.' + f.getName().substring(0, f.getName().length() - 6)));
        }
        for (File f : directory.listFiles()) {
            if (f.isDirectory())
                classes.addAll(getAllClasses(pckgname + "." + f.getName()));
        }
    } else
        throw new ClassNotFoundException(pckgname + " does not appear to be a valid package");

    return classes;
}

From source file:anslab2.AnsLab2.java

public static DefaultTableModel generateTable(boolean fdt, boolean rft, int dataType, ArrayList labels,
        String label) {/*  ww w. ja  va  2s .co m*/
    //DefaultTableModel model = new DefaultTableModel();

    HashMap<String, Integer> map = new HashMap<String, Integer>();

    for (Object temp : labels) {
        Integer count = map.get(String.valueOf(temp));
        map.put(String.valueOf(temp), (count == null) ? 1 : count + 1);
    }

    Vector _label = new Vector();
    Vector _freq = new Vector();
    Vector _rel_freq = new Vector();

    if (dataType == 1 || dataType == 3) {
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            _label.add(entry.getKey());
            _freq.add(entry.getValue());
            _rel_freq.add(((double) entry.getValue() / labels.size()) * (100));
        }
        string_maps = map;
        model.addColumn(label, _label);
    }

    else if (dataType == 2) {
        TreeMap<Double, Integer> num_map = new TreeMap<Double, Integer>();

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            num_map.put(Double.valueOf(entry.getKey()), entry.getValue());
        }

        for (Map.Entry<Double, Integer> entry1 : num_map.entrySet()) {
            _label.add(entry1.getKey());
            _freq.add(entry1.getValue());
            _rel_freq.add(round(((double) entry1.getValue() / labels.size()) * (100), 2));
        }
        double_maps = num_map;
        model.addColumn(label, _label);
    }

    if (fdt == true) {
        model.addColumn("Frequency", _freq);
    }
    if (rft == true) {
        model.addColumn("Relative Frequency", _rel_freq);
    }

    return model;
}

From source file:de.betterform.agent.web.WebUtil.java

private static Vector<BasicClientCookie> saveAsBasicClientCookie(Iterator iterator,
        Vector<BasicClientCookie> commonsCookies) {
    while (iterator.hasNext()) {
        javax.servlet.http.Cookie c = (Cookie) iterator.next();
        BasicClientCookie commonsCookie = new BasicClientCookie(c.getName(), c.getValue());
        commonsCookie.setDomain(c.getDomain());
        commonsCookie.setPath(c.getPath());
        commonsCookie.setAttribute(ClientCookie.MAX_AGE_ATTR, Integer.toString(c.getMaxAge()));
        commonsCookie.setSecure(c.getSecure());

        commonsCookies.add(commonsCookie);

        if (WebUtil.LOGGER.isDebugEnabled()) {
            WebUtil.LOGGER.debug("adding cookie >>>>>");
            WebUtil.LOGGER.debug("name: " + c.getName());
            WebUtil.LOGGER.debug("value: " + c.getValue());
            WebUtil.LOGGER.debug("path: " + c.getPath());
            WebUtil.LOGGER.debug("maxAge: " + c.getMaxAge());
            WebUtil.LOGGER.debug("secure: " + c.getSecure());
            WebUtil.LOGGER.debug("adding cookie done <<<<<");
        }/*from w ww .  jav a  2 s  . c o  m*/
    }

    return commonsCookies;
}

From source file:net.java.sip.communicator.impl.history.HistoryReaderImpl.java

/**
 * Used to limit the files if any starting or ending date exist
 * So only few files to be searched./*w  w  w .java  2  s.c om*/
 *
 * @param filelist Iterator
 * @param startDate Date
 * @param endDate Date
 * @param reverseOrder reverse order of files
 * @return Vector
 */
static Vector<String> filterFilesByDate(Iterator<String> filelist, Date startDate, Date endDate,
        final boolean reverseOrder) {
    if (startDate == null && endDate == null) {
        // no filtering needed then just return the same list
        Vector<String> result = new Vector<String>();
        while (filelist.hasNext()) {
            result.add(filelist.next());
        }

        Collections.sort(result, new Comparator<String>() {

            public int compare(String o1, String o2) {
                if (reverseOrder)
                    return o2.compareTo(o1);
                else
                    return o1.compareTo(o2);
            }
        });

        return result;
    }
    // first convert all files to long
    TreeSet<Long> files = new TreeSet<Long>();
    while (filelist.hasNext()) {
        String filename = filelist.next();

        files.add(Long.parseLong(filename.substring(0, filename.length() - 4)));
    }

    TreeSet<Long> resultAsLong = new TreeSet<Long>();

    // Temporary fix of a NoSuchElementException
    if (files.size() == 0) {
        return new Vector<String>();
    }

    Long startLong;
    Long endLong;

    if (startDate == null)
        startLong = Long.MIN_VALUE;
    else
        startLong = startDate.getTime();

    if (endDate == null)
        endLong = Long.MAX_VALUE;
    else
        endLong = endDate.getTime();

    // get all records inclusive the one before the startdate
    for (Long f : files) {
        if (startLong <= f && f <= endLong) {
            resultAsLong.add(f);
        }
    }

    // get the subset before the start date, to get its last element
    // if exists
    if (!files.isEmpty() && files.first() <= startLong) {
        SortedSet<Long> setBeforeTheInterval = files.subSet(files.first(), true, startLong, true);
        if (!setBeforeTheInterval.isEmpty())
            resultAsLong.add(setBeforeTheInterval.last());
    }

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

    Iterator<Long> iter = resultAsLong.iterator();
    while (iter.hasNext()) {
        Long item = iter.next();
        result.add(item.toString() + ".xml");
    }

    Collections.sort(result, new Comparator<String>() {

        public int compare(String o1, String o2) {
            if (reverseOrder)
                return o2.compareTo(o1);
            else
                return o1.compareTo(o2);
        }
    });

    return result;
}

From source file:com.ricemap.spateDB.mapred.FileSplitUtil.java

/**
 * Combines a number of input splits into the given numSplits.
 * @param conf//  ww w . j  a v  a  2  s.  com
 * @param inputSplits
 * @param numSplits
 * @return
 * @throws IOException 
 */
public static InputSplit[] autoCombineSplits(JobConf conf, Vector<FileSplit> inputSplits, int numSplits)
        throws IOException {
    LOG.info("Combining " + inputSplits.size() + " splits into " + numSplits);
    Map<String, Vector<FileSplit>> blocksPerHost = new HashMap<String, Vector<FileSplit>>();
    for (FileSplit fsplit : inputSplits) {
        // Get locations for this split
        final Path path = fsplit.getPath();
        final FileSystem fs = path.getFileSystem(conf);
        BlockLocation[] blockLocations = fs.getFileBlockLocations(fs.getFileStatus(path), fsplit.getStart(),
                fsplit.getLength());
        for (BlockLocation blockLocation : blockLocations) {
            for (String hostName : blockLocation.getHosts()) {
                if (!blocksPerHost.containsKey(hostName))
                    blocksPerHost.put(hostName, new Vector<FileSplit>());
                blocksPerHost.get(hostName).add(fsplit);
            }
        }
    }

    // If the user requested a fewer number of splits, start to combine them
    InputSplit[] combined_splits = new InputSplit[numSplits];
    int splitsAvailable = inputSplits.size();

    for (int i = 0; i < numSplits; i++) {
        // Decide how many splits to combine
        int numSplitsToCombine = splitsAvailable / (numSplits - i);
        Vector<FileSplit> splitsToCombine = new Vector<FileSplit>();
        while (numSplitsToCombine > 0) {
            // Choose the host with minimum number of splits
            Map.Entry<String, Vector<FileSplit>> minEntry = null;
            for (Map.Entry<String, Vector<FileSplit>> entry : blocksPerHost.entrySet()) {
                if (minEntry == null || entry.getValue().size() < minEntry.getValue().size()) {
                    minEntry = entry;
                }
            }
            // Combine all or some of blocks in this host
            for (FileSplit fsplit : minEntry.getValue()) {
                if (!splitsToCombine.contains(fsplit)) {
                    splitsToCombine.add(fsplit);
                    if (--numSplitsToCombine == 0)
                        break;
                }
            }
            if (numSplitsToCombine != 0) {
                // Remove this host so that it is not selected again
                blocksPerHost.remove(minEntry.getKey());
            }
        }

        combined_splits[i] = combineFileSplits(conf, splitsToCombine, 0, splitsToCombine.size());

        for (Map.Entry<String, Vector<FileSplit>> entry : blocksPerHost.entrySet()) {
            entry.getValue().removeAll(splitsToCombine);
        }
        splitsAvailable -= splitsToCombine.size();
    }

    LOG.info("Combined splits " + combined_splits.length);
    return combined_splits;
}

From source file:eu.crowdrec.contest.sender.RequestSender.java

/**
 * read logFile then sends line by line to server.
 * /* w w  w . ja  v  a  2  s  . c o  m*/
 * @param inLogFileName
 *            path to log file. That can be a zip file or text file.
 * @param outLogFile
 *            path to outLog file. The outLog file should be analyzed by the evaluator.
 *            if the filename is null; no output will be generated
 * @param serverURL
 *            URL of the server
 */
public static void sender(final String inLogFileName, final String outLogFile, final String serverURL) {

    // handle the log file
    // check type of file

    // try to read the defined logFile
    BufferedReader br = null;
    BufferedWriter bw = null;
    try {
        // if outLogFile name is not null, create an output file
        if (outLogFile != null && outLogFile.length() > 0) {
            bw = new BufferedWriter(new FileWriter(new File(outLogFile), false));
        }

        // support a list of files in a directory
        File inLogFile = new File(inLogFileName);
        InputStream is;
        if (inLogFile.isFile()) {
            is = new FileInputStream(inLogFileName);
            // support gZip files
            if (inLogFile.getName().toLowerCase().endsWith(".gz")) {
                is = new GZIPInputStream(is);
            }
        } else {
            // if the input is a directory, consider all files based on a pattern
            File[] childs = inLogFile.listFiles(new FilenameFilter() {

                @Override
                public boolean accept(File dir, String name) {
                    final String fileName = name.toLowerCase();
                    return fileName.endsWith("data.idomaar.txt.gz") || fileName.endsWith("data.idomaar.txt")
                            || fileName.endsWith(".data.gz");
                }
            });
            if (childs == null || childs.length == 0) {
                throw new IOException("invalid inLogFileName or empty directory");
            }
            Arrays.sort(childs, new Comparator<File>() {

                @Override
                public int compare(File o1, File o2) {
                    return o1.getName().compareTo(o2.getName());
                }
            });
            Vector<InputStream> isChilds = new Vector<InputStream>();
            for (int i = 0; i < childs.length; i++) {
                InputStream tmpIS = new FileInputStream(childs[i]);
                // support gZip files
                if (childs[i].getName().toLowerCase().endsWith(".gz")) {
                    tmpIS = new GZIPInputStream(tmpIS);
                }
                isChilds.add(tmpIS);
            }
            is = new SequenceInputStream(isChilds.elements());
        }

        // read the log file line by line
        br = new BufferedReader(new InputStreamReader(is));
        try {
            for (String line = br.readLine(); line != null; line = br.readLine()) {

                // ignore invalid lines and header
                if (line.startsWith("null") || line.startsWith("#")) {
                    continue;
                }

                if (useThreadPool) {
                    RequestSenderThread t = new RequestSenderThread(line, serverURL, bw);
                    try {
                        // try to limit the speed of sending requests
                        if (Thread.activeCount() > 1000) {
                            if (logger.isDebugEnabled()) {
                                logger.debug("Thread.activeCount() = " + Thread.activeCount());
                            }
                            Thread.sleep(200);
                        }
                    } catch (Exception e) {
                        logger.info(e.toString());
                    }
                    t.start();
                } else {
                    // send parameters to http server and get response.
                    final long startTime = System.currentTimeMillis();
                    String result = HttpLib.HTTPCLIENT.equals(httpLib)
                            ? excutePostWithHttpClient(line, serverURL)
                            : excutePost(line, serverURL);

                    // analyze whether an answer is expected
                    boolean answerExpected = false;
                    if (line.contains("\"event_type\": \"recommendation_request\"")) {
                        answerExpected = true;
                    }
                    if (answerExpected) {
                        if (logger.isInfoEnabled()) {
                            logger.info("serverResponse: " + result);
                        }

                        // if the output file is not null, write the output in a synchronized way
                        if (bw != null) {
                            String[] data = LogFileUtils.extractEvaluationRelevantDataFromInputLine(line);
                            String requestId = data[0];
                            String userId = data[1];
                            String itemId = data[2];
                            String domainId = data[3];
                            String timeStamp = data[4];
                            long responseTime = System.currentTimeMillis() - startTime;
                            synchronized (bw) {
                                try {
                                    bw.write("prediction\t" + requestId + "\t" + timeStamp + "\t" + responseTime
                                            + "\t" + itemId + "\t" + userId + "\t" + domainId + "\t" + result);
                                    bw.newLine();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            logger.warn(e.toString(), e);
        }
    } catch (FileNotFoundException e) {
        logger.error("logFile not found e:" + e.toString());
    } catch (IOException e) {
        logger.error("reading the logFile failed e:" + e.toString());
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                logger.debug("close read-log file failed");
            }
        }
        if (bw != null) {
            try {
                // wait for ensuring that all request are finished
                // this simplifies the management of thread and worked fine for all test machines
                Thread.sleep(5000);
                bw.flush();
            } catch (Exception e) {
                logger.debug("close write-log file failed");
            }
        }
    }
}

From source file:Main.java

Main(String title) {
    super(title);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Vector v = new Vector();
    v.add("A");
    v.add("B");/*from   w  w  w  . j  av  a  2 s .  c om*/
    v.add("C");
    JComboBox jcb = new JComboBox(v);

    getContentPane().add(jcb);

    setSize(200, 50);
    setVisible(true);
}

From source file:MainClass.java

MainClass(String title) {
    super(title);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Vector v = new Vector();
    v.add("A");
    v.add("B");//  w  w w  . jav  a 2 s .  c  o m
    v.add("C");
    JComboBox jcb = new JComboBox(v);

    getContentPane().add(jcb);

    setSize(200, 50);
    setVisible(true);
}