Jmeter 支持CASLogin 透传重定向地址

这是一个关于如何使用JMeter的Java实现,`CASLogin` 类,进行CAS(Central Authentication Service)登录并获取重定向地址的示例。代码中包括了设置测试参数、初始化、执行登录操作以及解析重定向URL的方法。该类继承自`AbstractJavaSamplerClient`,并实现了测试开始和结束时的回调方法。

package com.*.casLogin;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;

import com.*.jmeter.util.CASHttpClient;

public class CASLogin extends AbstractJavaSamplerClient {

    private String url;
    private String username;
    private String password;
    private static final String _eventId = "submit";
    private String lt;
    private SampleResult results;
    
    private static final String regex = "(\\d+\\.\\d+\\.\\d+\\.\\d+)\\:(\\d+)";
    
    // 这个方法是用来自定义java方法入参的。
    // params.addArgument("num1","");表示入参名字叫num1,默认值为空。
    public Arguments getDefaultParameters() {
        Arguments params = new Arguments();
        params.addArgument("url", "");
        params.addArgument("username", "");
        params.addArgument("password", "");
        return params;
    }

    //每个线程测试前执行一次,做一些初始化工作;
    public void setupTest(JavaSamplerContext context) {
        results = new SampleResult();
        results.setSampleLabel( "JAVA【CAS登录-返回重定向地址】");
        results.setDataEncoding("UTF-8");//因为响应的数据有中文,所以最好先设置编码
        url = context.getParameter("url");
        username = context.getParameter("username");
        password = context.getParameter("password");
        results.setSamplerData("url:"+url+"\n"+"username:"+username+"\n"+"password:"+password+"\n");
    }

    @Override
    public SampleResult runTest(JavaSamplerContext context) {
        try {
            results.sampleStart();// jmeter 开始统计响应时间标记
            lt = CASHttpClient.getCasLt(url);
            if ("".equals(lt)||null==lt) {
                throw new Exception("lt没有取到~!");
            }
            String redirect_url = CASHttpClient.sendCasLogin(url, username, password, lt,_eventId);
            
            redirect_url = rebuildRedirectUrl(redirect_url);
            if (redirect_url != null && redirect_url.length() > 0) {
                System.out.println("redirect_url:"+redirect_url);
                results.setResponseData(redirect_url, "UTF-8");
                results.setContentType("application/json");
                //results.setDataType(SampleResult.TEXT);
            }
            // System.out.println(resultData);
            results.setSuccessful(true);
        } catch (Throwable e) {
            results.setSuccessful(false);
            e.printStackTrace();
        }finally {
            results.sampleEnd();// jmeter 结束统计响应时间标记
        }
        return results;
    }

    private String rebuildRedirectUrl(String redirect_url) {
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(redirect_url);
        while(m.find()) {
            //System.out.println("ip:"+m.group(1));
            //System.out.println("port:"+m.group(2));
            System.out.println(redirect_url.substring(m.start(2)+4));
            return redirect_url.substring(m.start(2)+4);
        }
        return null;
    }

    //测试结束时调用;
    public void teardownTest(JavaSamplerContext arg0) {
        arg0 = null;
    }
    
    // main只是为了调试用,最后打jar包的时候注释掉。
    public static void main(String[] args) 
    { 
        //testEOSCreateApplication();
        testCasLogin();
    }

    public static void testEOSCreateApplication() {
        Arguments params = new Arguments(); 
        String url = "http://ip:8980/developer/management/applications";
        String filename = "小哥服务平台";
        String filepath = "E:\\IDSS.JPG";
        String application = "{\"application\": {\"type\": 0,\"zhName\": \"快狗打车\",\"enName\": \"kuaigoudache\",\"introduction\": \"快狗打车【kuaigoudache】来了\"}";
        params.addArgument("url", url);//设置参数,并赋予默认值 
        params.addArgument("filename", filename);//设置参数,并赋予默认值
        params.addArgument("filepath", filepath);//设置参数,并赋予默认值
        params.addArgument("application", application);//设置参数,并赋予默认值
        JavaSamplerContext arg0 = new JavaSamplerContext(params); 
        CASLogin eosCreateApplication = new CASLogin(); 
        eosCreateApplication.setupTest(arg0); 
        eosCreateApplication.runTest(arg0);
        eosCreateApplication.teardownTest(arg0); 
    }
    
    public static void testCasLogin() {
        Arguments params = new Arguments(); 
        String url = "http://ip:8980/developer/management/applications";
        String username = "username";
        String password = "password";
        params.addArgument("url", url);//设置参数,并赋予默认值 
        params.addArgument("username", username);//设置参数,并赋予默认值
        params.addArgument("password", password);//设置参数,并赋予默认值
        JavaSamplerContext arg0 = new JavaSamplerContext(params); 
        CASLogin eosCreateApplication = new CASLogin(); 
        eosCreateApplication.setupTest(arg0); 
        eosCreateApplication.runTest(arg0);
        eosCreateApplication.teardownTest(arg0); 
    }
    
}

 

 

package com.*.jmeter;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.AbstractSampler;
import org.apache.jmeter.samplers.Entry;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.testelement.TestStateListener;

import com.*.casLogin.CASLogin;
import com.*.jmeter.util.CASHttpClient;

public class CASLoginSampler extends AbstractSampler implements TestStateListener {
    private static final long serialVersionUID = 1L;
    
    private String url = "http://ip:8980/developer/management/applications";
    private String username = "username";
    private String password = "password";
    private static final String _eventId = "submit";
    private String lt = "LT-a66917f8-e044-c533-b67f-c04509efc806Ze1s1";
    private static final String regex = "(\\d+\\.\\d+\\.\\d+\\.\\d+)\\:(\\d+)";
    
    public CASLoginSampler(){
        setName("CASLogin Sampler");
    }
    
    @Override
    public SampleResult sample(Entry entry) {
        SampleResult results = new SampleResult();
        results.setSampleLabel(getName());
        try {
            results.sampleStart();// jmeter 开始统计响应时间标记
            lt = CASHttpClient.getCasLt(url);
            System.out.println("CASLoginSampler.lt:"+lt);
            System.out.println("url:"+getUrl());
            String redirect_url = CASHttpClient.sendCasLogin(getUrl(), getUsername(), getPassword(), lt,_eventId);
            redirect_url = rebuildRedirectUrl(redirect_url);
            results.setSamplerData("url:"+getUrl()+"\n"+"username:"+getUsername()+"\n"+"password:"+getPassword()+"\n"
                    +"lt:"+lt+"\n"+"_eventId:"+_eventId+"\n"+"redirect_url:"+redirect_url+"\n");
            results.sampleEnd(); 
            results.setSuccessful(true);
            results.setResponseCodeOK();
            results.setResponseData(redirect_url, "UTF-8");
            results.setContentType("application/json");
            //results.setContentType(SampleResult.TEXT);
        } catch (Exception e) {
            results.sampleEnd(); // stop stopwatch
            results.setSuccessful(false);
            results.setResponseMessage("Exception: " + e);
            // get stack trace as a String to return as document data
            java.io.StringWriter stringWriter = new java.io.StringWriter();
            e.printStackTrace(new java.io.PrintWriter(stringWriter));
            results.setResponseData(stringWriter.toString(), null);
            results.setDataType(org.apache.jmeter.samplers.SampleResult.TEXT);
            results.setResponseCode("FAILED");
        }
        return results;
    }
    
    
    /*@Override
    public SampleResult sample(Entry entry) {
        Arguments params = new Arguments(); 
        params.addArgument("url", getUrl());//设置参数,并赋予默认值 
        params.addArgument("username", getUsername());//设置参数,并赋予默认值
        params.addArgument("password", getPassword());//设置参数,并赋予默认值

        JavaSamplerContext arg0 = new JavaSamplerContext(params); 
        CASLogin casLogin = new CASLogin();
        casLogin.setupTest(arg0); 
        SampleResult result = casLogin.runTest(arg0);
        result.setSamplerData("url:"+url+"\n"+"username:"+username+"\n"+"password:"+password+"\n");
        casLogin.teardownTest(arg0); 
        return result;
    }*/

    public String getUrl() {
        return getPropertyAsString(url);
    }

    public void setUrl(String url) {
        setProperty(this.url, url);
    }

    public String getUsername() {
        return getPropertyAsString(username);
    }

    public void setUsername(String username) {
        setProperty(this.username, username);
    }

    public String getPassword() {
        return getPropertyAsString(password);
    }

    public void setPassword(String password) {
        setProperty(this.password, password);
    }
    
    public String getLt() {
        return getPropertyAsString(lt);
    }

    public void setLt(String lt) {
        setProperty(this.lt, lt);
    }

    @Override
    public void testEnded() {
        this.testEnded("local");
    }

    @Override
    public void testEnded(String arg0) {
        /*Iterator<Producer<String, String>> it = producers.values().iterator();
        while(it.hasNext()) {
            Producer<String, String> producer = it.next();
            producer.close();
        }*/
    }

    @Override
    public void testStarted() {
    }

    @Override
    public void testStarted(String arg0) {
    }

    private String rebuildRedirectUrl(String redirect_url) {
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(redirect_url);
        while(m.find()) {
            //System.out.println("ip:"+m.group(1));
            //System.out.println("port:"+m.group(2));
            System.out.println(redirect_url.substring(m.start(2)+4));
            return redirect_url.substring(m.start(2)+4);
        }
        return null;
    }
    
    @Override
    public String toString() {
        return "CASLoginSampler [url=" + url + ", username=" + username + ", password=" + password + ", lt=" + lt + "]";
    }
    
}

 

 

package com.*.jmeter;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;

import javax.swing.BorderFactory;
import javax.swing.JPanel;

import org.apache.jmeter.gui.util.VerticalPanel;
import org.apache.jmeter.samplers.gui.AbstractSamplerGui;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jorphan.gui.JLabeledTextField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.*.jmeter.util.CASHttpClient;

@SuppressWarnings("deprecation")
public class CASLoginSamplerUI extends AbstractSamplerGui {
    private static final long serialVersionUID = 1L;
    private static final Logger log = LoggerFactory.getLogger(CASLoginSamplerUI.class);
    private final JLabeledTextField urlField = new JLabeledTextField("url");
    private final JLabeledTextField usernameField = new JLabeledTextField("username");
    private final JLabeledTextField passwordField = new JLabeledTextField("password");

    public CASLoginSamplerUI() {
        super();
        this.init();
    }

    private void init() {
        log.info("Initializing the UI.");
        setLayout(new BorderLayout());
        setBorder(makeBorder());

        add(makeTitlePanel(), BorderLayout.NORTH);
        JPanel mainPanel = new VerticalPanel();
        add(mainPanel, BorderLayout.CENTER);

        JPanel DPanel = new JPanel();
        DPanel.setLayout(new GridLayout(3, 2));
        DPanel.add(urlField);
        DPanel.add(usernameField);
        DPanel.add(passwordField);

        JPanel ControlPanel = new VerticalPanel();
        ControlPanel.add(DPanel);
        ControlPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.gray), "Parameters"));
        mainPanel.add(ControlPanel);

        JPanel ContentPanel = new VerticalPanel();
        JPanel messageContentPanel = new JPanel(new BorderLayout());
        ContentPanel.add(messageContentPanel);
        ContentPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.gray), "Content"));
        mainPanel.add(ContentPanel);
    }

    @Override
    public TestElement createTestElement() {
        CASLoginSampler sampler = new CASLoginSampler();
        this.setupSamplerProperties(sampler);
        return sampler;
    }
    
    @Override
    public void clearGui() {
        super.clearGui();
        this.urlField.setText("");
        this.usernameField.setText("");
        this.passwordField.setText("");
    }

    @Override
    public void configure(TestElement element) {
        super.configure(element);
        CASLoginSampler sampler = (CASLoginSampler)element;
        this.urlField.setText(sampler.getUrl());
        this.usernameField.setText(sampler.getUsername());
        this.passwordField.setText(sampler.getPassword());
    }

    private void setupSamplerProperties(CASLoginSampler sampler) {
        this.configureTestElement(sampler);
        System.out.println(sampler.toString());
        sampler.setUrl(this.urlField.getText());
        sampler.setUsername(this.usernameField.getText());
        sampler.setPassword(this.passwordField.getText());
    }
    
    @Override
    public String getStaticLabel() {
        return "CASLogin Sampler";
    }

    @Override
    public String getLabelResource() {
        throw new IllegalStateException("This shouldn't be called"); 
    }

    @Override
    public void modifyTestElement(TestElement testElement) {
        CASLoginSampler sampler = (CASLoginSampler) testElement;
        this.setupSamplerProperties(sampler);
    }
    
    
    public static void main(String[] args) throws Exception {
        CASLoginSamplerUI kafkaSamplerUI = new CASLoginSamplerUI();
        CASLoginSampler sampler = new CASLoginSampler();
        kafkaSamplerUI.setupSamplerProperties(sampler);
    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值