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.maverick.http.MultiStatusResponse.java

public static MultiStatusResponse[] createResponse(HttpResponse response) throws IOException {

    if (response.getStatus() != 207) {
        throw new IOException(Messages.getString("MultiStatusResponse.not207")); //$NON-NLS-1$
    }//from  w  ww. j  a v a  2 s.  c  o m

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int read;
    byte[] buf = new byte[4096];
    while ((read = response.getInputStream().read(buf)) > -1) {
        out.write(buf, 0, read);
    }

    // #ifdef DEBUG
    if (log.isDebugEnabled())
        log.debug(new String(out.toByteArray()));
    // #endif

    try {
        IXMLParser parser = XMLParserFactory.createDefaultXMLParser();
        IXMLReader reader = StdXMLReader.stringReader(new String(out.toByteArray(), "UTF8")); //$NON-NLS-1$
        parser.setReader(reader);
        IXMLElement rootElement = (IXMLElement) parser.parse();

        if (!rootElement.getName().equalsIgnoreCase("multistatus")) //$NON-NLS-1$
            throw new IOException(
                    Messages.getString("MultiStatusResponse.invalidDavRootElement") + rootElement.getName()); //$NON-NLS-1$

        // Now process the responses
        Vector children = rootElement.getChildrenNamed("response", rootElement.getNamespace()); //$NON-NLS-1$
        Vector responses = new Vector();

        for (Enumeration e = children.elements(); e.hasMoreElements();) {
            responses.addElement(new MultiStatusResponse((IXMLElement) e.nextElement()));
        }

        MultiStatusResponse[] array = new MultiStatusResponse[responses.size()];
        responses.copyInto(array);
        return array;

    } catch (Exception ex) {
        // #ifdef DEBUG
        log.error(Messages.getString("MultiStatusResponse.failedToProcessMultistatusResponse"), ex); //$NON-NLS-1$
        // #endif
        throw new IOException(ex.getMessage());
    }

}

From source file:net.rim.ejde.internal.model.BlackBerryPropertiesFactory.java

/**
 * Initialize from a given legacy project.
 *
 * @param properties/*from   w ww  .ja  va 2 s. c  o m*/
 *
 * @param project
 *            the project
 * @param javaProj
 *            the java proj
 */
static private void initializeFromLegacy(BlackBerryProperties properties, final Project project,
        final IJavaProject javaProj) {
    // Initialize the general section
    properties._general.setTitle(project.getTitle());
    properties._general.setVersion(project.getVersion());
    properties._general.setDescription(project.getDescription());
    properties._general.setVendor(project.getVendor());

    // Initialize the application section
    properties._application.setHomeScreenPosition(project.getRibbonPosition());
    properties._application.setIsAutostartup(project.getRunOnStartup());
    properties._application.setIsSystemModule(project.getSystemModule());
    switch (project.getType()) {
    case Project.MIDLET: {
        properties._application.setMainArgs(IConstants.EMPTY_STRING);
        properties._application.setMainMIDletName(project.getMidletClass());
        break;
    }
    case Project.CLDC_APPLICATION: {
        properties._application.setMainArgs(project.getMidletClass());
        properties._application.setMainMIDletName(IConstants.EMPTY_STRING);
        break;
    }
    case Project.LIBRARY: {
        properties._application.setIsSystemModule(Boolean.TRUE);
        // No break falling through to default case
    }
    default: {
        properties._application.setMainArgs(IConstants.EMPTY_STRING);
        properties._application.setMainMIDletName(IConstants.EMPTY_STRING);
    }
    }
    properties._application
            .setStartupTier(Math.max(project.getStartupTier(), ProjectUtils.getStartupTiers()[0]));
    properties._application.setType(GeneralSection.projectTypeChoiceList[project.getType()]);

    // Initialize the resources section
    properties._resources.setHasTitleResource(project.isTitleResourceBundleActive());
    properties._resources.setTitleResourceBundleName(project.getTitleResourceBundleName());
    properties._resources.setTitleResourceBundleKey(project.getTitleResourceTitleKey());
    properties._resources.setTitleResourceBundleClassName(project.getTitleResourceBundleClassName());
    final IProject iProject = javaProj.getProject();
    final String resourceBundlePath = project.getTitleResourceBundlePath();
    if (!StringUtils.isBlank(resourceBundlePath)) {
        final String resourceBundleFilePath = Util.makeAbsolute(resourceBundlePath, project.getFile());
        properties._resources.setTitleResourceBundleRelativePath(
                getTargetRelFilePath(new File(resourceBundleFilePath), project, JavaCore.create(iProject)));
    } else {
        properties._resources.setTitleResourceBundleRelativePath(IConstants.EMPTY_STRING);
    }
    properties._resources.setDescriptionId(project.getTitleResourceDescriptionKey());
    properties._resources.setIconFiles(getIcons(project, iProject));
    // Initialize the keyword section
    // TODO we use the KeywordResourceBundleKey to store ID for now, later on when we implemented the UI part, we need to
    // change
    properties.getKeywordResources().setKeywordResourceBundleKey(project.getKeywordResourceBundleId());
    properties.getKeywordResources()
            .setKeywordResourceBundleClassName(project.getKeywordResourceBundleClassName());
    // Initialize the compiler section
    properties._compile.setAliasList(project.getAlias());
    properties._compile.setCompressResources(project.getWorkspace().getResourcesCompressed());
    properties._compile.setConvertImages(!project.getIsNoConvertPng());
    properties._compile.setCreateWarningForNoExportedRoutine(!project.getIsNoMainWarn());
    properties._compile.setOutputCompilerMessages(project.getIsNoWarn());
    final Vector<String> defines = project.getDefines();
    properties._compile.setPreprocessorDefines(
            PreprocessorTag.create(defines.toArray(new String[defines.size()]), PreprocessorTag.PJ_SCOPE));

    // Initialize the packaging section
    final Vector<File> alxFileVector = project.getAlxImports();
    final String[] alxFiles = new String[alxFileVector.size()];
    for (int i = 0; i < alxFileVector.size(); i++) {
        final File alxFile = alxFileVector.get(i);
        alxFiles[i] = alxFile.getPath();
    }
    properties._packaging.setAlxFiles(alxFiles);
    properties._packaging.setCleanStep(project.getCleanBuild());
    properties.setValidOutputFileName(project.getOutputFileName());
    properties._packaging.setPostBuildStep(project.getPostBuild());
    properties._packaging.setPreBuildStep(project.getPreBuild());
    properties._packaging.setGenerateALXFile(PackagingUtils.getDefaultGenerateAlxFile());

    // Initialize alternate entry points
    final int AEPNumber = project.getNumEntries();
    properties._alternateEntryPoints = new AlternateEntryPoint[AEPNumber];
    for (int i = 0; i < AEPNumber; i++) {
        final Project entry = project.getEntry(i);
        try {
            properties._alternateEntryPoints[i] = createAlternateEntryPoint(entry, iProject);
        } catch (final CoreException e) {
            _log.error(e.getMessage(), e);
        }
    }

    // Initialize hidden properties
    properties._hiddenProperties.setClassProtection(project.getClassProtection());
    properties._hiddenProperties.setPackageProtection(project.getPackageProtection());
}

From source file:at.lame.hellonzb.parser.NzbParser.java

/**
 * This method is called to save the currently loaded parser data
 * to a file (to be loaded later on).// ww w  . j  a v  a  2s  .co  m
 * 
 * @param logger The central logger object
 * @param counter File(name) counter
 * @param filename File name to use
 * @param dlFiles The vector of DownloadFile to write
 * @return Success status (true or false)
 */
public synchronized static boolean saveParserData(MyLogger logger, int counter, String filename,
        Vector<DownloadFile> dlFiles) {
    String newline = System.getProperty("line.separator");

    if (dlFiles.size() < 1)
        return true;

    try {
        String datadirPath = System.getProperty("user.home") + "/.HelloNzb/";

        // create home directory
        File datadir = new File(datadirPath);
        if (datadir.exists()) {
            if (datadir.isFile()) {
                logger.msg("Can't create data directory: " + datadirPath, MyLogger.SEV_ERROR);
                return false;
            }
        } else
            datadir.mkdirs();

        File file = new File(datadirPath, counter + "-" + filename + ".nzb");
        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");

        // XML header
        writer.write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
        writer.write(newline);

        // XML doctype
        writer.write("<!DOCTYPE nzb PUBLIC \"-//newzBin//DTD NZB 1.0//EN\" "
                + "\"http://www.newzbin.com/DTD/nzb/nzb-1.0.dtd\">");
        writer.write(newline);

        // HelloNzb signature line
        writer.write("<!-- NZB generated by HelloNzb, the Binary Usenet tool -->");
        writer.write(newline);

        // XML namespace
        writer.write("<nzb xmlns=\"http://www.newzbin.com/DTD/2003/nzb\">");
        writer.write(newline);
        writer.write(newline);

        // now write all files passed to this method
        for (DownloadFile dlFile : dlFiles)
            writeDlFileToXml(writer, dlFile);

        // end <nzb> element
        writer.write(newline);
        writer.write("</nzb>");

        // flush and close file
        writer.flush();
        writer.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }

    return true;
}

From source file:com.sittinglittleduck.DirBuster.GenBaseCase.java

/**
 * Generates the base case// ww w  .j a  v a  2s .  c  o m
 *
 * @param manager the manager class
 * @param url The directy or file we need a base case for
 * @param isDir true if it's dir, else false if it's a file
 * @param fileExtention File extention to be scanned, set to null if it's a dir that is to be
 *     tested
 * @return A BaseCase Object
 */
public static BaseCase genBaseCase(Manager manager, String url, boolean isDir, String fileExtention)
        throws MalformedURLException, IOException {
    String type;
    if (isDir) {
        type = "Dir";
    } else {
        type = "File";
    }

    /*
     * markers for using regex instead
     */
    boolean useRegexInstead = false;
    String regex = null;

    BaseCase tempBaseCase = manager.getBaseCase(url, isDir, fileExtention);

    if (tempBaseCase != null) {
        // System.out.println("Using prestored basecase");
        return tempBaseCase;
    }

    // System.out.println("DEBUG GenBaseCase: URL to get baseCase for: " + url + " (" + type +
    // ")");
    if (Config.debug) {
        System.out.println("DEBUG GenBaseCase: URL to get baseCase for:" + url);
    }

    BaseCase baseCase = null;
    int failcode = 0;
    String failString = Config.failCaseString;
    String baseResponce = "";
    URL failurl = null;
    if (isDir) {
        failurl = new URL(url + failString + "/");
    } else {
        if (manager.isBlankExt()) {
            fileExtention = "";
            failurl = new URL(url + failString + fileExtention);
        } else {
            if (!fileExtention.startsWith(".")) {
                fileExtention = "." + fileExtention;
            }
            failurl = new URL(url + failString + fileExtention);
        }
    }

    // System.out.println("DEBUG GenBaseCase: Getting :" + failurl + " (" + type + ")");
    if (Config.debug) {
        System.out.println("DEBUG GenBaseCase: Getting:" + failurl);
    }

    GetMethod httpget = new GetMethod(failurl.toString());
    // set the custom HTTP headers
    Vector HTTPheaders = manager.getHTTPHeaders();
    for (int a = 0; a < HTTPheaders.size(); a++) {
        HTTPHeader httpHeader = (HTTPHeader) HTTPheaders.elementAt(a);
        /*
         * Host header has to be set in a different way!
         */
        if (httpHeader.getHeader().startsWith("Host")) {
            httpget.getParams().setVirtualHost(httpHeader.getValue());
        } else {
            httpget.setRequestHeader(httpHeader.getHeader(), httpHeader.getValue());
        }
    }
    httpget.setFollowRedirects(Config.followRedirects);

    // save the http responce code for the base case
    failcode = manager.getHttpclient().executeMethod(httpget);
    manager.workDone();

    // we now need to get the content as we need a base case!
    if (failcode == 200) {
        if (Config.debug) {
            System.out.println("DEBUG GenBaseCase: base case for " + failurl.toString() + "came back as 200!");
        }

        BufferedReader input = new BufferedReader(new InputStreamReader(httpget.getResponseBodyAsStream()));
        String tempLine;
        StringBuffer buf = new StringBuffer();
        while ((tempLine = input.readLine()) != null) {
            buf.append("\r\n" + tempLine);
        }
        baseResponce = buf.toString();
        input.close();

        // HTMLparse.parseHTML();

        // HTMLparse htmlParse = new HTMLparse(baseResponce, null);
        // Thread parse  = new Thread(htmlParse);
        // parse.start();

        // clean up the base case, based on the basecase URL
        baseResponce = FilterResponce.CleanResponce(baseResponce, failurl, failString);

        httpget.releaseConnection();

        /*
         * get the base case twice more, for consisitency checking
         */
        String baseResponce1 = baseResponce;
        String baseResponce2 = getBaseCaseAgain(manager, failurl, failString);
        String baseResponce3 = getBaseCaseAgain(manager, failurl, failString);

        if (baseResponce1 != null && baseResponce2 != null && baseResponce3 != null) {
            /*
             * check that all the responces are same, if they are do nothing if not enter the if statement
             */

            if (!baseResponce1.equalsIgnoreCase(baseResponce2) || !baseResponce1.equalsIgnoreCase(baseResponce3)
                    || !baseResponce2.equalsIgnoreCase(baseResponce3)) {
                if (manager.getFailCaseRegexes().size() != 0) {

                    /*
                     * for each saved regex see if it will work, if it does then use that one
                     * if not then give the uses the dialog
                     */

                    Vector<String> failCaseRegexes = manager.getFailCaseRegexes();
                    for (int a = 0; a < failCaseRegexes.size(); a++) {

                        Pattern regexFindFile = Pattern.compile(failCaseRegexes.elementAt(a));

                        Matcher m1 = regexFindFile.matcher(baseResponce1);
                        Matcher m2 = regexFindFile.matcher(baseResponce2);
                        Matcher m3 = regexFindFile.matcher(baseResponce3);

                        boolean test1 = m1.find();
                        boolean test2 = m2.find();
                        boolean test3 = m3.find();

                        if (test1 && test2 && test3) {
                            regex = failCaseRegexes.elementAt(a);
                            useRegexInstead = true;
                            break;
                        }
                    }
                }
            } else {
                /*
                 * We have a big problem as now we have different responce codes for the same request
                 * //TODO think of a way to deal with is
                 */
            }

            if (Config.debug) {
                System.out.println("DEBUG GenBaseCase: base case was set to :" + baseResponce);
            }
        }
    }
    httpget.releaseConnection();

    baseCase = new BaseCase(new URL(url), failcode, isDir, failurl, baseResponce, fileExtention,
            useRegexInstead, regex);

    // add the new base case to the manager list
    manager.addBaseCase(baseCase);
    manager.addNumberOfBaseCasesProduced();

    return baseCase;
}

From source file:Main.java

/**
 * Splits a string into substrings. //from   w w w  . jav a2  s  . com
 * @param str The string which is to split.
 * @param delim The delimiter character, for example a space <code>' '</code>.
 * @param trailing The ending which is added as a substring though it wasn't 
 *                 in the <code>str</code>. This parameter is just for the 
 *                 <code>IRCParser</code> class which uses this method to 
 *                 split the <code>middle</code> part into the parameters. 
 *                 But as last parameter always the <code>trailing</code> is 
 *                 added. This is done here because it's the fastest way to 
 *                 do it here.<br />
 *                 If the <code>end</code> is <code>null</code> or 
 *                 <code>""</code>, nothing is appended.
 * @return An array with all substrings.
 * @see #split(String, int)
 */
public static String[] split(String str, int delim, String trailing) {
    Vector items = new Vector(15);
    int last = 0;
    int index = 0;
    int len = str.length();
    while (index < len) {
        if (str.charAt(index) == delim) {
            items.add(str.substring(last, index));
            last = index + 1;
        }
        index++;
    }
    if (last != len)
        items.add(str.substring(last));
    if (trailing != null && trailing.length() != 0)
        items.add(trailing);
    String[] result = new String[items.size()];
    items.copyInto(result);
    return result;
}

From source file:StringUtil.java

/**
 * Split the source into two strings at the first occurrence of the splitter Subsequent occurrences are not treated specially, and may be part of the second string.
 * /*from   w w w. j a  v a2  s . com*/
 * @param source
 *        The string to split
 * @param splitter
 *        The string that forms the boundary between the two strings returned.
 * @return An array of two strings split from source by splitter.
 */
public static String[] splitFirst(String source, String splitter) {
    // hold the results as we find them
    Vector rv = new Vector();
    int last = 0;
    int next = 0;

    // find first splitter in source
    next = source.indexOf(splitter, last);
    if (next != -1) {
        // isolate from last thru before next
        rv.add(source.substring(last, next));
        last = next + splitter.length();
    }

    if (last < source.length()) {
        rv.add(source.substring(last, source.length()));
    }

    // convert to array
    return (String[]) rv.toArray(new String[rv.size()]);
}

From source file:azkaban.common.utils.Utils.java

/**
 * Parse lines in byteArray and store the last *lineCount* lines in
 * *lastNLines*/*from w  w w  . j  a va 2 s  .c  o m*/
 * 
 * @param byteArray         source byte array
 * @param offset                offset of the byte array
 * @param length                length of the byte array
 * @param lineCount             desired number of lines
 * @param lastNLines        vector of last N lines
 * @return true         indicates we get *lineCount* lines 
 *                false         otherwise
 */
protected static boolean parseLinesFromLast(byte[] byteArray, int offset, int length, int lineCount,
        Vector<String> lastNLines) {

    if (lastNLines.size() > lineCount)
        return true;

    // convert byte array to string
    String lastNChars = new String(byteArray, offset, length);

    // reverse the string
    StringBuffer sb = new StringBuffer(lastNChars);
    lastNChars = sb.reverse().toString();

    // tokenize the string using "\n"
    String[] tokens = lastNChars.split("\n");

    // append lines to lastNLines
    for (int index = 0; index < tokens.length; index++) {
        StringBuffer sbLine = new StringBuffer(tokens[index]);
        String newline = sbLine.reverse().toString();

        if (index == 0 && !lastNLines.isEmpty()) { // first line might not be a complete line
            int lineNum = lastNLines.size();
            String halfLine = lastNLines.get(lineNum - 1);
            lastNLines.set(lineNum - 1, newline + halfLine);
        } else {
            lastNLines.add(newline);
        }

        if (lastNLines.size() > lineCount) {
            return true;
        }
    }

    return false;
}

From source file:Main.java

/**
 * Resolve a link relative to an absolute base.  The path to resolve could
 * itself be absolute or relative.//w w  w  .  j a  v  a 2 s  .co  m
 * 
 * e.g.
 * resolvePath("http://www.server.com/some/dir", "../img.jpg");
 *  returns http://www.server.com/some/img.jpg
 * 
 * @param base The absolute base path
 * @param link The link given relative to the base
 * @return 
 */
public static String resolveLink(String base, String link) {
    String linkLower = link.toLowerCase();
    int charFoundIndex;

    charFoundIndex = linkLower.indexOf("://");
    if (charFoundIndex != -1) {
        boolean isAllChars = true;
        char cc;
        for (int i = 0; i < charFoundIndex; i++) {
            cc = linkLower.charAt(i);
            isAllChars &= ((cc > 'a' && cc < 'z') || (cc > '0' && cc < '9') || cc == '+' || cc == '.'
                    || cc == '-');
        }

        //we found :// and all valid scheme name characters before; path itself is absolute
        if (isAllChars) {
            return link;
        }
    }

    //Check if this is actually a data: link which should not be resolved
    if (link.startsWith("data:")) {
        return link;
    }

    if (link.length() > 2 && link.charAt(0) == '/' && link.charAt(1) == '/') {
        //we want the protocol only from the base
        String resolvedURL = base.substring(0, base.indexOf(':') + 1) + link;
        return resolvedURL;
    }

    if (link.length() > 1 && link.charAt(0) == '/') {
        //we should start from the end of the server
        int serverStartPos = base.indexOf("://") + 3;
        int serverFinishPos = base.indexOf('/', serverStartPos + 1);
        return base.substring(0, serverFinishPos) + link;
    }

    //get rid of query if it's present in the base path
    charFoundIndex = base.indexOf('?');
    if (charFoundIndex != -1) {
        base = base.substring(0, charFoundIndex);
    }

    //remove the filename component if present in base path
    //if the base path ends with a /, remove that, because it will be joined to the path using a /
    charFoundIndex = base.lastIndexOf(FILE_SEP);
    base = base.substring(0, charFoundIndex);

    String[] baseParts = splitString(base, FILE_SEP);
    String[] linkParts = splitString(link, FILE_SEP);

    Vector resultVector = new Vector();
    for (int i = 0; i < baseParts.length; i++) {
        resultVector.addElement(baseParts[i]);
    }

    for (int i = 0; i < linkParts.length; i++) {
        if (linkParts[i].equals(".")) {
            continue;
        }

        if (linkParts[i].equals("..")) {
            resultVector.removeElementAt(resultVector.size() - 1);
        } else {
            resultVector.addElement(linkParts[i]);
        }
    }

    StringBuffer resultSB = new StringBuffer();
    int numElements = resultVector.size();
    for (int i = 0; i < numElements; i++) {
        resultSB.append(resultVector.elementAt(i));
        if (i < numElements - 1) {
            resultSB.append(FILE_SEP);
        }
    }

    return resultSB.toString();
}

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

/**
 * Builds NamePair array from list./*  w ww  .  j ava 2s  .  com*/
 * @param postParams the list 
 * @return the array
 */
public static NameValuePair[] buildNamePairArray(final Vector<NameValuePair> postParams) {
    // create an array from the params
    NameValuePair[] paramArray = new NameValuePair[postParams.size()];
    for (int i = 0; i < paramArray.length; ++i) {
        paramArray[i] = postParams.get(i);
    }
    return paramArray;
}

From source file:it.geosolutions.geobatch.destination.common.utils.RemoteBrowserUtils.java

/**
 * SFTP protocol ls//from   w  w  w  .j a  v  a 2s.  c o m
 * 
 * @param userName
 * @param password
 * @param host
 * @param port
 * @param path
 * @param timeout
 * @param pattern
 * @return name of files or directories inside the remote folder
 * @throws IOException
 * @throws FTPException
 * @throws ParseException
 */
private static List<String> sftpLS(String userName, String password, String host, int port, String path,
        int timeout, Pattern pattern) throws IOException {

    //TODO: use pattern
    Session session = null;
    Channel channel = null;
    ChannelSftp sftpChannel = null;
    List<String> names = new LinkedList<String>();

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(userName, host, port);
        session.setPassword(password);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        channel = session.openChannel(RemoteBrowserProtocol.sftp.name());
        channel.connect();
        sftpChannel = (ChannelSftp) channel;
        sftpChannel.cd(path);
        @SuppressWarnings("unchecked")
        Vector<LsEntry> filelist = sftpChannel.ls(path);
        for (int i = 0; i < filelist.size(); i++) {
            String fileName = filelist.get(i).getFilename();
            if (pattern != null) {
                Matcher m = pattern.matcher(fileName);
                if (m.matches()) {
                    names.add(fileName);
                }
            } else {
                if (!fileName.equals(".") && !fileName.equals("..")) {
                    names.add(fileName);
                }
            }
        }

    } catch (Exception e) {
        throw new IOException("Error on ls", e);
    } finally {
        if (sftpChannel != null) {
            sftpChannel.exit();
        }
        if (session != null) {
            session.disconnect();
        }
    }

    return names;
}