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

📄 httpsamplerbase.java

📁 测试工具
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
    }

    /**
     * Add an argument which has already been encoded
     */
    public void addEncodedArgument(String name, String value) {
        this.addEncodedArgument(name, value, ARG_VAL_SEP);
    }

	public void addEncodedArgument(String name, String value, String metaData, String contentEncoding) {
        if (log.isDebugEnabled()){
		    log.debug("adding argument: name: " + name + " value: " + value + " metaData: " + metaData + " contentEncoding: " + contentEncoding);
        }
        
		HTTPArgument arg = null;
        if(contentEncoding != null) {
            arg = new HTTPArgument(name, value, metaData, true, contentEncoding);
        }
        else {
            arg = new HTTPArgument(name, value, metaData, true);
        }

        // Check if there are any difference between name and value and their encoded name and value
        String valueEncoded = null;
        if(contentEncoding != null) {
            try {
                valueEncoded = arg.getEncodedValue(contentEncoding);
            }
            catch (UnsupportedEncodingException e) {
                log.warn("Unable to get encoded value using encoding " + contentEncoding);
                valueEncoded = arg.getEncodedValue();
            }
        }
        else {
            valueEncoded = arg.getEncodedValue();
        }
        // If there is no difference, we mark it as not needing encoding
		if (arg.getName().equals(arg.getEncodedName()) && arg.getValue().equals(valueEncoded)) {
			arg.setAlwaysEncoded(false);
		}
		this.getArguments().addArgument(arg);
	}

    public void addEncodedArgument(String name, String value, String metaData) {
        this.addEncodedArgument(name, value, metaData, null);
    }

    public void addNonEncodedArgument(String name, String value, String metadata) {
        HTTPArgument arg = new HTTPArgument(name, value, metadata, false);
        arg.setAlwaysEncoded(false);
        this.getArguments().addArgument(arg);
    }
    
	public void addArgument(String name, String value) {
		this.getArguments().addArgument(new HTTPArgument(name, value));
	}

	public void addArgument(String name, String value, String metadata) {
		this.getArguments().addArgument(new HTTPArgument(name, value, metadata));
	}
	
	public boolean hasArguments() {
		return getArguments().getArgumentCount() > 0;
	}

	public void addTestElement(TestElement el) {
		if (el instanceof CookieManager) {
			setCookieManager((CookieManager) el);
		} else if (el instanceof HeaderManager) {
			setHeaderManager((HeaderManager) el);
		} else if (el instanceof AuthManager) {
			setAuthManager((AuthManager) el);
		} else {
			super.addTestElement(el);
		}
	}

	public void setPort(int value) {
		setProperty(new IntegerProperty(PORT, value));
	}

    public static int getDefaultPort(String protocol,int port){
        if (port==-1){
            return 
                protocol.equalsIgnoreCase(PROTOCOL_HTTP)  ? DEFAULT_HTTP_PORT :
                protocol.equalsIgnoreCase(PROTOCOL_HTTPS) ? DEFAULT_HTTPS_PORT :
                    port;
        }
        return port;
    }

    /**
     * Tell whether the default port for the specified protocol is used
     * 
     * @return true if the default port number for the protocol is used, false otherwise
     */
    public boolean isProtocolDefaultPort() {
    	final int port = getPropertyAsInt(PORT);
        final String protocol = getProtocol();
		if (port == UNSPECIFIED_PORT || 
                (PROTOCOL_HTTP.equalsIgnoreCase(protocol) && port == DEFAULT_HTTP_PORT) ||
                (PROTOCOL_HTTPS.equalsIgnoreCase(protocol) && port == DEFAULT_HTTPS_PORT)) {
            return true;
        }
        else {
            return false;
        }
    }
    
	public int getPort() {
		int port = getPropertyAsInt(PORT);
		if (port == UNSPECIFIED_PORT) {
			String prot = getProtocol();
            if (PROTOCOL_HTTPS.equalsIgnoreCase(prot)) {
				return DEFAULT_HTTPS_PORT;
			}
            if (!PROTOCOL_HTTP.equalsIgnoreCase(prot)) {
                log.warn("Unexpected protocol: "+prot);
                // TODO - should this return something else?
            }
			return DEFAULT_HTTP_PORT;
		}
		return port;
	}

	public void setDomain(String value) {
		setProperty(DOMAIN, value);
	}

	public String getDomain() {
		return getPropertyAsString(DOMAIN);
	}

	public void setArguments(Arguments value) {
		setProperty(new TestElementProperty(ARGUMENTS, value));
	}

	public Arguments getArguments() {
		return (Arguments) getProperty(ARGUMENTS).getObjectValue();
	}

	public void setAuthManager(AuthManager value) {
		AuthManager mgr = getAuthManager();
		if (mgr != null) {
			log.warn("Existing Manager " + mgr.getName() + " superseded by " + value.getName());
		}
		setProperty(new TestElementProperty(AUTH_MANAGER, value));
	}

	public AuthManager getAuthManager() {
		return (AuthManager) getProperty(AUTH_MANAGER).getObjectValue();
	}

	public void setHeaderManager(HeaderManager value) {
		HeaderManager mgr = getHeaderManager();
		if (mgr != null) {
			log.warn("Existing Manager " + mgr.getName() + " superseded by " + value.getName());
		}
		setProperty(new TestElementProperty(HEADER_MANAGER, value));
	}

	public HeaderManager getHeaderManager() {
		return (HeaderManager) getProperty(HEADER_MANAGER).getObjectValue();
	}

	public void setCookieManager(CookieManager value) {
		CookieManager mgr = getCookieManager();
		if (mgr != null) {
			log.warn("Existing Manager " + mgr.getName() + " superseded by " + value.getName());
		}
		setProperty(new TestElementProperty(COOKIE_MANAGER, value));
	}

	public CookieManager getCookieManager() {
		return (CookieManager) getProperty(COOKIE_MANAGER).getObjectValue();
	}

	public void setMimetype(String value) {
		setProperty(MIMETYPE, value);
	}

	public String getMimetype() {
		return getPropertyAsString(MIMETYPE);
	}

	public boolean isImageParser() {
		return getPropertyAsBoolean(IMAGE_PARSER);
	}

	public void setImageParser(boolean parseImages) {
		setProperty(new BooleanProperty(IMAGE_PARSER, parseImages));
	}

	/**
	 * Get the regular expression URLs must match.
	 * 
	 * @return regular expression (or empty) string
	 */
	public String getEmbeddedUrlRE() {
		return getPropertyAsString(EMBEDDED_URL_RE,"");
	}

	public void setEmbeddedUrlRE(String regex) {
		setProperty(new StringProperty(EMBEDDED_URL_RE, regex));
	}

	/**
	 * Obtain a result that will help inform the user that an error has occured
	 * during sampling, and how long it took to detect the error.
	 * 
	 * @param e
	 *            Exception representing the error.
	 * @param res
	 *            SampleResult
	 * @return a sampling result useful to inform the user about the exception.
	 */
	protected HTTPSampleResult errorResult(Throwable e, HTTPSampleResult res) {
		res.setSampleLabel("Error");
		res.setDataType(HTTPSampleResult.TEXT);
		ByteArrayOutputStream text = new ByteArrayOutputStream(200);
		e.printStackTrace(new PrintStream(text));
		res.setResponseData(text.toByteArray());
		res.setResponseCode(NON_HTTP_RESPONSE_CODE+": "+e.getClass().getName());
		res.setResponseMessage(NON_HTTP_RESPONSE_MESSAGE+": "+e.getMessage());
		res.setSuccessful(false);
		res.setMonitor(this.isMonitor());
		return res;
	}

	/**
	 * Get the URL, built from its component parts.
	 * 
	 * @return The URL to be requested by this sampler.
	 * @throws MalformedURLException
	 */
	public URL getUrl() throws MalformedURLException {
		StringBuffer pathAndQuery = new StringBuffer(100);
		String path = this.getPath();
        if (!path.startsWith("/")){ // $NON-NLS-1$
            pathAndQuery.append("/"); // $NON-NLS-1$
        }
        pathAndQuery.append(path);

        // Add the query string if it is a HTTP GET or DELETE request
        if(GET.equals(getMethod()) || DELETE.equals(getMethod())) {
            // Get the query string encoded in specified encoding
            // If no encoding is specified by user, we will get it
            // encoded in UTF-8, which is what the HTTP spec says
            String queryString = getQueryString(getContentEncoding());
            if(queryString.length() > 0) {
                if (path.indexOf(QRY_PFX) > -1) {
                    pathAndQuery.append(QRY_SEP);
                } else {
                    pathAndQuery.append(QRY_PFX);
                }
                pathAndQuery.append(queryString);
            }
		}
        // If default port for protocol is used, we do not include port in URL
        if(isProtocolDefaultPort()) {
			return new URL(getProtocol(), getDomain(), pathAndQuery.toString());
		}
        else {
            return new URL(getProtocol(), getDomain(), getPort(), pathAndQuery.toString());
        }
	}

    /**
     * Gets the QueryString attribute of the UrlConfig object, using
     * UTF-8 to encode the URL
     * 
     * @return the QueryString value
     */
    public String getQueryString() {
        // We use the encoding which should be used according to the HTTP spec, which is UTF-8
        return getQueryString(EncoderCache.URL_ARGUMENT_ENCODING);
    }
    
	/**
	 * Gets the QueryString attribute of the UrlConfig object, using the
	 * specified encoding to encode the parameter values put into the URL
	 * 
	 * @param contentEncoding the encoding to use for encoding parameter values
	 * @return the QueryString value
	 */
	public String getQueryString(String contentEncoding) {
 		// Check if the sampler has a specified content encoding        
 		if(contentEncoding == null || contentEncoding.trim().length() == 0) {
 			// We use the encoding which should be used according to the HTTP spec, which is UTF-8
 			contentEncoding = EncoderCache.URL_ARGUMENT_ENCODING;
 		}
		StringBuffer buf = new StringBuffer();
		PropertyIterator iter = getArguments().iterator();
		boolean first = true;
		while (iter.hasNext()) {
			HTTPArgument item = null;
            /*
             * N.B. Revision 323346 introduced the ClassCast check, but then used iter.next()
             * to fetch the item to be cast, thus skipping the element that did not cast.
             * Reverted to work more like the original code, but with the check in place.
             * Added a warning message so can track whether it is necessary
             */
			Object objectValue = iter.next().getObjectValue();
            try {
				item = (HTTPArgument) objectValue;
			} catch (ClassCastException e) {
                log.warn("Unexpected argument type: "+objectValue.getClass().getName());
				item = new HTTPArgument((Argument) objectValue);
			}
			final String encodedName = item.getEncodedName();
			if (encodedName.length() == 0) {
				continue; // Skip parameters with a blank name (allows use of optional variables in parameter lists)
			}
			if (!first) {
				buf.append(QRY_SEP);
			} else {
				first = false;
			}
			buf.append(encodedName);
			if (item.getMetaData() == null) {
				buf.append(ARG_VAL_SEP);
			} else {
				buf.append(item.getMetaData());
			}
            
			// Encode the parameter value in the specified content encoding
			try {
			    buf.append(item.getEncodedValue(contentEncoding));
			}
			catch(UnsupportedEncodingException e) {
			    log.warn("Unable to encode parameter in encoding " + contentEncoding + ", parameter value not included in query string");
			}
		}
		return buf.toString();
	}

    // Mark Walsh 2002-08-03, modified to also parse a parameter name value
    // string, where string contains only the parameter name and no equal sign.
    /**
     * This method allows a proxy server to send over the raw text from a
     * browser's output stream to be parsed and stored correctly into the
     * UrlConfig object.
     * 
     * For each name found, addArgument() is called
     * 
     * @param queryString -
     *            the query string
     * @param contentEncoding -
     *            the content encoding of the query string. The query string might
     *            actually be the post body of a http post request.
     */
    public void parseArguments(String queryString, String contentEncoding) {
        String[] args = JOrphanUtils.split(queryString, QRY_SEP);
        for (int i = 0; i < args.length; i++) {
			// need to handle four cases: 
            // - string contains name=value
			// - string contains name=
			// - string contains name
			// - empty string
            
			String metaData; // records the existance of an equal sign
            String name;
            String value;
            int length = args[i].length();
            int endOfNameIndex = args[i].indexOf(ARG_VAL_SEP);
            if (endOfNameIndex != -1) {// is there a separator?
				// case of name=value, name=
				metaData = ARG_VAL_SEP;
                name = args[i].substring(0, endOfNameIndex);
                value = args[i].substring(endOfNameIndex + 1, length);
			} else {
				metaData = "";
                name=args[i];
                value="";
            }
            if (name.length() > 0) {
                // If we know the encoding, we can decode the argument value,
                // to make it easier to read for the user
                if(contentEncoding != null) {
                    addEncodedArgument(name, value, metaData, contentEncoding);
                }
                else {
                    // If we do not know the encoding, we just use the encoded value
                    // The browser has already done the encoding, so save the values as is
                    addNonEncodedArgument(name, value, metaData);
                }
            }
        }
    }

    public void parseArguments(String queryString) {
        // We do not know the content encoding of the query string
        parseArguments(queryString, null);
    }

	public String toString() {
        try {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(this.getUrl().toString());
            // Append body if it is a post or put
            if(POST.equals(getMethod()) || PUT.equals(getMethod())) {
                stringBuffer.append("\nQuery Data: ");
                stringBuffer.append(getQueryString());
            }
            return stringBuffer.toString();
        } catch (MalformedURLException e) {
            return "";
        }
	}

	/**
	 * Do a sampling and return its results.
	 * 
	 * @param e
	 *            <code>Entry</code> to be sampled
	 * @return results of the sampling
	 */
	public SampleResult sample(Entry e) {
		return sample();
	}

	/**
	 * Perform a sample, and return the results
	 * 
	 * @return results of the sampling
	 */
	public SampleResult sample() {
		SampleResult res = null;
		try {
			if (PROTOCOL_FILE.equalsIgnoreCase(getProtocol())){

⌨️ 快捷键说明

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