jira api操作

/ Java / 0 条评论 / 599浏览
1. jira api常见操作
public static void login(String username,String password) {
		String request = requestUrl + "j_atl_security_check";
		String input = "j_username="+username+"&j_password="+password+"&submit=Log+in";
		sendPost(request, input);
		//System.out.println(result);
	}
	
	public static void getATl_token() {
		headers.put("Referer", requestUrl+"projects");
		String request = requestUrl + "projects?create";
		String result = sendGet(request, null);
		Pattern pat = Pattern.compile("atl_token(.*)(?=(\"></form))");
		Matcher mat = pat.matcher(result);
		String out = "";
		if(mat.find()) {
			out = mat.group(1);
		}
		atl_token = out.substring(out.lastIndexOf("\"")+1);
		System.out.println("atl_token: " + atl_token);
	}
	
	public static void createProject(String projectName,String porjectKey, String Description) {
		String request = requestUrl + "projects?create";
		String input = "name="+projectName+"&key="+porjectKey+"&description="+Description+"&avatar=&submit=Create+project&atl_token="+atl_token;
		sendPost(request, input);
	}
	
	//
	public static String getProjectId(String projectName) {
		headers.put("Content-Type","application/json;charset=UTF-8");
		headers.put("Accept","application/json, text/javascript, */*; q=0.01");
		String request = requestUrl + "projects";
		String input = "avatarSize=32&permission=PROJECT_ADMIN&start=0&limit=25&name="+projectName;
		String result = sendGet(request, input, false);
		JSONArray fromObject = JSONObject.fromObject(result).getJSONArray("values");
		for(int i=0;i<fromObject.size();i++) {
			JSONObject object = (JSONObject)fromObject.get(i);
			if(object.get("name").toString().equals(projectName)) {
				return object.get("id").toString();
			}
		}
		return "";
	}
	

	//新建branch
	public static void copyBranch(String module) {
		headers.put("Content-Type","application/json;charset=UTF-8");
		headers.put("Accept","application/json, text/javascript, */*; q=0.01");
		String request = requestUrl + "rest/branch-utils/latest/projects/IOS/repos/"+module.toLowerCase()+"/branches";
		String input ="{\"name\":\"UEM5.2.0_nqsky\",\"startPoint\":\"refs/heads/UEM5.2.0\"}";//refs/heads/UEM5.2.0
		sendPost(request, input);
	}
	
	//http://192.168.22.67:7990/projects/ANDROID/repos/nqmdm?fork
	public static void forkProject(String project, String module, String projectName) {
		String toProjectId = getProjectId(projectName);
		headers.put("Content-Type","application/x-www-form-urlencoded");
		headers.put("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		String request = requestUrl + "projects/"+project+"/repos/"+module.toLowerCase()+"?fork";
		String input = "toProjectId="+toProjectId+"&name="+module+"&fork-repo-submit=Fork+repository&atl_token="+atl_token;
		sendPost(request, input);
	}
	
	public static void operateBranchs(String projectKey, String module, String branchName) {
		//设置默认branch
		String request = requestUrl + "projects/"+projectKey+"/repos/"+module.toLowerCase()+"/settings";
		String input = "name="+module+"&defaultBranchId=refs%2Fheads%2F"+branchName+"&forkable=on&submit=Save&atl_token="+atl_token;
		sendPost(request, input);
		//获取branch + 删除多余branch
		headers.put("Content-Type","application/json;charset=UTF-8");
		headers.put("Accept","application/json, text/javascript, */*; q=0.01");
		request = requestUrl + "rest/api/latest/projects/"+projectKey+"/repos/"+module.toLowerCase()+"/branches";
		input = "start=0&limit=50";
		//input = "base=refs/heads/master&details=true&start=0&limit=50&orderBy=MODIFICATION&context={\"withMessages\":false}";
		String result = sendGet(request, input, false);
		if(!result.contains("NoSuchRepositoryException")) {
			JSONArray fromObject = JSONObject.fromObject(result).getJSONArray("values");
			for(int i=0;i<fromObject.size();i++) {
				JSONObject object = (JSONObject)fromObject.get(i);
				String displayName = object.get("displayId").toString();
				if(!displayName.equals(branchName)) {
					String endPoint = object.get("latestCommit").toString();
					//删除branch
					System.out.println(displayName);
					headers.put("Content-Type","application/json;charset=UTF-8");
					headers.put("Accept","application/json, text/javascript, */*; q=0.01");
					request = requestUrl + "rest/branch-utils/latest/projects/"+projectKey+"/repos/"+module.toLowerCase()+"/branches?";
					input = "{\"name\":\""+displayName+"\",\"endPoint\":\""+endPoint+"\"}";
					sendDelete(request,input);
				}
			}
		}
	}
	
	//PROJECT_ADMIN PROJECT_WRITE
	//REPO_WRITE REPO_ADMIN
	public static void grantPermission(String projectKey, String module, String name ,String role) {
		headers.put("Content-Type","application/json;charset=UTF-8");
		headers.put("Accept","application/json, text/javascript, */*; q=0.01");
		String request = requestUrl + "projects/"+projectKey+"/repos/"+module.toLowerCase()+"/permissions/users";
		String input = "permission="+role+"&name="+name;
		sendPut(request, input);
	}
	
	public static void grantPermission(String projectKey, String name ,String role) {
		headers.put("Content-Type","application/json;charset=UTF-8");
		headers.put("Accept","application/json, text/javascript, */*; q=0.01");
		String request = requestUrl + "projects/"+projectKey+"/permissions/groups";
		String input = "permission="+role+"&name="+name;
		sendPut(request, input);
	}
	
	public static void deleteProject(String projectKey) {
		String request = requestUrl + "projects/"+projectKey;
		String result = sendGet(request, null);
		//result  
		Pattern pat = Pattern.compile("projects/"+projectKey+"/repos/(.{5,30})?=/");
		Matcher mat = pat.matcher(result);
		String out = "";
		while(mat.find()) {
			out = mat.group(1);
			request = requestUrl + "projects/"+projectKey+"/repos/"+out;
			sendDelete(request, null);
			System.out.println("delete: " + out);
		}
		
		request = requestUrl + "projects/"+projectKey;
		sendDelete(request, null);
	}
	
	//http://192.168.22.205:8080/jenkins/job/emm_master_android_build_EMMAccreditSDKDemo_4.0.1/1170/doDelete
	public static void deleteJenkinsBuild(String jobName, String buildNo) {
		String requestUrl = "http://192.168.22.205:8080/jenkins/job/"+jobName+"/"+buildNo+"/doDelete";
		sendPost(requestUrl, "json={}&Submit=确定");
	}
2. http封装
public static void sendPost(String url, String param) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		System.out.println("url:" + url);
		System.out.println("param:" + param);
		HttpPost httppost = new HttpPost(url);
		for(String key : headers.keySet()) {
			httppost.setHeader(key, headers.get(key));
		}
		StringEntity stringEntity = new StringEntity(param.toString(), "UTF-8");
		stringEntity.setContentEncoding("UTF-8");
		httppost.setEntity(stringEntity);
		HttpResponse response;
		try {
			response = httpclient.execute(httppost);
			if(response.getHeaders("Set-Cookie").length>0) {
				String cookie = response.getHeaders("Set-Cookie")[0].getValue();
				System.out.println(cookie.substring(0, cookie.indexOf(";")));
				headers.put("Cookie", cookie.substring(0, cookie.indexOf(";")));
			}
			//String result = EntityUtils.toString(response.getEntity());
			EntityUtils.consume(response.getEntity());
			System.out.println("post end! Status: " + response.getStatusLine().getStatusCode());
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public static void sendPut(String url, String param) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		System.out.println("url:" + url);
		System.out.println("param:" + param);
		String urlNameString = url;
		if (param != null) {
			urlNameString += "?" + param;
		}
		HttpPut httpput = new HttpPut(urlNameString);
		for(String key : headers.keySet()) {
			httpput.setHeader(key, headers.get(key));
		}
		HttpResponse response;
		try {
			response = httpclient.execute(httpput);
			EntityUtils.consume(response.getEntity());
			System.out.println("post end! Status: " + response.getStatusLine().getStatusCode());
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public static void sendDelete(String url, String params) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpDeleteWithBody deleteMethod = new HttpDeleteWithBody(url);
		for(String key : headers.keySet()) {
			deleteMethod.setHeader(key, headers.get(key));
		}
		try {
			if(params!=null) {
				StringEntity entity = new StringEntity(params, "utf-8");
				entity.setContentEncoding("UTF-8");
				entity.setContentType("application/json");
				deleteMethod.setEntity(entity);
			}
			httpclient.execute(deleteMethod);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
3. 浏览器模拟header
static {
		headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:66.0) Gecko/20100101 Firefox/66.0");
		headers.put("Cookie", "JSESSIONID="+JSESSIONID);
		headers.put("Content-Type", "application/x-www-form-urlencoded");
//		headers.put("Referer", requestUrl+"login");
//		headers.put("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
//		headers.put("Cache-Control","max-age=0");
	}
4. Delete处理(带body)
@NotThreadSafe
class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {

    public static final String METHOD_NAME = "DELETE";

    /**
     * 获取方法(必须重载)
     *
     * @return
     */
    @Override
    public String getMethod() {
        return METHOD_NAME;
    }

    public HttpDeleteWithBody(final String uri) {
        super();
        setURI(URI.create(uri));
    }

    public HttpDeleteWithBody(final URI uri) {
        super();
        setURI(uri);
    }

    public HttpDeleteWithBody() {
        super();
    }
}
评论已关闭.