From ac1481ffee8b517bbc66d8140d36bfb00549cf87 Mon Sep 17 00:00:00 2001 From: "oleg.shaburov" Date: Tue, 17 Apr 2018 01:39:20 +0300 Subject: [PATCH 1/3] Fixed: GITHUB-297: The "connectTimeout" parameter is not configurable Refactoring: add getter for host field GitlabAPI && remove unused IOException from the method signature --- CHANGES.txt | 2 + src/main/java/org/gitlab/api/GitlabAPI.java | 95 +++++++++---------- .../gitlab/api/http/GitlabHTTPRequestor.java | 8 ++ 3 files changed, 55 insertions(+), 50 deletions(-) create mode 100644 CHANGES.txt diff --git a/CHANGES.txt b/CHANGES.txt new file mode 100644 index 00000000..f8749726 --- /dev/null +++ b/CHANGES.txt @@ -0,0 +1,2 @@ +Current +Fixed: GITHUB-297: The "connectTimeout" parameter is not configurable. \ No newline at end of file diff --git a/src/main/java/org/gitlab/api/GitlabAPI.java b/src/main/java/org/gitlab/api/GitlabAPI.java index 3b41aafb..9a1da032 100644 --- a/src/main/java/org/gitlab/api/GitlabAPI.java +++ b/src/main/java/org/gitlab/api/GitlabAPI.java @@ -42,6 +42,7 @@ public class GitlabAPI { private boolean ignoreCertificateErrors = false; private Proxy proxy; private int requestTimeout = 0; + private int connectionTimeout = 0; private String userAgent = GitlabAPI.class.getCanonicalName() + "/" + System.getProperty("java.version"); private GitlabAPI(String hostUrl, String apiToken, TokenType tokenType, AuthMethod method) { @@ -89,6 +90,15 @@ public GitlabAPI setRequestTimeout(int requestTimeout) { return this; } + public int getConnectionTimeout() { + return connectionTimeout; + } + + public GitlabAPI setConnectionTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + return this; + } + public GitlabHTTPRequestor retrieve() { return new GitlabHTTPRequestor(this).authenticate(apiToken, tokenType, authMethod); } @@ -120,7 +130,11 @@ public URL getUrl(String tailAPIUrl) throws IOException { return new URL(hostUrl + tailAPIUrl); } - public List getUsers() throws IOException { + public String getHost() { + return hostUrl; + } + + public List getUsers() { String tailUrl = GitlabUser.URL + PARAM_MAX_ITEMS_PER_PAGE; return retrieve().getAll(tailUrl, GitlabUser[].class); } @@ -134,7 +148,7 @@ public List getUsers() throws IOException { * @throws IOException */ public List findUsers(String emailOrUsername) throws IOException { - List users = new ArrayList(); + List users = new ArrayList<>(); if (emailOrUsername != null && !emailOrUsername.equals("")) { String tailUrl = GitlabUser.URL + "?search=" + emailOrUsername; GitlabUser[] response = retrieve().to(tailUrl, GitlabUser[].class); @@ -429,9 +443,8 @@ public List getGroupsViaSudo(String username, Pagination pagination * * @param group the target group * @return a list of projects for the group - * @throws IOException */ - public List getGroupProjects(GitlabGroup group) throws IOException { + public List getGroupProjects(GitlabGroup group) { return getGroupProjects(group.getId()); } @@ -440,9 +453,8 @@ public List getGroupProjects(GitlabGroup group) throws IOExceptio * * @param groupId the target group's id. * @return a list of projects for the group - * @throws IOException */ - public List getGroupProjects(Integer groupId) throws IOException { + public List getGroupProjects(Integer groupId) { String tailUrl = GitlabGroup.URL + "/" + groupId + GitlabProject.URL + PARAM_MAX_ITEMS_PER_PAGE; return retrieve().getAll(tailUrl, GitlabProject[].class); } @@ -452,9 +464,8 @@ public List getGroupProjects(Integer groupId) throws IOException * * @param group The GitLab Group * @return The Group Members - * @throws IOException on gitlab api call error */ - public List getGroupMembers(GitlabGroup group) throws IOException { + public List getGroupMembers(GitlabGroup group) { return getGroupMembers(group.getId()); } @@ -463,9 +474,8 @@ public List getGroupMembers(GitlabGroup group) throws IOExcep * * @param groupId The id of the GitLab Group * @return The Group Members - * @throws IOException on gitlab api call error */ - public List getGroupMembers(Integer groupId) throws IOException { + public List getGroupMembers(Integer groupId) { String tailUrl = GitlabGroup.URL + "/" + groupId + GitlabGroupMember.URL + PARAM_MAX_ITEMS_PER_PAGE; return retrieve().getAll(tailUrl, GitlabGroupMember[].class); } @@ -710,9 +720,8 @@ public void deleteGroup(Integer groupId) throws IOException { * Get's all projects in Gitlab, requires sudo user * * @return A list of gitlab projects - * @throws IOException */ - public List getAllProjects() throws IOException { + public List getAllProjects() { String tailUrl = GitlabProject.URL; return retrieve().getAll(tailUrl, GitlabProject[].class); } @@ -757,9 +766,8 @@ public String getProjectJson(String namespace, String projectName) throws IOExce * Get a list of projects accessible by the authenticated user. * * @return A list of gitlab projects - * @throws IOException */ - public List getProjects() throws IOException { + public List getProjects() { String tailUrl = GitlabProject.URL + PARAM_MAX_ITEMS_PER_PAGE; return retrieve().getAll(tailUrl, GitlabProject[].class); } @@ -893,9 +901,8 @@ public List getProjectsViaSudoWithPagination(GitlabUser user, Pag * If the user is an administrator, a list of all namespaces in the GitLab instance is shown. * * @return A list of gitlab namespace - * @throws IOException */ - public List getNamespaces() throws IOException { + public List getNamespaces() { String tailUrl = GitlabNamespace.URL + PARAM_MAX_ITEMS_PER_PAGE; return retrieve().getAll(tailUrl, GitlabNamespace[].class); } @@ -918,9 +925,8 @@ public GitlabUpload uploadFile(GitlabProject project, File file) throws IOExcept * * @param project the project * @return A list of project jobs - * @throws IOException */ - public List getProjectJobs(GitlabProject project) throws IOException { + public List getProjectJobs(GitlabProject project) { return getProjectJobs(project.getId()); } @@ -929,9 +935,8 @@ public List getProjectJobs(GitlabProject project) throws IOException * * @param projectId the project id * @return A list of project jobs - * @throws IOException */ - public List getProjectJobs(Integer projectId) throws IOException { + public List getProjectJobs(Integer projectId) { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabJob.URL + PARAM_MAX_ITEMS_PER_PAGE; return retrieve().getAll(tailUrl, GitlabJob[].class); } @@ -943,9 +948,8 @@ public List getProjectJobs(Integer projectId) throws IOException { * @param project the project * @param pipelineId * @return A list of project jobs - * @throws IOException */ - public List getPipelineJobs(GitlabProject project, Integer pipelineId) throws IOException { + public List getPipelineJobs(GitlabProject project, Integer pipelineId) { return getPipelineJobs(project.getId(), pipelineId); } @@ -955,7 +959,6 @@ public List getPipelineJobs(GitlabProject project, Integer pipelineId * @param projectId * @param pipelineId * @return A list of project jobs - * @throws IOException */ public List getPipelineJobs(Integer projectId, Integer pipelineId) { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabPipeline.URL + "/" + sanitizeId(pipelineId, "PipelineID") + GitlabJob.URL + PARAM_MAX_ITEMS_PER_PAGE; @@ -1404,27 +1407,27 @@ public List getMergeRequestsWithStatus(GitlabProject project return retrieve().getAll(tailUrl, GitlabMergeRequest[].class); } - public List getMergeRequests(Serializable projectId) throws IOException { + public List getMergeRequests(Serializable projectId) { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabMergeRequest.URL + PARAM_MAX_ITEMS_PER_PAGE; return retrieve().getAll(tailUrl, GitlabMergeRequest[].class); } - public List getMergeRequests(Serializable projectId, Pagination pagination) throws IOException { + public List getMergeRequests(Serializable projectId, Pagination pagination) { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabMergeRequest.URL + pagination.toString(); return retrieve().getAll(tailUrl, GitlabMergeRequest[].class); } - public List getMergeRequests(GitlabProject project) throws IOException { + public List getMergeRequests(GitlabProject project) { String tailUrl = GitlabProject.URL + "/" + project.getId() + GitlabMergeRequest.URL + PARAM_MAX_ITEMS_PER_PAGE; return retrieve().getAll(tailUrl, GitlabMergeRequest[].class); } - public List getMergeRequests(GitlabProject project, Pagination pagination) throws IOException { + public List getMergeRequests(GitlabProject project, Pagination pagination) { String tailUrl = GitlabProject.URL + "/" + project.getId() + GitlabMergeRequest.URL + pagination.toString(); return retrieve().getAll(tailUrl, GitlabMergeRequest[].class); } - public List getAllMergeRequests(GitlabProject project) throws IOException { + public List getAllMergeRequests(GitlabProject project) { String tailUrl = GitlabProject.URL + "/" + project.getId() + GitlabMergeRequest.URL; return retrieve().getAll(tailUrl, GitlabMergeRequest[].class); } @@ -1595,7 +1598,7 @@ public List getNotes(GitlabMergeRequest mergeRequest) throws IOExcep return Arrays.asList(notes); } - public List getAllNotes(GitlabMergeRequest mergeRequest) throws IOException { + public List getAllNotes(GitlabMergeRequest mergeRequest) { String tailUrl = GitlabProject.URL + "/" + mergeRequest.getProjectId() + GitlabMergeRequest.URL + "/" + mergeRequest.getIid() + GitlabNote.URL + PARAM_MAX_ITEMS_PER_PAGE; @@ -1941,12 +1944,12 @@ public void deleteNote(GitlabMergeRequest mergeRequest, GitlabNote noteToDelete) retrieve().method("DELETE").to(tailUrl, GitlabNote.class); } - public List getBranches(Serializable projectId) throws IOException { + public List getBranches(Serializable projectId) { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBranch.URL + PARAM_MAX_ITEMS_PER_PAGE; return retrieve().getAll(tailUrl, GitlabBranch[].class); } - public List getBranches(GitlabProject project) throws IOException { + public List getBranches(GitlabProject project) { String tailUrl = GitlabProject.URL + "/" + project.getId() + GitlabBranch.URL + PARAM_MAX_ITEMS_PER_PAGE; return retrieve().getAll(tailUrl, GitlabBranch[].class); } @@ -2086,23 +2089,23 @@ public void deleteProjectHook(GitlabProject project, String hookId) throws IOExc retrieve().method("DELETE").to(tailUrl, Void.class); } - public List getIssues(GitlabProject project) throws IOException { + public List getIssues(GitlabProject project) { return getIssues(project.getId()); } - public List getIssues(Serializable projectId) throws IOException { + public List getIssues(Serializable projectId) { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabIssue.URL + PARAM_MAX_ITEMS_PER_PAGE; return retrieve().getAll(tailUrl, GitlabIssue[].class); } - public List getIssues(GitlabProject project, GitlabMilestone milestone) throws IOException { + public List getIssues(GitlabProject project, GitlabMilestone milestone) { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(project.getId()) + GitlabMilestone.URL + "/" + sanitizeMilestoneId(milestone.getId()) + GitlabIssue.URL + PARAM_MAX_ITEMS_PER_PAGE; return retrieve().getAll(tailUrl, GitlabIssue[].class); } - public List getIssues(GitlabGroup group, GitlabMilestone milestone) throws IOException { + public List getIssues(GitlabGroup group, GitlabMilestone milestone) { String tailUrl = GitlabGroup.URL + "/" + sanitizeGroupId(group.getId()) + GitlabMilestone.URL + "/" + sanitizeMilestoneId(milestone.getId()) + GitlabIssue.URL + PARAM_MAX_ITEMS_PER_PAGE; @@ -2807,9 +2810,8 @@ public List getCommitComments(Integer projectId, String sha) thro * * @param projectId * @return - * @throws IOException on gitlab api call error */ - public List getTags(Serializable projectId) throws IOException { + public List getTags(Serializable projectId) { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabTag.URL + PARAM_MAX_ITEMS_PER_PAGE; return retrieve().getAll(tailUrl, GitlabTag[].class); } @@ -2819,9 +2821,8 @@ public List getTags(Serializable projectId) throws IOException { * * @param project * @return - * @throws IOException on gitlab api call error */ - public List getTags(GitlabProject project) throws IOException { + public List getTags(GitlabProject project) { String tailUrl = GitlabProject.URL + "/" + project.getId() + GitlabTag.URL + PARAM_MAX_ITEMS_PER_PAGE; return retrieve().getAll(tailUrl, GitlabTag[].class); } @@ -2896,9 +2897,8 @@ public void deleteTag(GitlabProject project, String tagName) throws IOException * Get all awards for a merge request * * @param mergeRequest - * @throws IOException on gitlab api call error */ - public List getAllAwards(GitlabMergeRequest mergeRequest) throws IOException { + public List getAllAwards(GitlabMergeRequest mergeRequest) { String tailUrl = GitlabProject.URL + "/" + mergeRequest.getProjectId() + GitlabMergeRequest.URL + "/" + mergeRequest.getIid() + GitlabAward.URL + PARAM_MAX_ITEMS_PER_PAGE; @@ -2952,9 +2952,8 @@ public void deleteAward(GitlabMergeRequest mergeRequest, GitlabAward award) thro * Get all awards for an issue * * @param issue - * @throws IOException on gitlab api call error */ - public List getAllAwards(GitlabIssue issue) throws IOException { + public List getAllAwards(GitlabIssue issue) { String tailUrl = GitlabProject.URL + "/" + issue.getProjectId() + GitlabIssue.URL + "/" + issue.getId() + GitlabAward.URL + PARAM_MAX_ITEMS_PER_PAGE; @@ -3008,9 +3007,8 @@ public void deleteAward(GitlabIssue issue, GitlabAward award) throws IOException * * @param issue * @param noteId - * @throws IOException on gitlab api call error */ - public List getAllAwards(GitlabIssue issue, Integer noteId) throws IOException { + public List getAllAwards(GitlabIssue issue, Integer noteId) { String tailUrl = GitlabProject.URL + "/" + issue.getProjectId() + GitlabIssue.URL + "/" + issue.getId() + GitlabNote.URL + noteId + GitlabAward.URL + PARAM_MAX_ITEMS_PER_PAGE; @@ -3207,9 +3205,8 @@ public GitlabBuildVariable updateBuildVariable(Integer projectId, * @param project the project * @return list of build triggers * @throws IllegalStateException if jobs are not enabled for the project - * @throws IOException */ - public List getPipelineTriggers(GitlabProject project) throws IOException { + public List getPipelineTriggers(GitlabProject project) { if (!project.isJobsEnabled()) { // if the project has not allowed jobs, you will only get a 403 forbidden message which is // not helpful. @@ -3239,8 +3236,6 @@ public GitlabServiceEmailOnPush getEmailsOnPush(Integer projectId) throws IOExce * @throws IOException */ public boolean updateEmailsOnPush(Integer projectId, String emailAddress) throws IOException { - String tailUrl = GitlabProject.URL + "/" + projectId + GitlabServiceEmailOnPush.URL; - GitlabServiceEmailOnPush emailOnPush = this.getEmailsOnPush(projectId); GitlabEmailonPushProperties properties = emailOnPush.getProperties(); String appendedRecipients = properties.getRecipients(); @@ -3255,7 +3250,7 @@ public boolean updateEmailsOnPush(Integer projectId, String emailAddress) throws .appendIf("active", true) .appendIf("recipients", appendedRecipients); - tailUrl = GitlabProject.URL + "/" + projectId + GitlabServiceEmailOnPush.URL + query.toString(); + String tailUrl = GitlabProject.URL + "/" + projectId + GitlabServiceEmailOnPush.URL + query.toString(); return retrieve().method("PUT").to(tailUrl, Boolean.class); } diff --git a/src/main/java/org/gitlab/api/http/GitlabHTTPRequestor.java b/src/main/java/org/gitlab/api/http/GitlabHTTPRequestor.java index e12dc6c6..7ca8372e 100644 --- a/src/main/java/org/gitlab/api/http/GitlabHTTPRequestor.java +++ b/src/main/java/org/gitlab/api/http/GitlabHTTPRequestor.java @@ -360,6 +360,11 @@ private HttpURLConnection setupConnection(URL url) throws IOException { connection.setReadTimeout(requestTimeout); } + final int connectionTimeout = root.getConnectionTimeout(); + if (connectionTimeout > 0) { + connection.setConnectTimeout(connectionTimeout); + } + try { connection.setRequestMethod(method); } catch (ProtocolException e) { @@ -421,6 +426,9 @@ private void handleAPIError(IOException e, HttpURLConnection connection) throws if (e instanceof SocketTimeoutException && root.getRequestTimeout() > 0) { throw e; } + if (e instanceof ConnectException && root.getConnectionTimeout() > 0) { + throw e; + } InputStream es = wrapStream(connection, connection.getErrorStream()); try { From cf8e869da1a3b18db5ac1ee662539440ab1a287a Mon Sep 17 00:00:00 2001 From: "oleg.shaburov" Date: Thu, 3 May 2018 21:31:55 +0300 Subject: [PATCH 2/3] add unit tests + jupiter + logging + refactoring + fix smells & corrupted tests --- build.gradle | 23 +- src/main/java/org/gitlab/api/GitlabAPI.java | 230 ++++++++++-------- .../gitlab/api/http/GitlabHTTPRequestor.java | 122 ++++------ src/main/java/org/gitlab/api/http/Method.java | 11 + src/test/java/org/gitlab/api/GitlabAPIIT.java | 86 +++---- src/test/java/org/gitlab/api/GitlabAPIUT.java | 93 +++++++ .../api/http/GitlabHTTPRequestorTest.java | 106 +++++++- src/test/resources/log4j2.xml | 16 ++ 8 files changed, 449 insertions(+), 238 deletions(-) create mode 100644 src/main/java/org/gitlab/api/http/Method.java create mode 100644 src/test/java/org/gitlab/api/GitlabAPIUT.java create mode 100644 src/test/resources/log4j2.xml diff --git a/build.gradle b/build.gradle index 1469b1a8..4d0ab7e8 100644 --- a/build.gradle +++ b/build.gradle @@ -23,10 +23,18 @@ repositories { } dependencies { - compile(group: "com.fasterxml.jackson.core", name: "jackson-databind", version: "2.5.+") - compile(group: "commons-io", name: "commons-io", version: "2.4") - testCompile(group: "org.hamcrest", name: "hamcrest-all", version: "1.3") - testCompile(group: "junit", name: "junit", version: "4.12") + compile(group: 'org.slf4j', name: 'slf4j-api', version: '1.8.0-beta2') + compile(group: "com.fasterxml.jackson.core", name: "jackson-databind", version: "2.5.+") + compile(group: "commons-io", name: "commons-io", version: "2.4") + testCompile(group: "org.hamcrest", name: "hamcrest-all", version: "1.3") + testCompile(group: 'org.mockito', name: 'mockito-core', version: '2.18.3') + testCompile(group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.11.0') + testCompile(group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: '2.11.0') + testCompile(group: 'com.github.tomakehurst', name: 'wiremock-standalone', version: '2.17.0') + testCompile(group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.2.0') + testRuntime(group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: '5.2.0') + testCompile(group: "junit", name: "junit", version: "4.12") + testRuntime(group: 'org.junit.vintage', name: 'junit-vintage-engine', version: '5.2.0') } jar { @@ -51,3 +59,10 @@ artifacts { archives sourcesJar } task wrapper(type: Wrapper) { gradleVersion = "4.6" } + +test { + useJUnitPlatform { + includeEngines 'junit-jupiter' + includeEngines 'junit-vintage' + } +} \ No newline at end of file diff --git a/src/main/java/org/gitlab/api/GitlabAPI.java b/src/main/java/org/gitlab/api/GitlabAPI.java index 9a1da032..bae26fab 100644 --- a/src/main/java/org/gitlab/api/GitlabAPI.java +++ b/src/main/java/org/gitlab/api/GitlabAPI.java @@ -5,6 +5,8 @@ import org.gitlab.api.http.GitlabHTTPRequestor; import org.gitlab.api.http.Query; import org.gitlab.api.models.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; @@ -19,15 +21,18 @@ import java.util.Date; import java.util.List; +import static org.gitlab.api.http.Method.*; /** * Gitlab API Wrapper class * * @author @timols (Tim O) */ -@SuppressWarnings("unused") +@SuppressWarnings({"unused", "WeakerAccess"}) public class GitlabAPI { + private static final Logger LOG = LoggerFactory.getLogger(GitlabAPI.class); + public static final ObjectMapper MAPPER = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); private static final String API_NAMESPACE = "/api/v4"; @@ -41,8 +46,9 @@ public class GitlabAPI { private AuthMethod authMethod; private boolean ignoreCertificateErrors = false; private Proxy proxy; - private int requestTimeout = 0; - private int connectionTimeout = 0; + private int defaultTimeout = 0; + private int readTimeout = defaultTimeout; + private int connectionTimeout = defaultTimeout; private String userAgent = GitlabAPI.class.getCanonicalName() + "/" + System.getProperty("java.version"); private GitlabAPI(String hostUrl, String apiToken, TokenType tokenType, AuthMethod method) { @@ -81,12 +87,35 @@ public GitlabAPI proxy(Proxy proxy) { return this; } + public int getResponseReadTimeout() { + return readTimeout; + } + + /** + * @deprecated use this.getResponseReadTimeout() method + */ + @Deprecated public int getRequestTimeout() { - return requestTimeout; + return getResponseReadTimeout(); + } + + /** + * @deprecated use this.setResponseReadTimeout(int readTimeout) method + */ + @Deprecated + public GitlabAPI setRequestTimeout(int readTimeout) { + setResponseReadTimeout(readTimeout); + return this; } - public GitlabAPI setRequestTimeout(int requestTimeout) { - this.requestTimeout = requestTimeout; + public GitlabAPI setResponseReadTimeout(int readTimeout) { + if (readTimeout < 0) { + LOG.warn("The value of the \"Response Read Timeout\" parameter can not be negative. " + + "The default value [{}] will be used.", defaultTimeout); + this.readTimeout = defaultTimeout; + } else { + this.readTimeout = readTimeout; + } return this; } @@ -95,7 +124,13 @@ public int getConnectionTimeout() { } public GitlabAPI setConnectionTimeout(int connectionTimeout) { - this.connectionTimeout = connectionTimeout; + if (connectionTimeout < 0) { + LOG.warn("The value of the \"Connection Timeout\" parameter can not be negative. " + + "The default value [{}] will be used.", defaultTimeout); + this.connectionTimeout = defaultTimeout; + } else { + this.connectionTimeout = connectionTimeout; + } return this; } @@ -104,7 +139,7 @@ public GitlabHTTPRequestor retrieve() { } public GitlabHTTPRequestor dispatch() { - return new GitlabHTTPRequestor(this).authenticate(apiToken, tokenType, authMethod).method("POST"); + return new GitlabHTTPRequestor(this).authenticate(apiToken, tokenType, authMethod).method(POST); } public boolean isIgnoreCertificateErrors() { @@ -145,7 +180,7 @@ public List getUsers() { * @param emailOrUsername Some portion of the email address or username * @return A non-null List of GitlabUser instances. If the search term is * null or empty a List with zero GitlabUsers is returned. - * @throws IOException + * @throws IOException on gitlab api call error */ public List findUsers(String emailOrUsername) throws IOException { List users = new ArrayList<>(); @@ -289,7 +324,7 @@ public GitlabUser updateUser(Integer targetUserId, String tailUrl = GitlabUser.USERS_URL + "/" + targetUserId + query.toString(); - return retrieve().method("PUT").to(tailUrl, GitlabUser.class); + return retrieve().method(PUT).to(tailUrl, GitlabUser.class); } /** @@ -302,7 +337,7 @@ public void blockUser(Integer targetUserId) throws IOException { String tailUrl = GitlabUser.USERS_URL + "/" + targetUserId + GitlabUser.BLOCK_URL; - retrieve().method("POST").to(tailUrl, Void.class); + retrieve().method(POST).to(tailUrl, Void.class); } /** @@ -315,7 +350,7 @@ public void unblockUser(Integer targetUserId) throws IOException { String tailUrl = GitlabUser.USERS_URL + "/" + targetUserId + GitlabUser.UNBLOCK_URL; - retrieve().method("POST").to(tailUrl, Void.class); + retrieve().method(POST).to(tailUrl, Void.class); } /** @@ -366,7 +401,7 @@ public GitlabSSHKey createSSHKey(String title, String key) throws IOException { */ public void deleteSSHKey(Integer targetUserId, Integer targetKeyId) throws IOException { String tailUrl = GitlabUser.USERS_URL + "/" + targetUserId + GitlabSSHKey.KEYS_URL + "/" + targetKeyId; - retrieve().method("DELETE").to(tailUrl, Void.class); + retrieve().method(DELETE).to(tailUrl, Void.class); } @@ -402,7 +437,7 @@ public GitlabSSHKey getSSHKey(Integer keyId) throws IOException { */ public void deleteUser(Integer targetUserId) throws IOException { String tailUrl = GitlabUser.USERS_URL + "/" + targetUserId; - retrieve().method("DELETE").to(tailUrl, Void.class); + retrieve().method(DELETE).to(tailUrl, Void.class); } public GitlabGroup getGroup(Integer groupId) throws IOException { @@ -413,8 +448,9 @@ public GitlabGroup getGroup(Integer groupId) throws IOException { * Get a group by path * * @param path Path of the group - * @return - * @throws IOException + * @return {@link GitlabGroup} object + * + * @throws IOException on gitlab api call error */ public GitlabGroup getGroup(String path) throws IOException { String tailUrl = GitlabGroup.URL + "/" + URLEncoder.encode(path, "UTF-8"); @@ -648,7 +684,7 @@ public GitlabGroup updateGroup(GitlabGroup group, GitlabUser sudoUser) throws IO String tailUrl = GitlabGroup.URL + "/" + group.getId() + query.toString(); - return retrieve().method("PUT").to(tailUrl, GitlabGroup.class); + return retrieve().method(PUT).to(tailUrl, GitlabGroup.class); } /** @@ -702,7 +738,7 @@ public void deleteGroupMember(GitlabGroup group, GitlabUser user) throws IOExcep */ public void deleteGroupMember(Integer groupId, Integer userId) throws IOException { String tailUrl = GitlabGroup.URL + "/" + groupId + "/" + GitlabGroupMember.URL + "/" + userId; - retrieve().method("DELETE").to(tailUrl, Void.class); + retrieve().method(DELETE).to(tailUrl, Void.class); } /** @@ -713,7 +749,7 @@ public void deleteGroupMember(Integer groupId, Integer userId) throws IOExceptio */ public void deleteGroup(Integer groupId) throws IOException { String tailUrl = GitlabGroup.URL + "/" + groupId; - retrieve().method("DELETE").to(tailUrl, Void.class); + retrieve().method(DELETE).to(tailUrl, Void.class); } /** @@ -729,9 +765,9 @@ public List getAllProjects() { /** * Get Project by project Id * - * @param projectId - * @return - * @throws IOException + * @param projectId - gitlab project Id + * @return {@link GitlabProject} + * @throws IOException on gitlab api call error */ public GitlabProject getProject(Serializable projectId) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId); @@ -792,7 +828,7 @@ public List getProjectsWithPagination(int page, int perPage) thro * * @param pagination * @return - * @throws IOException + * @throws IOException on gitlab api call error */ public List getProjectsWithPagination(Pagination pagination) throws IOException { StringBuilder tailUrl = new StringBuilder(GitlabProject.URL); @@ -802,14 +838,14 @@ public List getProjectsWithPagination(Pagination pagination) thro tailUrl.append(query.toString()); } - return Arrays.asList(retrieve().method("GET").to(tailUrl.toString(), GitlabProject[].class)); + return Arrays.asList(retrieve().method(GET).to(tailUrl.toString(), GitlabProject[].class)); } /** * Get a list of projects owned by the authenticated user. * * @return A list of gitlab projects - * @throws IOException + * @throws IOException on gitlab api call error */ public List getOwnedProjects() throws IOException { Query query = new Query().append("owner", "true"); @@ -822,7 +858,7 @@ public List getOwnedProjects() throws IOException { * Get a list of projects that the authenticated user is a member of. * * @return A list of gitlab projects - * @throws IOException + * @throws IOException on gitlab api call error */ public List getMembershipProjects() throws IOException { Query query = new Query().append("membership", "true"); @@ -835,7 +871,7 @@ public List getMembershipProjects() throws IOException { * Get a list of projects starred by the authenticated user. * * @return A list of gitlab projects - * @throws IOException + * @throws IOException on gitlab api call error */ public List getStarredProjects() throws IOException { Query query = new Query().append("starred", "true"); @@ -848,7 +884,7 @@ public List getStarredProjects() throws IOException { * Get a list of projects accessible by the authenticated user. * * @return A list of gitlab projects - * @throws IOException + * @throws IOException on gitlab api call error */ public List getProjectsViaSudo(GitlabUser user) throws IOException { Query query = new Query() @@ -893,7 +929,7 @@ public List getProjectsViaSudoWithPagination(GitlabUser user, Pag } tailUrl.append(query.toString()); - return Arrays.asList(retrieve().method("GET").to(tailUrl.toString(), GitlabProject[].class)); + return Arrays.asList(retrieve().method(GET).to(tailUrl.toString(), GitlabProject[].class)); } /** @@ -913,7 +949,7 @@ public List getNamespaces() { * @param project * @param file * @return - * @throws IOException + * @throws IOException on gitlab api call error */ public GitlabUpload uploadFile(GitlabProject project, File file) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(project.getId()) + GitlabUpload.URL; @@ -972,7 +1008,7 @@ public List getPipelineJobs(Integer projectId, Integer pipelineId) { * @param projectId * @param jobId * @return - * @throws IOException + * @throws IOException on gitlab api call error */ public GitlabJob cancelJob(Integer projectId, Integer jobId) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabJob.URL + "/" + sanitizeId(jobId, "JobID") + "/cancel"; @@ -985,7 +1021,7 @@ public GitlabJob cancelJob(Integer projectId, Integer jobId) throws IOException * @param projectId * @param jobId * @return - * @throws IOException + * @throws IOException on gitlab api call error */ public GitlabJob retryJob(Integer projectId, Integer jobId) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabJob.URL + "/" + sanitizeId(jobId, "JobID") + "/retry"; @@ -998,7 +1034,7 @@ public GitlabJob retryJob(Integer projectId, Integer jobId) throws IOException { * @param projectId * @param jobId * @return - * @throws IOException + * @throws IOException on gitlab api call error */ public GitlabJob eraseJob(Integer projectId, Integer jobId) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabJob.URL + "/" + sanitizeId(jobId, "JobID") + "/erase"; @@ -1012,7 +1048,7 @@ public GitlabJob eraseJob(Integer projectId, Integer jobId) throws IOException { * @param projectId * @param jobId * @return - * @throws IOException + * @throws IOException on gitlab api call error */ public GitlabJob playJob(Integer projectId, Integer jobId) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabJob.URL + "/" + sanitizeId(jobId, "JobID") + "/play"; @@ -1026,7 +1062,7 @@ public GitlabJob playJob(Integer projectId, Integer jobId) throws IOException { * @param projectId the project id * @param jobId the build id * @return A list of project jobs - * @throws IOException + * @throws IOException on gitlab api call error */ public GitlabJob getProjectJob(Integer projectId, Integer jobId) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabJob.URL + "/" + jobId; @@ -1323,7 +1359,7 @@ public GitlabProject updateProject( String tailUrl = GitlabProject.URL + "/" + projectId + query.toString(); - return retrieve().method("PUT").to(tailUrl, GitlabProject.class); + return retrieve().method(PUT).to(tailUrl, GitlabProject.class); } /** @@ -1334,7 +1370,7 @@ public GitlabProject updateProject( */ public void deleteProject(Serializable projectId) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId); - retrieve().method("DELETE").to(tailUrl, null); + retrieve().method(DELETE).to(tailUrl, null); } public List getOpenMergeRequests(Serializable projectId) throws IOException { @@ -1549,7 +1585,7 @@ public GitlabMergeRequest updateMergeRequest(Serializable projectId, Integer mer String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabMergeRequest.URL + "/" + mergeRequestId + query.toString(); - return retrieve().method("PUT").to(tailUrl, GitlabMergeRequest.class); + return retrieve().method(PUT).to(tailUrl, GitlabMergeRequest.class); } /** @@ -1565,7 +1601,7 @@ public GitlabMergeRequest acceptMergeRequest(GitlabProject project, Integer merg public GitlabMergeRequest acceptMergeRequest(Serializable projectId, Integer mergeRequestId, String mergeCommitMessage) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabMergeRequest.URL + "/" + mergeRequestId + "/merge"; - GitlabHTTPRequestor requestor = retrieve().method("PUT"); + GitlabHTTPRequestor requestor = retrieve().method(PUT); requestor.with("id", projectId); requestor.with("merge_request_id", mergeRequestId); if (mergeCommitMessage != null) @@ -1878,7 +1914,7 @@ public GitlabSimpleRepositoryFile createRepositoryFile(GitlabProject project, St */ public GitlabSimpleRepositoryFile updateRepositoryFile(GitlabProject project, String path, String branchName, String commitMsg, String content) throws IOException { String tailUrl = GitlabProject.URL + "/" + project.getId() + "/repository/files/" + sanitizePath(path); - GitlabHTTPRequestor requestor = retrieve().method("PUT"); + GitlabHTTPRequestor requestor = retrieve().method(PUT); return requestor .with("branch", branchName) @@ -1902,7 +1938,7 @@ public void deleteRepositoryFile(GitlabProject project, String path, String bran .append("branch", branchName) .append("commit_message", commitMsg); String tailUrl = GitlabProject.URL + "/" + project.getId() + "/repository/files/" + sanitizePath(path) + query.toString(); - retrieve().method("DELETE").to(tailUrl, Void.class); + retrieve().method(DELETE).to(tailUrl, Void.class); } /** @@ -1921,7 +1957,7 @@ public GitlabNote updateNote(GitlabMergeRequest mergeRequest, Integer noteId, St String tailUrl = GitlabProject.URL + "/" + mergeRequest.getProjectId() + GitlabMergeRequest.URL + "/" + mergeRequest.getIid() + GitlabNote.URL + "/" + noteId + query.toString(); - return retrieve().method("PUT").to(tailUrl, GitlabNote.class); + return retrieve().method(PUT).to(tailUrl, GitlabNote.class); } public GitlabNote createNote(GitlabMergeRequest mergeRequest, String body) throws IOException { @@ -1941,7 +1977,7 @@ public GitlabNote createNote(GitlabMergeRequest mergeRequest, String body) throw public void deleteNote(GitlabMergeRequest mergeRequest, GitlabNote noteToDelete) throws IOException { String tailUrl = GitlabProject.URL + "/" + mergeRequest.getProjectId() + GitlabMergeRequest.URL + "/" + mergeRequest.getIid() + GitlabNote.URL + "/" + noteToDelete.getId(); - retrieve().method("DELETE").to(tailUrl, GitlabNote.class); + retrieve().method(DELETE).to(tailUrl, GitlabNote.class); } public List getBranches(Serializable projectId) { @@ -1994,7 +2030,7 @@ public void createBranch(Serializable projectId, String branchName, String ref) */ public void deleteBranch(Serializable projectId, String branchName) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBranch.URL + '/' + sanitizePath(branchName); - retrieve().method("DELETE").to(tailUrl, Void.class); + retrieve().method(DELETE).to(tailUrl, Void.class); } public GitlabBranch getBranch(Serializable projectId, String branchName) throws IOException { @@ -2015,12 +2051,12 @@ public void protectBranchWithDeveloperOptions(GitlabProject project, String bran final Query query = new Query() .append("developers_can_push", Boolean.toString(developers_can_push)) .append("developers_can_merge", Boolean.toString(developers_can_merge)); - retrieve().method("PUT").to(tailUrl + query.toString(), Void.class); + retrieve().method(PUT).to(tailUrl + query.toString(), Void.class); } public void unprotectBranch(GitlabProject project, String branchName) throws IOException { String tailUrl = GitlabProject.URL + "/" + project.getId() + GitlabBranch.URL + '/' + sanitizePath(branchName) + "/unprotect"; - retrieve().method("PUT").to(tailUrl, Void.class); + retrieve().method(PUT).to(tailUrl, Void.class); } public List getProjectHooks(Serializable projectId) throws IOException { @@ -2076,17 +2112,17 @@ public GitlabProjectHook editProjectHook(GitlabProject project, String hookId, S .append("url", url); String tailUrl = GitlabProject.URL + "/" + project.getId() + GitlabProjectHook.URL + "/" + hookId + query.toString(); - return retrieve().method("PUT").to(tailUrl, GitlabProjectHook.class); + return retrieve().method(PUT).to(tailUrl, GitlabProjectHook.class); } public void deleteProjectHook(GitlabProjectHook hook) throws IOException { String tailUrl = GitlabProject.URL + "/" + hook.getProjectId() + GitlabProjectHook.URL + "/" + hook.getId(); - retrieve().method("DELETE").to(tailUrl, Void.class); + retrieve().method(DELETE).to(tailUrl, Void.class); } public void deleteProjectHook(GitlabProject project, String hookId) throws IOException { String tailUrl = GitlabProject.URL + "/" + project.getId() + GitlabProjectHook.URL + "/" + hookId; - retrieve().method("DELETE").to(tailUrl, Void.class); + retrieve().method(DELETE).to(tailUrl, Void.class); } public List getIssues(GitlabProject project) { @@ -2141,7 +2177,7 @@ public GitlabIssue moveIssue(Integer projectId, Integer issueId, Integer toProje public GitlabIssue editIssue(int projectId, int issueId, int assigneeId, int milestoneId, String labels, String description, String title, GitlabIssue.Action action) throws IOException { String tailUrl = GitlabProject.URL + "/" + projectId + GitlabIssue.URL + "/" + issueId; - GitlabHTTPRequestor requestor = retrieve().method("PUT"); + GitlabHTTPRequestor requestor = retrieve().method(PUT); applyIssue(requestor, projectId, assigneeId, milestoneId, labels, description, title); if (action != GitlabIssue.Action.LEAVE) { @@ -2200,7 +2236,7 @@ public void deleteNote(Serializable projectId, Integer issueId, GitlabNote noteT String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabIssue.URL + "/" + issueId + GitlabNote.URL + "/" + noteToDelete.getId(); - retrieve().method("DELETE").to(tailUrl, GitlabNote.class); + retrieve().method(DELETE).to(tailUrl, GitlabNote.class); } /** @@ -2219,7 +2255,7 @@ public void deleteNote(GitlabIssue issue, GitlabNote noteToDelete) throws IOExce * * @param projectId The ID of the project. * @return A non-null list of labels. - * @throws IOException + * @throws IOException on gitlab api call error */ public List getLabels(Serializable projectId) throws IOException { @@ -2233,7 +2269,7 @@ public List getLabels(Serializable projectId) * * @param project The project associated with labels. * @return A non-null list of labels. - * @throws IOException + * @throws IOException on gitlab api call error */ public List getLabels(GitlabProject project) throws IOException { @@ -2247,7 +2283,7 @@ public List getLabels(GitlabProject project) * @param name The name of the label. * @param color The color of the label (eg #ff0000). * @return The newly created label. - * @throws IOException + * @throws IOException on gitlab api call error */ public GitlabLabel createLabel( Serializable projectId, @@ -2278,7 +2314,7 @@ public GitlabLabel createLabel(Serializable projectId, GitlabLabel label) * * @param projectId The ID of the project containing the label. * @param name The name of the label to delete. - * @throws IOException + * @throws IOException on gitlab api call error */ public void deleteLabel(Serializable projectId, String name) throws IOException { @@ -2288,7 +2324,7 @@ public void deleteLabel(Serializable projectId, String name) sanitizeProjectId(projectId) + GitlabLabel.URL + query.toString(); - retrieve().method("DELETE").to(tailUrl, Void.class); + retrieve().method(DELETE).to(tailUrl, Void.class); } /** @@ -2296,7 +2332,7 @@ public void deleteLabel(Serializable projectId, String name) * * @param projectId The ID of the project containing the label. * @param label The label to delete. - * @throws IOException + * @throws IOException on gitlab api call error */ public void deleteLabel(Serializable projectId, GitlabLabel label) throws IOException { @@ -2311,14 +2347,14 @@ public void deleteLabel(Serializable projectId, GitlabLabel label) * @param newName The updated name. * @param newColor The updated color. * @return The updated, deserialized label. - * @throws IOException + * @throws IOException on gitlab api call error */ public GitlabLabel updateLabel(Serializable projectId, String name, String newName, String newColor) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabLabel.URL; - GitlabHTTPRequestor requestor = retrieve().method("PUT"); + GitlabHTTPRequestor requestor = retrieve().method(PUT); requestor.with("name", name); if (newName != null) { requestor.with("new_name", newName); @@ -2356,7 +2392,7 @@ public List getGroupMilestones(Serializable groupId) throws IOE * @param dueDate The date the milestone is due. (Optional) * @param startDate The start date of the milestone. (Optional) * @return The newly created, de-serialized milestone. - * @throws IOException + * @throws IOException on gitlab api call error */ public GitlabMilestone createMilestone( Serializable projectId, @@ -2385,7 +2421,7 @@ public GitlabMilestone createMilestone( * @param projectId The ID of the project. * @param milestone The milestone to create. * @return The newly created, de-serialized milestone. - * @throws IOException + * @throws IOException on gitlab api call error */ public GitlabMilestone createMilestone( Serializable projectId, @@ -2409,7 +2445,7 @@ public GitlabMilestone createMilestone( * @param stateEvent A value used to update the state of the milestone. * (Optional) (activate | close) * @return The updated, de-serialized milestone. - * @throws IOException + * @throws IOException on gitlab api call error */ public GitlabMilestone updateMilestone( Serializable projectId, @@ -2423,7 +2459,7 @@ public GitlabMilestone updateMilestone( sanitizeProjectId(projectId) + GitlabMilestone.URL + "/" + milestoneId; - GitlabHTTPRequestor requestor = retrieve().method("PUT"); + GitlabHTTPRequestor requestor = retrieve().method(PUT); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); if (title != null) { requestor.with("title", title); @@ -2451,7 +2487,7 @@ public GitlabMilestone updateMilestone( * @param stateEvent A value used to update the state of the milestone. * (Optional) (activate | close) * @return The updated, de-serialized milestone. - * @throws IOException + * @throws IOException on gitlab api call error */ public GitlabMilestone updateMilestone( Serializable projectId, @@ -2473,7 +2509,7 @@ public GitlabMilestone updateMilestone( * @param stateEvent A value used to update the state of the milestone. * (Optional) (activate | close) * @return The updated, de-serialized milestone. - * @throws IOException + * @throws IOException on gitlab api call error */ public GitlabMilestone updateMilestone( GitlabMilestone edited, @@ -2533,7 +2569,7 @@ public void deleteProjectMember(GitlabProject project, GitlabUser user) throws I */ public void deleteProjectMember(Integer projectId, Integer userId) throws IOException { String tailUrl = GitlabProject.URL + "/" + projectId + "/" + GitlabProjectMember.URL + "/" + userId; - retrieve().method("DELETE").to(tailUrl, Void.class); + retrieve().method(DELETE).to(tailUrl, Void.class); } /** @@ -2564,7 +2600,7 @@ public GitlabProjectMember updateProjectMember(Integer projectId, Integer userId .appendIf("access_level", accessLevel) .appendIf("expires_at", expiresAt); String tailUrl = GitlabProject.URL + "/" + projectId + GitlabProjectMember.URL + "/" + userId + query.toString(); - return retrieve().method("PUT").to(tailUrl, GitlabProjectMember.class); + return retrieve().method(PUT).to(tailUrl, GitlabProjectMember.class); } @@ -2667,7 +2703,7 @@ private GitlabSSHKey createDeployKey(Integer targetProjectId, String title, Stri */ public void deleteDeployKey(Integer targetProjectId, Integer targetKeyId) throws IOException { String tailUrl = GitlabProject.URL + "/" + targetProjectId + GitlabSSHKey.DEPLOY_KEYS_URL + "/" + targetKeyId; - retrieve().method("DELETE").to(tailUrl, Void.class); + retrieve().method(DELETE).to(tailUrl, Void.class); } /** @@ -2726,7 +2762,7 @@ public void testSystemHook(Integer hookId) throws IOException { */ public GitlabSystemHook deleteSystemHook(Integer hookId) throws IOException { String tailUrl = GitlabSystemHook.URL + "/" + hookId; - return retrieve().method("DELETE").to(tailUrl, GitlabSystemHook.class); + return retrieve().method(DELETE).to(tailUrl, GitlabSystemHook.class); } private String sanitizeProjectId(Serializable projectId) { @@ -2878,7 +2914,7 @@ public GitlabTag addTag(GitlabProject project, String tagName, String ref, Strin */ public void deleteTag(Serializable projectId, String tagName) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabTag.URL + "/" + tagName; - retrieve().method("DELETE").to(tailUrl, Void.class); + retrieve().method(DELETE).to(tailUrl, Void.class); } /** @@ -2890,7 +2926,7 @@ public void deleteTag(Serializable projectId, String tagName) throws IOException */ public void deleteTag(GitlabProject project, String tagName) throws IOException { String tailUrl = GitlabProject.URL + "/" + project + GitlabTag.URL + "/" + tagName; - retrieve().method("DELETE").to(tailUrl, Void.class); + retrieve().method(DELETE).to(tailUrl, Void.class); } /** @@ -2945,7 +2981,7 @@ public void deleteAward(GitlabMergeRequest mergeRequest, GitlabAward award) thro String tailUrl = GitlabProject.URL + "/" + mergeRequest.getProjectId() + GitlabMergeRequest.URL + "/" + mergeRequest.getIid() + GitlabAward.URL + "/" + award.getId(); - retrieve().method("DELETE").to(tailUrl, Void.class); + retrieve().method(DELETE).to(tailUrl, Void.class); } /** @@ -2999,7 +3035,7 @@ public GitlabAward createAward(GitlabIssue issue, String awardName) throws IOExc public void deleteAward(GitlabIssue issue, GitlabAward award) throws IOException { String tailUrl = GitlabProject.URL + "/" + issue.getProjectId() + GitlabIssue.URL + "/" + issue.getId() + GitlabAward.URL + "/" + award.getId(); - retrieve().method("DELETE").to(tailUrl, Void.class); + retrieve().method(DELETE).to(tailUrl, Void.class); } /** @@ -3057,7 +3093,7 @@ public GitlabAward createAward(GitlabIssue issue, Integer noteId, String awardNa public void deleteAward(GitlabIssue issue, Integer noteId, GitlabAward award) throws IOException { String tailUrl = GitlabProject.URL + "/" + issue.getProjectId() + GitlabIssue.URL + "/" + issue.getId() + GitlabNote.URL + noteId + GitlabAward.URL + "/" + award.getId(); - retrieve().method("DELETE").to(tailUrl, Void.class); + retrieve().method(DELETE).to(tailUrl, Void.class); } /** @@ -3065,7 +3101,7 @@ public void deleteAward(GitlabIssue issue, Integer noteId, GitlabAward award) th * * @param projectId The ID of the project. * @return A non-null list of variables. - * @throws IOException + * @throws IOException on gitlab api call error */ public List getBuildVariables(Integer projectId) throws IOException { @@ -3079,7 +3115,7 @@ public List getBuildVariables(Integer projectId) * * @param project The project associated with variables. * @return A non-null list of variables. - * @throws IOException + * @throws IOException on gitlab api call error */ public List getBuildVariables(GitlabProject project) throws IOException { @@ -3092,7 +3128,7 @@ public List getBuildVariables(GitlabProject project) * @param projectId The ID of the project. * @param key The key of the variable. * @return A variable. - * @throws IOException + * @throws IOException on gitlab api call error */ public GitlabBuildVariable getBuildVariable(Integer projectId, String key) throws IOException { @@ -3108,7 +3144,7 @@ public GitlabBuildVariable getBuildVariable(Integer projectId, String key) * * @param project The project associated with the variable. * @return A variable. - * @throws IOException + * @throws IOException on gitlab api call error */ public GitlabBuildVariable getBuildVariable(GitlabProject project, String key) throws IOException { @@ -3122,7 +3158,7 @@ public GitlabBuildVariable getBuildVariable(GitlabProject project, String key) * @param key The key of the variable. * @param value The value of the variable * @return The newly created variable. - * @throws IOException + * @throws IOException on gitlab api call error */ public GitlabBuildVariable createBuildVariable( Integer projectId, @@ -3153,7 +3189,7 @@ public GitlabBuildVariable createBuildVariable(Integer projectId, GitlabBuildVar * * @param projectId The ID of the project containing the variable. * @param key The key of the variable to delete. - * @throws IOException + * @throws IOException on gitlab api call error */ public void deleteBuildVariable(Integer projectId, String key) throws IOException { @@ -3161,7 +3197,7 @@ public void deleteBuildVariable(Integer projectId, String key) projectId + GitlabBuildVariable.URL + "/" + key; - retrieve().method("DELETE").to(tailUrl, Void.class); + retrieve().method(DELETE).to(tailUrl, Void.class); } /** @@ -3169,7 +3205,7 @@ public void deleteBuildVariable(Integer projectId, String key) * * @param projectId The ID of the project containing the variable. * @param variable The variable to delete. - * @throws IOException + * @throws IOException on gitlab api call error */ public void deleteBuildVariable(Integer projectId, GitlabBuildVariable variable) throws IOException { @@ -3183,7 +3219,7 @@ public void deleteBuildVariable(Integer projectId, GitlabBuildVariable variable) * @param key The key of the variable to update. * @param newValue The updated value. * @return The updated, deserialized variable. - * @throws IOException + * @throws IOException on gitlab api call error */ public GitlabBuildVariable updateBuildVariable(Integer projectId, String key, @@ -3192,7 +3228,7 @@ public GitlabBuildVariable updateBuildVariable(Integer projectId, projectId + GitlabBuildVariable.URL + "/" + key; - GitlabHTTPRequestor requestor = retrieve().method("PUT"); + GitlabHTTPRequestor requestor = retrieve().method(PUT); if (newValue != null) { requestor = requestor.with("value", newValue); } @@ -3220,7 +3256,7 @@ public List getPipelineTriggers(GitlabProject project) { * Gets email-on-push service setup for a projectId. * * @param projectId The ID of the project containing the variable. - * @throws IOException + * @throws IOException on gitlab api call error */ public GitlabServiceEmailOnPush getEmailsOnPush(Integer projectId) throws IOException { String tailUrl = GitlabProject.URL + "/" + projectId + GitlabServiceEmailOnPush.URL; @@ -3233,7 +3269,7 @@ public GitlabServiceEmailOnPush getEmailsOnPush(Integer projectId) throws IOExce * @param projectId The ID of the project containing the variable. * @param emailAddress The emailaddress of the recipent who is going to receive push notification. * @return - * @throws IOException + * @throws IOException on gitlab api call error */ public boolean updateEmailsOnPush(Integer projectId, String emailAddress) throws IOException { GitlabServiceEmailOnPush emailOnPush = this.getEmailsOnPush(projectId); @@ -3251,7 +3287,7 @@ public boolean updateEmailsOnPush(Integer projectId, String emailAddress) throws .appendIf("recipients", appendedRecipients); String tailUrl = GitlabProject.URL + "/" + projectId + GitlabServiceEmailOnPush.URL + query.toString(); - return retrieve().method("PUT").to(tailUrl, Boolean.class); + return retrieve().method(PUT).to(tailUrl, Boolean.class); } /** @@ -3260,7 +3296,7 @@ public boolean updateEmailsOnPush(Integer projectId, String emailAddress) throws * * @param projectId The ID of the project containing the variable. * @return - * @throws IOException + * @throws IOException on gitlab api call error */ public GitlabServiceJira getJiraService(Integer projectId) throws IOException { String tailUrl = GitlabProject.URL + "/" + projectId + GitlabServiceJira.URL; @@ -3273,11 +3309,11 @@ public GitlabServiceJira getJiraService(Integer projectId) throws IOException { * * @param projectId The ID of the project containing the variable. * @return - * @throws IOException + * @throws IOException on gitlab api call error */ public boolean deleteJiraService(Integer projectId) throws IOException { String tailUrl = GitlabProject.URL + "/" + projectId + GitlabServiceJira.URL; - return retrieve().method("DELETE").to(tailUrl, Boolean.class); + return retrieve().method(DELETE).to(tailUrl, Boolean.class); } /** @@ -3287,7 +3323,7 @@ public boolean deleteJiraService(Integer projectId) throws IOException { * @param projectId The ID of the project containing the variable. * @param jiraPropties * @return - * @throws IOException + * @throws IOException on gitlab api call error */ public boolean createOrEditJiraService(Integer projectId, GitlabJiraProperties jiraPropties) throws IOException { @@ -3309,7 +3345,7 @@ public boolean createOrEditJiraService(Integer projectId, GitlabJiraProperties j String tailUrl = GitlabProject.URL + "/" + projectId + GitlabServiceJira.URL + query.toString(); - return retrieve().method("PUT").to(tailUrl, Boolean.class); + return retrieve().method(PUT).to(tailUrl, Boolean.class); } @@ -3317,7 +3353,7 @@ public boolean createOrEditJiraService(Integer projectId, GitlabJiraProperties j * Get a list of projects accessible by the authenticated user by search. * * @return A list of gitlab projects - * @throws IOException + * @throws IOException on gitlab api call error */ public List searchProjects(String search) throws IOException { Query query = new Query() @@ -3366,7 +3402,7 @@ public void deleteSharedProjectGroupLink(GitlabGroup group, GitlabProject projec */ public void deleteSharedProjectGroupLink(int groupId, int projectId) throws IOException { String tailUrl = GitlabProject.URL + "/" + projectId + "/share/" + groupId; - retrieve().method("DELETE").to(tailUrl, Void.class); + retrieve().method(DELETE).to(tailUrl, Void.class); } /** @@ -3390,7 +3426,7 @@ public GitlabVersion getVersion() throws IOException { * Returns a List of all GitlabRunners. * * @return List of GitlabRunners - * @throws IOException + * @throws IOException on gitlab api call error */ public List getRunners() throws IOException { return getRunnersWithPagination(GitlabRunner.RunnerScope.ALL, null); @@ -3441,7 +3477,7 @@ public List getRunnersWithPagination(GitlabRunner.RunnerScope scop } tailUrl.append(query.toString()); - return Arrays.asList(retrieve().method("GET").to(tailUrl.toString(), GitlabRunner[].class)); + return Arrays.asList(retrieve().method(GET).to(tailUrl.toString(), GitlabRunner[].class)); } /** @@ -3449,7 +3485,7 @@ public List getRunnersWithPagination(GitlabRunner.RunnerScope scop * * @param id Runner id. * @return Extensive GitlabRunner Details. - * @throws IOException + * @throws IOException on gitlab api call error */ public GitlabRunner getRunnerDetail(int id) throws IOException { String tailUrl = String.format("%s/%d", GitlabRunner.URL, id); diff --git a/src/main/java/org/gitlab/api/http/GitlabHTTPRequestor.java b/src/main/java/org/gitlab/api/http/GitlabHTTPRequestor.java index 7ca8372e..0b2a2a65 100644 --- a/src/main/java/org/gitlab/api/http/GitlabHTTPRequestor.java +++ b/src/main/java/org/gitlab/api/http/GitlabHTTPRequestor.java @@ -25,6 +25,10 @@ import org.gitlab.api.GitlabAPIException; import org.gitlab.api.TokenType; +import static org.gitlab.api.http.Method.GET; +import static org.gitlab.api.http.Method.POST; +import static org.gitlab.api.http.Method.PUT; + /** * Gitlab HTTP Requestor * Responsible for handling HTTP requests to the Gitlab API @@ -37,32 +41,14 @@ public class GitlabHTTPRequestor { private final GitlabAPI root; - private String method = "GET"; // Default to GET requests - private Map data = new HashMap(); - private Map attachments = new HashMap(); + private Method method = GET; // Default to GET requests + private Map data = new HashMap<>(); + private Map attachments = new HashMap<>(); private String apiToken; private TokenType tokenType; private AuthMethod authMethod; - private enum METHOD { - GET, PUT, POST, PATCH, DELETE, HEAD, OPTIONS, TRACE; - - public static String prettyValues() { - METHOD[] methods = METHOD.values(); - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < methods.length; i++) { - METHOD method = methods[i]; - builder.append(method.toString()); - - if (i != methods.length - 1) { - builder.append(", "); - } - } - return builder.toString(); - } - } - public GitlabHTTPRequestor(GitlabAPI root) { this.root = root; } @@ -82,7 +68,7 @@ public GitlabHTTPRequestor authenticate(String token, TokenType type, AuthMethod this.authMethod = method; return this; } - + /** * Sets the HTTP Request method for the request. * Has a fluent api for method chaining. @@ -90,13 +76,8 @@ public GitlabHTTPRequestor authenticate(String token, TokenType type, AuthMethod * @param method The HTTP method * @return this */ - public GitlabHTTPRequestor method(String method) { - try { - this.method = METHOD.valueOf(method).toString(); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("Invalid HTTP Method: " + method + ". Must be one of " + METHOD.prettyValues()); - } - + public GitlabHTTPRequestor method(Method method) { + this.method = method; return this; } @@ -157,7 +138,7 @@ public T to(String tailAPIUrl, Class type, T instance) throws IOException submitAttachments(connection); } else if (hasOutput()) { submitData(connection); - } else if ("PUT".equals(method)) { + } else if (PUT.equals(method)) { // PUT requires Content-Length: 0 even when there is no body (eg: API for protecting a branch) connection.setDoOutput(true); connection.setFixedLengthStreamingMode(0); @@ -178,7 +159,7 @@ public T to(String tailAPIUrl, Class type, T instance) throws IOException } public List getAll(final String tailUrl, final Class type) { - List results = new ArrayList(); + List results = new ArrayList<>(); Iterator iterator = asIterator(tailUrl, type); while (iterator.hasNext()) { @@ -192,7 +173,7 @@ public List getAll(final String tailUrl, final Class type) { } public Iterator asIterator(final String tailApiUrl, final Class type) { - method("GET"); // Ensure we only use iterators for GET requests + method(GET); // Ensure we only use iterators for GET requests // Ensure that we don't submit any data and alert the user if (!data.isEmpty()) { @@ -293,35 +274,30 @@ private void submitAttachments(HttpURLConnection connection) throws IOException String charset = "UTF-8"; String CRLF = "\r\n"; // Line separator required by multipart/form-data. OutputStream output = connection.getOutputStream(); - PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true); - try { + try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true)) { for (Map.Entry paramEntry : data.entrySet()) { String paramName = paramEntry.getKey(); String param = GitlabAPI.MAPPER.writeValueAsString(paramEntry.getValue()); - writer.append("--" + boundary).append(CRLF); - writer.append("Content-Disposition: form-data; name=\"" + paramName + "\"").append(CRLF); - writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); + writer.append("--").append(boundary).append(CRLF); + writer.append("Content-Disposition: form-data; name=\"").append(paramName).append("\"").append(CRLF); + writer.append("Content-Type: text/plain; charset=").append(charset).append(CRLF); writer.append(CRLF).append(param).append(CRLF).flush(); } for (Map.Entry attachMentEntry : attachments.entrySet()) { File binaryFile = attachMentEntry.getValue(); - writer.append("--" + boundary).append(CRLF); - writer.append("Content-Disposition: form-data; name=\""+ attachMentEntry.getKey() +"\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF); - writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF); + writer.append("--").append(boundary).append(CRLF); + writer.append("Content-Disposition: form-data; name=\"").append(attachMentEntry.getKey()) + .append("\"; filename=\"").append(binaryFile.getName()).append("\"").append(CRLF); + writer.append("Content-Type: ").append(URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append(CRLF).flush(); - Reader fileReader = new FileReader(binaryFile); - try { + try (Reader fileReader = new FileReader(binaryFile)) { IOUtils.copy(fileReader, output); - } finally { - fileReader.close(); } output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. } - writer.append("--" + boundary + "--").append(CRLF).flush(); - } finally { - writer.close(); + writer.append("--").append(boundary).append("--").append(CRLF).flush(); } } @@ -336,7 +312,7 @@ private boolean hasAttachments() { } private boolean hasOutput() { - return method.equals("POST") || method.equals("PUT") && !data.isEmpty(); + return method.equals(POST) || method.equals(PUT) && !data.isEmpty(); } private HttpURLConnection setupConnection(URL url) throws IOException { @@ -346,35 +322,31 @@ private HttpURLConnection setupConnection(URL url) throws IOException { if (apiToken != null && authMethod == AuthMethod.URL_PARAMETER) { String urlWithAuth = url.toString(); - urlWithAuth = urlWithAuth + (urlWithAuth.indexOf('?') > 0 ? '&' : '?') + tokenType.getTokenParamName() + "=" + apiToken; + urlWithAuth = urlWithAuth + (urlWithAuth.indexOf('?') > 0 ? '&' : '?') + + tokenType.getTokenParamName() + "=" + apiToken; url = new URL(urlWithAuth); } - HttpURLConnection connection = root.getProxy() != null ? (HttpURLConnection) url.openConnection(root.getProxy()) : (HttpURLConnection) url.openConnection(); + HttpURLConnection connection = root.getProxy() != null ? + (HttpURLConnection) url.openConnection(root.getProxy()) : (HttpURLConnection) url.openConnection(); if (apiToken != null && authMethod == AuthMethod.HEADER) { - connection.setRequestProperty(tokenType.getTokenHeaderName(), String.format(tokenType.getTokenHeaderFormat(), apiToken)); + connection.setRequestProperty(tokenType.getTokenHeaderName(), + String.format(tokenType.getTokenHeaderFormat(), apiToken)); } - final int requestTimeout = root.getRequestTimeout(); - if (requestTimeout > 0) { - connection.setReadTimeout(requestTimeout); - } - - final int connectionTimeout = root.getConnectionTimeout(); - if (connectionTimeout > 0) { - connection.setConnectTimeout(connectionTimeout); - } + connection.setReadTimeout(root.getResponseReadTimeout()); + connection.setConnectTimeout(root.getConnectionTimeout()); try { - connection.setRequestMethod(method); + connection.setRequestMethod(method.name()); } catch (ProtocolException e) { // Hack in case the API uses a non-standard HTTP verb try { Field methodField = connection.getClass().getDeclaredField("method"); methodField.setAccessible(true); - methodField.set(connection, method); + methodField.set(connection, method.name()); } catch (Exception x) { - throw (IOException) new IOException("Failed to set the custom verb").initCause(x); + throw new IOException("Failed to set the custom verb", x); } } connection.setRequestProperty("User-Agent", root.getUserAgent()); @@ -401,7 +373,8 @@ private T parse(HttpURLConnection connection, Class type, T instance) thr return null; } } catch (SSLHandshakeException e) { - throw new SSLHandshakeException("You can disable certificate checking by setting ignoreCertificateErrors on GitlabHTTPRequestor. SSL Error: " + e.getMessage()); + throw new SSLException("You can disable certificate checking by setting ignoreCertificateErrors " + + "on GitlabHTTPRequestor.", e); } finally { IOUtils.closeQuietly(reader); } @@ -420,13 +393,9 @@ private InputStream wrapStream(HttpURLConnection connection, InputStream inputSt } private void handleAPIError(IOException e, HttpURLConnection connection) throws IOException { - if (e instanceof FileNotFoundException) { - throw e; // pass through 404 Not Found to allow the caller to handle it intelligently - } - if (e instanceof SocketTimeoutException && root.getRequestTimeout() > 0) { - throw e; - } - if (e instanceof ConnectException && root.getConnectionTimeout() > 0) { + if (e instanceof FileNotFoundException || // pass through 404 Not Found to allow the caller to handle it intelligently + e instanceof SocketTimeoutException || + e instanceof ConnectException) { throw e; } @@ -462,12 +431,7 @@ public void checkServerTrusted( } }; // Added per https://github.com/timols/java-gitlab-api/issues/44 - HostnameVerifier nullVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; + HostnameVerifier nullVerifier = (hostname, session) -> true; try { SSLContext sc = SSLContext.getInstance("SSL"); @@ -475,8 +439,6 @@ public boolean verify(String hostname, SSLSession session) { HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // Added per https://github.com/timols/java-gitlab-api/issues/44 HttpsURLConnection.setDefaultHostnameVerifier(nullVerifier); - } catch (Exception e) { - // Ignore it - } + } catch (Exception ignore) {} } } diff --git a/src/main/java/org/gitlab/api/http/Method.java b/src/main/java/org/gitlab/api/http/Method.java new file mode 100644 index 00000000..02655e7e --- /dev/null +++ b/src/main/java/org/gitlab/api/http/Method.java @@ -0,0 +1,11 @@ +package org.gitlab.api.http; + +/** + * Created by Oleg Shaburov on 03.05.2018 + * shaburov.o.a@gmail.com + */ +public enum Method { + + GET, PUT, POST, PATCH, DELETE, HEAD, OPTIONS, TRACE; + +} diff --git a/src/test/java/org/gitlab/api/GitlabAPIIT.java b/src/test/java/org/gitlab/api/GitlabAPIIT.java index 121d86a0..bee0c645 100644 --- a/src/test/java/org/gitlab/api/GitlabAPIIT.java +++ b/src/test/java/org/gitlab/api/GitlabAPIIT.java @@ -5,19 +5,23 @@ import org.junit.Test; import java.io.FileNotFoundException; -import java.io.IOException; import java.net.URL; import java.util.List; import java.util.UUID; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; import static org.junit.Assert.*; public class GitlabAPIIT { - static GitlabAPI api; + private static GitlabAPI api; - private static final String TEST_URL = "http://" + System.getProperty("docker.host.address", "localhost") + ":" + System.getProperty("gitlab.port", "18080"); - String rand = createRandomString(); + private static final String TEST_URL = "http://" + System.getProperty("docker.host.address", "localhost") + + ":" + System.getProperty("gitlab.port", "18080"); @BeforeClass public static void getApi() { @@ -25,9 +29,10 @@ public static void getApi() { } @Test - public void Check_invalid_credentials() throws IOException { + public void checkInvalidCredentials() throws Exception { try { - api.dispatch().with("login", "INVALID").with("password", createRandomString()).to("session", GitlabUser.class); + api.dispatch().with("login", "INVALID").with("password", createRandomString()) + .to("session", GitlabUser.class); } catch (GitlabAPIException e) { final String message = e.getMessage(); if (!message.equals("{\"message\":\"401 Unauthorized\"}")) { @@ -37,30 +42,26 @@ public void Check_invalid_credentials() throws IOException { } } } - @Test - public void testAllProjects() throws IOException { - api.getAllProjects(); - } @Test - public void testConnect() throws IOException { - assertEquals(GitlabAPI.class, api.getClass()); + public void testAllProjects() { + assertThat(api.getAllProjects(), is(notNullValue())); } @Test - public void testGetAPIUrl() throws IOException { + public void testGetAPIUrl() throws Exception { URL expected = new URL(TEST_URL + "/api/v4/"); assertEquals(expected, api.getAPIUrl("")); } @Test - public void testGetUrl() throws IOException { + public void testGetUrl() throws Exception { URL expected = new URL(TEST_URL); assertEquals(expected + "/", api.getUrl("").toString()); } @Test - public void testCreateUpdateDeleteVariable() throws IOException { + public void testCreateUpdateDeleteVariable() throws Exception { String key = randVal("key"); String value = randVal("value"); String newValue = randVal("new_value"); @@ -81,16 +82,13 @@ public void testCreateUpdateDeleteVariable() throws IOException { api.updateBuildVariable(project.getId(), key, newValue); - GitlabBuildVariable postUpdate = api.getBuildVariable(project.getId(), key); - assertNotNull(postUpdate); assertEquals(postUpdate.getKey(), variable.getKey()); assertNotEquals(postUpdate.getValue(), variable.getValue()); assertEquals(postUpdate.getValue(), newValue); - api.deleteBuildVariable(project.getId(), key); // expect a 404, but we have no access to it @@ -100,16 +98,12 @@ public void testCreateUpdateDeleteVariable() throws IOException { } catch (FileNotFoundException thisIsSoOddForAnRESTApiClient) { assertTrue(true); // expected } - api.deleteProject(project.getId()); } @Test - public void testCreateUpdateDeleteUser() throws IOException, InterruptedException { - + public void testCreateUpdateDeleteUser() throws Exception { String password = randVal("$%password"); - - GitlabUser gitUser = api.createUser(randVal("testEmail@gitlabapitest.com"), password, randVal("userName"), @@ -134,14 +128,14 @@ public void testCreateUpdateDeleteUser() throws IOException, InterruptedExceptio assertEquals(refetched.getUsername(), gitUser.getUsername()); api.updateUser(gitUser.getId(), gitUser.getEmail(), password, gitUser.getUsername(), - gitUser.getName(), "newSkypeId", gitUser.getLinkedin(), gitUser.getTwitter(), gitUser.getWebsiteUrl(), - 10 /* project limit does not come back on GET */, gitUser.getExternUid(), gitUser.getExternProviderName(), + gitUser.getName(), "newSkypeId", gitUser.getLinkedin(), + gitUser.getTwitter(), gitUser.getWebsiteUrl(), + 10 /* project limit does not come back on GET */, + gitUser.getExternUid(), gitUser.getExternProviderName(), gitUser.getBio(), gitUser.isAdmin(), gitUser.isCanCreateGroup(), gitUser.isExternal()); - GitlabUser postUpdate = api.getUserViaSudo(gitUser.getUsername()); - assertNotNull(postUpdate); assertEquals(postUpdate.getSkype(), "newSkypeId"); @@ -159,12 +153,10 @@ public void testCreateUpdateDeleteUser() throws IOException, InterruptedExceptio } catch (FileNotFoundException thisIsSoOddForAnRESTApiClient) { assertTrue(true); // expected } - - } @Test - public void testGetGroupByPath() throws IOException { + public void testGetGroupByPath() throws Exception { // Given String name = "groupName"; String path = "groupPath"; @@ -185,7 +177,7 @@ public void testGetGroupByPath() throws IOException { } @Test - public void testCreateAndUpdateGroup() throws IOException { + public void testCreateAndUpdateGroup() throws Exception { // Given GitlabGroup originalGroup = new GitlabGroup(); originalGroup.setDescription("test description"); @@ -217,41 +209,36 @@ public void testCreateAndUpdateGroup() throws IOException { } @Test - public void testGetMembershipProjects() throws IOException { - final List membershipProjects = api.getMembershipProjects(); - assertTrue(membershipProjects.size() >= 0); + public void testGetMembershipProjects() throws Exception { + assertThat(api.getMembershipProjects(), not(nullValue())); } @Test - public void Check_get_owned_projects() throws IOException { - final List ownedProjects = api.getOwnedProjects(); - assertTrue(ownedProjects.size() >= 0); + public void checkGetOwnedProjects() throws Exception { + assertThat(api.getOwnedProjects(), not(nullValue())); } @Test - public void Check_search_projects() throws IOException { + public void checkSearchProjects() throws Exception { final List searchedProjects = api.searchProjects("foo"); - assertEquals(0, searchedProjects.size()); + assertThat(searchedProjects, not(nullValue())); + assertThat(searchedProjects.isEmpty(), is(true)); } /** * There is at least one namespace for the user - * - * @throws IOException */ @Test - public void testGetNamespace() throws IOException { + public void testGetNamespace() { final List gitlabNamespaces = api.getNamespaces(); - assertTrue(gitlabNamespaces.size() > 0); + assertThat(gitlabNamespaces, not(nullValue())); + assertThat(gitlabNamespaces.isEmpty(), is(false)); } @Test - public void testCreateDeleteFork() throws IOException { + public void testCreateDeleteFork() throws Exception { String projectName = randVal("Fork-me"); - String password = randVal("$%password"); - - GitlabUser gitUser = api.createUser(randVal("testEmail@gitlabapitest.com"), password, randVal("userName"), @@ -269,22 +256,19 @@ public void testCreateDeleteFork() throws IOException { false, false); - GitlabProject project = api.createUserProject(gitUser.getId(), projectName); GitlabProject fork = api.createFork(api.getNamespaces().get(0).getPath(), project); assertNotNull(fork); - assertEquals(project.getId(), fork.getForkedFrom().getId()); api.deleteProject(project.getId()); api.deleteProject(fork.getId()); - api.deleteUser(gitUser.getId()); } private String randVal(String postfix) { - return rand + "_" + postfix; + return createRandomString() + "_" + postfix; } private static String createRandomString() { diff --git a/src/test/java/org/gitlab/api/GitlabAPIUT.java b/src/test/java/org/gitlab/api/GitlabAPIUT.java new file mode 100644 index 00000000..b2cce34a --- /dev/null +++ b/src/test/java/org/gitlab/api/GitlabAPIUT.java @@ -0,0 +1,93 @@ +package org.gitlab.api; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.net.ServerSocket; +import java.net.SocketTimeoutException; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Created by Oleg Shaburov on 03.05.2018 + * shaburov.o.a@gmail.com + */ +@SuppressWarnings("WeakerAccess") +public class GitlabAPIUT { + + @Test + @DisplayName(value = "Check non-routable connection with connection timeout error") + public void unitTest_20180503175711() { + GitlabAPI api = GitlabAPI.connect("http://172.16.0.0:80", "test"); + api.setConnectionTimeout(100); + Throwable exception = assertThrows(SocketTimeoutException.class, api::getVersion); + assertThat(exception.getMessage(), is("connect timed out")); + } + + @Test + @DisplayName(value = "Check default value is 0 for connection timeout") + public void unitTest_20180503185536() { + GitlabAPI api = GitlabAPI.connect("http://test.api", "test"); + assertThat(api.getConnectionTimeout(), is(0)); + } + + @Test + @DisplayName(value = "Check set/get methods for connection timeout parameter") + public void unitTest_20180503185632() { + GitlabAPI api = GitlabAPI.connect("http://test.api", "test"); + api.setConnectionTimeout(123); + assertThat(api.getConnectionTimeout(), is(123)); + } + + @Test + @DisplayName(value = "Check ignore negative value for connection timeout parameter") + public void unitTest_20180503185750() { + GitlabAPI api = GitlabAPI.connect("http://test.api", "test"); + api.setConnectionTimeout(-123); + assertThat(api.getConnectionTimeout(), is(0)); + } + + @Test + @DisplayName(value = "Check connection with read timeout error") + public void unitTest_20180503191159() throws IOException { + ServerSocket socket = null; + try { + socket = new ServerSocket(15896); + GitlabAPI api = GitlabAPI.connect("http://localhost:15896", "test"); + api.setResponseReadTimeout(100); + Throwable exception = assertThrows(SocketTimeoutException.class, api::getVersion); + assertThat(exception.getMessage(), is("Read timed out")); + } finally { + if (socket != null) { + socket.close(); + } + } + } + + @Test + @DisplayName(value = "Check default value is 0 for request timeout parameter") + public void unitTest_20180503191716() { + GitlabAPI api = GitlabAPI.connect("http://test.api", "test"); + assertThat(api.getResponseReadTimeout(), is(0)); + } + + @Test + @DisplayName(value = "Check set/get methods for request timeout parameter") + public void unitTest_20180503191945() { + GitlabAPI api = GitlabAPI.connect("http://test.api", "test"); + api.setResponseReadTimeout(123); + assertThat(api.getResponseReadTimeout(), is(123)); + } + + @Test + @DisplayName(value = "Check ignore negative value for request timeout parameter") + public void unitTest_20180503192141() { + GitlabAPI api = GitlabAPI.connect("http://test.api", "test"); + api.setResponseReadTimeout(-123); + assertThat(api.getResponseReadTimeout(), is(0)); + } + +} diff --git a/src/test/java/org/gitlab/api/http/GitlabHTTPRequestorTest.java b/src/test/java/org/gitlab/api/http/GitlabHTTPRequestorTest.java index f9effc4b..9db94bac 100644 --- a/src/test/java/org/gitlab/api/http/GitlabHTTPRequestorTest.java +++ b/src/test/java/org/gitlab/api/http/GitlabHTTPRequestorTest.java @@ -1,20 +1,114 @@ package org.gitlab.api.http; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import org.gitlab.api.GitlabAPI; -import org.junit.Test; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import java.lang.reflect.Method; +import java.net.HttpURLConnection; +import java.net.URL; + +@SuppressWarnings({"WeakerAccess", "ConstantConditions"}) public class GitlabHTTPRequestorTest { @Test - public void testSettingInvalidHTTPMethod() { - GitlabHTTPRequestor http = new GitlabHTTPRequestor(GitlabAPI.connect("localhost", "api")); + @DisplayName(value = "Expected success, calling the \"setupConnection\" method if the connection timeout = 0") + public void unitTest_20180503194340() throws Exception { + GitlabAPI api = mock(GitlabAPI.class); + when(api.getConnectionTimeout()).thenReturn(0); + GitlabHTTPRequestor http = new GitlabHTTPRequestor(api); + URL url = new URL("http://test.url"); + Method method = GitlabHTTPRequestor.class.getDeclaredMethod("setupConnection", URL.class); + method.setAccessible(true); + HttpURLConnection connection = (HttpURLConnection) method.invoke(http, url); + assertThat(connection.getConnectTimeout(), is(0)); + } + + @Test + @DisplayName(value = "Expected success, calling the \"setupConnection\" method if the connection timeout > 0") + public void unitTest_20180503194559() throws Exception { + GitlabAPI api = mock(GitlabAPI.class); + when(api.getConnectionTimeout()).thenReturn(456); + GitlabHTTPRequestor http = new GitlabHTTPRequestor(api); + URL url = new URL("http://test.url"); + Method method = GitlabHTTPRequestor.class.getDeclaredMethod("setupConnection", URL.class); + method.setAccessible(true); + HttpURLConnection connection = (HttpURLConnection) method.invoke(http, url); + assertThat(connection.getConnectTimeout(), is(456)); + } + + @Test + @DisplayName(value = "An error is expected, calling the \"setupConnection\" method if the connection timeout < 0") + public void unitTest_20180503194643() throws Exception { + GitlabAPI api = mock(GitlabAPI.class); + when(api.getConnectionTimeout()).thenReturn(-555); + GitlabHTTPRequestor http = new GitlabHTTPRequestor(api); + URL url = new URL("http://test.url"); + Method method = GitlabHTTPRequestor.class.getDeclaredMethod("setupConnection", URL.class); + method.setAccessible(true); + Throwable throwable = null; + try { + method.invoke(http, url); + } catch (Exception e) { + throwable = e.getCause(); + } + assertThat(throwable, not(nullValue())); + assertThat(throwable, is(instanceOf(IllegalArgumentException.class))); + assertThat(throwable.getMessage(), is("timeouts can't be negative")); + } + + @Test + @DisplayName(value = "Expected success, calling the \"setupConnection\" method if the read timeout = 0") + public void unitTest_20180503202458() throws Exception { + GitlabAPI api = mock(GitlabAPI.class); + when(api.getResponseReadTimeout()).thenReturn(0); + GitlabHTTPRequestor http = new GitlabHTTPRequestor(api); + URL url = new URL("http://test.url"); + Method method = GitlabHTTPRequestor.class.getDeclaredMethod("setupConnection", URL.class); + method.setAccessible(true); + HttpURLConnection connection = (HttpURLConnection) method.invoke(http, url); + assertThat(connection.getReadTimeout(), is(0)); + } + + @Test + @DisplayName(value = "Expected success, calling the \"setupConnection\" method if the read timeout > 0") + public void unitTest_20180503203531() throws Exception { + GitlabAPI api = mock(GitlabAPI.class); + when(api.getResponseReadTimeout()).thenReturn(555); + GitlabHTTPRequestor http = new GitlabHTTPRequestor(api); + URL url = new URL("http://test.url"); + Method method = GitlabHTTPRequestor.class.getDeclaredMethod("setupConnection", URL.class); + method.setAccessible(true); + HttpURLConnection connection = (HttpURLConnection) method.invoke(http, url); + assertThat(connection.getReadTimeout(), is(555)); + } + + @Test + @DisplayName(value = "An error is expected, calling the \"setupConnection\" method if the read timeout < 0") + public void unitTest_20180503203635() throws Exception { + GitlabAPI api = mock(GitlabAPI.class); + when(api.getResponseReadTimeout()).thenReturn(-555); + GitlabHTTPRequestor http = new GitlabHTTPRequestor(api); + URL url = new URL("http://test.url"); + Method method = GitlabHTTPRequestor.class.getDeclaredMethod("setupConnection", URL.class); + method.setAccessible(true); + Throwable throwable = null; try { - http.method("WRONG METHOD"); + method.invoke(http, url); } catch (Exception e) { - assertEquals("Invalid HTTP Method: WRONG METHOD. Must be one of GET, PUT, POST, PATCH, DELETE, HEAD, OPTIONS, TRACE", e.getMessage()); + throwable = e.getCause(); } + assertThat(throwable, not(nullValue())); + assertThat(throwable, is(instanceOf(IllegalArgumentException.class))); + assertThat(throwable.getMessage(), is("timeouts can't be negative")); } } diff --git a/src/test/resources/log4j2.xml b/src/test/resources/log4j2.xml new file mode 100644 index 00000000..57f3d206 --- /dev/null +++ b/src/test/resources/log4j2.xml @@ -0,0 +1,16 @@ + + + + %d{HH:mm:ss.SSS} [%-5p] [%25.25C] - %m%n + + + + + + + + + + + + From 61b25cf063d4b8987c89661f2165f576fac28bed Mon Sep 17 00:00:00 2001 From: "oleg.shaburov" Date: Thu, 3 May 2018 21:53:33 +0300 Subject: [PATCH 3/3] add dependencies to the pom.xml --- build.gradle | 1 - pom.xml | 60 +++++++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 57 insertions(+), 4 deletions(-) diff --git a/build.gradle b/build.gradle index 4d0ab7e8..c9fd7ac3 100644 --- a/build.gradle +++ b/build.gradle @@ -30,7 +30,6 @@ dependencies { testCompile(group: 'org.mockito', name: 'mockito-core', version: '2.18.3') testCompile(group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.11.0') testCompile(group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: '2.11.0') - testCompile(group: 'com.github.tomakehurst', name: 'wiremock-standalone', version: '2.17.0') testCompile(group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.2.0') testRuntime(group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: '5.2.0') testCompile(group: "junit", name: "junit", version: "4.12") diff --git a/pom.xml b/pom.xml index 95aba0ce..106212de 100644 --- a/pom.xml +++ b/pom.xml @@ -38,6 +38,14 @@ luu@fuzzproductions.com Fuzz Productions + + Oleg Shaburov + shaburov.o.a@gmail.com + + Automation QA + + +3 + @@ -67,6 +75,8 @@ 2.20 180000 + 2.11.0 + 5.2.0 @@ -85,10 +95,23 @@ commons-io 2.4 + - org.hamcrest - hamcrest-all - 1.3 + org.slf4j + slf4j-api + 1.8.0-beta2 + + + + org.junit.jupiter + junit-jupiter-api + ${junit.jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} test @@ -97,6 +120,37 @@ 4.12 test + + org.junit.vintage + junit-vintage-engine + ${junit.jupiter.version} + test + + + org.hamcrest + hamcrest-all + 1.3 + test + + + org.mockito + mockito-core + 2.10.0 + test + + + + org.apache.logging.log4j + log4j-api + ${log4j.version} + test + + + org.apache.logging.log4j + log4j-slf4j-impl + ${log4j.version} + test +