diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100755 index 00000000..9cc84ea9 Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100755 index 00000000..56bb0164 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index 4332fd0b..b6b481f2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,10 +1,10 @@ language: java -sudo: false +sudo: required +services: + - docker jdk: - oraclejdk7 install: -- ./gradlew assemble +- ./mvnw -B -q -Pdocker-gitlab dependency:go-offline verify -DskipTests -Ddocker.skip script: -- ./gradlew check -before_deploy: -- ./gradlew deployZip +- ./mvnw -B -V -Pdocker-gitlab verify diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..5b8d6f70 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,9 @@ +# How to contribute + + +* The integration tests need a running Docker infrastructure. +* To execute these, run `mvn -Pdocker-gitlab clean verify`. This will spawn + a new gitlab instance (`pull` needs some time and starting `gitlab-ce` may take up to 3 minutes). +* To run integration tests in your IDE, you need to execute `mvn -Pdocker-gitlab,docker-ide docker:start`. +* Once you are done, you may stop gitlab by executing `mvn -Pdocker-gitlab,docker-ide docker:stop`. +* For more information about the API, take a look at the [documentation](https://gitlab.com/help/api/README.md). \ No newline at end of file diff --git a/README.md b/README.md index 7a64ec5e..fff8b844 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ # Gitlab Java API Wrapper [![Maven Central](https://img.shields.io/maven-central/v/org.gitlab/java-gitlab-api.svg)](http://mvnrepository.com/artifact/org.gitlab/java-gitlab-api) - +[![Build Status](https://travis-ci.org/timols/java-gitlab-api.svg?branch=master)](https://travis-ci.org/timols/java-gitlab-api) A wrapper for the [Gitlab API](https://gitlab.org) written in Java. [Documentation](https://timols.github.io/java-gitlab-api) is available in the form of [Javadocs](https://timols.github.io/java-gitlab-api) +The major version indicates the API version of gitlab. diff --git a/mvnw b/mvnw new file mode 100755 index 00000000..5bf251c0 --- /dev/null +++ b/mvnw @@ -0,0 +1,225 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + 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 + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Migwn, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +echo $MAVEN_PROJECTBASEDIR +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100755 index 00000000..019bd74d --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,143 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" + +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/pom.xml b/pom.xml index f8a7e936..148befc7 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ org.gitlab java-gitlab-api - 1.2.9-SNAPSHOT + 4.0.1-SNAPSHOT Gitlab Java API Wrapper A Java wrapper for the Gitlab Git Hosting Server API @@ -60,8 +60,13 @@ + 1.7 + 1.7 UTF-8 UTF-8 + 2.20 + + 180000 @@ -100,26 +105,28 @@ org.apache.maven.plugins maven-compiler-plugin 2.5.1 - - 1.6 - 1.6 - org.apache.maven.plugins maven-surefire-plugin - 2.17 + ${maven-surefire-plugin.version} org.apache.maven.plugins maven-failsafe-plugin - 2.17 + ${maven-surefire-plugin.version} default-integration-test integration-test + + + ${docker.host.address} + ${gitlab.port} + + default-verify @@ -145,4 +152,67 @@ + + + docker-ide + + 127.0.0.1 + 18080 + + + + docker-gitlab + + + + io.fabric8 + docker-maven-plugin + 0.18.1 + + + default-start + + start + + + + default-stop + + stop + + + + + + + gitlab/gitlab-ce:latest + gitlab + + + gitlab.port:80 + + + + + ${user.dir}/src/test/resources/gitlab.rb:/etc/gitlab/gitlab.rb + + + + + + http://${docker.host.address}:${gitlab.port}/api/v4/version + GET + 401 + + + + + + + + + + + + diff --git a/src/main/java/org/gitlab/api/GitlabAPI.java b/src/main/java/org/gitlab/api/GitlabAPI.java index 16a13c3b..47089f44 100644 --- a/src/main/java/org/gitlab/api/GitlabAPI.java +++ b/src/main/java/org/gitlab/api/GitlabAPI.java @@ -27,7 +27,7 @@ public class GitlabAPI { public static final ObjectMapper MAPPER = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - private static final String API_NAMESPACE = "/api/v3"; + private static final String API_NAMESPACE = "/api/v4"; private static final String PARAM_SUDO = "sudo"; private static final String PARAM_MAX_ITEMS_PER_PAGE = new Pagination().withPerPage(Pagination.MAX_ITEMS_PER_PAGE).toString(); @@ -268,7 +268,7 @@ public void blockUser(Integer targetUserId) throws IOException { String tailUrl = GitlabUser.USERS_URL + "/" + targetUserId + GitlabUser.BLOCK_URL; - retrieve().method("PUT").to(tailUrl, Void.class); + retrieve().method("POST").to(tailUrl, Void.class); } /** @@ -281,7 +281,7 @@ public void unblockUser(Integer targetUserId) throws IOException { String tailUrl = GitlabUser.USERS_URL + "/" + targetUserId + GitlabUser.UNBLOCK_URL; - retrieve().method("PUT").to(tailUrl, Void.class); + retrieve().method("POST").to(tailUrl, Void.class); } /** @@ -609,34 +609,36 @@ public List getProjects() throws IOException { * @throws IOException */ public List getOwnedProjects() throws IOException { - String tailUrl = GitlabProject.URL + "/owned" + PARAM_MAX_ITEMS_PER_PAGE; + Query query = new Query().append("owner", "true"); + String tailUrl = GitlabProject.URL + query.toString() + PARAM_MAX_ITEMS_PER_PAGE; return retrieve().getAll(tailUrl, GitlabProject[].class); } /** * - * Get a list of projects accessible by the authenticated user. + * Get a list of projects starred by the authenticated user. * * @return A list of gitlab projects * @throws IOException */ - public List getProjectsViaSudo(GitlabUser user) throws IOException { - Query query = new Query() - .appendIf(PARAM_SUDO, user.getId()); - query.mergeWith(new Pagination().withPerPage(Pagination.MAX_ITEMS_PER_PAGE).asQuery()); - String tailUrl = GitlabProject.URL + query.toString(); + public List getStarredProjects() throws IOException { + Query query = new Query().append("starred", "true"); + String tailUrl = GitlabProject.URL + query.toString() + PARAM_MAX_ITEMS_PER_PAGE; return retrieve().getAll(tailUrl, GitlabProject[].class); } /** * - * Get's all projects in Gitlab, requires sudo user + * Get a list of projects accessible by the authenticated user. * * @return A list of gitlab projects * @throws IOException */ - public List getAllProjects() throws IOException { - String tailUrl = GitlabProject.URL + "/all" + PARAM_MAX_ITEMS_PER_PAGE; + public List getProjectsViaSudo(GitlabUser user) throws IOException { + Query query = new Query() + .appendIf(PARAM_SUDO, user.getId()); + query.mergeWith(new Pagination().withPerPage(Pagination.MAX_ITEMS_PER_PAGE).asQuery()); + String tailUrl = GitlabProject.URL + query.toString(); return retrieve().getAll(tailUrl, GitlabProject[].class); } @@ -655,27 +657,27 @@ public GitlabUpload uploadFile(GitlabProject project, File file) throws IOExcept /** * - * Gets a list of a project's builds in Gitlab + * Gets a list of a project's jobs in Gitlab * * @param project the project - * @return A list of project builds + * @return A list of project jobs * @throws IOException */ - public List getProjectBuilds(GitlabProject project) throws IOException { - return getProjectBuilds(project.getId()); + public List getProjectJobs(GitlabProject project) throws IOException { + return getProjectJobs(project.getId()); } /** * - * Gets a list of a project's builds in Gitlab + * Gets a list of a project's jobs in Gitlab * * @param projectId the project id - * @return A list of project builds + * @return A list of project jobs * @throws IOException */ - public List getProjectBuilds(Integer projectId) throws IOException { - String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBuild.URL + PARAM_MAX_ITEMS_PER_PAGE; - return retrieve().getAll(tailUrl, GitlabBuild[].class); + public List getProjectJobs(Integer projectId) throws IOException { + String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabJob.URL + PARAM_MAX_ITEMS_PER_PAGE; + return retrieve().getAll(tailUrl, GitlabJob[].class); } /** @@ -683,35 +685,35 @@ public List getProjectBuilds(Integer projectId) throws IOException * Gets a build for a project * * @param projectId the project id - * @param buildId the build id - * @return A list of project builds + * @param jobId the build id + * @return A list of project jobs * @throws IOException */ - public GitlabBuild getProjectBuild(Integer projectId, Integer buildId) throws IOException { - String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBuild.URL + "/" + buildId; - return retrieve().to(tailUrl, GitlabBuild.class); + public GitlabJob getProjectJob(Integer projectId, Integer jobId) throws IOException { + String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabJob.URL + "/" + jobId; + return retrieve().to(tailUrl, GitlabJob.class); } /** * Get build artifacts of a project build * * @param project The Project - * @param build The build + * @param job The build * @throws IOException on gitlab api call error */ - public byte[] getBuildArtifact(GitlabProject project, GitlabBuild build) throws IOException { - return getBuildArtifact(project.getId(), build.getId()); + public byte[] getJobArtifact(GitlabProject project, GitlabJob job) throws IOException { + return getJobArtifact(project.getId(), job.getId()); } /** * Get build artifacts of a project build * * @param projectId The Project's Id - * @param buildId The build's Id + * @param jobId The build's Id * @throws IOException on gitlab api call error */ - public byte[] getBuildArtifact(Integer projectId, Integer buildId) throws IOException { - String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBuild.URL + "/" + buildId + "/artifacts"; + public byte[] getJobArtifact(Integer projectId, Integer jobId) throws IOException { + String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabJob.URL + "/" + jobId + "/artifacts"; return retrieve().to(tailUrl, byte[].class); } @@ -757,12 +759,12 @@ public GitlabProject createProjectForGroup(String name, GitlabGroup group, Strin * @param name The name of the project * @param group The group for which the project should be crated * @param description The project description - * @param visibilityLevel The project visibility level (private: 0, internal: 10, public: 20) + * @param visibility The project visibility level (private: 0, internal: 10, public: 20) * @return The GitLab Project * @throws IOException on gitlab api call error */ - public GitlabProject createProjectForGroup(String name, GitlabGroup group, String description, Integer visibilityLevel) throws IOException { - return createProject(name, group.getId(), description, null, null, null, null, null, null, visibilityLevel, null); + public GitlabProject createProjectForGroup(String name, GitlabGroup group, String description, String visibility) throws IOException { + return createProject(name, group.getId(), description, null, null, null, null, null, null, visibility, null); } /** @@ -776,14 +778,13 @@ public GitlabProject createProjectForGroup(String name, GitlabGroup group, Strin * @param mergeRequestsEnabled Whether Merge Requests should be enabled, otherwise null indicates to use GitLab default * @param wikiEnabled Whether a Wiki should be enabled, otherwise null indicates to use GitLab default * @param snippetsEnabled Whether Snippets should be enabled, otherwise null indicates to use GitLab default - * @param publik Whether the project is public or private, if true same as setting visibilityLevel = 20, otherwise null indicates to use GitLab default - * @param visibilityLevel The visibility level of the project, otherwise null indicates to use GitLab default + * @param visibility The visibility level of the project, otherwise null indicates to use GitLab default * @param importUrl The Import URL for the project, otherwise null * @return the Gitlab Project * @throws IOException on gitlab api call error */ @Deprecated - public GitlabProject createProject(String name, Integer namespaceId, String description, Boolean issuesEnabled, Boolean wallEnabled, Boolean mergeRequestsEnabled, Boolean wikiEnabled, Boolean snippetsEnabled, Boolean publik, Integer visibilityLevel, String importUrl) throws IOException { + public GitlabProject createProject(String name, Integer namespaceId, String description, Boolean issuesEnabled, Boolean wallEnabled, Boolean mergeRequestsEnabled, Boolean wikiEnabled, Boolean snippetsEnabled, Boolean publik, String visibility, String importUrl) throws IOException { Query query = new Query() .append("name", name) .appendIf("namespace_id", namespaceId) @@ -793,8 +794,7 @@ public GitlabProject createProject(String name, Integer namespaceId, String desc .appendIf("merge_requests_enabled", mergeRequestsEnabled) .appendIf("wiki_enabled", wikiEnabled) .appendIf("snippets_enabled", snippetsEnabled) - .appendIf("public", publik) - .appendIf("visibility_level", visibilityLevel) + .appendIf("visibility", visibility) .appendIf("import_url", importUrl); String tailUrl = GitlabProject.URL + query.toString(); @@ -811,7 +811,7 @@ public GitlabProject createProject(String name, Integer namespaceId, String desc * @throws IOException on gitlab api call error */ public GitlabProject createUserProject(Integer userId, String name) throws IOException { - return createUserProject(userId, name, null, null, null, null, null, null, null, null, null, null); + return createUserProject(userId, name, null, null, null, null, null, null, null, null, null); } /** @@ -826,14 +826,13 @@ public GitlabProject createUserProject(Integer userId, String name) throws IOExc * @param mergeRequestsEnabled Whether Merge Requests should be enabled, otherwise null indicates to use GitLab default * @param wikiEnabled Whether a Wiki should be enabled, otherwise null indicates to use GitLab default * @param snippetsEnabled Whether Snippets should be enabled, otherwise null indicates to use GitLab default - * @param publik Whether the project is public or private, if true same as setting visibilityLevel = 20, otherwise null indicates to use GitLab default - * @param visibilityLevel The visibility level of the project, otherwise null indicates to use GitLab default + * @param visibility The visibility level of the project, otherwise null indicates to use GitLab default * @param importUrl The Import URL for the project, otherwise null * @return The GitLab Project * @throws IOException on gitlab api call error */ @Deprecated - public GitlabProject createUserProject(Integer userId, String name, String description, String defaultBranch, Boolean issuesEnabled, Boolean wallEnabled, Boolean mergeRequestsEnabled, Boolean wikiEnabled, Boolean snippetsEnabled, Boolean publik, Integer visibilityLevel, String importUrl) throws IOException { + public GitlabProject createUserProject(Integer userId, String name, String description, String defaultBranch, Boolean issuesEnabled, Boolean wallEnabled, Boolean mergeRequestsEnabled, Boolean wikiEnabled, Boolean snippetsEnabled, String visibility, String importUrl) throws IOException { Query query = new Query() .append("name", name) .appendIf("description", description) @@ -843,8 +842,7 @@ public GitlabProject createUserProject(Integer userId, String name, String descr .appendIf("merge_requests_enabled", mergeRequestsEnabled) .appendIf("wiki_enabled", wikiEnabled) .appendIf("snippets_enabled", snippetsEnabled) - .appendIf("public", publik) - .appendIf("visibility_level", visibilityLevel) + .appendIf("visibility", visibility) .appendIf("import_url", importUrl); String tailUrl = GitlabProject.URL + "/user/" + userId + query.toString(); @@ -864,7 +862,6 @@ public GitlabProject createUserProject(Integer userId, String name, String descr * @param mergeRequestsEnabled Whether Merge Requests should be enabled, otherwise null indicates to use GitLab default * @param wikiEnabled Whether a Wiki should be enabled, otherwise null indicates to use GitLab default * @param snippetsEnabled Whether Snippets should be enabled, otherwise null indicates to use GitLab default - * @param publik Whether the project is public or private, if true same as setting visibilityLevel = 20, otherwise null indicates to use GitLab default * @param visibilityLevel The visibility level of the project, otherwise null indicates to use GitLab default * @return the Gitlab Project * @throws IOException on gitlab api call error @@ -880,8 +877,7 @@ public GitlabProject updateProject( Boolean mergeRequestsEnabled, Boolean wikiEnabled, Boolean snippetsEnabled, - Boolean publik, - Integer visibilityLevel) + String visibility) throws IOException { Query query = new Query() @@ -893,8 +889,7 @@ public GitlabProject updateProject( .appendIf("merge_requests_enabled", mergeRequestsEnabled) .appendIf("wiki_enabled", wikiEnabled) .appendIf("snippets_enabled", snippetsEnabled) - .appendIf("public", publik) - .appendIf("visibility_level", visibilityLevel); + .appendIf("visibility", visibility); String tailUrl = GitlabProject.URL + "/" + projectId + query.toString(); @@ -970,12 +965,12 @@ public GitlabMergeRequest getMergeRequestByIid(Serializable projectId, Integer m * @throws IOException on gitlab api call error */ public GitlabMergeRequest getMergeRequestChanges(Serializable projectId, Integer mergeRequestId) throws IOException { - String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + "/merge_request/" + mergeRequestId + "/changes"; + String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + "/merge_requests/" + mergeRequestId + "/changes"; return retrieve().to(tailUrl, GitlabMergeRequest.class); } public GitlabMergeRequest getMergeRequest(GitlabProject project, Integer mergeRequestId) throws IOException { - String tailUrl = GitlabProject.URL + "/" + project.getId() + "/merge_request/" + mergeRequestId; + String tailUrl = GitlabProject.URL + "/" + project.getId() + "/merge_requests/" + mergeRequestId; return retrieve().to(tailUrl, GitlabMergeRequest.class); } @@ -1094,17 +1089,6 @@ public GitlabCommit getCommit(Serializable projectId, String commitHash) throws return retrieve().to(tailUrl, GitlabCommit.class); } - - public List getCommitBuilds(GitlabProject projectId, String commitHash) throws IOException { - return getCommitBuilds(projectId.getId(), commitHash); - } - - public List getCommitBuilds(Serializable projectId, String commitHash) throws IOException { - String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + "/repository/commits/" + commitHash + GitlabBuild.URL + PARAM_MAX_ITEMS_PER_PAGE; - return retrieve().getAll(tailUrl, GitlabBuild[].class); - } - - public List getCommits(GitlabMergeRequest mergeRequest) throws IOException { return getCommits(mergeRequest, new Pagination()); } @@ -1260,9 +1244,9 @@ public byte[] getRawFileContent(GitlabProject project, String sha, String filepa */ public byte[] getRawFileContent(Integer projectId, String sha, String filepath) throws IOException { Query query = new Query() - .append("filepath", filepath); + .append("ref", sha); - String tailUrl = GitlabProject.URL + "/" + projectId + "/repository/blobs/" + sha + query.toString(); + String tailUrl = GitlabProject.URL + "/" + projectId + "/repository/files/" + sanitizePath(filepath) + "/raw" + query.toString(); return retrieve().to(tailUrl, byte[].class); } @@ -1294,13 +1278,13 @@ public byte[] getFileArchive(GitlabProject project) throws IOException { * * @param project The Project * @param path The path inside the repository. Used to get content of subdirectories (optional) - * @param ref_name The name of a repository branch or tag or if not given the default branch (optional) + * @param ref The name of a repository branch or tag or if not given the default branch (optional) * @throws IOException on gitlab api call error */ - public List getRepositoryTree(GitlabProject project, String path, String ref_name, boolean recursive) throws IOException { + public List getRepositoryTree(GitlabProject project, String path, String ref, boolean recursive) throws IOException { Query query = new Query() .appendIf("path", path) - .appendIf("ref_name", ref_name) + .appendIf("ref", ref) .appendIf("recursive", recursive); String tailUrl = GitlabProject.URL + "/" + project.getId() + "/repository" + GitlabRepositoryTree.URL + query.toString(); @@ -1310,10 +1294,9 @@ public List getRepositoryTree(GitlabProject project, Strin public GitlabRepositoryFile getRepositoryFile(GitlabProject project, String path, String ref) throws IOException { Query query = new Query() - .append("file_path", path) .append("ref", ref); - String tailUrl = GitlabProject.URL + "/" + project.getId() + "/repository/files" + query.toString(); + String tailUrl = GitlabProject.URL + "/" + project.getId() + "/repository/files/" + sanitizePath(path) + query.toString(); return retrieve().to(tailUrl, GitlabRepositoryFile.class); } @@ -1397,7 +1380,7 @@ public void createBranch(GitlabProject project, String branchName, String ref) t */ public void createBranch(Serializable projectId, String branchName, String ref) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBranch.URL; - dispatch().with("branch_name", branchName).with("ref", ref).to(tailUrl, Void.class); + dispatch().with("branch", branchName).with("ref", ref).to(tailUrl, Void.class); } /** @@ -1408,12 +1391,12 @@ public void createBranch(Serializable projectId, String branchName, String ref) * @throws IOException on gitlab api call error */ public void deleteBranch(Serializable projectId, String branchName) throws IOException { - String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBranch.URL + '/' + sanitizeBranch(branchName); + String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBranch.URL + '/' + sanitizePath(branchName); retrieve().method("DELETE").to(tailUrl, Void.class); } public GitlabBranch getBranch(Serializable projectId, String branchName) throws IOException { - String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBranch.URL + '/' + sanitizeBranch(branchName); + String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBranch.URL + '/' + sanitizePath(branchName); return retrieve().to(tailUrl, GitlabBranch.class); } @@ -1422,12 +1405,19 @@ public GitlabBranch getBranch(GitlabProject project, String branchName) throws I } public void protectBranch(GitlabProject project, String branchName) throws IOException { - String tailUrl = GitlabProject.URL + "/" + project.getId() + GitlabBranch.URL + '/' + sanitizeBranch(branchName) + "/protect"; - retrieve().method("PUT").to(tailUrl, Void.class); + protectBranchWithDeveloperOptions(project, branchName, false, false); + } + + public void protectBranchWithDeveloperOptions(GitlabProject project, String branchName, boolean developers_can_push, boolean developers_can_merge) throws IOException { + String tailUrl = GitlabProject.URL + "/" + project.getId() + GitlabBranch.URL + '/' + sanitizePath(branchName) + "/protect"; + final Query query = new Query() + .append("developers_can_push", Boolean.toString(developers_can_push)) + .append("developers_can_merge", Boolean.toString(developers_can_merge)); + retrieve().method("PUT").to(tailUrl + query.toString(), Void.class); } public void unprotectBranch(GitlabProject project, String branchName) throws IOException { - String tailUrl = GitlabProject.URL + "/" + project.getId() + GitlabBranch.URL + '/' + sanitizeBranch(branchName) + "/unprotect"; + String tailUrl = GitlabProject.URL + "/" + project.getId() + GitlabBranch.URL + '/' + sanitizePath(branchName) + "/unprotect"; retrieve().method("PUT").to(tailUrl, Void.class); } @@ -1949,15 +1939,34 @@ public void transfer(Integer namespaceId, Integer projectId) throws IOException * @throws IOException on gitlab api call error */ public GitlabSSHKey createDeployKey(Integer targetProjectId, String title, String key) throws IOException { + return createDeployKey(targetProjectId, title, key, false); + } + + /** + * Create a new deploy key for the project which can push. + * + * @param targetProjectId The id of the Gitlab project + * @param title The title of the ssh key + * @param key The public key + * @return The new GitlabSSHKey + * @throws IOException on gitlab api call error + */ + public GitlabSSHKey createPushDeployKey(Integer targetProjectId, String title, String key) throws IOException { + return createDeployKey(targetProjectId, title, key, true); + } + + private GitlabSSHKey createDeployKey(Integer targetProjectId, String title, String key, boolean canPush) throws IOException { Query query = new Query() .append("title", title) - .append("key", key); + .append("key", key) + .append("can_push", Boolean.toString(canPush)); - String tailUrl = GitlabProject.URL + "/" + targetProjectId + GitlabSSHKey.KEYS_URL + query.toString(); + String tailUrl = GitlabProject.URL + "/" + targetProjectId + GitlabSSHKey.DEPLOY_KEYS_URL + query.toString(); return dispatch().to(tailUrl, GitlabSSHKey.class); } + /** * Delete a deploy key for a project * @@ -1966,7 +1975,7 @@ public GitlabSSHKey createDeployKey(Integer targetProjectId, String title, Strin * @throws IOException on gitlab api call error */ public void deleteDeployKey(Integer targetProjectId, Integer targetKeyId) throws IOException { - String tailUrl = GitlabProject.URL + "/" + targetProjectId + GitlabSSHKey.KEYS_URL + "/" + targetKeyId; + String tailUrl = GitlabProject.URL + "/" + targetProjectId + GitlabSSHKey.DEPLOY_KEYS_URL + "/" + targetKeyId; retrieve().method("DELETE").to(tailUrl, Void.class); } @@ -1978,7 +1987,7 @@ public void deleteDeployKey(Integer targetProjectId, Integer targetKeyId) throws * @throws IOException on gitlab api call error */ public List getDeployKeys(Integer targetProjectId) throws IOException { - String tailUrl = GitlabProject.URL + "/" + targetProjectId + GitlabSSHKey.KEYS_URL; + String tailUrl = GitlabProject.URL + "/" + targetProjectId + GitlabSSHKey.DEPLOY_KEYS_URL; return Arrays.asList(retrieve().to(tailUrl, GitlabSSHKey[].class)); } @@ -2041,7 +2050,7 @@ private String sanitizeProjectId(Serializable projectId) { } } - private String sanitizeBranch(String branch){ + private String sanitizePath(String branch){ try { return URLEncoder.encode(branch, "UTF-8"); } catch (UnsupportedEncodingException e) { @@ -2390,7 +2399,7 @@ public GitlabBuildVariable getBuildVariable(Integer projectId, String key) throws IOException { String tailUrl = GitlabProject.URL + "/" + projectId + - GitlabBuildVariable.URL + + GitlabBuildVariable.URL + "/" + key; return retrieve().to(tailUrl, GitlabBuildVariable.class); } @@ -2447,7 +2456,7 @@ public void deleteBuildVariable(Integer projectId, String key) throws IOException { String tailUrl = GitlabProject.URL + "/" + projectId + - GitlabBuildVariable.URL + + GitlabBuildVariable.URL + "/" + key; retrieve().method("DELETE").to(tailUrl, Void.class); } @@ -2476,7 +2485,7 @@ public GitlabBuildVariable updateBuildVariable(Integer projectId, String newValue) throws IOException { String tailUrl = GitlabProject.URL + "/" + projectId + - GitlabBuildVariable.URL + + GitlabBuildVariable.URL + "/" + key; GitlabHTTPRequestor requestor = retrieve().method("PUT"); if (newValue != null) { @@ -2490,14 +2499,14 @@ public GitlabBuildVariable updateBuildVariable(Integer projectId, * * @param project the project * @return list of build triggers - * @throws IllegalStateException if builds are not enabled for the project + * @throws IllegalStateException if jobs are not enabled for the project * @throws IOException */ - public List getBuildTriggers(GitlabProject project) throws IOException { - if (!project.isBuildsEnabled()) { - // if the project has not allowed builds, you will only get a 403 forbidden message which is + public List getPipelineTriggers(GitlabProject project) throws IOException { + if (!project.isJobsEnabled()) { + // if the project has not allowed jobs, you will only get a 403 forbidden message which is // not helpful. - throw new IllegalStateException("Builds are not enabled for " + project.getNameWithNamespace() ); + throw new IllegalStateException("Jobs are not enabled for " + project.getNameWithNamespace() ); } else { return retrieve().getAll(GitlabProject.URL + "/" + project.getId() + GitlabTrigger.URL + PARAM_MAX_ITEMS_PER_PAGE, GitlabTrigger[].class); } @@ -2550,12 +2559,12 @@ public boolean updateEmailsOnPush(Integer projectId, String emailAddress) throws * @return A list of gitlab projects * @throws IOException */ - public List searchProjects(String query) throws IOException { - List projects = new ArrayList(); - String tailUrl = GitlabProject.URL + "/search/" + query; + public List searchProjects(String search) throws IOException { + Query query = new Query() + .append("search", search); + String tailUrl = GitlabProject.URL + query.toString(); GitlabProject[] response = retrieve().to(tailUrl, GitlabProject[].class); - projects = Arrays.asList(response); - return projects; + return Arrays.asList(response); } /** diff --git a/src/main/java/org/gitlab/api/models/GitlabBuildVariable.java b/src/main/java/org/gitlab/api/models/GitlabBuildVariable.java index 605499de..e7e202f6 100644 --- a/src/main/java/org/gitlab/api/models/GitlabBuildVariable.java +++ b/src/main/java/org/gitlab/api/models/GitlabBuildVariable.java @@ -6,7 +6,7 @@ * @author Vitezslav Zak */ public class GitlabBuildVariable { - public final static String URL = "/variables/"; + public final static String URL = "/variables"; public GitlabBuildVariable() { } diff --git a/src/main/java/org/gitlab/api/models/GitlabBuild.java b/src/main/java/org/gitlab/api/models/GitlabJob.java similarity index 97% rename from src/main/java/org/gitlab/api/models/GitlabBuild.java rename to src/main/java/org/gitlab/api/models/GitlabJob.java index d1805138..4027c544 100644 --- a/src/main/java/org/gitlab/api/models/GitlabBuild.java +++ b/src/main/java/org/gitlab/api/models/GitlabJob.java @@ -3,9 +3,9 @@ import com.fasterxml.jackson.annotation.JsonProperty; -public class GitlabBuild { +public class GitlabJob { - public final static String URL = "/builds"; + public final static String URL = "/jobs"; private GitlabCommit commit; private Float coverage; diff --git a/src/main/java/org/gitlab/api/models/GitlabProject.java b/src/main/java/org/gitlab/api/models/GitlabProject.java index 9de2a1b6..5fc9d857 100644 --- a/src/main/java/org/gitlab/api/models/GitlabProject.java +++ b/src/main/java/org/gitlab/api/models/GitlabProject.java @@ -45,14 +45,14 @@ public class GitlabProject { @JsonProperty("wiki_enabled") private boolean wikiEnabled; - @JsonProperty("builds_enabled") - private boolean buildsEnabled; + @JsonProperty("jobs_enabled") + private boolean jobsEnabled; @JsonProperty("shared_runners_enabled") private boolean sharedRunnersEnabled; - @JsonProperty("public_builds") - private boolean publicBuilds; + @JsonProperty("public_jobs") + private boolean publicJobs; @JsonProperty("runners_token") private String runnersToken; @@ -210,12 +210,12 @@ public void setWikiEnabled(boolean wikiEnabled) { this.wikiEnabled = wikiEnabled; } - public boolean isBuildsEnabled() { - return buildsEnabled; + public boolean isJobsEnabled() { + return jobsEnabled; } - public void setBuildsEnabled(boolean buildsEnabled) { - this.buildsEnabled = buildsEnabled; + public void setJobsEnabled(boolean jobsEnabled) { + this.jobsEnabled = jobsEnabled; } public boolean isSharedRunnersEnabled() { @@ -226,12 +226,12 @@ public void setSharedRunnersEnabled(boolean sharedRunnersEnabled) { this.sharedRunnersEnabled = sharedRunnersEnabled; } - public boolean hasPublicBuilds() { - return publicBuilds; + public boolean hasPublicJobs() { + return publicJobs; } - public void setPublicBuilds(boolean publicBuilds) { - this.publicBuilds = publicBuilds; + public void setPublicJobs(boolean publicJobs) { + this.publicJobs = publicJobs; } public String getRunnersToken() { diff --git a/src/main/java/org/gitlab/api/models/GitlabSSHKey.java b/src/main/java/org/gitlab/api/models/GitlabSSHKey.java index 4635ae5a..f9e29e6e 100644 --- a/src/main/java/org/gitlab/api/models/GitlabSSHKey.java +++ b/src/main/java/org/gitlab/api/models/GitlabSSHKey.java @@ -3,6 +3,7 @@ public class GitlabSSHKey { public static String KEYS_URL = "/keys"; + public static String DEPLOY_KEYS_URL = "/deploy_keys"; private Integer _id; private String _title; diff --git a/src/test/java/org/gitlab/api/APIForIntegrationTestingHolder.java b/src/test/java/org/gitlab/api/APIForIntegrationTestingHolder.java new file mode 100644 index 00000000..a2ac1a2a --- /dev/null +++ b/src/test/java/org/gitlab/api/APIForIntegrationTestingHolder.java @@ -0,0 +1,43 @@ +package org.gitlab.api; + + +import org.gitlab.api.models.GitlabSession; +import org.junit.AssumptionViolatedException; + +import java.io.IOException; + +/** + * Token holder for integration tests. + *
    + *
  • By throwing an {@link AssumptionViolatedException} when the host is not reachable, + * provoke skipping of tests.
  • + *
  • GitLab is strict about creating too much sessions for username/password. + * If you create too many sessions, you will receive HTTP/429 (Retry Later).
  • + *
+ */ +public class APIForIntegrationTestingHolder { + + private static final String TEST_URL = "http://" + System.getProperty("docker.host.address", "localhost") + ":" + System.getProperty("gitlab.port", "18080"); + + public static APIForIntegrationTestingHolder INSTANCE = new APIForIntegrationTestingHolder(); + + private Object api; + + private APIForIntegrationTestingHolder(){ + final GitlabSession session; + try { + session = GitlabAPI.connect(TEST_URL, "root", "password"); + String privateToken = session.getPrivateToken(); + api = GitlabAPI.connect(TEST_URL, privateToken); + } catch (IOException e) { + api = e; + } + } + + public GitlabAPI getApi() { + if (api instanceof IOException) { + throw new AssumptionViolatedException("GITLAB not running on '" + TEST_URL + "', skipping...", (IOException)api); + } + return (GitlabAPI)api; + } +} diff --git a/src/test/java/org/gitlab/api/GitlabAPITest.java b/src/test/java/org/gitlab/api/GitlabAPIIT.java similarity index 78% rename from src/test/java/org/gitlab/api/GitlabAPITest.java rename to src/test/java/org/gitlab/api/GitlabAPIIT.java index f2f636e5..d3f24155 100644 --- a/src/test/java/org/gitlab/api/GitlabAPITest.java +++ b/src/test/java/org/gitlab/api/GitlabAPIIT.java @@ -1,40 +1,36 @@ package org.gitlab.api; import org.gitlab.api.models.GitlabBuildVariable; -import org.gitlab.api.models.GitlabProject; import org.gitlab.api.models.GitlabGroup; +import org.gitlab.api.models.GitlabProject; import org.gitlab.api.models.GitlabUser; -import org.junit.Before; -import org.junit.Ignore; +import org.junit.BeforeClass; import org.junit.Test; import java.io.FileNotFoundException; import java.io.IOException; -import java.net.ConnectException; import java.net.URL; +import java.util.List; import java.util.UUID; import static org.junit.Assert.*; -import static org.junit.Assume.assumeNoException; -@Ignore -public class GitlabAPITest { +public class GitlabAPIIT { - GitlabAPI api; + static GitlabAPI api; - private static final String TEST_URL = System.getProperty("TEST_URL", "http://localhost"); - private static final String TEST_TOKEN = System.getProperty("TEST_TOKEN", "y0E5b9761b7y4qk"); - - String rand = UUID.randomUUID().toString().replace("-", "").substring(0, 8); + private static final String TEST_URL = "http://" + System.getProperty("docker.host.address", "localhost") + ":" + System.getProperty("gitlab.port", "18080"); + String rand = createRandomString(); + @BeforeClass + public static void getApi() { + api = APIForIntegrationTestingHolder.INSTANCE.getApi(); + } - @Before - public void setup() throws IOException { - api = GitlabAPI.connect(TEST_URL, TEST_TOKEN); + @Test + public void Check_invalid_credentials() throws IOException { try { - api.dispatch().with("login", "INVALID").with("password", rand).to("session", GitlabUser.class); - } catch (ConnectException e) { - assumeNoException("GITLAB not running on '" + TEST_URL + "', skipping...", e); + api.dispatch().with("login", "INVALID").with("password", createRandomString()).to("session", GitlabUser.class); } catch (GitlabAPIException e) { final String message = e.getMessage(); if (!message.equals("{\"message\":\"401 Unauthorized\"}")) { @@ -44,10 +40,9 @@ public void setup() throws IOException { } } } - @Test public void testAllProjects() throws IOException { - api.getAllProjects(); + api.getProjects(); } @Test @@ -57,7 +52,7 @@ public void testConnect() throws IOException { @Test public void testGetAPIUrl() throws IOException { - URL expected = new URL(TEST_URL + "/api/v3/"); + URL expected = new URL(TEST_URL + "/api/v4/"); assertEquals(expected, api.getAPIUrl("")); } @@ -113,7 +108,7 @@ public void testCreateUpdateDeleteVariable() throws IOException { } @Test - public void testCreateUpdateDeleteUser() throws IOException { + public void testCreateUpdateDeleteUser() throws IOException, InterruptedException { String password = randVal("$%password"); @@ -138,7 +133,6 @@ public void testCreateUpdateDeleteUser() throws IOException { GitlabUser refetched = api.getUserViaSudo(gitUser.getUsername()); assertNotNull(refetched); - assertEquals(refetched.getUsername(), gitUser.getUsername()); api.updateUser(gitUser.getId(), gitUser.getEmail(), password, gitUser.getUsername(), @@ -153,9 +147,13 @@ public void testCreateUpdateDeleteUser() throws IOException { assertNotNull(postUpdate); assertEquals(postUpdate.getSkype(), "newSkypeId"); + // block + api.blockUser(refetched.getId()); + api.unblockUser(refetched.getId()); api.deleteUser(postUpdate.getId()); - + // This is odd, but it seems the user is deleted asynchronously... + Thread.sleep(1000); // expect a 404, but we have no access to it try { GitlabUser shouldNotExist = api.getUser(postUpdate.getId()); @@ -188,7 +186,23 @@ public void testGetGroupByPath() throws IOException { api.deleteGroup(group.getId()); } + @Test + public void Check_get_owned_projects() throws IOException { + final List ownedProjects = api.getOwnedProjects(); + assertEquals(0, ownedProjects.size()); + } + + @Test + public void Check_search_projects() throws IOException { + final List searchedProjects = api.searchProjects("foo"); + assertEquals(0, searchedProjects.size()); + } + private String randVal(String postfix) { return rand + "_" + postfix; } + + private static String createRandomString() { + return UUID.randomUUID().toString().replace("-", "").substring(0, 8); + } } diff --git a/src/test/java/org/gitlab/api/GitlabUploadIT.java b/src/test/java/org/gitlab/api/GitlabUploadIT.java new file mode 100644 index 00000000..31524b66 --- /dev/null +++ b/src/test/java/org/gitlab/api/GitlabUploadIT.java @@ -0,0 +1,52 @@ +package org.gitlab.api; + +import org.apache.commons.io.IOUtils; +import org.gitlab.api.models.GitlabProject; +import org.gitlab.api.models.GitlabUpload; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.*; + +public class GitlabUploadIT { + + static GitlabAPI api; + + @BeforeClass + public static void getApi() { + api = APIForIntegrationTestingHolder.INSTANCE.getApi(); + } + + + @Test + public void testUploadToProject() throws Exception { + GitlabProject project; + try { + project = api.getProject("root", "project"); + } catch (FileNotFoundException e) { + project = api.createUserProject(api.getUser().getId(), "project"); + } + String content = "test file content"; + File tempFile = createTempFile(content); + try { + GitlabUpload upload = api.uploadFile(project, tempFile); + Assert.assertNotNull(upload.getUrl()); + } finally { + tempFile.delete(); + } + } + + private File createTempFile(String content) throws IOException { + File tempFile = File.createTempFile("upload-", ".txt"); + InputStream is = new ByteArrayInputStream(content.getBytes()); + OutputStream os = new FileOutputStream(tempFile); + try { + IOUtils.copy(is, os); + } finally { + is.close(); + os.close(); + } + return tempFile; + } +} diff --git a/src/test/java/org/gitlab/api/GitlabUploadTest.java b/src/test/java/org/gitlab/api/GitlabUploadTest.java deleted file mode 100644 index 0288d377..00000000 --- a/src/test/java/org/gitlab/api/GitlabUploadTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.gitlab.api; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.commons.io.IOUtils; -import org.gitlab.api.models.GitlabProject; -import org.gitlab.api.models.GitlabUpload; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - -@Ignore -public class GitlabUploadTest { - - private static final String TEST_URL = System.getProperty("TEST_URL", "http://localhost"); - private static final String TEST_TOKEN = System.getProperty("TEST_TOKEN", "y0E5b9761b7y4qk"); - private static final String TEST_PROJECT = System.getProperty("TEST_PROJECT", "user/project"); - - @Test - public void testUploadToProject() throws Exception { - GitlabAPI api = GitlabAPI.connect(TEST_URL, TEST_TOKEN); - String content = "test file content"; - File tempFile = createTempFile(content); - try { - GitlabUpload upload = api.uploadFile(gitlabProject(api), tempFile); - Assert.assertNotNull(upload.getUrl()); - } finally { - tempFile.delete(); - } - } - - private File createTempFile(String content) throws IOException { - File tempFile = File.createTempFile("upload-", ".txt"); - InputStream is = new ByteArrayInputStream(content.getBytes()); - OutputStream os = new FileOutputStream(tempFile); - try { - IOUtils.copy(is, os); - } finally { - is.close(); - os.close(); - } - return tempFile; - } - - private GitlabProject gitlabProject(GitlabAPI api) throws IOException { - for (GitlabProject gitlabProject : api.getProjects()) { - String projetPath = String.format("%s/%s", gitlabProject.getNamespace().getPath(), gitlabProject.getPath()); - if (projetPath.equals(TEST_PROJECT)) { - return gitlabProject; - } - } - throw new IllegalStateException(); - } - -} diff --git a/src/test/resources/gitlab.rb b/src/test/resources/gitlab.rb new file mode 100644 index 00000000..c47fdb49 --- /dev/null +++ b/src/test/resources/gitlab.rb @@ -0,0 +1,2 @@ +gitlab_rails['initial_root_password'] = "password" +gitlab_rails['lfs_enabled'] = false