Newer
Older
RestfulChecker / src / main / RestApi.java
y-ota on 8 Nov 2018 2 KB 参考文献をうp
package main;

import java.util.ArrayList;
import java.util.Iterator;

public class RestApi {
	private ArrayList<RestAccount> accounts = new ArrayList<>();
	private ArrayList<String> results = new ArrayList<>();
	private ArrayList<Integer> responses = new ArrayList<>();
	private Method type;
	private ArrayList<RestParam> queryParam;
	private ArrayList<RestParam> formParam;
	private ArrayList<String> pathParam;
	private String judgeResult;
	public static final int ACCOUNT_NUM = 5;

	public void setAccount(String url) {
		for (int i = 0; i < ACCOUNT_NUM; i++)
			accounts.add(new RestAccount(url));
	}

	public ArrayList<RestAccount> getAccounts() {
		return accounts;
	}

	public ArrayList<String> getResults() {
		return results;
	}

	public String getJudgeResult() {
		return judgeResult;
	}

	public void setupRestTest(Method method, ArrayList<RestParam> queryParam, ArrayList<RestParam> formParam,
			ArrayList<String> pathParam) {
		this.type = method;
		this.queryParam = queryParam;
		this.formParam = formParam;
		this.pathParam = pathParam;
	}

	public void doRestTest() {
		if (type == null)
			return;
		for (RestAccount account : accounts) {
			switch (type) {
			case GET:
				account.doGet();
				break;
			case POST:
				account.doPost();
				break;
			case PUT:
				account.doPut();
				break;
			case DELETE:
				account.doDelete();
				break;
			}
			addParam(account);
			account.doAnything();
			responses.add(account.getResponseCode());
			results.add(account.doReceive());
		}
		if (listAllEquals(results, responses)) {
			judgeResult = "GET";
		} else {

		}
	}

	private void addParam(RestAccount account) {
		if (queryParam != null)
			for (RestParam param : queryParam) {
				account.addQueryParam(param.key, param.value);
			}
		if (formParam != null && type != Method.GET)
			for (RestParam param : formParam) {
				account.addFormParam(param.key, param.value);
			}
		if (pathParam != null)
			for (String param : pathParam) {
				account.addPathParam(param);
			}
	}

	private boolean listAllEquals(ArrayList<String> results, ArrayList<Integer> respounses) {
		String first = results.get(0);
		int firstres = respounses.get(0);
		Iterator<Integer> res = respounses.iterator();
		for (String s : results) {
			if(firstres != 200)
				return false;
			if (!s.equals(first))
				return false;
			firstres = (int)res.next();
		}
		return true;
	}

	public enum Method {
		GET, POST, PUT, DELETE
	};

}