⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cookiemanager.java

📁 测试工具
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
	 */
	public void add(Cookie c) {
		String cv = c.getValue();
        String cn = c.getName();
        removeMatchingCookies(c); // Can't have two matching cookies
        
		if (DELETE_NULL_COOKIES && (null == cv || cv.length()==0)) {
            if (log.isDebugEnabled()) {
                log.debug("Dropping cookie with null value " + c.toString());
            }
		} else {
            if (log.isDebugEnabled()) {
                log.debug("Add cookie to store " + c.toString());
            }
			getCookies().addItem(c);
            // Store cookie as a thread variable. 
            // TODO - should we add a prefix to these variables?
            // TODO - should storing cookie values be optional?
            JMeterContext context = getThreadContext();
			if (context.isSamplingStarted()) {
				context.getVariables().put(cn, cv);
			}
		}
	}

	public void clear(){
		super.clear();
		clearCookies(); // ensure data is set up OK initially
	}

	/*
	 * Remove all the cookies.
	 */
	private void clearCookies() {
		log.debug("Clear all cookies from store");
		setProperty(new CollectionProperty(COOKIES, new ArrayList()));
	}

	/**
	 * Remove a cookie.
	 */
	public void remove(int index) {// TODO not used by GUI
		getCookies().remove(index);
	}

	/**
	 * Return the cookie at index i.
	 */
	public Cookie get(int i) {// Only used by GUI
		return (Cookie) getCookies().get(i).getObjectValue();
	}

    /*
     * Create an HttpClient cookie from a JMeter cookie
     */
    private org.apache.commons.httpclient.Cookie makeCookie(Cookie jmc){
        long exp = jmc.getExpiresMillis();
        org.apache.commons.httpclient.Cookie ret=
            new org.apache.commons.httpclient.Cookie(
                jmc.getDomain(),
                jmc.getName(),
                jmc.getValue(),
                jmc.getPath(),
                exp > 0 ? new Date(exp) : null, // use null for no expiry
                jmc.getSecure()
               );
        ret.setPathAttributeSpecified(jmc.isPathSpecified());
        ret.setDomainAttributeSpecified(jmc.isDomainSpecified());
        return ret;
    }
    
    /**
     * Get array of valid HttpClient cookies for the URL
     * 
     * @param url the target URL
     * @return array of HttpClient cookies
     * 
     */
    public org.apache.commons.httpclient.Cookie[] getCookiesForUrl(URL url){
        CollectionProperty jar=getCookies();
        org.apache.commons.httpclient.Cookie cookies[]=
            new org.apache.commons.httpclient.Cookie[jar.size()];
        int i=0;
        for (PropertyIterator iter = getCookies().iterator(); iter.hasNext();) {
            Cookie jmcookie = (Cookie) iter.next().getObjectValue();
            // Set to running version, to allow function evaluation for the cookie values (bug 28715)
            if (ALLOW_VARIABLE_COOKIES) jmcookie.setRunningVersion(true);
            cookies[i++] = makeCookie(jmcookie);
            if (ALLOW_VARIABLE_COOKIES) jmcookie.setRunningVersion(false);
        }
        String host = url.getHost();
        String protocol = url.getProtocol();
        int port= HTTPSamplerBase.getDefaultPort(protocol,url.getPort());
        String path = url.getPath();
        boolean secure = HTTPSamplerBase.isSecure(protocol);
        return cookieSpec.match(host, port, path, secure, cookies);
    }
    
    /**
     * Find cookies applicable to the given URL and build the Cookie header from
     * them.
     * 
     * @param url
     *            URL of the request to which the returned header will be added.
     * @return the value string for the cookie header (goes after "Cookie: ").
     */
    public String getCookieHeaderForURL(URL url) {
        org.apache.commons.httpclient.Cookie[] c = getCookiesForUrl(url);
        int count = c.length;
        boolean debugEnabled = log.isDebugEnabled();
        if (debugEnabled){
            log.debug("Found "+count+" cookies for "+url.toExternalForm());
        }
        if (count <=0){
            return null;
        }
        String hdr=cookieSpec.formatCookieHeader(c).getValue();
        if (debugEnabled){
            log.debug("Cookie: "+hdr);
        }
        return hdr;
    }
    

    public void addCookieFromHeader(String cookieHeader, URL url){
        boolean debugEnabled = log.isDebugEnabled(); 
        if (debugEnabled) {
            log.debug("Received Cookie: " + cookieHeader + " From: " + url.toExternalForm());
        }
        String protocol = url.getProtocol();
        String host = url.getHost();
        int port= HTTPSamplerBase.getDefaultPort(protocol,url.getPort());
        String path = url.getPath();
        boolean isSecure=HTTPSamplerBase.isSecure(protocol);
        org.apache.commons.httpclient.Cookie[] cookies= null;
        try {
            cookies = cookieSpec.parse(host, port, path, isSecure, cookieHeader);
        } catch (MalformedCookieException e) {
            log.warn(cookieHeader+e.getLocalizedMessage());
        } catch (IllegalArgumentException e) {
            log.warn(cookieHeader+e.getLocalizedMessage());
        }
        if (cookies == null) return;
        for(int i=0;i<cookies.length;i++){
            Date expiryDate = cookies[i].getExpiryDate();
            long exp = 0;
            if (expiryDate!= null) {
                exp=expiryDate.getTime();
            }
            Cookie newCookie = new Cookie(
                    cookies[i].getName(),
                    cookies[i].getValue(),
                    cookies[i].getDomain(),
                    cookies[i].getPath(),
                    cookies[i].getSecure(), 
                    exp / 1000,
                    cookies[i].isPathAttributeSpecified(),
                    cookies[i].isDomainAttributeSpecified()
                    );

            // Store session cookies as well as unexpired ones
            if (exp == 0 || exp >= System.currentTimeMillis()) {
                add(newCookie); // Has its own debug log; removes matching cookies
            } else {
                removeMatchingCookies(newCookie);
                if (debugEnabled){
                    log.debug("Dropping expired Cookie: "+newCookie.toString());
                }      
            }
        }

    }
    private boolean match(Cookie a, Cookie b){
        return 
        a.getName().equals(b.getName())
        &&
        a.getPath().equals(b.getPath())
        &&
        a.getDomain().equals(b.getDomain());
    }
    
    private void removeMatchingCookies(Cookie newCookie){
        // Scan for any matching cookies
        PropertyIterator iter = getCookies().iterator();
        while (iter.hasNext()) {
            Cookie cookie = (Cookie) iter.next().getObjectValue();
            if (cookie == null)
                continue;
            if (match(cookie,newCookie)) { 
                if (log.isDebugEnabled()) {
                    log.debug("New Cookie = " + newCookie.toString()
                              + " removing matching Cookie " + cookie.toString());
                }
                iter.remove();
            }
        }       
    }
    
	public String getClassLabel() {
		return JMeterUtils.getResString("cookie_manager_title");// $NON-NLS-1$
	}

	public void testStarted() {
		initialCookies = getCookies();
	}

	public void testEnded() {
	}

	public void testStarted(String host) {
		testStarted();
	}

	public void testEnded(String host) {
	}

	public void testIterationStart(LoopIterationEvent event) {
		if (getClearEachIteration()) {
			clearCookies();
			setProperty(initialCookies);
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -