aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/bitbucketpullrequestbuilder/bitbucketpullrequestbuilder/bitbucket
diff options
context:
space:
mode:
Diffstat (limited to 'src/main/java/bitbucketpullrequestbuilder/bitbucketpullrequestbuilder/bitbucket')
-rw-r--r--src/main/java/bitbucketpullrequestbuilder/bitbucketpullrequestbuilder/bitbucket/ApiClient.java285
-rw-r--r--src/main/java/bitbucketpullrequestbuilder/bitbucketpullrequestbuilder/bitbucket/BuildState.java10
-rw-r--r--src/main/java/bitbucketpullrequestbuilder/bitbucketpullrequestbuilder/bitbucket/Pullrequest.java392
3 files changed, 0 insertions, 687 deletions
diff --git a/src/main/java/bitbucketpullrequestbuilder/bitbucketpullrequestbuilder/bitbucket/ApiClient.java b/src/main/java/bitbucketpullrequestbuilder/bitbucketpullrequestbuilder/bitbucket/ApiClient.java
deleted file mode 100644
index 0c21806..0000000
--- a/src/main/java/bitbucketpullrequestbuilder/bitbucketpullrequestbuilder/bitbucket/ApiClient.java
+++ /dev/null
@@ -1,285 +0,0 @@
-package bitbucketpullrequestbuilder.bitbucketpullrequestbuilder.bitbucket;
-
-import org.apache.commons.httpclient.*;
-import org.apache.commons.httpclient.auth.AuthScope;
-import org.apache.commons.httpclient.methods.GetMethod;
-import org.apache.commons.httpclient.methods.PostMethod;
-import org.apache.commons.httpclient.methods.DeleteMethod;
-import org.apache.commons.httpclient.params.HttpClientParams;
-import org.codehaus.jackson.map.ObjectMapper;
-import org.codehaus.jackson.map.type.TypeFactory;
-import org.codehaus.jackson.type.JavaType;
-import org.codehaus.jackson.type.TypeReference;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import jenkins.model.Jenkins;
-import hudson.ProxyConfiguration;
-
-import java.io.UnsupportedEncodingException;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import org.apache.commons.codec.binary.Hex;
-import org.apache.commons.httpclient.methods.PutMethod;
-import org.apache.commons.httpclient.util.EncodingUtil;
-
-/**
- * Created by nishio
- */
-public class ApiClient {
- private static final Logger logger = Logger.getLogger(ApiClient.class.getName());
- private static final String V1_API_BASE_URL = "https://bitbucket.org/api/1.0/repositories/";
- private static final String V2_API_BASE_URL = "https://bitbucket.org/api/2.0/repositories/";
- private static final String COMPUTED_KEY_FORMAT = "%s-%s";
- private String owner;
- private String repositoryName;
- private Credentials credentials;
- private String key;
- private String name;
- private HttpClientFactory factory;
-
- public static final byte MAX_KEY_SIZE_BB_API = 40;
-
- public static class HttpClientFactory {
- public static final HttpClientFactory INSTANCE = new HttpClientFactory();
- private static final int DEFAULT_TIMEOUT = 60000;
-
- public HttpClient getInstanceHttpClient() {
- HttpClient client = new HttpClient();
-
- HttpClientParams params = client.getParams();
- params.setConnectionManagerTimeout(DEFAULT_TIMEOUT);
- params.setSoTimeout(DEFAULT_TIMEOUT);
-
- if (Jenkins.getInstance() == null) return client;
-
- ProxyConfiguration proxy = getInstance().proxy;
- if (proxy == null) return client;
-
- logger.log(Level.FINE, "Jenkins proxy: {0}:{1}", new Object[]{ proxy.name, proxy.port });
- client.getHostConfiguration().setProxy(proxy.name, proxy.port);
- String username = proxy.getUserName();
- String password = proxy.getPassword();
-
- // Consider it to be passed if username specified. Sufficient?
- if (username != null && !"".equals(username.trim())) {
- logger.log(Level.FINE, "Using proxy authentication (user={0})", username);
- client.getState().setProxyCredentials(AuthScope.ANY,
- new UsernamePasswordCredentials(username, password));
- }
-
- return client;
- }
-
- private Jenkins getInstance() {
- final Jenkins instance = Jenkins.getInstance();
- if (instance == null){
- throw new IllegalStateException("Jenkins instance is NULL!");
- }
- return instance;
- }
- }
-
-
-
- public <T extends HttpClientFactory> ApiClient(
- String username, String password,
- String owner, String repositoryName,
- String key, String name,
- T httpFactory
- ) {
- this.credentials = new UsernamePasswordCredentials(username, password);
- this.owner = owner;
- this.repositoryName = repositoryName;
- this.key = key;
- this.name = name;
- this.factory = httpFactory != null ? httpFactory : HttpClientFactory.INSTANCE;
- }
-
- public List<Pullrequest> getPullRequests() {
- return getAllValues(v2("/pullrequests/"), 50, Pullrequest.class);
- }
-
- public List<Pullrequest.Comment> getPullRequestComments(String commentOwnerName, String commentRepositoryName, String pullRequestId) {
- return getAllValues(v2("/pullrequests/" + pullRequestId + "/comments"), 100, Pullrequest.Comment.class);
- }
-
- public String getName() {
- return this.name;
- }
-
- private static MessageDigest SHA1 = null;
-
- /**
- * Retrun
- * @param keyExPart
- * @return key parameter for call BitBucket API
- */
- private String computeAPIKey(String keyExPart) {
- String computedKey = String.format(COMPUTED_KEY_FORMAT, this.key, keyExPart);
-
- if (computedKey.length() > MAX_KEY_SIZE_BB_API) {
- try {
- if (SHA1 == null) SHA1 = MessageDigest.getInstance("SHA1");
- return new String(Hex.encodeHex(SHA1.digest(computedKey.getBytes("UTF-8"))));
- } catch(NoSuchAlgorithmException e) {
- logger.log(Level.WARNING, "Failed to create hash provider", e);
- } catch (UnsupportedEncodingException e) {
- logger.log(Level.WARNING, "Failed to create hash provider", e);
- }
- }
- return (computedKey.length() <= MAX_KEY_SIZE_BB_API) ? computedKey : computedKey.substring(0, MAX_KEY_SIZE_BB_API);
- }
-
- public String buildStatusKey(String bsKey) {
- return this.computeAPIKey(bsKey);
- }
-
- public boolean hasBuildStatus(String owner, String repositoryName, String revision, String keyEx) {
- String url = v2(owner, repositoryName, "/commit/" + revision + "/statuses/build/" + this.computeAPIKey(keyEx));
- String reqBody = get(url);
- return reqBody != null && reqBody.contains("\"state\"");
- }
-
- public void setBuildStatus(String owner, String repositoryName, String revision, BuildState state, String buildUrl, String comment, String keyEx) {
- String url = v2(owner, repositoryName, "/commit/" + revision + "/statuses/build");
- String computedKey = this.computeAPIKey(keyEx);
- NameValuePair[] data = new NameValuePair[]{
- new NameValuePair("description", comment),
- new NameValuePair("key", computedKey),
- new NameValuePair("name", this.name),
- new NameValuePair("state", state.toString()),
- new NameValuePair("url", buildUrl),
- };
- logger.log(Level.FINE, "POST state {0} to {1} with key {2} with response {3}", new Object[]{
- state, url, computedKey, post(url, data)}
- );
- }
-
- public void deletePullRequestApproval(String pullRequestId) {
- delete(v2("/pullrequests/" + pullRequestId + "/approve"));
- }
-
- public void deletePullRequestComment(String pullRequestId, String commentId) {
- delete(v1("/pullrequests/" + pullRequestId + "/comments/" + commentId));
- }
-
- public void updatePullRequestComment(String pullRequestId, String content, String commentId) {
- NameValuePair[] data = new NameValuePair[] {
- new NameValuePair("content", content),
- };
- put(v1("/pullrequests/" + pullRequestId + "/comments/" + commentId), data);
- }
-
- public Pullrequest.Participant postPullRequestApproval(String pullRequestId) {
- try {
- return parse(post(v2("/pullrequests/" + pullRequestId + "/approve"),
- new NameValuePair[]{}), Pullrequest.Participant.class);
- } catch (IOException e) {
- logger.log(Level.WARNING, "Invalid pull request approval response.", e);
- }
- return null;
- }
-
- public Pullrequest.Comment postPullRequestComment(String pullRequestId, String content) {
- NameValuePair[] data = new NameValuePair[] {
- new NameValuePair("content", content),
- };
- try {
- return parse(post(v1("/pullrequests/" + pullRequestId + "/comments"), data), new TypeReference<Pullrequest.Comment>() {});
- } catch(Exception e) {
- logger.log(Level.WARNING, "Invalid pull request comment response.", e);
- }
- return null;
- }
-
- private <T> List<T> getAllValues(String rootUrl, int pageLen, Class<T> cls) {
- List<T> values = new ArrayList<T>();
- try {
- String url = rootUrl + "?pagelen=" + pageLen;
- do {
- final JavaType type = TypeFactory.defaultInstance().constructParametricType(Pullrequest.Response.class, cls);
- Pullrequest.Response<T> response = parse(get(url), type);
- values.addAll(response.getValues());
- url = response.getNext();
- } while (url != null);
- } catch (Exception e) {
- logger.log(Level.WARNING, "invalid response.", e);
- }
- return values;
- }
-
- private HttpClient getHttpClient() {
- return this.factory.getInstanceHttpClient();
- }
-
- private String v1(String url) {
- return V1_API_BASE_URL + this.owner + "/" + this.repositoryName + url;
- }
-
- private String v2(String path) {
- return v2(this.owner, this.repositoryName, path);
- }
-
- private String v2(String owner, String repositoryName, String path) {
- return V2_API_BASE_URL + owner + "/" + repositoryName + path;
- }
-
- private String get(String path) {
- return send(new GetMethod(path));
- }
-
- private String post(String path, NameValuePair[] data) {
- PostMethod req = new PostMethod(path);
- req.setRequestBody(data);
- req.getParams().setContentCharset("utf-8");
- return send(req);
- }
-
- private void delete(String path) {
- send(new DeleteMethod(path));
- }
-
- private void put(String path, NameValuePair[] data) {
- PutMethod req = new PutMethod(path);
- req.setRequestBody(EncodingUtil.formUrlEncode(data, "utf-8"));
- req.getParams().setContentCharset("utf-8");
- send(req);
- }
-
- private String send(HttpMethodBase req) {
- HttpClient client = getHttpClient();
- client.getState().setCredentials(AuthScope.ANY, credentials);
- client.getParams().setAuthenticationPreemptive(true);
- try {
- int statusCode = client.executeMethod(req);
- if (statusCode != HttpStatus.SC_OK) {
- logger.log(Level.WARNING, "Response status: " + req.getStatusLine()+" URI: "+req.getURI());
- }else{
- return req.getResponseBodyAsString();
- }
- } catch (HttpException e) {
- logger.log(Level.WARNING, "Failed to send request.", e);
- } catch (IOException e) {
- logger.log(Level.WARNING, "Failed to send request.", e);
- } finally {
- req.releaseConnection();
- }
- return null;
- }
-
- private <R> R parse(String response, Class<R> cls) throws IOException {
- return new ObjectMapper().readValue(response, cls);
- }
- private <R> R parse(String response, JavaType type) throws IOException {
- return new ObjectMapper().readValue(response, type);
- }
- private <R> R parse(String response, TypeReference<R> ref) throws IOException {
- return new ObjectMapper().readValue(response, ref);
- }
-}
diff --git a/src/main/java/bitbucketpullrequestbuilder/bitbucketpullrequestbuilder/bitbucket/BuildState.java b/src/main/java/bitbucketpullrequestbuilder/bitbucketpullrequestbuilder/bitbucket/BuildState.java
deleted file mode 100644
index a3ef1f1..0000000
--- a/src/main/java/bitbucketpullrequestbuilder/bitbucketpullrequestbuilder/bitbucket/BuildState.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package bitbucketpullrequestbuilder.bitbucketpullrequestbuilder.bitbucket;
-
-/**
- * Valid build states for a pull request
- *
- * @see "https://confluence.atlassian.com/bitbucket/buildstatus-resource-779295267.html"
- */
-public enum BuildState {
- FAILED, INPROGRESS, SUCCESSFUL
-}
diff --git a/src/main/java/bitbucketpullrequestbuilder/bitbucketpullrequestbuilder/bitbucket/Pullrequest.java b/src/main/java/bitbucketpullrequestbuilder/bitbucketpullrequestbuilder/bitbucket/Pullrequest.java
deleted file mode 100644
index b69805e..0000000
--- a/src/main/java/bitbucketpullrequestbuilder/bitbucketpullrequestbuilder/bitbucket/Pullrequest.java
+++ /dev/null
@@ -1,392 +0,0 @@
-package bitbucketpullrequestbuilder.bitbucketpullrequestbuilder.bitbucket;
-
-import java.util.List;
-import java.util.Comparator;
-import java.util.Map;
-
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.annotate.JsonProperty;
-
-/**
- * POJOs representing the pull-requests extracted from the
- * JSON response of the Bitbucket API V2.
- *
- * @see "https://confluence.atlassian.com/bitbucket/pullrequests-resource-423626332.html#pullrequestsResource-GETaspecificpullrequest"
- */
-
-@JsonIgnoreProperties(ignoreUnknown = true)
-public class Pullrequest {
-
- private String description;
- private Boolean closeSourceBranch;
- private String title;
- private Revision destination;
- private String reason;
- private String closedBy;
- private Revision source;
- private String state;
- private String createdOn;
- private String updatedOn;
- private String mergeCommit;
- private String id;
- private Author author;
-
- @JsonIgnoreProperties(ignoreUnknown = true)
- public static class Response<T> {
- private int pageLength;
- private List<T> values;
- private int page;
- private int size;
- private String next;
-
- @JsonProperty("pagelen")
- public int getPageLength() {
- return pageLength;
- }
- @JsonProperty("pagelen")
- public void setPageLength(int pageLength) {
- this.pageLength = pageLength;
- }
- public List<T> getValues() {
- return values;
- }
- public void setValues(List<T> values) {
- this.values = values;
- }
- public int getPage() {
- return page;
- }
- public void setPage(int page) {
- this.page = page;
- }
- public int getSize() {
- return size;
- }
- public void setSize(int size) {
- this.size = size;
- }
- public String getNext() {
- return next;
- }
- public void setNext(String next) {
- this.next = next;
- }
- }
-
-
- @JsonIgnoreProperties(ignoreUnknown = true)
- public static class Revision {
- private Repository repository;
- private Branch branch;
- private Commit commit;
-
- public Repository getRepository() {
- return repository;
- }
- public void setRepository(Repository repository) {
- this.repository = repository;
- }
- public Branch getBranch() {
- return branch;
- }
- public void setBranch(Branch branch) {
- this.branch = branch;
- }
- public Commit getCommit() {
- return commit;
- }
- public void setCommit(Commit commit) {
- this.commit = commit;
- }
- }
-
- @JsonIgnoreProperties(ignoreUnknown = true)
- public static class Repository {
- private String fullName;
- private String name;
- private String ownerName;
- private String repositoryName;
-
- @JsonProperty("full_name")
- public String getFullName() {
- return fullName;
- }
- @JsonProperty("full_name")
- public void setFullName(String fullName) {
- // Also extract owner- and reponame
- if (fullName != null) {
- this.ownerName = fullName.split("/")[0];
- this.repositoryName = fullName.split("/")[1];
- }
- this.fullName = fullName;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getOwnerName() {
- return ownerName;
- }
- public String getRepositoryName() {
- return repositoryName;
- }
- }
-
- @JsonIgnoreProperties(ignoreUnknown = true)
- public static class Branch {
- private String name;
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
- }
-
- @JsonIgnoreProperties(ignoreUnknown = true)
- public static class Commit {
- private String hash;
-
- public String getHash() {
- return hash;
- }
-
- public void setHash(String hash) {
- this.hash = hash;
- }
- }
-
- // Was: Approval
- @JsonIgnoreProperties(ignoreUnknown = true)
- public static class Participant {
- private String role;
- private Boolean approved;
-
- public String getRole() {
- return role;
- }
- public void setRole(String role) {
- this.role = role;
- }
- public Boolean getApproved() {
- return approved;
- }
- public void setApproved(Boolean approved) {
- this.approved = approved;
- }
- }
-
- // https://confluence.atlassian.com/bitbucket/pullrequests-resource-1-0-296095210.html#pullrequestsResource1.0-POSTanewcomment
- @JsonIgnoreProperties(ignoreUnknown = true)
- public static class Comment implements Comparable<Comment> {
- private Integer id;
- private String filename;
- private String content;
-
- @Override
- public int compareTo(Comment target) {
- if (target == null){
- return -1;
- } else if (this.getId() > target.getId()) {
- return 1;
- } else if (this.getId().equals(target.getId())) {
- return 0;
- } else {
- return -1;
- }
- }
-
- @Override
- public boolean equals(final Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- final Comment comment = (Comment) o;
-
- return getId() != null ? getId().equals(comment.getId()) : comment.getId() == null;
- }
-
- @Override
- public int hashCode() {
- return getId() != null ? getId().hashCode() : 0;
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getFilename() {
- return filename;
- }
-
- public void setFilename(String filename) {
- this.filename = filename;
- }
-
- public String getContent() {
- return content;
- }
-
- public void setContent(Object content) {
- if (content instanceof String) {
- this.content = (String)content;
- } else if (content instanceof Map){
- this.content = (String)((Map)content).get("raw");
- }
- return;
- }
-
- }
-
- @JsonIgnoreProperties(ignoreUnknown = true)
- public static class Author {
- private String username;
- private String display_name;
- public static final String COMBINED_NAME = "%s <@%s>";
-
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
-
- @JsonProperty("display_name")
- public String getDisplayName() {
- return display_name;
- }
-
- @JsonProperty("display_name")
- public void setDisplayName(String display_name) {
- this.display_name = display_name;
- }
- public String getCombinedUsername() {
- return String.format(COMBINED_NAME, this.getDisplayName(), this.getUsername());
- }
- }
-
- //-------------------- only getters and setters follow -----------------
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- @JsonProperty("close_source_branch")
- public Boolean getCloseSourceBranch() {
- return closeSourceBranch;
- }
-
- @JsonProperty("close_source_branch")
- public void setCloseSourceBranch(Boolean closeSourceBranch) {
- this.closeSourceBranch = closeSourceBranch;
- }
-
- public String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public Revision getDestination() {
- return destination;
- }
-
- public void setDestination(Revision destination) {
- this.destination = destination;
- }
-
- public String getReason() {
- return reason;
- }
-
- public void setReason(String reason) {
- this.reason = reason;
- }
-
- @JsonProperty("closed_by")
- public String getClosedBy() {
- return closedBy;
- }
-
- @JsonProperty("closed_by")
- public void setClosedBy(String closedBy) {
- this.closedBy = closedBy;
- }
-
- public Revision getSource() {
- return source;
- }
-
- public void setSource(Revision source) {
- this.source = source;
- }
-
- public String getState() {
- return state;
- }
-
- public void setState(String state) {
- this.state = state;
- }
-
- @JsonProperty("created_on")
- public String getCreatedOn() {
- return createdOn;
- }
-
- @JsonProperty("created_on")
- public void setCreatedOn(String createdOn) {
- this.createdOn = createdOn;
- }
-
- @JsonProperty("updated_on")
- public String getUpdatedOn() {
- return updatedOn;
- }
-
- @JsonProperty("updated_on")
- public void setUpdatedOn(String updatedOn) {
- this.updatedOn = updatedOn;
- }
-
- @JsonProperty("merge_commit")
- public String getMergeCommit() {
- return mergeCommit;
- }
-
- @JsonProperty("merge_commit")
- public void setMergeCommit(String mergeCommit) {
- this.mergeCommit = mergeCommit;
- }
-
- public String getId() {
- return id;
- }
-
- public void setId(String id) {
- this.id = id;
- }
-
- public Author getAuthor() {
- return this.author;
- }
-
- public void setAutohor(Author author) {
- this.author = author;
- }
-
-}