diff --git a/.travis.yml b/.travis.yml index 87800ef2..257d4981 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,7 +3,7 @@ sudo: required services: - docker jdk: -- oraclejdk8 +- openjdk8 install: - ./mvnw -B -q -Pdocker-gitlab dependency:go-offline verify -DskipTests -Ddocker.skip script: diff --git a/build.gradle b/build.gradle index c9fd7ac3..a245c85b 100644 --- a/build.gradle +++ b/build.gradle @@ -15,7 +15,7 @@ sourceCompatibility = 1.8 targetCompatibility = 1.8 group = "org.gitlab" -version = "4.0.1-SNAPSHOT" +version = "4.1.2-SNAPSHOT" repositories { mavenLocal() @@ -23,17 +23,18 @@ repositories { } dependencies { - 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: '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') + compile(group: "org.slf4j", name: "slf4j-api", version: "1.8.0-beta2") + compile(group: "commons-io", name: "commons-io", version: "2.4") + compile(group: "com.fasterxml.jackson.core", name: "jackson-databind", version: "2.5.+") + compile(group: "com.fasterxml.jackson.datatype", name: "jackson-datatype-jsr310", version: "2.5.1") + 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: "org.hamcrest", name: "hamcrest-all", version: "1.3") + testCompile(group: "org.mockito", name: "mockito-core", version: "2.18.3") + testCompile(group: "org.junit.jupiter", name: "junit-jupiter-api", version: "5.2.0") + testCompile(group: "junit", name: "junit", version: "4.12") + testRuntime(group: "org.junit.jupiter", name: "junit-jupiter-engine", version: "5.2.0") + testRuntime(group: "org.junit.vintage", name: "junit-vintage-engine", version: "5.2.0") } jar { @@ -55,13 +56,9 @@ task sourcesJar(type: Jar, dependsOn:classes) { 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/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index b5166dad..f6b961fd 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index cd225d45..430dfabc 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,5 @@ -#Tue Mar 06 18:55:53 EST 2018 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-5.5.1-all.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip diff --git a/gradlew b/gradlew index 91a7e269..cccdd3d5 100755 --- a/gradlew +++ b/gradlew @@ -1,4 +1,4 @@ -#!/usr/bin/env bash +#!/usr/bin/env sh ############################################################################## ## @@ -6,20 +6,38 @@ ## ############################################################################## -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" -warn ( ) { +warn () { echo "$*" } -die ( ) { +die () { echo echo "$*" echo @@ -30,6 +48,7 @@ die ( ) { cygwin=false msys=false darwin=false +nonstop=false case "`uname`" in CYGWIN* ) cygwin=true @@ -40,31 +59,11 @@ case "`uname`" in MINGW* ) msys=true ;; + NONSTOP* ) + nonstop=true + ;; esac -# For Cygwin, ensure paths are in UNIX format before anything is touched. -if $cygwin ; then - [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` -fi - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >&- -APP_HOME="`pwd -P`" -cd "$SAVED" >&- - CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. @@ -90,7 +89,7 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then @@ -114,6 +113,7 @@ fi if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` @@ -154,11 +154,19 @@ if $cygwin ; then esac fi -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " } -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index aec99730..e95643d6 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -8,14 +8,14 @@ @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome @@ -46,10 +46,9 @@ echo location of your Java installation. goto fail :init -@rem Get command-line arguments, handling Windowz variants +@rem Get command-line arguments, handling Windows variants if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. @@ -60,11 +59,6 @@ set _SKIP=2 if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ :execute @rem Setup the command line diff --git a/pom.xml b/pom.xml index 29a9e759..902f0424 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ org.gitlab java-gitlab-api - 4.0.1-SNAPSHOT + 4.1.2-SNAPSHOT Gitlab Java API Wrapper A Java wrapper for the Gitlab Git Hosting Server API @@ -88,7 +88,7 @@ com.fasterxml.jackson.core jackson-databind - 2.5.3 + 2.9.10.5 commons-io @@ -151,6 +151,13 @@ ${log4j.version} test + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + 2.5.1 + + @@ -215,6 +222,26 @@ + + org.apache.maven.plugins + maven-gpg-plugin + 1.6 + + + sign-artifacts + verify + + sign + + + + --pinentry-mode + loopback + + + + + diff --git a/src/main/java/org/gitlab/api/GitlabAPI.java b/src/main/java/org/gitlab/api/GitlabAPI.java index bae26fab..c0c88fa7 100644 --- a/src/main/java/org/gitlab/api/GitlabAPI.java +++ b/src/main/java/org/gitlab/api/GitlabAPI.java @@ -5,6 +5,9 @@ import org.gitlab.api.http.GitlabHTTPRequestor; import org.gitlab.api.http.Query; import org.gitlab.api.models.*; +import org.gitlab.api.query.PaginationQuery; +import org.gitlab.api.query.PipelinesQuery; +import org.gitlab.api.query.ProjectsQuery; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -20,6 +23,7 @@ import java.util.Arrays; import java.util.Date; import java.util.List; +import java.util.Collection; import static org.gitlab.api.http.Method.*; @@ -35,8 +39,10 @@ public class GitlabAPI { public static final ObjectMapper MAPPER = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - private static final String API_NAMESPACE = "/api/v4"; + + private static final String DEFAULT_API_NAMESPACE = "/api/v4"; private static final String PARAM_SUDO = "sudo"; + private static final String PARAM_WITH_PROJECTS = "with_projects"; private static final String PARAM_MAX_ITEMS_PER_PAGE = new Pagination().withPerPage(Pagination.MAX_ITEMS_PER_PAGE).toString(); private final String hostUrl; @@ -44,6 +50,7 @@ public class GitlabAPI { private final String apiToken; private final TokenType tokenType; private AuthMethod authMethod; + private final String apiNamespace; private boolean ignoreCertificateErrors = false; private Proxy proxy; private int defaultTimeout = 0; @@ -51,16 +58,21 @@ public class GitlabAPI { private int connectionTimeout = defaultTimeout; private String userAgent = GitlabAPI.class.getCanonicalName() + "/" + System.getProperty("java.version"); - private GitlabAPI(String hostUrl, String apiToken, TokenType tokenType, AuthMethod method) { + private GitlabAPI(String hostUrl, String apiToken, TokenType tokenType, AuthMethod method, String apiNamespace) { this.hostUrl = hostUrl.endsWith("/") ? hostUrl.replaceAll("/$", "") : hostUrl; this.apiToken = apiToken; this.tokenType = tokenType; this.authMethod = method; + this.apiNamespace = apiNamespace; + } + + private GitlabAPI(String hostUrl, String apiToken, TokenType tokenType, AuthMethod method) { + this(hostUrl, apiToken, tokenType, method, DEFAULT_API_NAMESPACE); } public static GitlabSession connect(String hostUrl, String username, String password) throws IOException { String tailUrl = GitlabSession.URL; - GitlabAPI api = connect(hostUrl, null, null, null); + GitlabAPI api = connect(hostUrl, null, null, (AuthMethod) null); return api.dispatch().with("login", username).with("password", password) .to(tailUrl, GitlabSession.class); } @@ -77,6 +89,14 @@ public static GitlabAPI connect(String hostUrl, String apiToken, TokenType token return new GitlabAPI(hostUrl, apiToken, tokenType, method); } + public static GitlabAPI connect(String hostUrl, String apiToken, TokenType tokenType, String apiNamespace) { + return new GitlabAPI(hostUrl, apiToken, tokenType, AuthMethod.HEADER, apiNamespace); + } + + public static GitlabAPI connect(String hostUrl, String apiToken, TokenType tokenType, AuthMethod method, String apiNamespace) { + return new GitlabAPI(hostUrl, apiToken, tokenType, method, apiNamespace); + } + public GitlabAPI ignoreCertificateErrors(boolean ignoreCertificateErrors) { this.ignoreCertificateErrors = ignoreCertificateErrors; return this; @@ -142,6 +162,10 @@ public GitlabHTTPRequestor dispatch() { return new GitlabHTTPRequestor(this).authenticate(apiToken, tokenType, authMethod).method(POST); } + public GitlabHTTPRequestor put() { + return new GitlabHTTPRequestor(this).authenticate(apiToken, tokenType, authMethod).method(PUT); + } + public boolean isIgnoreCertificateErrors() { return ignoreCertificateErrors; } @@ -154,7 +178,7 @@ public URL getAPIUrl(String tailAPIUrl) throws IOException { if (!tailAPIUrl.startsWith("/")) { tailAPIUrl = "/" + tailAPIUrl; } - return new URL(hostUrl + API_NAMESPACE + tailAPIUrl); + return new URL(hostUrl + apiNamespace + tailAPIUrl); } public URL getUrl(String tailAPIUrl) throws IOException { @@ -372,7 +396,7 @@ public GitlabSSHKey createSSHKey(Integer targetUserId, String title, String key) return dispatch().to(tailUrl, GitlabSSHKey.class); } - + /** * Create a new ssh key for the authenticated user. * @@ -444,8 +468,24 @@ public GitlabGroup getGroup(Integer groupId) throws IOException { return getGroup(groupId.toString()); } + public GitlabGroup getGroupWithoutProjects(Integer groupId) throws IOException { + return getGroupWithoutProjects(groupId.toString()); + } + /** - * Get a group by path + * Get a group by path. Don't include the projects. + * + * @param path Path of the group + * @return {@link GitlabGroup} object + * + * @throws IOException on gitlab api call error + */ + public GitlabGroup getGroupWithoutProjects(String path) throws IOException { + return getGroup(path, false); + } + + /** + * Get a group by path, including its projects. * * @param path Path of the group * @return {@link GitlabGroup} object @@ -453,8 +493,24 @@ public GitlabGroup getGroup(Integer groupId) throws IOException { * @throws IOException on gitlab api call error */ public GitlabGroup getGroup(String path) throws IOException { + return getGroup(path, true); + } + + /** + * Get a group by path + * + * @param path Path of the group + * @param withProjects If true, include the projects + * @return {@link GitlabGroup} object + * + * @throws IOException on gitlab api call error + */ + public GitlabGroup getGroup(String path, boolean withProjects) throws IOException { String tailUrl = GitlabGroup.URL + "/" + URLEncoder.encode(path, "UTF-8"); - return retrieve().to(tailUrl, GitlabGroup.class); + Query query = new Query() + .append(PARAM_WITH_PROJECTS, "" + withProjects); + + return retrieve().to(tailUrl + query.toString(), GitlabGroup.class); } public List getGroups() throws IOException { @@ -627,7 +683,7 @@ public GitlabGroup createGroup(String name, String path, String ldapCn, GitlabAc return dispatch().to(tailUrl, GitlabGroup.class); } - + /** * Creates a Group * @@ -823,6 +879,16 @@ public List getProjectsWithPagination(int page, int perPage) thro return getProjectsWithPagination(pagination); } + /** + * Get a list of projects accessible by the authenticated user. + * + * @return A list of gitlab projects + */ + public List getProjects(ProjectsQuery projectsQuery) { + String tailUrl = GitlabProject.URL + projectsQuery; + return retrieve().getAll(tailUrl, GitlabProject[].class); + } + /** * Get a list of projects by pagination accessible by the authenticated user. * @@ -848,7 +914,7 @@ public List getProjectsWithPagination(Pagination pagination) thro * @throws IOException on gitlab api call error */ public List getOwnedProjects() throws IOException { - Query query = new Query().append("owner", "true"); + Query query = new Query().append("owned", "true"); query.mergeWith(new Pagination().withPerPage(Pagination.MAX_ITEMS_PER_PAGE).asQuery()); String tailUrl = GitlabProject.URL + query.toString(); return retrieve().getAll(tailUrl, GitlabProject[].class); @@ -956,6 +1022,70 @@ public GitlabUpload uploadFile(GitlabProject project, File file) throws IOExcept return dispatch().withAttachment("file", file).to(tailUrl, GitlabUpload.class); } + /** + * Get a project's pipeline + * + * @param project the project + * @param pipeline the pipeline + * @return The project pipeline + */ + public GitlabPipeline getProjectPipeline(GitlabProject project, GitlabPipeline pipeline) throws IOException { + return getProjectPipeline(project.getId(), pipeline.getId()); + } + + /** + * Get a project's pipeline + * + * @param projectId the project id + * @param pipelineId the pipeline id + * @return The project pipeline + */ + public GitlabPipeline getProjectPipeline(Integer projectId, Integer pipelineId) throws IOException { + String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabPipeline.URL + "/" + sanitizeId(pipelineId, "pipelineId"); + return retrieve().to(tailUrl, GitlabPipeline.class); + } + + /** + * Get a list of a project's pipelines in Gitlab + * + * @param project the project + * @return A list of project pipelines + */ + public List getProjectPipelines(GitlabProject project) { + return getProjectPipelines(project.getId()); + } + + /** + * Get a list of a project's pipelines in Gitlab + * + * @param projectId the project id + * @return A list of project pipelines + */ + public List getProjectPipelines(Integer projectId) { + return getProjectPipelines(projectId, new PipelinesQuery().withPerPage(PaginationQuery.MAX_ITEMS_PER_PAGE)); + } + + /** + * Get a list of a project's pipelines in Gitlab + * + * @param project the project + * @return A list of project pipelines + */ + public List getProjectPipelines(GitlabProject project, PipelinesQuery pipelinesQuery) { + return getProjectPipelines(project.getId(), pipelinesQuery); + } + + /** + * Get a list of a project's pipelines in Gitlab + * + * @param projectId the project id + * @return A list of project pipelines + */ + public List getProjectPipelines(Integer projectId, PipelinesQuery pipelinesQuery) { + String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabPipeline.URL + pipelinesQuery; + return retrieve().getAll(tailUrl, GitlabPipeline[].class); + } + /** * Gets a list of a project's jobs in Gitlab * @@ -978,6 +1108,33 @@ public List getProjectJobs(Integer projectId) { } + /** + * Run pipeline for selected project and branch + * @param project project + * @param ref branch + * @param variables pipeline variables + * @return Created pipeline + * @throws IOException + */ + public GitlabPipeline runPipeline(GitlabProject project, String ref, List variables) throws IOException { + return runPipeline(project.getId(), ref, variables); + } + + + /** + * Run pipeline for selected project and branch + * @param projectId project's id + * @param ref branch + * @param variables pipeline variables + * @return Created pipeline + * @throws IOException + */ + public GitlabPipeline runPipeline(Integer projectId, String ref, List variables) throws IOException { + Query query = new Query().appendIf("ref", ref); + String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabPipeline.CREATE_URL + query.toString(); + return dispatch().with("variables", variables).to(tailUrl, GitlabPipeline.class); + } + /** * Gets a list of project's jobs of the given pipeline in Gitlab * @@ -1147,7 +1304,8 @@ public GitlabProject createProject(GitlabProject project) throws IOException { .appendIf("request_access_enabled", project.isRequestAccessEnabled()) .appendIf("repository_storage", project.getRepositoryStorage()) .appendIf("approvals_before_merge", project.getApprovalsBeforeMerge()) - .appendIf("printing_merge_request_link_enabled", project.isPrintingMergeRequestLinkEnabled()); + .appendIf("printing_merge_request_link_enabled", project.isPrintingMergeRequestLinkEnabled()) + .appendIf("initialize_with_readme",project.isInitializeWithReadme()); GitlabNamespace namespace = project.getNamespace(); if (namespace != null) { @@ -1296,17 +1454,30 @@ public GitlabProject createUserProject(Integer userId, String name, String descr /** * @param namespace The namespace of the fork * @param projectId ProjectId of the project forked + * @param path The path that will be assigned to the resultant project after forking. (Optional) + * @param name The name that will be assigned to the resultant project after forking. (Optional) * @return The new Gitlab Project * @throws IOException on gitlab api call error */ - public GitlabProject createFork(String namespace, Integer projectId) throws IOException { + public GitlabProject createFork(String namespace, Integer projectId, String path, String name) throws IOException { Query query = new Query() - .appendIf("id", projectId) - .append("namespace", namespace); - String tailUrl = GitlabProject.URL + "/" + projectId + "/fork"; + .appendIf("namespace", namespace) + .appendIf("path", path) + .appendIf("name", name); + String tailUrl = GitlabProject.URL + "/" + projectId + "/fork" + query.toString(); return dispatch().to(tailUrl, GitlabProject.class); } + /** + * @param namespace The namespace of the fork + * @param projectId ProjectId of the project forked + * @return The new Gitlab Project + * @throws IOException on gitlab api call error + */ + public GitlabProject createFork(String namespace, Integer projectId) throws IOException { + return createFork(namespace, projectId, null, null); + } + /** * @param namespace The namespace of the fork * @param gitlabProject The project forked @@ -1478,6 +1649,36 @@ public GitlabMergeRequestApprovals getMergeRequestApprovals(GitlabMergeRequest m return retrieve().to(tailUrl, GitlabMergeRequestApprovals.class); } + /** + * Set the number of required approvers. + * + * EE only. + */ + public GitlabMergeRequestApprovals setMergeRequestApprovals(GitlabMergeRequest mr, int count) throws IOException { + String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(mr.getProjectId()) + + GitlabMergeRequest.URL + "/" + mr.getIid() + GitlabMergeRequestApprovals.URL; + return dispatch() + .with("approvals_required", count) + .to(tailUrl, GitlabMergeRequestApprovals.class); + } + + /** + * Set the list of approvers. Important: Approvers and groups not + * in the request will be removed + * + * EE only. + */ + public GitlabMergeRequestApprovals setMergeRequestApprovers(GitlabMergeRequest mr, + Collection userApproverIds, + Collection groupApproverIds) throws IOException { + String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(mr.getProjectId()) + + GitlabMergeRequest.URL + "/" + mr.getIid() + GitlabMergeRequestApprovals.APPROVERS_URL; + return put() + .with("approver_ids", userApproverIds) + .with("approver_group_ids", groupApproverIds) + .to(tailUrl, GitlabMergeRequestApprovals.class); + } + /** * Cherry picks a commit. * @@ -1501,7 +1702,7 @@ public GitlabCommit cherryPick(GitlabProject project, String sha, String targetB * Return Merge Request. * * @param projectId The id of the project - * @param mergeRequestIid The iid of the merge request + * @param mergeRequestIid The internal id of the merge request * @return the Gitlab Merge Request * @throws IOException on gitlab api call error */ @@ -1513,23 +1714,28 @@ public GitlabMergeRequest getMergeRequestByIid(Serializable projectId, Integer m /** * Return a Merge Request including its changes. * - * @param projectId The id of the project - * @param mergeRequestId The id of the merge request + * @param projectId The id of the project + * @param mergeRequestIid The internal id of the merge request * @return the Gitlab Merge Request * @throws IOException on gitlab api call error */ - public GitlabMergeRequest getMergeRequestChanges(Serializable projectId, Integer mergeRequestId) throws IOException { - String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabMergeRequest.URL + "/" + mergeRequestId + "/changes"; + public GitlabMergeRequest getMergeRequestChanges(Serializable projectId, + Integer mergeRequestIid) throws IOException { + String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + + GitlabMergeRequest.URL + "/" + mergeRequestIid + "/changes"; return retrieve().to(tailUrl, GitlabMergeRequest.class); } - public GitlabMergeRequest getMergeRequest(Serializable projectId, Integer mergeRequestId) throws IOException { - String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabMergeRequest.URL + "/" + mergeRequestId; + public GitlabMergeRequest getMergeRequest(Serializable projectId, + Integer mergeRequestIid) throws IOException { + String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + + GitlabMergeRequest.URL + "/" + mergeRequestIid; return retrieve().to(tailUrl, GitlabMergeRequest.class); } - public GitlabMergeRequest getMergeRequest(GitlabProject project, Integer mergeRequestId) throws IOException { - return getMergeRequest(project.getId(), mergeRequestId); + public GitlabMergeRequest getMergeRequest(GitlabProject project, + Integer mergeRequestIid) throws IOException { + return getMergeRequest(project.getId(), mergeRequestIid); } /** @@ -1561,18 +1767,18 @@ public GitlabMergeRequest createMergeRequest(Serializable projectId, String sour /** * Updates a Merge Request * - * @param projectId The id of the project - * @param mergeRequestId The id of the merge request to update - * @param targetBranch The target branch of the merge request, otherwise null to leave it untouched - * @param assigneeId The id of the assignee, otherwise null to leave it untouched - * @param title The title of the merge request, otherwise null to leave it untouched - * @param description The description of the merge request, otherwise null to leave it untouched - * @param stateEvent The state (close|reopen|merge) of the merge request, otherwise null to leave it untouched - * @param labels A comma separated list of labels, otherwise null to leave it untouched + * @param projectId The id of the project + * @param mergeRequestIid The internal id of the merge request to update + * @param targetBranch The target branch of the merge request, otherwise null to leave it untouched + * @param assigneeId The id of the assignee, otherwise null to leave it untouched + * @param title The title of the merge request, otherwise null to leave it untouched + * @param description The description of the merge request, otherwise null to leave it untouched + * @param stateEvent The state (close|reopen|merge) of the merge request, otherwise null to leave it untouched + * @param labels A comma separated list of labels, otherwise null to leave it untouched * @return the Merge Request * @throws IOException on gitlab api call error */ - public GitlabMergeRequest updateMergeRequest(Serializable projectId, Integer mergeRequestId, String targetBranch, + public GitlabMergeRequest updateMergeRequest(Serializable projectId, Integer mergeRequestIid, String targetBranch, Integer assigneeId, String title, String description, String stateEvent, String labels) throws IOException { Query query = new Query() @@ -1583,27 +1789,29 @@ public GitlabMergeRequest updateMergeRequest(Serializable projectId, Integer mer .appendIf("state_event", stateEvent) .appendIf("labels", labels); - String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabMergeRequest.URL + "/" + mergeRequestId + query.toString(); + String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + + GitlabMergeRequest.URL + "/" + mergeRequestIid + query.toString(); return retrieve().method(PUT).to(tailUrl, GitlabMergeRequest.class); } /** * @param project The Project - * @param mergeRequestId Merge Request ID + * @param mergeRequestIid Merge Request internal ID * @param mergeCommitMessage optional merge commit message. Null if not set * @return new merge request status * @throws IOException on gitlab api call error */ - public GitlabMergeRequest acceptMergeRequest(GitlabProject project, Integer mergeRequestId, String mergeCommitMessage) throws IOException { - return acceptMergeRequest(project.getId(), mergeRequestId, mergeCommitMessage); + public GitlabMergeRequest acceptMergeRequest(GitlabProject project, Integer mergeRequestIid, String mergeCommitMessage) throws IOException { + return acceptMergeRequest(project.getId(), mergeRequestIid, mergeCommitMessage); } - public GitlabMergeRequest acceptMergeRequest(Serializable projectId, Integer mergeRequestId, String mergeCommitMessage) throws IOException { - String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabMergeRequest.URL + "/" + mergeRequestId + "/merge"; + public GitlabMergeRequest acceptMergeRequest(Serializable projectId, Integer mergeRequestIid, String mergeCommitMessage) throws IOException { + String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + + GitlabMergeRequest.URL + "/" + mergeRequestIid + "/merge"; GitlabHTTPRequestor requestor = retrieve().method(PUT); requestor.with("id", projectId); - requestor.with("merge_request_id", mergeRequestId); + requestor.with("merge_request_iid", mergeRequestIid); if (mergeCommitMessage != null) requestor.with("merge_commit_message", mergeCommitMessage); return requestor.to(tailUrl, GitlabMergeRequest.class); @@ -1617,7 +1825,8 @@ public GitlabMergeRequest acceptMergeRequest(Serializable projectId, Integer mer * @return the Gitlab Note * @throws IOException on gitlab api call error */ - public GitlabNote getNote(GitlabMergeRequest mergeRequest, Integer noteId) throws IOException { + public GitlabNote getNote(GitlabMergeRequest mergeRequest, + Integer noteId) throws IOException { String tailUrl = GitlabProject.URL + "/" + mergeRequest.getProjectId() + GitlabMergeRequest.URL + "/" + mergeRequest.getIid() + GitlabNote.URL + "/" + noteId; @@ -1642,6 +1851,263 @@ public List getAllNotes(GitlabMergeRequest mergeRequest) { return retrieve().getAll(tailUrl, GitlabNote[].class); } + /** + * Get a discussion by id from a merge request. + * https://docs.gitlab.com/ce/api/discussions.html#get-single-merge-request-discussion + * + * @param mergeRequest to fetch the discussion from. + * @param discussionId The id of the discussion. + * + * @return The GitLab discussion identified by the given id. + * @throws IOException on a GitLab api call error + */ + public GitlabDiscussion getDiscussion(GitlabMergeRequest mergeRequest, + int discussionId) throws IOException { + String tailUrl = GitlabProject.URL + "/" + mergeRequest.getProjectId() + + GitlabMergeRequest.URL + "/" + mergeRequest.getIid() + + GitlabDiscussion.URL + "/" + discussionId; + return retrieve().to(tailUrl, GitlabDiscussion.class); + } + + /** + * Get the discussions from a merge request. + * https://docs.gitlab.com/ce/api/discussions.html#list-project-merge-request-discussions + * + * @param mergeRequest to fetch the discussions from. + * + * @return The discussions contained in the given merge request. + * @throws IOException on a GitLab api call error + */ + public List getDiscussions(GitlabMergeRequest mergeRequest) throws IOException { + String tailUrl = GitlabProject.URL + "/" + mergeRequest.getProjectId() + + GitlabMergeRequest.URL + "/" + mergeRequest.getIid() + + GitlabDiscussion.URL; + + GitlabDiscussion[] discussions = retrieve().to(tailUrl, GitlabDiscussion[].class); + return Arrays.asList(discussions); + } + + /** + * Create a discussion just with the required arguments. + * + * @param mergeRequest The merge request where the discussion is created. + * @param body The content of a discussion. + * @param positionBaseSha The base commit SHA in the source branch. + * @param positionStartSha The SHA referencing the commit in the target branch. + * @param positionHeadSha The SHA referencing the HEAD of this merge request. + * + * @return The created discussion object. + * @throws IOException on a GitLab api call error + */ + public GitlabDiscussion createDiscussion(GitlabMergeRequest mergeRequest, + String body, String positionBaseSha, String positionStartSha, + String positionHeadSha) throws IOException { + return createTextDiscussion(mergeRequest, body, null, + positionBaseSha, positionStartSha, positionHeadSha, + null, null, null, null); + } + + /** + * Create a new discussion with position type text on the given merge request. + * https://docs.gitlab.com/ce/api/discussions.html#create-new-merge-request-discussion + * + * @param mergeRequest The merge request where the discussion is created. + * @param body The content of a discussion. + * @param position The position when creating a diff note. (hash) + * @param positionBaseSha The base commit SHA in the source branch. + * @param positionStartSha The SHA referencing the commit in the target branch. + * @param positionHeadSha The SHA referencing the HEAD of this merge request. + * @param positionNewPath The file path after the change. + * @param positionNewLine The Line number after change + * @param positionOldPath The file path before the change. + * @param positionOldLine The Line number before change. + * + * @return The created discussion object. + * @throws IOException on a GitLab api call error + */ + public GitlabDiscussion createTextDiscussion(GitlabMergeRequest mergeRequest, + String body, String position, String positionBaseSha, String positionStartSha, + String positionHeadSha, String positionNewPath, Integer positionNewLine, + String positionOldPath, Integer positionOldLine) throws IOException { + checkRequiredCreateDiscussionArguments(body, positionBaseSha, positionStartSha, positionHeadSha); + Query query = new Query() + .append("body", body) + .appendIf("position", position) + .append("position[base_sha]", positionBaseSha) + .append("position[start_sha]", positionStartSha) + .append("position[head_sha]", positionHeadSha) + .append("position[position_type]", "text") + .appendIf("position[new_path]", positionNewPath) + .appendIf("position[new_line]", positionNewLine) + .appendIf("position[old_path]", positionOldPath) + .appendIf("position[old_line]", positionOldLine); + + String tailUrl = GitlabProject.URL + "/" + mergeRequest.getProjectId() + + GitlabMergeRequest.URL + "/" + mergeRequest.getIid() + + GitlabDiscussion.URL + query.toString(); + + return dispatch().to(tailUrl, GitlabDiscussion.class); + } + + /** + * Create a new discussion with position type image on the given merge request. + * https://docs.gitlab.com/ce/api/discussions.html#create-new-merge-request-discussion + * + * @param mergeRequest The merge request where the discussion is created. + * @param body The content of a discussion. + * @param position The position when creating a diff note. (hash) + * @param positionBaseSha The base commit SHA in the source branch. + * @param positionStartSha The SHA referencing the commit in the target branch. + * @param positionHeadSha The SHA referencing the HEAD of this merge request. + * @param positionNewPath The file path after the change. + * @param positionOldPath The file path before the change. + * @param positionWidth The width of the image. + * @param positionHeight The height of the image. + * @param positionX The X coordinate. + * @param positionY The Y coordinate. + * + * @return The created discussion object. + * @throws IOException on a GitLab api call error + */ + public GitlabDiscussion createImageDiscussion( + GitlabMergeRequest mergeRequest, String body, String position, + String positionBaseSha, String positionStartSha, + String positionHeadSha, String positionNewPath, String positionOldPath, + Integer positionWidth, Integer positionHeight, Integer positionX, + Integer positionY + ) throws IOException { + checkRequiredCreateDiscussionArguments(body, positionBaseSha, positionStartSha, positionHeadSha); + Query query = new Query() + .append("body", body) + .appendIf("position", position) + .append("position[base_sha]", positionBaseSha) + .append("position[start_sha]", positionStartSha) + .append("position[head_sha]", positionHeadSha) + .append("position[position_type]", "image") + .appendIf("position[new_path]", positionNewPath) + .appendIf("position[old_path]", positionOldPath) + .appendIf("position[width]", positionWidth) + .appendIf("position[height]", positionHeight) + .appendIf("position[x]", positionX) + .appendIf("position[y]", positionY); + + String tailUrl = GitlabProject.URL + "/" + mergeRequest.getProjectId() + + GitlabMergeRequest.URL + "/" + mergeRequest.getIid() + + GitlabDiscussion.URL + query.toString(); + + return dispatch().to(tailUrl, GitlabDiscussion.class); + } + + /** + * Check if the required arguments to create a discussion are present and + * contain values. + * + * @param body The content of a discussion. + * @param positionBaseSha The base commit SHA in the source branch. + * @param positionStartSha The SHA referencing commit in target branch + * @param positionHeadSha The SHA referencing HEAD of this merge request + */ + private void checkRequiredCreateDiscussionArguments(String body, + String positionBaseSha, String positionStartSha, String positionHeadSha) { + if (body == null || body.isEmpty()) { + throw new IllegalArgumentException("Missing required argument 'body'!"); + } else if (positionBaseSha == null || positionBaseSha.isEmpty()) { + throw new IllegalArgumentException("Missing required argument 'positionBaseSha'!"); + } else if (positionStartSha == null || positionStartSha.isEmpty()) { + throw new IllegalArgumentException("Missing required argument 'positionStartSha'!"); + } else if (positionHeadSha == null || positionHeadSha.isEmpty()) { + throw new IllegalArgumentException("Missing required argument 'positionHeadSha'!"); + } + } + + /** + * Resolve or unresolve a whole discussion of a merge request. + * + * @param mergeRequest The merge request of the discussion. + * @param discussionId The id of the discussion to resolve. + * @param resolved Resolve or unresolve the note. + * + * @return The discussion object. + * @throws IOException on a GitLab api call error + */ + public GitlabDiscussion resolveDiscussion(GitlabMergeRequest mergeRequest, + int discussionId, boolean resolved) throws IOException { + String tailUrl = GitlabProject.URL + "/" + mergeRequest.getProjectId() + + GitlabMergeRequest.URL + "/" + mergeRequest.getIid() + + GitlabDiscussion.URL + "/" + discussionId; + return retrieve().method(PUT) + .with("resolved", resolved) + .to(tailUrl, GitlabDiscussion.class); + } + + /** + * Add a note to existing merge request discussion. + * + * @param mergeRequest The merge request of the discussion. + * @param discussionId The id of the discussion to add a note to. + * @param body The content of the discussion. + * + * @return The added note object. + * @throws IOException on a GitLab api call error + */ + public GitlabNote addDiscussionNote(GitlabMergeRequest mergeRequest, + int discussionId, String body) throws IOException { + String tailUrl = GitlabProject.URL + "/" + mergeRequest.getProjectId() + + GitlabMergeRequest.URL + "/" + mergeRequest.getIid() + + GitlabDiscussion.URL + "/" + discussionId + + GitlabNote.URL; + return dispatch().with("body", body).to(tailUrl, GitlabNote.class); + } + + /** + * Modify or resolve an existing discussion note of the given merge request. + * + * @param mergeRequest The merge request of the discussion. + * @param discussionId The id of the discussion to modify. + * @param noteId The id of the discussion note. + * @param body The content of the discussion. + * @param resolved Resolve or unresolve the note. + * + * @return The modified note object. + * @throws IOException on a GitLab api call error + */ + public GitlabNote modifyDiscussionNote(GitlabMergeRequest mergeRequest, int discussionId, + int noteId, String body, Boolean resolved) throws IOException { + boolean bodyHasValue = false; + if (body != null && !body.isEmpty()) { + bodyHasValue = true; + } + if ((!bodyHasValue && resolved == null) || (bodyHasValue && resolved != null)) { + throw new IllegalArgumentException("Exactly one of body or resolved must be set!"); + } + String tailUrl = GitlabProject.URL + "/" + mergeRequest.getProjectId() + + GitlabMergeRequest.URL + "/" + mergeRequest.getIid() + + GitlabDiscussion.URL + "/" + discussionId + + GitlabNote.URL + "/" + noteId; + return retrieve().method(PUT) + .with("body", body) + .with("resolved", resolved) + .to(tailUrl, GitlabNote.class); + } + + /** + * Delete a discussion note of a merge request. + * + * @param mergeRequest The merge request of the discussion. + * @param discussionId The id of the discussion to resolve. + * @param noteId The id of a discussion note. + * + * @return The deleted note object. + * @throws IOException on a GitLab api call error + */ + public void deleteDiscussionNote(GitlabMergeRequest mergeRequest, int discussionId, int noteId) throws IOException { + String tailUrl = GitlabProject.URL + "/" + mergeRequest.getProjectId() + + GitlabMergeRequest.URL + "/" + mergeRequest.getIid() + + GitlabDiscussion.URL + "/" + discussionId + + GitlabNote.URL + "/" + noteId; + retrieve().method(DELETE).to(tailUrl, Void.class); + } + // Get a specific commit identified by the commit hash or name of a branch or tag // GET /projects/:id/repository/commits/:sha public GitlabCommit getCommit(Serializable projectId, String commitHash) throws IOException { @@ -1659,13 +2125,9 @@ public List getCommits(GitlabMergeRequest mergeRequest, Pagination projectId = mergeRequest.getProjectId(); } - Query query = new Query() - .append("ref_name", mergeRequest.getSourceBranch()); - - query.mergeWith(pagination.asQuery()); - String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + - "/repository" + GitlabCommit.URL + query.toString(); + GitlabMergeRequest.URL + "/" + mergeRequest.getIid() + + GitlabCommit.URL + pagination.toString(); GitlabCommit[] commits = retrieve().to(tailUrl, GitlabCommit[].class); return Arrays.asList(commits); @@ -1681,7 +2143,7 @@ public List getLastCommits(Serializable projectId, String branchOr public List getCommits(Serializable projectId, Pagination pagination, String branchOrTag) throws IOException { - return getCommits(projectId, null, branchOrTag, null); + return getCommits(projectId, pagination, branchOrTag, null); } public List getCommits(Serializable projectId, Pagination pagination, @@ -2061,14 +2523,12 @@ public void unprotectBranch(GitlabProject project, String branchName) throws IOE public List getProjectHooks(Serializable projectId) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabProjectHook.URL; - GitlabProjectHook[] hooks = retrieve().to(tailUrl, GitlabProjectHook[].class); - return Arrays.asList(hooks); + return retrieve().getAll(tailUrl, GitlabProjectHook[].class); } public List getProjectHooks(GitlabProject project) throws IOException { String tailUrl = GitlabProject.URL + "/" + project.getId() + GitlabProjectHook.URL; - GitlabProjectHook[] hooks = retrieve().to(tailUrl, GitlabProjectHook[].class); - return Arrays.asList(hooks); + return retrieve().getAll(tailUrl, GitlabProjectHook[].class); } public GitlabProjectHook getProjectHook(GitlabProject project, String hookId) throws IOException { @@ -2092,7 +2552,7 @@ public GitlabProjectHook addProjectHook(GitlabProject project, String url, Strin .to(tailUrl, GitlabProjectHook.class); } - public GitlabProjectHook addProjectHook(Serializable projectId, String url, boolean pushEvents, boolean issuesEvents, boolean mergeRequestEvents, boolean noteEvents, boolean tagPushEvents, boolean sslVerification, String token) throws IOException { + public GitlabProjectHook addProjectHook(Serializable projectId, String url, boolean pushEvents, boolean issuesEvents, boolean mergeRequestEvents, boolean noteEvents, boolean tagPushEvents, boolean sslVerification, boolean jobEvents, boolean pipelineEvents, boolean wikiPageEvents, String token) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabProjectHook.URL; return dispatch() @@ -2103,18 +2563,46 @@ public GitlabProjectHook addProjectHook(Serializable projectId, String url, bool .with("note_events", noteEvents ? "true" : "false") .with("tag_push_events", tagPushEvents ? "true" : "false") .with("enable_ssl_verification", sslVerification ? "true" : "false") + .with("job_events", jobEvents ? "true" : "false") + .with("pipeline_events", pipelineEvents ? "true" : "false") + .with("wiki_page_events", wikiPageEvents ? "true" : "false") .with("token", token) .to(tailUrl, GitlabProjectHook.class); } - public GitlabProjectHook editProjectHook(GitlabProject project, String hookId, String url) throws IOException { - Query query = new Query() - .append("url", url); + public GitlabProjectHook addProjectHook(Serializable projectId, String url, GitlabProjectHook hook, String token) throws IOException { + return this.addProjectHook(projectId, url, hook.getPushEvents(), hook.getIssueEvents(), hook.isMergeRequestsEvents(), + hook.isNoteEvents(), hook.isTagPushEvents(), hook.isSslVerificationEnabled(), hook.isJobEvents(), + hook.isPipelineEvents(), hook.isWikiPageEvents(), token); + } + public GitlabProjectHook editProjectHook(GitlabProject project, String hookId, String url, + boolean pushEvents, boolean issuesEvents, boolean mergeRequestEvents, boolean noteEvents, + boolean tagPushEvents, boolean sslVerification, boolean jobEvents, boolean pipelineEvents, + boolean wikiPageEvents, String token) throws IOException { + Query query = new Query(); + query.append("url", url); + query.append("push_events", String.valueOf(pushEvents)); + query.append("issues_events", String.valueOf(issuesEvents)); + query.append("merge_request_events", String.valueOf(mergeRequestEvents)); + query.append("note_events", String.valueOf(noteEvents)); + query.append("tag_push_events", String.valueOf(tagPushEvents)); + query.append("enable_ssl_verification", String.valueOf(sslVerification)); + query.append("job_events", String.valueOf(jobEvents)); + query.append("pipeline_events", String.valueOf(pipelineEvents)); + query.append("wiki_page_events", String.valueOf(wikiPageEvents)); + query.append("token", token); String tailUrl = GitlabProject.URL + "/" + project.getId() + GitlabProjectHook.URL + "/" + hookId + query.toString(); return retrieve().method(PUT).to(tailUrl, GitlabProjectHook.class); } + public GitlabProjectHook editProjectHook(GitlabProject project, GitlabProjectHook projectHook, String token) throws IOException { + return editProjectHook(project, projectHook.getId(), projectHook.getUrl(), projectHook.getPushEvents(), + projectHook.getIssueEvents(), projectHook.isMergeRequestsEvents(), projectHook.isNoteEvents(), + projectHook.isTagPushEvents(), projectHook.isSslVerificationEnabled(), projectHook.isJobEvents(), + projectHook.isWikiPageEvents(), projectHook.isPipelineEvents(), token); + } + public void deleteProjectHook(GitlabProjectHook hook) throws IOException { String tailUrl = GitlabProject.URL + "/" + hook.getProjectId() + GitlabProjectHook.URL + "/" + hook.getId(); retrieve().method(DELETE).to(tailUrl, Void.class); @@ -2221,7 +2709,7 @@ public GitlabNote createNote(Serializable projectId, Integer issueId, String mes } public GitlabNote createNote(GitlabIssue issue, String message) throws IOException { - return createNote(String.valueOf(issue.getProjectId()), issue.getId(), message); + return createNote(String.valueOf(issue.getProjectId()), issue.getIid(), message); } /** @@ -2250,6 +2738,162 @@ public void deleteNote(GitlabIssue issue, GitlabNote noteToDelete) throws IOExce deleteNote(String.valueOf(issue.getProjectId()), issue.getId(), noteToDelete); } + /** + * Get project badges + * + * @param projectId The id of the project for which the badges should be retrieved + * @return The list of badges + * + * @throws IOException on GitLab API call error + */ + public List getProjectBadges(Serializable projectId) throws IOException { + String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBadge.URL; + return Arrays.asList(retrieve().to(tailUrl, GitlabBadge[].class)); + } + + /** + * Get project badge + * + * @param projectId The id of the project for which the badge should be retrieved + * @param badgeId The id of the badge that should be retrieved + * @return The badge with a given id + * + * @throws IOException on GitLab API call error + */ + public GitlabBadge getProjectBadge(Serializable projectId, Integer badgeId) throws IOException { + String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBadge.URL + + "/" + badgeId; + return retrieve().to(tailUrl, GitlabBadge.class); + } + + /** + * Add project badge + * + * @param projectId The id of the project for which the badge should be added + * @param linkUrl The URL that the badge should link to + * @param imageUrl The URL to the badge image + * @return The created badge + * + * @throws IOException on GitLab API call error + */ + public GitlabBadge addProjectBadge(Serializable projectId, String linkUrl, String imageUrl) throws IOException { + String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBadge.URL; + return dispatch().with("link_url", linkUrl) + .with("image_url", imageUrl) + .to(tailUrl, GitlabBadge.class); + } + + /** + * Edit project badge + * + * @param projectId The id of the project for which the badge should be edited + * @param badgeId The id of the badge that should be edited + * @param linkUrl The URL that the badge should link to + * @param imageUrl The URL to the badge image + * @return The updated badge + * + * @throws IOException on GitLab API call error + */ + public GitlabBadge editProjectBadge(Serializable projectId, Integer badgeId, String linkUrl, String imageUrl) throws IOException { + String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBadge.URL + + "/" + badgeId; + GitlabHTTPRequestor requestor = retrieve().method(PUT); + requestor.with("link_url", linkUrl) + .with("image_url", imageUrl); + return requestor.to(tailUrl, GitlabBadge.class); + } + + /** + * Delete project badge + * + * @param projectId The id of the project for which the badge should be deleted + * @param badgeId The id of the badge that should be deleted + * @throws IOException on GitLab API call error + */ + public void deleteProjectBadge(Serializable projectId, Integer badgeId) throws IOException { + String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBadge.URL + + "/" + badgeId; + retrieve().method(DELETE).to(tailUrl, Void.class); + } + + /** + * Get project badges + * + * @param groupId The id of the group for which the badges should be retrieved + * @return The list of badges + * + * @throws IOException on GitLab API call error + */ + public List getGroupBadges(Integer groupId) throws IOException { + String tailUrl = GitlabGroup.URL + "/" + groupId + GitlabBadge.URL; + return Arrays.asList(retrieve().to(tailUrl, GitlabBadge[].class)); + } + + /** + * Get group badge + * + * @param groupId The id of the group for which the badge should be retrieved + * @param badgeId The id of the badge that should be retrieved + * @return The badge with a given id + * + * @throws IOException on GitLab API call error + */ + public GitlabBadge getGroupBadge(Integer groupId, Integer badgeId) throws IOException { + String tailUrl = GitlabGroup.URL + "/" + groupId + GitlabBadge.URL + + "/" + badgeId; + return retrieve().to(tailUrl, GitlabBadge.class); + } + + /** + * Add group badge + * + * @param groupId The id of the group for which the badge should be added + * @param linkUrl The URL that the badge should link to + * @param imageUrl The URL to the badge image + * @return The created badge + * + * @throws IOException on GitLab API call error + */ + public GitlabBadge addGroupBadge(Integer groupId, String linkUrl, String imageUrl) throws IOException { + String tailUrl = GitlabGroup.URL + "/" + groupId + GitlabBadge.URL; + return dispatch().with("link_url", linkUrl) + .with("image_url", imageUrl) + .to(tailUrl, GitlabBadge.class); + } + + /** + * Edit group badge + * + * @param groupId The id of the group for which the badge should be edited + * @param badgeId The id of the badge that should be edited + * @param linkUrl The URL that the badge should link to + * @param imageUrl The URL to the badge image + * @return The updated badge + * + * @throws IOException on GitLab API call error + */ + public GitlabBadge editGroupBadge(Integer groupId, Integer badgeId, String linkUrl, String imageUrl) throws IOException { + String tailUrl = GitlabGroup.URL + "/" + groupId + GitlabBadge.URL + + "/" + badgeId; + GitlabHTTPRequestor requestor = retrieve().method(PUT); + requestor.with("link_url", linkUrl) + .with("image_url", imageUrl); + return requestor.to(tailUrl, GitlabBadge.class); + } + + /** + * Delete group badge + * + * @param groupId The id of the group for which the badge should be deleted + * @param badgeId The id of the badge that should be deleted + * @throws IOException on GitLab API call error + */ + public void deleteGroupBadge(Integer groupId, Integer badgeId) throws IOException { + String tailUrl = GitlabGroup.URL + "/" + groupId + GitlabBadge.URL + + "/" + badgeId; + retrieve().method(DELETE).to(tailUrl, Void.class); + } + /** * Gets labels associated with a project. * @@ -2652,8 +3296,9 @@ public List getNamespaceMembers(Integer namespaceId) throws * @throws IOException on gitlab api call error */ public void transfer(Integer namespaceId, Integer projectId) throws IOException { - String tailUrl = GitlabGroup.URL + "/" + namespaceId + GitlabProject.URL + "/" + projectId; - dispatch().to(tailUrl, Void.class); + Query query = new Query().append("namespace", String.valueOf(namespaceId)); + String tailUrl = GitlabProject.URL + "/" + projectId + "/transfer" + query.toString(); + retrieve().method(PUT).to(tailUrl, Void.class); } /** @@ -2791,7 +3436,7 @@ private String sanitizeId(Serializable id, String parameterName) { private String sanitizePath(String branch) { try { - return URLEncoder.encode(branch, "UTF-8"); + return URLEncoder.encode(branch, "UTF-8").replaceAll("\\+", "%20"); } catch (UnsupportedEncodingException e) { throw new RuntimeException((e)); } @@ -2863,6 +3508,19 @@ public List getTags(GitlabProject project) { return retrieve().getAll(tailUrl, GitlabTag[].class); } + /** + * Get a single repository tag in a specific project + * + * @param project (required) The ID or URL-encoded path of the project + * @param tagName (required) The name of the tag + * @return the found git tag object + * @throws IOException on gitlab api call error + */ + public GitlabTag getTag(GitlabProject project, String tagName) throws IOException { + String tailUrl = GitlabProject.URL + "/" + project.getId() + GitlabTag.URL + "/" + tagName; + return retrieve().to(tailUrl, GitlabTag.class); + } + /** * Create tag in specific project * @@ -3491,4 +4149,107 @@ public GitlabRunner getRunnerDetail(int id) throws IOException { String tailUrl = String.format("%s/%d", GitlabRunner.URL, id); return retrieve().to(tailUrl, GitlabRunner.class); } + + /** + * Get events for a project. + * + * @param action If not null, include only events of a particular action type + * @param targetType If not null, include only events of a particular target type + * @param before If not null, include only events created before a particular date. + * @param after If not null, include only events created before a + * particular date. + * @param sortOrder If null, uses the server's default, which is "desc" + */ + public List getEvents(GitlabProject project, + GitlabEvent.ActionType action, + GitlabEvent.TargetType targetType, + GitlabDate before, + GitlabDate after, + SortOrder sortOrder) + throws IOException { + return getEvents(project, action, targetType, before, + after, sortOrder, new Pagination()); + } + + /** + * Get events for a project. + * + * @param action If not null, include only events of a particular action type + * @param targetType If not null, include only events of a particular target type + * @param before If not null, include only events created before a particular date. + * @param after If not null, include only events created before a + * particular date. + * @param sortOrder If null, uses the server's default, which is "desc" + */ + public List getEvents(GitlabProject project, + GitlabEvent.ActionType action, + GitlabEvent.TargetType targetType, + GitlabDate before, + GitlabDate after, + SortOrder sortOrder, + Pagination pagination) + throws IOException { + return getProjectEvents(project.getId(), action, targetType, before, + after, sortOrder, pagination); + } + + /** + * Get events for a project. + * + * @param action If not null, include only events of a particular action type + * @param targetType If not null, include only events of a particular target type + * @param before If not null, include only events created before a particular date. + * @param after If not null, include only events created before a + * particular date. + * @param sort If null, uses the server's default, which is "desc" + */ + public List getProjectEvents(Serializable projectId, + GitlabEvent.ActionType action, + GitlabEvent.TargetType targetType, + GitlabDate before, + GitlabDate after, + SortOrder sort) + throws IOException { + return getProjectEvents(projectId, action, targetType, before, + after, sort, new Pagination()); + } + + /** + * Get events for a project. + * + * @param action If not null, include only events of a particular action type + * @param targetType If not null, include only events of a particular target type + * @param before If not null, include only events created before a particular date. + * @param after If not null, include only events created before a + * particular date. + * @param sort If null, uses the server's default, which is "desc" + */ + public List getProjectEvents(Serializable projectId, + GitlabEvent.ActionType action, + GitlabEvent.TargetType targetType, + GitlabDate before, + GitlabDate after, + SortOrder sort, + Pagination pagination) + throws IOException { + + final Query query = new Query(); + query.appendIf("action", action); + query.appendIf("target_type", targetType); + query.appendIf("before", before); + query.appendIf("after", after); + query.appendIf("sort", sort); + + if (pagination != null) { + query.mergeWith(pagination.asQuery()); + } + + StringBuilder tailUrl = new StringBuilder(GitlabProject.URL) + .append("/") + .append(sanitizeProjectId(projectId)) + .append(GitlabEvent.URL) + .append(query.toString()); + + return Arrays.asList(retrieve().method(GET).to(tailUrl.toString(), GitlabEvent[].class)); + } } diff --git a/src/main/java/org/gitlab/api/Pagination.java b/src/main/java/org/gitlab/api/Pagination.java index b7084529..20be0d27 100644 --- a/src/main/java/org/gitlab/api/Pagination.java +++ b/src/main/java/org/gitlab/api/Pagination.java @@ -1,48 +1,44 @@ package org.gitlab.api; import org.gitlab.api.http.Query; +import org.gitlab.api.query.PaginationQuery; -import java.io.UnsupportedEncodingException; +/** + * @deprecated Use {@link PaginationQuery#PARAM_PAGE} instead. + */ +@Deprecated +public class Pagination extends PaginationQuery { -public class Pagination { - public static final String PARAM_PAGE = "page"; - public static final String PARAM_PER_PAGE = "per_page"; - public static final int MAX_ITEMS_PER_PAGE = 100; - private final Query paginationQuery = new Query(); + /** + * @deprecated Use {@link PaginationQuery#PARAM_PAGE} instead. + */ + @Deprecated + public static final String PARAM_PAGE = PaginationQuery.PARAM_PAGE; - public void setPage(int page) { - try { - paginationQuery.append(PARAM_PAGE, String.valueOf(page)); - } catch (UnsupportedEncodingException ignored) { - } - } + /** + @deprecated Use {@link PaginationQuery#PARAM_PER_PAGE} instead. + */ + @Deprecated + public static final String PARAM_PER_PAGE = PaginationQuery.PARAM_PER_PAGE; + + /** + @deprecated Use {@link PaginationQuery#MAX_ITEMS_PER_PAGE} instead. + */ + @Deprecated + public static final int MAX_ITEMS_PER_PAGE = PaginationQuery.MAX_ITEMS_PER_PAGE; - public void setPerPage(int perPage) { - if (perPage > MAX_ITEMS_PER_PAGE) { - throw new IllegalArgumentException("Max value for perPage is " + MAX_ITEMS_PER_PAGE); - } - try { - paginationQuery.append(PARAM_PER_PAGE, String.valueOf(perPage)); - } catch (UnsupportedEncodingException ignored) { - } - } - public Pagination withPage(int page) { setPage(page); return this; } - + public Pagination withPerPage(int perPage) { setPerPage(perPage); return this; } public Query asQuery() { - return paginationQuery; + return this; } - @Override - public String toString() { - return paginationQuery.toString(); - } } diff --git a/src/main/java/org/gitlab/api/http/GitlabHTTPRequestor.java b/src/main/java/org/gitlab/api/http/GitlabHTTPRequestor.java index 0b2a2a65..ebe80573 100644 --- a/src/main/java/org/gitlab/api/http/GitlabHTTPRequestor.java +++ b/src/main/java/org/gitlab/api/http/GitlabHTTPRequestor.java @@ -10,6 +10,7 @@ import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; +import java.io.UncheckedIOException; import java.lang.reflect.Field; import java.net.*; import java.util.*; @@ -188,7 +189,7 @@ public Iterator asIterator(final String tailApiUrl, final Class type) try { url = root.getAPIUrl(tailApiUrl); } catch (IOException e) { - throw new RuntimeException(e); + throw new UncheckedIOException(e); } } @@ -240,7 +241,7 @@ private void fetch() { handleAPIError(e, connection); } } catch (IOException e) { - throw new RuntimeException(e); + throw new UncheckedIOException(e); } } @@ -261,7 +262,7 @@ private void findNextUrl() throws MalformedURLException { } else { // Since the page query was not present, its safe to assume that we just // currently used the first page, so we can default to page 2 - this.url = new URL(url + (url.indexOf('?') > 0 ? '&' : '?') + "&page=2"); + this.url = new URL(url + (url.indexOf('?') > 0 ? '&' : '?') + "page=2"); } } }; diff --git a/src/main/java/org/gitlab/api/http/Query.java b/src/main/java/org/gitlab/api/http/Query.java index 521c493c..ad8db9a0 100644 --- a/src/main/java/org/gitlab/api/http/Query.java +++ b/src/main/java/org/gitlab/api/http/Query.java @@ -51,39 +51,7 @@ public Query append(final String name, final String value) throws UnsupportedEnc * @return this * @throws java.io.UnsupportedEncodingException If the provided value cannot be URL Encoded */ - public Query appendIf(final String name, final String value) throws UnsupportedEncodingException { - if (value != null) { - append(name, value); - } - return this; - } - - /** - * Conditionally append a parameter to the query - * if the value of the parameter is not null - * - * @param name Parameter name - * @param value Parameter value - * @return this - * @throws java.io.UnsupportedEncodingException If the provided value cannot be URL Encoded - */ - public Query appendIf(final String name, final Integer value) throws UnsupportedEncodingException { - if (value != null) { - append(name, value.toString()); - } - return this; - } - - /** - * Conditionally append a parameter to the query - * if the value of the parameter is not null - * - * @param name Parameter name - * @param value Parameter value - * @return this - * @throws java.io.UnsupportedEncodingException If the provided value cannot be URL Encoded - */ - public Query appendIf(final String name, final Boolean value) throws UnsupportedEncodingException { + public Query appendIf(final String name, final T value) throws UnsupportedEncodingException { if (value != null) { append(name, value.toString()); } diff --git a/src/main/java/org/gitlab/api/jackson/InstantDeserializer.java b/src/main/java/org/gitlab/api/jackson/InstantDeserializer.java new file mode 100644 index 00000000..5663826a --- /dev/null +++ b/src/main/java/org/gitlab/api/jackson/InstantDeserializer.java @@ -0,0 +1,80 @@ +package org.gitlab.api.jackson; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; + +import java.io.IOException; +import java.time.Instant; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeFormatterBuilder; +import java.time.format.DateTimeParseException; +import java.time.format.FormatStyle; +import java.util.Locale; +import java.util.Objects; +import java.util.stream.Stream; + +/** + * A spezialized {@link Instant} deserializer that can parse different formats. + */ +public class InstantDeserializer extends StdDeserializer { + + private static final DateTimeFormatter LOCAL_DATE_TIME_FORMATTER_WITH_SPACE_SEPARATOR = new DateTimeFormatterBuilder() + .parseCaseInsensitive() + .append(DateTimeFormatter.ISO_LOCAL_DATE) + .appendLiteral(' ') + .append(DateTimeFormatter.ISO_LOCAL_TIME) + .toFormatter(Locale.getDefault(Locale.Category.FORMAT)); + + public InstantDeserializer() { + super(Instant.class); + } + + @Override + public Instant deserialize(JsonParser parser, DeserializationContext context) throws IOException { + if (JsonToken.VALUE_NULL.equals(parser.getCurrentToken())) { + return null; + } + + final String text = parser.getText(); + + if (null == text || text.trim().isEmpty()) { + return null; + } + + return getFormatters() + .map(formatter -> { + try { + return formatter.parse(text, Instant::from); + } catch (DateTimeParseException e) { + return null; + } + }) + .filter(Objects::nonNull) + .findFirst() + .orElseThrow(() -> new JsonParseException("Unable to parse instant \"" + text + "\"", parser.getCurrentLocation())); + } + + private static Stream getFormatters() { + return Stream.of( + // English (Standard) Formats + DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG, FormatStyle.LONG).withLocale(Locale.ENGLISH), + DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.LONG).withLocale(Locale.ENGLISH), + DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.LONG).withLocale(Locale.ENGLISH), + DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG, FormatStyle.MEDIUM).withLocale(Locale.ENGLISH), + DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.MEDIUM).withLocale(Locale.ENGLISH), + DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.MEDIUM).withLocale(Locale.ENGLISH), + DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG, FormatStyle.SHORT).withLocale(Locale.ENGLISH), + DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT).withLocale(Locale.ENGLISH), + DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.SHORT).withLocale(Locale.ENGLISH), + + // ISO Formats + LOCAL_DATE_TIME_FORMATTER_WITH_SPACE_SEPARATOR, + DateTimeFormatter.ISO_LOCAL_DATE_TIME, + DateTimeFormatter.ISO_DATE_TIME + ); + } + +} diff --git a/src/main/java/org/gitlab/api/models/GitlabBadge.java b/src/main/java/org/gitlab/api/models/GitlabBadge.java new file mode 100644 index 00000000..7de3f1a6 --- /dev/null +++ b/src/main/java/org/gitlab/api/models/GitlabBadge.java @@ -0,0 +1,70 @@ +package org.gitlab.api.models; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @author Olga Maciaszek-Sharma + */ +public class GitlabBadge { + + public static final String URL = "/badges"; + + private Integer id; + @JsonProperty("link_url") + private String linkUrl; + @JsonProperty("image_url") + private String imageUrl; + @JsonProperty("rendered_link_url") + private String renderedLinkUrl; + @JsonProperty("rendered_image_url") + private String renderedImageUrl; + private String kind; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getLinkUrl() { + return linkUrl; + } + + public void setLinkUrl(String linkUrl) { + this.linkUrl = linkUrl; + } + + public String getImageUrl() { + return imageUrl; + } + + public void setImageUrl(String imageUrl) { + this.imageUrl = imageUrl; + } + + public String getRenderedLinkUrl() { + return renderedLinkUrl; + } + + public void setRenderedLinkUrl(String renderedLinkUrl) { + this.renderedLinkUrl = renderedLinkUrl; + } + + public String getRenderedImageUrl() { + return renderedImageUrl; + } + + public void setRenderedImageUrl(String renderedImageUrl) { + this.renderedImageUrl = renderedImageUrl; + } + + public String getKind() { + return kind; + } + + public void setKind(String kind) { + this.kind = kind; + } +} diff --git a/src/main/java/org/gitlab/api/models/GitlabBuildVariable.java b/src/main/java/org/gitlab/api/models/GitlabBuildVariable.java index e7e202f6..e26b9601 100644 --- a/src/main/java/org/gitlab/api/models/GitlabBuildVariable.java +++ b/src/main/java/org/gitlab/api/models/GitlabBuildVariable.java @@ -14,6 +14,13 @@ public GitlabBuildVariable() { public GitlabBuildVariable(String key, String value) { this.key = key; this.value = value; + this.variableType = VariableType.env_var; + } + + public GitlabBuildVariable(String key, String value, VariableType variableType) { + this.key = key; + this.value = value; + this.variableType = variableType; } @JsonProperty("key") @@ -22,6 +29,9 @@ public GitlabBuildVariable(String key, String value) { @JsonProperty("value") private String value; + @JsonProperty("variable_type") + private VariableType variableType; + public String getKey() { return key; } @@ -37,4 +47,18 @@ public String getValue() { public void setValue(String value) { this.value = value; } + + public VariableType getVariableType() { + return variableType; + } + + public void setVariableType(VariableType variableType) { + this.variableType = variableType; + } + + public enum VariableType { + env_var, + file + } + } diff --git a/src/main/java/org/gitlab/api/models/GitlabDate.java b/src/main/java/org/gitlab/api/models/GitlabDate.java new file mode 100644 index 00000000..43b2e845 --- /dev/null +++ b/src/main/java/org/gitlab/api/models/GitlabDate.java @@ -0,0 +1,55 @@ +package org.gitlab.api.models; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Date; +import java.util.List; + +/** + * A date, with no time or timezone. This is, given the lack of + * timezone, an object whose meaning is somewhat ill-defined, but we + * must use the API that the hexarchs^W^W Gitlab gives us. We're + * going to make this immutable, because that's less error-prone. And + * we won't provide a constructor from Date, because Date is an + * instant in time rather than a calendar period. + */ +public final class GitlabDate { + private int year; + private int month; + private int day; + + /** + * @param month and day are 1-based. + */ + public GitlabDate(int year, int month, int day) { + this.year = year; + this.month = month; + this.day = day; + } + + public int getYear() { + return year; + } + + public int getMonth() { + return month; + } + public int getDay() { + return day; + } + + public String toString() { + // Gitlab requires this specific format + return String.format("%04d-%02d-%02d", year, month, day); + } + + public int hashCode() { + return this.year * 31 * 12 + this.month * 31 + this.day; + } + + public boolean equals(Object o) { + if (o == null || getClass() != o.getClass()) return false; + GitlabDate that = (GitlabDate) o; + return this.year == that.year && this.month == that.month && this.day == that.day; + } +} diff --git a/src/main/java/org/gitlab/api/models/GitlabDiscussion.java b/src/main/java/org/gitlab/api/models/GitlabDiscussion.java new file mode 100644 index 00000000..5b4b6887 --- /dev/null +++ b/src/main/java/org/gitlab/api/models/GitlabDiscussion.java @@ -0,0 +1,71 @@ +package org.gitlab.api.models; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * A class representing a GitLab discussion. A discussion is a collection of + * notes. + * + * @author Patrizio Bonzani + */ +public class GitlabDiscussion { + + public static final String URL = "/discussions"; + + /** + * The ID of a discussion. + */ + private String id; + + /** + * The notes contained in this discussion. + */ + private List notes = new ArrayList(); + + @JsonProperty("individual_note") + private boolean individualNote; + + @SuppressWarnings("unused") + private GitlabDiscussion() {} + + public GitlabDiscussion(String id) { + this.id = id; + } + + /** + * Get the id of this discussion. + * + * @return The id of the discussion. + */ + public String getId() { + return id; + } + + /** + * Get the notes of this discussion. + * + * @return The notes contained in this discussion. + */ + public List getNotes() { + return Collections.unmodifiableList(notes); + } + + /** + * Add a note to the discussion. + * + * @param note The note to add to the discussion. + * @return true (as specified by {@link Collection#add}) + */ + public boolean addNote(GitlabNote note) { + return notes.add(note); + } + + public boolean isIndividualNote() { + return individualNote; + } +} diff --git a/src/main/java/org/gitlab/api/models/GitlabEvent.java b/src/main/java/org/gitlab/api/models/GitlabEvent.java new file mode 100644 index 00000000..640a8f66 --- /dev/null +++ b/src/main/java/org/gitlab/api/models/GitlabEvent.java @@ -0,0 +1,185 @@ +package org.gitlab.api.models; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Date; +import java.util.List; + +public class GitlabEvent { + + public final static String URL = "/events"; + + private String title; + + @JsonProperty("project_id") + private String projectId; + + @JsonProperty("action_name") + private String actionName; + + // nullable + @JsonProperty("target_id") + private Integer targetId; + + // nullable + @JsonProperty("target_iid") + private Integer targetIid; + + @JsonProperty("target_type") + private TargetType targetType; + + // It's not clear if this is nullable + @JsonProperty("author_id") + private Integer authorId; + + // nullable + @JsonProperty("target_title") + private String targetTitle; + + @JsonProperty("created_at") + private Date createdAt; + + // see above re "author" + private GitlabUser author; + + // see above re "author" + @JsonProperty("author_username") + private String authorUsername; + + @JsonProperty("push_data") + private GitlabPushData pushData; + + public String getTitle() { + return title; + } + + public String getProjectId() { + return projectId; + } + + /** + * It would be reasonable to expect that this matches up with + * ActionType, below, but it doesn't. The action type "pushed" is + * spelled "pushed to" in action_name (but it's spelled "pushed" + * in GitlabPushData). + */ + public String getActionName() { + return actionName; + } + + public Integer getTargetId() { + return targetId; + } + + public Integer getTargetIid() { + return targetIid; + } + + public TargetType getTargetType() { + return targetType; + } + + /** See() {@link #getAuthor()} for note */ + public Integer getAuthorId() { + return authorId; + } + + public String getTargetTitle() { + return targetTitle; + } + + public Date getCreatedAt() { + return createdAt; + } + + /** + * For many events, this seem to have nothing to do with any + * "author", but is in fact the user who performed the action. + * e.g. a push's "author" is not necessarily the author or + * committer of any commit, but the user doing the pushing. + */ + public GitlabUser getAuthor() { + return author; + } + + /** See {@link #getAuthor()} for note */ + public String getAuthorUsername() { + return authorUsername; + } + + public GitlabPushData getPushData() { + return pushData; + } + + public void setTitle(String title) { + this.title = title; + } + + public void setProjectId(String projectId) { + this.projectId = projectId; + } + + public void setActionName(String actionName) { + this.actionName = actionName; + } + + public void setTargetId(Integer targetId) { + this.targetId = targetId; + } + + public void setTargetIid(Integer targetIid) { + this.targetIid = targetIid; + } + + public void setTargetType(TargetType targetType) { + this.targetType = targetType; + } + + public void setAuthorId(Integer authorId) { + this.authorId = authorId; + } + + public void setTargetTitle(String targetTitle) { + this.targetTitle = targetTitle; + } + + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } + + public void setAuthor(GitlabUser author) { + this.author = author; + } + + public void setAuthorUsername(String authorUsername) { + this.authorUsername = authorUsername; + } + + public void setPushData(GitlabPushData pushData) { + this.pushData = pushData; + } + + public enum ActionType { + created, + updated, + closed, + reopened, + pushed, + commented, + merged, + joined, + left, + destroyed, + expired + } + + public enum TargetType { + issue, + milestone, + merge_request, + note, + project, + snippet, + user + } +} diff --git a/src/main/java/org/gitlab/api/models/GitlabIssue.java b/src/main/java/org/gitlab/api/models/GitlabIssue.java index de62fb5a..046fe609 100644 --- a/src/main/java/org/gitlab/api/models/GitlabIssue.java +++ b/src/main/java/org/gitlab/api/models/GitlabIssue.java @@ -4,8 +4,12 @@ import java.util.Date; import java.util.List; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; +@JsonIgnoreProperties(ignoreUnknown = true) public class GitlabIssue { public enum Action { @@ -41,6 +45,7 @@ public enum Action { @JsonProperty("downvotes") private Integer downVotes; + @JsonDeserialize(using = LocalDateDeserializer.class) @JsonProperty("due_date") private LocalDate dueDate; diff --git a/src/main/java/org/gitlab/api/models/GitlabMergeRequest.java b/src/main/java/org/gitlab/api/models/GitlabMergeRequest.java index 7663af17..11d037e5 100644 --- a/src/main/java/org/gitlab/api/models/GitlabMergeRequest.java +++ b/src/main/java/org/gitlab/api/models/GitlabMergeRequest.java @@ -10,7 +10,7 @@ public class GitlabMergeRequest { public static final String STATUS_OPENED = "opened"; public static final String STATUS_MERGED = "merged"; public static final String STATUS_CLOSED = "closed"; - + private Integer id; private Integer iid; private String title; @@ -23,10 +23,18 @@ public class GitlabMergeRequest { private GitlabMilestone milestone; private String[] labels; + private List changes; - private int upvotes; - private int downvotes; + private Integer upvotes; + + private Integer downvotes; + + @JsonProperty("updated_at") + private Date updatedAt; + + @JsonProperty("created_at") + private Date createdAt; @JsonProperty("target_branch") private String targetBranch; @@ -46,23 +54,64 @@ public class GitlabMergeRequest { @JsonProperty("milestone_id") private Integer milestoneId; - @JsonProperty("updated_at") - private Date updatedAt; + @JsonProperty("work_in_progress") + private Boolean workInProgress; - @JsonProperty("created_at") - private Date createdAt; + @JsonProperty("merge_when_pipeline_succeeds") + private Boolean mergeWhenPipelineSucceeds; - @JsonProperty("merge_commit_sha") - private String mergeCommitSHA; - @JsonProperty("merge_status") private String mergeStatus; + @JsonProperty("sha") + private String sha; + + @JsonProperty("merge_commit_sha") + private String mergeCommitSHA; + + @JsonProperty("user_notes_count") + private Integer userNotesCount; + + @JsonProperty("discussion_locked") + private Boolean discussionLocked; + + @JsonProperty("should_remove_source_branch") + private Boolean shouldRemoveSourceBranch; + + @JsonProperty("force_remove_source_branch") + private Boolean forceRemoveSourceBranch; + @JsonProperty("web_url") private String webUrl; - @JsonProperty("sha") - private String sha; + private Boolean squash; + + @JsonProperty("changes_count") + private String changesCount; + + @JsonProperty("merged_by") + private GitlabUser mergedBy; + + @JsonProperty("merged_at") + private Date mergedAt; + + @JsonProperty("closed_by") + private GitlabUser closedBy; + + @JsonProperty("closed_at") + private Date closedAt; + + @JsonProperty("latest_build_started_at") + private Date latestBuildStartedAt; + + @JsonProperty("latest_build_finished_at") + private Date latestBuildFinishedAt; + + @JsonProperty("first_deployed_to_production_at") + private Date firstDeployedToProductionAt; + + @JsonProperty("diff_refs") + private DiffRefs diffRefs; public Integer getId() { return id; @@ -202,7 +251,7 @@ public void setLabels(String[] labels) { this.labels = labels; } - public int getUpvotes() { + public Integer getUpvotes() { return upvotes; } @@ -210,7 +259,7 @@ public void setUpvotes(int upvotes) { this.upvotes = upvotes; } - public int getDownvotes() { + public Integer getDownvotes() { return downvotes; } @@ -281,4 +330,96 @@ public String getSha() { public void setSha(String sha) { this.sha = sha; } + + public Boolean isWorkInProgress() { + return workInProgress; + } + + + public Boolean isMergeWhenPipelineSucceeds() { + return mergeWhenPipelineSucceeds; + } + + public Integer getUserNotesCount() { + return userNotesCount; + } + + public Boolean isDiscussionLocked() { + return discussionLocked; + } + + public Boolean isShouldRemoveSourceBranch() { + return shouldRemoveSourceBranch; + } + + public Boolean isForceRemoveSourceBranch() { + return forceRemoveSourceBranch; + } + + public Boolean isSquash() { + return squash; + } + + public String getChangesCount() { + return changesCount; + } + + public GitlabUser getMergedBy() { + return mergedBy; + } + + public Date getMergedAt() { + return mergedAt; + } + + public GitlabUser getClosedBy() { + return closedBy; + } + + public Date getClosedAt() { + return closedAt; + } + + public Date getLatestBuildStartedAt() { + return latestBuildStartedAt; + } + + public Date getLatestBuildFinishedAt() { + return latestBuildFinishedAt; + } + + public Date getFirstDeployedToProductionAt() { + return firstDeployedToProductionAt; + } + + public String getBaseSha() { + return diffRefs == null ? null : diffRefs.baseSha; + } + + public String getHeadSha() { + return diffRefs == null ? null : diffRefs.headSha; + } + + public String getStartSha() { + return diffRefs == null ? null : diffRefs.startSha; + } + + /** + * Class representing the diff_refs json object, which is just a collection + * of sha references of the merge request. It is currently not provided by + * GitLab when fetching multiple merge requests. + * + * @author Patrizio Bonzani + */ + private static class DiffRefs { + + @JsonProperty("base_sha") + private String baseSha; + + @JsonProperty("head_sha") + private String headSha; + + @JsonProperty("start_sha") + private String startSha; + } } diff --git a/src/main/java/org/gitlab/api/models/GitlabMergeRequestApprovals.java b/src/main/java/org/gitlab/api/models/GitlabMergeRequestApprovals.java index 84069fed..81c6c991 100644 --- a/src/main/java/org/gitlab/api/models/GitlabMergeRequestApprovals.java +++ b/src/main/java/org/gitlab/api/models/GitlabMergeRequestApprovals.java @@ -9,6 +9,7 @@ public class GitlabMergeRequestApprovals { public static final String URL = "/approvals"; + public static final String APPROVERS_URL = "/approvers"; private Integer id; private Integer iid; @@ -39,6 +40,10 @@ public class GitlabMergeRequestApprovals { @JsonProperty("suggested_approvers") private List suggestedApprovers; + private List approvers; + + @JsonProperty("approver_groups") + private List approverGroups; public Integer getId() { return id; @@ -135,7 +140,7 @@ public List getApprovedBy() { public void setApprovedBy(List approvedBy) { this.approvedBy = approvedBy; } - + public List getSuggestedApprovers() { return suggestedApprovers; } @@ -143,4 +148,21 @@ public List getSuggestedApprovers() { public void setSuggestedApprovers(List suggestedApprovers) { this.suggestedApprovers = suggestedApprovers; } + + public List getApprovers() { + return approvers; + } + + public void setApprovers(List approvers) { + this.approvers = approvers; + } + + public List getApproverGroups() { + return approverGroups; + } + + public void setApproverGroups(List approverGroups) { + this.approverGroups = approverGroups; + } + } diff --git a/src/main/java/org/gitlab/api/models/GitlabPipeline.java b/src/main/java/org/gitlab/api/models/GitlabPipeline.java index 31927db5..c2f55b95 100644 --- a/src/main/java/org/gitlab/api/models/GitlabPipeline.java +++ b/src/main/java/org/gitlab/api/models/GitlabPipeline.java @@ -1,23 +1,73 @@ package org.gitlab.api.models; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import org.gitlab.api.jackson.InstantDeserializer; + +import java.time.Instant; public class GitlabPipeline { public static final String URL = "/pipelines"; + public static final String CREATE_URL = "/pipeline"; + @JsonProperty("id") private Integer id; - @JsonProperty("ref") - private String ref; - @JsonProperty("sha") private String sha; + @JsonProperty("ref") + private String ref; + @JsonProperty("status") private String status; + @JsonProperty("web_url") + private String webUrl; + + @JsonProperty("before_sha") + private String beforeSha; + + @JsonProperty("tag") + private boolean tag; + + @JsonProperty("yaml_errors") + private String yamlErrors; + + @JsonProperty("user") + private GitlabUser user; + + @JsonProperty("created_at") + @JsonDeserialize(using = InstantDeserializer.class) + private Instant createdAt; + + @JsonProperty("updated_at") + @JsonDeserialize(using = InstantDeserializer.class) + private Instant updatedAt; + + @JsonProperty("started_at") + @JsonDeserialize(using = InstantDeserializer.class) + private Instant startedAt; + + @JsonProperty("finished_at") + @JsonDeserialize(using = InstantDeserializer.class) + private Instant finishedAt; + + @JsonProperty("committed_at") + @JsonDeserialize(using = InstantDeserializer.class) + private Instant committedAt; + + @JsonProperty("duration") + private int duration; + + @JsonProperty("coverage") + private String coverage; + + @JsonProperty("detailed_status") + private DetailedStatus detailedStatus; + public Integer getId() { return id; } @@ -26,14 +76,6 @@ public void setId(Integer id) { this.id = id; } - public String getRef() { - return ref; - } - - public void setRef(String ref) { - this.ref = ref; - } - public String getSha() { return sha; } @@ -42,6 +84,14 @@ public void setSha(String sha) { this.sha = sha; } + public String getRef() { + return ref; + } + + public void setRef(String ref) { + this.ref = ref; + } + public String getStatus() { return status; } @@ -49,4 +99,205 @@ public String getStatus() { public void setStatus(String status) { this.status = status; } + + public String getWebUrl() { + return webUrl; + } + + public void setWebUrl(String webUrl) { + this.webUrl = webUrl; + } + + public String getBeforeSha() { + return beforeSha; + } + + public void setBeforeSha(String beforeSha) { + this.beforeSha = beforeSha; + } + + public boolean isTag() { + return tag; + } + + public void setTag(boolean tag) { + this.tag = tag; + } + + public String getYamlErrors() { + return yamlErrors; + } + + public void setYamlErrors(String yamlErrors) { + this.yamlErrors = yamlErrors; + } + + public GitlabUser getUser() { + return user; + } + + public void setUser(GitlabUser user) { + this.user = user; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public Instant getStartedAt() { + return startedAt; + } + + public void setStartedAt(Instant startedAt) { + this.startedAt = startedAt; + } + + public Instant getFinishedAt() { + return finishedAt; + } + + public void setFinishedAt(Instant finishedAt) { + this.finishedAt = finishedAt; + } + + public Instant getCommittedAt() { + return committedAt; + } + + public void setCommittedAt(Instant committedAt) { + this.committedAt = committedAt; + } + + public int getDuration() { + return duration; + } + + public void setDuration(int duration) { + this.duration = duration; + } + + public String getCoverage() { + return coverage; + } + + public void setCoverage(String coverage) { + this.coverage = coverage; + } + + public DetailedStatus getDetailedStatus() { + return detailedStatus; + } + + public void setDetailedStatus(DetailedStatus detailedStatus) { + this.detailedStatus = detailedStatus; + } + + public static class DetailedStatus { + + private String icon; + + private String text; + + private String label; + + private String group; + + private String tooltip; + + @JsonProperty("has_details") + private String hasDetails; + + @JsonProperty("details_path") + private String detailsPath; + + private String illustration; + + private String favicon; + + public String getIcon() { + return icon; + } + + public void setIcon(String icon) { + this.icon = icon; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getGroup() { + return group; + } + + public void setGroup(String group) { + this.group = group; + } + + public String getTooltip() { + return tooltip; + } + + public void setTooltip(String tooltip) { + this.tooltip = tooltip; + } + + public String getHasDetails() { + return hasDetails; + } + + public void setHasDetails(String hasDetails) { + this.hasDetails = hasDetails; + } + + public String getDetailsPath() { + return detailsPath; + } + + public void setDetailsPath(String detailsPath) { + this.detailsPath = detailsPath; + } + + public String getIllustration() { + return illustration; + } + + public void setIllustration(String illustration) { + this.illustration = illustration; + } + + public String getFavicon() { + return favicon; + } + + public void setFavicon(String favicon) { + this.favicon = favicon; + } + + } + } diff --git a/src/main/java/org/gitlab/api/models/GitlabProject.java b/src/main/java/org/gitlab/api/models/GitlabProject.java index 33fb923c..a245d23b 100644 --- a/src/main/java/org/gitlab/api/models/GitlabProject.java +++ b/src/main/java/org/gitlab/api/models/GitlabProject.java @@ -125,9 +125,15 @@ public class GitlabProject { @JsonProperty("forked_from_project") private GitlabProject forkedFrom; - @JsonProperty("is_printing_merge_request_link_enabled") + @JsonProperty("printing_merge_request_link_enabled") private Boolean printingMergeRequestLinkEnabled; + @JsonProperty("import_status") + private String importStatus; + + @JsonProperty("initialize_with_readme") + private Boolean initializeWithReadme; + public Integer getId() { return id; } @@ -472,6 +478,14 @@ public void setPrintingMergeRequestLinkEnabled(Boolean printingMergeRequestLinkE this.printingMergeRequestLinkEnabled = printingMergeRequestLinkEnabled; } + public Boolean isInitializeWithReadme() { + return initializeWithReadme; + } + + public void setInitializeWithReadme(Boolean initializeWithReadme) { + this.initializeWithReadme = initializeWithReadme; + } + @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/src/main/java/org/gitlab/api/models/GitlabProjectHook.java b/src/main/java/org/gitlab/api/models/GitlabProjectHook.java index 32f63ed4..34326f4c 100644 --- a/src/main/java/org/gitlab/api/models/GitlabProjectHook.java +++ b/src/main/java/org/gitlab/api/models/GitlabProjectHook.java @@ -25,13 +25,25 @@ public class GitlabProjectHook { @JsonProperty("tag_push_events") private boolean tagPushEvents; - + @JsonProperty("created_at") private Date createdAt; @JsonProperty("enable_ssl_verification") private boolean sslVerificationEnabled; + @JsonProperty("note_events") + private boolean noteEvents; + + @JsonProperty("job_events") + private boolean jobEvents; + + @JsonProperty("pipeline_events") + private boolean pipelineEvents; + + @JsonProperty("wiki_page_events") + private boolean wikiPageEvents; + public String getId() { return id; } @@ -80,15 +92,14 @@ public void setMergeRequestsEvents(boolean mergeRequestsEvents) { this.mergeRequestsEvents = mergeRequestsEvents; } - public boolean isTagPushEvents() { return tagPushEvents; } - + public void setTagPushEvents(boolean tagPushEvents) { this.tagPushEvents = tagPushEvents; } - + public Date getCreatedAt() { return createdAt; } @@ -105,4 +116,19 @@ public void setSslVerificationEnabled(boolean sslVerificationEnabled) { this.sslVerificationEnabled = sslVerificationEnabled; } + public boolean isNoteEvents() { return noteEvents; } + + public void setNoteEvents(boolean noteEvents) { this.noteEvents = noteEvents; } + + public boolean isJobEvents() { return jobEvents; } + + public void setJobEvents(boolean jobEvents) { this.jobEvents = jobEvents; } + + public boolean isPipelineEvents() { return pipelineEvents; } + + public void setPipelineEvents(boolean pipelineEvents) { this.pipelineEvents = pipelineEvents; } + + public boolean isWikiPageEvents() { return wikiPageEvents; } + + public void setWikiPageEvents(boolean wikiPageEvents) { this.wikiPageEvents = wikiPageEvents; } } diff --git a/src/main/java/org/gitlab/api/models/GitlabPushData.java b/src/main/java/org/gitlab/api/models/GitlabPushData.java new file mode 100644 index 00000000..95f8f4d7 --- /dev/null +++ b/src/main/java/org/gitlab/api/models/GitlabPushData.java @@ -0,0 +1,85 @@ +package org.gitlab.api.models; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Date; +import java.util.List; + +public class GitlabPushData { + + @JsonProperty("commit_count") + private int commitCount; + + @JsonProperty("action") + private GitlabEvent.ActionType action; + + @JsonProperty("ref_type") + private String refType; + + @JsonProperty("commit_from") + private String commitFrom; + + @JsonProperty("commit_to") + private String commitTo; + + private String ref; + + @JsonProperty("commit_title") + private String commitTitle; + + public int getCommitCount() { + return commitCount; + } + + public GitlabEvent.ActionType getAction() { + return action; + } + + public String getRefType() { + return refType; + } + + public String getCommitFrom() { + return commitFrom; + } + + public String getCommitTo() { + return commitTo; + } + + public String getRef() { + return ref; + } + + public String getCommitTitle() { + return commitTitle; + } + + public void setCommitCount(int commitCount) { + this.commitCount = commitCount; + } + + public void setAction(GitlabEvent.ActionType action) { + this.action = action; + } + + public void setRefType(String refType) { + this.refType = refType; + } + + public void setCommitFrom(String commitFrom) { + this.commitFrom = commitFrom; + } + + public void setCommitTo(String commitTo) { + this.commitTo = commitTo; + } + + public void setRef(String ref) { + this.ref = ref; + } + + public void setCommitTitle(String commitTitle) { + this.commitTitle = commitTitle; + } +} diff --git a/src/main/java/org/gitlab/api/models/GitlabTag.java b/src/main/java/org/gitlab/api/models/GitlabTag.java index 4ed51596..c0ec8cbb 100644 --- a/src/main/java/org/gitlab/api/models/GitlabTag.java +++ b/src/main/java/org/gitlab/api/models/GitlabTag.java @@ -7,7 +7,7 @@ public class GitlabTag { public final static String URL = "/repository/tags"; @JsonProperty("commit") - private GitlabBranchCommit commit; + private GitlabCommit commit; @JsonProperty("release") private GitlabRelease release; @@ -18,11 +18,11 @@ public class GitlabTag { @JsonProperty("message") private String message; - public GitlabBranchCommit getCommit() { + public GitlabCommit getCommit() { return commit; } - public void setCommit(GitlabBranchCommit commit) { + public void setCommit(GitlabCommit commit) { this.commit = commit; } diff --git a/src/main/java/org/gitlab/api/models/GitlabUser.java b/src/main/java/org/gitlab/api/models/GitlabUser.java index 840c6f86..9f6cff5f 100644 --- a/src/main/java/org/gitlab/api/models/GitlabUser.java +++ b/src/main/java/org/gitlab/api/models/GitlabUser.java @@ -1,10 +1,12 @@ package org.gitlab.api.models; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + import java.util.Date; import java.util.List; -import com.fasterxml.jackson.annotation.JsonProperty; - +@JsonIgnoreProperties(ignoreUnknown = true) public class GitlabUser { public static String URL = "/users"; diff --git a/src/main/java/org/gitlab/api/models/SortOrder.java b/src/main/java/org/gitlab/api/models/SortOrder.java new file mode 100644 index 00000000..a181791f --- /dev/null +++ b/src/main/java/org/gitlab/api/models/SortOrder.java @@ -0,0 +1,12 @@ +package org.gitlab.api.models; + +public enum SortOrder { + ASC, DESC; + + public static final SortOrder DEFAULT = DESC; + + @Override + public String toString() { + return name().toLowerCase(); + } +} diff --git a/src/main/java/org/gitlab/api/query/PaginationQuery.java b/src/main/java/org/gitlab/api/query/PaginationQuery.java new file mode 100644 index 00000000..7996ec3f --- /dev/null +++ b/src/main/java/org/gitlab/api/query/PaginationQuery.java @@ -0,0 +1,40 @@ +package org.gitlab.api.query; + +import org.gitlab.api.http.Query; + +import java.io.UnsupportedEncodingException; + +public class PaginationQuery extends Query { + + public static final String PARAM_PAGE = "page"; + public static final String PARAM_PER_PAGE = "per_page"; + public static final int MAX_ITEMS_PER_PAGE = 100; + + public void setPage(int page) { + try { + append(PARAM_PAGE, String.valueOf(page)); + } catch (UnsupportedEncodingException ignored) { + } + } + + public void setPerPage(int perPage) { + if (perPage > MAX_ITEMS_PER_PAGE) { + throw new IllegalArgumentException("Max value for perPage is " + MAX_ITEMS_PER_PAGE); + } + try { + append(PARAM_PER_PAGE, String.valueOf(perPage)); + } catch (UnsupportedEncodingException ignored) { + } + } + + public PaginationQuery withPage(int page) { + setPage(page); + return this; + } + + public PaginationQuery withPerPage(int perPage) { + setPerPage(perPage); + return this; + } + +} diff --git a/src/main/java/org/gitlab/api/query/PipelinesQuery.java b/src/main/java/org/gitlab/api/query/PipelinesQuery.java new file mode 100644 index 00000000..5c919e2c --- /dev/null +++ b/src/main/java/org/gitlab/api/query/PipelinesQuery.java @@ -0,0 +1,100 @@ +package org.gitlab.api.query; + +import java.io.UnsupportedEncodingException; + +public class PipelinesQuery extends PaginationQuery { + + public void setScope(String scope) throws UnsupportedEncodingException { + appendIf("scope", scope); + } + + public PipelinesQuery withScope(String scope) throws UnsupportedEncodingException { + this.setScope(scope); + return this; + } + + public void setStatus(String status) throws UnsupportedEncodingException { + appendIf("status", status); + } + + public PipelinesQuery withStatus(String status) throws UnsupportedEncodingException { + this.setStatus(status); + return this; + } + + public void setRef(String ref) throws UnsupportedEncodingException { + appendIf("ref", ref); + } + + public PipelinesQuery withRef(String ref) throws UnsupportedEncodingException { + this.setRef(ref); + return this; + } + + public void setSha(String sha) throws UnsupportedEncodingException { + appendIf("sha", sha); + } + + public PipelinesQuery withSha(String sha) throws UnsupportedEncodingException { + this.setSha(sha); + return this; + } + + public void setYamlErrors(Boolean yamlErrors) throws UnsupportedEncodingException { + appendIf("yaml_errors", yamlErrors); + } + + public PipelinesQuery withYamlErrors(Boolean yamlErrors) throws UnsupportedEncodingException { + this.setYamlErrors(yamlErrors); + return this; + } + + public void setName(String name) throws UnsupportedEncodingException { + appendIf("name", name); + } + + public PipelinesQuery withName(String name) throws UnsupportedEncodingException { + this.setName(name); + return this; + } + + public void setUsername(String username) throws UnsupportedEncodingException { + appendIf("username", username); + } + + public PipelinesQuery withUsername(String username) throws UnsupportedEncodingException { + this.setUsername(username); + return this; + } + + public void setOrderBy(String orderBy) throws UnsupportedEncodingException { + appendIf("order_by", orderBy); + } + + public PipelinesQuery withOrderBy(String orderBy) throws UnsupportedEncodingException { + this.setOrderBy(orderBy); + return this; + } + + public void setSort(String sort) throws UnsupportedEncodingException { + appendIf("sort", sort); + } + + public PipelinesQuery withSort(String sort) throws UnsupportedEncodingException { + this.setSort(sort); + return this; + } + + @Override + public PipelinesQuery withPage(int page) { + super.withPage(page); + return this; + } + + @Override + public PipelinesQuery withPerPage(int perPage) { + super.withPerPage(perPage); + return this; + } + +} diff --git a/src/main/java/org/gitlab/api/query/ProjectsQuery.java b/src/main/java/org/gitlab/api/query/ProjectsQuery.java new file mode 100644 index 00000000..02fd4142 --- /dev/null +++ b/src/main/java/org/gitlab/api/query/ProjectsQuery.java @@ -0,0 +1,192 @@ +package org.gitlab.api.query; + +import org.gitlab.api.models.GitlabAccessLevel; + +import java.io.UnsupportedEncodingException; + +public class ProjectsQuery extends PaginationQuery { + + public static final String PARAM_ARCHIVED = "archived"; + public static final String PARAM_VISIBILITY = "visibility"; + public static final String PARAM_ORDER_BY = "order_by"; + public static final String PARAM_SORT = "sort"; + public static final String PARAM_SEARCH = "search"; + public static final String PARAM_SIMPLE = "simple"; + public static final String PARAM_OWNED = "owned"; + public static final String PARAM_MEMBERSHIP = "membership"; + public static final String PARAM_STARRED = "starred"; + public static final String PARAM_STATISTICS = "statistics"; + public static final String PARAM_WITH_CUSTOM_ATTRIBUTES = "with_custom_attributes"; + public static final String PARAM_WITH_ISSUES_ENABLED = "with_issues_enabled"; + public static final String PARAM_WITH_MERGE_REQUESTS_ENABLED = "with_merge_requests_enabled"; + public static final String PARAM_WITH_PROGRAMMING_LANGUAGE = "with_programming_language"; + public static final String PARAM_WIKI_CHECKSUM_FAILED = "wiki_checksum_failed"; + public static final String PARAM_REPOSITORY_CHECKSUM_FAILED = "repository_checksum_failed"; + public static final String PARAM_MIN_ACCESS_LEVEL = "min_access_level"; + + public void setArchived(Boolean archived) throws UnsupportedEncodingException { + appendIf(PARAM_ARCHIVED, archived); + } + + public ProjectsQuery withArchived(Boolean archived) throws UnsupportedEncodingException { + setArchived(archived); + return this; + } + + public void setVisibility(String visibility) throws UnsupportedEncodingException { + appendIf(PARAM_VISIBILITY, visibility); + } + + public ProjectsQuery withVisibility(String visibility) throws UnsupportedEncodingException { + setVisibility(visibility); + return this; + } + + public void setOrderBy(String orderBy) throws UnsupportedEncodingException { + appendIf(PARAM_ORDER_BY, orderBy); + } + + public ProjectsQuery withOrderBy(String orderBy) throws UnsupportedEncodingException { + setOrderBy(orderBy); + return this; + } + + public void setSort(String sort) throws UnsupportedEncodingException { + appendIf(PARAM_SORT, sort); + } + + public ProjectsQuery withSort(String sort) throws UnsupportedEncodingException { + setSort(sort); + return this; + } + + public void setSearch(String search) throws UnsupportedEncodingException { + appendIf(PARAM_SEARCH, search); + } + + public ProjectsQuery withSearch(String search) throws UnsupportedEncodingException { + setSearch(search); + return this; + } + + public void setSimple(Boolean simple) throws UnsupportedEncodingException { + appendIf(PARAM_SIMPLE, simple); + } + + public ProjectsQuery withSimple(Boolean simple) throws UnsupportedEncodingException { + setSimple(simple); + return this; + } + + public void setOwned(Boolean owned) throws UnsupportedEncodingException { + appendIf(PARAM_OWNED, owned); + } + + public ProjectsQuery withOwned(Boolean owned) throws UnsupportedEncodingException { + setOwned(owned); + return this; + } + + public void setMembership(Boolean membership) throws UnsupportedEncodingException { + appendIf(PARAM_MEMBERSHIP, membership); + } + + public ProjectsQuery withMembership(Boolean membership) throws UnsupportedEncodingException { + setMembership(membership); + return this; + } + + public void setStarred(Boolean starred) throws UnsupportedEncodingException { + appendIf(PARAM_STARRED, starred); + } + + public ProjectsQuery withStarred(Boolean starred) throws UnsupportedEncodingException { + setStarred(starred); + return this; + } + + public void setStatistics(Boolean statistics) throws UnsupportedEncodingException { + appendIf(PARAM_STATISTICS, statistics); + } + + public ProjectsQuery withStatistics(Boolean statistics) throws UnsupportedEncodingException { + setStatistics(statistics); + return this; + } + + public void setWithCustomAttributes(Boolean withCustomAttributes) throws UnsupportedEncodingException { + appendIf(PARAM_WITH_CUSTOM_ATTRIBUTES, withCustomAttributes); + } + + public ProjectsQuery withWithCustomAttributes(Boolean withCustomAttributes) throws UnsupportedEncodingException { + setWithCustomAttributes(withCustomAttributes); + return this; + } + + public void setWithIssuesEnabled(Boolean withIssuesEnabled) throws UnsupportedEncodingException { + appendIf(PARAM_WITH_ISSUES_ENABLED, withIssuesEnabled); + } + + public ProjectsQuery withWithIssuesEnabled(Boolean withIssuesEnabled) throws UnsupportedEncodingException { + setWithIssuesEnabled(withIssuesEnabled); + return this; + } + + public void setWithMergeRequestsEnabled(Boolean withMergeRequestsEnabled) throws UnsupportedEncodingException { + appendIf(PARAM_WITH_MERGE_REQUESTS_ENABLED, withMergeRequestsEnabled); + } + + public ProjectsQuery withWithMergeRequestsEnabled(Boolean withMergeRequestsEnabled) throws UnsupportedEncodingException { + setWithMergeRequestsEnabled(withMergeRequestsEnabled); + return this; + } + + public void setWithProgrammingLanguage(String withProgrammingLanguage) throws UnsupportedEncodingException { + appendIf(PARAM_WITH_PROGRAMMING_LANGUAGE, withProgrammingLanguage); + } + + public ProjectsQuery withWithProgrammingLanguage(String withProgrammingLanguage) throws UnsupportedEncodingException { + setWithProgrammingLanguage(withProgrammingLanguage); + return this; + } + + public void setWikiChecksumFailed(Boolean wikiChecksumFailed) throws UnsupportedEncodingException { + appendIf(PARAM_WIKI_CHECKSUM_FAILED, wikiChecksumFailed); + } + + public ProjectsQuery withWikiChecksumFailed(Boolean wikiChecksumFailed) throws UnsupportedEncodingException { + setWikiChecksumFailed(wikiChecksumFailed); + return this; + } + + public void setRepositoryChecksumFailed(Boolean repositoryChecksumFailed) throws UnsupportedEncodingException { + appendIf(PARAM_REPOSITORY_CHECKSUM_FAILED, repositoryChecksumFailed); + } + + public ProjectsQuery withRepositoryChecksumFailed(Boolean repositoryChecksumFailed) throws UnsupportedEncodingException { + setRepositoryChecksumFailed(repositoryChecksumFailed); + return this; + } + + public void setMinAccessLevel(GitlabAccessLevel minAccessLevel) throws UnsupportedEncodingException { + appendIf(PARAM_MIN_ACCESS_LEVEL, minAccessLevel); + } + + public ProjectsQuery withMinAccessLevel(GitlabAccessLevel minAccessLevel) throws UnsupportedEncodingException { + setMinAccessLevel(minAccessLevel); + return this; + } + + @Override + public ProjectsQuery withPage(int page) { + super.withPage(page); + return this; + } + + @Override + public ProjectsQuery withPerPage(int perPage) { + super.withPerPage(perPage); + return this; + } + +} diff --git a/src/test/java/org/gitlab/api/GitlabAPIIT.java b/src/test/java/org/gitlab/api/GitlabAPIIT.java index bee0c645..f8d2fc62 100644 --- a/src/test/java/org/gitlab/api/GitlabAPIIT.java +++ b/src/test/java/org/gitlab/api/GitlabAPIIT.java @@ -256,11 +256,14 @@ public void testCreateDeleteFork() throws Exception { false, false); + String namespace = api.getNamespaces().get(0).getPath(); + GitlabProject project = api.createUserProject(gitUser.getId(), projectName); - GitlabProject fork = api.createFork(api.getNamespaces().get(0).getPath(), project); + GitlabProject fork = api.createFork(namespace, project); assertNotNull(fork); assertEquals(project.getId(), fork.getForkedFrom().getId()); + assertEquals(project.getNamespace(), namespace); api.deleteProject(project.getId()); api.deleteProject(fork.getId()); diff --git a/src/test/java/org/gitlab/api/GitlabAPIUT.java b/src/test/java/org/gitlab/api/GitlabAPIUT.java index b2cce34a..dd5cec6e 100644 --- a/src/test/java/org/gitlab/api/GitlabAPIUT.java +++ b/src/test/java/org/gitlab/api/GitlabAPIUT.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test; import java.io.IOException; +import java.net.NoRouteToHostException; import java.net.ServerSocket; import java.net.SocketTimeoutException; @@ -18,13 +19,13 @@ @SuppressWarnings("WeakerAccess") public class GitlabAPIUT { - @Test + //@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")); + Throwable exception = assertThrows(NoRouteToHostException.class, api::getVersion); + assertThat(exception.getMessage(), is("No route to host")); } @Test diff --git a/src/test/java/org/gitlab/api/InstantDeserializerTest.java b/src/test/java/org/gitlab/api/InstantDeserializerTest.java new file mode 100644 index 00000000..727554db --- /dev/null +++ b/src/test/java/org/gitlab/api/InstantDeserializerTest.java @@ -0,0 +1,34 @@ +package org.gitlab.api; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.gitlab.api.jackson.InstantDeserializer; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.time.*; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.*; + +class InstantDeserializerTest { + + @Test + void deserialize() throws IOException { + final ObjectMapper objectMapper = new ObjectMapper(); + + final InstantDeserializer deserializer = new InstantDeserializer(); + final JsonParser parser = objectMapper.treeAsTokens(objectMapper.readTree("\"2016-08-11T11:28:34.085Z\"")); + parser.nextToken(); + final Instant instant = deserializer.deserialize(parser, objectMapper.getDeserializationContext()); + + assertEquals(Instant.from( + ZonedDateTime.of( + LocalDate.of(2016, 8, 11), + LocalTime.of(11, 28, 34, (int) TimeUnit.MILLISECONDS.toNanos(85)), + ZoneOffset.UTC + ) + ), instant); + } + +} \ No newline at end of file diff --git a/src/test/java/org/gitlab/api/TestUtils.java b/src/test/java/org/gitlab/api/TestUtils.java new file mode 100644 index 00000000..71bbe027 --- /dev/null +++ b/src/test/java/org/gitlab/api/TestUtils.java @@ -0,0 +1,18 @@ +package org.gitlab.api; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.stream.Collectors; + +public class TestUtils { + public static String readDataFromResource(String path) throws IOException { + InputStream inputStream = TestUtils.class.getClassLoader().getResourceAsStream(path); + assert inputStream != null; + try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { + return reader.lines().collect(Collectors.joining("\n")); + } + } + +} diff --git a/src/test/java/org/gitlab/api/models/GitlabIssueDeserializationTest.java b/src/test/java/org/gitlab/api/models/GitlabIssueDeserializationTest.java new file mode 100644 index 00000000..52802671 --- /dev/null +++ b/src/test/java/org/gitlab/api/models/GitlabIssueDeserializationTest.java @@ -0,0 +1,17 @@ +package org.gitlab.api.models; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.gitlab.api.TestUtils; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +class GitlabIssueDeserializationTest { + @Test + void deserializationTest() { + ObjectMapper objectMapper = new ObjectMapper(); + Assertions.assertDoesNotThrow(() -> objectMapper.readValue( + TestUtils.readDataFromResource("IssueExample.json"), GitlabIssue.class)); + } +} diff --git a/src/test/resources/IssueExample.json b/src/test/resources/IssueExample.json new file mode 100644 index 00000000..66936686 --- /dev/null +++ b/src/test/resources/IssueExample.json @@ -0,0 +1,44 @@ +{ + "id":231, + "iid":2456, + "project_id":871, + "title":"Data Feed Dghrythfh00", + "description":"# Bountyrdhfy.", + "state":"opened", + "created_at":"2019-06-06T21:54:50.241Z", + "updated_at":"2019-06-08T17:22:59.613Z", + "closed_at":null, + "closed_by":null, + "labels":[ + "bounty::available", + "status::untouched" + ], + "milestone":null, + "assignees":[ + + ], + "author":{ + "id":1325, + "name":"jlsfldgs", + "username":"jlsfldgsd", + "state":"active", + "avatar_url":"https://assets.gitlab-static.net/uploads/-/system/user/avatar/139453452225/avatar.png", + "web_url":"https://gitlab.com/jlsfldgsd" + }, + "assignee":null, + "user_notes_count":4, + "merge_requests_count":0, + "upvotes":0, + "downvotes":0, + "due_date":"2019-06-29", + "confidential":false, + "discussion_locked":null, + "web_url":"https://gitlab.com/3456457", + "time_stats":{ + "time_estimate":0, + "total_time_spent":0, + "human_time_estimate":null, + "human_total_time_spent":null + }, + "weight":null +} \ No newline at end of file