From fbd39a4e0ce3f4e65faf935a3b58ab5e1c1beb59 Mon Sep 17 00:00:00 2001 From: Gabriel Barbier Date: Mon, 3 Apr 2023 17:19:45 +0200 Subject: [PATCH 1/5] :arrow_up: upgrade version of java and dependencies In order to work with Spring Boot 3.x, transition from javax to jakarta is mandatory. It involves also an update of target jdk. --- pom.xml | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/pom.xml b/pom.xml index a3919c943..7b9b90b67 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.gitlab4j gitlab4j-api jar - 5.1.0 + 6.0.0 GitLab4J-API - GitLab API Java Client GitLab4J-API (gitlab4j-api) provides a full featured Java client library for working with GitLab repositories and servers via the GitLab REST API. https://github.com/gitlab4j/gitlab4j-api @@ -43,21 +43,20 @@ - 8 - 1.8 - 1.8 + 11 + 11 UTF-8 UTF-8 - 2.35 - 2.12.4 - 4.0.4 - 1.2.2 + 3.1.1 + 2.14.1 + 6.0.0 + 2.1.1 - 5.8.2 + 5.9.2 1.15.3 - 4.4.0 + 5.2.0 1.3 1.19.0 @@ -258,7 +257,7 @@ - 1.8 + 11 module-info @@ -285,7 +284,7 @@ org.codehaus.mojo animal-sniffer-maven-plugin - 1.20 + 1.23 @@ -297,7 +296,8 @@ org.codehaus.mojo.signature - java1${java.level} + java18 + 1.0 @@ -449,7 +449,7 @@ uk.org.webcompere system-stubs-jupiter - 1.2.0 + 2.0.2 test From 000cc150d8b0b74a859cf31468462a9aafee308d Mon Sep 17 00:00:00 2001 From: Gabriel Barbier Date: Mon, 3 Apr 2023 17:28:07 +0200 Subject: [PATCH 2/5] :fire: replace javax package by jakarta package in sources. --- .../java/org/gitlab4j/api/AbstractApi.java | 1607 +-- .../gitlab4j/api/ApplicationSettingsApi.java | 49 +- .../org/gitlab4j/api/ApplicationsApi.java | 242 +- .../java/org/gitlab4j/api/AuditEventApi.java | 20 +- .../java/org/gitlab4j/api/AwardEmojiApi.java | 1055 +- src/main/java/org/gitlab4j/api/BoardsApi.java | 712 +- .../java/org/gitlab4j/api/CommitsApi.java | 2196 +++-- .../gitlab4j/api/ContainerRegistryApi.java | 510 +- .../java/org/gitlab4j/api/DeployKeysApi.java | 52 +- .../org/gitlab4j/api/DeployTokensApi.java | 500 +- .../java/org/gitlab4j/api/DeploymentsApi.java | 484 +- .../java/org/gitlab4j/api/DiscussionsApi.java | 1805 ++-- .../org/gitlab4j/api/EnvironmentsApi.java | 376 +- src/main/java/org/gitlab4j/api/EpicsApi.java | 1023 +- src/main/java/org/gitlab4j/api/EventsApi.java | 94 +- .../gitlab4j/api/ExternalStatusCheckApi.java | 618 +- src/main/java/org/gitlab4j/api/GitLabApi.java | 3207 +++--- .../org/gitlab4j/api/GitLabApiClient.java | 1830 ++-- .../org/gitlab4j/api/GitLabApiException.java | 408 +- .../java/org/gitlab4j/api/GitLabApiForm.java | 388 +- src/main/java/org/gitlab4j/api/GroupApi.java | 4446 +++++---- .../java/org/gitlab4j/api/HealthCheckApi.java | 27 +- .../java/org/gitlab4j/api/HookManager.java | 110 +- .../org/gitlab4j/api/ImportExportApi.java | 496 +- src/main/java/org/gitlab4j/api/IssuesApi.java | 2354 +++-- src/main/java/org/gitlab4j/api/JobApi.java | 1385 +-- src/main/java/org/gitlab4j/api/KeysApi.java | 17 +- src/main/java/org/gitlab4j/api/LabelsApi.java | 1287 +-- .../java/org/gitlab4j/api/LicenseApi.java | 24 +- .../org/gitlab4j/api/LicenseTemplatesApi.java | 22 +- .../java/org/gitlab4j/api/MarkdownApi.java | 13 +- .../org/gitlab4j/api/MergeRequestApi.java | 3115 +++--- .../java/org/gitlab4j/api/MilestonesApi.java | 1440 +-- .../java/org/gitlab4j/api/NamespaceApi.java | 28 +- src/main/java/org/gitlab4j/api/NotesApi.java | 1022 +- .../gitlab4j/api/NotificationSettingsApi.java | 307 +- .../java/org/gitlab4j/api/PackagesApi.java | 48 +- src/main/java/org/gitlab4j/api/Pager.java | 695 +- .../java/org/gitlab4j/api/PipelineApi.java | 2057 ++-- .../java/org/gitlab4j/api/ProjectApi.java | 8627 ++++++++++------- .../gitlab4j/api/ProtectedBranchesApi.java | 548 +- .../java/org/gitlab4j/api/ReleasesApi.java | 32 +- .../java/org/gitlab4j/api/RepositoryApi.java | 1783 ++-- .../org/gitlab4j/api/RepositoryFileApi.java | 1118 ++- .../gitlab4j/api/ResourceLabelEventsApi.java | 575 +- .../java/org/gitlab4j/api/RunnersApi.java | 100 +- .../java/org/gitlab4j/api/ServicesApi.java | 1286 ++- .../java/org/gitlab4j/api/SnippetsApi.java | 50 +- .../java/org/gitlab4j/api/SystemHooksApi.java | 36 +- src/main/java/org/gitlab4j/api/TagsApi.java | 1022 +- src/main/java/org/gitlab4j/api/TodosApi.java | 26 +- src/main/java/org/gitlab4j/api/UserApi.java | 2736 +++--- src/main/java/org/gitlab4j/api/WikisApi.java | 514 +- .../api/systemhooks/SystemHookManager.java | 6 +- .../org/gitlab4j/api/utils/FileUtils.java | 12 +- .../gitlab4j/api/utils/HttpRequestUtils.java | 63 +- .../org/gitlab4j/api/utils/JacksonJson.java | 10 +- .../api/utils/MaskingLoggingFilter.java | 613 +- .../api/utils/Oauth2LoginStreamingOutput.java | 6 +- .../gitlab4j/api/webhook/WebHookManager.java | 86 +- src/test/java/org/gitlab4j/api/JsonUtils.java | 283 +- 61 files changed, 31570 insertions(+), 24031 deletions(-) diff --git a/src/main/java/org/gitlab4j/api/AbstractApi.java b/src/main/java/org/gitlab4j/api/AbstractApi.java index 6381549f1..59be5a6f4 100644 --- a/src/main/java/org/gitlab4j/api/AbstractApi.java +++ b/src/main/java/org/gitlab4j/api/AbstractApi.java @@ -1,15 +1,13 @@ package org.gitlab4j.api; +import jakarta.ws.rs.NotAuthorizedException; +import jakarta.ws.rs.core.Form; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.StreamingOutput; import java.io.File; import java.io.InputStream; import java.net.URL; - -import javax.ws.rs.NotAuthorizedException; -import javax.ws.rs.core.Form; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.StreamingOutput; - import org.gitlab4j.api.GitLabApi.ApiVersion; import org.gitlab4j.api.models.Group; import org.gitlab4j.api.models.Label; @@ -23,742 +21,861 @@ */ public abstract class AbstractApi implements Constants { - protected final GitLabApi gitLabApi; - - public AbstractApi(GitLabApi gitLabApi) { - this.gitLabApi = gitLabApi; - } - - /** - * Returns the project ID or path from the provided Integer, String, or Project instance. - * - * @param obj the object to determine the ID or path from - * @return the project ID or path from the provided Long, String, or Project instance - * @throws GitLabApiException if any exception occurs during execution - */ - public Object getProjectIdOrPath(Object obj) throws GitLabApiException { - - if (obj == null) { - throw (new RuntimeException("Cannot determine ID or path from null object")); - } else if (obj instanceof Long) { - return (obj); - } else if (obj instanceof String) { - return (urlEncode(((String) obj).trim())); - } else if (obj instanceof Project) { - - Long id = ((Project) obj).getId(); - if (id != null && id.longValue() > 0) { - return (id); - } - - String path = ((Project) obj).getPathWithNamespace(); - if (path != null && path.trim().length() > 0) { - return (urlEncode(path.trim())); - } - - throw (new RuntimeException("Cannot determine ID or path from provided Project instance")); - - } else { - throw (new RuntimeException("Cannot determine ID or path from provided " + obj.getClass().getSimpleName() + - " instance, must be Long, String, or a Project instance")); - } - } - - /** - * Returns the group ID or path from the provided Integer, String, or Group instance. - * - * @param obj the object to determine the ID or path from - * @return the group ID or path from the provided Long, String, or Group instance - * @throws GitLabApiException if any exception occurs during execution - */ - public Object getGroupIdOrPath(Object obj) throws GitLabApiException { - - if (obj == null) { - throw (new RuntimeException("Cannot determine ID or path from null object")); - } else if (obj instanceof Long) { - return (obj); - } else if (obj instanceof String) { - return (urlEncode(((String) obj).trim())); - } else if (obj instanceof Group) { - - Long id = ((Group) obj).getId(); - if (id != null && id.longValue() > 0) { - return (id); - } - - String path = ((Group) obj).getFullPath(); - if (path != null && path.trim().length() > 0) { - return (urlEncode(path.trim())); - } - - throw (new RuntimeException("Cannot determine ID or path from provided Group instance")); - - } else { - throw (new RuntimeException("Cannot determine ID or path from provided " + obj.getClass().getSimpleName() + - " instance, must be Long, String, or a Group instance")); - } - } - - /** - * Returns the user ID or path from the provided Integer, String, or User instance. - * - * @param obj the object to determine the ID or username from - * @return the user ID or username from the provided Integer, String, or User instance - * @throws GitLabApiException if any exception occurs during execution - */ - public Object getUserIdOrUsername(Object obj) throws GitLabApiException { - - if (obj == null) { - throw (new RuntimeException("Cannot determine ID or username from null object")); - } else if (obj instanceof Long) { - return (obj); - } else if (obj instanceof String) { - return (urlEncode(((String) obj).trim())); - } else if (obj instanceof User) { - - Long id = ((User) obj).getId(); - if (id != null && id.longValue() > 0) { - return (id); - } - - String username = ((User) obj).getUsername(); - if (username != null && username.trim().length() > 0) { - return (urlEncode(username.trim())); - } - - throw (new RuntimeException("Cannot determine ID or username from provided User instance")); - - } else { - throw (new RuntimeException("Cannot determine ID or username from provided " + obj.getClass().getSimpleName() + - " instance, must be Integer, String, or a User instance")); - } - } - - /** - * Returns the label ID or name from the provided Integer, String, or Label instance. - * - * @param obj the object to determine the ID or name from - * @return the user ID or name from the provided Integer, String, or Label instance - * @throws GitLabApiException if any exception occurs during execution - */ - public Object getLabelIdOrName(Object obj) throws GitLabApiException { - - if (obj == null) { - throw (new RuntimeException("Cannot determine ID or name from null object")); - } else if (obj instanceof Long) { - return (obj); - } else if (obj instanceof String) { - return (urlEncode(((String) obj).trim())); - } else if (obj instanceof Label) { - - Long id = ((Label) obj).getId(); - if (id != null && id.longValue() > 0) { - return (id); - } - - String name = ((Label) obj).getName(); - if (name != null && name.trim().length() > 0) { - return (urlEncode(name.trim())); - } - - throw (new RuntimeException("Cannot determine ID or name from provided Label instance")); - - } else { - throw (new RuntimeException("Cannot determine ID or name from provided " + obj.getClass().getSimpleName() + - " instance, must be Integer, String, or a Label instance")); - } - } - - protected ApiVersion getApiVersion() { - return (gitLabApi.getApiVersion()); - } - - protected boolean isApiVersion(ApiVersion apiVersion) { - return (gitLabApi.getApiVersion() == apiVersion); - } - - protected int getDefaultPerPage() { - return (gitLabApi.getDefaultPerPage()); - } - - protected GitLabApiClient getApiClient() { - return (gitLabApi.getApiClient()); - } - - /** - * Encode a string to be used as in-path argument for a gitlab api request. - * - * Standard URL encoding changes spaces to plus signs, but for arguments that are part of the path, - * like the :file_path in a "Get raw file" request, gitlab expects spaces to be encoded with %20. - * - * @param s the string to encode - * @return encoded version of s with spaces encoded as %2F - * @throws GitLabApiException if encoding throws an exception - */ - protected String urlEncode(String s) throws GitLabApiException { - return (UrlEncoder.urlEncode(s)); - } - - /** - * Perform an HTTP GET call with the specified query parameters and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param queryParams multivalue map of request parameters - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response get(Response.Status expectedStatus, MultivaluedMap queryParams, Object... pathArgs) throws GitLabApiException { - try { - return validate(getApiClient().get(queryParams, pathArgs), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - /** - * Perform an HTTP GET call with the specified query parameters and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param queryParams multivalue map of request parameters - * @param accepts if non-empty will set the Accepts header to this value - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response getWithAccepts(Response.Status expectedStatus, MultivaluedMap queryParams, String accepts, Object... pathArgs) throws GitLabApiException { - try { - return validate(getApiClient().getWithAccepts(queryParams, accepts, pathArgs), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - /** - * Perform an HTTP GET call with the specified query parameters and URL, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param queryParams multivalue map of request parameters - * @param url the fully formed path to the GitLab API endpoint - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response get(Response.Status expectedStatus, MultivaluedMap queryParams, URL url) throws GitLabApiException { - try { - return validate(getApiClient().get(queryParams, url), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - /** - * Perform an HTTP HEAD call with the specified query parameters and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param queryParams multivalue map of request parameters - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response head(Response.Status expectedStatus, MultivaluedMap queryParams, Object... pathArgs) throws GitLabApiException { - try { - return validate(getApiClient().head(queryParams, pathArgs), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - /** - * Perform an HTTP PATCH call with the specified query parameters and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param queryParams multivalue map of request parameters - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response patch(Response.Status expectedStatus, MultivaluedMap queryParams, Object... pathArgs) throws GitLabApiException { - try { - return validate(getApiClient().patch(queryParams, pathArgs), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - /** - * Perform an HTTP PATCH call with the specified query parameters and URL, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param queryParams multivalue map of request parameters - * @param url the fully formed path to the GitLab API endpoint - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response patch(Response.Status expectedStatus, MultivaluedMap queryParams, URL url) throws GitLabApiException { - try { - return validate(getApiClient().patch(queryParams, url), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - /** - * Perform an HTTP POST call with the specified form data and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param formData the Form containing the name/value pairs for the POST data - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response post(Response.Status expectedStatus, Form formData, Object... pathArgs) throws GitLabApiException { - try { - return validate(getApiClient().post(formData, pathArgs), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - /** - * Perform an HTTP POST call with the specified payload object and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param payload the object instance that will be serialized to JSON and used as the POST data - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response post(Response.Status expectedStatus, Object payload, Object... pathArgs) throws GitLabApiException { - try { - return validate(getApiClient().post(payload, pathArgs), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - /** - * Perform an HTTP POST call with the specified payload object and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param stream the StreamingOutput that will be used for the POST data - * @param mediaType the content-type for the streamed data - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response post(Response.Status expectedStatus, StreamingOutput stream, String mediaType, Object... pathArgs) throws GitLabApiException { - try { - return validate(getApiClient().post(stream, mediaType, pathArgs), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - /** - * Perform an HTTP POST call with the specified form data and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param queryParams multivalue map of request parameters - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response post(Response.Status expectedStatus, MultivaluedMap queryParams, Object... pathArgs) throws GitLabApiException { - try { - return validate(getApiClient().post(queryParams, pathArgs), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - /** - * Perform an HTTP POST call with the specified form data and URL, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param formData the Form containing the name/value pairs for the POST data - * @param url the fully formed path to the GitLab API endpoint - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response post(Response.Status expectedStatus, Form formData, URL url) throws GitLabApiException { - try { - return validate(getApiClient().post(formData, url), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - /** - * Perform a file upload with the specified File instance and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param name the name for the form field that contains the file name - * @param fileToUpload a File instance pointing to the file to upload - * @param mediaType unused; will be removed in the next major version - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response upload(Response.Status expectedStatus, String name, File fileToUpload, String mediaType, Object... pathArgs) throws GitLabApiException { - try { - return validate(getApiClient().upload(name, fileToUpload, mediaType, pathArgs), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - protected Response upload(Response.Status expectedStatus, String name, InputStream inputStream, String filename, String mediaType, Object... pathArgs) throws GitLabApiException { - try { - return validate(getApiClient().upload(name, inputStream, filename, mediaType, pathArgs), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - /** - * Perform a file upload with the specified File instance and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param name the name for the form field that contains the file name - * @param fileToUpload a File instance pointing to the file to upload - * @param mediaType unused; will be removed in the next major version - * @param url the fully formed path to the GitLab API endpoint - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response upload(Response.Status expectedStatus, String name, File fileToUpload, String mediaType, URL url) throws GitLabApiException { - try { - return validate(getApiClient().upload(name, fileToUpload, mediaType, url), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - /** - * Perform a file upload with the specified File instance and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param name the name for the form field that contains the file name - * @param fileToUpload a File instance pointing to the file to upload - * @param mediaType unused; will be removed in the next major version - * @param formData the Form containing the name/value pairs - * @param url the fully formed path to the GitLab API endpoint - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response upload(Response.Status expectedStatus, String name, File fileToUpload, String mediaType, Form formData, URL url) throws GitLabApiException { - - try { - return validate(getApiClient().upload(name, fileToUpload, mediaType, formData, url), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - /** - * Perform an HTTP PUT call with the specified form data and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param queryParams multivalue map of request parameters - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response put(Response.Status expectedStatus, MultivaluedMap queryParams, Object... pathArgs) throws GitLabApiException { - try { - return validate(getApiClient().put(queryParams, pathArgs), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - /** - * Perform an HTTP PUT call with the specified form data and URL, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param queryParams multivalue map of request parameters - * @param url the fully formed path to the GitLab API endpoint - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response put(Response.Status expectedStatus, MultivaluedMap queryParams, URL url) throws GitLabApiException { - try { - return validate(getApiClient().put(queryParams, url), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - /** - * Perform an HTTP PUT call with the specified payload object and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param payload the object instance that will be serialized to JSON and used as the PUT data - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response put(Response.Status expectedStatus, Object payload, Object... pathArgs) throws GitLabApiException { - try { - return validate(getApiClient().put(payload, pathArgs), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - /** - * Perform an HTTP PUT call with the specified form data and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param formData the Form containing the name/value pairs for the POST data - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response putWithFormData(Response.Status expectedStatus, Form formData, Object... pathArgs) throws GitLabApiException { - try { - return validate(getApiClient().put(formData, pathArgs), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - - /** - * Perform a file upload using the HTTP PUT method with the specified File instance and path objects, - * returning a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param name the name for the form field that contains the file name - * @param fileToUpload a File instance pointing to the file to upload - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response putUpload(Response.Status expectedStatus, String name, File fileToUpload, Object... pathArgs) throws GitLabApiException { - try { - return validate(getApiClient().putUpload(name, fileToUpload, pathArgs), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - /** - * Perform a file upload using the HTTP PUT method with the specified File instance and path objects, - * returning a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param name the name for the form field that contains the file name - * @param fileToUpload a File instance pointing to the file to upload - * @param url the fully formed path to the GitLab API endpoint - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response putUpload(Response.Status expectedStatus, String name, File fileToUpload, URL url) throws GitLabApiException { - try { - return validate(getApiClient().putUpload(name, fileToUpload, url), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - /** - * Perform an HTTP DELETE call with the specified form data and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param queryParams multivalue map of request parameters - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response delete(Response.Status expectedStatus, MultivaluedMap queryParams, Object... pathArgs) throws GitLabApiException { - try { - return validate(getApiClient().delete(queryParams, pathArgs), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - /** - * Perform an HTTP DELETE call with the specified form data and URL, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param expectedStatus the HTTP status that should be returned from the server - * @param queryParams multivalue map of request parameters - * @param url the fully formed path to the GitLab API endpoint - * @return a ClientResponse instance with the data returned from the endpoint - * @throws GitLabApiException if any exception occurs during execution - */ - protected Response delete(Response.Status expectedStatus, MultivaluedMap queryParams, URL url) throws GitLabApiException { - try { - return validate(getApiClient().delete(queryParams, url), expectedStatus); - } catch (Exception e) { - throw handle(e); - } - } - - /** - * Convenience method for adding query and form parameters to a get() or post() call. - * - * @param formData the Form containing the name/value pairs - * @param name the name of the field/attribute to add - * @param value the value of the field/attribute to add - */ - protected void addFormParam(Form formData, String name, Object value) throws IllegalArgumentException { - addFormParam(formData, name, value, false); - } - - /** - * Convenience method for adding query and form parameters to a get() or post() call. - * If required is true and value is null, will throw an IllegalArgumentException. - * - * @param formData the Form containing the name/value pairs - * @param name the name of the field/attribute to add - * @param value the value of the field/attribute to add - * @param required the field is required flag - * @throws IllegalArgumentException if a required parameter is null or empty - */ - protected void addFormParam(Form formData, String name, Object value, boolean required) throws IllegalArgumentException { - - if (value == null) { - - if (required) { - throw new IllegalArgumentException(name + " cannot be empty or null"); - } - - return; - } - - String stringValue = value.toString(); - if (required && stringValue.trim().length() == 0) { - throw new IllegalArgumentException(name + " cannot be empty or null"); - } - - formData.param(name, stringValue); - } - - /** - * Validates response the response from the server against the expected HTTP status and - * the returned secret token, if either is not correct will throw a GitLabApiException. - * - * @param response response - * @param expected expected response status - * @return original response if the response status is expected - * @throws GitLabApiException if HTTP status is not as expected, or the secret token doesn't match - */ - protected Response validate(Response response, Response.Status expected) throws GitLabApiException { - - int responseCode = response.getStatus(); - int expectedResponseCode = expected.getStatusCode(); - - if (responseCode != expectedResponseCode) { - - // If the expected code is 200-204 and the response code is 200-204 it is OK. We do this because - // GitLab is constantly changing the expected code in the 200 to 204 range - if (expectedResponseCode > 204 || responseCode > 204 || expectedResponseCode < 200 || responseCode < 200) - throw new GitLabApiException(response); - } - - if (!getApiClient().validateSecretToken(response)) { - throw new GitLabApiException(new NotAuthorizedException("Invalid secret token in response.")); - } - - return (response); - } - - /** - * Wraps an exception in a GitLabApiException if needed. - * - * @param thrown the exception that should be wrapped - * @return either the untouched GitLabApiException or a new GitLabApiExceptin wrapping a non-GitLabApiException - */ - protected GitLabApiException handle(Exception thrown) { - - if (thrown instanceof GitLabApiException) { - return ((GitLabApiException) thrown); - } - - return (new GitLabApiException(thrown)); - } - - /** - * Creates a MultivaluedMap instance containing the "per_page" param. - * - * @param perPage the number of projects per page - * @return a MultivaluedMap instance containing the "per_page" param - */ - protected MultivaluedMap getPerPageQueryParam(int perPage) { - return (new GitLabApiForm().withParam(PER_PAGE_PARAM, perPage).asMap()); - } - - /** - * Creates a MultivaluedMap instance containing "page" and "per_page" params. - * - * @param page the page to get - * @param perPage the number of projects per page - * @return a MultivaluedMap instance containing "page" and "per_page" params - */ - protected MultivaluedMap getPageQueryParams(int page, int perPage) { - return (new GitLabApiForm().withParam(PAGE_PARAM, page).withParam(PER_PAGE_PARAM, perPage).asMap()); - } - - /** - * Creates a MultivaluedMap instance containing "page" and "per_page" params. - * - * @param page the page to get - * @param perPage the number of projects per page - * @param customAttributesEnabled enables customAttributes for this query - * @return a MultivaluedMap instance containing "page" and "per_page" params - */ - protected MultivaluedMap getPageQueryParams(int page, int perPage, boolean customAttributesEnabled) { - - GitLabApiForm form = new GitLabApiForm().withParam(PAGE_PARAM, page).withParam(PER_PAGE_PARAM, perPage); - if (customAttributesEnabled) - return (form.withParam("with_custom_attributes", true).asMap()); - - return (form.asMap()); - } - - /** - * Creates a MultivaluedMap instance containing the "per_page" param with the default value. - * - * @return a MultivaluedMap instance containing the "per_page" param with the default value - */ - protected MultivaluedMap getDefaultPerPageParam() { - return (new GitLabApiForm().withParam(PER_PAGE_PARAM, getDefaultPerPage()).asMap()); - } - - /** - * Creates a MultivaluedMap instance containing the "per_page" param with the default value. - * - * @param customAttributesEnabled enables customAttributes for this query - * @return a MultivaluedMap instance containing the "per_page" param with the default value - */ - protected MultivaluedMap getDefaultPerPageParam(boolean customAttributesEnabled) { - - GitLabApiForm form = new GitLabApiForm().withParam(PER_PAGE_PARAM, getDefaultPerPage()); - if (customAttributesEnabled) - return (form.withParam("with_custom_attributes", true).asMap()); - - return (form.asMap()); - } + protected final GitLabApi gitLabApi; + + public AbstractApi(final GitLabApi gitLabApi) { + this.gitLabApi = gitLabApi; + } + + /** + * Returns the project ID or path from the provided Integer, String, or Project instance. + * + * @param obj the object to determine the ID or path from + * @return the project ID or path from the provided Long, String, or Project instance + * @throws GitLabApiException if any exception occurs during execution + */ + public Object getProjectIdOrPath(final Object obj) throws GitLabApiException { + + if (obj == null) { + throw (new RuntimeException("Cannot determine ID or path from null object")); + } else if (obj instanceof Long) { + return (obj); + } else if (obj instanceof String) { + return (urlEncode(((String) obj).trim())); + } else if (obj instanceof Project) { + + final Long id = ((Project) obj).getId(); + if (id != null && id.longValue() > 0) { + return (id); + } + + final String path = ((Project) obj).getPathWithNamespace(); + if (path != null && path.trim().length() > 0) { + return (urlEncode(path.trim())); + } + + throw (new RuntimeException("Cannot determine ID or path from provided Project instance")); + + } else { + throw (new RuntimeException( + "Cannot determine ID or path from provided " + + obj.getClass().getSimpleName() + + " instance, must be Long, String, or a Project instance")); + } + } + + /** + * Returns the group ID or path from the provided Integer, String, or Group instance. + * + * @param obj the object to determine the ID or path from + * @return the group ID or path from the provided Long, String, or Group instance + * @throws GitLabApiException if any exception occurs during execution + */ + public Object getGroupIdOrPath(final Object obj) throws GitLabApiException { + + if (obj == null) { + throw (new RuntimeException("Cannot determine ID or path from null object")); + } else if (obj instanceof Long) { + return (obj); + } else if (obj instanceof String) { + return (urlEncode(((String) obj).trim())); + } else if (obj instanceof Group) { + + final Long id = ((Group) obj).getId(); + if (id != null && id.longValue() > 0) { + return (id); + } + + final String path = ((Group) obj).getFullPath(); + if (path != null && path.trim().length() > 0) { + return (urlEncode(path.trim())); + } + + throw (new RuntimeException("Cannot determine ID or path from provided Group instance")); + + } else { + throw (new RuntimeException( + "Cannot determine ID or path from provided " + + obj.getClass().getSimpleName() + + " instance, must be Long, String, or a Group instance")); + } + } + + /** + * Returns the user ID or path from the provided Integer, String, or User instance. + * + * @param obj the object to determine the ID or username from + * @return the user ID or username from the provided Integer, String, or User instance + * @throws GitLabApiException if any exception occurs during execution + */ + public Object getUserIdOrUsername(final Object obj) throws GitLabApiException { + + if (obj == null) { + throw (new RuntimeException("Cannot determine ID or username from null object")); + } else if (obj instanceof Long) { + return (obj); + } else if (obj instanceof String) { + return (urlEncode(((String) obj).trim())); + } else if (obj instanceof User) { + + final Long id = ((User) obj).getId(); + if (id != null && id.longValue() > 0) { + return (id); + } + + final String username = ((User) obj).getUsername(); + if (username != null && username.trim().length() > 0) { + return (urlEncode(username.trim())); + } + + throw (new RuntimeException("Cannot determine ID or username from provided User instance")); + + } else { + throw (new RuntimeException( + "Cannot determine ID or username from provided " + + obj.getClass().getSimpleName() + + " instance, must be Integer, String, or a User instance")); + } + } + + /** + * Returns the label ID or name from the provided Integer, String, or Label instance. + * + * @param obj the object to determine the ID or name from + * @return the user ID or name from the provided Integer, String, or Label instance + * @throws GitLabApiException if any exception occurs during execution + */ + public Object getLabelIdOrName(final Object obj) throws GitLabApiException { + + if (obj == null) { + throw (new RuntimeException("Cannot determine ID or name from null object")); + } else if (obj instanceof Long) { + return (obj); + } else if (obj instanceof String) { + return (urlEncode(((String) obj).trim())); + } else if (obj instanceof Label) { + + final Long id = ((Label) obj).getId(); + if (id != null && id.longValue() > 0) { + return (id); + } + + final String name = ((Label) obj).getName(); + if (name != null && name.trim().length() > 0) { + return (urlEncode(name.trim())); + } + + throw (new RuntimeException("Cannot determine ID or name from provided Label instance")); + + } else { + throw (new RuntimeException( + "Cannot determine ID or name from provided " + + obj.getClass().getSimpleName() + + " instance, must be Integer, String, or a Label instance")); + } + } + + protected ApiVersion getApiVersion() { + return (gitLabApi.getApiVersion()); + } + + protected boolean isApiVersion(final ApiVersion apiVersion) { + return (gitLabApi.getApiVersion() == apiVersion); + } + + protected int getDefaultPerPage() { + return (gitLabApi.getDefaultPerPage()); + } + + protected GitLabApiClient getApiClient() { + return (gitLabApi.getApiClient()); + } + + /** + * Encode a string to be used as in-path argument for a gitlab api request. + * + *

Standard URL encoding changes spaces to plus signs, but for arguments that are part of the + * path, like the :file_path in a "Get raw file" request, gitlab expects spaces to be encoded with + * %20. + * + * @param s the string to encode + * @return encoded version of s with spaces encoded as %2F + * @throws GitLabApiException if encoding throws an exception + */ + protected String urlEncode(final String s) throws GitLabApiException { + return (UrlEncoder.urlEncode(s)); + } + + /** + * Perform an HTTP GET call with the specified query parameters and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param queryParams multivalue map of request parameters + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response get( + final Response.Status expectedStatus, + final MultivaluedMap queryParams, + final Object... pathArgs) + throws GitLabApiException { + try { + return validate(getApiClient().get(queryParams, pathArgs), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Perform an HTTP GET call with the specified query parameters and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param queryParams multivalue map of request parameters + * @param accepts if non-empty will set the Accepts header to this value + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response getWithAccepts( + final Response.Status expectedStatus, + final MultivaluedMap queryParams, + final String accepts, + final Object... pathArgs) + throws GitLabApiException { + try { + return validate( + getApiClient().getWithAccepts(queryParams, accepts, pathArgs), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Perform an HTTP GET call with the specified query parameters and URL, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param queryParams multivalue map of request parameters + * @param url the fully formed path to the GitLab API endpoint + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response get( + final Response.Status expectedStatus, + final MultivaluedMap queryParams, + final URL url) + throws GitLabApiException { + try { + return validate(getApiClient().get(queryParams, url), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Perform an HTTP HEAD call with the specified query parameters and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param queryParams multivalue map of request parameters + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response head( + final Response.Status expectedStatus, + final MultivaluedMap queryParams, + final Object... pathArgs) + throws GitLabApiException { + try { + return validate(getApiClient().head(queryParams, pathArgs), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Perform an HTTP PATCH call with the specified query parameters and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param queryParams multivalue map of request parameters + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response patch( + final Response.Status expectedStatus, + final MultivaluedMap queryParams, + final Object... pathArgs) + throws GitLabApiException { + try { + return validate(getApiClient().patch(queryParams, pathArgs), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Perform an HTTP PATCH call with the specified query parameters and URL, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param queryParams multivalue map of request parameters + * @param url the fully formed path to the GitLab API endpoint + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response patch( + final Response.Status expectedStatus, + final MultivaluedMap queryParams, + final URL url) + throws GitLabApiException { + try { + return validate(getApiClient().patch(queryParams, url), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Perform an HTTP POST call with the specified form data and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param formData the Form containing the name/value pairs for the POST data + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response post( + final Response.Status expectedStatus, final Form formData, final Object... pathArgs) + throws GitLabApiException { + try { + return validate(getApiClient().post(formData, pathArgs), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Perform an HTTP POST call with the specified payload object and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param payload the object instance that will be serialized to JSON and used as the POST data + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response post( + final Response.Status expectedStatus, final Object payload, final Object... pathArgs) + throws GitLabApiException { + try { + return validate(getApiClient().post(payload, pathArgs), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Perform an HTTP POST call with the specified payload object and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param stream the StreamingOutput that will be used for the POST data + * @param mediaType the content-type for the streamed data + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response post( + final Response.Status expectedStatus, + final StreamingOutput stream, + final String mediaType, + final Object... pathArgs) + throws GitLabApiException { + try { + return validate(getApiClient().post(stream, mediaType, pathArgs), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Perform an HTTP POST call with the specified form data and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param queryParams multivalue map of request parameters + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response post( + final Response.Status expectedStatus, + final MultivaluedMap queryParams, + final Object... pathArgs) + throws GitLabApiException { + try { + return validate(getApiClient().post(queryParams, pathArgs), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Perform an HTTP POST call with the specified form data and URL, returning a ClientResponse + * instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param formData the Form containing the name/value pairs for the POST data + * @param url the fully formed path to the GitLab API endpoint + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response post(final Response.Status expectedStatus, final Form formData, final URL url) + throws GitLabApiException { + try { + return validate(getApiClient().post(formData, url), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Perform a file upload with the specified File instance and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param name the name for the form field that contains the file name + * @param fileToUpload a File instance pointing to the file to upload + * @param mediaType unused; will be removed in the next major version + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response upload( + final Response.Status expectedStatus, + final String name, + final File fileToUpload, + final String mediaType, + final Object... pathArgs) + throws GitLabApiException { + try { + return validate( + getApiClient().upload(name, fileToUpload, mediaType, pathArgs), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + protected Response upload( + final Response.Status expectedStatus, + final String name, + final InputStream inputStream, + final String filename, + final String mediaType, + final Object... pathArgs) + throws GitLabApiException { + try { + return validate( + getApiClient().upload(name, inputStream, filename, mediaType, pathArgs), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Perform a file upload with the specified File instance and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param name the name for the form field that contains the file name + * @param fileToUpload a File instance pointing to the file to upload + * @param mediaType unused; will be removed in the next major version + * @param url the fully formed path to the GitLab API endpoint + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response upload( + final Response.Status expectedStatus, + final String name, + final File fileToUpload, + final String mediaType, + final URL url) + throws GitLabApiException { + try { + return validate(getApiClient().upload(name, fileToUpload, mediaType, url), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Perform a file upload with the specified File instance and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param name the name for the form field that contains the file name + * @param fileToUpload a File instance pointing to the file to upload + * @param mediaType unused; will be removed in the next major version + * @param formData the Form containing the name/value pairs + * @param url the fully formed path to the GitLab API endpoint + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response upload( + final Response.Status expectedStatus, + final String name, + final File fileToUpload, + final String mediaType, + final Form formData, + final URL url) + throws GitLabApiException { + + try { + return validate( + getApiClient().upload(name, fileToUpload, mediaType, formData, url), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Perform an HTTP PUT call with the specified form data and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param queryParams multivalue map of request parameters + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response put( + final Response.Status expectedStatus, + final MultivaluedMap queryParams, + final Object... pathArgs) + throws GitLabApiException { + try { + return validate(getApiClient().put(queryParams, pathArgs), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Perform an HTTP PUT call with the specified form data and URL, returning a ClientResponse + * instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param queryParams multivalue map of request parameters + * @param url the fully formed path to the GitLab API endpoint + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response put( + final Response.Status expectedStatus, + final MultivaluedMap queryParams, + final URL url) + throws GitLabApiException { + try { + return validate(getApiClient().put(queryParams, url), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Perform an HTTP PUT call with the specified payload object and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param payload the object instance that will be serialized to JSON and used as the PUT data + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response put( + final Response.Status expectedStatus, final Object payload, final Object... pathArgs) + throws GitLabApiException { + try { + return validate(getApiClient().put(payload, pathArgs), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Perform an HTTP PUT call with the specified form data and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param formData the Form containing the name/value pairs for the POST data + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response putWithFormData( + final Response.Status expectedStatus, final Form formData, final Object... pathArgs) + throws GitLabApiException { + try { + return validate(getApiClient().put(formData, pathArgs), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Perform a file upload using the HTTP PUT method with the specified File instance and path + * objects, returning a ClientResponse instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param name the name for the form field that contains the file name + * @param fileToUpload a File instance pointing to the file to upload + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response putUpload( + final Response.Status expectedStatus, + final String name, + final File fileToUpload, + final Object... pathArgs) + throws GitLabApiException { + try { + return validate(getApiClient().putUpload(name, fileToUpload, pathArgs), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Perform a file upload using the HTTP PUT method with the specified File instance and path + * objects, returning a ClientResponse instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param name the name for the form field that contains the file name + * @param fileToUpload a File instance pointing to the file to upload + * @param url the fully formed path to the GitLab API endpoint + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response putUpload( + final Response.Status expectedStatus, + final String name, + final File fileToUpload, + final URL url) + throws GitLabApiException { + try { + return validate(getApiClient().putUpload(name, fileToUpload, url), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Perform an HTTP DELETE call with the specified form data and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param queryParams multivalue map of request parameters + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response delete( + final Response.Status expectedStatus, + final MultivaluedMap queryParams, + final Object... pathArgs) + throws GitLabApiException { + try { + return validate(getApiClient().delete(queryParams, pathArgs), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Perform an HTTP DELETE call with the specified form data and URL, returning a ClientResponse + * instance with the data returned from the endpoint. + * + * @param expectedStatus the HTTP status that should be returned from the server + * @param queryParams multivalue map of request parameters + * @param url the fully formed path to the GitLab API endpoint + * @return a ClientResponse instance with the data returned from the endpoint + * @throws GitLabApiException if any exception occurs during execution + */ + protected Response delete( + final Response.Status expectedStatus, + final MultivaluedMap queryParams, + final URL url) + throws GitLabApiException { + try { + return validate(getApiClient().delete(queryParams, url), expectedStatus); + } catch (final Exception e) { + throw handle(e); + } + } + + /** + * Convenience method for adding query and form parameters to a get() or post() call. + * + * @param formData the Form containing the name/value pairs + * @param name the name of the field/attribute to add + * @param value the value of the field/attribute to add + */ + protected void addFormParam(final Form formData, final String name, final Object value) + throws IllegalArgumentException { + addFormParam(formData, name, value, false); + } + + /** + * Convenience method for adding query and form parameters to a get() or post() call. If required + * is true and value is null, will throw an IllegalArgumentException. + * + * @param formData the Form containing the name/value pairs + * @param name the name of the field/attribute to add + * @param value the value of the field/attribute to add + * @param required the field is required flag + * @throws IllegalArgumentException if a required parameter is null or empty + */ + protected void addFormParam( + final Form formData, final String name, final Object value, final boolean required) + throws IllegalArgumentException { + + if (value == null) { + + if (required) { + throw new IllegalArgumentException(name + " cannot be empty or null"); + } + + return; + } + + final String stringValue = value.toString(); + if (required && stringValue.trim().length() == 0) { + throw new IllegalArgumentException(name + " cannot be empty or null"); + } + + formData.param(name, stringValue); + } + + /** + * Validates response the response from the server against the expected HTTP status and the + * returned secret token, if either is not correct will throw a GitLabApiException. + * + * @param response response + * @param expected expected response status + * @return original response if the response status is expected + * @throws GitLabApiException if HTTP status is not as expected, or the secret token doesn't match + */ + protected Response validate(final Response response, final Response.Status expected) + throws GitLabApiException { + + final int responseCode = response.getStatus(); + final int expectedResponseCode = expected.getStatusCode(); + + if (responseCode != expectedResponseCode) { + + // If the expected code is 200-204 and the response code is 200-204 it is OK. We do this + // because + // GitLab is constantly changing the expected code in the 200 to 204 range + if (expectedResponseCode > 204 + || responseCode > 204 + || expectedResponseCode < 200 + || responseCode < 200) throw new GitLabApiException(response); + } + + if (!getApiClient().validateSecretToken(response)) { + throw new GitLabApiException(new NotAuthorizedException("Invalid secret token in response.")); + } + + return (response); + } + + /** + * Wraps an exception in a GitLabApiException if needed. + * + * @param thrown the exception that should be wrapped + * @return either the untouched GitLabApiException or a new GitLabApiExceptin wrapping a + * non-GitLabApiException + */ + protected GitLabApiException handle(final Exception thrown) { + + if (thrown instanceof GitLabApiException) { + return ((GitLabApiException) thrown); + } + + return (new GitLabApiException(thrown)); + } + + /** + * Creates a MultivaluedMap instance containing the "per_page" param. + * + * @param perPage the number of projects per page + * @return a MultivaluedMap instance containing the "per_page" param + */ + protected MultivaluedMap getPerPageQueryParam(final int perPage) { + return (new GitLabApiForm().withParam(PER_PAGE_PARAM, perPage).asMap()); + } + + /** + * Creates a MultivaluedMap instance containing "page" and "per_page" params. + * + * @param page the page to get + * @param perPage the number of projects per page + * @return a MultivaluedMap instance containing "page" and "per_page" params + */ + protected MultivaluedMap getPageQueryParams(final int page, final int perPage) { + return (new GitLabApiForm() + .withParam(PAGE_PARAM, page) + .withParam(PER_PAGE_PARAM, perPage) + .asMap()); + } + + /** + * Creates a MultivaluedMap instance containing "page" and "per_page" params. + * + * @param page the page to get + * @param perPage the number of projects per page + * @param customAttributesEnabled enables customAttributes for this query + * @return a MultivaluedMap instance containing "page" and "per_page" params + */ + protected MultivaluedMap getPageQueryParams( + final int page, final int perPage, final boolean customAttributesEnabled) { + + final GitLabApiForm form = + new GitLabApiForm().withParam(PAGE_PARAM, page).withParam(PER_PAGE_PARAM, perPage); + if (customAttributesEnabled) return (form.withParam("with_custom_attributes", true).asMap()); + + return (form.asMap()); + } + + /** + * Creates a MultivaluedMap instance containing the "per_page" param with the default value. + * + * @return a MultivaluedMap instance containing the "per_page" param with the default value + */ + protected MultivaluedMap getDefaultPerPageParam() { + return (new GitLabApiForm().withParam(PER_PAGE_PARAM, getDefaultPerPage()).asMap()); + } + + /** + * Creates a MultivaluedMap instance containing the "per_page" param with the default value. + * + * @param customAttributesEnabled enables customAttributes for this query + * @return a MultivaluedMap instance containing the "per_page" param with the default value + */ + protected MultivaluedMap getDefaultPerPageParam( + final boolean customAttributesEnabled) { + + final GitLabApiForm form = new GitLabApiForm().withParam(PER_PAGE_PARAM, getDefaultPerPage()); + if (customAttributesEnabled) return (form.withParam("with_custom_attributes", true).asMap()); + + return (form.asMap()); + } } diff --git a/src/main/java/org/gitlab4j/api/ApplicationSettingsApi.java b/src/main/java/org/gitlab4j/api/ApplicationSettingsApi.java index 28ff1d716..88b28afc5 100644 --- a/src/main/java/org/gitlab4j/api/ApplicationSettingsApi.java +++ b/src/main/java/org/gitlab4j/api/ApplicationSettingsApi.java @@ -1,23 +1,20 @@ package org.gitlab4j.api; +import com.fasterxml.jackson.databind.JsonNode; +import jakarta.ws.rs.core.Response; import java.text.ParseException; import java.util.Iterator; - -import javax.ws.rs.core.Response; - -import org.gitlab4j.api.models.Setting; import org.gitlab4j.api.models.ApplicationSettings; +import org.gitlab4j.api.models.Setting; import org.gitlab4j.api.utils.ISO8601; -import com.fasterxml.jackson.databind.JsonNode; - /** * This class implements the client side API for the GitLab Application Settings API. * See Application Settings API at GitLab for more information. */ public class ApplicationSettingsApi extends AbstractApi { - public ApplicationSettingsApi(GitLabApi gitLabApi) { + public ApplicationSettingsApi(final GitLabApi gitLabApi) { super(gitLabApi); } @@ -31,8 +28,8 @@ public ApplicationSettingsApi(GitLabApi gitLabApi) { */ public ApplicationSettings getApplicationSettings() throws GitLabApiException { - Response response = get(Response.Status.OK, null, "application", "settings"); - JsonNode root = response.readEntity(JsonNode.class); + final Response response = get(Response.Status.OK, null, "application", "settings"); + final JsonNode root = response.readEntity(JsonNode.class); return (parseApplicationSettings(root)); } @@ -46,7 +43,7 @@ public ApplicationSettings getApplicationSettings() throws GitLabApiException { * @return the updated application settings in an ApplicationSettings instance * @throws GitLabApiException if any exception occurs */ - public ApplicationSettings updateApplicationSettings(ApplicationSettings appSettings) throws GitLabApiException { + public ApplicationSettings updateApplicationSettings(final ApplicationSettings appSettings) throws GitLabApiException { if (appSettings == null || appSettings.getSettings().isEmpty()) { throw new GitLabApiException("ApplicationSettings cannot be null or empty."); @@ -54,8 +51,8 @@ public ApplicationSettings updateApplicationSettings(ApplicationSettings appSett final GitLabApiForm form = new GitLabApiForm(); appSettings.getSettings().forEach((s, v) -> form.withParam(s, v)); - Response response = put(Response.Status.OK, form.asMap(), "application", "settings"); - JsonNode root = response.readEntity(JsonNode.class); + final Response response = put(Response.Status.OK, form.asMap(), "application", "settings"); + final JsonNode root = response.readEntity(JsonNode.class); return (parseApplicationSettings(root)); } @@ -69,7 +66,7 @@ public ApplicationSettings updateApplicationSettings(ApplicationSettings appSett * @return the updated application settings in an ApplicationSettings instance * @throws GitLabApiException if any exception occurs */ - public ApplicationSettings updateApplicationSetting(Setting setting, Object value) throws GitLabApiException { + public ApplicationSettings updateApplicationSetting(final Setting setting, final Object value) throws GitLabApiException { if (setting == null) { throw new GitLabApiException("setting cannot be null."); @@ -88,15 +85,15 @@ public ApplicationSettings updateApplicationSetting(Setting setting, Object valu * @return the updated application settings in an ApplicationSettings instance * @throws GitLabApiException if any exception occurs */ - public ApplicationSettings updateApplicationSetting(String setting, Object value) throws GitLabApiException { + public ApplicationSettings updateApplicationSetting(final String setting, final Object value) throws GitLabApiException { if (setting == null || setting.trim().isEmpty()) { throw new GitLabApiException("setting cannot be null or empty."); } - GitLabApiForm form = new GitLabApiForm().withParam(setting, value); - Response response = put(Response.Status.OK, form.asMap(), "application", "settings"); - JsonNode root = response.readEntity(JsonNode.class); + final GitLabApiForm form = new GitLabApiForm().withParam(setting, value); + final Response response = put(Response.Status.OK, form.asMap(), "application", "settings"); + final JsonNode root = response.readEntity(JsonNode.class); return (parseApplicationSettings(root)); } @@ -107,14 +104,14 @@ public ApplicationSettings updateApplicationSetting(String setting, Object value * @return the populated ApplicationSettings instance * @throws GitLabApiException if any error occurs */ - public static final ApplicationSettings parseApplicationSettings(JsonNode root) throws GitLabApiException { + public static final ApplicationSettings parseApplicationSettings(final JsonNode root) throws GitLabApiException { - ApplicationSettings appSettings = new ApplicationSettings(); + final ApplicationSettings appSettings = new ApplicationSettings(); - Iterator fieldNames = root.fieldNames(); + final Iterator fieldNames = root.fieldNames(); while (fieldNames.hasNext()) { - String fieldName = fieldNames.next(); + final String fieldName = fieldNames.next(); switch (fieldName) { case "id": appSettings.setId(root.path(fieldName).asLong()); @@ -122,25 +119,25 @@ public static final ApplicationSettings parseApplicationSettings(JsonNode root) case "created_at": try { - String value = root.path(fieldName).asText(); + final String value = root.path(fieldName).asText(); appSettings.setCreatedAt(ISO8601.toDate(value)); - } catch (ParseException pe) { + } catch (final ParseException pe) { throw new GitLabApiException(pe); } break; case "updated_at": try { - String value = root.path(fieldName).asText(); + final String value = root.path(fieldName).asText(); appSettings.setUpdatedAt(ISO8601.toDate(value)); - } catch (ParseException pe) { + } catch (final ParseException pe) { throw new GitLabApiException(pe); } break; default: - Setting setting = Setting.forValue(fieldName); + final Setting setting = Setting.forValue(fieldName); if (setting != null) { appSettings.addSetting(setting, root.path(fieldName)); } else { diff --git a/src/main/java/org/gitlab4j/api/ApplicationsApi.java b/src/main/java/org/gitlab4j/api/ApplicationsApi.java index b5c793702..1bfe21748 100644 --- a/src/main/java/org/gitlab4j/api/ApplicationsApi.java +++ b/src/main/java/org/gitlab4j/api/ApplicationsApi.java @@ -1,132 +1,144 @@ package org.gitlab4j.api; +import jakarta.ws.rs.core.GenericType; +import jakarta.ws.rs.core.Response; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; - -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; - import org.gitlab4j.api.models.Application; /** - * This class implements the client side API for the GitLab Applications API. - * See Applications API at GitLab for more information. + * This class implements the client side API for the GitLab Applications API. See Applications API at GitLab for more + * information. */ public class ApplicationsApi extends AbstractApi { - public ApplicationsApi(GitLabApi gitLabApi) { - super(gitLabApi); + public ApplicationsApi(final GitLabApi gitLabApi) { + super(gitLabApi); + } + + /** + * Get all OATH applications. + * + *

GitLab Endpoint: GET /api/v4/applications
+ * + * @return a List of OAUTH Application instances + * @throws GitLabApiException if any exception occurs + */ + public List getApplications() throws GitLabApiException { + return (getApplications(getDefaultPerPage()).all()); + } + + /** + * Get all OAUTH applications using the specified page and per page setting + * + *
GitLab Endpoint: GET /api/v4/applications
+ * + * @param page the page to get + * @param perPage the number of items per page + * @return a list of OAUTH Applications in the specified range + * @throws GitLabApiException if any exception occurs + */ + public List getApplications(final int page, final int perPage) + throws GitLabApiException { + final Response response = + get( + jakarta.ws.rs.core.Response.Status.OK, + getPageQueryParams(page, perPage), + "applications"); + return (response.readEntity(new GenericType>() {})); + } + + /** + * Get a Pager of all OAUTH applications. + * + *
GitLab Endpoint: GET /api/v4/applications
+ * + * @param itemsPerPage the number of items per page + * @return a Pager of Application instances in the specified range + * @throws GitLabApiException if any exception occurs + */ + public Pager getApplications(final int itemsPerPage) throws GitLabApiException { + return (new Pager(this, Application.class, itemsPerPage, null, "applications")); + } + + /** + * Get a Stream of all OAUTH Application instances. + * + *
GitLab Endpoint: GET /api/v4/applications
+ * + * @return a Stream of OAUTH Application instances + * @throws GitLabApiException if any exception occurs + */ + public Stream getApplicationsStream() throws GitLabApiException { + return (getApplications(getDefaultPerPage()).stream()); + } + + /** + * Create an OAUTH Application. + * + *
GitLab Endpoint: POST /api/v4/applications
+ * + * @param name the name for the OAUTH Application + * @param redirectUri the redirect URI for the OAUTH Application + * @param scopes the scopes of the application (api, read_user, sudo, read_repository, openid, + * profile, email) + * @return the created Application instance + * @throws GitLabApiException if any exception occurs + */ + public Application createApplication( + final String name, final String redirectUri, final ApplicationScope[] scopes) + throws GitLabApiException { + + if (scopes == null || scopes.length == 0) { + throw new GitLabApiException("scopes cannot be null or empty"); } - /** - * Get all OATH applications. - * - *
GitLab Endpoint: GET /api/v4/applications
- * - * @return a List of OAUTH Application instances - * @throws GitLabApiException if any exception occurs - */ - public List getApplications() throws GitLabApiException { - return (getApplications(getDefaultPerPage()).all()); + return (createApplication(name, redirectUri, Arrays.asList(scopes))); + } + + /** + * Create an OAUTH Application. + * + *
GitLab Endpoint: POST /api/v4/applications
+ * + * @param name the name for the OAUTH Application + * @param redirectUri the redirect URI for the OAUTH Application + * @param scopes the scopes of the application (api, read_user, sudo, read_repository, openid, + * profile, email) + * @return the created Application instance + * @throws GitLabApiException if any exception occurs + */ + public Application createApplication( + final String name, final String redirectUri, final List scopes) + throws GitLabApiException { + + if (scopes == null || scopes.isEmpty()) { + throw new GitLabApiException("scopes cannot be null or empty"); } - /** - * Get all OAUTH applications using the specified page and per page setting - * - *
GitLab Endpoint: GET /api/v4/applications
- * - * @param page the page to get - * @param perPage the number of items per page - * @return a list of OAUTH Applications in the specified range - * @throws GitLabApiException if any exception occurs - */ - public List getApplications(int page, int perPage) throws GitLabApiException { - Response response = get(javax.ws.rs.core.Response.Status.OK, getPageQueryParams(page, perPage), "applications"); - return (response.readEntity(new GenericType>() {})); - } - - /** - * Get a Pager of all OAUTH applications. - * - *
GitLab Endpoint: GET /api/v4/applications
- * - * @param itemsPerPage the number of items per page - * @return a Pager of Application instances in the specified range - * @throws GitLabApiException if any exception occurs - */ - public Pager getApplications(int itemsPerPage) throws GitLabApiException { - return (new Pager(this, Application.class, itemsPerPage, null, "applications")); - } - - /** - * Get a Stream of all OAUTH Application instances. - * - *
GitLab Endpoint: GET /api/v4/applications
- * - * @return a Stream of OAUTH Application instances - * @throws GitLabApiException if any exception occurs - */ - public Stream getApplicationsStream() throws GitLabApiException { - return (getApplications(getDefaultPerPage()).stream()); - } - - /** - * Create an OAUTH Application. - * - *
GitLab Endpoint: POST /api/v4/applications
- * - * @param name the name for the OAUTH Application - * @param redirectUri the redirect URI for the OAUTH Application - * @param scopes the scopes of the application (api, read_user, sudo, read_repository, openid, profile, email) - * @return the created Application instance - * @throws GitLabApiException if any exception occurs - */ - public Application createApplication(String name, String redirectUri, ApplicationScope[] scopes) throws GitLabApiException { - - if (scopes == null || scopes.length == 0) { - throw new GitLabApiException("scopes cannot be null or empty"); - } - - return (createApplication(name, redirectUri, Arrays.asList(scopes))); - } - - /** - * Create an OAUTH Application. - * - *
GitLab Endpoint: POST /api/v4/applications
- * - * @param name the name for the OAUTH Application - * @param redirectUri the redirect URI for the OAUTH Application - * @param scopes the scopes of the application (api, read_user, sudo, read_repository, openid, profile, email) - * @return the created Application instance - * @throws GitLabApiException if any exception occurs - */ - public Application createApplication(String name, String redirectUri, List scopes) throws GitLabApiException { - - if (scopes == null || scopes.isEmpty()) { - throw new GitLabApiException("scopes cannot be null or empty"); - } - - String scopesString = scopes.stream().map(ApplicationScope::toString).collect(Collectors.joining(",")); - GitLabApiForm formData = new GitLabApiForm() - .withParam("name", name, true) - .withParam("redirect_uri", redirectUri, true) - .withParam("scopes", scopesString, true); - Response response = post(Response.Status.CREATED, formData, "applications"); - return (response.readEntity(Application.class)); - } - - /** - * Delete the specified OAUTH Application. - * - *
GitLab Endpoint: DELETE /api/v4/applications/:applicationId
- * - * @param applicationId the ID of the OUAUTH Application to delete - * @throws GitLabApiException if any exception occurs - */ - public void deleteApplication(Long applicationId) throws GitLabApiException { - delete(Response.Status.NO_CONTENT, null, "applications", applicationId); - } + final String scopesString = + scopes.stream().map(ApplicationScope::toString).collect(Collectors.joining(",")); + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("name", name, true) + .withParam("redirect_uri", redirectUri, true) + .withParam("scopes", scopesString, true); + final Response response = post(Response.Status.CREATED, formData, "applications"); + return (response.readEntity(Application.class)); + } + + /** + * Delete the specified OAUTH Application. + * + *
GitLab Endpoint: DELETE /api/v4/applications/:applicationId
+ * + * @param applicationId the ID of the OUAUTH Application to delete + * @throws GitLabApiException if any exception occurs + */ + public void deleteApplication(final Long applicationId) throws GitLabApiException { + delete(Response.Status.NO_CONTENT, null, "applications", applicationId); + } } diff --git a/src/main/java/org/gitlab4j/api/AuditEventApi.java b/src/main/java/org/gitlab4j/api/AuditEventApi.java index eebfb6173..9404696e2 100644 --- a/src/main/java/org/gitlab4j/api/AuditEventApi.java +++ b/src/main/java/org/gitlab4j/api/AuditEventApi.java @@ -1,12 +1,10 @@ package org.gitlab4j.api; +import jakarta.ws.rs.core.Form; +import jakarta.ws.rs.core.Response; import java.util.Date; import java.util.List; import java.util.stream.Stream; - -import javax.ws.rs.core.Form; -import javax.ws.rs.core.Response; - import org.gitlab4j.api.models.AuditEvent; import org.gitlab4j.api.utils.ISO8601; @@ -16,7 +14,7 @@ */ public class AuditEventApi extends AbstractApi { - public AuditEventApi(GitLabApi gitLabApi) { + public AuditEventApi(final GitLabApi gitLabApi) { super(gitLabApi); } @@ -32,7 +30,7 @@ public AuditEventApi(GitLabApi gitLabApi) { * @return a List of group Audit events * @throws GitLabApiException if any exception occurs */ - public List getAuditEvents(Date created_after, Date created_before, String entityType, Long entityId) throws GitLabApiException { + public List getAuditEvents(final Date created_after, final Date created_before, final String entityType, final Long entityId) throws GitLabApiException { return (getAuditEvents(created_after, created_before, entityType, entityId, getDefaultPerPage()).all()); } @@ -49,8 +47,8 @@ public List getAuditEvents(Date created_after, Date created_before, * @return a Pager of group Audit events * @throws GitLabApiException if any exception occurs */ - public Pager getAuditEvents(Date created_after, Date created_before, String entityType, Long entityId, int itemsPerPage) throws GitLabApiException { - Form form = new GitLabApiForm() + public Pager getAuditEvents(final Date created_after, final Date created_before, final String entityType, final Long entityId, final int itemsPerPage) throws GitLabApiException { + final Form form = new GitLabApiForm() .withParam("created_before", ISO8601.toString(created_before, false)) .withParam("created_after", ISO8601.toString(created_after, false)) .withParam("entity_type", entityType) @@ -70,7 +68,7 @@ public Pager getAuditEvents(Date created_after, Date created_before, * @return a Stream of group Audit events * @throws GitLabApiException if any exception occurs */ - public Stream getAuditEventsStream(Date created_after, Date created_before, String entityType, Long entityId) throws GitLabApiException { + public Stream getAuditEventsStream(final Date created_after, final Date created_before, final String entityType, final Long entityId) throws GitLabApiException { return (getAuditEvents(created_after, created_before, entityType, entityId, getDefaultPerPage()).stream()); } @@ -83,8 +81,8 @@ public Stream getAuditEventsStream(Date created_after, Date created_ * @return the group Audit event * @throws GitLabApiException if any exception occurs */ - public AuditEvent getAuditEvent(Long auditEventId) throws GitLabApiException { - Response response = get(Response.Status.OK, null, "audit_events", auditEventId); + public AuditEvent getAuditEvent(final Long auditEventId) throws GitLabApiException { + final Response response = get(Response.Status.OK, null, "audit_events", auditEventId); return (response.readEntity(AuditEvent.class)); } } diff --git a/src/main/java/org/gitlab4j/api/AwardEmojiApi.java b/src/main/java/org/gitlab4j/api/AwardEmojiApi.java index dce6a1306..53a7f9db1 100644 --- a/src/main/java/org/gitlab4j/api/AwardEmojiApi.java +++ b/src/main/java/org/gitlab4j/api/AwardEmojiApi.java @@ -1,427 +1,702 @@ package org.gitlab4j.api; +import jakarta.ws.rs.core.GenericType; +import jakarta.ws.rs.core.Response; import java.util.List; - -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; - import org.gitlab4j.api.models.AwardEmoji; /** * This class implements the client side API for the GitLab Award Emoji API calls. * - * @see GitLab Award Emoji API Documentaion + * @see GitLab Award Emoji API + * Documentaion * @since v4.8.31 */ public class AwardEmojiApi extends AbstractApi { - public AwardEmojiApi(GitLabApi gitLabApi) { - super(gitLabApi); - } + public AwardEmojiApi(final GitLabApi gitLabApi) { + super(gitLabApi); + } - /** - * Get a list of award emoji for the specified issue. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/award_emoji
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param issueIid the issue IID to get the award emojis for - * @return a list of AwardEmoji for the specified issue - * @throws GitLabApiException if any exception occurs - */ - public List getIssueAwardEmojis(Object projectIdOrPath, Long issueIid) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(1, getDefaultPerPage()), - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "award_emoji"); - return response.readEntity(new GenericType>() {}); - } + /** + * Get a list of award emoji for the specified issue. + * + *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/award_emoji
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param issueIid the issue IID to get the award emojis for + * @return a list of AwardEmoji for the specified issue + * @throws GitLabApiException if any exception occurs + */ + public List getIssueAwardEmojis(final Object projectIdOrPath, final Long issueIid) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getPageQueryParams(1, getDefaultPerPage()), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "award_emoji"); + return response.readEntity(new GenericType>() {}); + } - /** - * Get a list of award emoji for the specified merge request. - * - *
GitLab Endpoint: GET /projects/:id/merge_requests/:merge_request_iid/award_emoji
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param mergeRequestIid the merge request IID to get the award emojis for - * @return a list of AwardEmoji for the specified merge request - * @throws GitLabApiException if any exception occurs - */ - public List getMergeRequestAwardEmojis(Object projectIdOrPath, Long mergeRequestIid) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(1, getDefaultPerPage()), - "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "award_emoji"); - return response.readEntity(new GenericType>() {}); - } + /** + * Get a list of award emoji for the specified merge request. + * + *
+   * GitLab Endpoint: GET /projects/:id/merge_requests/:merge_request_iid/award_emoji
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param mergeRequestIid the merge request IID to get the award emojis for + * @return a list of AwardEmoji for the specified merge request + * @throws GitLabApiException if any exception occurs + */ + public List getMergeRequestAwardEmojis( + final Object projectIdOrPath, final Long mergeRequestIid) throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getPageQueryParams(1, getDefaultPerPage()), + "projects", + getProjectIdOrPath(projectIdOrPath), + "merge_requests", + mergeRequestIid, + "award_emoji"); + return response.readEntity(new GenericType>() {}); + } - /** - * Get a list of award emoji for the specified snippet. - * - *
GitLab Endpoint: GET /projects/:id/snippets/:snippet_id/award_emoji
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param snippetId the snippet ID to get the award emojis for - * @return a list of AwardEmoji for the specified snippet - * @throws GitLabApiException if any exception occurs - */ - public List getSnippetAwardEmojis(Object projectIdOrPath, Long snippetId) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(1, getDefaultPerPage()), - "projects", getProjectIdOrPath(projectIdOrPath), "snippets", snippetId, "award_emoji"); - return response.readEntity(new GenericType>() {}); - } + /** + * Get a list of award emoji for the specified snippet. + * + *
GitLab Endpoint: GET /projects/:id/snippets/:snippet_id/award_emoji
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param snippetId the snippet ID to get the award emojis for + * @return a list of AwardEmoji for the specified snippet + * @throws GitLabApiException if any exception occurs + */ + public List getSnippetAwardEmojis(final Object projectIdOrPath, final Long snippetId) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getPageQueryParams(1, getDefaultPerPage()), + "projects", + getProjectIdOrPath(projectIdOrPath), + "snippets", + snippetId, + "award_emoji"); + return response.readEntity(new GenericType>() {}); + } - /** - * Get a list of award emoji for the specified issue note. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/notes/:note_id/award_emoji
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param issueIid the issue IID of the issue that owns the note - * @param noteId the note ID to get the award emojis for - * @return a list of AwardEmoji for the specified note - * @throws GitLabApiException if any exception occurs - */ - public List getIssueNoteAwardEmojis(Object projectIdOrPath, Long issueIid, Long noteId) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(1, getDefaultPerPage()), - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "notes", noteId, "award_emoji"); - return response.readEntity(new GenericType>() {}); - } + /** + * Get a list of award emoji for the specified issue note. + * + *
+   * GitLab Endpoint: GET /projects/:id/issues/:issue_iid/notes/:note_id/award_emoji
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param issueIid the issue IID of the issue that owns the note + * @param noteId the note ID to get the award emojis for + * @return a list of AwardEmoji for the specified note + * @throws GitLabApiException if any exception occurs + */ + public List getIssueNoteAwardEmojis( + final Object projectIdOrPath, final Long issueIid, final Long noteId) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getPageQueryParams(1, getDefaultPerPage()), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "notes", + noteId, + "award_emoji"); + return response.readEntity(new GenericType>() {}); + } - /** - * Get a list of award emoji for the specified issue note. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/notes/:note_id/award_emoji
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param issueIid the issue IID of the issue that owns the note - * @param noteId the note ID to get the award emojis for - * @return a list of AwardEmoji for the specified note - * @throws GitLabApiException if any exception occurs - */ - public List getNoteAwardEmojis(Object projectIdOrPath, Long issueIid, Long noteId) throws GitLabApiException { - return getIssueNoteAwardEmojis(projectIdOrPath, issueIid, noteId); - } + /** + * Get a list of award emoji for the specified issue note. + * + *
+   * GitLab Endpoint: GET /projects/:id/issues/:issue_iid/notes/:note_id/award_emoji
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param issueIid the issue IID of the issue that owns the note + * @param noteId the note ID to get the award emojis for + * @return a list of AwardEmoji for the specified note + * @throws GitLabApiException if any exception occurs + */ + public List getNoteAwardEmojis( + final Object projectIdOrPath, final Long issueIid, final Long noteId) + throws GitLabApiException { + return getIssueNoteAwardEmojis(projectIdOrPath, issueIid, noteId); + } - /** - * Get a list of award emoji for the specified merge request note. - * - *
GitLab Endpoint: GET /projects/:id/merge_requests/:merge_request_iid/notes/:note_id/award_emoji
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param mergeRequestIid the merge request IID of the merge request that owns the note - * @param noteId the note ID to get the award emojis for - * @return a list of AwardEmoji for the specified note - * @throws GitLabApiException if any exception occurs - */ - public List getMergeRequestNoteAwardEmojis(Object projectIdOrPath, Long mergeRequestIid, Long noteId) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(1, getDefaultPerPage()), - "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "notes", noteId, "award_emoji"); - return response.readEntity(new GenericType>() {}); - } + /** + * Get a list of award emoji for the specified merge request note. + * + *
+   * GitLab Endpoint: GET /projects/:id/merge_requests/:merge_request_iid/notes/:note_id/award_emoji
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param mergeRequestIid the merge request IID of the merge request that owns the note + * @param noteId the note ID to get the award emojis for + * @return a list of AwardEmoji for the specified note + * @throws GitLabApiException if any exception occurs + */ + public List getMergeRequestNoteAwardEmojis( + final Object projectIdOrPath, final Long mergeRequestIid, final Long noteId) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getPageQueryParams(1, getDefaultPerPage()), + "projects", + getProjectIdOrPath(projectIdOrPath), + "merge_requests", + mergeRequestIid, + "notes", + noteId, + "award_emoji"); + return response.readEntity(new GenericType>() {}); + } - /** - * Get the specified award emoji for the specified issue. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/award_emoji/:award_id
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param issueIid the issue IID to get the award emoji for - * @param awardId the ID of the award emoji to get - * @return an AwardEmoji instance for the specified award emoji - * @throws GitLabApiException if any exception occurs - */ - public AwardEmoji getIssueAwardEmoji(Object projectIdOrPath, Long issueIid, Long awardId) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(1, getDefaultPerPage()), - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "award_emoji", awardId); - return (response.readEntity(AwardEmoji.class)); - } + /** + * Get the specified award emoji for the specified issue. + * + *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/award_emoji/:award_id
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param issueIid the issue IID to get the award emoji for + * @param awardId the ID of the award emoji to get + * @return an AwardEmoji instance for the specified award emoji + * @throws GitLabApiException if any exception occurs + */ + public AwardEmoji getIssueAwardEmoji( + final Object projectIdOrPath, final Long issueIid, final Long awardId) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getPageQueryParams(1, getDefaultPerPage()), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "award_emoji", + awardId); + return (response.readEntity(AwardEmoji.class)); + } - /** - * Get the specified award emoji for the specified merge request. - * - *
GitLab Endpoint: GET /projects/:id/merge_requests/:merge_request_iid/award_emoji/:award_id
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param mergeRequestIid the merge request IID to get the award emoji for - * @param awardId the ID of the award emoji to get - * @return an AwardEmoji instance for the specified award emoji - * @throws GitLabApiException if any exception occurs - */ - public AwardEmoji getMergeRequestAwardEmoji(Object projectIdOrPath, Long mergeRequestIid, Long awardId) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(1, getDefaultPerPage()), - "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "award_emoji", awardId); - return (response.readEntity(AwardEmoji.class)); - } + /** + * Get the specified award emoji for the specified merge request. + * + *
+   * GitLab Endpoint: GET /projects/:id/merge_requests/:merge_request_iid/award_emoji/:award_id
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param mergeRequestIid the merge request IID to get the award emoji for + * @param awardId the ID of the award emoji to get + * @return an AwardEmoji instance for the specified award emoji + * @throws GitLabApiException if any exception occurs + */ + public AwardEmoji getMergeRequestAwardEmoji( + final Object projectIdOrPath, final Long mergeRequestIid, final Long awardId) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getPageQueryParams(1, getDefaultPerPage()), + "projects", + getProjectIdOrPath(projectIdOrPath), + "merge_requests", + mergeRequestIid, + "award_emoji", + awardId); + return (response.readEntity(AwardEmoji.class)); + } - /** - * Get the specified award emoji for the specified snippet. - * - *
GitLab Endpoint: GET /projects/:id/snippets/:snippet_id/award_emoji/:award_id
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param snippetId the snippet ID to get the award emoji for - * @param awardId the ID of the award emoji to get - * @return an AwardEmoji instance for the specified award emoji - * @throws GitLabApiException if any exception occurs - */ - public AwardEmoji getSnippetAwardEmoji(Object projectIdOrPath, Long snippetId, Long awardId) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(1, getDefaultPerPage()), - "projects", getProjectIdOrPath(projectIdOrPath), "snippets", snippetId, "award_emoji", awardId); - return (response.readEntity(AwardEmoji.class)); - } + /** + * Get the specified award emoji for the specified snippet. + * + *
GitLab Endpoint: GET /projects/:id/snippets/:snippet_id/award_emoji/:award_id
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param snippetId the snippet ID to get the award emoji for + * @param awardId the ID of the award emoji to get + * @return an AwardEmoji instance for the specified award emoji + * @throws GitLabApiException if any exception occurs + */ + public AwardEmoji getSnippetAwardEmoji( + final Object projectIdOrPath, final Long snippetId, final Long awardId) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getPageQueryParams(1, getDefaultPerPage()), + "projects", + getProjectIdOrPath(projectIdOrPath), + "snippets", + snippetId, + "award_emoji", + awardId); + return (response.readEntity(AwardEmoji.class)); + } - /** - * Get the specified award emoji for the specified issue note. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/notes/:note_id/award_emoji/:award_id
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param issueIid the issue IID of the issue that owns the note - * @param noteId the note ID to get the award emoji from - * @param awardId the ID of the award emoji to get - * @return an AwardEmoji instance for the specified award emoji - * @throws GitLabApiException if any exception occurs - */ - public AwardEmoji getIssueNoteAwardEmoji(Object projectIdOrPath, Long issueIid, Long noteId, Long awardId) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(1, getDefaultPerPage()), - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "notes", noteId, "award_emoji", awardId); - return (response.readEntity(AwardEmoji.class)); - } + /** + * Get the specified award emoji for the specified issue note. + * + *
+   * GitLab Endpoint: GET /projects/:id/issues/:issue_iid/notes/:note_id/award_emoji/:award_id
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param issueIid the issue IID of the issue that owns the note + * @param noteId the note ID to get the award emoji from + * @param awardId the ID of the award emoji to get + * @return an AwardEmoji instance for the specified award emoji + * @throws GitLabApiException if any exception occurs + */ + public AwardEmoji getIssueNoteAwardEmoji( + final Object projectIdOrPath, final Long issueIid, final Long noteId, final Long awardId) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getPageQueryParams(1, getDefaultPerPage()), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "notes", + noteId, + "award_emoji", + awardId); + return (response.readEntity(AwardEmoji.class)); + } - /** - * Get the specified award emoji for the specified issue note. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/notes/:note_id/award_emoji/:award_id
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param issueIid the issue IID of the issue that owns the note - * @param noteId the note ID to get the award emoji from - * @param awardId the ID of the award emoji to get - * @return an AwardEmoji instance for the specified award emoji - * @throws GitLabApiException if any exception occurs - * @deprecated use {@link #getIssueNoteAwardEmoji(Object, Long, Long, Long)} instead - */ - @Deprecated - public AwardEmoji getNoteAwardEmoji(Object projectIdOrPath, Long issueIid, Long noteId, Long awardId) throws GitLabApiException { - return getIssueNoteAwardEmoji(projectIdOrPath, issueIid, noteId, awardId); - } + /** + * Get the specified award emoji for the specified issue note. + * + *
+   * GitLab Endpoint: GET /projects/:id/issues/:issue_iid/notes/:note_id/award_emoji/:award_id
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param issueIid the issue IID of the issue that owns the note + * @param noteId the note ID to get the award emoji from + * @param awardId the ID of the award emoji to get + * @return an AwardEmoji instance for the specified award emoji + * @throws GitLabApiException if any exception occurs + * @deprecated use {@link #getIssueNoteAwardEmoji(Object, Long, Long, Long)} instead + */ + @Deprecated + public AwardEmoji getNoteAwardEmoji( + final Object projectIdOrPath, final Long issueIid, final Long noteId, final Long awardId) + throws GitLabApiException { + return getIssueNoteAwardEmoji(projectIdOrPath, issueIid, noteId, awardId); + } - /** - * Get the specified award emoji for the specified merge request note. - * - *
GitLab Endpoint: GET /projects/:id/merge_requests/:merge_request_iid/notes/:note_id/award_emoji/:award_id
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param mergeRequestIid the merge request IID of the merge request that owns the note - * @param noteId the note ID to get the award emoji from - * @param awardId the ID of the award emoji to get - * @return an AwardEmoji instance for the specified award emoji - * @throws GitLabApiException if any exception occurs - */ - public AwardEmoji getMergeRequestNoteAwardEmoji(Object projectIdOrPath, Long mergeRequestIid, Long noteId, Long awardId) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(1, getDefaultPerPage()), - "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "notes", noteId, "award_emoji", awardId); - return (response.readEntity(AwardEmoji.class)); - } + /** + * Get the specified award emoji for the specified merge request note. + * + *
+   * GitLab Endpoint: GET /projects/:id/merge_requests/:merge_request_iid/notes/:note_id/award_emoji/:award_id
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param mergeRequestIid the merge request IID of the merge request that owns the note + * @param noteId the note ID to get the award emoji from + * @param awardId the ID of the award emoji to get + * @return an AwardEmoji instance for the specified award emoji + * @throws GitLabApiException if any exception occurs + */ + public AwardEmoji getMergeRequestNoteAwardEmoji( + final Object projectIdOrPath, + final Long mergeRequestIid, + final Long noteId, + final Long awardId) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getPageQueryParams(1, getDefaultPerPage()), + "projects", + getProjectIdOrPath(projectIdOrPath), + "merge_requests", + mergeRequestIid, + "notes", + noteId, + "award_emoji", + awardId); + return (response.readEntity(AwardEmoji.class)); + } - /** - * Add an award emoji for the specified issue. - * - *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/award_emoji
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param issueIid the issue IID to add the award emoji to - * @param name the name of the award emoji to add - * @return an AwardEmoji instance for the added award emoji - * @throws GitLabApiException if any exception occurs - */ - public AwardEmoji addIssueAwardEmoji(Object projectIdOrPath, Long issueIid, String name) throws GitLabApiException { - GitLabApiForm form = new GitLabApiForm().withParam("name", name, true); - Response response = post(Response.Status.CREATED, form.asMap(), - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "award_emoji"); - return (response.readEntity(AwardEmoji.class)); - } + /** + * Add an award emoji for the specified issue. + * + *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/award_emoji
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param issueIid the issue IID to add the award emoji to + * @param name the name of the award emoji to add + * @return an AwardEmoji instance for the added award emoji + * @throws GitLabApiException if any exception occurs + */ + public AwardEmoji addIssueAwardEmoji( + final Object projectIdOrPath, final Long issueIid, final String name) + throws GitLabApiException { + final GitLabApiForm form = new GitLabApiForm().withParam("name", name, true); + final Response response = + post( + Response.Status.CREATED, + form.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "award_emoji"); + return (response.readEntity(AwardEmoji.class)); + } - /** - * Add an award emoji to the specified merge request. - * - *
GitLab Endpoint: POST /projects/:id/merge_requests/:merge_request_iid/award_emoji
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param mergeRequestIid the merge request IID to add the award emoji to - * @param name the name of the award emoji to add - * @return an AwardEmoji instance for the added award emoji - * @throws GitLabApiException if any exception occurs - */ - public AwardEmoji addMergeRequestAwardEmoji(Object projectIdOrPath, Long mergeRequestIid, String name) throws GitLabApiException { - GitLabApiForm form = new GitLabApiForm().withParam("name", name, true); - Response response = post(Response.Status.CREATED, form.asMap(), - "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "award_emoji"); - return (response.readEntity(AwardEmoji.class)); - } + /** + * Add an award emoji to the specified merge request. + * + *
+   * GitLab Endpoint: POST /projects/:id/merge_requests/:merge_request_iid/award_emoji
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param mergeRequestIid the merge request IID to add the award emoji to + * @param name the name of the award emoji to add + * @return an AwardEmoji instance for the added award emoji + * @throws GitLabApiException if any exception occurs + */ + public AwardEmoji addMergeRequestAwardEmoji( + final Object projectIdOrPath, final Long mergeRequestIid, final String name) + throws GitLabApiException { + final GitLabApiForm form = new GitLabApiForm().withParam("name", name, true); + final Response response = + post( + Response.Status.CREATED, + form.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "merge_requests", + mergeRequestIid, + "award_emoji"); + return (response.readEntity(AwardEmoji.class)); + } - /** - * Add an award emoji to the specified snippet. - * - *
GitLab Endpoint: POST /projects/:id/snippets/:snippet_id/award_emoji
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param snippetId the snippet ID to add the award emoji to - * @param name the name of the award emoji to add - * @return an AwardEmoji instance for the added award emoji - * @throws GitLabApiException if any exception occurs - */ - public AwardEmoji addSnippetAwardEmoji(Object projectIdOrPath, Long snippetId, String name) throws GitLabApiException { - GitLabApiForm form = new GitLabApiForm().withParam("name", name, true); - Response response = post(Response.Status.CREATED, form.asMap(), - "projects", getProjectIdOrPath(projectIdOrPath), "snippets", snippetId, "award_emoji"); - return (response.readEntity(AwardEmoji.class)); - } + /** + * Add an award emoji to the specified snippet. + * + *
GitLab Endpoint: POST /projects/:id/snippets/:snippet_id/award_emoji
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param snippetId the snippet ID to add the award emoji to + * @param name the name of the award emoji to add + * @return an AwardEmoji instance for the added award emoji + * @throws GitLabApiException if any exception occurs + */ + public AwardEmoji addSnippetAwardEmoji( + final Object projectIdOrPath, final Long snippetId, final String name) + throws GitLabApiException { + final GitLabApiForm form = new GitLabApiForm().withParam("name", name, true); + final Response response = + post( + Response.Status.CREATED, + form.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "snippets", + snippetId, + "award_emoji"); + return (response.readEntity(AwardEmoji.class)); + } - /** - * Add an award emoji for the specified issue note. - * - *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/notes/:noteId/award_emoji
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param issueIid the issue IID of the issue that owns the note - * @param noteId the note ID to add the award emoji to - * @param name the name of the award emoji to add - * @return an AwardEmoji instance for the added award emoji - * @throws GitLabApiException if any exception occurs - */ - public AwardEmoji addIssueNoteAwardEmoji(Object projectIdOrPath, Long issueIid, Long noteId, String name) throws GitLabApiException { - GitLabApiForm form = new GitLabApiForm().withParam("name", name, true); - Response response = post(Response.Status.CREATED, form.asMap(), - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "notes", noteId, "award_emoji"); - return (response.readEntity(AwardEmoji.class)); - } + /** + * Add an award emoji for the specified issue note. + * + *
+   * GitLab Endpoint: POST /projects/:id/issues/:issue_iid/notes/:noteId/award_emoji
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param issueIid the issue IID of the issue that owns the note + * @param noteId the note ID to add the award emoji to + * @param name the name of the award emoji to add + * @return an AwardEmoji instance for the added award emoji + * @throws GitLabApiException if any exception occurs + */ + public AwardEmoji addIssueNoteAwardEmoji( + final Object projectIdOrPath, final Long issueIid, final Long noteId, final String name) + throws GitLabApiException { + final GitLabApiForm form = new GitLabApiForm().withParam("name", name, true); + final Response response = + post( + Response.Status.CREATED, + form.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "notes", + noteId, + "award_emoji"); + return (response.readEntity(AwardEmoji.class)); + } - /** - * Add an award emoji for the specified issue note. - * - *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/notes/:noteId/award_emoji
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param issueIid the issue IID of the issue that owns the note - * @param noteId the note ID to add the award emoji to - * @param name the name of the award emoji to add - * @return an AwardEmoji instance for the added award emoji - * @throws GitLabApiException if any exception occurs - * @deprecated use {@link #addIssueNoteAwardEmoji(Object, Long, Long, String)} - */ - @Deprecated - public AwardEmoji addNoteAwardEmoji(Object projectIdOrPath, Long issueIid, Long noteId, String name) throws GitLabApiException { - return addIssueNoteAwardEmoji(projectIdOrPath, issueIid, noteId, name); - } + /** + * Add an award emoji for the specified issue note. + * + *
+   * GitLab Endpoint: POST /projects/:id/issues/:issue_iid/notes/:noteId/award_emoji
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param issueIid the issue IID of the issue that owns the note + * @param noteId the note ID to add the award emoji to + * @param name the name of the award emoji to add + * @return an AwardEmoji instance for the added award emoji + * @throws GitLabApiException if any exception occurs + * @deprecated use {@link #addIssueNoteAwardEmoji(Object, Long, Long, String)} + */ + @Deprecated + public AwardEmoji addNoteAwardEmoji( + final Object projectIdOrPath, final Long issueIid, final Long noteId, final String name) + throws GitLabApiException { + return addIssueNoteAwardEmoji(projectIdOrPath, issueIid, noteId, name); + } - /** - * Add an award emoji for the specified merge request note. - * - *
GitLab Endpoint: POST /projects/:id/merge_requests/:merge_request_iid/notes/:noteId/award_emoji
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param mergeRequestIid the merge request IID of the merge request that owns the note - * @param noteId the note ID to add the award emoji to - * @param name the name of the award emoji to add - * @return an AwardEmoji instance for the added award emoji - * @throws GitLabApiException if any exception occurs - */ - public AwardEmoji addMergeRequestAwardEmoji(Object projectIdOrPath, Integer mergeRequestIid, Integer noteId, String name) throws GitLabApiException { - GitLabApiForm form = new GitLabApiForm().withParam("name", name, true); - Response response = post(Response.Status.CREATED, form.asMap(), - "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "notes", noteId, "award_emoji"); - return (response.readEntity(AwardEmoji.class)); - } + /** + * Add an award emoji for the specified merge request note. + * + *
+   * GitLab Endpoint: POST /projects/:id/merge_requests/:merge_request_iid/notes/:noteId/award_emoji
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param mergeRequestIid the merge request IID of the merge request that owns the note + * @param noteId the note ID to add the award emoji to + * @param name the name of the award emoji to add + * @return an AwardEmoji instance for the added award emoji + * @throws GitLabApiException if any exception occurs + */ + public AwardEmoji addMergeRequestAwardEmoji( + final Object projectIdOrPath, + final Integer mergeRequestIid, + final Integer noteId, + final String name) + throws GitLabApiException { + final GitLabApiForm form = new GitLabApiForm().withParam("name", name, true); + final Response response = + post( + Response.Status.CREATED, + form.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "merge_requests", + mergeRequestIid, + "notes", + noteId, + "award_emoji"); + return (response.readEntity(AwardEmoji.class)); + } - /** - * Delete an award emoji from the specified issue. - * - *
GitLab Endpoint: DELETE /projects/:id/issues/:issue_iid/award_emoji/:award_id
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param issueIid the issue IID to delete the award emoji from - * @param awardId the ID of the award emoji to delete - * @throws GitLabApiException if any exception occurs - */ - public void deleteIssueAwardEmoji(Object projectIdOrPath, Long issueIid, Long awardId) throws GitLabApiException { - delete(Response.Status.NO_CONTENT, null, - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "award_emoji", awardId); - } + /** + * Delete an award emoji from the specified issue. + * + *
GitLab Endpoint: DELETE /projects/:id/issues/:issue_iid/award_emoji/:award_id
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param issueIid the issue IID to delete the award emoji from + * @param awardId the ID of the award emoji to delete + * @throws GitLabApiException if any exception occurs + */ + public void deleteIssueAwardEmoji( + final Object projectIdOrPath, final Long issueIid, final Long awardId) + throws GitLabApiException { + delete( + Response.Status.NO_CONTENT, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "award_emoji", + awardId); + } - /** - * Delete an award emoji from the specified merge request. - * - *
GitLab Endpoint: DELETE /projects/:id/merge_requests/:merge_request_iid/award_emoji/:award_id
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param mergeRequestIid the merge request IID to delete the award emoji from - * @param awardId the ID of the award emoji to delete - * @throws GitLabApiException if any exception occurs - */ - public void deleteMergeRequestAwardEmoji(Object projectIdOrPath, Long mergeRequestIid, Long awardId) throws GitLabApiException { - delete(Response.Status.NO_CONTENT, null, - "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "award_emoji", awardId); - } + /** + * Delete an award emoji from the specified merge request. + * + *
+   * GitLab Endpoint: DELETE /projects/:id/merge_requests/:merge_request_iid/award_emoji/:award_id
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param mergeRequestIid the merge request IID to delete the award emoji from + * @param awardId the ID of the award emoji to delete + * @throws GitLabApiException if any exception occurs + */ + public void deleteMergeRequestAwardEmoji( + final Object projectIdOrPath, final Long mergeRequestIid, final Long awardId) + throws GitLabApiException { + delete( + Response.Status.NO_CONTENT, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "merge_requests", + mergeRequestIid, + "award_emoji", + awardId); + } - /** - * Delete an award emoji from the specified snippet. - * - *
GitLab Endpoint: DELETE /projects/:id/snippets/:snippet_id/award_emoji/:award_id
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param snippetId the snippet ID to delete the award emoji from - * @param awardId the ID of the award emoji to delete - * @throws GitLabApiException if any exception occurs - */ - public void deleteSnippetAwardEmoji(Object projectIdOrPath, Long snippetId, Long awardId) throws GitLabApiException { - delete(Response.Status.NO_CONTENT, null, - "projects", getProjectIdOrPath(projectIdOrPath), "snippets", snippetId, "award_emoji", awardId); - } + /** + * Delete an award emoji from the specified snippet. + * + *
+   * GitLab Endpoint: DELETE /projects/:id/snippets/:snippet_id/award_emoji/:award_id
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param snippetId the snippet ID to delete the award emoji from + * @param awardId the ID of the award emoji to delete + * @throws GitLabApiException if any exception occurs + */ + public void deleteSnippetAwardEmoji( + final Object projectIdOrPath, final Long snippetId, final Long awardId) + throws GitLabApiException { + delete( + Response.Status.NO_CONTENT, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "snippets", + snippetId, + "award_emoji", + awardId); + } - /** - * Delete an award emoji from the specified issue note. - * - *
GitLab Endpoint: DELETE /projects/:id/issues/:issue_iid/notes/:note_id/award_emoji/:award_id
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param issueIid the issue IID that owns the note - * @param noteId the note ID of the note to delete the award emoji from - * @param awardId the ID of the award emoji to delete - * @throws GitLabApiException if any exception occurs - */ - public void deleteIssueNoteAwardEmoji(Object projectIdOrPath, Long issueIid, Long noteId, Long awardId) throws GitLabApiException { - delete(Response.Status.NO_CONTENT, null, - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "notes", noteId, "award_emoji", awardId); - } + /** + * Delete an award emoji from the specified issue note. + * + *
+   * GitLab Endpoint: DELETE /projects/:id/issues/:issue_iid/notes/:note_id/award_emoji/:award_id
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param issueIid the issue IID that owns the note + * @param noteId the note ID of the note to delete the award emoji from + * @param awardId the ID of the award emoji to delete + * @throws GitLabApiException if any exception occurs + */ + public void deleteIssueNoteAwardEmoji( + final Object projectIdOrPath, final Long issueIid, final Long noteId, final Long awardId) + throws GitLabApiException { + delete( + Response.Status.NO_CONTENT, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "notes", + noteId, + "award_emoji", + awardId); + } - /** - * Delete an award emoji from the specified issue note. - * - *
GitLab Endpoint: DELETE /projects/:id/issues/:issue_iid/notes/:note_id/award_emoji/:award_id
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param issueIid the issue IID that owns the note - * @param noteId the note ID of the note to delete the award emoji from - * @param awardId the ID of the award emoji to delete - * @throws GitLabApiException if any exception occurs - * @deprecated use {@link #deleteIssueNoteAwardEmoji(Object, Long, Long, Long)} instead - */ - @Deprecated - public void deleteNoteAwardEmoji(Object projectIdOrPath, Long issueIid, Long noteId, Long awardId) throws GitLabApiException { - deleteIssueNoteAwardEmoji(projectIdOrPath, issueIid, noteId, awardId); - } + /** + * Delete an award emoji from the specified issue note. + * + *
+   * GitLab Endpoint: DELETE /projects/:id/issues/:issue_iid/notes/:note_id/award_emoji/:award_id
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param issueIid the issue IID that owns the note + * @param noteId the note ID of the note to delete the award emoji from + * @param awardId the ID of the award emoji to delete + * @throws GitLabApiException if any exception occurs + * @deprecated use {@link #deleteIssueNoteAwardEmoji(Object, Long, Long, Long)} instead + */ + @Deprecated + public void deleteNoteAwardEmoji( + final Object projectIdOrPath, final Long issueIid, final Long noteId, final Long awardId) + throws GitLabApiException { + deleteIssueNoteAwardEmoji(projectIdOrPath, issueIid, noteId, awardId); + } - /** - * Delete an award emoji from the specified merge request note. - * - *
GitLab Endpoint: DELETE /projects/:id/merge_requests/:merge_request_iid/notes/:note_id/award_emoji/:award_id
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param mergeRequestIid the merge request IID of the merge request that owns the note - * @param noteId the note ID of the note to delete the award emoji from - * @param awardId the ID of the award emoji to delete - * @throws GitLabApiException if any exception occurs - */ - public void deleteMergeRequestNoteAwardEmoji(Object projectIdOrPath, Long mergeRequestIid, Long noteId, Long awardId) throws GitLabApiException { - delete(Response.Status.NO_CONTENT, null, - "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "notes", noteId, "award_emoji", awardId); - } + /** + * Delete an award emoji from the specified merge request note. + * + *
+   * GitLab Endpoint: DELETE /projects/:id/merge_requests/:merge_request_iid/notes/:note_id/award_emoji/:award_id
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param mergeRequestIid the merge request IID of the merge request that owns the note + * @param noteId the note ID of the note to delete the award emoji from + * @param awardId the ID of the award emoji to delete + * @throws GitLabApiException if any exception occurs + */ + public void deleteMergeRequestNoteAwardEmoji( + final Object projectIdOrPath, + final Long mergeRequestIid, + final Long noteId, + final Long awardId) + throws GitLabApiException { + delete( + Response.Status.NO_CONTENT, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "merge_requests", + mergeRequestIid, + "notes", + noteId, + "award_emoji", + awardId); + } } diff --git a/src/main/java/org/gitlab4j/api/BoardsApi.java b/src/main/java/org/gitlab4j/api/BoardsApi.java index 975cba5e4..ff04152da 100644 --- a/src/main/java/org/gitlab4j/api/BoardsApi.java +++ b/src/main/java/org/gitlab4j/api/BoardsApi.java @@ -3,327 +3,453 @@ import java.util.List; import java.util.Optional; import java.util.stream.Stream; - -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; - +import jakarta.ws.rs.core.GenericType; +import jakarta.ws.rs.core.Response; import org.gitlab4j.api.models.Board; import org.gitlab4j.api.models.BoardList; /** * This class implements the client side API for the GitLab Issue Boards API calls. * - * NOTE: If a user is not a member of a group and the group is private, - * a GET request on that group will result to a 404 status code. + *

NOTE: If a user is not a member of a group and the group is private, a GET request on that + * group will result to a 404 status code. * - * @see GitLab Issue Boards API Documentaion + * @see GitLab Issue Boards API + * Documentaion */ public class BoardsApi extends AbstractApi { - public BoardsApi(GitLabApi gitLabApi) { - super(gitLabApi); - } + public BoardsApi(final GitLabApi gitLabApi) { + super(gitLabApi); + } - /** - * Lists Issue Boards in the given project. - * - *

GitLab Endpoint: GET /projects/:id/boards
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @return a list of project's issue boards - * @throws GitLabApiException if any exception occurs - */ - public List getBoards(Object projectIdOrPath) throws GitLabApiException { - return (getBoards(projectIdOrPath, getDefaultPerPage()).all()); - } + /** + * Lists Issue Boards in the given project. + * + *
GitLab Endpoint: GET /projects/:id/boards
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @return a list of project's issue boards + * @throws GitLabApiException if any exception occurs + */ + public List getBoards(final Object projectIdOrPath) throws GitLabApiException { + return (getBoards(projectIdOrPath, getDefaultPerPage()).all()); + } - /** - * Get all issue boards for the specified project using the specified page and per page setting - * - *
GitLab Endpoint: GET /projects/:id/boards
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param page the page to get - * @param perPage the number of items per page - * @return a list of project's Boards in the specified range - * @throws GitLabApiException if any exception occurs - */ - public List getBoards(Object projectIdOrPath, int page, int perPage) throws GitLabApiException { - Response response = get(javax.ws.rs.core.Response.Status.OK, getPageQueryParams(page, perPage), - "projects", getProjectIdOrPath(projectIdOrPath), "boards"); - return (response.readEntity(new GenericType>() {})); - } + /** + * Get all issue boards for the specified project using the specified page and per page setting + * + *
GitLab Endpoint: GET /projects/:id/boards
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param page the page to get + * @param perPage the number of items per page + * @return a list of project's Boards in the specified range + * @throws GitLabApiException if any exception occurs + */ + public List getBoards(final Object projectIdOrPath, final int page, final int perPage) + throws GitLabApiException { + final Response response = + get( + jakarta.ws.rs.core.Response.Status.OK, + getPageQueryParams(page, perPage), + "projects", + getProjectIdOrPath(projectIdOrPath), + "boards"); + return (response.readEntity(new GenericType>() {})); + } - /** - * Get a Pager of all issue boards for the specified project. - * - *
GitLab Endpoint: GET /projects/:id/boards
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param itemsPerPage the number of items per page - * @return a Pager of project's issue boards - * @throws GitLabApiException if any exception occurs - */ - public Pager getBoards(Object projectIdOrPath, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, Board.class, itemsPerPage, null, - "projects", getProjectIdOrPath(projectIdOrPath), "boards")); - } + /** + * Get a Pager of all issue boards for the specified project. + * + *
GitLab Endpoint: GET /projects/:id/boards
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param itemsPerPage the number of items per page + * @return a Pager of project's issue boards + * @throws GitLabApiException if any exception occurs + */ + public Pager getBoards(final Object projectIdOrPath, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, + Board.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "boards")); + } - /** - * Get a Stream of all issue boards for the specified project. - * - *
GitLab Endpoint: GET /projects/:id/boards
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @return a Stream of project's issue boards - * @throws GitLabApiException if any exception occurs - */ - public Stream getBoardsStream(Object projectIdOrPath) throws GitLabApiException { - return (getBoards(projectIdOrPath, getDefaultPerPage()).stream()); - } + /** + * Get a Stream of all issue boards for the specified project. + * + *
GitLab Endpoint: GET /projects/:id/boards
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @return a Stream of project's issue boards + * @throws GitLabApiException if any exception occurs + */ + public Stream getBoardsStream(final Object projectIdOrPath) throws GitLabApiException { + return (getBoards(projectIdOrPath, getDefaultPerPage()).stream()); + } - /** - * Get a single issue board. - * - *
GitLab Endpoint: GET /projects/:id/boards/:board_id
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param boardId the ID of the board - * @return a Board instance for the specified board ID - * @throws GitLabApiException if any exception occurs - */ - public Board getBoard(Object projectIdOrPath, Long boardId) throws GitLabApiException { - Response response = get(Response.Status.OK, null, - "projects", getProjectIdOrPath(projectIdOrPath), "boards", boardId); - return (response.readEntity(Board.class)); - } + /** + * Get a single issue board. + * + *
GitLab Endpoint: GET /projects/:id/boards/:board_id
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param boardId the ID of the board + * @return a Board instance for the specified board ID + * @throws GitLabApiException if any exception occurs + */ + public Board getBoard(final Object projectIdOrPath, final Long boardId) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "boards", + boardId); + return (response.readEntity(Board.class)); + } - /** - * Get an issue board as an Optional instance. - * - *
GitLab Endpoint: GET /projects/:id/boards/:board_id
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param boardId the ID of the board - * @return the Board instance for the specified board ID as an Optional instance - */ - public Optional getOptionalBoard(Object projectIdOrPath, Long boardId) { - try { - return (Optional.ofNullable(getBoard(projectIdOrPath, boardId))); - } catch (GitLabApiException glae) { - return (GitLabApi.createOptionalFromException(glae)); - } + /** + * Get an issue board as an Optional instance. + * + *
GitLab Endpoint: GET /projects/:id/boards/:board_id
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param boardId the ID of the board + * @return the Board instance for the specified board ID as an Optional instance + */ + public Optional getOptionalBoard(final Object projectIdOrPath, final Long boardId) { + try { + return (Optional.ofNullable(getBoard(projectIdOrPath, boardId))); + } catch (final GitLabApiException glae) { + return (GitLabApi.createOptionalFromException(glae)); } + } - /** - * Creates a new Issue Board. - * - *

NOTE: This is only available in GitLab EE

- * - *
GitLab Endpoint: POST /projects/:id/boards
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param name the name for the new board - * @return the created Board instance - * @throws GitLabApiException if any exception occurs - */ - public Board createBoard(Object projectIdOrPath, String name) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm().withParam("name", name, true); - Response response = post(Response.Status.CREATED, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "boards"); - return (response.readEntity(Board.class)); - } + /** + * Creates a new Issue Board. + * + *

NOTE: This is only available in GitLab EE + * + *

GitLab Endpoint: POST /projects/:id/boards
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param name the name for the new board + * @return the created Board instance + * @throws GitLabApiException if any exception occurs + */ + public Board createBoard(final Object projectIdOrPath, final String name) + throws GitLabApiException { + final GitLabApiForm formData = new GitLabApiForm().withParam("name", name, true); + final Response response = + post( + Response.Status.CREATED, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "boards"); + return (response.readEntity(Board.class)); + } - /** - * Updates an existing Issue Board. - * - *

NOTE: This is only available in GitLab EE

- * - *
GitLab Endpoint: PUT /projects/:id/boards/:board_id
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance, required - * @param boardId the ID of the board, required - * @param name the new name of the board, optional (can be null) - * @param assigneeId the assignee the board should be scoped to, optional (can be null) - * @param milestoneId the milestone the board should be scoped to, optional (can be null) - * @param labels a comma-separated list of label names which the board should be scoped to, optional (can be null) - * @param weight the weight range from 0 to 9, to which the board should be scoped to, optional (can be null) - * @return the updated Board instance - * @throws GitLabApiException if any exception occurs - */ - public BoardList updateBoard(Object projectIdOrPath, Long boardId, String name, - Long assigneeId, Long milestoneId, String labels, Integer weight) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() - .withParam("name", name) - .withParam("assignee_id", assigneeId) - .withParam("milestone_id", milestoneId) - .withParam("labels", labels) - .withParam("weight", weight); - Response response = put(Response.Status.OK, formData.asMap(), - "projects", getProjectIdOrPath(projectIdOrPath), "boards", boardId); - return (response.readEntity(BoardList.class)); - } + /** + * Updates an existing Issue Board. + * + *

NOTE: This is only available in GitLab EE + * + *

GitLab Endpoint: PUT /projects/:id/boards/:board_id
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance, required + * @param boardId the ID of the board, required + * @param name the new name of the board, optional (can be null) + * @param assigneeId the assignee the board should be scoped to, optional (can be null) + * @param milestoneId the milestone the board should be scoped to, optional (can be null) + * @param labels a comma-separated list of label names which the board should be scoped to, + * optional (can be null) + * @param weight the weight range from 0 to 9, to which the board should be scoped to, optional + * (can be null) + * @return the updated Board instance + * @throws GitLabApiException if any exception occurs + */ + public BoardList updateBoard( + final Object projectIdOrPath, + final Long boardId, + final String name, + final Long assigneeId, + final Long milestoneId, + final String labels, + final Integer weight) + throws GitLabApiException { + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("name", name) + .withParam("assignee_id", assigneeId) + .withParam("milestone_id", milestoneId) + .withParam("labels", labels) + .withParam("weight", weight); + final Response response = + put( + Response.Status.OK, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "boards", + boardId); + return (response.readEntity(BoardList.class)); + } - /** - * Soft deletes an existing Issue Board. - * - *

NOTE: This is only available in GitLab EE

- * - *
GitLab Endpoint: DELETE /projects/:id/boards/:board_id
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param boardId the ID of the board - * @throws GitLabApiException if any exception occurs - */ - public void deleteBoard(Object projectIdOrPath, Long boardId) throws GitLabApiException { - delete(Response.Status.NO_CONTENT, null, "projects", getProjectIdOrPath(projectIdOrPath), "boards", boardId); - } + /** + * Soft deletes an existing Issue Board. + * + *

NOTE: This is only available in GitLab EE + * + *

GitLab Endpoint: DELETE /projects/:id/boards/:board_id
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param boardId the ID of the board + * @throws GitLabApiException if any exception occurs + */ + public void deleteBoard(final Object projectIdOrPath, final Long boardId) + throws GitLabApiException { + delete( + Response.Status.NO_CONTENT, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "boards", + boardId); + } - /** - * Get a list of the board’s lists. Does not include open and closed lists. - * - *
GitLab Endpoint: GET /projects/:id/boards/:board_id/lists
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param boardId the ID of the board - * @return a list of the issue board's lists - * @throws GitLabApiException if any exception occurs - */ - public List getBoardLists(Object projectIdOrPath, Long boardId) throws GitLabApiException { - return (getBoardLists(projectIdOrPath, boardId, getDefaultPerPage()).all()); - } + /** + * Get a list of the board’s lists. Does not include open and closed lists. + * + *
GitLab Endpoint: GET /projects/:id/boards/:board_id/lists
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param boardId the ID of the board + * @return a list of the issue board's lists + * @throws GitLabApiException if any exception occurs + */ + public List getBoardLists(final Object projectIdOrPath, final Long boardId) + throws GitLabApiException { + return (getBoardLists(projectIdOrPath, boardId, getDefaultPerPage()).all()); + } - /** - * Get a list of the board’s lists for the specified project to using the specified page and per page setting. - * Does not include open and closed lists. - * - *
GitLab Endpoint: GET /projects/:id/boards/:board_id/lists
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param boardId the ID of the board - * @param page the page to get - * @param perPage the number of Boards per page - * @return a list of the issue board's lists in the specified range - * @throws GitLabApiException if any exception occurs - */ - public List getBoardLists(Object projectIdOrPath, Long boardId, int page, int perPage) throws GitLabApiException { - Response response = get(javax.ws.rs.core.Response.Status.OK, getPageQueryParams(page, perPage), - "projects", getProjectIdOrPath(projectIdOrPath), "boards", boardId, "lists"); - return (response.readEntity(new GenericType>() {})); - } + /** + * Get a list of the board’s lists for the specified project to using the specified page and per + * page setting. Does not include open and closed lists. + * + *
GitLab Endpoint: GET /projects/:id/boards/:board_id/lists
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param boardId the ID of the board + * @param page the page to get + * @param perPage the number of Boards per page + * @return a list of the issue board's lists in the specified range + * @throws GitLabApiException if any exception occurs + */ + public List getBoardLists( + final Object projectIdOrPath, final Long boardId, final int page, final int perPage) + throws GitLabApiException { + final Response response = + get( + jakarta.ws.rs.core.Response.Status.OK, + getPageQueryParams(page, perPage), + "projects", + getProjectIdOrPath(projectIdOrPath), + "boards", + boardId, + "lists"); + return (response.readEntity(new GenericType>() {})); + } - /** - * Get a Pager of the board’s lists. Does not include open and closed lists. - * - *
GitLab Endpoint: GET /projects/:id/boards/:board_id/lists
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param boardId the ID of the board - * @param itemsPerPage the number of Board instances that will be fetched per page - * @return a Pager of the issue board's lists - * @throws GitLabApiException if any exception occurs - */ - public Pager getBoardLists(Object projectIdOrPath, Long boardId, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, BoardList.class, itemsPerPage, null, - "projects", getProjectIdOrPath(projectIdOrPath), "boards", boardId, "lists")); - } + /** + * Get a Pager of the board’s lists. Does not include open and closed lists. + * + *
GitLab Endpoint: GET /projects/:id/boards/:board_id/lists
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param boardId the ID of the board + * @param itemsPerPage the number of Board instances that will be fetched per page + * @return a Pager of the issue board's lists + * @throws GitLabApiException if any exception occurs + */ + public Pager getBoardLists( + final Object projectIdOrPath, final Long boardId, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, + BoardList.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "boards", + boardId, + "lists")); + } - /** - * Get a Stream of the board’s lists. Does not include open and closed lists. - * - *
GitLab Endpoint: GET /projects/:id/boards/:board_id/lists
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param boardId the ID of the board - * @return a Stream of the issue board's lists - * @throws GitLabApiException if any exception occurs - */ - public Stream getBoardsListsStream(Object projectIdOrPath, Long boardId) throws GitLabApiException { - return (getBoardLists(projectIdOrPath, boardId, getDefaultPerPage()).stream()); - } + /** + * Get a Stream of the board’s lists. Does not include open and closed lists. + * + *
GitLab Endpoint: GET /projects/:id/boards/:board_id/lists
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param boardId the ID of the board + * @return a Stream of the issue board's lists + * @throws GitLabApiException if any exception occurs + */ + public Stream getBoardsListsStream(final Object projectIdOrPath, final Long boardId) + throws GitLabApiException { + return (getBoardLists(projectIdOrPath, boardId, getDefaultPerPage()).stream()); + } - /** - * Get a single issue board list. - * - *
GitLab Endpoint: GET /projects/:id/boards/:board_id/lists/:list_id
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param boardId the ID of the board - * @param listId the ID of the board lists to get - * @return a BoardList instance for the specified board ID and list ID - * @throws GitLabApiException if any exception occurs - */ - public BoardList getBoardList(Object projectIdOrPath, Long boardId, Long listId) throws GitLabApiException { - Response response = get(Response.Status.OK, null, - "projects", getProjectIdOrPath(projectIdOrPath), "boards", boardId, "lists", listId); - return (response.readEntity(BoardList.class)); - } + /** + * Get a single issue board list. + * + *
GitLab Endpoint: GET /projects/:id/boards/:board_id/lists/:list_id
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param boardId the ID of the board + * @param listId the ID of the board lists to get + * @return a BoardList instance for the specified board ID and list ID + * @throws GitLabApiException if any exception occurs + */ + public BoardList getBoardList(final Object projectIdOrPath, final Long boardId, final Long listId) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "boards", + boardId, + "lists", + listId); + return (response.readEntity(BoardList.class)); + } - /** - * Get a single issue board list as an Optional instance. - * - *
GitLab Endpoint: GET /projects/:id/boards/:board_id/lists/:list_id
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param boardId the ID of the board - * @param listId the ID of the board lists to get - * @return a BoardList instance for the specified board ID and list ID as an Optional instance - */ - public Optional getOptionalBoardList(Object projectIdOrPath, Long boardId, Long listId) { - try { - return (Optional.ofNullable(getBoardList(projectIdOrPath, boardId, listId))); - } catch (GitLabApiException glae) { - return (GitLabApi.createOptionalFromException(glae)); - } + /** + * Get a single issue board list as an Optional instance. + * + *
GitLab Endpoint: GET /projects/:id/boards/:board_id/lists/:list_id
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param boardId the ID of the board + * @param listId the ID of the board lists to get + * @return a BoardList instance for the specified board ID and list ID as an Optional instance + */ + public Optional getOptionalBoardList( + final Object projectIdOrPath, final Long boardId, final Long listId) { + try { + return (Optional.ofNullable(getBoardList(projectIdOrPath, boardId, listId))); + } catch (final GitLabApiException glae) { + return (GitLabApi.createOptionalFromException(glae)); } + } - /** - * Creates a new Issue Board list. - * - *
GitLab Endpoint: POST /projects/:id/boards/:board_id/lists
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param boardId the ID of the board - * @param labelId the ID of the label - * @return the created BoardList instance - * @throws GitLabApiException if any exception occurs - */ - public BoardList createBoardList(Object projectIdOrPath, Long boardId, Long labelId) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() - .withParam("label_id", labelId, true); - Response response = post(Response.Status.CREATED, formData, "projects", getProjectIdOrPath(projectIdOrPath), "boards", boardId, "lists"); - return (response.readEntity(BoardList.class)); - } + /** + * Creates a new Issue Board list. + * + *
GitLab Endpoint: POST /projects/:id/boards/:board_id/lists
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param boardId the ID of the board + * @param labelId the ID of the label + * @return the created BoardList instance + * @throws GitLabApiException if any exception occurs + */ + public BoardList createBoardList( + final Object projectIdOrPath, final Long boardId, final Long labelId) + throws GitLabApiException { + final GitLabApiForm formData = new GitLabApiForm().withParam("label_id", labelId, true); + final Response response = + post( + Response.Status.CREATED, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "boards", + boardId, + "lists"); + return (response.readEntity(BoardList.class)); + } - /** - * Updates an existing Issue Board list. This call is used to change list position. - * - *
GitLab Endpoint: PUT /projects/:id/boards/:board_id/lists/:list_id
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param boardId the ID of the board - * @param listId the ID of the list - * @param position the new position for the list - * @return the updated BoardList instance - * @throws GitLabApiException if any exception occurs - */ - public BoardList updateBoardList(Object projectIdOrPath, Long boardId, Long listId, Integer position) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm().withParam("position", position, true); - Response response = putWithFormData(Response.Status.OK, formData, - "projects", getProjectIdOrPath(projectIdOrPath), "boards", boardId, "lists", listId); - return (response.readEntity(BoardList.class)); - } + /** + * Updates an existing Issue Board list. This call is used to change list position. + * + *
GitLab Endpoint: PUT /projects/:id/boards/:board_id/lists/:list_id
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param boardId the ID of the board + * @param listId the ID of the list + * @param position the new position for the list + * @return the updated BoardList instance + * @throws GitLabApiException if any exception occurs + */ + public BoardList updateBoardList( + final Object projectIdOrPath, final Long boardId, final Long listId, final Integer position) + throws GitLabApiException { + final GitLabApiForm formData = new GitLabApiForm().withParam("position", position, true); + final Response response = + putWithFormData( + Response.Status.OK, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "boards", + boardId, + "lists", + listId); + return (response.readEntity(BoardList.class)); + } - /** - * Soft deletes an existing Issue Board list. Only for admins and project owners. - * - *
GitLab Endpoint: DELETE /projects/:id/boards/:board_id/lists/:list_id
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param boardId the ID of the board - * @param listId the ID of the list - * @throws GitLabApiException if any exception occurs - */ - public void deleteBoardList(Object projectIdOrPath, Long boardId, Long listId) throws GitLabApiException { - delete(Response.Status.NO_CONTENT, null, "projects", getProjectIdOrPath(projectIdOrPath), "boards", boardId, "lists", listId); - } + /** + * Soft deletes an existing Issue Board list. Only for admins and project owners. + * + *
GitLab Endpoint: DELETE /projects/:id/boards/:board_id/lists/:list_id
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param boardId the ID of the board + * @param listId the ID of the list + * @throws GitLabApiException if any exception occurs + */ + public void deleteBoardList(final Object projectIdOrPath, final Long boardId, final Long listId) + throws GitLabApiException { + delete( + Response.Status.NO_CONTENT, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "boards", + boardId, + "lists", + listId); + } } diff --git a/src/main/java/org/gitlab4j/api/CommitsApi.java b/src/main/java/org/gitlab4j/api/CommitsApi.java index c6cffde7d..0ae4308d2 100644 --- a/src/main/java/org/gitlab4j/api/CommitsApi.java +++ b/src/main/java/org/gitlab4j/api/CommitsApi.java @@ -1,16 +1,14 @@ package org.gitlab4j.api; +import jakarta.ws.rs.core.Form; +import jakarta.ws.rs.core.GenericType; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.stream.Stream; - -import javax.ws.rs.core.Form; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; - import org.gitlab4j.api.models.Comment; import org.gitlab4j.api.models.Commit; import org.gitlab4j.api.models.CommitAction; @@ -26,940 +24,1324 @@ import org.gitlab4j.api.utils.ISO8601; /** - * This class implements the client side API for the GitLab commits calls. - * See Commits API at GitLab for more information. + * This class implements the client side API for the GitLab commits calls. See Commits API at GitLab for more + * information. */ public class CommitsApi extends AbstractApi { - public CommitsApi(GitLabApi gitLabApi) { - super(gitLabApi); - } - - /** - * Get a list of all repository commits in a project. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @return a list containing the commits for the specified project ID - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public List getCommits(Object projectIdOrPath) throws GitLabApiException { - return (getCommits(projectIdOrPath, null, null, null, null, true, null, null, getDefaultPerPage()).all()); - } - - /** - * Get a list of repository commits in a project. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param page the page to get - * @param perPage the number of commits per page - * @return a list containing the commits for the specified project ID - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - * @deprecated - */ - @Deprecated - public List getCommits(Object projectIdOrPath, int page, int perPage) throws GitLabApiException { - return (getCommits(projectIdOrPath, null, null, null, page, perPage)); - } - - /** - * Get a Pager of all repository commits in a project. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param itemsPerPage the number of Commit instances that will be fetched per page - * @return a Pager containing the commits for the specified project ID - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Pager getCommits(Object projectIdOrPath, int itemsPerPage) throws GitLabApiException { - return (getCommits(projectIdOrPath, null, null, null, null, true, null, null, itemsPerPage)); - } - - /** - * Get a Stream of all repository commits in a project. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @return a Stream containing the commits for the specified project ID - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Stream getCommitStream(Object projectIdOrPath) throws GitLabApiException { - return (getCommits(projectIdOrPath, null, null, null,null, true, null, null, getDefaultPerPage()).stream()); - } - - /** - * Get a list of repository commits in a project. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param ref the name of a repository branch or tag or if not given the default branch - * @param since only commits after or on this date will be returned - * @param until only commits before or on this date will be returned - * @param path the path to file of a project - * @return a list containing the commits for the specified project ID - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public List getCommits(Object projectIdOrPath, String ref, Date since, Date until, String path) throws GitLabApiException { - return (getCommits(projectIdOrPath, ref, since, until, path, null, null, null, getDefaultPerPage()).all()); - } - - /** - * Get a list of file commits in a project - * - *
GitLab Endpoint: GET /projects/:id/repository/commits?path=:file_path
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param ref the name of a repository branch or tag or if not given the default branch - * @param path the path to file of a project - * @return a list containing the commits for the specified project ID and file - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public List getCommits(Object projectIdOrPath, String ref, String path) throws GitLabApiException { - return (getCommits(projectIdOrPath, ref, null, null, path, null, null, null, getDefaultPerPage()).all()); - } - - /** - * Get a list of repository commits in a project. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param ref the name of a repository branch or tag or if not given the default branch - * @param since only commits after or on this date will be returned - * @param until only commits before or on this date will be returned - * @return a list containing the commits for the specified project ID - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public List getCommits(Object projectIdOrPath, String ref, Date since, Date until) throws GitLabApiException { - return (getCommits(projectIdOrPath, ref, since, until, null, null, null, null, getDefaultPerPage()).all()); - } - - /** - * Get a list of repository commits in a project. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param ref the name of a repository branch or tag or if not given the default branch - * @param since only commits after or on this date will be returned - * @param until only commits before or on this date will be returned - * @param page the page to get - * @param perPage the number of commits per page - * @return a list containing the commits for the specified project ID - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - * @deprecated - */ - @Deprecated - public List getCommits(Object projectIdOrPath, String ref, Date since, Date until, int page, int perPage) throws GitLabApiException { - return (getCommits(projectIdOrPath, ref, since, until, null, page, perPage)); - } - - /** - * Get a Stream of repository commits in a project. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param ref the name of a repository branch or tag or if not given the default branch - * @param since only commits after or on this date will be returned - * @param until only commits before or on this date will be returned - * @return a Stream containing the commits for the specified project ID - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Stream getCommitsStream(Object projectIdOrPath, String ref, Date since, Date until) throws GitLabApiException { - return (getCommits(projectIdOrPath, ref, since, until, null, null, null, null, getDefaultPerPage()).stream()); - } - - /** - * Get a Stream of repository commits in a project. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param ref the name of a repository branch or tag or if not given the default branch - * @param since only commits after or on this date will be returned - * @param until only commits before or on this date will be returned - * @param path the path to file of a project - * @return a Stream containing the commits for the specified project ID - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Stream getCommitsStream(Object projectIdOrPath, String ref, Date since, Date until, String path) throws GitLabApiException { - return (getCommits(projectIdOrPath, ref, since, until, path, null, null, null, getDefaultPerPage()).stream()); - } - - /** - * Get a list of repository commits in a project. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param ref the name of a repository branch or tag or if not given the default branch - * @param since only commits after or on this date will be returned - * @param until only commits before or on this date will be returned - * @param path the path to file of a project - * @param page the page to get - * @param perPage the number of commits per page - * @return a list containing the commits for the specified project ID - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - * @deprecated - */ - @Deprecated - public List getCommits(Object projectIdOrPath, String ref, Date since, Date until, String path, int page, int perPage) throws GitLabApiException { - Form formData = new GitLabApiForm() - .withParam("ref_name", ref) - .withParam("since", ISO8601.toString(since, false)) - .withParam("until", ISO8601.toString(until, false)) - .withParam("path", (path == null ? null : urlEncode(path))) - .withParam(PAGE_PARAM, page) - .withParam(PER_PAGE_PARAM, perPage); - Response response = get(Response.Status.OK, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "repository", "commits"); - return (response.readEntity(new GenericType>() {})); - } - - /** - * Get a Pager of repository commits in a project. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param ref the name of a repository branch or tag or if not given the default branch - * @param since only commits after or on this date will be returned - * @param until only commits before or on this date will be returned - * @param itemsPerPage the number of Commit instances that will be fetched per page - * @return a Pager containing the commits for the specified project ID - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Pager getCommits(Object projectIdOrPath, String ref, Date since, Date until, int itemsPerPage) throws GitLabApiException { - return getCommits(projectIdOrPath, ref, since, until, null, null, null, null, itemsPerPage); - } - - /** - * Get a Pager of repository commits in a project - * - *
GitLab Endpoint: GET /projects/:id/repository/commits
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param ref the name of a repository branch or tag or if not given the default branch - * @param since only commits after or on this date will be returned - * @param until only commits before or on this date will be returned - * @param itemsPerPage the number of Commit instances that will be fetched per page - * @param path the path to file of a project - * @return a Pager containing the commits for the specified project ID - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Pager getCommits(Object projectIdOrPath, String ref, Date since, Date until, String path, int itemsPerPage) throws GitLabApiException { - return (getCommits(projectIdOrPath, ref, since, until, path, null, null, null, itemsPerPage)); - } - - /** - * Get a List of the specified repository commits in a project - * - *
GitLab Endpoint: GET /projects/:id/repository/commits
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param ref the name of a repository branch or tag or if not given the default branch - * @param since only commits after or on this date will be returned - * @param until only commits before or on this date will be returned - * @param path the path to file of a project - * @param all retrieve every commit from the repository - * @param withStats stats about each commit will be added to the response - * @param firstParent follow only the first parent commit upon seeing a merge commit - * @return a Pager containing the commits for the specified project ID - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public List getCommits(Object projectIdOrPath, String ref, Date since, Date until, - String path, Boolean all, Boolean withStats, Boolean firstParent) throws GitLabApiException { - return (getCommits(projectIdOrPath, ref, since, until, path, all, withStats, firstParent, getDefaultPerPage()).all()); - } - - /** - * Get a Pager of the specified repository commits in a project - * - *
GitLab Endpoint: GET /projects/:id/repository/commits
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param ref the name of a repository branch or tag or if not given the default branch - * @param since only commits after or on this date will be returned - * @param until only commits before or on this date will be returned - * @param path the path to file of a project - * @param all retrieve every commit from the repository - * @param withStats stats about each commit will be added to the response - * @param firstParent follow only the first parent commit upon seeing a merge commit - * @param itemsPerPage the number of Commit instances that will be fetched per page - * @return a Pager containing the commits for the specified project ID - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Pager getCommits(Object projectIdOrPath, String ref, Date since, Date until, - String path, Boolean all, Boolean withStats, Boolean firstParent, int itemsPerPage) throws GitLabApiException { - Form formData = new GitLabApiForm() - .withParam("ref_name", ref) - .withParam("since", ISO8601.toString(since, false)) - .withParam("until", ISO8601.toString(until, false)) - .withParam("path", (path == null ? null : urlEncode(path))) - .withParam("all", all) - .withParam("with_stats", withStats) - .withParam("first_parent", firstParent); - return (new Pager(this, Commit.class, itemsPerPage, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "repository", "commits")); - } - - /** - * Get a Stream of the specified repository commits in a project - * - *
GitLab Endpoint: GET /projects/:id/repository/commits
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param ref the name of a repository branch or tag or if not given the default branch - * @param since only commits after or on this date will be returned - * @param until only commits before or on this date will be returned - * @param path the path to file of a project - * @param all retrieve every commit from the repository - * @param withStats stats about each commit will be added to the response - * @param firstParent follow only the first parent commit upon seeing a merge commit - * @return a Stream containing the commits for the specified project ID - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Stream getCommitsStream(Object projectIdOrPath, String ref, Date since, Date until, - String path, Boolean all, Boolean withStats, Boolean firstParent) throws GitLabApiException { - return (getCommits(projectIdOrPath, ref, since, until, path, all, withStats, firstParent, getDefaultPerPage()).stream()); - } - - /** - * Get a specific commit identified by the commit hash or name of a branch or tag. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha a commit hash or name of a branch or tag - * @return the Commit instance for the specified project ID/sha pair - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Commit getCommit(Object projectIdOrPath, String sha) throws GitLabApiException { - Response response = get(Response.Status.OK, getDefaultPerPageParam(), "projects", getProjectIdOrPath(projectIdOrPath), "repository", "commits", urlEncode(sha)); - return (response.readEntity(Commit.class)); - } - - /** - * Get a specific commit identified by the commit hash or name of a branch or tag as an Optional instance - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha a commit hash or name of a branch or tag - * @return the Commit for the specified project ID/sha pair as an Optional instance - */ - public Optional getOptionalCommit(Object projectIdOrPath, String sha) { - try { - return (Optional.ofNullable(getCommit(projectIdOrPath, sha))); - } catch (GitLabApiException glae) { - return (GitLabApi.createOptionalFromException(glae)); - } - } - - /** - * Get a List of all references (from branches or tags) a commit is pushed to. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/refs
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha a commit hash or name of a branch or tag - * @return a List of all references (from branches or tags) a commit is pushed to - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - * @since Gitlab 10.6 - */ - public List getCommitRefs(Object projectIdOrPath, String sha) throws GitLabApiException { - return (getCommitRefs(projectIdOrPath, sha, RefType.ALL, getDefaultPerPage()).all()); - } - - /** - * Get a Pager of references (from branches or tags) a commit is pushed to. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/refs?type=:refType
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha a commit hash or name of a branch or tag - * @param itemsPerPage the number of Commit instances that will be fetched per page - * @return a Pager of references (from branches or tags) a commit is pushed to - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - * @since Gitlab 10.6 - */ - public Pager getCommitRefs(Object projectIdOrPath, String sha, int itemsPerPage) throws GitLabApiException { - return (getCommitRefs(projectIdOrPath, sha, RefType.ALL, itemsPerPage)); - } - - /** - * Get a Stream of all references (from branches or tags) a commit is pushed to. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/refs
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha a commit hash or name of a branch or tag - * @return a Stream of all references (from branches or tags) a commit is pushed to - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - * @since Gitlab 10.6 - */ - public Stream getCommitRefsStream(Object projectIdOrPath, String sha) throws GitLabApiException { - return (getCommitRefs(projectIdOrPath, sha, RefType.ALL, getDefaultPerPage()).stream()); - } - - /** - * Get a List of all references (from branches or tags) a commit is pushed to. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/refs?type=:refType
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha a commit hash or name of a branch or tag - * @param refType the scope of commits. Possible values branch, tag, all. Default is all. - * @return a List of all references (from branches or tags) a commit is pushed to - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - * @since Gitlab 10.6 - */ - public List getCommitRefs(Object projectIdOrPath, String sha, RefType refType) throws GitLabApiException { - return (getCommitRefs(projectIdOrPath, sha, refType, getDefaultPerPage()).all()); - } - - /** - * Get a Pager of references (from branches or tags) a commit is pushed to. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/refs?type=:refType
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha a commit hash or name of a branch or tag - * @param refType the scope of commits. Possible values branch, tag, all. Default is all. - * @param itemsPerPage the number of Commit instances that will be fetched per page - * @return a Pager of references (from branches or tags) a commit is pushed to - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - * @since Gitlab 10.6 - */ - public Pager getCommitRefs(Object projectIdOrPath, String sha, CommitRef.RefType refType, int itemsPerPage) throws GitLabApiException { - Form form = new GitLabApiForm().withParam("type", refType); - return (new Pager(this, CommitRef.class, itemsPerPage, form.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "repository", "commits", urlEncode(sha), "refs")); + public CommitsApi(final GitLabApi gitLabApi) { + super(gitLabApi); + } + + /** + * Get a list of all repository commits in a project. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @return a list containing the commits for the specified project ID + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public List getCommits(final Object projectIdOrPath) throws GitLabApiException { + return (getCommits( + projectIdOrPath, null, null, null, null, true, null, null, getDefaultPerPage()) + .all()); + } + + /** + * Get a list of repository commits in a project. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param page the page to get + * @param perPage the number of commits per page + * @return a list containing the commits for the specified project ID + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + * @deprecated + */ + @Deprecated + public List getCommits(final Object projectIdOrPath, final int page, final int perPage) + throws GitLabApiException { + return (getCommits(projectIdOrPath, null, null, null, page, perPage)); + } + + /** + * Get a Pager of all repository commits in a project. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param itemsPerPage the number of Commit instances that will be fetched per page + * @return a Pager containing the commits for the specified project ID + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Pager getCommits(final Object projectIdOrPath, final int itemsPerPage) + throws GitLabApiException { + return (getCommits(projectIdOrPath, null, null, null, null, true, null, null, itemsPerPage)); + } + + /** + * Get a Stream of all repository commits in a project. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @return a Stream containing the commits for the specified project ID + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Stream getCommitStream(final Object projectIdOrPath) throws GitLabApiException { + return (getCommits( + projectIdOrPath, null, null, null, null, true, null, null, getDefaultPerPage()) + .stream()); + } + + /** + * Get a list of repository commits in a project. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param ref the name of a repository branch or tag or if not given the default branch + * @param since only commits after or on this date will be returned + * @param until only commits before or on this date will be returned + * @param path the path to file of a project + * @return a list containing the commits for the specified project ID + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public List getCommits( + final Object projectIdOrPath, + final String ref, + final Date since, + final Date until, + final String path) + throws GitLabApiException { + return (getCommits( + projectIdOrPath, ref, since, until, path, null, null, null, getDefaultPerPage()) + .all()); + } + + /** + * Get a list of file commits in a project + * + *
GitLab Endpoint: GET /projects/:id/repository/commits?path=:file_path
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param ref the name of a repository branch or tag or if not given the default branch + * @param path the path to file of a project + * @return a list containing the commits for the specified project ID and file + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public List getCommits(final Object projectIdOrPath, final String ref, final String path) + throws GitLabApiException { + return (getCommits( + projectIdOrPath, ref, null, null, path, null, null, null, getDefaultPerPage()) + .all()); + } + + /** + * Get a list of repository commits in a project. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param ref the name of a repository branch or tag or if not given the default branch + * @param since only commits after or on this date will be returned + * @param until only commits before or on this date will be returned + * @return a list containing the commits for the specified project ID + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public List getCommits( + final Object projectIdOrPath, final String ref, final Date since, final Date until) + throws GitLabApiException { + return (getCommits( + projectIdOrPath, ref, since, until, null, null, null, null, getDefaultPerPage()) + .all()); + } + + /** + * Get a list of repository commits in a project. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param ref the name of a repository branch or tag or if not given the default branch + * @param since only commits after or on this date will be returned + * @param until only commits before or on this date will be returned + * @param page the page to get + * @param perPage the number of commits per page + * @return a list containing the commits for the specified project ID + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + * @deprecated + */ + @Deprecated + public List getCommits( + final Object projectIdOrPath, + final String ref, + final Date since, + final Date until, + final int page, + final int perPage) + throws GitLabApiException { + return (getCommits(projectIdOrPath, ref, since, until, null, page, perPage)); + } + + /** + * Get a Stream of repository commits in a project. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param ref the name of a repository branch or tag or if not given the default branch + * @param since only commits after or on this date will be returned + * @param until only commits before or on this date will be returned + * @return a Stream containing the commits for the specified project ID + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Stream getCommitsStream( + final Object projectIdOrPath, final String ref, final Date since, final Date until) + throws GitLabApiException { + return (getCommits( + projectIdOrPath, ref, since, until, null, null, null, null, getDefaultPerPage()) + .stream()); + } + + /** + * Get a Stream of repository commits in a project. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param ref the name of a repository branch or tag or if not given the default branch + * @param since only commits after or on this date will be returned + * @param until only commits before or on this date will be returned + * @param path the path to file of a project + * @return a Stream containing the commits for the specified project ID + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Stream getCommitsStream( + final Object projectIdOrPath, + final String ref, + final Date since, + final Date until, + final String path) + throws GitLabApiException { + return (getCommits( + projectIdOrPath, ref, since, until, path, null, null, null, getDefaultPerPage()) + .stream()); + } + + /** + * Get a list of repository commits in a project. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param ref the name of a repository branch or tag or if not given the default branch + * @param since only commits after or on this date will be returned + * @param until only commits before or on this date will be returned + * @param path the path to file of a project + * @param page the page to get + * @param perPage the number of commits per page + * @return a list containing the commits for the specified project ID + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + * @deprecated + */ + @Deprecated + public List getCommits( + final Object projectIdOrPath, + final String ref, + final Date since, + final Date until, + final String path, + final int page, + final int perPage) + throws GitLabApiException { + final Form formData = + new GitLabApiForm() + .withParam("ref_name", ref) + .withParam("since", ISO8601.toString(since, false)) + .withParam("until", ISO8601.toString(until, false)) + .withParam("path", (path == null ? null : urlEncode(path))) + .withParam(PAGE_PARAM, page) + .withParam(PER_PAGE_PARAM, perPage); + final Response response = + get( + Response.Status.OK, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "repository", + "commits"); + return (response.readEntity(new GenericType>() {})); + } + + /** + * Get a Pager of repository commits in a project. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param ref the name of a repository branch or tag or if not given the default branch + * @param since only commits after or on this date will be returned + * @param until only commits before or on this date will be returned + * @param itemsPerPage the number of Commit instances that will be fetched per page + * @return a Pager containing the commits for the specified project ID + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Pager getCommits( + final Object projectIdOrPath, + final String ref, + final Date since, + final Date until, + final int itemsPerPage) + throws GitLabApiException { + return getCommits(projectIdOrPath, ref, since, until, null, null, null, null, itemsPerPage); + } + + /** + * Get a Pager of repository commits in a project + * + *
GitLab Endpoint: GET /projects/:id/repository/commits
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param ref the name of a repository branch or tag or if not given the default branch + * @param since only commits after or on this date will be returned + * @param until only commits before or on this date will be returned + * @param itemsPerPage the number of Commit instances that will be fetched per page + * @param path the path to file of a project + * @return a Pager containing the commits for the specified project ID + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Pager getCommits( + final Object projectIdOrPath, + final String ref, + final Date since, + final Date until, + final String path, + final int itemsPerPage) + throws GitLabApiException { + return (getCommits(projectIdOrPath, ref, since, until, path, null, null, null, itemsPerPage)); + } + + /** + * Get a List of the specified repository commits in a project + * + *
GitLab Endpoint: GET /projects/:id/repository/commits
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param ref the name of a repository branch or tag or if not given the default branch + * @param since only commits after or on this date will be returned + * @param until only commits before or on this date will be returned + * @param path the path to file of a project + * @param all retrieve every commit from the repository + * @param withStats stats about each commit will be added to the response + * @param firstParent follow only the first parent commit upon seeing a merge commit + * @return a Pager containing the commits for the specified project ID + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public List getCommits( + final Object projectIdOrPath, + final String ref, + final Date since, + final Date until, + final String path, + final Boolean all, + final Boolean withStats, + final Boolean firstParent) + throws GitLabApiException { + return (getCommits( + projectIdOrPath, + ref, + since, + until, + path, + all, + withStats, + firstParent, + getDefaultPerPage()) + .all()); + } + + /** + * Get a Pager of the specified repository commits in a project + * + *
GitLab Endpoint: GET /projects/:id/repository/commits
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param ref the name of a repository branch or tag or if not given the default branch + * @param since only commits after or on this date will be returned + * @param until only commits before or on this date will be returned + * @param path the path to file of a project + * @param all retrieve every commit from the repository + * @param withStats stats about each commit will be added to the response + * @param firstParent follow only the first parent commit upon seeing a merge commit + * @param itemsPerPage the number of Commit instances that will be fetched per page + * @return a Pager containing the commits for the specified project ID + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Pager getCommits( + final Object projectIdOrPath, + final String ref, + final Date since, + final Date until, + final String path, + final Boolean all, + final Boolean withStats, + final Boolean firstParent, + final int itemsPerPage) + throws GitLabApiException { + final Form formData = + new GitLabApiForm() + .withParam("ref_name", ref) + .withParam("since", ISO8601.toString(since, false)) + .withParam("until", ISO8601.toString(until, false)) + .withParam("path", (path == null ? null : urlEncode(path))) + .withParam("all", all) + .withParam("with_stats", withStats) + .withParam("first_parent", firstParent); + return (new Pager( + this, + Commit.class, + itemsPerPage, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "repository", + "commits")); + } + + /** + * Get a Stream of the specified repository commits in a project + * + *
GitLab Endpoint: GET /projects/:id/repository/commits
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param ref the name of a repository branch or tag or if not given the default branch + * @param since only commits after or on this date will be returned + * @param until only commits before or on this date will be returned + * @param path the path to file of a project + * @param all retrieve every commit from the repository + * @param withStats stats about each commit will be added to the response + * @param firstParent follow only the first parent commit upon seeing a merge commit + * @return a Stream containing the commits for the specified project ID + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Stream getCommitsStream( + final Object projectIdOrPath, + final String ref, + final Date since, + final Date until, + final String path, + final Boolean all, + final Boolean withStats, + final Boolean firstParent) + throws GitLabApiException { + return (getCommits( + projectIdOrPath, ref, since, until, path, all, withStats, firstParent, getDefaultPerPage()) + .stream()); + } + + /** + * Get a specific commit identified by the commit hash or name of a branch or tag. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha a commit hash or name of a branch or tag + * @return the Commit instance for the specified project ID/sha pair + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Commit getCommit(final Object projectIdOrPath, final String sha) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getDefaultPerPageParam(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "repository", + "commits", + urlEncode(sha)); + return (response.readEntity(Commit.class)); + } + + /** + * Get a specific commit identified by the commit hash or name of a branch or tag as an Optional + * instance + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha a commit hash or name of a branch or tag + * @return the Commit for the specified project ID/sha pair as an Optional instance + */ + public Optional getOptionalCommit(final Object projectIdOrPath, final String sha) { + try { + return (Optional.ofNullable(getCommit(projectIdOrPath, sha))); + } catch (final GitLabApiException glae) { + return (GitLabApi.createOptionalFromException(glae)); } - - /** - * Get a Stream of all references (from branches or tags) a commit is pushed to. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/refs?type=:refType
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha a commit hash or name of a branch or tag - * @param refType the scope of commits. Possible values branch, tag, all. Default is all. - * @return a Stream of all references (from branches or tags) a commit is pushed to - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - * @since Gitlab 10.6 - */ - public Stream getCommitRefsStream(Object projectIdOrPath, String sha, RefType refType) throws GitLabApiException { - return (getCommitRefs(projectIdOrPath, sha, refType, getDefaultPerPage()).stream()); + } + + /** + * Get a List of all references (from branches or tags) a commit is pushed to. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/refs
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha a commit hash or name of a branch or tag + * @return a List of all references (from branches or tags) a commit is pushed to + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + * @since Gitlab 10.6 + */ + public List getCommitRefs(final Object projectIdOrPath, final String sha) + throws GitLabApiException { + return (getCommitRefs(projectIdOrPath, sha, RefType.ALL, getDefaultPerPage()).all()); + } + + /** + * Get a Pager of references (from branches or tags) a commit is pushed to. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/refs?type=:refType
+   * 
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha a commit hash or name of a branch or tag + * @param itemsPerPage the number of Commit instances that will be fetched per page + * @return a Pager of references (from branches or tags) a commit is pushed to + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + * @since Gitlab 10.6 + */ + public Pager getCommitRefs( + final Object projectIdOrPath, final String sha, final int itemsPerPage) + throws GitLabApiException { + return (getCommitRefs(projectIdOrPath, sha, RefType.ALL, itemsPerPage)); + } + + /** + * Get a Stream of all references (from branches or tags) a commit is pushed to. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/refs
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha a commit hash or name of a branch or tag + * @return a Stream of all references (from branches or tags) a commit is pushed to + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + * @since Gitlab 10.6 + */ + public Stream getCommitRefsStream(final Object projectIdOrPath, final String sha) + throws GitLabApiException { + return (getCommitRefs(projectIdOrPath, sha, RefType.ALL, getDefaultPerPage()).stream()); + } + + /** + * Get a List of all references (from branches or tags) a commit is pushed to. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/refs?type=:refType
+   * 
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha a commit hash or name of a branch or tag + * @param refType the scope of commits. Possible values branch, tag, all. Default is all. + * @return a List of all references (from branches or tags) a commit is pushed to + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + * @since Gitlab 10.6 + */ + public List getCommitRefs( + final Object projectIdOrPath, final String sha, final RefType refType) + throws GitLabApiException { + return (getCommitRefs(projectIdOrPath, sha, refType, getDefaultPerPage()).all()); + } + + /** + * Get a Pager of references (from branches or tags) a commit is pushed to. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/refs?type=:refType
+   * 
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha a commit hash or name of a branch or tag + * @param refType the scope of commits. Possible values branch, tag, all. Default is all. + * @param itemsPerPage the number of Commit instances that will be fetched per page + * @return a Pager of references (from branches or tags) a commit is pushed to + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + * @since Gitlab 10.6 + */ + public Pager getCommitRefs( + final Object projectIdOrPath, + final String sha, + final CommitRef.RefType refType, + final int itemsPerPage) + throws GitLabApiException { + final Form form = new GitLabApiForm().withParam("type", refType); + return (new Pager( + this, + CommitRef.class, + itemsPerPage, + form.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "repository", + "commits", + urlEncode(sha), + "refs")); + } + + /** + * Get a Stream of all references (from branches or tags) a commit is pushed to. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/refs?type=:refType
+   * 
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha a commit hash or name of a branch or tag + * @param refType the scope of commits. Possible values branch, tag, all. Default is all. + * @return a Stream of all references (from branches or tags) a commit is pushed to + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + * @since Gitlab 10.6 + */ + public Stream getCommitRefsStream( + final Object projectIdOrPath, final String sha, final RefType refType) + throws GitLabApiException { + return (getCommitRefs(projectIdOrPath, sha, refType, getDefaultPerPage()).stream()); + } + + /** + * Get a list of repository commit statuses that meet the provided filter. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/statuses
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha the commit SHA + * @param filter the commit statuses file, contains ref, stage, name, all + * @return a List containing the commit statuses for the specified project and sha that meet the + * provided filter + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public List getCommitStatuses( + final Object projectIdOrPath, final String sha, final CommitStatusFilter filter) + throws GitLabApiException { + return (getCommitStatuses(projectIdOrPath, sha, filter, getDefaultPerPage()).all()); + } + + /** + * Get a list of repository commit statuses that meet the provided filter. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/statuses
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha the commit SHA + * @param filter the commit statuses file, contains ref, stage, name, all + * @param page the page to get + * @param perPage the number of commits statuses per page + * @return a List containing the commit statuses for the specified project and sha that meet the + * provided filter + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public List getCommitStatuses( + final Object projectIdOrPath, + final String sha, + final CommitStatusFilter filter, + final int page, + final int perPage) + throws GitLabApiException { + + if (projectIdOrPath == null) { + throw new RuntimeException("projectIdOrPath cannot be null"); } - /** - * Get a list of repository commit statuses that meet the provided filter. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/statuses
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha the commit SHA - * @param filter the commit statuses file, contains ref, stage, name, all - * @return a List containing the commit statuses for the specified project and sha that meet the provided filter - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public List getCommitStatuses(Object projectIdOrPath, String sha, CommitStatusFilter filter) throws GitLabApiException { - return (getCommitStatuses(projectIdOrPath, sha, filter, getDefaultPerPage()).all()); + if (sha == null || sha.trim().isEmpty()) { + throw new RuntimeException("sha cannot be null"); } - /** - * Get a list of repository commit statuses that meet the provided filter. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/statuses
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha the commit SHA - * @param filter the commit statuses file, contains ref, stage, name, all - * @param page the page to get - * @param perPage the number of commits statuses per page - * @return a List containing the commit statuses for the specified project and sha that meet the provided filter - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public List getCommitStatuses(Object projectIdOrPath, String sha, - CommitStatusFilter filter, int page, int perPage) throws GitLabApiException { - - if (projectIdOrPath == null) { - throw new RuntimeException("projectIdOrPath cannot be null"); - } - - if (sha == null || sha.trim().isEmpty()) { - throw new RuntimeException("sha cannot be null"); - } - - MultivaluedMap queryParams = (filter != null ? - filter.getQueryParams(page, perPage).asMap() : getPageQueryParams(page, perPage)); - Response response = get(Response.Status.OK, queryParams, - "projects", this.getProjectIdOrPath(projectIdOrPath), "repository", "commits", sha, "statuses"); - return (response.readEntity(new GenericType>() {})); + final MultivaluedMap queryParams = + (filter != null + ? filter.getQueryParams(page, perPage).asMap() + : getPageQueryParams(page, perPage)); + final Response response = + get( + Response.Status.OK, + queryParams, + "projects", + this.getProjectIdOrPath(projectIdOrPath), + "repository", + "commits", + sha, + "statuses"); + return (response.readEntity(new GenericType>() {})); + } + + /** + * Get a Pager of repository commit statuses that meet the provided filter. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/statuses
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha the commit SHA + * @param filter the commit statuses file, contains ref, stage, name, all + * @param itemsPerPage the number of CommitStatus instances that will be fetched per page + * @return a Pager containing the commit statuses for the specified project and sha that meet the + * provided filter + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Pager getCommitStatuses( + final Object projectIdOrPath, + final String sha, + final CommitStatusFilter filter, + final int itemsPerPage) + throws GitLabApiException { + + if (projectIdOrPath == null) { + throw new RuntimeException("projectIdOrPath cannot be null"); } - /** - * Get a Pager of repository commit statuses that meet the provided filter. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/statuses
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha the commit SHA - * @param filter the commit statuses file, contains ref, stage, name, all - * @param itemsPerPage the number of CommitStatus instances that will be fetched per page - * @return a Pager containing the commit statuses for the specified project and sha that meet the provided filter - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Pager getCommitStatuses(Object projectIdOrPath, String sha, - CommitStatusFilter filter, int itemsPerPage) throws GitLabApiException { - - if (projectIdOrPath == null) { - throw new RuntimeException("projectIdOrPath cannot be null"); - } - - if (sha == null || sha.trim().isEmpty()) { - throw new RuntimeException("sha cannot be null"); - } - - MultivaluedMap queryParams = (filter != null ? filter.getQueryParams().asMap() : null); - return (new Pager(this, CommitStatus.class, itemsPerPage, queryParams, - "projects", this.getProjectIdOrPath(projectIdOrPath), "repository", "commits", sha, "statuses")); + if (sha == null || sha.trim().isEmpty()) { + throw new RuntimeException("sha cannot be null"); } - /** - * Get a Stream of repository commit statuses that meet the provided filter. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/statuses
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha the commit SHA - * @param filter the commit statuses file, contains ref, stage, name, all - * @return a Stream containing the commit statuses for the specified project and sha that meet the provided filter - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Stream getCommitStatusesStream(Object projectIdOrPath, String sha, CommitStatusFilter filter) throws GitLabApiException { - return (getCommitStatuses(projectIdOrPath, sha, filter, getDefaultPerPage()).stream()); + final MultivaluedMap queryParams = + (filter != null ? filter.getQueryParams().asMap() : null); + return (new Pager( + this, + CommitStatus.class, + itemsPerPage, + queryParams, + "projects", + this.getProjectIdOrPath(projectIdOrPath), + "repository", + "commits", + sha, + "statuses")); + } + + /** + * Get a Stream of repository commit statuses that meet the provided filter. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/statuses
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha the commit SHA + * @param filter the commit statuses file, contains ref, stage, name, all + * @return a Stream containing the commit statuses for the specified project and sha that meet the + * provided filter + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Stream getCommitStatusesStream( + final Object projectIdOrPath, final String sha, final CommitStatusFilter filter) + throws GitLabApiException { + return (getCommitStatuses(projectIdOrPath, sha, filter, getDefaultPerPage()).stream()); + } + + /** + * Add or update the build status of a commit. The following fluent methods are available on the + * CommitStatus instance for setting up the status: + * + *

+   * withCoverage(Float)
+   * withDescription(String)
+   * withName(String)
+   * withRef(String)
+   * withTargetUrl(String)
+   * 
+ * + *
GitLab Endpoint: POST /projects/:id/statuses/:sha
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance (required) + * @param sha a commit SHA (required) + * @param state the state of the status. Can be one of the following: PENDING, RUNNING, SUCCESS, + * FAILED, CANCELED (required) + * @param status the CommitSatus instance hoilding the optional parms: ref, name, target_url, + * description, and coverage + * @return a CommitStatus instance with the updated info + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public CommitStatus addCommitStatus( + final Object projectIdOrPath, + final String sha, + final CommitBuildState state, + final CommitStatus status) + throws GitLabApiException { + return addCommitStatus(projectIdOrPath, sha, state, null, status); + } + + /** + * Add or update the build status of a commit. The following fluent methods are available on the + * CommitStatus instance for setting up the status: + * + *

+   * withCoverage(Float)
+   * withDescription(String)
+   * withName(String)
+   * withRef(String)
+   * withTargetUrl(String)
+   * 
+ * + *
GitLab Endpoint: POST /projects/:id/statuses/:sha
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance (required) + * @param sha a commit SHA (required) + * @param state the state of the status. Can be one of the following: PENDING, RUNNING, SUCCESS, + * FAILED, CANCELED (required) + * @param pipelineId The ID of the pipeline to set status. Use in case of several pipeline on same + * SHA (optional) + * @param status the CommitSatus instance hoilding the optional parms: ref, name, target_url, + * description, and coverage + * @return a CommitStatus instance with the updated info + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public CommitStatus addCommitStatus( + final Object projectIdOrPath, + final String sha, + final CommitBuildState state, + final Long pipelineId, + final CommitStatus status) + throws GitLabApiException { + + if (projectIdOrPath == null) { + throw new RuntimeException("projectIdOrPath cannot be null"); } - /** - *

Add or update the build status of a commit. The following fluent methods are available on the - * CommitStatus instance for setting up the status:

- *

-     * withCoverage(Float)
-     * withDescription(String)
-     * withName(String)
-     * withRef(String)
-     * withTargetUrl(String)
-     * 
- * - *
GitLab Endpoint: POST /projects/:id/statuses/:sha
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance (required) - * @param sha a commit SHA (required) - * @param state the state of the status. Can be one of the following: PENDING, RUNNING, SUCCESS, FAILED, CANCELED (required) - * @param status the CommitSatus instance hoilding the optional parms: ref, name, target_url, description, and coverage - * @return a CommitStatus instance with the updated info - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public CommitStatus addCommitStatus(Object projectIdOrPath, String sha, CommitBuildState state, CommitStatus status) throws GitLabApiException { - return addCommitStatus(projectIdOrPath, sha, state, null, status); + if (sha == null || sha.trim().isEmpty()) { + throw new RuntimeException("sha cannot be null"); } - /** - *

Add or update the build status of a commit. The following fluent methods are available on the - * CommitStatus instance for setting up the status:

- *

-     * withCoverage(Float)
-     * withDescription(String)
-     * withName(String)
-     * withRef(String)
-     * withTargetUrl(String)
-     * 
- * - *
GitLab Endpoint: POST /projects/:id/statuses/:sha
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance (required) - * @param sha a commit SHA (required) - * @param state the state of the status. Can be one of the following: PENDING, RUNNING, SUCCESS, FAILED, CANCELED (required) - * @param pipelineId The ID of the pipeline to set status. Use in case of several pipeline on same SHA (optional) - * @param status the CommitSatus instance hoilding the optional parms: ref, name, target_url, description, and coverage - * @return a CommitStatus instance with the updated info - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public CommitStatus addCommitStatus(Object projectIdOrPath, String sha, CommitBuildState state, Long pipelineId, CommitStatus status) throws GitLabApiException { - - if (projectIdOrPath == null) { - throw new RuntimeException("projectIdOrPath cannot be null"); - } - - if (sha == null || sha.trim().isEmpty()) { - throw new RuntimeException("sha cannot be null"); - } - - GitLabApiForm formData = new GitLabApiForm().withParam("state", state, true); - if (status != null) { - formData.withParam("ref", status.getRef()) - .withParam("name", status.getName()) - .withParam("target_url", status.getTargetUrl()) - .withParam("description", status.getDescription()) - .withParam("coverage", status.getCoverage()); - } - - if (pipelineId != null) { - formData.withParam("pipeline_id", pipelineId); - } - - Response response = post(Response.Status.OK, formData, "projects", getProjectIdOrPath(projectIdOrPath), "statuses", sha); - return (response.readEntity(CommitStatus.class)); - } - - /** - * Get the list of diffs of a commit in a project. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/diff
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha a commit hash or name of a branch or tag - * @return a List of Diff instances for the specified project ID/sha pair - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public List getDiff(Object projectIdOrPath, String sha) throws GitLabApiException { - return (getDiff(projectIdOrPath, sha, getDefaultPerPage()).all()); + final GitLabApiForm formData = new GitLabApiForm().withParam("state", state, true); + if (status != null) { + formData + .withParam("ref", status.getRef()) + .withParam("name", status.getName()) + .withParam("target_url", status.getTargetUrl()) + .withParam("description", status.getDescription()) + .withParam("coverage", status.getCoverage()); } - /** - * Get the Pager of diffs of a commit in a project. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/diff
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha a commit hash or name of a branch or tag - * @param itemsPerPage the number of Diff instances that will be fetched per page - * @return a Pager of Diff instances for the specified project ID/sha pair - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Pager getDiff(Object projectIdOrPath, String sha, int itemsPerPage) throws GitLabApiException { - - if (projectIdOrPath == null) { - throw new RuntimeException("projectIdOrPath cannot be null"); - } - - if (sha == null || sha.trim().isEmpty()) { - throw new RuntimeException("sha cannot be null"); - } - - return (new Pager(this, Diff.class, itemsPerPage, null, - "projects", getProjectIdOrPath(projectIdOrPath), "repository", "commits", sha, "diff")); + if (pipelineId != null) { + formData.withParam("pipeline_id", pipelineId); } - /** - * Get the Diff of diffs of a commit in a project. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/diff
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha a commit hash or name of a branch or tag - * @return a Stream of Diff instances for the specified project ID/sha pair - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Stream getDiffStream(Object projectIdOrPath, String sha) throws GitLabApiException { - return (getDiff(projectIdOrPath, sha, getDefaultPerPage()).stream()); + final Response response = + post( + Response.Status.OK, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "statuses", + sha); + return (response.readEntity(CommitStatus.class)); + } + + /** + * Get the list of diffs of a commit in a project. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/diff
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha a commit hash or name of a branch or tag + * @return a List of Diff instances for the specified project ID/sha pair + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public List getDiff(final Object projectIdOrPath, final String sha) + throws GitLabApiException { + return (getDiff(projectIdOrPath, sha, getDefaultPerPage()).all()); + } + + /** + * Get the Pager of diffs of a commit in a project. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/diff
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha a commit hash or name of a branch or tag + * @param itemsPerPage the number of Diff instances that will be fetched per page + * @return a Pager of Diff instances for the specified project ID/sha pair + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Pager getDiff(final Object projectIdOrPath, final String sha, final int itemsPerPage) + throws GitLabApiException { + + if (projectIdOrPath == null) { + throw new RuntimeException("projectIdOrPath cannot be null"); } - /** - * Get the comments of a commit in a project. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/comments
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha a commit hash or name of a branch or tag - * @return a List of Comment instances for the specified project ID/sha pair - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public List getComments(Object projectIdOrPath, String sha) throws GitLabApiException { - return (getComments(projectIdOrPath, sha, getDefaultPerPage()).all()); + if (sha == null || sha.trim().isEmpty()) { + throw new RuntimeException("sha cannot be null"); } - /** - * Get a Pager of the comments of a commit in a project. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/comments
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha a commit hash or name of a branch or tag - * @param itemsPerPage the number of Comment instances that will be fetched per page - * @return a List of Comment instances for the specified project ID/sha pair - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Pager getComments(Object projectIdOrPath, String sha, int itemsPerPage) throws GitLabApiException { - return new Pager(this, Comment.class, itemsPerPage, null, "projects", getProjectIdOrPath(projectIdOrPath), "repository", "commits", sha, "comments"); + return (new Pager( + this, + Diff.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "repository", + "commits", + sha, + "diff")); + } + + /** + * Get the Diff of diffs of a commit in a project. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/diff
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha a commit hash or name of a branch or tag + * @return a Stream of Diff instances for the specified project ID/sha pair + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Stream getDiffStream(final Object projectIdOrPath, final String sha) + throws GitLabApiException { + return (getDiff(projectIdOrPath, sha, getDefaultPerPage()).stream()); + } + + /** + * Get the comments of a commit in a project. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/comments
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha a commit hash or name of a branch or tag + * @return a List of Comment instances for the specified project ID/sha pair + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public List getComments(final Object projectIdOrPath, final String sha) + throws GitLabApiException { + return (getComments(projectIdOrPath, sha, getDefaultPerPage()).all()); + } + + /** + * Get a Pager of the comments of a commit in a project. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/comments
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha a commit hash or name of a branch or tag + * @param itemsPerPage the number of Comment instances that will be fetched per page + * @return a List of Comment instances for the specified project ID/sha pair + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Pager getComments( + final Object projectIdOrPath, final String sha, final int itemsPerPage) + throws GitLabApiException { + return new Pager( + this, + Comment.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "repository", + "commits", + sha, + "comments"); + } + + /** + * Get the comments of a commit in a project as a Stream. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/comments
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha a commit hash or name of a branch or tag + * @return a Stream of Comment instances for the specified project ID/sha pair + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Stream getCommentsStream(final Object projectIdOrPath, final String sha) + throws GitLabApiException { + return (getComments(projectIdOrPath, sha, getDefaultPerPage()).stream()); + } + + /** + * Add a comment to a commit. In order to post a comment in a particular line of a particular + * file, you must specify the full commit SHA, the path, the line and lineType should be NEW. + * + *
GitLab Endpoint: POST /projects/:id/repository/commits/:sha/comments
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha a commit hash or name of a branch or tag + * @param note the text of the comment, required + * @param path the file path relative to the repository, optional + * @param line the line number where the comment should be placed, optional + * @param lineType the line type, optional + * @return a Comment instance for the posted comment + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Comment addComment( + final Object projectIdOrPath, + final String sha, + final String note, + final String path, + final Integer line, + final LineType lineType) + throws GitLabApiException { + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("note", note, true) + .withParam("path", path) + .withParam("line", line) + .withParam("line_type", lineType); + final Response response = + post( + Response.Status.CREATED, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "repository", + "commits", + sha, + "comments"); + return (response.readEntity(Comment.class)); + } + + /** + * Add a comment to a commit. + * + *
GitLab Endpoint: POST /projects/:id/repository/commits/:sha/comments
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha a commit hash or name of a branch or tag + * @param note the text of the comment, required + * @return a Comment instance for the posted comment + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Comment addComment(final Object projectIdOrPath, final String sha, final String note) + throws GitLabApiException { + return (addComment(projectIdOrPath, sha, note, null, null, null)); + } + + /** + * Create a commit with single file and action. + * + *
GitLab Endpoint: POST /projects/:id/repository/commits
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param branch tame of the branch to commit into. To create a new branch, also provide + * startBranch + * @param commitMessage the commit message + * @param startBranch the name of the branch to start the new commit from + * @param authorEmail the commit author's email address + * @param authorName the commit author's name + * @param action the CommitAction to commit + * @return the created Commit instance + * @throws GitLabApiException if any exception occurs during execution + */ + public Commit createCommit( + final Object projectIdOrPath, + final String branch, + final String commitMessage, + final String startBranch, + final String authorEmail, + final String authorName, + final CommitAction action) + throws GitLabApiException { + + // Validate the action + if (action == null) { + throw new GitLabApiException("action cannot be null or empty."); } - /** - * Get the comments of a commit in a project as a Stream. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/comments
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha a commit hash or name of a branch or tag - * @return a Stream of Comment instances for the specified project ID/sha pair - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Stream getCommentsStream(Object projectIdOrPath, String sha) throws GitLabApiException { - return (getComments(projectIdOrPath, sha, getDefaultPerPage()).stream()); + return (createCommit( + projectIdOrPath, + branch, + commitMessage, + startBranch, + authorEmail, + authorName, + Arrays.asList(action))); + } + + /** + * Create a commit with multiple files and actions. + * + *
GitLab Endpoint: POST /projects/:id/repository/commits
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param branch tame of the branch to commit into. To create a new branch, also provide + * startBranch + * @param commitMessage the commit message + * @param startBranch the name of the branch to start the new commit from + * @param authorEmail the commit author's email address + * @param authorName the commit author's name + * @param actions the array of CommitAction to commit as a batch + * @return the created Commit instance + * @throws GitLabApiException if any exception occurs during execution + */ + public Commit createCommit( + final Object projectIdOrPath, + final String branch, + final String commitMessage, + final String startBranch, + final String authorEmail, + final String authorName, + final List actions) + throws GitLabApiException { + + final CommitPayload payload = + new CommitPayload() + .withBranch(branch) + .withStartBranch(startBranch) + .withCommitMessage(commitMessage) + .withAuthorEmail(authorEmail) + .withAuthorName(authorName) + .withActions(actions); + return (createCommit(projectIdOrPath, payload)); + } + + /** + * Create a commit with multiple files and actions. + * + *
GitLab Endpoint: POST /projects/:id/repository/commits
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param payload a CommitPayload instance holding the parameters for the commit + * @return the created Commit instance + * @throws GitLabApiException if any exception occurs during execution + */ + public Commit createCommit(final Object projectIdOrPath, final CommitPayload payload) + throws GitLabApiException { + + // Validate the actions + final List actions = payload.getActions(); + if (actions == null || actions.isEmpty()) { + throw new GitLabApiException("actions cannot be null or empty."); } - /** - * Add a comment to a commit. In order to post a comment in a particular line of a particular file, - * you must specify the full commit SHA, the path, the line and lineType should be NEW. - * - *
GitLab Endpoint: POST /projects/:id/repository/commits/:sha/comments
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha a commit hash or name of a branch or tag - * @param note the text of the comment, required - * @param path the file path relative to the repository, optional - * @param line the line number where the comment should be placed, optional - * @param lineType the line type, optional - * @return a Comment instance for the posted comment - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Comment addComment(Object projectIdOrPath, String sha, String note, String path, Integer line, LineType lineType) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() - .withParam("note", note, true) - .withParam("path", path) - .withParam("line", line) - .withParam("line_type", lineType); - Response response = post(Response.Status.CREATED, formData, "projects", getProjectIdOrPath(projectIdOrPath), "repository", "commits", sha, "comments"); - return (response.readEntity(Comment.class)); - } + for (final CommitAction action : actions) { - /** - * Add a comment to a commit. - * - *
GitLab Endpoint: POST /projects/:id/repository/commits/:sha/comments
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha a commit hash or name of a branch or tag - * @param note the text of the comment, required - * @return a Comment instance for the posted comment - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Comment addComment(Object projectIdOrPath, String sha, String note) throws GitLabApiException { - return (addComment(projectIdOrPath, sha, note, null, null, null)); - } - - /** - * Create a commit with single file and action. - * - *
GitLab Endpoint: POST /projects/:id/repository/commits
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param branch tame of the branch to commit into. To create a new branch, also provide startBranch - * @param commitMessage the commit message - * @param startBranch the name of the branch to start the new commit from - * @param authorEmail the commit author's email address - * @param authorName the commit author's name - * @param action the CommitAction to commit - * @return the created Commit instance - * @throws GitLabApiException if any exception occurs during execution - */ - public Commit createCommit(Object projectIdOrPath, String branch, String commitMessage, String startBranch, - String authorEmail, String authorName, CommitAction action) throws GitLabApiException { - - // Validate the action - if (action == null) { - throw new GitLabApiException("action cannot be null or empty."); - } - - return (createCommit(projectIdOrPath, branch, commitMessage, startBranch, - authorEmail, authorName, Arrays.asList(action))); - } - - /** - * Create a commit with multiple files and actions. - * - *
GitLab Endpoint: POST /projects/:id/repository/commits
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param branch tame of the branch to commit into. To create a new branch, also provide startBranch - * @param commitMessage the commit message - * @param startBranch the name of the branch to start the new commit from - * @param authorEmail the commit author's email address - * @param authorName the commit author's name - * @param actions the array of CommitAction to commit as a batch - * @return the created Commit instance - * @throws GitLabApiException if any exception occurs during execution - */ - public Commit createCommit(Object projectIdOrPath, String branch, String commitMessage, String startBranch, - String authorEmail, String authorName, List actions) throws GitLabApiException { - - CommitPayload payload = new CommitPayload() - .withBranch(branch) - .withStartBranch(startBranch) - .withCommitMessage(commitMessage) - .withAuthorEmail(authorEmail) - .withAuthorName(authorName) - .withActions(actions); - return (createCommit(projectIdOrPath, payload)); - } - - /** - * Create a commit with multiple files and actions. - * - *
GitLab Endpoint: POST /projects/:id/repository/commits
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param payload a CommitPayload instance holding the parameters for the commit - * @return the created Commit instance - * @throws GitLabApiException if any exception occurs during execution - */ - public Commit createCommit(Object projectIdOrPath, CommitPayload payload) throws GitLabApiException { - - // Validate the actions - List actions = payload.getActions(); - if (actions == null || actions.isEmpty()) { - throw new GitLabApiException("actions cannot be null or empty."); - } - - for (CommitAction action : actions) { - - // File content is required for create and update - Action actionType = action.getAction(); - if (actionType == Action.CREATE || actionType == Action.UPDATE) { - String content = action.getContent(); - if (content == null) { - throw new GitLabApiException("Content cannot be null for create or update actions."); - } - } - } - - if (payload.getStartProject() != null) { - payload.setStartProject(getProjectIdOrPath(payload.getStartProject())); + // File content is required for create and update + final Action actionType = action.getAction(); + if (actionType == Action.CREATE || actionType == Action.UPDATE) { + final String content = action.getContent(); + if (content == null) { + throw new GitLabApiException("Content cannot be null for create or update actions."); } - - Response response = post(Response.Status.CREATED, payload, - "projects", getProjectIdOrPath(projectIdOrPath), "repository", "commits"); - return (response.readEntity(Commit.class)); - } - - /** - * Reverts a commit in a given branch. - * - *
GitLab Endpoint: POST /projects/:id/repository/commits/:sha/revert
- * - * @since GitLab 11.5 - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha the commit SHA to revert - * @param branch the target branch to revert the commit on - * @return a Commit instance holding the reverted commit - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Commit revertCommit(Object projectIdOrPath, String sha, String branch) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm().withParam("branch", branch, true); - Response response = post(Response.Status.CREATED, formData, - "projects", getProjectIdOrPath(projectIdOrPath), "repository", "commits", sha, "revert"); - return (response.readEntity(Commit.class)); - } - - /** - * Cherry picks a commit in a given branch. - * - *
GitLab Endpoint: POST /projects/:id/repository/commits/:sha/cherry_pick
- * - * @since GitLab 8.15 - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha the commit SHA to cherry pick - * @param branch the target branch to cherry pick the commit on - * @return a Commit instance holding the cherry picked commit - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Commit cherryPickCommit(Object projectIdOrPath, String sha, String branch) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm().withParam("branch", branch, true); - Response response = post(Response.Status.CREATED, formData, - "projects", getProjectIdOrPath(projectIdOrPath), "repository", "commits", sha, "cherry_pick"); - return (response.readEntity(Commit.class)); - } - - /** - * Get a list of Merge Requests related to the specified commit. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/merge_requests
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha the commit SHA to get merge requests for - * @return a list containing the MergeRequest instances for the specified project/SHA - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public List getMergeRequests(Object projectIdOrPath, String sha) throws GitLabApiException { - return (getMergeRequests(projectIdOrPath, sha, getDefaultPerPage()).all()); - } - - /** - * Get a Pager of Merge Requests related to the specified commit. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/merge_requests
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha the commit SHA to get merge requests for - * @param itemsPerPage the number of Commit instances that will be fetched per page - * @return a Pager containing the MergeRequest instances for the specified project/SHA - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Pager getMergeRequests(Object projectIdOrPath, String sha, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, MergeRequest.class, itemsPerPage, null, - "projects", getProjectIdOrPath(projectIdOrPath), "repository", "commits", urlEncode(sha), "merge_requests")); + } } - /** - * Get a Stream of Merge Requests related to the specified commit. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/merge_requests
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha the commit SHA to get merge requests for - * @return a Stream containing the MergeRequest instances for the specified project/SHA - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Stream getMergeRequestsStream(Object projectIdOrPath, String sha) throws GitLabApiException { - return (getMergeRequests(projectIdOrPath, sha, getDefaultPerPage()).stream()); + if (payload.getStartProject() != null) { + payload.setStartProject(getProjectIdOrPath(payload.getStartProject())); } - /** - * Get the GPG signature from a commit, if it is signed. For unsigned commits, it results in a 404 response. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/signature
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha a commit hash or name of a branch or tag - * @return the GpgSignature instance for the specified project ID/sha pair - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public GpgSignature getGpgSignature(Object projectIdOrPath, String sha) throws GitLabApiException { - Response response = get(Response.Status.OK, getDefaultPerPageParam(), - "projects", getProjectIdOrPath(projectIdOrPath), "repository", "commits", urlEncode(sha), "signature"); - return (response.readEntity(GpgSignature.class)); - } - - /** - * Get the GPG signature from a commit as an Optional instance - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/signature
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param sha a commit hash or name of a branch or tag - * @return the GpgSignature for the specified project ID/sha pair as an Optional instance - */ - public Optional getOptionalGpgSignature(Object projectIdOrPath, String sha) { - try { - return (Optional.ofNullable(getGpgSignature(projectIdOrPath, sha))); - } catch (GitLabApiException glae) { - return (GitLabApi.createOptionalFromException(glae)); - } + final Response response = + post( + Response.Status.CREATED, + payload, + "projects", + getProjectIdOrPath(projectIdOrPath), + "repository", + "commits"); + return (response.readEntity(Commit.class)); + } + + /** + * Reverts a commit in a given branch. + * + *
GitLab Endpoint: POST /projects/:id/repository/commits/:sha/revert
+ * + * @since GitLab 11.5 + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha the commit SHA to revert + * @param branch the target branch to revert the commit on + * @return a Commit instance holding the reverted commit + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Commit revertCommit(final Object projectIdOrPath, final String sha, final String branch) + throws GitLabApiException { + final GitLabApiForm formData = new GitLabApiForm().withParam("branch", branch, true); + final Response response = + post( + Response.Status.CREATED, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "repository", + "commits", + sha, + "revert"); + return (response.readEntity(Commit.class)); + } + + /** + * Cherry picks a commit in a given branch. + * + *
GitLab Endpoint: POST /projects/:id/repository/commits/:sha/cherry_pick
+ * + * @since GitLab 8.15 + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha the commit SHA to cherry pick + * @param branch the target branch to cherry pick the commit on + * @return a Commit instance holding the cherry picked commit + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Commit cherryPickCommit( + final Object projectIdOrPath, final String sha, final String branch) + throws GitLabApiException { + final GitLabApiForm formData = new GitLabApiForm().withParam("branch", branch, true); + final Response response = + post( + Response.Status.CREATED, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "repository", + "commits", + sha, + "cherry_pick"); + return (response.readEntity(Commit.class)); + } + + /** + * Get a list of Merge Requests related to the specified commit. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/merge_requests
+   * 
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha the commit SHA to get merge requests for + * @return a list containing the MergeRequest instances for the specified project/SHA + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public List getMergeRequests(final Object projectIdOrPath, final String sha) + throws GitLabApiException { + return (getMergeRequests(projectIdOrPath, sha, getDefaultPerPage()).all()); + } + + /** + * Get a Pager of Merge Requests related to the specified commit. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/merge_requests
+   * 
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha the commit SHA to get merge requests for + * @param itemsPerPage the number of Commit instances that will be fetched per page + * @return a Pager containing the MergeRequest instances for the specified project/SHA + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Pager getMergeRequests( + final Object projectIdOrPath, final String sha, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, + MergeRequest.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "repository", + "commits", + urlEncode(sha), + "merge_requests")); + } + + /** + * Get a Stream of Merge Requests related to the specified commit. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/merge_requests
+   * 
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha the commit SHA to get merge requests for + * @return a Stream containing the MergeRequest instances for the specified project/SHA + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Stream getMergeRequestsStream(final Object projectIdOrPath, final String sha) + throws GitLabApiException { + return (getMergeRequests(projectIdOrPath, sha, getDefaultPerPage()).stream()); + } + + /** + * Get the GPG signature from a commit, if it is signed. For unsigned commits, it results in a 404 + * response. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/signature
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha a commit hash or name of a branch or tag + * @return the GpgSignature instance for the specified project ID/sha pair + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public GpgSignature getGpgSignature(final Object projectIdOrPath, final String sha) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getDefaultPerPageParam(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "repository", + "commits", + urlEncode(sha), + "signature"); + return (response.readEntity(GpgSignature.class)); + } + + /** + * Get the GPG signature from a commit as an Optional instance + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:sha/signature
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param sha a commit hash or name of a branch or tag + * @return the GpgSignature for the specified project ID/sha pair as an Optional instance + */ + public Optional getOptionalGpgSignature( + final Object projectIdOrPath, final String sha) { + try { + return (Optional.ofNullable(getGpgSignature(projectIdOrPath, sha))); + } catch (final GitLabApiException glae) { + return (GitLabApi.createOptionalFromException(glae)); } + } } diff --git a/src/main/java/org/gitlab4j/api/ContainerRegistryApi.java b/src/main/java/org/gitlab4j/api/ContainerRegistryApi.java index 87fc62892..e57813bf2 100644 --- a/src/main/java/org/gitlab4j/api/ContainerRegistryApi.java +++ b/src/main/java/org/gitlab4j/api/ContainerRegistryApi.java @@ -26,236 +26,334 @@ import java.util.List; import java.util.Optional; import java.util.stream.Stream; - -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; - +import jakarta.ws.rs.core.GenericType; +import jakarta.ws.rs.core.Response; import org.gitlab4j.api.models.RegistryRepository; import org.gitlab4j.api.models.RegistryRepositoryTag; /** - *

This class implements the client side API for the GitLab Container Registry API. - * See Container Registry API at GitLab - * for more information.

+ * This class implements the client side API for the GitLab Container Registry API. See Container Registry API at + * GitLab for more information. */ public class ContainerRegistryApi extends AbstractApi { - public ContainerRegistryApi(GitLabApi gitLabApi) { - super(gitLabApi); - } - - /** - * Get a list of registry repositories in a project. - * - *
GitLab Endpoint: GET /projects/:id/registry/repositories
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @return a list of pages in the project's registry repositories - * @throws GitLabApiException if any exception occurs - */ - public List getRepositories(Object projectIdOrPath) throws GitLabApiException { - return (getRepositories(projectIdOrPath, getDefaultPerPage()).all()); - } + public ContainerRegistryApi(final GitLabApi gitLabApi) { + super(gitLabApi); + } - /** - * Get a list of registry repositories in a project that fall within the specified page parameters. - * - *
GitLab Endpoint: GET /projects/:id/registry/repositories
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param page the page to get - * @param perPage the number of Package instances per page - * @return a list of registry repositories for the specified range - * @throws GitLabApiException if any exception occurs - */ - public List getRepositories(Object projectIdOrPath, int page, int perPage) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), - "projects", getProjectIdOrPath(projectIdOrPath), "registry", "repositories"); - return response.readEntity(new GenericType>() { - }); - } + /** + * Get a list of registry repositories in a project. + * + *
GitLab Endpoint: GET /projects/:id/registry/repositories
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @return a list of pages in the project's registry repositories + * @throws GitLabApiException if any exception occurs + */ + public List getRepositories(final Object projectIdOrPath) + throws GitLabApiException { + return (getRepositories(projectIdOrPath, getDefaultPerPage()).all()); + } - /** - * Get a Pager of registry repositories in a project. - * - *
GitLab Endpoint: GET /projects/:id/registry/repositories
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param itemsPerPage the number of RegistryRepository instances per page - * @return a Pager of registry repositories for the specified range - * @throws GitLabApiException if any exception occurs - */ - public Pager getRepositories(Object projectIdOrPath, int itemsPerPage) throws GitLabApiException { - return (new Pager<>(this, RegistryRepository.class, itemsPerPage, null, - "projects", getProjectIdOrPath(projectIdOrPath), "registry", "repositories")); - } + /** + * Get a list of registry repositories in a project that fall within the specified page + * parameters. + * + *
GitLab Endpoint: GET /projects/:id/registry/repositories
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param page the page to get + * @param perPage the number of Package instances per page + * @return a list of registry repositories for the specified range + * @throws GitLabApiException if any exception occurs + */ + public List getRepositories( + final Object projectIdOrPath, final int page, final int perPage) throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getPageQueryParams(page, perPage), + "projects", + getProjectIdOrPath(projectIdOrPath), + "registry", + "repositories"); + return response.readEntity(new GenericType>() {}); + } - /** - * Get a Stream of registry repositories in a project. - * - *
GitLab Endpoint: GET /projects/:id/registry/repositories
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @return a Stream of pages in the project's registry repositories - * @throws GitLabApiException if any exception occurs - */ - public Stream getRepositoriesStream(Object projectIdOrPath) throws GitLabApiException { - return (getRepositories(projectIdOrPath, getDefaultPerPage()).stream()); - } + /** + * Get a Pager of registry repositories in a project. + * + *
GitLab Endpoint: GET /projects/:id/registry/repositories
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param itemsPerPage the number of RegistryRepository instances per page + * @return a Pager of registry repositories for the specified range + * @throws GitLabApiException if any exception occurs + */ + public Pager getRepositories( + final Object projectIdOrPath, final int itemsPerPage) throws GitLabApiException { + return (new Pager<>( + this, + RegistryRepository.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "registry", + "repositories")); + } - /** - * Delete a repository in registry. - *

- * This operation is executed asynchronously and might take some time to get executed. - * - *

GitLab Endpoint: DELETE /projects/:id/registry/repositories/:repository_id
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param repositoryId the ID of registry repository - * @throws GitLabApiException if any exception occurs - */ - public void deleteRepository(Object projectIdOrPath, Long repositoryId) throws GitLabApiException { + /** + * Get a Stream of registry repositories in a project. + * + *
GitLab Endpoint: GET /projects/:id/registry/repositories
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @return a Stream of pages in the project's registry repositories + * @throws GitLabApiException if any exception occurs + */ + public Stream getRepositoriesStream(final Object projectIdOrPath) + throws GitLabApiException { + return (getRepositories(projectIdOrPath, getDefaultPerPage()).stream()); + } - if (repositoryId == null) { - throw new RuntimeException("repositoryId cannot be null"); - } + /** + * Delete a repository in registry. + * + *

This operation is executed asynchronously and might take some time to get executed. + * + *

GitLab Endpoint: DELETE /projects/:id/registry/repositories/:repository_id
+   * 
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param repositoryId the ID of registry repository + * @throws GitLabApiException if any exception occurs + */ + public void deleteRepository(final Object projectIdOrPath, final Long repositoryId) + throws GitLabApiException { - delete(Response.Status.NO_CONTENT, null, "projects", getProjectIdOrPath(projectIdOrPath), "registry", "repositories", repositoryId); + if (repositoryId == null) { + throw new RuntimeException("repositoryId cannot be null"); } - /** - * Get a list of tags for given registry repository. - * - *
GitLab Endpoint: GET /projects/:id/registry/repositories/:repository_id/tags
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param repositoryId the ID of registry repository - * @return a list of Repository Tags for the specified repository ID - * @throws GitLabApiException if any exception occurs - */ - public List getRepositoryTags(Object projectIdOrPath, Long repositoryId) throws GitLabApiException { - return getRepositoryTags(projectIdOrPath, repositoryId, getDefaultPerPage()).all(); - } + delete( + Response.Status.NO_CONTENT, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "registry", + "repositories", + repositoryId); + } - /** - * Get a Pager of tags for given registry repository. - * - *
GitLab Endpoint: GET /projects/:id/registry/repositories/:repository_id/tags
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param repositoryId the ID of registry repository - * @param itemsPerPage the number of RegistryRepositoryTag instances per page - * @return a Pager of Repository Tags for the specified repository ID - * @throws GitLabApiException if any exception occurs - */ - public Pager getRepositoryTags(Object projectIdOrPath, Long repositoryId, int itemsPerPage) throws GitLabApiException { - return (new Pager<>(this, RegistryRepositoryTag.class, itemsPerPage, null, - "projects", getProjectIdOrPath(projectIdOrPath), "registry", "repositories", repositoryId, "tags")); - } + /** + * Get a list of tags for given registry repository. + * + *
GitLab Endpoint: GET /projects/:id/registry/repositories/:repository_id/tags
+   * 
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param repositoryId the ID of registry repository + * @return a list of Repository Tags for the specified repository ID + * @throws GitLabApiException if any exception occurs + */ + public List getRepositoryTags( + final Object projectIdOrPath, final Long repositoryId) throws GitLabApiException { + return getRepositoryTags(projectIdOrPath, repositoryId, getDefaultPerPage()).all(); + } - /** - * Get a Stream of tags for given registry repository. - * - *
GitLab Endpoint: GET /projects/:id/registry/repositories/:repository_id/tags
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param repositoryId the ID of registry repository - * @return a list of Repository Tags for the specified repository ID - * @throws GitLabApiException if any exception occurs - */ - public Stream getRepositoryTagsStream(Object projectIdOrPath, Long repositoryId) throws GitLabApiException { - return getRepositoryTags(projectIdOrPath, repositoryId, getDefaultPerPage()).stream(); - } + /** + * Get a Pager of tags for given registry repository. + * + *
GitLab Endpoint: GET /projects/:id/registry/repositories/:repository_id/tags
+   * 
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param repositoryId the ID of registry repository + * @param itemsPerPage the number of RegistryRepositoryTag instances per page + * @return a Pager of Repository Tags for the specified repository ID + * @throws GitLabApiException if any exception occurs + */ + public Pager getRepositoryTags( + final Object projectIdOrPath, final Long repositoryId, final int itemsPerPage) + throws GitLabApiException { + return (new Pager<>( + this, + RegistryRepositoryTag.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "registry", + "repositories", + repositoryId, + "tags")); + } - /** - * Get details of a registry repository tag. - * - *
GitLab Endpoint: GET /projects/:id/registry/repositories/:repository_id/tags/:tag_name
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param repositoryId the ID of registry repository - * @param tagName the name of tag - * @return the Repository Tag for the specified repository ID - * @throws GitLabApiException if any exception occurs - */ - public RegistryRepositoryTag getRepositoryTag(Object projectIdOrPath, Long repositoryId, String tagName) throws GitLabApiException { - Response response = get(Response.Status.OK, null, - "projects", getProjectIdOrPath(projectIdOrPath), "registry", "repositories", repositoryId, "tags", tagName); - return response.readEntity(new GenericType() { - }); - } + /** + * Get a Stream of tags for given registry repository. + * + *
GitLab Endpoint: GET /projects/:id/registry/repositories/:repository_id/tags
+   * 
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param repositoryId the ID of registry repository + * @return a list of Repository Tags for the specified repository ID + * @throws GitLabApiException if any exception occurs + */ + public Stream getRepositoryTagsStream( + final Object projectIdOrPath, final Long repositoryId) throws GitLabApiException { + return getRepositoryTags(projectIdOrPath, repositoryId, getDefaultPerPage()).stream(); + } - /** - * Get details of a registry repository tag as the value of an Optional. - * - *
GitLab Endpoint: GET /projects/:id/registry/repositories/:repository_id/tags/:tag_name
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param repositoryId the ID of registry repository - * @param tagName the name of tag - * @return the Repository Tag for the specified repository ID as the value of the Optional - */ - public Optional getOptionalRepositoryTag(Object projectIdOrPath, Long repositoryId, String tagName) { - try { - return (Optional.ofNullable(getRepositoryTag(projectIdOrPath, repositoryId, tagName))); - } catch (GitLabApiException glae) { - return (GitLabApi.createOptionalFromException(glae)); - } - } + /** + * Get details of a registry repository tag. + * + *
+   * GitLab Endpoint: GET /projects/:id/registry/repositories/:repository_id/tags/:tag_name
+   * 
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param repositoryId the ID of registry repository + * @param tagName the name of tag + * @return the Repository Tag for the specified repository ID + * @throws GitLabApiException if any exception occurs + */ + public RegistryRepositoryTag getRepositoryTag( + final Object projectIdOrPath, final Long repositoryId, final String tagName) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "registry", + "repositories", + repositoryId, + "tags", + tagName); + return response.readEntity(new GenericType() {}); + } - /** - * Delete a registry repository tag. - * - *
GitLab Endpoint: DELETE /projects/:id/registry/repositories/:repository_id/tags/:tag_name
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param repositoryId the ID of registry repository - * @param tagName the name of the tag to delete - * @throws GitLabApiException if any exception occurs - */ - public void deleteRepositoryTag(Object projectIdOrPath, Long repositoryId, String tagName) throws GitLabApiException { + /** + * Get details of a registry repository tag as the value of an Optional. + * + *
+   * GitLab Endpoint: GET /projects/:id/registry/repositories/:repository_id/tags/:tag_name
+   * 
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param repositoryId the ID of registry repository + * @param tagName the name of tag + * @return the Repository Tag for the specified repository ID as the value of the Optional + */ + public Optional getOptionalRepositoryTag( + final Object projectIdOrPath, final Long repositoryId, final String tagName) { + try { + return (Optional.ofNullable(getRepositoryTag(projectIdOrPath, repositoryId, tagName))); + } catch (final GitLabApiException glae) { + return (GitLabApi.createOptionalFromException(glae)); + } + } - if (repositoryId == null) { - throw new RuntimeException("repositoryId cannot be null"); - } + /** + * Delete a registry repository tag. + * + *
+   * GitLab Endpoint: DELETE /projects/:id/registry/repositories/:repository_id/tags/:tag_name
+   * 
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param repositoryId the ID of registry repository + * @param tagName the name of the tag to delete + * @throws GitLabApiException if any exception occurs + */ + public void deleteRepositoryTag( + final Object projectIdOrPath, final Long repositoryId, final String tagName) + throws GitLabApiException { - delete(Response.Status.NO_CONTENT, null, "projects", getProjectIdOrPath(projectIdOrPath), "registry", "repositories", repositoryId, "tags", tagName); + if (repositoryId == null) { + throw new RuntimeException("repositoryId cannot be null"); } - /** - * Delete repository tags in bulk based on given criteria. - * - *
GitLab Endpoint: DELETE /projects/:id/registry/repositories/:repository_id/tags
- *

- * This API call performs the following operations: - *

    - *
  1. It orders all tags by creation date. The creation date is the time of the manifest creation, - * not the time of tag push.
  2. - *
  3. It removes only the tags matching the given name_regex.
  4. - *
  5. It never removes the tag named latest.
  6. - *
  7. It keeps N latest matching tags (if keep_n is specified).
  8. - *
  9. It only removes tags that are older than X amount of time (if older_than is specified).
  10. - *
  11. It schedules the asynchronous job to be executed in the background.
  12. - *
- *

- * These operations are executed asynchronously and it might take time to get executed. You can run this at most - * once an hour for a given container repository. - * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param repositoryId the ID of registry repository - * @param nameRegex the regex of the name to delete. To delete all tags specify .*. - * @param keepN the amount of latest tags of given name to keep. - * @param olderThan tags to delete that are older than the given time, written in human readable form - * 1h, 1d, 1month. - * @throws GitLabApiException if any exception occurs - */ - public void deleteRepositoryTags(Object projectIdOrPath, Long repositoryId, String nameRegex, Integer keepN, String olderThan) throws GitLabApiException { + delete( + Response.Status.NO_CONTENT, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "registry", + "repositories", + repositoryId, + "tags", + tagName); + } - GitLabApiForm formData = new GitLabApiForm() - .withParam("name_regex", nameRegex, true) - .withParam("keep_n", keepN) - .withParam("older_than", olderThan); + /** + * Delete repository tags in bulk based on given criteria. + * + *

+   * GitLab Endpoint: DELETE /projects/:id/registry/repositories/:repository_id/tags
+   * 
+ * + *

This API call performs the following operations: + * + *

    + *
  1. It orders all tags by creation date. The creation date is the time of the manifest + * creation, not the time of tag push. + *
  2. It removes only the tags matching the given name_regex. + *
  3. It never removes the tag named latest. + *
  4. It keeps N latest matching tags (if keep_n is specified). + *
  5. It only removes tags that are older than X amount of time (if older_than is specified). + *
  6. It schedules the asynchronous job to be executed in the background. + *
+ * + *

These operations are executed asynchronously and it might take time to get executed. You can + * run this at most once an hour for a given container repository. + * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param repositoryId the ID of registry repository + * @param nameRegex the regex of the name to delete. To delete all tags specify .*. + * @param keepN the amount of latest tags of given name to keep. + * @param olderThan tags to delete that are older than the given time, written in human readable + * form 1h, 1d, 1month. + * @throws GitLabApiException if any exception occurs + */ + public void deleteRepositoryTags( + final Object projectIdOrPath, + final Long repositoryId, + final String nameRegex, + final Integer keepN, + final String olderThan) + throws GitLabApiException { - delete(Response.Status.NO_CONTENT, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "registry", "repositories", repositoryId, "tags"); - } + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("name_regex", nameRegex, true) + .withParam("keep_n", keepN) + .withParam("older_than", olderThan); + + delete( + Response.Status.NO_CONTENT, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "registry", + "repositories", + repositoryId, + "tags"); + } } diff --git a/src/main/java/org/gitlab4j/api/DeployKeysApi.java b/src/main/java/org/gitlab4j/api/DeployKeysApi.java index c8525956d..4a7c12a3b 100644 --- a/src/main/java/org/gitlab4j/api/DeployKeysApi.java +++ b/src/main/java/org/gitlab4j/api/DeployKeysApi.java @@ -3,11 +3,9 @@ import java.util.List; import java.util.Optional; import java.util.stream.Stream; - -import javax.ws.rs.core.Form; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; - +import jakarta.ws.rs.core.Form; +import jakarta.ws.rs.core.GenericType; +import jakarta.ws.rs.core.Response; import org.gitlab4j.api.models.DeployKey; /** @@ -15,7 +13,7 @@ */ public class DeployKeysApi extends AbstractApi { - public DeployKeysApi(GitLabApi gitLabApi) { + public DeployKeysApi(final GitLabApi gitLabApi) { super(gitLabApi); } @@ -32,7 +30,7 @@ public List getDeployKeys() throws GitLabApiException { } /** - * Get a list of all deploy keys across all projects of the GitLab instance using the specified page and per page settings. + * Get a list of all deploy keys across all projects of the GitLab instance using the specified page and per page settings. * This method requires admin access. * *

GitLab Endpoint: GET /deploy_keys
@@ -42,8 +40,8 @@ public List getDeployKeys() throws GitLabApiException { * @return the list of DeployKey in the specified range * @throws GitLabApiException if any exception occurs */ - public List getDeployKeys(int page, int perPage) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "deploy_keys"); + public List getDeployKeys(final int page, final int perPage) throws GitLabApiException { + final Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "deploy_keys"); return (response.readEntity(new GenericType>() {})); } @@ -56,7 +54,7 @@ public List getDeployKeys(int page, int perPage) throws GitLabApiExce * @return a Pager of DeployKey * @throws GitLabApiException if any exception occurs */ - public Pager getDeployKeys(int itemsPerPage) throws GitLabApiException { + public Pager getDeployKeys(final int itemsPerPage) throws GitLabApiException { return (new Pager(this, DeployKey.class, itemsPerPage, null, "deploy_keys")); } @@ -81,12 +79,12 @@ public Stream getDeployKeysStream() throws GitLabApiException { * @return a list of DeployKey * @throws GitLabApiException if any exception occurs */ - public List getProjectDeployKeys(Object projectIdOrPath) throws GitLabApiException { + public List getProjectDeployKeys(final Object projectIdOrPath) throws GitLabApiException { return (getProjectDeployKeys(projectIdOrPath, getDefaultPerPage()).all()); } /** - * Get a list of the deploy keys for the specified project using the specified page and per page settings. + * Get a list of the deploy keys for the specified project using the specified page and per page settings. * This method requires admin access. * *
GitLab Endpoint: GET /projects/:id/deploy_keys
@@ -97,8 +95,8 @@ public List getProjectDeployKeys(Object projectIdOrPath) throws GitLa * @return the list of DeployKey in the specified range * @throws GitLabApiException if any exception occurs */ - public List getProjectDeployKeys(Object projectIdOrPath, int page, int perPage) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), + public List getProjectDeployKeys(final Object projectIdOrPath, final int page, final int perPage) throws GitLabApiException { + final Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "projects", getProjectIdOrPath(projectIdOrPath), "deploy_keys"); return (response.readEntity(new GenericType>() {})); } @@ -113,7 +111,7 @@ public List getProjectDeployKeys(Object projectIdOrPath, int page, in * @return a Pager of DeployKey * @throws GitLabApiException if any exception occurs */ - public Pager getProjectDeployKeys(Object projectIdOrPath, int itemsPerPage) throws GitLabApiException { + public Pager getProjectDeployKeys(final Object projectIdOrPath, final int itemsPerPage) throws GitLabApiException { return (new Pager(this, DeployKey.class, itemsPerPage, null, "projects", getProjectIdOrPath(projectIdOrPath), "deploy_keys")); } @@ -127,7 +125,7 @@ public Pager getProjectDeployKeys(Object projectIdOrPath, int itemsPe * @return a list of DeployKey * @throws GitLabApiException if any exception occurs */ - public Stream getProjectDeployKeysStream(Object projectIdOrPath) throws GitLabApiException { + public Stream getProjectDeployKeysStream(final Object projectIdOrPath) throws GitLabApiException { return (getProjectDeployKeys(projectIdOrPath, getDefaultPerPage()).stream()); } @@ -141,13 +139,13 @@ public Stream getProjectDeployKeysStream(Object projectIdOrPath) thro * @return the DeployKey instance for the specified project ID and key ID * @throws GitLabApiException if any exception occurs */ - public DeployKey getDeployKey(Object projectIdOrPath, Long keyId) throws GitLabApiException { + public DeployKey getDeployKey(final Object projectIdOrPath, final Long keyId) throws GitLabApiException { if (keyId == null) { throw new RuntimeException("keyId cannot be null"); } - Response response = get(Response.Status.OK, null, + final Response response = get(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), "deploy_keys", keyId); return (response.readEntity(DeployKey.class)); } @@ -161,10 +159,10 @@ public DeployKey getDeployKey(Object projectIdOrPath, Long keyId) throws GitLabA * @param keyId the ID of the deploy key to delete * @return the DeployKey for the specified project ID and key ID as an Optional instance */ - public Optional getOptionalDeployKey(Object projectIdOrPath, Long keyId) { + public Optional getOptionalDeployKey(final Object projectIdOrPath, final Long keyId) { try { return (Optional.ofNullable(getDeployKey(projectIdOrPath, keyId))); - } catch (GitLabApiException glae) { + } catch (final GitLabApiException glae) { return (GitLabApi.createOptionalFromException(glae)); } } @@ -181,13 +179,13 @@ public Optional getOptionalDeployKey(Object projectIdOrPath, Long key * @return an DeployKey instance with info on the added deploy key * @throws GitLabApiException if any exception occurs */ - public DeployKey addDeployKey(Object projectIdOrPath, String title, String key, Boolean canPush) throws GitLabApiException { + public DeployKey addDeployKey(final Object projectIdOrPath, final String title, final String key, final Boolean canPush) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() + final GitLabApiForm formData = new GitLabApiForm() .withParam("title", title, true) .withParam("key", key, true) .withParam("can_push", canPush); - Response response = post(Response.Status.CREATED, formData, + final Response response = post(Response.Status.CREATED, formData, "projects", getProjectIdOrPath(projectIdOrPath), "deploy_keys"); return (response.readEntity(DeployKey.class)); } @@ -204,7 +202,7 @@ public DeployKey addDeployKey(Object projectIdOrPath, String title, String key, * @return an updated DeployKey instance * @throws GitLabApiException if any exception occurs */ - public DeployKey updateDeployKey(Object projectIdOrPath, Long deployKeyId, String title, Boolean canPush) throws GitLabApiException { + public DeployKey updateDeployKey(final Object projectIdOrPath, final Long deployKeyId, final String title, final Boolean canPush) throws GitLabApiException { if (deployKeyId == null) { throw new RuntimeException("deployKeyId cannot be null"); @@ -228,7 +226,7 @@ public DeployKey updateDeployKey(Object projectIdOrPath, Long deployKeyId, Strin * @param keyId the ID of the deploy key to delete * @throws GitLabApiException if any exception occurs */ - public void deleteDeployKey(Object projectIdOrPath, Long keyId) throws GitLabApiException { + public void deleteDeployKey(final Object projectIdOrPath, final Long keyId) throws GitLabApiException { if (keyId == null) { throw new RuntimeException("keyId cannot be null"); @@ -247,13 +245,13 @@ public void deleteDeployKey(Object projectIdOrPath, Long keyId) throws GitLabApi * @return an DeployKey instance with info on the enabled deploy key * @throws GitLabApiException if any exception occurs */ - public DeployKey enableDeployKey(Object projectIdOrPath, Long keyId) throws GitLabApiException { + public DeployKey enableDeployKey(final Object projectIdOrPath, final Long keyId) throws GitLabApiException { if (keyId == null) { throw new RuntimeException("keyId cannot be null"); } - Response response = post(Response.Status.CREATED, (Form)null, + final Response response = post(Response.Status.CREATED, (Form)null, "projects", getProjectIdOrPath(projectIdOrPath), "deploy_keys", keyId, "enable"); return (response.readEntity(DeployKey.class)); } diff --git a/src/main/java/org/gitlab4j/api/DeployTokensApi.java b/src/main/java/org/gitlab4j/api/DeployTokensApi.java index 214089f1a..f1f9295de 100644 --- a/src/main/java/org/gitlab4j/api/DeployTokensApi.java +++ b/src/main/java/org/gitlab4j/api/DeployTokensApi.java @@ -1,238 +1,318 @@ package org.gitlab4j.api; -import org.gitlab4j.api.models.DeployToken; - -import javax.ws.rs.core.Response; import java.util.Date; import java.util.List; import java.util.stream.Stream; +import jakarta.ws.rs.core.Response; +import org.gitlab4j.api.models.DeployToken; /** - * This class implements the client side API for the GitLab Deploy Tokens API calls. - * See https://docs.gitlab.com/ee/api/deploy_tokens.html - * - * Since GitLab 12.9 + * This class implements the client side API for the GitLab Deploy Tokens API calls. See + * https://docs.gitlab.com/ee/api/deploy_tokens.html * + *

Since GitLab 12.9 */ public class DeployTokensApi extends AbstractApi { - public DeployTokensApi(GitLabApi gitLabApi) { - super(gitLabApi); - } + public DeployTokensApi(final GitLabApi gitLabApi) { + super(gitLabApi); + } - /* ************************************************************************************************ - * Global Deploy Token API - */ - - /** - * Get a list of all deploy tokens across the GitLab instance. This endpoint requires admin access. - * - *

GitLab Endpoint: GET /deploy_tokens
- * - * @return a list of DeployToken - * @throws GitLabApiException if any exception occurs - */ - public List getDeployTokens() throws GitLabApiException { - return (getDeployTokens(getDefaultPerPage()).all()); - } + /* ************************************************************************************************ + * Global Deploy Token API + */ - /** - * Get a Pager of all deploy tokens across all projects of the GitLab instance. This method requires admin access. - * - *
GitLab Endpoint: GET /deploy_tokens
- * - * @param itemsPerPage the number of DeployToken instances that will be fetched per page - * @return a Pager of DeployToken - * @throws GitLabApiException if any exception occurs - */ - public Pager getDeployTokens(int itemsPerPage) throws GitLabApiException { - return (new Pager<>(this, DeployToken.class, itemsPerPage, null, "deploy_tokens")); - } + /** + * Get a list of all deploy tokens across the GitLab instance. This endpoint requires admin + * access. + * + *
GitLab Endpoint: GET /deploy_tokens
+ * + * @return a list of DeployToken + * @throws GitLabApiException if any exception occurs + */ + public List getDeployTokens() throws GitLabApiException { + return (getDeployTokens(getDefaultPerPage()).all()); + } - /** - * Get a Stream of all deploy tokens across all projects of the GitLab instance. This method requires admin access. - * - *
GitLab Endpoint: GET /deploy_tokens
- * - * @return a list of DeployToken - * @throws GitLabApiException if any exception occurs - */ - public Stream getDeployTokensStream() throws GitLabApiException { - return (getDeployTokens(getDefaultPerPage()).stream()); - } + /** + * Get a Pager of all deploy tokens across all projects of the GitLab instance. This method + * requires admin access. + * + *
GitLab Endpoint: GET /deploy_tokens
+ * + * @param itemsPerPage the number of DeployToken instances that will be fetched per page + * @return a Pager of DeployToken + * @throws GitLabApiException if any exception occurs + */ + public Pager getDeployTokens(final int itemsPerPage) throws GitLabApiException { + return (new Pager<>(this, DeployToken.class, itemsPerPage, null, "deploy_tokens")); + } - /* ************************************************************************************************ - * Projects Deploy Token API - */ - - /** - * Get a list of the deploy tokens for the specified project. This method requires admin access. - * - *
GitLab Endpoint: GET /projects/:id/deploy_tokens
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @return a list of DeployToken - * @throws GitLabApiException if any exception occurs - */ - public List getProjectDeployTokens(Object projectIdOrPath) throws GitLabApiException { - return (getProjectDeployTokens(projectIdOrPath, getDefaultPerPage()).all()); - } + /** + * Get a Stream of all deploy tokens across all projects of the GitLab instance. This method + * requires admin access. + * + *
GitLab Endpoint: GET /deploy_tokens
+ * + * @return a list of DeployToken + * @throws GitLabApiException if any exception occurs + */ + public Stream getDeployTokensStream() throws GitLabApiException { + return (getDeployTokens(getDefaultPerPage()).stream()); + } - /** - * Get a Pager of the deploy tokens for the specified project. This method requires admin access. - * - *
GitLab Endpoint: GET /projects/:id/deploy_tokens
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance@param projectId the ID of the project - * @param itemsPerPage the number of DeployToken instances that will be fetched per page - * @return a Pager of DeployToken - * @throws GitLabApiException if any exception occurs - */ - public Pager getProjectDeployTokens(Object projectIdOrPath, int itemsPerPage) throws GitLabApiException { - return (new Pager<>(this, DeployToken.class, itemsPerPage, null, - "projects", getProjectIdOrPath(projectIdOrPath), "deploy_tokens")); - } + /* ************************************************************************************************ + * Projects Deploy Token API + */ - /** - * Get a list of the deploy tokens for the specified project. This method requires admin access. - * - *
GitLab Endpoint: GET /projects/:id/deploy_tokens
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @return a list of DeployToken - * @throws GitLabApiException if any exception occurs - */ - public Stream getProjectDeployTokensStream(Object projectIdOrPath) throws GitLabApiException { - return (getProjectDeployTokens(projectIdOrPath, getDefaultPerPage()).stream()); - } + /** + * Get a list of the deploy tokens for the specified project. This method requires admin access. + * + *
GitLab Endpoint: GET /projects/:id/deploy_tokens
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @return a list of DeployToken + * @throws GitLabApiException if any exception occurs + */ + public List getProjectDeployTokens(final Object projectIdOrPath) + throws GitLabApiException { + return (getProjectDeployTokens(projectIdOrPath, getDefaultPerPage()).all()); + } - /** - * Creates a new deploy token for a project. - * - *
GitLab Endpoint: POST /projects/:id/deploy_tokens
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param name the new deploy token’s name, required - * @param expiresAt expiration date for the deploy token. Currently documented as not required but api fails if not provided. Does not expire if no value is provided. - * @param username the username for deploy token. Currently documented as not required but api fails if not provided. Default is gitlab+deploy-token-{n} - * @param scopes indicates the deploy token scopes. Must be at least one of {@link org.gitlab4j.api.Constants.DeployTokenScope}. - * @return an DeployToken instance with info on the added deploy token - * @throws GitLabApiException if any exception occurs - */ - public DeployToken addProjectDeployToken(Object projectIdOrPath, String name, Date expiresAt, String username, List scopes) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() - .withParam("name", name, true) - .withParam("expires_at", expiresAt, true) // Currently documented as not required but api fails if not provided - .withParam("username", username, true)// Currently documented as not required but api fails if not provided - .withParam("scopes", scopes, true); - Response response = post(Response.Status.CREATED, formData, - "projects", getProjectIdOrPath(projectIdOrPath), "deploy_tokens"); - return (response.readEntity(DeployToken.class)); - } + /** + * Get a Pager of the deploy tokens for the specified project. This method requires admin access. + * + *
GitLab Endpoint: GET /projects/:id/deploy_tokens
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance@param projectId the ID of the project + * @param itemsPerPage the number of DeployToken instances that will be fetched per page + * @return a Pager of DeployToken + * @throws GitLabApiException if any exception occurs + */ + public Pager getProjectDeployTokens( + final Object projectIdOrPath, final int itemsPerPage) throws GitLabApiException { + return (new Pager<>( + this, + DeployToken.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "deploy_tokens")); + } - /** - * Removes a deploy token from the group. - * - *
GitLab Endpoint: DELETE /projects/:id/deploy_tokens/:token_id
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param tokenId the ID of the deploy token to delete - * @throws GitLabApiException if any exception occurs - */ - public void deleteProjectDeployToken(Object projectIdOrPath, Long tokenId) throws GitLabApiException { - - if (tokenId == null) { - throw new RuntimeException("tokenId cannot be null"); - } - - delete(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), "deploy_tokens", tokenId); - } + /** + * Get a list of the deploy tokens for the specified project. This method requires admin access. + * + *
GitLab Endpoint: GET /projects/:id/deploy_tokens
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @return a list of DeployToken + * @throws GitLabApiException if any exception occurs + */ + public Stream getProjectDeployTokensStream(final Object projectIdOrPath) + throws GitLabApiException { + return (getProjectDeployTokens(projectIdOrPath, getDefaultPerPage()).stream()); + } - /* ************************************************************************************************ - * Groups Deploy Token API - */ - - /** - * Get a list of the deploy tokens for the specified group. This method requires admin access. - * - *
GitLab Endpoint: GET /groups/:id/deploy_tokens
- * - * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance - * @return a list of DeployToken - * @throws GitLabApiException if any exception occurs - */ - public List getGroupDeployTokens(Object groupIdOrPath) throws GitLabApiException { - return (getGroupDeployTokens(groupIdOrPath, getDefaultPerPage()).all()); - } + /** + * Creates a new deploy token for a project. + * + *
GitLab Endpoint: POST /projects/:id/deploy_tokens
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param name the new deploy token’s name, required + * @param expiresAt expiration date for the deploy token. Currently documented as not required but + * api fails if not provided. Does not expire if no value is provided. + * @param username the username for deploy token. Currently documented as not required but api + * fails if not provided. Default is gitlab+deploy-token-{n} + * @param scopes indicates the deploy token scopes. Must be at least one of {@link + * org.gitlab4j.api.Constants.DeployTokenScope}. + * @return an DeployToken instance with info on the added deploy token + * @throws GitLabApiException if any exception occurs + */ + public DeployToken addProjectDeployToken( + final Object projectIdOrPath, + final String name, + final Date expiresAt, + final String username, + final List scopes) + throws GitLabApiException { + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("name", name, true) + .withParam( + "expires_at", + expiresAt, + true) // Currently documented as not required but api fails if not provided + .withParam( + "username", + username, + true) // Currently documented as not required but api fails if not provided + .withParam("scopes", scopes, true); + final Response response = + post( + Response.Status.CREATED, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "deploy_tokens"); + return (response.readEntity(DeployToken.class)); + } - /** - * Get a Pager of the deploy tokens for the specified group. This method requires admin access. - * - *
GitLab Endpoint: GET /groups/:id/deploy_tokens
- * - * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance@param groupId the ID of the group - * @param itemsPerPage the number of DeployToken instances that will be fetched per page - * @return a Pager of DeployToken - * @throws GitLabApiException if any exception occurs - */ - public Pager getGroupDeployTokens(Object groupIdOrPath, int itemsPerPage) throws GitLabApiException { - return (new Pager<>(this, DeployToken.class, itemsPerPage, null, - "groups", getGroupIdOrPath(groupIdOrPath), "deploy_tokens")); - } + /** + * Removes a deploy token from the group. + * + *
GitLab Endpoint: DELETE /projects/:id/deploy_tokens/:token_id
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param tokenId the ID of the deploy token to delete + * @throws GitLabApiException if any exception occurs + */ + public void deleteProjectDeployToken(final Object projectIdOrPath, final Long tokenId) + throws GitLabApiException { - /** - * Get a list of the deploy tokens for the specified group. This method requires admin access. - * - *
GitLab Endpoint: GET /groups/:id/deploy_tokens
- * - * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance - * @return a list of DeployToken - * @throws GitLabApiException if any exception occurs - */ - public Stream getGroupDeployTokensStream(Object groupIdOrPath) throws GitLabApiException { - return (getGroupDeployTokens(groupIdOrPath, getDefaultPerPage()).stream()); + if (tokenId == null) { + throw new RuntimeException("tokenId cannot be null"); } - /** - * Creates a new deploy token for a group. - * - *
GitLab Endpoint: POST /groups/:id/deploy_tokens
- * - * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance - * @param name the new deploy token’s name, required - * @param expiresAt expiration date for the deploy token. Currently documented as not required but api fails if not provided. Does not expire if no value is provided. - * @param username the username for deploy token. Currently documented as not required but api fails if not provided. Default is gitlab+deploy-token-{n} - * @param scopes indicates the deploy token scopes. Must be at least one of {@link org.gitlab4j.api.Constants.DeployTokenScope}. - * @return an DeployToken instance with info on the added deploy token - * @throws GitLabApiException if any exception occurs - */ - public DeployToken addGroupDeployToken(Object groupIdOrPath, String name, Date expiresAt, String username, List scopes) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() - .withParam("name", name, true) - .withParam("expires_at", expiresAt, true) // Currently documented as not required but api fails if not provided - .withParam("username", username, true)// Currently documented as not required but api fails if not provided - .withParam("scopes", scopes, true); - Response response = post(Response.Status.CREATED, formData, - "groups", getGroupIdOrPath(groupIdOrPath), "deploy_tokens"); - return (response.readEntity(DeployToken.class)); - } + delete( + Response.Status.OK, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "deploy_tokens", + tokenId); + } + + /* ************************************************************************************************ + * Groups Deploy Token API + */ + + /** + * Get a list of the deploy tokens for the specified group. This method requires admin access. + * + *
GitLab Endpoint: GET /groups/:id/deploy_tokens
+ * + * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance + * @return a list of DeployToken + * @throws GitLabApiException if any exception occurs + */ + public List getGroupDeployTokens(final Object groupIdOrPath) + throws GitLabApiException { + return (getGroupDeployTokens(groupIdOrPath, getDefaultPerPage()).all()); + } + + /** + * Get a Pager of the deploy tokens for the specified group. This method requires admin access. + * + *
GitLab Endpoint: GET /groups/:id/deploy_tokens
+ * + * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group + * instance@param groupId the ID of the group + * @param itemsPerPage the number of DeployToken instances that will be fetched per page + * @return a Pager of DeployToken + * @throws GitLabApiException if any exception occurs + */ + public Pager getGroupDeployTokens(final Object groupIdOrPath, final int itemsPerPage) + throws GitLabApiException { + return (new Pager<>( + this, + DeployToken.class, + itemsPerPage, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "deploy_tokens")); + } + + /** + * Get a list of the deploy tokens for the specified group. This method requires admin access. + * + *
GitLab Endpoint: GET /groups/:id/deploy_tokens
+ * + * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance + * @return a list of DeployToken + * @throws GitLabApiException if any exception occurs + */ + public Stream getGroupDeployTokensStream(final Object groupIdOrPath) + throws GitLabApiException { + return (getGroupDeployTokens(groupIdOrPath, getDefaultPerPage()).stream()); + } + + /** + * Creates a new deploy token for a group. + * + *
GitLab Endpoint: POST /groups/:id/deploy_tokens
+ * + * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance + * @param name the new deploy token’s name, required + * @param expiresAt expiration date for the deploy token. Currently documented as not required but + * api fails if not provided. Does not expire if no value is provided. + * @param username the username for deploy token. Currently documented as not required but api + * fails if not provided. Default is gitlab+deploy-token-{n} + * @param scopes indicates the deploy token scopes. Must be at least one of {@link + * org.gitlab4j.api.Constants.DeployTokenScope}. + * @return an DeployToken instance with info on the added deploy token + * @throws GitLabApiException if any exception occurs + */ + public DeployToken addGroupDeployToken( + final Object groupIdOrPath, + final String name, + final Date expiresAt, + final String username, + final List scopes) + throws GitLabApiException { + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("name", name, true) + .withParam( + "expires_at", + expiresAt, + true) // Currently documented as not required but api fails if not provided + .withParam( + "username", + username, + true) // Currently documented as not required but api fails if not provided + .withParam("scopes", scopes, true); + final Response response = + post( + Response.Status.CREATED, + formData, + "groups", + getGroupIdOrPath(groupIdOrPath), + "deploy_tokens"); + return (response.readEntity(DeployToken.class)); + } + + /** + * Removes a deploy token from the group. + * + *
GitLab Endpoint: DELETE /groups/:id/deploy_tokens/:token_id
+ * + * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance + * @param tokenId the ID of the deploy token to delete + * @throws GitLabApiException if any exception occurs + */ + public void deleteGroupDeployToken(final Object groupIdOrPath, final Long tokenId) + throws GitLabApiException { - /** - * Removes a deploy token from the group. - * - *
GitLab Endpoint: DELETE /groups/:id/deploy_tokens/:token_id
- * - * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance - * @param tokenId the ID of the deploy token to delete - * @throws GitLabApiException if any exception occurs - */ - public void deleteGroupDeployToken(Object groupIdOrPath, Long tokenId) throws GitLabApiException { - - if (tokenId == null) { - throw new RuntimeException("tokenId cannot be null"); - } - - delete(Response.Status.OK, null, "groups", getGroupIdOrPath(groupIdOrPath), "deploy_tokens", tokenId); + if (tokenId == null) { + throw new RuntimeException("tokenId cannot be null"); } + delete( + Response.Status.OK, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "deploy_tokens", + tokenId); + } } diff --git a/src/main/java/org/gitlab4j/api/DeploymentsApi.java b/src/main/java/org/gitlab4j/api/DeploymentsApi.java index 299c7ce3d..1407dd4e4 100644 --- a/src/main/java/org/gitlab4j/api/DeploymentsApi.java +++ b/src/main/java/org/gitlab4j/api/DeploymentsApi.java @@ -3,238 +3,304 @@ import java.util.List; import java.util.Optional; import java.util.stream.Stream; - -import javax.ws.rs.core.Response; - +import jakarta.ws.rs.core.Response; import org.gitlab4j.api.models.Deployment; import org.gitlab4j.api.models.DeploymentFilter; import org.gitlab4j.api.models.MergeRequest; /** - * This class implements the client side API for the GitLab Deployments API calls. - * See https://docs.gitlab.com/ee/api/deployments.html - * + * This class implements the client side API for the GitLab Deployments API calls. See + * https://docs.gitlab.com/ee/api/deployments.html */ public class DeploymentsApi extends AbstractApi { - public DeploymentsApi(GitLabApi gitLabApi) { - super(gitLabApi); - } + public DeploymentsApi(final GitLabApi gitLabApi) { + super(gitLabApi); + } - /** - * Get a list of deployments for the specified project. - * - *
GitLab Endpoint: GET /projects/:id/deployments
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @return a list of Deployments - * @throws GitLabApiException if any exception occurs - */ - public List getProjectDeployments(Object projectIdOrPath) throws GitLabApiException { - return (getProjectDeployments(projectIdOrPath, null, getDefaultPerPage()).all()); - } + /** + * Get a list of deployments for the specified project. + * + *
GitLab Endpoint: GET /projects/:id/deployments
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @return a list of Deployments + * @throws GitLabApiException if any exception occurs + */ + public List getProjectDeployments(final Object projectIdOrPath) + throws GitLabApiException { + return (getProjectDeployments(projectIdOrPath, null, getDefaultPerPage()).all()); + } - /** - * Get a Pager of all deployments for the specified project. - * - *
GitLab Endpoint: GET /projects/:id/deployments
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param itemsPerPage the number of Deployments instances that will be fetched per page - * @return a Pager of Deployment - * @throws GitLabApiException if any exception occurs - */ - public Pager getProjectDeployments(Object projectIdOrPath, int itemsPerPage) throws GitLabApiException { - return (getProjectDeployments(projectIdOrPath, null, itemsPerPage)); - } + /** + * Get a Pager of all deployments for the specified project. + * + *
GitLab Endpoint: GET /projects/:id/deployments
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param itemsPerPage the number of Deployments instances that will be fetched per page + * @return a Pager of Deployment + * @throws GitLabApiException if any exception occurs + */ + public Pager getProjectDeployments( + final Object projectIdOrPath, final int itemsPerPage) throws GitLabApiException { + return (getProjectDeployments(projectIdOrPath, null, itemsPerPage)); + } - /** - * Get a Pager of all deployments for the specified project. - * - *
GitLab Endpoint: GET /projects/:id/deployments
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param filter {@link DeploymentFilter} a DeploymentFilter instance with the filter settings - * @return a Pager of Deployment - * @throws GitLabApiException if any exception occurs - */ - public Pager getProjectDeployments(Object projectIdOrPath, DeploymentFilter filter) throws GitLabApiException { - return (getProjectDeployments(projectIdOrPath, filter, getDefaultPerPage())); - } + /** + * Get a Pager of all deployments for the specified project. + * + *
GitLab Endpoint: GET /projects/:id/deployments
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param filter {@link DeploymentFilter} a DeploymentFilter instance with the filter settings + * @return a Pager of Deployment + * @throws GitLabApiException if any exception occurs + */ + public Pager getProjectDeployments( + final Object projectIdOrPath, final DeploymentFilter filter) throws GitLabApiException { + return (getProjectDeployments(projectIdOrPath, filter, getDefaultPerPage())); + } - /** - * Get a Pager of all deployments for the specified project. - * - *
GitLab Endpoint: GET /projects/:id/deployments
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param filter {@link DeploymentFilter} a DeploymentFilter instance with the filter settings - * @param itemsPerPage the number of Deployments instances that will be fetched per page - * @return a Pager of Deployment - * @throws GitLabApiException if any exception occurs - */ - public Pager getProjectDeployments(Object projectIdOrPath, DeploymentFilter filter, int itemsPerPage) throws GitLabApiException { - GitLabApiForm formData = (filter != null ? filter.getQueryParams() : new GitLabApiForm()); - return (new Pager(this, Deployment.class, itemsPerPage, formData.asMap(), - "projects", getProjectIdOrPath(projectIdOrPath), "deployments")); - } + /** + * Get a Pager of all deployments for the specified project. + * + *
GitLab Endpoint: GET /projects/:id/deployments
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param filter {@link DeploymentFilter} a DeploymentFilter instance with the filter settings + * @param itemsPerPage the number of Deployments instances that will be fetched per page + * @return a Pager of Deployment + * @throws GitLabApiException if any exception occurs + */ + public Pager getProjectDeployments( + final Object projectIdOrPath, final DeploymentFilter filter, final int itemsPerPage) + throws GitLabApiException { + final GitLabApiForm formData = (filter != null ? filter.getQueryParams() : new GitLabApiForm()); + return (new Pager( + this, + Deployment.class, + itemsPerPage, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "deployments")); + } - /** - * Get a Stream of all deployments for the specified project. - * - *
GitLab Endpoint: GET /projects/:id/deployments
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @return a list of Deployment - * @throws GitLabApiException if any exception occurs - */ - public Stream getProjectDeploymentsStream(Object projectIdOrPath) throws GitLabApiException { - return (getProjectDeployments(projectIdOrPath, null, getDefaultPerPage()).stream()); - } + /** + * Get a Stream of all deployments for the specified project. + * + *
GitLab Endpoint: GET /projects/:id/deployments
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @return a list of Deployment + * @throws GitLabApiException if any exception occurs + */ + public Stream getProjectDeploymentsStream(final Object projectIdOrPath) + throws GitLabApiException { + return (getProjectDeployments(projectIdOrPath, null, getDefaultPerPage()).stream()); + } - /** - * Get a Stream of all deployments for the specified project. - * - *
GitLab Endpoint: GET /projects/:id/deployments
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param filter {@link DeploymentFilter} a DeploymentFilter instance with the filter settings - * @return a list of Deployment - * @throws GitLabApiException if any exception occurs - */ - public Stream getProjectDeploymentsStream(Object projectIdOrPath, DeploymentFilter filter) throws GitLabApiException { - return (getProjectDeployments(projectIdOrPath, filter, getDefaultPerPage()).stream()); - } + /** + * Get a Stream of all deployments for the specified project. + * + *
GitLab Endpoint: GET /projects/:id/deployments
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param filter {@link DeploymentFilter} a DeploymentFilter instance with the filter settings + * @return a list of Deployment + * @throws GitLabApiException if any exception occurs + */ + public Stream getProjectDeploymentsStream( + final Object projectIdOrPath, final DeploymentFilter filter) throws GitLabApiException { + return (getProjectDeployments(projectIdOrPath, filter, getDefaultPerPage()).stream()); + } - /** - * Get a specific deployment. - * - *
GitLab Endpoint: GET /projects/:id/deployments/:deployment_id
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param deploymentId the ID of a project's deployment - * @return the specified Deployment instance - * @throws GitLabApiException if any exception occurs - */ - public Deployment getDeployment(Object projectIdOrPath, Long deploymentId) throws GitLabApiException { - Response response = get(Response.Status.OK, getDefaultPerPageParam(), - "projects", getProjectIdOrPath(projectIdOrPath), "deployments", deploymentId); - return (response.readEntity(Deployment.class)); - } + /** + * Get a specific deployment. + * + *
GitLab Endpoint: GET /projects/:id/deployments/:deployment_id
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param deploymentId the ID of a project's deployment + * @return the specified Deployment instance + * @throws GitLabApiException if any exception occurs + */ + public Deployment getDeployment(final Object projectIdOrPath, final Long deploymentId) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getDefaultPerPageParam(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "deployments", + deploymentId); + return (response.readEntity(Deployment.class)); + } - /** - * Get a specific deployment as an Optional instance. - * - *
GitLab Endpoint: GET /projects/:id/deployments/:deployment_id
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param deploymentId the ID of a project's deployment - * @return the specified Deployment as an Optional instance - */ - public Optional getOptionalDeployment(Object projectIdOrPath, Long deploymentId) { - try { - return (Optional.ofNullable(getDeployment(projectIdOrPath, deploymentId))); - } catch (GitLabApiException glae) { - return (GitLabApi.createOptionalFromException(glae)); - } + /** + * Get a specific deployment as an Optional instance. + * + *
GitLab Endpoint: GET /projects/:id/deployments/:deployment_id
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param deploymentId the ID of a project's deployment + * @return the specified Deployment as an Optional instance + */ + public Optional getOptionalDeployment( + final Object projectIdOrPath, final Long deploymentId) { + try { + return (Optional.ofNullable(getDeployment(projectIdOrPath, deploymentId))); + } catch (final GitLabApiException glae) { + return (GitLabApi.createOptionalFromException(glae)); } + } - /** - * Creates a new deployment for a project. - * - *
GitLab Endpoint: POST /projects/:id/deployments
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param environment The name of the environment to create the deployment for, required - * @param sha The SHA of the commit that is deployed, required - * @param ref The name of the branch or tag that is deployed, required - * @param tag A boolean that indicates if the deployed ref is a tag (true) or not (false), required - * @param status The status to filter deployments by, required - * @return a Deployment instance with info on the added deployment - * @throws GitLabApiException if any exception occurs - */ - public Deployment addDeployment(Object projectIdOrPath, String environment, String sha, String ref, Boolean tag, DeploymentStatus status) throws GitLabApiException { - - GitLabApiForm formData = new GitLabApiForm() - .withParam("environment", environment, true) - .withParam("sha", sha, true) - .withParam("ref", ref, true) - .withParam("tag", tag, true) - .withParam("status", status, true); - - Response response = post(Response.Status.CREATED, formData, - "projects", getProjectIdOrPath(projectIdOrPath), "deployments"); - return (response.readEntity(Deployment.class)); - } + /** + * Creates a new deployment for a project. + * + *
GitLab Endpoint: POST /projects/:id/deployments
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param environment The name of the environment to create the deployment for, required + * @param sha The SHA of the commit that is deployed, required + * @param ref The name of the branch or tag that is deployed, required + * @param tag A boolean that indicates if the deployed ref is a tag (true) or not (false), + * required + * @param status The status to filter deployments by, required + * @return a Deployment instance with info on the added deployment + * @throws GitLabApiException if any exception occurs + */ + public Deployment addDeployment( + final Object projectIdOrPath, + final String environment, + final String sha, + final String ref, + final Boolean tag, + final DeploymentStatus status) + throws GitLabApiException { - /** - * Updates an existing project deploy key. - * - *
GitLab Endpoint: PUT /projects/:id/deployments/:key_id
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param deploymentId The ID of the deployment to update, required - * @param status The new status of the deployment, required - * @return an updated Deployment instance - * @throws GitLabApiException if any exception occurs - */ - public Deployment updateDeployment(Object projectIdOrPath, Long deploymentId, DeploymentStatus status) throws GitLabApiException { - - if (deploymentId == null) { - throw new RuntimeException("deploymentId cannot be null"); - } - - final Deployment deployment = new Deployment(); - deployment.setStatus(status); - final Response response = put(Response.Status.OK, deployment, - "projects", getProjectIdOrPath(projectIdOrPath), "deployments", deploymentId); - - return (response.readEntity(Deployment.class)); - } + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("environment", environment, true) + .withParam("sha", sha, true) + .withParam("ref", ref, true) + .withParam("tag", tag, true) + .withParam("status", status, true); - /** - * Get a list of Merge Requests shipped with a given deployment. - * - *
GitLab Endpoint: GET /projects/:id/deployments/:deployment_id/merge_requests
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param deploymentId The ID of the deployment to update, required - * @return a list containing the MergeRequest instances shipped with a given deployment - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public List getMergeRequests(Object projectIdOrPath, Long deploymentId) throws GitLabApiException { - return (getMergeRequests(projectIdOrPath, deploymentId, getDefaultPerPage()).all()); - } + final Response response = + post( + Response.Status.CREATED, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "deployments"); + return (response.readEntity(Deployment.class)); + } - /** - * Get a Pager of Merge Requests shipped with a given deployment. - * - *
GitLab Endpoint: GET /projects/:id/deployments/:deployment_id/merge_requests
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param deploymentId The ID of the deployment to update, required - * @param itemsPerPage the number of Commit instances that will be fetched per page - * @return a Pager containing the MergeRequest instances shipped with a given deployment - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Pager getMergeRequests(Object projectIdOrPath, Long deploymentId, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, MergeRequest.class, itemsPerPage, null, - "projects", getProjectIdOrPath(projectIdOrPath), "deployments", deploymentId, "merge_requests")); - } + /** + * Updates an existing project deploy key. + * + *
GitLab Endpoint: PUT /projects/:id/deployments/:key_id
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param deploymentId The ID of the deployment to update, required + * @param status The new status of the deployment, required + * @return an updated Deployment instance + * @throws GitLabApiException if any exception occurs + */ + public Deployment updateDeployment( + final Object projectIdOrPath, final Long deploymentId, final DeploymentStatus status) + throws GitLabApiException { - /** - * Get a Stream of Merge Requests shipped with a given deployment. - * - *
GitLab Endpoint: GET /projects/:id/deployments/:deployment_id/merge_requests
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param deploymentId The ID of the deployment to update, required - * @return a Stream containing the MergeRequest instances shipped with a given deployment - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public Stream getMergeRequestsStream(Object projectIdOrPath, Long deploymentId) throws GitLabApiException { - return (getMergeRequests(projectIdOrPath, deploymentId, getDefaultPerPage()).stream()); + if (deploymentId == null) { + throw new RuntimeException("deploymentId cannot be null"); } + final Deployment deployment = new Deployment(); + deployment.setStatus(status); + final Response response = + put( + Response.Status.OK, + deployment, + "projects", + getProjectIdOrPath(projectIdOrPath), + "deployments", + deploymentId); + + return (response.readEntity(Deployment.class)); + } + + /** + * Get a list of Merge Requests shipped with a given deployment. + * + *
GitLab Endpoint: GET /projects/:id/deployments/:deployment_id/merge_requests
+   * 
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param deploymentId The ID of the deployment to update, required + * @return a list containing the MergeRequest instances shipped with a given deployment + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public List getMergeRequests(final Object projectIdOrPath, final Long deploymentId) + throws GitLabApiException { + return (getMergeRequests(projectIdOrPath, deploymentId, getDefaultPerPage()).all()); + } + + /** + * Get a Pager of Merge Requests shipped with a given deployment. + * + *
GitLab Endpoint: GET /projects/:id/deployments/:deployment_id/merge_requests
+   * 
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param deploymentId The ID of the deployment to update, required + * @param itemsPerPage the number of Commit instances that will be fetched per page + * @return a Pager containing the MergeRequest instances shipped with a given deployment + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Pager getMergeRequests( + final Object projectIdOrPath, final Long deploymentId, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, + MergeRequest.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "deployments", + deploymentId, + "merge_requests")); + } + /** + * Get a Stream of Merge Requests shipped with a given deployment. + * + *
GitLab Endpoint: GET /projects/:id/deployments/:deployment_id/merge_requests
+   * 
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param deploymentId The ID of the deployment to update, required + * @return a Stream containing the MergeRequest instances shipped with a given deployment + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public Stream getMergeRequestsStream( + final Object projectIdOrPath, final Long deploymentId) throws GitLabApiException { + return (getMergeRequests(projectIdOrPath, deploymentId, getDefaultPerPage()).stream()); + } } diff --git a/src/main/java/org/gitlab4j/api/DiscussionsApi.java b/src/main/java/org/gitlab4j/api/DiscussionsApi.java index 687d5a836..c1b10fc72 100644 --- a/src/main/java/org/gitlab4j/api/DiscussionsApi.java +++ b/src/main/java/org/gitlab4j/api/DiscussionsApi.java @@ -4,754 +4,1169 @@ import java.util.List; import java.util.Optional; import java.util.stream.Stream; - -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; - +import jakarta.ws.rs.core.GenericType; +import jakarta.ws.rs.core.Response; import org.gitlab4j.api.models.Discussion; import org.gitlab4j.api.models.Note; import org.gitlab4j.api.models.Position; /** - * This class implements the client side API for the GitLab Discussions API. - * See Discussions API at GitLab for more information. + * This class implements the client side API for the GitLab Discussions API. See Discussions API at GitLab for more + * information. */ public class DiscussionsApi extends AbstractApi { - public DiscussionsApi(GitLabApi gitLabApi) { - super(gitLabApi); - } + public DiscussionsApi(final GitLabApi gitLabApi) { + super(gitLabApi); + } - /** - * Get a list of all discussions for the specified issue. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the internal ID of the issue - * @return a list containing all the discussions for the specified issue - * @throws GitLabApiException if any exception occurs during execution - */ - public List getIssueDiscussions(Object projectIdOrPath, Long issueIid) throws GitLabApiException { - Pager pager = getIssueDiscussionsPager(projectIdOrPath, issueIid, getDefaultPerPage()); - return (pager.all()); - } + /** + * Get a list of all discussions for the specified issue. + * + *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/discussions
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param issueIid the internal ID of the issue + * @return a list containing all the discussions for the specified issue + * @throws GitLabApiException if any exception occurs during execution + */ + public List getIssueDiscussions(final Object projectIdOrPath, final Long issueIid) + throws GitLabApiException { + final Pager pager = + getIssueDiscussionsPager(projectIdOrPath, issueIid, getDefaultPerPage()); + return (pager.all()); + } - /** - * Get a list of discussions for the specified issue. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the internal ID of the issue - * @param maxItems the maximum number of Discussion instances to get, if < 1 will fetch all Discussion instances for the issue - * @return a list containing the discussions for the specified issue - * @throws GitLabApiException if any exception occurs during execution - */ - public List getIssueDiscussions(Object projectIdOrPath, Long issueIid, int maxItems) throws GitLabApiException { - if (maxItems < 1) { - return (getIssueDiscussions(projectIdOrPath, issueIid)); - } else { - Response response = get(Response.Status.OK, getPerPageQueryParam(maxItems), - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "discussions"); - return (response.readEntity(new GenericType>() {})); - } + /** + * Get a list of discussions for the specified issue. + * + *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/discussions
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param issueIid the internal ID of the issue + * @param maxItems the maximum number of Discussion instances to get, if < 1 will fetch all + * Discussion instances for the issue + * @return a list containing the discussions for the specified issue + * @throws GitLabApiException if any exception occurs during execution + */ + public List getIssueDiscussions( + final Object projectIdOrPath, final Long issueIid, final int maxItems) + throws GitLabApiException { + if (maxItems < 1) { + return (getIssueDiscussions(projectIdOrPath, issueIid)); + } else { + final Response response = + get( + Response.Status.OK, + getPerPageQueryParam(maxItems), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "discussions"); + return (response.readEntity(new GenericType>() {})); } + } - /** - * Get a Pager of Discussion instances for the specified issue. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the internal ID of the issue - * @param itemsPerPage the number of Discussion instances that will be fetched per page - * @return a Pager containing the Discussion instances for the specified issue - * @throws GitLabApiException if any exception occurs during execution - */ - public Pager getIssueDiscussionsPager(Object projectIdOrPath, Long issueIid, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, Discussion.class, itemsPerPage, null, - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "discussions")); - } + /** + * Get a Pager of Discussion instances for the specified issue. + * + *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/discussions
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param issueIid the internal ID of the issue + * @param itemsPerPage the number of Discussion instances that will be fetched per page + * @return a Pager containing the Discussion instances for the specified issue + * @throws GitLabApiException if any exception occurs during execution + */ + public Pager getIssueDiscussionsPager( + final Object projectIdOrPath, final Long issueIid, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, + Discussion.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "discussions")); + } - /** - * Get a Stream of Discussion instances for the specified issue. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the internal ID of the issue - * @return a Stream instance containing the Discussion instances for the specified issue - * @throws GitLabApiException if any exception occurs during execution - */ - public Stream getIssueDiscussionsStream(Object projectIdOrPath, Long issueIid) throws GitLabApiException { - Pager pager = getIssueDiscussionsPager(projectIdOrPath, issueIid, getDefaultPerPage()); - return (pager.stream()); - } + /** + * Get a Stream of Discussion instances for the specified issue. + * + *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/discussions
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param issueIid the internal ID of the issue + * @return a Stream instance containing the Discussion instances for the specified issue + * @throws GitLabApiException if any exception occurs during execution + */ + public Stream getIssueDiscussionsStream( + final Object projectIdOrPath, final Long issueIid) throws GitLabApiException { + final Pager pager = + getIssueDiscussionsPager(projectIdOrPath, issueIid, getDefaultPerPage()); + return (pager.stream()); + } - /** - * Get a list of all discussions for the specified snippet. - * - *
GitLab Endpoint: GET /projects/:id/snippets/:snippet_id/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param snippetId the ID of the snippet - * @return a list containing all the discussions for the specified snippet - * @throws GitLabApiException if any exception occurs during execution - */ - public List getSnippetDiscussions(Object projectIdOrPath, Long snippetId) throws GitLabApiException { - Pager pager = getSnippetDiscussionsPager(projectIdOrPath, snippetId, getDefaultPerPage()); - return (pager.all()); - } + /** + * Get a list of all discussions for the specified snippet. + * + *
GitLab Endpoint: GET /projects/:id/snippets/:snippet_id/discussions
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param snippetId the ID of the snippet + * @return a list containing all the discussions for the specified snippet + * @throws GitLabApiException if any exception occurs during execution + */ + public List getSnippetDiscussions(final Object projectIdOrPath, final Long snippetId) + throws GitLabApiException { + final Pager pager = + getSnippetDiscussionsPager(projectIdOrPath, snippetId, getDefaultPerPage()); + return (pager.all()); + } - /** - * Get a list of discussions for the specified snippet. - * - *
GitLab Endpoint: GET /projects/:id/snippets/:snippet_id/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param snippetId the ID of the snippet - * @param maxItems the maximum number of Discussion instances to get, if < 1 will fetch all Discussion instances for the snippet - * @return a list containing the discussions for the specified snippet - * @throws GitLabApiException if any exception occurs during execution - */ - public List getSnippetDiscussions(Object projectIdOrPath, Long snippetId, int maxItems) throws GitLabApiException { - if (maxItems < 1) { - return (getSnippetDiscussions(projectIdOrPath, snippetId)); - } else { - Response response = get(Response.Status.OK, getPerPageQueryParam(maxItems), - "projects", getProjectIdOrPath(projectIdOrPath), "snippets", snippetId, "discussions"); - return (response.readEntity(new GenericType>() {})); - } + /** + * Get a list of discussions for the specified snippet. + * + *
GitLab Endpoint: GET /projects/:id/snippets/:snippet_id/discussions
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param snippetId the ID of the snippet + * @param maxItems the maximum number of Discussion instances to get, if < 1 will fetch all + * Discussion instances for the snippet + * @return a list containing the discussions for the specified snippet + * @throws GitLabApiException if any exception occurs during execution + */ + public List getSnippetDiscussions( + final Object projectIdOrPath, final Long snippetId, final int maxItems) + throws GitLabApiException { + if (maxItems < 1) { + return (getSnippetDiscussions(projectIdOrPath, snippetId)); + } else { + final Response response = + get( + Response.Status.OK, + getPerPageQueryParam(maxItems), + "projects", + getProjectIdOrPath(projectIdOrPath), + "snippets", + snippetId, + "discussions"); + return (response.readEntity(new GenericType>() {})); } + } - /** - * Get a Pager of Discussion instances for the specified snippet. - * - *
GitLab Endpoint: GET /projects/:id/snippets/:snippet_id/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param snippetId the ID of the snippet - * @param itemsPerPage the number of Discussion instances that will be fetched per page - * @return a Pager containing the Discussion instances for the specified snippet - * @throws GitLabApiException if any exception occurs during execution - */ - public Pager getSnippetDiscussionsPager(Object projectIdOrPath, Long snippetId, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, Discussion.class, itemsPerPage, null, - "projects", getProjectIdOrPath(projectIdOrPath), "snippets", snippetId, "discussions")); - } + /** + * Get a Pager of Discussion instances for the specified snippet. + * + *
GitLab Endpoint: GET /projects/:id/snippets/:snippet_id/discussions
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param snippetId the ID of the snippet + * @param itemsPerPage the number of Discussion instances that will be fetched per page + * @return a Pager containing the Discussion instances for the specified snippet + * @throws GitLabApiException if any exception occurs during execution + */ + public Pager getSnippetDiscussionsPager( + final Object projectIdOrPath, final Long snippetId, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, + Discussion.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "snippets", + snippetId, + "discussions")); + } - /** - * Get a Stream of Discussion instances for the specified snippet. - * - *
GitLab Endpoint: GET /projects/:id/snippets/:snippet_id/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param snippetId the ID of the snippet - * @return a Stream instance containing the Discussion instances for the specified snippet - * @throws GitLabApiException if any exception occurs during execution - */ - public Stream getSnippetDiscussionsStream(Object projectIdOrPath, Long snippetId) throws GitLabApiException { - Pager pager = getSnippetDiscussionsPager(projectIdOrPath, snippetId, getDefaultPerPage()); - return (pager.stream()); - } + /** + * Get a Stream of Discussion instances for the specified snippet. + * + *
GitLab Endpoint: GET /projects/:id/snippets/:snippet_id/discussions
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param snippetId the ID of the snippet + * @return a Stream instance containing the Discussion instances for the specified snippet + * @throws GitLabApiException if any exception occurs during execution + */ + public Stream getSnippetDiscussionsStream( + final Object projectIdOrPath, final Long snippetId) throws GitLabApiException { + final Pager pager = + getSnippetDiscussionsPager(projectIdOrPath, snippetId, getDefaultPerPage()); + return (pager.stream()); + } + /** + * Get a list of all discussions for the specified epic. + * + *
GitLab Endpoint: GET /projects/:id/epics/:epic_id/discussions
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param epicId the internal ID of the epic + * @return a list containing all the discussions for the specified epic + * @throws GitLabApiException if any exception occurs during execution + */ + public List getEpicDiscussions(final Object projectIdOrPath, final Long epicId) + throws GitLabApiException { + final Pager pager = + getEpicDiscussionsPager(projectIdOrPath, epicId, getDefaultPerPage()); + return (pager.all()); + } - /** - * Get a list of all discussions for the specified epic. - * - *
GitLab Endpoint: GET /projects/:id/epics/:epic_id/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param epicId the internal ID of the epic - * @return a list containing all the discussions for the specified epic - * @throws GitLabApiException if any exception occurs during execution - */ - public List getEpicDiscussions(Object projectIdOrPath, Long epicId) throws GitLabApiException { - Pager pager = getEpicDiscussionsPager(projectIdOrPath, epicId, getDefaultPerPage()); - return (pager.all()); + /** + * Get a list of discussions for the specified epic. + * + *
GitLab Endpoint: GET /projects/:id/epics/:epic_id/discussions
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param epicId the internal ID of the epic + * @param maxItems the maximum number of Discussion instances to get, if < 1 will fetch all + * Discussion instances for the epic + * @return a list containing the discussions for the specified epic + * @throws GitLabApiException if any exception occurs during execution + */ + public List getEpicDiscussions( + final Object projectIdOrPath, final Long epicId, final int maxItems) + throws GitLabApiException { + if (maxItems < 1) { + return (getEpicDiscussions(projectIdOrPath, epicId)); + } else { + final Response response = + get( + Response.Status.OK, + getPerPageQueryParam(maxItems), + "projects", + getProjectIdOrPath(projectIdOrPath), + "epics", + epicId, + "discussions"); + return (response.readEntity(new GenericType>() {})); } + } - /** - * Get a list of discussions for the specified epic. - * - *
GitLab Endpoint: GET /projects/:id/epics/:epic_id/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param epicId the internal ID of the epic - * @param maxItems the maximum number of Discussion instances to get, if < 1 will fetch all Discussion instances for the epic - * @return a list containing the discussions for the specified epic - * @throws GitLabApiException if any exception occurs during execution - */ - public List getEpicDiscussions(Object projectIdOrPath, Long epicId, int maxItems) throws GitLabApiException { - if (maxItems < 1) { - return (getEpicDiscussions(projectIdOrPath, epicId)); - } else { - Response response = get(Response.Status.OK, getPerPageQueryParam(maxItems), - "projects", getProjectIdOrPath(projectIdOrPath), "epics", epicId, "discussions"); - return (response.readEntity(new GenericType>() {})); - } - } + /** + * Get a Pager of Discussion instances for the specified epic. + * + *
GitLab Endpoint: GET /projects/:id/epics/:epic_id/discussions
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param epicId the internal ID of the epic + * @param itemsPerPage the number of Discussion instances that will be fetched per page + * @return a Pager containing the Discussion instances for the specified epic + * @throws GitLabApiException if any exception occurs during execution + */ + public Pager getEpicDiscussionsPager( + final Object projectIdOrPath, final Long epicId, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, + Discussion.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "epics", + epicId, + "discussions")); + } - /** - * Get a Pager of Discussion instances for the specified epic. - * - *
GitLab Endpoint: GET /projects/:id/epics/:epic_id/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param epicId the internal ID of the epic - * @param itemsPerPage the number of Discussion instances that will be fetched per page - * @return a Pager containing the Discussion instances for the specified epic - * @throws GitLabApiException if any exception occurs during execution - */ - public Pager getEpicDiscussionsPager(Object projectIdOrPath, Long epicId, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, Discussion.class, itemsPerPage, null, - "projects", getProjectIdOrPath(projectIdOrPath), "epics", epicId, "discussions")); - } + /** + * Get a Stream of Discussion instances for the specified epic. + * + *
GitLab Endpoint: GET /projects/:id/epics/:epic_id/discussions
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param epicId the internal ID of the epic + * @return a Stream instance containing the Discussion instances for the specified epic + * @throws GitLabApiException if any exception occurs during execution + */ + public Stream getEpicDiscussionsStream( + final Object projectIdOrPath, final Long epicId) throws GitLabApiException { + final Pager pager = + getEpicDiscussionsPager(projectIdOrPath, epicId, getDefaultPerPage()); + return (pager.stream()); + } - /** - * Get a Stream of Discussion instances for the specified epic. - * - *
GitLab Endpoint: GET /projects/:id/epics/:epic_id/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param epicId the internal ID of the epic - * @return a Stream instance containing the Discussion instances for the specified epic - * @throws GitLabApiException if any exception occurs during execution - */ - public Stream getEpicDiscussionsStream(Object projectIdOrPath, Long epicId) throws GitLabApiException { - Pager pager = getEpicDiscussionsPager(projectIdOrPath, epicId, getDefaultPerPage()); - return (pager.stream()); - } + /** + * Get a list of all discussions for the specified merge request. + * + *
+   * GitLab Endpoint: GET /projects/:id/merge_requests/:merge_request_iid/discussions
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param mergeRequestIid the internal ID of the merge request + * @return a list containing all the discussions for the specified merge request + * @throws GitLabApiException if any exception occurs during execution + */ + public List getMergeRequestDiscussions( + final Object projectIdOrPath, final Long mergeRequestIid) throws GitLabApiException { + final Pager pager = + getMergeRequestDiscussionsPager(projectIdOrPath, mergeRequestIid, getDefaultPerPage()); + return (pager.all()); + } - /** - * Get a list of all discussions for the specified merge request. - * - *
GitLab Endpoint: GET /projects/:id/merge_requests/:merge_request_iid/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param mergeRequestIid the internal ID of the merge request - * @return a list containing all the discussions for the specified merge request - * @throws GitLabApiException if any exception occurs during execution - */ - public List getMergeRequestDiscussions(Object projectIdOrPath, Long mergeRequestIid) throws GitLabApiException { - Pager pager = getMergeRequestDiscussionsPager(projectIdOrPath, mergeRequestIid, getDefaultPerPage()); - return (pager.all()); + /** + * Get a list of discussions for the specified merge request. + * + *
+   * GitLab Endpoint: GET /projects/:id/merge_requests/:merge_request_iid/discussions
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param mergeRequestIid the internal ID of the merge request + * @param maxItems the maximum number of Discussion instances to get, if < 1 will fetch all + * Discussion instances for the merge request + * @return a list containing the discussions for the specified merge request + * @throws GitLabApiException if any exception occurs during execution + */ + public List getMergeRequestDiscussions( + final Object projectIdOrPath, final Long mergeRequestIid, final int maxItems) + throws GitLabApiException { + if (maxItems < 1) { + return (getMergeRequestDiscussions(projectIdOrPath, mergeRequestIid)); + } else { + final Response response = + get( + Response.Status.OK, + getPerPageQueryParam(maxItems), + "projects", + getProjectIdOrPath(projectIdOrPath), + "merge_requests", + mergeRequestIid, + "discussions"); + return (response.readEntity(new GenericType>() {})); } + } - /** - * Get a list of discussions for the specified merge request. - * - *
GitLab Endpoint: GET /projects/:id/merge_requests/:merge_request_iid/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param mergeRequestIid the internal ID of the merge request - * @param maxItems the maximum number of Discussion instances to get, if < 1 will fetch all Discussion instances for the merge request - * @return a list containing the discussions for the specified merge request - * @throws GitLabApiException if any exception occurs during execution - */ - public List getMergeRequestDiscussions(Object projectIdOrPath, Long mergeRequestIid, int maxItems) throws GitLabApiException { - if (maxItems < 1) { - return (getMergeRequestDiscussions(projectIdOrPath, mergeRequestIid)); - } else { - Response response = get(Response.Status.OK, getPerPageQueryParam(maxItems), - "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "discussions"); - return (response.readEntity(new GenericType>() {})); - } - } + /** + * Get a Pager of Discussion instances for the specified merge request. + * + *
+   * GitLab Endpoint: GET /projects/:id/merge_requests/:merge_request_iid/discussions
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param mergeRequestIid the internal ID of the merge request + * @param itemsPerPage the number of Discussion instances that will be fetched per page + * @return a Pager containing the Discussion instances for the specified merge request + * @throws GitLabApiException if any exception occurs during execution + */ + public Pager getMergeRequestDiscussionsPager( + final Object projectIdOrPath, final Long mergeRequestIid, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, + Discussion.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "merge_requests", + mergeRequestIid, + "discussions")); + } - /** - * Get a Pager of Discussion instances for the specified merge request. - * - *
GitLab Endpoint: GET /projects/:id/merge_requests/:merge_request_iid/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param mergeRequestIid the internal ID of the merge request - * @param itemsPerPage the number of Discussion instances that will be fetched per page - * @return a Pager containing the Discussion instances for the specified merge request - * @throws GitLabApiException if any exception occurs during execution - */ - public Pager getMergeRequestDiscussionsPager(Object projectIdOrPath, Long mergeRequestIid, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, Discussion.class, itemsPerPage, null, - "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "discussions")); - } + /** + * Get a Stream of Discussion instances for the specified merge request. + * + *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/discussions
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param mergeRequestIid the internal ID of the merge request + * @return a Stream instance containing the Discussion instances for the specified issue + * @throws GitLabApiException if any exception occurs during execution + */ + public Stream getMergeRequestDiscussionsStream( + final Object projectIdOrPath, final Long mergeRequestIid) throws GitLabApiException { + final Pager pager = + getMergeRequestDiscussionsPager(projectIdOrPath, mergeRequestIid, getDefaultPerPage()); + return (pager.stream()); + } - /** - * Get a Stream of Discussion instances for the specified merge request. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param mergeRequestIid the internal ID of the merge request - * @return a Stream instance containing the Discussion instances for the specified issue - * @throws GitLabApiException if any exception occurs during execution - */ - public Stream getMergeRequestDiscussionsStream(Object projectIdOrPath, Long mergeRequestIid) throws GitLabApiException { - Pager pager = getMergeRequestDiscussionsPager(projectIdOrPath, mergeRequestIid, getDefaultPerPage()); - return (pager.stream()); - } + /** + * Creates a new discussion to a single project merge request. This is similar to creating a note + * but other comments (replies) can be added to it later. + * + *
+   * GitLab Endpoint: POST /projects/:id/merge_requests/:merge_request_iid/discussions
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param mergeRequestIid mergeRequestIid the internal ID of the merge request + * @param body the content of a discussion + * @param createdAt date the discussion was created (requires admin or project/group owner rights) + * @param positionHash position when creating a diff note + * @param position a Position instance holding the position attributes + * @return a Discussion instance containing the newly created discussion + * @throws GitLabApiException if any exception occurs during execution + */ + public Discussion createMergeRequestDiscussion( + final Object projectIdOrPath, + final Long mergeRequestIid, + final String body, + final Date createdAt, + final String positionHash, + final Position position) + throws GitLabApiException { - /** - * Creates a new discussion to a single project merge request. This is similar to creating - * a note but other comments (replies) can be added to it later. - * - *
GitLab Endpoint: POST /projects/:id/merge_requests/:merge_request_iid/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param mergeRequestIid mergeRequestIid the internal ID of the merge request - * @param body the content of a discussion - * @param createdAt date the discussion was created (requires admin or project/group owner rights) - * @param positionHash position when creating a diff note - * @param position a Position instance holding the position attributes - * @return a Discussion instance containing the newly created discussion - * @throws GitLabApiException if any exception occurs during execution - */ - public Discussion createMergeRequestDiscussion(Object projectIdOrPath, Long mergeRequestIid, - String body, Date createdAt, String positionHash, Position position) throws GitLabApiException { - - GitLabApiForm formData = new GitLabApiForm() - .withParam("body", body, true) - .withParam("created_at", createdAt) - .withParam("position", positionHash); - - if (position != null) { - formData.withParam("position[base_sha]", position.getBaseSha(), true) - .withParam("position[start_sha]", position.getStartSha(), true) - .withParam("position[head_sha]", position.getHeadSha(), true) - .withParam("position[position_type]", position.getPositionType(), true) - .withParam("position[new_path]", position.getNewPath()) - .withParam("position[new_line]", position.getNewLine()) - .withParam("position[old_path]", position.getOldPath()) - .withParam("position[old_line]", position.getOldLine()) - .withParam("position[width]", position.getWidth()) - .withParam("position[height]", position.getHeight()) - .withParam("position[x]", position.getX()) - .withParam("position[y]", position.getY()); - } - - Response response = post(Response.Status.CREATED, formData, - "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "discussions"); - return (response.readEntity(Discussion.class)); - } + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("body", body, true) + .withParam("created_at", createdAt) + .withParam("position", positionHash); - /** - * Resolve or unresolve whole discussion of a merge request. - * - *
GitLab Endpoint: PUT /projects/:id/merge_requests/:merge_request_iid/discussions/:discussion_id
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param mergeRequestIid mergeRequestIid the internal ID of the merge request - * @param discussionId the ID of a discussion - * @param resolved resolve/unresolve the discussion - * @return the updated DIscussion instance - * @throws GitLabApiException if any exception occurs during execution - */ - public Discussion resolveMergeRequestDiscussion(Object projectIdOrPath, Long mergeRequestIid, - String discussionId, Boolean resolved) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm().withParam("resolved", resolved, true); - Response response = put(Response.Status.OK, formData.asMap(), - "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "discussions", discussionId); - return (response.readEntity(Discussion.class)); + if (position != null) { + formData + .withParam("position[base_sha]", position.getBaseSha(), true) + .withParam("position[start_sha]", position.getStartSha(), true) + .withParam("position[head_sha]", position.getHeadSha(), true) + .withParam("position[position_type]", position.getPositionType(), true) + .withParam("position[new_path]", position.getNewPath()) + .withParam("position[new_line]", position.getNewLine()) + .withParam("position[old_path]", position.getOldPath()) + .withParam("position[old_line]", position.getOldLine()) + .withParam("position[width]", position.getWidth()) + .withParam("position[height]", position.getHeight()) + .withParam("position[x]", position.getX()) + .withParam("position[y]", position.getY()); } - /** - * Deletes an existing discussion note of a merge request. - * - *
GitLab Endpoint: DELETE /projects/:id/merge_requests/:merge_request_iid/discussions/:discussion_id/notes/:note_id
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param mergeRequestIid mergeRequestIid the internal ID of the merge request - * @param discussionId the ID of a discussion - * @param noteId the note ID to delete - * @throws GitLabApiException if any exception occurs during execution - */ - public void deleteMergeRequestDiscussionNote(Object projectIdOrPath, Long mergeRequestIid, - String discussionId, Long noteId) throws GitLabApiException { - delete(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), - "merge_requests", mergeRequestIid, "discussions", discussionId, "notes", noteId); - } + final Response response = + post( + Response.Status.CREATED, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "merge_requests", + mergeRequestIid, + "discussions"); + return (response.readEntity(Discussion.class)); + } - /** - * Get a list of all discussions for the specified commit. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:commit_sha/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param commitSha the SHA of the commit to get discussions for - * @return a list containing all the discussions for the specified commit - * @throws GitLabApiException if any exception occurs during execution - */ - public List getCommitDiscussions(Object projectIdOrPath, String commitSha) throws GitLabApiException { - Pager pager = getCommitDiscussionsPager(projectIdOrPath, commitSha, getDefaultPerPage()); - return (pager.all()); - } + /** + * Resolve or unresolve whole discussion of a merge request. + * + *
+   * GitLab Endpoint: PUT /projects/:id/merge_requests/:merge_request_iid/discussions/:discussion_id
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param mergeRequestIid mergeRequestIid the internal ID of the merge request + * @param discussionId the ID of a discussion + * @param resolved resolve/unresolve the discussion + * @return the updated DIscussion instance + * @throws GitLabApiException if any exception occurs during execution + */ + public Discussion resolveMergeRequestDiscussion( + final Object projectIdOrPath, + final Long mergeRequestIid, + final String discussionId, + final Boolean resolved) + throws GitLabApiException { + final GitLabApiForm formData = new GitLabApiForm().withParam("resolved", resolved, true); + final Response response = + put( + Response.Status.OK, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "merge_requests", + mergeRequestIid, + "discussions", + discussionId); + return (response.readEntity(Discussion.class)); + } - /** - * Get a list of discussions for the specified commit. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:commit_sha/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param commitSha the SHA of the commit to get discussions for - * @param maxItems the maximum number of Discussion instances to get, if < 1 will fetch all Discussion instances for the commit - * @return a list containing the discussions for the specified commit - * @throws GitLabApiException if any exception occurs during execution - */ - public List getCommitDiscussions(Object projectIdOrPath, String commitSha, int maxItems) throws GitLabApiException { - if (maxItems < 1) { - return (getCommitDiscussions(projectIdOrPath, commitSha)); - } else { - Response response = get(Response.Status.OK, getPerPageQueryParam(maxItems), - "projects", getProjectIdOrPath(projectIdOrPath), "repository", "commits", commitSha, "discussions"); - return (response.readEntity(new GenericType>() {})); - } - } + /** + * Deletes an existing discussion note of a merge request. + * + *
+   * GitLab Endpoint: DELETE /projects/:id/merge_requests/:merge_request_iid/discussions/:discussion_id/notes/:note_id
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param mergeRequestIid mergeRequestIid the internal ID of the merge request + * @param discussionId the ID of a discussion + * @param noteId the note ID to delete + * @throws GitLabApiException if any exception occurs during execution + */ + public void deleteMergeRequestDiscussionNote( + final Object projectIdOrPath, + final Long mergeRequestIid, + final String discussionId, + final Long noteId) + throws GitLabApiException { + delete( + Response.Status.OK, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "merge_requests", + mergeRequestIid, + "discussions", + discussionId, + "notes", + noteId); + } - /** - * Get a Pager of Discussion instances for the specified commit. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:commit_sha/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param commitSha the SHA of the commit to get discussions for - * @param itemsPerPage the number of Discussion instances that will be fetched per page - * @return a Pager containing the Discussion instances for the specified commit - * @throws GitLabApiException if any exception occurs during execution - */ - public Pager getCommitDiscussionsPager(Object projectIdOrPath, String commitSha, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, Discussion.class, itemsPerPage, null, - "projects", getProjectIdOrPath(projectIdOrPath), "repository", "commits", commitSha, "discussions")); - } + /** + * Get a list of all discussions for the specified commit. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:commit_sha/discussions
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param commitSha the SHA of the commit to get discussions for + * @return a list containing all the discussions for the specified commit + * @throws GitLabApiException if any exception occurs during execution + */ + public List getCommitDiscussions(final Object projectIdOrPath, final String commitSha) + throws GitLabApiException { + final Pager pager = + getCommitDiscussionsPager(projectIdOrPath, commitSha, getDefaultPerPage()); + return (pager.all()); + } - /** - * Get a Stream of Discussion instances for the specified commit. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:commit_sha/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param commitSha the SHA of the commit to get discussions for - * @return a Stream instance containing the Discussion instances for the specified commit - * @throws GitLabApiException if any exception occurs during execution - */ - public Stream getCommitDiscussionsStream(Object projectIdOrPath, String commitSha) throws GitLabApiException { - Pager pager = getCommitDiscussionsPager(projectIdOrPath, commitSha, getDefaultPerPage()); - return (pager.stream()); + /** + * Get a list of discussions for the specified commit. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:commit_sha/discussions
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param commitSha the SHA of the commit to get discussions for + * @param maxItems the maximum number of Discussion instances to get, if < 1 will fetch all + * Discussion instances for the commit + * @return a list containing the discussions for the specified commit + * @throws GitLabApiException if any exception occurs during execution + */ + public List getCommitDiscussions( + final Object projectIdOrPath, final String commitSha, final int maxItems) + throws GitLabApiException { + if (maxItems < 1) { + return (getCommitDiscussions(projectIdOrPath, commitSha)); + } else { + final Response response = + get( + Response.Status.OK, + getPerPageQueryParam(maxItems), + "projects", + getProjectIdOrPath(projectIdOrPath), + "repository", + "commits", + commitSha, + "discussions"); + return (response.readEntity(new GenericType>() {})); } + } - /** - * Get a single discussion for the specified commit. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:commit_sha/discussions/:discussion_id
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param commitSha the SHA of the commit to get discussions for - * @param discussionId the ID of the discussion - * @return the Discussion instance specified by discussionId for the specified commit - * @throws GitLabApiException if any exception occurs during execution - */ - public Discussion getCommitDiscussion(Object projectIdOrPath, String commitSha, String discussionId) throws GitLabApiException { - Response response = get(Response.Status.OK, null, - "projects", getProjectIdOrPath(projectIdOrPath), "repository", "commits", commitSha, "discussions", discussionId); - return (response.readEntity(Discussion.class)); - } + /** + * Get a Pager of Discussion instances for the specified commit. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:commit_sha/discussions
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param commitSha the SHA of the commit to get discussions for + * @param itemsPerPage the number of Discussion instances that will be fetched per page + * @return a Pager containing the Discussion instances for the specified commit + * @throws GitLabApiException if any exception occurs during execution + */ + public Pager getCommitDiscussionsPager( + final Object projectIdOrPath, final String commitSha, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, + Discussion.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "repository", + "commits", + commitSha, + "discussions")); + } - /** - * Get an Optional instance of a single discussion for the specified commit. - * - *
GitLab Endpoint: GET /projects/:id/repository/commits/:commit_sha/discussions/:discussion_id
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param commitSha the SHA of the commit to get discussions for - * @param discussionId the ID of the discussion - * @return an Optional instance with the specified Discussion instance as a value - */ - public Optional getOptionalCommitDiscussion(Object projectIdOrPath, String commitSha, String discussionId) { - try { - return (Optional.ofNullable(getCommitDiscussion(projectIdOrPath, commitSha, discussionId))); - } catch (GitLabApiException glae) { - return (GitLabApi.createOptionalFromException(glae)); - } - } + /** + * Get a Stream of Discussion instances for the specified commit. + * + *
GitLab Endpoint: GET /projects/:id/repository/commits/:commit_sha/discussions
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param commitSha the SHA of the commit to get discussions for + * @return a Stream instance containing the Discussion instances for the specified commit + * @throws GitLabApiException if any exception occurs during execution + */ + public Stream getCommitDiscussionsStream( + final Object projectIdOrPath, final String commitSha) throws GitLabApiException { + final Pager pager = + getCommitDiscussionsPager(projectIdOrPath, commitSha, getDefaultPerPage()); + return (pager.stream()); + } - /** - * Creates a new discussion to a single project commit. This is similar to creating - * a note but other comments (replies) can be added to it later. - * - *
GitLab Endpoint: POST /projects/:id/repository/commits/:commit_sha/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param commitSha the commit SHA to create the discussion for - * @param body the content of a discussion - * @param createdAt date the discussion was created (requires admin or project/group owner rights) - * @param positionHash position when creating a diff note - * @param position a Position instance holding the position attributes - * @return a Discussion instance containing the newly created discussion - * @throws GitLabApiException if any exception occurs during execution - */ - public Discussion createCommitDiscussion(Object projectIdOrPath, String commitSha, - String body, Date createdAt, String positionHash, Position position) throws GitLabApiException { - - if (position == null) { - throw new GitLabApiException("position instance can not be null"); - } - - GitLabApiForm formData = new GitLabApiForm() - .withParam("body", body, true) - .withParam("created_at", createdAt) - .withParam("position", positionHash) - .withParam("position[base_sha]", position.getBaseSha(), true) - .withParam("position[start_sha]", position.getStartSha(), true) - .withParam("position[head_sha]", position.getHeadSha(), true) - .withParam("position[position_type]", position.getPositionType(), true) - .withParam("position[new_path]", position.getNewPath()) - .withParam("position[new_line]", position.getNewLine()) - .withParam("position[old_path]", position.getOldPath()) - .withParam("position[old_line]", position.getOldLine()) - .withParam("position[width]", position.getWidth()) - .withParam("position[height]", position.getHeight()) - .withParam("position[x]", position.getX()) - .withParam("position[y]", position.getY()); - - Response response = post(Response.Status.CREATED, formData, - "projects", getProjectIdOrPath(projectIdOrPath), "repository", "commits", commitSha, "discussions"); - return (response.readEntity(Discussion.class)); - } + /** + * Get a single discussion for the specified commit. + * + *
+   * GitLab Endpoint: GET /projects/:id/repository/commits/:commit_sha/discussions/:discussion_id
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param commitSha the SHA of the commit to get discussions for + * @param discussionId the ID of the discussion + * @return the Discussion instance specified by discussionId for the specified commit + * @throws GitLabApiException if any exception occurs during execution + */ + public Discussion getCommitDiscussion( + final Object projectIdOrPath, final String commitSha, final String discussionId) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "repository", + "commits", + commitSha, + "discussions", + discussionId); + return (response.readEntity(Discussion.class)); + } - /** - * Adds a note to an existing commit discussion. - * - *
GitLab Endpoint: POST /projects/:id/repository/commits/:commit_sha/discussions/:discussion_id/notes
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param commitSha the commit SHA to create the discussion for - * @param discussionId the ID of a discussion - * @param body the content of a discussion - * @param createdAt date the discussion was created (requires admin or project/group owner rights) - * @return a Note instance containing the newly created discussion note - * @throws GitLabApiException if any exception occurs during execution - */ - public Note addCommitDiscussionNote(Object projectIdOrPath, String commitSha, String discussionId, - String body, Date createdAt) throws GitLabApiException { - - GitLabApiForm formData = new GitLabApiForm() - .withParam("body", body, true) - .withParam("created_at", createdAt); - - Response response = post(Response.Status.CREATED, formData, - "projects", getProjectIdOrPath(projectIdOrPath), - "repository", "commits", commitSha, "discussions", discussionId, "notes"); - return (response.readEntity(Note.class)); + /** + * Get an Optional instance of a single discussion for the specified commit. + * + *
+   * GitLab Endpoint: GET /projects/:id/repository/commits/:commit_sha/discussions/:discussion_id
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param commitSha the SHA of the commit to get discussions for + * @param discussionId the ID of the discussion + * @return an Optional instance with the specified Discussion instance as a value + */ + public Optional getOptionalCommitDiscussion( + final Object projectIdOrPath, final String commitSha, final String discussionId) { + try { + return (Optional.ofNullable(getCommitDiscussion(projectIdOrPath, commitSha, discussionId))); + } catch (final GitLabApiException glae) { + return (GitLabApi.createOptionalFromException(glae)); } + } - /** - * Modify an existing discussion note of a commit. - * - *
GitLab Endpoint: PUT /projects/:id/repository/commits/:commit_sha/discussions/:discussion_id/notes
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param commitSha the commit SHA to delete the discussion from - * @param discussionId the ID of a discussion - * @param noteId the note ID to modify - * @param body the content of a discussion - * @return a Note instance containing the updated discussion note - * @throws GitLabApiException if any exception occurs during execution - */ - public Note modifyCommitDiscussionNote(Object projectIdOrPath, - String commitSha, String discussionId, Long noteId, String body) throws GitLabApiException { - - GitLabApiForm formData = new GitLabApiForm().withParam("body", body, true); - Response response = this.putWithFormData(Response.Status.OK, formData, - "projects", getProjectIdOrPath(projectIdOrPath), - "repository", "commits", commitSha, "discussions", discussionId, "notes", noteId); - return (response.readEntity(Note.class)); - } + /** + * Creates a new discussion to a single project commit. This is similar to creating a note but + * other comments (replies) can be added to it later. + * + *
+   * GitLab Endpoint: POST /projects/:id/repository/commits/:commit_sha/discussions
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param commitSha the commit SHA to create the discussion for + * @param body the content of a discussion + * @param createdAt date the discussion was created (requires admin or project/group owner rights) + * @param positionHash position when creating a diff note + * @param position a Position instance holding the position attributes + * @return a Discussion instance containing the newly created discussion + * @throws GitLabApiException if any exception occurs during execution + */ + public Discussion createCommitDiscussion( + final Object projectIdOrPath, + final String commitSha, + final String body, + final Date createdAt, + final String positionHash, + final Position position) + throws GitLabApiException { - /** - * Resolve or unresolve an existing discussion note of a commit. - * - *
GitLab Endpoint: PUT /projects/:id/repository/commits/:commit_sha/discussions/:discussion_id/notes
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param commitSha the commit SHA to delete the discussion from - * @param discussionId the ID of a discussion - * @param noteId the note ID to resolve or unresolve - * @param resolved if true will resolve the note, false will unresolve the note - * @return a Note instance containing the updated discussion note - * @throws GitLabApiException if any exception occurs during execution - */ - public Note resolveCommitDiscussionNote(Object projectIdOrPath, - String commitSha, String discussionId, Long noteId, Boolean resolved) throws GitLabApiException { - - GitLabApiForm queryParams = new GitLabApiForm().withParam("resolved", resolved); - Response response = this.put(Response.Status.OK, queryParams.asMap(), - "projects", getProjectIdOrPath(projectIdOrPath), - "repository", "commits", commitSha, "discussions", discussionId, "notes", noteId); - return (response.readEntity(Note.class)); + if (position == null) { + throw new GitLabApiException("position instance can not be null"); } - /** - * Deletes an existing discussion note of a commit. - * - *
GitLab Endpoint: DELETE /projects/:id/repository/commits/:commit_sha/discussions/:discussion_id/notes/:note_id
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param commitSha the commit SHA to delete the discussion from - * @param discussionId the ID of a discussion - * @param noteId the note ID to delete - * @throws GitLabApiException if any exception occurs during execution - */ - public void deleteCommitDiscussionNote(Object projectIdOrPath, String commitSha, - String discussionId, Long noteId) throws GitLabApiException { - delete(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), - "repository", "commits", commitSha, "discussions", discussionId, "notes", noteId); - } + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("body", body, true) + .withParam("created_at", createdAt) + .withParam("position", positionHash) + .withParam("position[base_sha]", position.getBaseSha(), true) + .withParam("position[start_sha]", position.getStartSha(), true) + .withParam("position[head_sha]", position.getHeadSha(), true) + .withParam("position[position_type]", position.getPositionType(), true) + .withParam("position[new_path]", position.getNewPath()) + .withParam("position[new_line]", position.getNewLine()) + .withParam("position[old_path]", position.getOldPath()) + .withParam("position[old_line]", position.getOldLine()) + .withParam("position[width]", position.getWidth()) + .withParam("position[height]", position.getHeight()) + .withParam("position[x]", position.getX()) + .withParam("position[y]", position.getY()); - /** - * Adds a new note to the thread. This can also create a thread from a single comment. - * - *
GitLab Endpoint: POST /projects/:id/merge_requests/:merge_request_iid/discussions/:discussion_id/notes
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param mergeRequestIid mergeRequestIid the internal ID of the merge request - * @param discussionId the ID of a discussion - * @param body the content of a discussion - * @param createdAt date the discussion was created (requires admin or project/group owner rights) - * @return a Note instance containing the newly created discussion note - * @throws GitLabApiException if any exception occurs during execution - */ - public Note addMergeRequestThreadNote(Object projectIdOrPath, Long mergeRequestIid, - String discussionId, String body, Date createdAt) throws GitLabApiException { - - GitLabApiForm formData = new GitLabApiForm() - .withParam("body", body, true) - .withParam("created_at", createdAt); - Response response = post(Response.Status.CREATED, formData, - "projects", getProjectIdOrPath(projectIdOrPath), - "merge_requests", mergeRequestIid, "discussions", discussionId, "notes"); - return (response.readEntity(Note.class)); - } + final Response response = + post( + Response.Status.CREATED, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "repository", + "commits", + commitSha, + "discussions"); + return (response.readEntity(Discussion.class)); + } - /** - * Modify or resolve an existing thread note of a merge request. - * - *
GitLab Endpoint: PUT /projects/:id/merge_requests/:merge_request_iid/discussions/:discussion_id/notes/:note_id
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param mergeRequestIid mergeRequestIid the internal ID of the merge request - * @param discussionId the ID of a discussion - * @param noteId the note ID to modify - * @param body the content of a discussion - * @param resolved if true will resolve the note, false will unresolve the note - * @return a Note instance containing the updated discussion note - * @throws GitLabApiException if any exception occurs during execution - */ - public Note modifyMergeRequestThreadNote(Object projectIdOrPath, Long mergeRequestIid, - String discussionId, Long noteId, String body, Boolean resolved) throws GitLabApiException { - - GitLabApiForm formData = new GitLabApiForm().withParam("body", body).withParam("resolved", resolved); - Response response = this.putWithFormData(Response.Status.OK, formData, - "projects", getProjectIdOrPath(projectIdOrPath), - "merge_requests", mergeRequestIid, "discussions", discussionId, "notes", noteId); - return (response.readEntity(Note.class)); - } + /** + * Adds a note to an existing commit discussion. + * + *
+   * GitLab Endpoint: POST /projects/:id/repository/commits/:commit_sha/discussions/:discussion_id/notes
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param commitSha the commit SHA to create the discussion for + * @param discussionId the ID of a discussion + * @param body the content of a discussion + * @param createdAt date the discussion was created (requires admin or project/group owner rights) + * @return a Note instance containing the newly created discussion note + * @throws GitLabApiException if any exception occurs during execution + */ + public Note addCommitDiscussionNote( + final Object projectIdOrPath, + final String commitSha, + final String discussionId, + final String body, + final Date createdAt) + throws GitLabApiException { - /** - * Deletes an existing thread note of a merge request. - * - *
GitLab Endpoint: DELETE /projects/:id/merge_requests/:merge_request_iid/discussions/:discussion_id/notes/:note_id
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param mergeRequestIid mergeRequestIid the internal ID of the merge request - * @param discussionId the ID of a discussion - * @param noteId the note ID to delete - * @throws GitLabApiException if any exception occurs during execution - */ - public void deleteMergeRequestThreadNote(Object projectIdOrPath, Long mergeRequestIid, - String discussionId, Long noteId) throws GitLabApiException { - delete(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), - "merge_requests", mergeRequestIid, "discussions", discussionId, "notes", noteId); - } + final GitLabApiForm formData = + new GitLabApiForm().withParam("body", body, true).withParam("created_at", createdAt); - /** - * Creates a new thread to a single project issue. This is similar to creating a note but other comments (replies) can be added to it later. - * - *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/discussions
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid The IID of an issue - * @param body the content of the discussion - * @param createdAt (optional) date the discussion was created (requires admin or project/group owner rights) - * @return a Discussion instance containing the newly created discussion - * @throws GitLabApiException if any exception occurs during execution - */ - public Discussion createIssueDiscussion(Object projectIdOrPath, Long issueIid, String body, Date createdAt) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() - .withParam("body", body, true) - .withParam("created_at", createdAt); - Response response = post(Response.Status.CREATED, formData, - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "discussions"); - return (response.readEntity(Discussion.class)); - } + final Response response = + post( + Response.Status.CREATED, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "repository", + "commits", + commitSha, + "discussions", + discussionId, + "notes"); + return (response.readEntity(Note.class)); + } - /** - * Adds a new note to the thread. - * - *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/discussions/:discussion_id/notes
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid The IID of an issue - * @param discussionId the id of discussion - * @param body the content of the note - * @param createdAt (optional) date the discussion was created (requires admin or project/group owner rights) - * @return a Note instance containing the newly created note - * @throws GitLabApiException if any exception occurs during execution - */ - public Note addIssueThreadNote(Object projectIdOrPath, Long issueIid, - String discussionId, String body, Date createdAt) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() - .withParam("body", body, true) - .withParam("created_at", createdAt); - Response response = post(Response.Status.CREATED, formData, - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "discussions", discussionId, "notes"); - return (response.readEntity(Note.class)); - } + /** + * Modify an existing discussion note of a commit. + * + *
+   * GitLab Endpoint: PUT /projects/:id/repository/commits/:commit_sha/discussions/:discussion_id/notes
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param commitSha the commit SHA to delete the discussion from + * @param discussionId the ID of a discussion + * @param noteId the note ID to modify + * @param body the content of a discussion + * @return a Note instance containing the updated discussion note + * @throws GitLabApiException if any exception occurs during execution + */ + public Note modifyCommitDiscussionNote( + final Object projectIdOrPath, + final String commitSha, + final String discussionId, + final Long noteId, + final String body) + throws GitLabApiException { - /** - * Modify existing thread note of an issue. - * - *
GitLab Endpoint: PUT /projects/:id/issues/:issue_iid/discussions/:discussion_id/notes/:note_id
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid The IID of an issue - * @param discussionId the id of discussion - * @param noteId the id of the note - * @param body the content of the note - * @return a Note instance containing the modified note - * @throws GitLabApiException if any exception occurs during execution - */ - public Note modifyIssueThreadNote(Object projectIdOrPath, Long issueIid, - String discussionId, Long noteId, String body) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() - .withParam("body", body, true); - Response response = putWithFormData(Response.Status.OK, formData, - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "discussions", discussionId, "notes", noteId); - return (response.readEntity(Note.class)); - } + final GitLabApiForm formData = new GitLabApiForm().withParam("body", body, true); + final Response response = + this.putWithFormData( + Response.Status.OK, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "repository", + "commits", + commitSha, + "discussions", + discussionId, + "notes", + noteId); + return (response.readEntity(Note.class)); + } - /** - * Deletes an existing thread note of an issue. - * - *
GitLab Endpoint: DELETE /projects/:id/issues/:issue_iid/discussions/:discussion_id/notes/:note_id
- * - * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid The IID of an issue - * @param discussionId the id of discussion - * @param noteId the id of the note - * @throws GitLabApiException if any exception occurs during execution - */ - public void deleteIssueThreadNote(Object projectIdOrPath, Long issueIid, - String discussionId, Long noteId) throws GitLabApiException { - delete(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "discussions", discussionId, "notes", noteId); - } + /** + * Resolve or unresolve an existing discussion note of a commit. + * + *
+   * GitLab Endpoint: PUT /projects/:id/repository/commits/:commit_sha/discussions/:discussion_id/notes
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param commitSha the commit SHA to delete the discussion from + * @param discussionId the ID of a discussion + * @param noteId the note ID to resolve or unresolve + * @param resolved if true will resolve the note, false will unresolve the note + * @return a Note instance containing the updated discussion note + * @throws GitLabApiException if any exception occurs during execution + */ + public Note resolveCommitDiscussionNote( + final Object projectIdOrPath, + final String commitSha, + final String discussionId, + final Long noteId, + final Boolean resolved) + throws GitLabApiException { + + final GitLabApiForm queryParams = new GitLabApiForm().withParam("resolved", resolved); + final Response response = + this.put( + Response.Status.OK, + queryParams.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "repository", + "commits", + commitSha, + "discussions", + discussionId, + "notes", + noteId); + return (response.readEntity(Note.class)); + } + + /** + * Deletes an existing discussion note of a commit. + * + *
+   * GitLab Endpoint: DELETE /projects/:id/repository/commits/:commit_sha/discussions/:discussion_id/notes/:note_id
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param commitSha the commit SHA to delete the discussion from + * @param discussionId the ID of a discussion + * @param noteId the note ID to delete + * @throws GitLabApiException if any exception occurs during execution + */ + public void deleteCommitDiscussionNote( + final Object projectIdOrPath, + final String commitSha, + final String discussionId, + final Long noteId) + throws GitLabApiException { + delete( + Response.Status.OK, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "repository", + "commits", + commitSha, + "discussions", + discussionId, + "notes", + noteId); + } + + /** + * Adds a new note to the thread. This can also create a thread from a single comment. + * + *
+   * GitLab Endpoint: POST /projects/:id/merge_requests/:merge_request_iid/discussions/:discussion_id/notes
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param mergeRequestIid mergeRequestIid the internal ID of the merge request + * @param discussionId the ID of a discussion + * @param body the content of a discussion + * @param createdAt date the discussion was created (requires admin or project/group owner rights) + * @return a Note instance containing the newly created discussion note + * @throws GitLabApiException if any exception occurs during execution + */ + public Note addMergeRequestThreadNote( + final Object projectIdOrPath, + final Long mergeRequestIid, + final String discussionId, + final String body, + final Date createdAt) + throws GitLabApiException { + + final GitLabApiForm formData = + new GitLabApiForm().withParam("body", body, true).withParam("created_at", createdAt); + final Response response = + post( + Response.Status.CREATED, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "merge_requests", + mergeRequestIid, + "discussions", + discussionId, + "notes"); + return (response.readEntity(Note.class)); + } + + /** + * Modify or resolve an existing thread note of a merge request. + * + *
+   * GitLab Endpoint: PUT /projects/:id/merge_requests/:merge_request_iid/discussions/:discussion_id/notes/:note_id
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param mergeRequestIid mergeRequestIid the internal ID of the merge request + * @param discussionId the ID of a discussion + * @param noteId the note ID to modify + * @param body the content of a discussion + * @param resolved if true will resolve the note, false will unresolve the note + * @return a Note instance containing the updated discussion note + * @throws GitLabApiException if any exception occurs during execution + */ + public Note modifyMergeRequestThreadNote( + final Object projectIdOrPath, + final Long mergeRequestIid, + final String discussionId, + final Long noteId, + final String body, + final Boolean resolved) + throws GitLabApiException { + + final GitLabApiForm formData = + new GitLabApiForm().withParam("body", body).withParam("resolved", resolved); + final Response response = + this.putWithFormData( + Response.Status.OK, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "merge_requests", + mergeRequestIid, + "discussions", + discussionId, + "notes", + noteId); + return (response.readEntity(Note.class)); + } + + /** + * Deletes an existing thread note of a merge request. + * + *
+   * GitLab Endpoint: DELETE /projects/:id/merge_requests/:merge_request_iid/discussions/:discussion_id/notes/:note_id
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param mergeRequestIid mergeRequestIid the internal ID of the merge request + * @param discussionId the ID of a discussion + * @param noteId the note ID to delete + * @throws GitLabApiException if any exception occurs during execution + */ + public void deleteMergeRequestThreadNote( + final Object projectIdOrPath, + final Long mergeRequestIid, + final String discussionId, + final Long noteId) + throws GitLabApiException { + delete( + Response.Status.OK, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "merge_requests", + mergeRequestIid, + "discussions", + discussionId, + "notes", + noteId); + } + + /** + * Creates a new thread to a single project issue. This is similar to creating a note but other + * comments (replies) can be added to it later. + * + *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/discussions
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param issueIid The IID of an issue + * @param body the content of the discussion + * @param createdAt (optional) date the discussion was created (requires admin or project/group + * owner rights) + * @return a Discussion instance containing the newly created discussion + * @throws GitLabApiException if any exception occurs during execution + */ + public Discussion createIssueDiscussion( + final Object projectIdOrPath, final Long issueIid, final String body, final Date createdAt) + throws GitLabApiException { + final GitLabApiForm formData = + new GitLabApiForm().withParam("body", body, true).withParam("created_at", createdAt); + final Response response = + post( + Response.Status.CREATED, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "discussions"); + return (response.readEntity(Discussion.class)); + } + + /** + * Adds a new note to the thread. + * + *
+   * GitLab Endpoint: POST /projects/:id/issues/:issue_iid/discussions/:discussion_id/notes
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param issueIid The IID of an issue + * @param discussionId the id of discussion + * @param body the content of the note + * @param createdAt (optional) date the discussion was created (requires admin or project/group + * owner rights) + * @return a Note instance containing the newly created note + * @throws GitLabApiException if any exception occurs during execution + */ + public Note addIssueThreadNote( + final Object projectIdOrPath, + final Long issueIid, + final String discussionId, + final String body, + final Date createdAt) + throws GitLabApiException { + final GitLabApiForm formData = + new GitLabApiForm().withParam("body", body, true).withParam("created_at", createdAt); + final Response response = + post( + Response.Status.CREATED, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "discussions", + discussionId, + "notes"); + return (response.readEntity(Note.class)); + } + + /** + * Modify existing thread note of an issue. + * + *
+   * GitLab Endpoint: PUT /projects/:id/issues/:issue_iid/discussions/:discussion_id/notes/:note_id
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param issueIid The IID of an issue + * @param discussionId the id of discussion + * @param noteId the id of the note + * @param body the content of the note + * @return a Note instance containing the modified note + * @throws GitLabApiException if any exception occurs during execution + */ + public Note modifyIssueThreadNote( + final Object projectIdOrPath, + final Long issueIid, + final String discussionId, + final Long noteId, + final String body) + throws GitLabApiException { + final GitLabApiForm formData = new GitLabApiForm().withParam("body", body, true); + final Response response = + putWithFormData( + Response.Status.OK, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "discussions", + discussionId, + "notes", + noteId); + return (response.readEntity(Note.class)); + } + /** + * Deletes an existing thread note of an issue. + * + *
+   * GitLab Endpoint: DELETE /projects/:id/issues/:issue_iid/discussions/:discussion_id/notes/:note_id
+   * 
+ * + * @param projectIdOrPath projectIdOrPath the project in the form of an Long(ID), String(path), or + * Project instance + * @param issueIid The IID of an issue + * @param discussionId the id of discussion + * @param noteId the id of the note + * @throws GitLabApiException if any exception occurs during execution + */ + public void deleteIssueThreadNote( + final Object projectIdOrPath, + final Long issueIid, + final String discussionId, + final Long noteId) + throws GitLabApiException { + delete( + Response.Status.OK, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "discussions", + discussionId, + "notes", + noteId); + } } diff --git a/src/main/java/org/gitlab4j/api/EnvironmentsApi.java b/src/main/java/org/gitlab4j/api/EnvironmentsApi.java index 6eca51277..074732f85 100644 --- a/src/main/java/org/gitlab4j/api/EnvironmentsApi.java +++ b/src/main/java/org/gitlab4j/api/EnvironmentsApi.java @@ -3,176 +3,244 @@ import java.util.List; import java.util.Optional; import java.util.stream.Stream; - -import javax.ws.rs.core.Response; - +import jakarta.ws.rs.core.Response; import org.gitlab4j.api.models.Environment; /** * This class provides an entry point to all the GitLab API Environments API calls. + * * @see Environments API */ public class EnvironmentsApi extends AbstractApi { - public EnvironmentsApi(GitLabApi gitLabApi) { - super(gitLabApi); - } + public EnvironmentsApi(final GitLabApi gitLabApi) { + super(gitLabApi); + } - /** - * Get all environments for a given project. - * - *
GitLab Endpoint: GET /projects/:id/environments
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @return a List of Environment instances - * @throws GitLabApiException if any exception occurs - */ - public List getEnvironments(Object projectIdOrPath) throws GitLabApiException { - return (getEnvironments(projectIdOrPath, getDefaultPerPage()).all()); - } + /** + * Get all environments for a given project. + * + *
GitLab Endpoint: GET /projects/:id/environments
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @return a List of Environment instances + * @throws GitLabApiException if any exception occurs + */ + public List getEnvironments(final Object projectIdOrPath) throws GitLabApiException { + return (getEnvironments(projectIdOrPath, getDefaultPerPage()).all()); + } - /** - * Get a Stream of all environments for a given project. - * - *
GitLab Endpoint: GET /projects/:id/environments
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @return a Stream of Environment instances - * @throws GitLabApiException if any exception occurs - */ - public Stream getEnvironmentsStream(Object projectIdOrPath) throws GitLabApiException { - return (getEnvironments(projectIdOrPath, getDefaultPerPage()).stream()); - } + /** + * Get a Stream of all environments for a given project. + * + *
GitLab Endpoint: GET /projects/:id/environments
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @return a Stream of Environment instances + * @throws GitLabApiException if any exception occurs + */ + public Stream getEnvironmentsStream(final Object projectIdOrPath) + throws GitLabApiException { + return (getEnvironments(projectIdOrPath, getDefaultPerPage()).stream()); + } - /** - * Get a Pager of all environments for a given project. - * - *
GitLab Endpoint: GET /projects/:id/environments
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param itemsPerPage the number of Environment instances that will be fetched per page - * @return a Pager of Environment instances - * @throws GitLabApiException if any exception occurs - */ - public Pager getEnvironments(Object projectIdOrPath, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, Environment.class, itemsPerPage, null, - "projects", getProjectIdOrPath(projectIdOrPath), "environments")); - } + /** + * Get a Pager of all environments for a given project. + * + *
GitLab Endpoint: GET /projects/:id/environments
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param itemsPerPage the number of Environment instances that will be fetched per page + * @return a Pager of Environment instances + * @throws GitLabApiException if any exception occurs + */ + public Pager getEnvironments(final Object projectIdOrPath, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, + Environment.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "environments")); + } - /** - * Get a specific environment. - * - *
GitLab Endpoint: GET /projects/:id/environments/:environment_id
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param environmentId the ID of the environment to get - * @return an Environment instance - * @throws GitLabApiException if any exception occurs - */ - public Environment getEnvironment(Object projectIdOrPath, Long environmentId) throws GitLabApiException { - Response response = get(Response.Status.OK, null, - "projects", getProjectIdOrPath(projectIdOrPath), "environments", environmentId); - return (response.readEntity(Environment.class)); - } + /** + * Get a specific environment. + * + *
GitLab Endpoint: GET /projects/:id/environments/:environment_id
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param environmentId the ID of the environment to get + * @return an Environment instance + * @throws GitLabApiException if any exception occurs + */ + public Environment getEnvironment(final Object projectIdOrPath, final Long environmentId) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "environments", + environmentId); + return (response.readEntity(Environment.class)); + } - /** - * Get a specific environment. as an Optional instance. - * - *
GitLab Endpoint: GET /projects/:id/environments/:environment_id
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param environmentId the ID of the environment to get - * @return the Environment as an Optional instance - */ - public Optional getOptionalEnvironment(Object projectIdOrPath, Long environmentId) { - try { - return (Optional.ofNullable(getEnvironment(projectIdOrPath, environmentId))); - } catch (GitLabApiException glae) { - return (GitLabApi.createOptionalFromException(glae)); - } + /** + * Get a specific environment. as an Optional instance. + * + *
GitLab Endpoint: GET /projects/:id/environments/:environment_id
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param environmentId the ID of the environment to get + * @return the Environment as an Optional instance + */ + public Optional getOptionalEnvironment( + final Object projectIdOrPath, final Long environmentId) { + try { + return (Optional.ofNullable(getEnvironment(projectIdOrPath, environmentId))); + } catch (final GitLabApiException glae) { + return (GitLabApi.createOptionalFromException(glae)); } + } - /** - * Create a new environment with the given name and external_url. - * - *
GitLab Endpoint:POST /projects/:id/environments
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param name the name of the environment - * @param externalUrl the place to link to for this environment - * @return the created Environment instance - * @throws GitLabApiException if any exception occurs - */ - public Environment createEnvironment(Object projectIdOrPath, String name, String externalUrl) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm().withParam("name", name, true).withParam("external_url", externalUrl); - Response response = post(Response.Status.CREATED, formData, - "projects", getProjectIdOrPath(projectIdOrPath), "environments"); - return (response.readEntity(Environment.class)); - } + /** + * Create a new environment with the given name and external_url. + * + *
GitLab Endpoint:POST /projects/:id/environments
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param name the name of the environment + * @param externalUrl the place to link to for this environment + * @return the created Environment instance + * @throws GitLabApiException if any exception occurs + */ + public Environment createEnvironment( + final Object projectIdOrPath, final String name, final String externalUrl) + throws GitLabApiException { + final GitLabApiForm formData = + new GitLabApiForm().withParam("name", name, true).withParam("external_url", externalUrl); + final Response response = + post( + Response.Status.CREATED, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "environments"); + return (response.readEntity(Environment.class)); + } - /** - * Update an existing environment. - * - *
GitLab Endpoint:POST /projects/:id/environments
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param environmentId the ID of the environment to update - * @param name the name of the environment - * @param externalUrl the place to link to for this environment - * @return the created Environment instance - * @throws GitLabApiException if any exception occurs - */ - public Environment updateEnvironment(Object projectIdOrPath, Long environmentId, String name, String externalUrl) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm().withParam("name", name).withParam("external_url", externalUrl); - Response response = putWithFormData(Response.Status.OK, formData, formData, - "projects", getProjectIdOrPath(projectIdOrPath), "environments", environmentId); - return (response.readEntity(Environment.class)); - } + /** + * Update an existing environment. + * + *
GitLab Endpoint:POST /projects/:id/environments
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param environmentId the ID of the environment to update + * @param name the name of the environment + * @param externalUrl the place to link to for this environment + * @return the created Environment instance + * @throws GitLabApiException if any exception occurs + */ + public Environment updateEnvironment( + final Object projectIdOrPath, + final Long environmentId, + final String name, + final String externalUrl) + throws GitLabApiException { + final GitLabApiForm formData = + new GitLabApiForm().withParam("name", name).withParam("external_url", externalUrl); + final Response response = + putWithFormData( + Response.Status.OK, + formData, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "environments", + environmentId); + return (response.readEntity(Environment.class)); + } - /** - * Stop an environment. - * - *
GitLab Endpoint: POST /projects/:id/environments/:environment_id/stop
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param environmentId the ID of the environment to stop - * @return the stopped Environment instance - * @throws GitLabApiException if any exception occurs - */ - public Environment stopEnvironment(Object projectIdOrPath, Long environmentId) throws GitLabApiException { - Response response = post(Response.Status.OK, (GitLabApiForm) null, - "projects", getProjectIdOrPath(projectIdOrPath), "environments", environmentId, "stop"); - return (response.readEntity(Environment.class)); - } + /** + * Stop an environment. + * + *
GitLab Endpoint: POST /projects/:id/environments/:environment_id/stop
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param environmentId the ID of the environment to stop + * @return the stopped Environment instance + * @throws GitLabApiException if any exception occurs + */ + public Environment stopEnvironment(final Object projectIdOrPath, final Long environmentId) + throws GitLabApiException { + final Response response = + post( + Response.Status.OK, + (GitLabApiForm) null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "environments", + environmentId, + "stop"); + return (response.readEntity(Environment.class)); + } - /** - * Delete an environment. - * - *
GitLab Endpoint: DELETE /projects/:id/environments/:environment_id
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param environmentId the ID of the environment to delete - * @throws GitLabApiException if any exception occurs - */ - public void deleteEnvironment(Object projectIdOrPath, Long environmentId) throws GitLabApiException { - delete(Response.Status.OK, null, - "projects", getProjectIdOrPath(projectIdOrPath), "environments", environmentId); - } + /** + * Delete an environment. + * + *
GitLab Endpoint: DELETE /projects/:id/environments/:environment_id
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param environmentId the ID of the environment to delete + * @throws GitLabApiException if any exception occurs + */ + public void deleteEnvironment(final Object projectIdOrPath, final Long environmentId) + throws GitLabApiException { + delete( + Response.Status.OK, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "environments", + environmentId); + } - /** - * Stop an environment. - * - *
GitLab Endpoint:POST /projects/:id/environments/:environment_id/stop
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param environmentId the ID of the environment to stop - * @return the Environment instance of the stopped environment - * @throws GitLabApiException if any exception occurs - */ - public Environment createEnvironment(Object projectIdOrPath, Long environmentId) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm(); - Response response = post(Response.Status.CREATED, formData, - "projects", getProjectIdOrPath(projectIdOrPath), "environments", environmentId, "stop"); - return (response.readEntity(Environment.class)); - } -} \ No newline at end of file + /** + * Stop an environment. + * + *
GitLab Endpoint:POST /projects/:id/environments/:environment_id/stop
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param environmentId the ID of the environment to stop + * @return the Environment instance of the stopped environment + * @throws GitLabApiException if any exception occurs + */ + public Environment createEnvironment(final Object projectIdOrPath, final Long environmentId) + throws GitLabApiException { + final GitLabApiForm formData = new GitLabApiForm(); + final Response response = + post( + Response.Status.CREATED, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "environments", + environmentId, + "stop"); + return (response.readEntity(Environment.class)); + } +} diff --git a/src/main/java/org/gitlab4j/api/EpicsApi.java b/src/main/java/org/gitlab4j/api/EpicsApi.java index 6eb59a1cf..2d001d826 100644 --- a/src/main/java/org/gitlab4j/api/EpicsApi.java +++ b/src/main/java/org/gitlab4j/api/EpicsApi.java @@ -4,457 +4,646 @@ import java.util.List; import java.util.Optional; import java.util.stream.Stream; - -import javax.ws.rs.core.Form; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; - +import jakarta.ws.rs.core.Form; +import jakarta.ws.rs.core.GenericType; +import jakarta.ws.rs.core.Response; import org.gitlab4j.api.models.Epic; import org.gitlab4j.api.models.EpicIssue; /** * This class implements the client side API for the GitLab Epics and Epic Issues API calls. * - * NOTE: - * - If a user is not a member of a group and the group is private, a GET request on that group will result to a 404 status code. - * - Epics are available only in Ultimate. If epics feature is not available a 403 status code will be returned. + *

NOTE: - If a user is not a member of a group and the group is private, a GET request on that + * group will result to a 404 status code. - Epics are available only in Ultimate. If epics feature + * is not available a 403 status code will be returned. * * @see GitLab Epics API Documentaion - * @see GitLab Epic Issues API Documentation + * @see GitLab Epic Issues API + * Documentation */ public class EpicsApi extends AbstractApi { - public EpicsApi(GitLabApi gitLabApi) { - super(gitLabApi); - } + public EpicsApi(final GitLabApi gitLabApi) { + super(gitLabApi); + } - /** - * Gets all epics of the requested group and its subgroups. - * - *

GitLab Endpoint: GET /groups/:id/epics
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @return a list of all epics of the requested group and its subgroups - * @throws GitLabApiException if any exception occurs - */ - public List getEpics(Object groupIdOrPath) throws GitLabApiException { - return (getEpics(groupIdOrPath, getDefaultPerPage()).all()); - } + /** + * Gets all epics of the requested group and its subgroups. + * + *
GitLab Endpoint: GET /groups/:id/epics
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @return a list of all epics of the requested group and its subgroups + * @throws GitLabApiException if any exception occurs + */ + public List getEpics(final Object groupIdOrPath) throws GitLabApiException { + return (getEpics(groupIdOrPath, getDefaultPerPage()).all()); + } - /** - * Gets all epics of the requested group and its subgroups using the specified page and per page setting. - * - *
GitLab Endpoint: GET /groups/:id/epics
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param page the page to get - * @param perPage the number of issues per page - * @return a list of all epics of the requested group and its subgroups in the specified range - * @throws GitLabApiException if any exception occurs - */ - public List getEpics(Object groupIdOrPath, int page, int perPage) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "groups", getGroupIdOrPath(groupIdOrPath), "epics"); - return (response.readEntity(new GenericType>() { })); - } + /** + * Gets all epics of the requested group and its subgroups using the specified page and per page + * setting. + * + *
GitLab Endpoint: GET /groups/:id/epics
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param page the page to get + * @param perPage the number of issues per page + * @return a list of all epics of the requested group and its subgroups in the specified range + * @throws GitLabApiException if any exception occurs + */ + public List getEpics(final Object groupIdOrPath, final int page, final int perPage) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getPageQueryParams(page, perPage), + "groups", + getGroupIdOrPath(groupIdOrPath), + "epics"); + return (response.readEntity(new GenericType>() {})); + } - /** - * Get a Pager of all epics of the requested group and its subgroups. - * - *
GitLab Endpoint: GET /groups/:id/epics
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param itemsPerPage the number of issues per page - * @return the Pager of all epics of the requested group and its subgroups - * @throws GitLabApiException if any exception occurs - */ - public Pager getEpics(Object groupIdOrPath, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, Epic.class, itemsPerPage, null, "groups", getGroupIdOrPath(groupIdOrPath), "epics")); - } + /** + * Get a Pager of all epics of the requested group and its subgroups. + * + *
GitLab Endpoint: GET /groups/:id/epics
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param itemsPerPage the number of issues per page + * @return the Pager of all epics of the requested group and its subgroups + * @throws GitLabApiException if any exception occurs + */ + public Pager getEpics(final Object groupIdOrPath, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, Epic.class, itemsPerPage, null, "groups", getGroupIdOrPath(groupIdOrPath), "epics")); + } - /** - * Gets all epics of the requested group and its subgroups as a Stream. - * - *
GitLab Endpoint: GET /groups/:id/epics
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @return a Stream of all epics of the requested group and its subgroups - * @throws GitLabApiException if any exception occurs - */ - public Stream getEpicsStream(Object groupIdOrPath) throws GitLabApiException { - return (getEpics(groupIdOrPath, getDefaultPerPage()).stream()); - } + /** + * Gets all epics of the requested group and its subgroups as a Stream. + * + *
GitLab Endpoint: GET /groups/:id/epics
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @return a Stream of all epics of the requested group and its subgroups + * @throws GitLabApiException if any exception occurs + */ + public Stream getEpicsStream(final Object groupIdOrPath) throws GitLabApiException { + return (getEpics(groupIdOrPath, getDefaultPerPage()).stream()); + } - /** - * Gets all epics of the requested group and its subgroups. - * - *
GitLab Endpoint: GET /groups/:id/epics
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param authorId returns epics created by the given user id - * @param labels return epics matching a comma separated list of labels names. - * Label names from the epic group or a parent group can be used - * @param orderBy return epics ordered by CREATED_AT or UPDATED_AT. Default is CREATED_AT - * @param sortOrder return epics sorted in ASC or DESC order. Default is DESC - * @param search search epics against their title and description - * @return a list of matching epics of the requested group and its subgroups - * @throws GitLabApiException if any exception occurs - */ - public List getEpics(Object groupIdOrPath, Long authorId, String labels, EpicOrderBy orderBy, - SortOrder sortOrder, String search) throws GitLabApiException { - return (getEpics(groupIdOrPath, authorId, labels, orderBy, sortOrder, search, getDefaultPerPage()).all()); - } + /** + * Gets all epics of the requested group and its subgroups. + * + *
GitLab Endpoint: GET /groups/:id/epics
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param authorId returns epics created by the given user id + * @param labels return epics matching a comma separated list of labels names. Label names from + * the epic group or a parent group can be used + * @param orderBy return epics ordered by CREATED_AT or UPDATED_AT. Default is CREATED_AT + * @param sortOrder return epics sorted in ASC or DESC order. Default is DESC + * @param search search epics against their title and description + * @return a list of matching epics of the requested group and its subgroups + * @throws GitLabApiException if any exception occurs + */ + public List getEpics( + final Object groupIdOrPath, + final Long authorId, + final String labels, + final EpicOrderBy orderBy, + final SortOrder sortOrder, + final String search) + throws GitLabApiException { + return (getEpics( + groupIdOrPath, authorId, labels, orderBy, sortOrder, search, getDefaultPerPage()) + .all()); + } - /** - * Gets all epics of the requested group and its subgroups using the specified page and per page setting. - * - *
GitLab Endpoint: GET /groups/:id/epics
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param authorId returns epics created by the given user id - * @param labels return epics matching a comma separated list of labels names - * Label names from the epic group or a parent group can be used - * @param orderBy return epics ordered by CREATED_AT or UPDATED_AT. Default is CREATED_AT - * @param sortOrder return epics sorted in ASC or DESC order. Default is DESC - * @param search search epics against their title and description - * @param page the page to get - * @param perPage the number of issues per page - * @return a list of matching epics of the requested group and its subgroups in the specified range - * @throws GitLabApiException if any exception occurs - */ - public List getEpics(Object groupIdOrPath, Long authorId, String labels, - EpicOrderBy orderBy, SortOrder sortOrder, String search, int page, int perPage) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm(page, perPage) - .withParam("author_id", authorId) - .withParam("labels", labels) - .withParam("order_by", orderBy) - .withParam("sort", sortOrder) - .withParam("search", search); - Response response = get(Response.Status.OK, formData.asMap(), "groups", getGroupIdOrPath(groupIdOrPath), "epics"); - return (response.readEntity(new GenericType>() { })); - } + /** + * Gets all epics of the requested group and its subgroups using the specified page and per page + * setting. + * + *
GitLab Endpoint: GET /groups/:id/epics
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param authorId returns epics created by the given user id + * @param labels return epics matching a comma separated list of labels names Label names from the + * epic group or a parent group can be used + * @param orderBy return epics ordered by CREATED_AT or UPDATED_AT. Default is CREATED_AT + * @param sortOrder return epics sorted in ASC or DESC order. Default is DESC + * @param search search epics against their title and description + * @param page the page to get + * @param perPage the number of issues per page + * @return a list of matching epics of the requested group and its subgroups in the specified + * range + * @throws GitLabApiException if any exception occurs + */ + public List getEpics( + final Object groupIdOrPath, + final Long authorId, + final String labels, + final EpicOrderBy orderBy, + final SortOrder sortOrder, + final String search, + final int page, + final int perPage) + throws GitLabApiException { + final GitLabApiForm formData = + new GitLabApiForm(page, perPage) + .withParam("author_id", authorId) + .withParam("labels", labels) + .withParam("order_by", orderBy) + .withParam("sort", sortOrder) + .withParam("search", search); + final Response response = + get( + Response.Status.OK, + formData.asMap(), + "groups", + getGroupIdOrPath(groupIdOrPath), + "epics"); + return (response.readEntity(new GenericType>() {})); + } - /** - * Get a Pager of all epics of the requested group and its subgroups. - * - *
GitLab Endpoint: GET /groups/:id/epics
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param authorId returns epics created by the given user id - * @param labels return epics matching a comma separated list of labels names. - * Label names from the epic group or a parent group can be used - * @param itemsPerPage the number of issues per page - * @param orderBy return epics ordered by CREATED_AT or UPDATED_AT. Default is CREATED_AT - * @param sortOrder return epics sorted in ASC or DESC order. Default is DESC - * @param search search epics against their title and description - * @return the Pager of matching epics of the requested group and its subgroups - * @throws GitLabApiException if any exception occurs - */ - public Pager getEpics(Object groupIdOrPath, Long authorId, String labels, - EpicOrderBy orderBy, SortOrder sortOrder, String search, int itemsPerPage) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() - .withParam("author_id", authorId) - .withParam("labels", labels) - .withParam("order_by", orderBy) - .withParam("sort", sortOrder) - .withParam("search", search); - return (new Pager(this, Epic.class, itemsPerPage, formData.asMap(), "groups", getGroupIdOrPath(groupIdOrPath), "epics")); - } + /** + * Get a Pager of all epics of the requested group and its subgroups. + * + *
GitLab Endpoint: GET /groups/:id/epics
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param authorId returns epics created by the given user id + * @param labels return epics matching a comma separated list of labels names. Label names from + * the epic group or a parent group can be used + * @param itemsPerPage the number of issues per page + * @param orderBy return epics ordered by CREATED_AT or UPDATED_AT. Default is CREATED_AT + * @param sortOrder return epics sorted in ASC or DESC order. Default is DESC + * @param search search epics against their title and description + * @return the Pager of matching epics of the requested group and its subgroups + * @throws GitLabApiException if any exception occurs + */ + public Pager getEpics( + final Object groupIdOrPath, + final Long authorId, + final String labels, + final EpicOrderBy orderBy, + final SortOrder sortOrder, + final String search, + final int itemsPerPage) + throws GitLabApiException { + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("author_id", authorId) + .withParam("labels", labels) + .withParam("order_by", orderBy) + .withParam("sort", sortOrder) + .withParam("search", search); + return (new Pager( + this, + Epic.class, + itemsPerPage, + formData.asMap(), + "groups", + getGroupIdOrPath(groupIdOrPath), + "epics")); + } - /** - * Gets all epics of the requested group and its subgroups as a Stream. - * - *
GitLab Endpoint: GET /groups/:id/epics
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param authorId returns epics created by the given user id - * @param labels return epics matching a comma separated list of labels names. - * Label names from the epic group or a parent group can be used - * @param orderBy return epics ordered by CREATED_AT or UPDATED_AT. Default is CREATED_AT - * @param sortOrder return epics sorted in ASC or DESC order. Default is DESC - * @param search search epics against their title and description - * @return a Stream of matching epics of the requested group and its subgroups - * @throws GitLabApiException if any exception occurs - */ - public Stream getEpicsStream(Object groupIdOrPath, Long authorId, String labels, EpicOrderBy orderBy, - SortOrder sortOrder, String search) throws GitLabApiException { - return (getEpics(groupIdOrPath, authorId, labels, orderBy, sortOrder, search, getDefaultPerPage()).stream()); - } + /** + * Gets all epics of the requested group and its subgroups as a Stream. + * + *
GitLab Endpoint: GET /groups/:id/epics
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param authorId returns epics created by the given user id + * @param labels return epics matching a comma separated list of labels names. Label names from + * the epic group or a parent group can be used + * @param orderBy return epics ordered by CREATED_AT or UPDATED_AT. Default is CREATED_AT + * @param sortOrder return epics sorted in ASC or DESC order. Default is DESC + * @param search search epics against their title and description + * @return a Stream of matching epics of the requested group and its subgroups + * @throws GitLabApiException if any exception occurs + */ + public Stream getEpicsStream( + final Object groupIdOrPath, + final Long authorId, + final String labels, + final EpicOrderBy orderBy, + final SortOrder sortOrder, + final String search) + throws GitLabApiException { + return (getEpics( + groupIdOrPath, authorId, labels, orderBy, sortOrder, search, getDefaultPerPage()) + .stream()); + } - /** - * Get a single epic for the specified group. - * - *
GitLab Endpoint: GET /groups/:id/epics/:epic_iid
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param epicIid the IID of the epic to get - * @return an Epic instance for the specified Epic - * @throws GitLabApiException if any exception occurs - */ - public Epic getEpic(Object groupIdOrPath, Long epicIid) throws GitLabApiException { - Response response = get(Response.Status.OK, null, "groups", getGroupIdOrPath(groupIdOrPath), "epics", epicIid); - return (response.readEntity(Epic.class)); - } + /** + * Get a single epic for the specified group. + * + *
GitLab Endpoint: GET /groups/:id/epics/:epic_iid
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param epicIid the IID of the epic to get + * @return an Epic instance for the specified Epic + * @throws GitLabApiException if any exception occurs + */ + public Epic getEpic(final Object groupIdOrPath, final Long epicIid) throws GitLabApiException { + final Response response = + get(Response.Status.OK, null, "groups", getGroupIdOrPath(groupIdOrPath), "epics", epicIid); + return (response.readEntity(Epic.class)); + } - /** - * Get an Optional instance with the value for the specific Epic. - * - *
GitLab Endpoint: GET /groups/:id/epics/:epic_iid
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param epicIid the IID of the epic to get - * @return an Optional instance with the specified Epic as a value - */ - public Optional getOptionalEpic(Object groupIdOrPath, Long epicIid) { - try { - return (Optional.ofNullable(getEpic(groupIdOrPath, epicIid))); - } catch (GitLabApiException glae) { - return (GitLabApi.createOptionalFromException(glae)); - } + /** + * Get an Optional instance with the value for the specific Epic. + * + *
GitLab Endpoint: GET /groups/:id/epics/:epic_iid
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param epicIid the IID of the epic to get + * @return an Optional instance with the specified Epic as a value + */ + public Optional getOptionalEpic(final Object groupIdOrPath, final Long epicIid) { + try { + return (Optional.ofNullable(getEpic(groupIdOrPath, epicIid))); + } catch (final GitLabApiException glae) { + return (GitLabApi.createOptionalFromException(glae)); } + } - /** - * Creates a new epic. - * - *
GitLab Endpoint: POST /groups/:id/epics
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param title the title of the epic (required) - * @param labels comma separated list of labels (optional) - * @param description the description of the epic (optional) - * @param startDate the start date of the epic (optional) - * @param endDate the end date of the epic (optional) - * @return an Epic instance containing info on the newly created epic - * @throws GitLabApiException if any exception occurs - */ - public Epic createEpic(Object groupIdOrPath, String title, String labels, String description, - Date startDate, Date endDate) throws GitLabApiException { - Form formData = new GitLabApiForm() - .withParam("title", title, true) - .withParam("labels", labels) - .withParam("description", description) - .withParam("start_date", startDate) - .withParam("end_date", endDate); - Response response = post(Response.Status.CREATED, formData.asMap(), - "groups", getGroupIdOrPath(groupIdOrPath), "epics"); - return (response.readEntity(Epic.class)); - } + /** + * Creates a new epic. + * + *
GitLab Endpoint: POST /groups/:id/epics
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param title the title of the epic (required) + * @param labels comma separated list of labels (optional) + * @param description the description of the epic (optional) + * @param startDate the start date of the epic (optional) + * @param endDate the end date of the epic (optional) + * @return an Epic instance containing info on the newly created epic + * @throws GitLabApiException if any exception occurs + */ + public Epic createEpic( + final Object groupIdOrPath, + final String title, + final String labels, + final String description, + final Date startDate, + final Date endDate) + throws GitLabApiException { + final Form formData = + new GitLabApiForm() + .withParam("title", title, true) + .withParam("labels", labels) + .withParam("description", description) + .withParam("start_date", startDate) + .withParam("end_date", endDate); + final Response response = + post( + Response.Status.CREATED, + formData.asMap(), + "groups", + getGroupIdOrPath(groupIdOrPath), + "epics"); + return (response.readEntity(Epic.class)); + } - /** - * Creates a new epic using the information contained in the provided Epic instance. Only the following - * fields from the Epic instance are used: - *

-     *      title - the title of the epic (required)
-     *      labels - comma separated list of labels (optional)
-     *      description - the description of the epic (optional)
-     *      startDate - the start date of the epic (optional)
-     *      endDate - the end date of the epic (optional)
-     * 
- * - *
GitLab Endpoint: POST /groups/:id/epics
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param epic the Epic instance with information for the new epic - * @return an Epic instance containing info on the newly created epic - * @throws GitLabApiException if any exception occurs - */ - public Epic createEpic(Object groupIdOrPath, Epic epic) throws GitLabApiException { - Form formData = new GitLabApiForm() - .withParam("title", epic.getTitle(), true) - .withParam("labels", epic.getLabels()) - .withParam("description", epic.getDescription()) - .withParam("start_date", epic.getStartDate()) - .withParam("end_date", epic.getEndDate()); - Response response = post(Response.Status.CREATED, formData.asMap(), - "groups", getGroupIdOrPath(groupIdOrPath), "epics"); - return (response.readEntity(Epic.class)); - } + /** + * Creates a new epic using the information contained in the provided Epic instance. Only the + * following fields from the Epic instance are used: + * + *

+   *      title - the title of the epic (required)
+   *      labels - comma separated list of labels (optional)
+   *      description - the description of the epic (optional)
+   *      startDate - the start date of the epic (optional)
+   *      endDate - the end date of the epic (optional)
+   * 
+ * + *
GitLab Endpoint: POST /groups/:id/epics
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param epic the Epic instance with information for the new epic + * @return an Epic instance containing info on the newly created epic + * @throws GitLabApiException if any exception occurs + */ + public Epic createEpic(final Object groupIdOrPath, final Epic epic) throws GitLabApiException { + final Form formData = + new GitLabApiForm() + .withParam("title", epic.getTitle(), true) + .withParam("labels", epic.getLabels()) + .withParam("description", epic.getDescription()) + .withParam("start_date", epic.getStartDate()) + .withParam("end_date", epic.getEndDate()); + final Response response = + post( + Response.Status.CREATED, + formData.asMap(), + "groups", + getGroupIdOrPath(groupIdOrPath), + "epics"); + return (response.readEntity(Epic.class)); + } - /** - * Updates an existing epic. - * - *
GitLab Endpoint: PUT /groups/:id/epics/:epic_iid
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param epicIid the IID of the epic to update - * @param title the title of the epic (optional) - * @param labels comma separated list of labels (optional) - * @param description the description of the epic (optional) - * @param startDate the start date of the epic (optional) - * @param endDate the end date of the epic (optional) - * @return an Epic instance containing info on the newly created epic - * @throws GitLabApiException if any exception occurs - */ - public Epic updateEpic(Object groupIdOrPath, Long epicIid, String title, String labels, String description, - Date startDate, Date endDate) throws GitLabApiException { - Form formData = new GitLabApiForm() - .withParam("title", title, true) - .withParam("labels", labels) - .withParam("description", description) - .withParam("start_date", startDate) - .withParam("end_date", endDate); - Response response = put(Response.Status.OK, formData.asMap(), - "groups", getGroupIdOrPath(groupIdOrPath), "epics", epicIid); - return (response.readEntity(Epic.class)); - } + /** + * Updates an existing epic. + * + *
GitLab Endpoint: PUT /groups/:id/epics/:epic_iid
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param epicIid the IID of the epic to update + * @param title the title of the epic (optional) + * @param labels comma separated list of labels (optional) + * @param description the description of the epic (optional) + * @param startDate the start date of the epic (optional) + * @param endDate the end date of the epic (optional) + * @return an Epic instance containing info on the newly created epic + * @throws GitLabApiException if any exception occurs + */ + public Epic updateEpic( + final Object groupIdOrPath, + final Long epicIid, + final String title, + final String labels, + final String description, + final Date startDate, + final Date endDate) + throws GitLabApiException { + final Form formData = + new GitLabApiForm() + .withParam("title", title, true) + .withParam("labels", labels) + .withParam("description", description) + .withParam("start_date", startDate) + .withParam("end_date", endDate); + final Response response = + put( + Response.Status.OK, + formData.asMap(), + "groups", + getGroupIdOrPath(groupIdOrPath), + "epics", + epicIid); + return (response.readEntity(Epic.class)); + } - /** - * Updates an epic using the information contained in the provided Epic instance. Only the following - * fields from the Epic instance are used: - *

-     *      title - the title of the epic (optional)
-     *      labels - comma separated list of labels (optional)
-     *      description - the description of the epic (optional)
-     *      startDate - the start date of the epic (optional)
-     *      endDate - the end date of the epic (optional)
-     * 
- *
GitLab Endpoint: PUT /groups/:id/epics/:epic_iid
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param epicIid the IID of the epic to update - * @param epic the Epic instance with update information - * @return an Epic instance containing info on the updated epic - * @throws GitLabApiException if any exception occurs - */ - public Epic updateEpic(Object groupIdOrPath, Long epicIid, Epic epic) throws GitLabApiException { - Form formData = new GitLabApiForm() - .withParam("title", epic.getTitle(), true) - .withParam("labels", epic.getLabels()) - .withParam("description", epic.getDescription()) - .withParam("start_date", epic.getStartDate()) - .withParam("end_date", epic.getEndDate()); - Response response = put(Response.Status.OK, formData.asMap(), - "groups", getGroupIdOrPath(groupIdOrPath), "epics", epicIid); - return (response.readEntity(Epic.class)); - } + /** + * Updates an epic using the information contained in the provided Epic instance. Only the + * following fields from the Epic instance are used: + * + *

+   *      title - the title of the epic (optional)
+   *      labels - comma separated list of labels (optional)
+   *      description - the description of the epic (optional)
+   *      startDate - the start date of the epic (optional)
+   *      endDate - the end date of the epic (optional)
+   * 
+ * + *
GitLab Endpoint: PUT /groups/:id/epics/:epic_iid
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param epicIid the IID of the epic to update + * @param epic the Epic instance with update information + * @return an Epic instance containing info on the updated epic + * @throws GitLabApiException if any exception occurs + */ + public Epic updateEpic(final Object groupIdOrPath, final Long epicIid, final Epic epic) + throws GitLabApiException { + final Form formData = + new GitLabApiForm() + .withParam("title", epic.getTitle(), true) + .withParam("labels", epic.getLabels()) + .withParam("description", epic.getDescription()) + .withParam("start_date", epic.getStartDate()) + .withParam("end_date", epic.getEndDate()); + final Response response = + put( + Response.Status.OK, + formData.asMap(), + "groups", + getGroupIdOrPath(groupIdOrPath), + "epics", + epicIid); + return (response.readEntity(Epic.class)); + } - /** - * Deletes an epic. - * - *
GitLab Endpoint: DELETE /groups/:id/epics/:epic_iid
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param epicIid the IID of the epic to delete - * @throws GitLabApiException if any exception occurs - */ - public void deleteEpic(Object groupIdOrPath, Long epicIid) throws GitLabApiException { - delete(Response.Status.NO_CONTENT, null, "groups", getGroupIdOrPath(groupIdOrPath), "epics", epicIid); - } + /** + * Deletes an epic. + * + *
GitLab Endpoint: DELETE /groups/:id/epics/:epic_iid
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param epicIid the IID of the epic to delete + * @throws GitLabApiException if any exception occurs + */ + public void deleteEpic(final Object groupIdOrPath, final Long epicIid) throws GitLabApiException { + delete( + Response.Status.NO_CONTENT, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "epics", + epicIid); + } - /** - * Gets all issues that are assigned to an epic and the authenticated user has access to. - * - *
GitLab Endpoint: GET /groups/:id/epics/:epic_iid/issues
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param epicIid the IID of the epic to get issues for - * @return a list of all epic issues belonging to the specified epic - * @throws GitLabApiException if any exception occurs - */ - public List getEpicIssues(Object groupIdOrPath, Long epicIid) throws GitLabApiException { - return (getEpicIssues(groupIdOrPath, epicIid, getDefaultPerPage()).all()); - } + /** + * Gets all issues that are assigned to an epic and the authenticated user has access to. + * + *
GitLab Endpoint: GET /groups/:id/epics/:epic_iid/issues
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param epicIid the IID of the epic to get issues for + * @return a list of all epic issues belonging to the specified epic + * @throws GitLabApiException if any exception occurs + */ + public List getEpicIssues(final Object groupIdOrPath, final Long epicIid) + throws GitLabApiException { + return (getEpicIssues(groupIdOrPath, epicIid, getDefaultPerPage()).all()); + } - /** - * Gets all issues that are assigned to an epic and the authenticated user has access to - * using the specified page and per page setting. - * - *
GitLab Endpoint: GET /groups/:id/epics/:epic_iid/issues
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param epicIid the IID of the epic to get issues for - * @param page the page to get - * @param perPage the number of issues per page - * @return a list of all epic issues belonging to the specified epic in the specified range - * @throws GitLabApiException if any exception occurs - */ - public List getEpicIssues(Object groupIdOrPath, Long epicIid, int page, int perPage) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "groups", getGroupIdOrPath(groupIdOrPath), "epics", epicIid, "issues"); - return (response.readEntity(new GenericType>() { })); - } + /** + * Gets all issues that are assigned to an epic and the authenticated user has access to using the + * specified page and per page setting. + * + *
GitLab Endpoint: GET /groups/:id/epics/:epic_iid/issues
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param epicIid the IID of the epic to get issues for + * @param page the page to get + * @param perPage the number of issues per page + * @return a list of all epic issues belonging to the specified epic in the specified range + * @throws GitLabApiException if any exception occurs + */ + public List getEpicIssues( + final Object groupIdOrPath, final Long epicIid, final int page, final int perPage) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getPageQueryParams(page, perPage), + "groups", + getGroupIdOrPath(groupIdOrPath), + "epics", + epicIid, + "issues"); + return (response.readEntity(new GenericType>() {})); + } - /** - * Get a Pager of all issues that are assigned to an epic and the authenticated user has access to. - * - *
GitLab Endpoint: GET /groups/:id/epics/:epic_iid/issues
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param epicIid the IID of the epic to get issues for - * @param itemsPerPage the number of issues per page - * @return the Pager of all epic issues belonging to the specified epic - * @throws GitLabApiException if any exception occurs - */ - public Pager getEpicIssues(Object groupIdOrPath, Long epicIid, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, Epic.class, itemsPerPage, null, "groups", getGroupIdOrPath(groupIdOrPath), "epics", epicIid, "issues")); - } + /** + * Get a Pager of all issues that are assigned to an epic and the authenticated user has access + * to. + * + *
GitLab Endpoint: GET /groups/:id/epics/:epic_iid/issues
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param epicIid the IID of the epic to get issues for + * @param itemsPerPage the number of issues per page + * @return the Pager of all epic issues belonging to the specified epic + * @throws GitLabApiException if any exception occurs + */ + public Pager getEpicIssues( + final Object groupIdOrPath, final Long epicIid, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, + Epic.class, + itemsPerPage, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "epics", + epicIid, + "issues")); + } - /** - * Gets all issues that are assigned to an epic and the authenticated user has access to as a Stream. - * - *
GitLab Endpoint: GET /groups/:id/epics/:epic_iid/issues
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param epicIid the IID of the epic to get issues for - * @return a Stream of all epic issues belonging to the specified epic - * @throws GitLabApiException if any exception occurs - */ - public Stream getEpicIssuesStream(Object groupIdOrPath, Long epicIid) throws GitLabApiException { - return (getEpicIssues(groupIdOrPath, epicIid, getDefaultPerPage()).stream()); - } + /** + * Gets all issues that are assigned to an epic and the authenticated user has access to as a + * Stream. + * + *
GitLab Endpoint: GET /groups/:id/epics/:epic_iid/issues
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param epicIid the IID of the epic to get issues for + * @return a Stream of all epic issues belonging to the specified epic + * @throws GitLabApiException if any exception occurs + */ + public Stream getEpicIssuesStream(final Object groupIdOrPath, final Long epicIid) + throws GitLabApiException { + return (getEpicIssues(groupIdOrPath, epicIid, getDefaultPerPage()).stream()); + } - /** - * Creates an epic - issue association. If the issue in question belongs to another epic - * it is unassigned from that epic. - * - *
GitLab Endpoint: POST /groups/:id/epics/:epic_iid/issues/:issue_id
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param epicIid the Epic IID to assign the issue to - * @param issueIid the issue IID of the issue to assign to the epic - * @return an EpicIssue instance containing info on the newly assigned epic issue - * @throws GitLabApiException if any exception occurs - */ - public EpicIssue assignIssue(Object groupIdOrPath, Long epicIid, Long issueIid) throws GitLabApiException { - Response response = post(Response.Status.CREATED, (Form)null, - "groups", getGroupIdOrPath(groupIdOrPath), "epics", epicIid, "issues", issueIid); - return (response.readEntity(EpicIssue.class)); - } + /** + * Creates an epic - issue association. If the issue in question belongs to another epic it is + * unassigned from that epic. + * + *
GitLab Endpoint: POST /groups/:id/epics/:epic_iid/issues/:issue_id
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param epicIid the Epic IID to assign the issue to + * @param issueIid the issue IID of the issue to assign to the epic + * @return an EpicIssue instance containing info on the newly assigned epic issue + * @throws GitLabApiException if any exception occurs + */ + public EpicIssue assignIssue(final Object groupIdOrPath, final Long epicIid, final Long issueIid) + throws GitLabApiException { + final Response response = + post( + Response.Status.CREATED, + (Form) null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "epics", + epicIid, + "issues", + issueIid); + return (response.readEntity(EpicIssue.class)); + } - /** - * Remove an epic - issue association. - * - *
GitLab Endpoint: DELETE /groups/:id/epics/:epic_iid/issues/:issue_id
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param epicIid the Epic IID to remove the issue from - * @param issueIid the issue IID of the issue to remove from the epic - * @return an EpicIssue instance containing info on the removed issue - * @throws GitLabApiException if any exception occurs - */ - public EpicIssue removeIssue(Object groupIdOrPath, Long epicIid, Long issueIid) throws GitLabApiException { - Response response = delete(Response.Status.OK, null, - "groups", getGroupIdOrPath(groupIdOrPath), "epics", epicIid, "issues", issueIid); - return (response.readEntity(EpicIssue.class)); - } + /** + * Remove an epic - issue association. + * + *
GitLab Endpoint: DELETE /groups/:id/epics/:epic_iid/issues/:issue_id
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param epicIid the Epic IID to remove the issue from + * @param issueIid the issue IID of the issue to remove from the epic + * @return an EpicIssue instance containing info on the removed issue + * @throws GitLabApiException if any exception occurs + */ + public EpicIssue removeIssue(final Object groupIdOrPath, final Long epicIid, final Long issueIid) + throws GitLabApiException { + final Response response = + delete( + Response.Status.OK, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "epics", + epicIid, + "issues", + issueIid); + return (response.readEntity(EpicIssue.class)); + } - /** - * Updates an epic - issue association. - * - *
GitLab Endpoint: PUT /groups/:id/epics/:epic_iid/issues/:issue_id
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param epicIid the Epic IID that the issue is assigned to - * @param issueIid the issue IID to update - * @param moveBeforeId the ID of the issue - epic association that should be placed before the link in the question (optional) - * @param moveAfterId the ID of the issue - epic association that should be placed after the link in the question (optional) - * @return an EpicIssue instance containing info on the newly assigned epic issue - * @throws GitLabApiException if any exception occurs - */ - public EpicIssue updateIssue(Object groupIdOrPath, Long epicIid, Long issueIid, Long moveBeforeId, Long moveAfterId) throws GitLabApiException { - GitLabApiForm form = new GitLabApiForm() + /** + * Updates an epic - issue association. + * + *
GitLab Endpoint: PUT /groups/:id/epics/:epic_iid/issues/:issue_id
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param epicIid the Epic IID that the issue is assigned to + * @param issueIid the issue IID to update + * @param moveBeforeId the ID of the issue - epic association that should be placed before the + * link in the question (optional) + * @param moveAfterId the ID of the issue - epic association that should be placed after the link + * in the question (optional) + * @return an EpicIssue instance containing info on the newly assigned epic issue + * @throws GitLabApiException if any exception occurs + */ + public EpicIssue updateIssue( + final Object groupIdOrPath, + final Long epicIid, + final Long issueIid, + final Long moveBeforeId, + final Long moveAfterId) + throws GitLabApiException { + final GitLabApiForm form = + new GitLabApiForm() .withParam("move_before_id", moveBeforeId) .withParam("move_after_id", moveAfterId); - Response response = post(Response.Status.OK, form, - "groups", getGroupIdOrPath(groupIdOrPath), "epics", epicIid, "issues", issueIid); - return (response.readEntity(EpicIssue.class)); - } + final Response response = + post( + Response.Status.OK, + form, + "groups", + getGroupIdOrPath(groupIdOrPath), + "epics", + epicIid, + "issues", + issueIid); + return (response.readEntity(EpicIssue.class)); + } } diff --git a/src/main/java/org/gitlab4j/api/EventsApi.java b/src/main/java/org/gitlab4j/api/EventsApi.java index cea0e62e5..1a5bbc051 100644 --- a/src/main/java/org/gitlab4j/api/EventsApi.java +++ b/src/main/java/org/gitlab4j/api/EventsApi.java @@ -3,10 +3,8 @@ import java.util.Date; import java.util.List; import java.util.stream.Stream; - -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; - +import jakarta.ws.rs.core.GenericType; +import jakarta.ws.rs.core.Response; import org.gitlab4j.api.models.Event; /** @@ -14,7 +12,7 @@ */ public class EventsApi extends AbstractApi { - public EventsApi(GitLabApi gitLabApi) { + public EventsApi(final GitLabApi gitLabApi) { super(gitLabApi); } @@ -31,8 +29,8 @@ public EventsApi(GitLabApi gitLabApi) { * @return a list of events for the authenticated user and matching the supplied parameters * @throws GitLabApiException if any exception occurs */ - public List getAuthenticatedUserEvents(ActionType action, TargetType targetType, - Date before, Date after, SortOrder sortOrder) throws GitLabApiException { + public List getAuthenticatedUserEvents(final ActionType action, final TargetType targetType, + final Date before, final Date after, final SortOrder sortOrder) throws GitLabApiException { return (getAuthenticatedUserEvents(action, targetType, before, after, sortOrder, getDefaultPerPage()).all()); } @@ -49,8 +47,8 @@ public List getAuthenticatedUserEvents(ActionType action, TargetType targ * @return a list of events for the authenticated user and matching the supplied parameters * @throws GitLabApiException if any exception occurs */ - public List getAllAuthenticatedUserEvents(ActionType action, TargetType targetType, - Date before, Date after, SortOrder sortOrder) throws GitLabApiException { + public List getAllAuthenticatedUserEvents(final ActionType action, final TargetType targetType, + final Date before, final Date after, final SortOrder sortOrder) throws GitLabApiException { return (getAuthenticatedUserEvents(action, targetType, before, after, sortOrder, getDefaultPerPage(), EventScope.ALL).all()); } @@ -69,8 +67,8 @@ public List getAllAuthenticatedUserEvents(ActionType action, TargetType t * @return a list of events for the authenticated user and matching the supplied parameters * @throws GitLabApiException if any exception occurs */ - public List getAuthenticatedUserEvents(ActionType action, TargetType targetType, - Date before, Date after, SortOrder sortOrder, int page, int perPage) throws GitLabApiException { + public List getAuthenticatedUserEvents(final ActionType action, final TargetType targetType, + final Date before, final Date after, final SortOrder sortOrder, final int page, final int perPage) throws GitLabApiException { return (getAuthenticatedUserEvents(action, targetType, before, after, sortOrder, page, perPage, null)); } @@ -86,14 +84,14 @@ public List getAuthenticatedUserEvents(ActionType action, TargetType targ * @param sortOrder sort events in ASC or DESC order by created_at. Default is DESC, optional * @param page the page to get * @param perPage the number of projects per page - * @param scope include all events across a user’s projects, optional + * @param scope include all events across a user’s projects, optional * @return a list of events for the authenticated user and matching the supplied parameters * @throws GitLabApiException if any exception occurs */ - public List getAuthenticatedUserEvents(ActionType action, TargetType targetType, - Date before, Date after, SortOrder sortOrder, int page, int perPage, EventScope scope) throws GitLabApiException { + public List getAuthenticatedUserEvents(final ActionType action, final TargetType targetType, + final Date before, final Date after, final SortOrder sortOrder, final int page, final int perPage, final EventScope scope) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() + final GitLabApiForm formData = new GitLabApiForm() .withParam("action", action) .withParam("target_type", targetType != null ? targetType.toValue().toLowerCase() : null) .withParam("before", before) @@ -103,7 +101,7 @@ public List getAuthenticatedUserEvents(ActionType action, TargetType targ .withParam(PER_PAGE_PARAM, perPage) .withParam("scope", scope != null ? scope.toValue().toLowerCase() : null); - Response response = get(Response.Status.OK, formData.asMap(), "events"); + final Response response = get(Response.Status.OK, formData.asMap(), "events"); return (response.readEntity(new GenericType>() {})); } @@ -121,8 +119,8 @@ public List getAuthenticatedUserEvents(ActionType action, TargetType targ * @return a Pager of events for the authenticated user and matching the supplied parameters * @throws GitLabApiException if any exception occurs */ - public Pager getAuthenticatedUserEvents(ActionType action, TargetType targetType, Date before, Date after, - SortOrder sortOrder, int itemsPerPage) throws GitLabApiException { + public Pager getAuthenticatedUserEvents(final ActionType action, final TargetType targetType, final Date before, final Date after, + final SortOrder sortOrder, final int itemsPerPage) throws GitLabApiException { return (getAuthenticatedUserEvents(action, targetType, before, after, sortOrder, itemsPerPage, null)); } @@ -137,14 +135,14 @@ public Pager getAuthenticatedUserEvents(ActionType action, TargetType tar * @param after include only events created after a particular date, optional * @param sortOrder sort events in ASC or DESC order by created_at. Default is DESC, optional * @param itemsPerPage the number of Event instances that will be fetched per page - * @param scope include all events across a user’s projects, optional + * @param scope include all events across a user’s projects, optional * @return a Pager of events for the authenticated user and matching the supplied parameters * @throws GitLabApiException if any exception occurs */ - public Pager getAuthenticatedUserEvents(ActionType action, TargetType targetType, Date before, Date after, - SortOrder sortOrder, int itemsPerPage, EventScope scope) throws GitLabApiException { + public Pager getAuthenticatedUserEvents(final ActionType action, final TargetType targetType, final Date before, final Date after, + final SortOrder sortOrder, final int itemsPerPage, final EventScope scope) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() + final GitLabApiForm formData = new GitLabApiForm() .withParam("action", action) .withParam("target_type", targetType != null ? targetType.toValue().toLowerCase() : null) .withParam("before", before) @@ -168,8 +166,8 @@ public Pager getAuthenticatedUserEvents(ActionType action, TargetType tar * @return a Stream of events for the authenticated user and matching the supplied parameters * @throws GitLabApiException if any exception occurs */ - public Stream getAuthenticatedUserEventsStream(ActionType action, TargetType targetType, - Date before, Date after, SortOrder sortOrder) throws GitLabApiException { + public Stream getAuthenticatedUserEventsStream(final ActionType action, final TargetType targetType, + final Date before, final Date after, final SortOrder sortOrder) throws GitLabApiException { return (getAuthenticatedUserEvents(action, targetType, before, after, sortOrder, getDefaultPerPage(), null).stream()); } @@ -186,8 +184,8 @@ public Stream getAuthenticatedUserEventsStream(ActionType action, TargetT * @return a Stream of events for the authenticated user and matching the supplied parameters * @throws GitLabApiException if any exception occurs */ - public Stream getAllAuthenticatedUserEventsStream(ActionType action, TargetType targetType, - Date before, Date after, SortOrder sortOrder) throws GitLabApiException { + public Stream getAllAuthenticatedUserEventsStream(final ActionType action, final TargetType targetType, + final Date before, final Date after, final SortOrder sortOrder) throws GitLabApiException { return (getAuthenticatedUserEvents(action, targetType, before, after, sortOrder, getDefaultPerPage(), EventScope.ALL).stream()); } @@ -205,8 +203,8 @@ public Stream getAllAuthenticatedUserEventsStream(ActionType action, Targ * @return a list of events for the specified user and matching the supplied parameters * @throws GitLabApiException if any exception occurs */ - public List getUserEvents(Object userIdOrUsername, ActionType action, TargetType targetType, - Date before, Date after, SortOrder sortOrder) throws GitLabApiException { + public List getUserEvents(final Object userIdOrUsername, final ActionType action, final TargetType targetType, + final Date before, final Date after, final SortOrder sortOrder) throws GitLabApiException { return (getUserEvents(userIdOrUsername, action, targetType, before, after, sortOrder, getDefaultPerPage()).all()); } @@ -226,10 +224,10 @@ public List getUserEvents(Object userIdOrUsername, ActionType action, Tar * @return a list of events for the specified user and matching the supplied parameters * @throws GitLabApiException if any exception occurs */ - public List getUserEvents(Object userIdOrUsername, ActionType action, TargetType targetType, - Date before, Date after, SortOrder sortOrder, int page, int perPage) throws GitLabApiException { + public List getUserEvents(final Object userIdOrUsername, final ActionType action, final TargetType targetType, + final Date before, final Date after, final SortOrder sortOrder, final int page, final int perPage) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() + final GitLabApiForm formData = new GitLabApiForm() .withParam("action", action) .withParam("target_type", targetType != null ? targetType.toValue().toLowerCase() : null) .withParam("before", before) @@ -238,7 +236,7 @@ public List getUserEvents(Object userIdOrUsername, ActionType action, Tar .withParam(PAGE_PARAM, page) .withParam(PER_PAGE_PARAM, perPage); - Response response = get(Response.Status.OK, formData.asMap(), + final Response response = get(Response.Status.OK, formData.asMap(), "users", getUserIdOrUsername(userIdOrUsername), "events"); return (response.readEntity(new GenericType>() {})); } @@ -258,10 +256,10 @@ public List getUserEvents(Object userIdOrUsername, ActionType action, Tar * @return a Pager of events for the specified user and matching the supplied parameters * @throws GitLabApiException if any exception occurs */ - public Pager getUserEvents(Object userIdOrUsername, ActionType action, TargetType targetType, Date before, Date after, - SortOrder sortOrder, int itemsPerPage) throws GitLabApiException { + public Pager getUserEvents(final Object userIdOrUsername, final ActionType action, final TargetType targetType, final Date before, final Date after, + final SortOrder sortOrder, final int itemsPerPage) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() + final GitLabApiForm formData = new GitLabApiForm() .withParam("action", action) .withParam("target_type", targetType != null ? targetType.toValue().toLowerCase() : null) .withParam("before", before) @@ -286,8 +284,8 @@ public Pager getUserEvents(Object userIdOrUsername, ActionType action, Ta * @return a Stream of events for the specified user and matching the supplied parameters * @throws GitLabApiException if any exception occurs */ - public Stream getUserEventsStream(Object userIdOrUsername, ActionType action, TargetType targetType, - Date before, Date after, SortOrder sortOrder) throws GitLabApiException { + public Stream getUserEventsStream(final Object userIdOrUsername, final ActionType action, final TargetType targetType, + final Date before, final Date after, final SortOrder sortOrder) throws GitLabApiException { return (getUserEvents(userIdOrUsername, action, targetType, before, after, sortOrder, getDefaultPerPage()).stream()); } @@ -305,8 +303,8 @@ public Stream getUserEventsStream(Object userIdOrUsername, ActionType act * @return a list of events for the specified project and matching the supplied parameters * @throws GitLabApiException if any exception occurs */ - public List getProjectEvents(Object projectIdOrPath, ActionType action, TargetType targetType, - Date before, Date after, SortOrder sortOrder) throws GitLabApiException { + public List getProjectEvents(final Object projectIdOrPath, final ActionType action, final TargetType targetType, + final Date before, final Date after, final SortOrder sortOrder) throws GitLabApiException { return (getProjectEvents(projectIdOrPath, action, targetType, before, after, sortOrder, getDefaultPerPage()).all()); } @@ -326,10 +324,10 @@ public List getProjectEvents(Object projectIdOrPath, ActionType action, T * @return a list of events for the specified project and matching the supplied parameters * @throws GitLabApiException if any exception occurs */ - public List getProjectEvents(Object projectIdOrPath, ActionType action, TargetType targetType, - Date before, Date after, SortOrder sortOrder, int page, int perPage) throws GitLabApiException { + public List getProjectEvents(final Object projectIdOrPath, final ActionType action, final TargetType targetType, + final Date before, final Date after, final SortOrder sortOrder, final int page, final int perPage) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() + final GitLabApiForm formData = new GitLabApiForm() .withParam("action", action) .withParam("target_type", targetType != null ? targetType.toValue().toLowerCase() : null) .withParam("before", before) @@ -338,7 +336,7 @@ public List getProjectEvents(Object projectIdOrPath, ActionType action, T .withParam(PAGE_PARAM, page) .withParam(PER_PAGE_PARAM, perPage); - Response response = get(Response.Status.OK, formData.asMap(), + final Response response = get(Response.Status.OK, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "events"); return (response.readEntity(new GenericType>() {})); } @@ -358,10 +356,10 @@ public List getProjectEvents(Object projectIdOrPath, ActionType action, T * @return a Pager of events for the specified project and matching the supplied parameters * @throws GitLabApiException if any exception occurs */ - public Pager getProjectEvents(Object projectIdOrPath, ActionType action, TargetType targetType, Date before, Date after, - SortOrder sortOrder, int itemsPerPage) throws GitLabApiException { + public Pager getProjectEvents(final Object projectIdOrPath, final ActionType action, final TargetType targetType, final Date before, final Date after, + final SortOrder sortOrder, final int itemsPerPage) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() + final GitLabApiForm formData = new GitLabApiForm() .withParam("action", action) .withParam("target_type", targetType != null ? targetType.toValue().toLowerCase() : null) .withParam("before", before) @@ -386,8 +384,8 @@ public Pager getProjectEvents(Object projectIdOrPath, ActionType action, * @return a Stream of events for the specified project and matching the supplied parameters * @throws GitLabApiException if any exception occurs */ - public Stream getProjectEventsStream(Object projectIdOrPath, ActionType action, TargetType targetType, - Date before, Date after, SortOrder sortOrder) throws GitLabApiException { + public Stream getProjectEventsStream(final Object projectIdOrPath, final ActionType action, final TargetType targetType, + final Date before, final Date after, final SortOrder sortOrder) throws GitLabApiException { return (getProjectEvents(projectIdOrPath, action, targetType, before, after, sortOrder, getDefaultPerPage()).stream()); } } diff --git a/src/main/java/org/gitlab4j/api/ExternalStatusCheckApi.java b/src/main/java/org/gitlab4j/api/ExternalStatusCheckApi.java index e0d04a26d..b80c08e38 100644 --- a/src/main/java/org/gitlab4j/api/ExternalStatusCheckApi.java +++ b/src/main/java/org/gitlab4j/api/ExternalStatusCheckApi.java @@ -3,10 +3,8 @@ import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; - -import javax.ws.rs.core.Form; -import javax.ws.rs.core.Response; - +import jakarta.ws.rs.core.Form; +import jakarta.ws.rs.core.Response; import org.gitlab4j.api.models.ExternalStatusCheck; import org.gitlab4j.api.models.ExternalStatusCheckProtectedBranch; import org.gitlab4j.api.models.ExternalStatusCheckResult; @@ -14,262 +12,398 @@ import org.gitlab4j.api.models.ExternalStatusCheckStatus.Status; /** - * This class implements the client side API for the GitLab external status checks. - * See External Status Checks API for more information. + * This class implements the client side API for the GitLab external status checks. See External Status Checks API for more + * information. */ public class ExternalStatusCheckApi extends AbstractApi { - public ExternalStatusCheckApi(GitLabApi gitLabApi) { - super(gitLabApi); - } + public ExternalStatusCheckApi(final GitLabApi gitLabApi) { + super(gitLabApi); + } - /** - * Gets a list of all external status checks for a given project. - * - *
GitLab Endpoint: GET /projects/:id/external_status_checks
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @return a List of ExternalStatusCheck - * @throws GitLabApiException if any exception occurs - */ - public List getExternalStatusChecks(Object projectIdOrPath) throws GitLabApiException { - return (getExternalStatusChecks(projectIdOrPath, getDefaultPerPage()).all()); - } + /** + * Gets a list of all external status checks for a given project. + * + *
GitLab Endpoint: GET /projects/:id/external_status_checks
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @return a List of ExternalStatusCheck + * @throws GitLabApiException if any exception occurs + */ + public List getExternalStatusChecks(final Object projectIdOrPath) + throws GitLabApiException { + return (getExternalStatusChecks(projectIdOrPath, getDefaultPerPage()).all()); + } - /** - * Gets a Pager of all external status checks for a given project. - * - *
GitLab Endpoint: GET /projects/:id/external_status_checks
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param itemsPerPage the number of ExternalStatusCheck instances that will be fetched per page - * @return the Pager of ExternalStatusCheck instances - * @throws GitLabApiException if any exception occurs - */ - public Pager getExternalStatusChecks(Object projectIdOrPath, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, ExternalStatusCheck.class, itemsPerPage, null, - "projects", getProjectIdOrPath(projectIdOrPath), "external_status_checks")); - } + /** + * Gets a Pager of all external status checks for a given project. + * + *
GitLab Endpoint: GET /projects/:id/external_status_checks
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param itemsPerPage the number of ExternalStatusCheck instances that will be fetched per page + * @return the Pager of ExternalStatusCheck instances + * @throws GitLabApiException if any exception occurs + */ + public Pager getExternalStatusChecks( + final Object projectIdOrPath, final int itemsPerPage) throws GitLabApiException { + return (new Pager( + this, + ExternalStatusCheck.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "external_status_checks")); + } - /** - * Gets a Stream of all external status checks for a given project. - * - *
GitLab Endpoint: GET /projects/:id/external_status_checks
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @return a Stream of ExternalStatusCheck - * @throws GitLabApiException if any exception occurs - */ - public Stream getExternalStatusChecksStream(Object projectIdOrPath) throws GitLabApiException { - return (getExternalStatusChecks(projectIdOrPath, getDefaultPerPage()).stream()); - } + /** + * Gets a Stream of all external status checks for a given project. + * + *
GitLab Endpoint: GET /projects/:id/external_status_checks
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @return a Stream of ExternalStatusCheck + * @throws GitLabApiException if any exception occurs + */ + public Stream getExternalStatusChecksStream(final Object projectIdOrPath) + throws GitLabApiException { + return (getExternalStatusChecks(projectIdOrPath, getDefaultPerPage()).stream()); + } - /** - * Creates a new external status check. - * - *
GitLab Endpoint: POST /projects/:id/external_status_checks
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param name Display name of external status check (required) - * @param externalUrl URL of external status check resource (optional) - * @param protectedBranchIds IDs of protected branches to scope the rule by (optional) - * @return an ExternalStatusCheck instance containing info on the newly created externalStatusCheck - * @throws GitLabApiException if any exception occurs - */ - public ExternalStatusCheck createExternalStatusCheck(Object projectIdOrPath, String name, String externalUrl, List protectedBranchIds) throws GitLabApiException { - Form formData = new GitLabApiForm() - .withParam("name", name, true) - .withParam("external_url", externalUrl, true) - .withParam("protected_branch_ids", protectedBranchIds); - Response response = post(Response.Status.CREATED, formData.asMap(), - "projects", getProjectIdOrPath(projectIdOrPath), "external_status_checks"); - return (response.readEntity(ExternalStatusCheck.class)); - } + /** + * Creates a new external status check. + * + *
GitLab Endpoint: POST /projects/:id/external_status_checks
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param name Display name of external status check (required) + * @param externalUrl URL of external status check resource (optional) + * @param protectedBranchIds IDs of protected branches to scope the rule by (optional) + * @return an ExternalStatusCheck instance containing info on the newly created + * externalStatusCheck + * @throws GitLabApiException if any exception occurs + */ + public ExternalStatusCheck createExternalStatusCheck( + final Object projectIdOrPath, + final String name, + final String externalUrl, + final List protectedBranchIds) + throws GitLabApiException { + final Form formData = + new GitLabApiForm() + .withParam("name", name, true) + .withParam("external_url", externalUrl, true) + .withParam("protected_branch_ids", protectedBranchIds); + final Response response = + post( + Response.Status.CREATED, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "external_status_checks"); + return (response.readEntity(ExternalStatusCheck.class)); + } - /** - * Creates a new external status check using the information contained in the provided ExternalStatusCheck instance. Only the following - * fields from the ExternalStatusCheck instance are used: - *

-     *      name - Display name of external status check (required)
-     *      external url - URL of external status check resource (required)
-     *      protected branches - the id of the protected branches (optional)
-     * 
- * - *
GitLab Endpoint: POST /projects/:id/external_status_checks
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param externalStatusCheck the ExternalStatusCheck instance with information for the new external status check - * @return an ExternalStatusCheck instance containing info on the newly created externalStatusCheck - * @throws GitLabApiException if any exception occurs - */ - public ExternalStatusCheck createExternalStatusCheck(Object projectIdOrPath, ExternalStatusCheck externalStatusCheck) throws GitLabApiException { - List protectedBranchIds; - if(externalStatusCheck.getProtectedBranches() == null) { - protectedBranchIds = null; - } else { - protectedBranchIds = externalStatusCheck.getProtectedBranches().stream().map(ExternalStatusCheckProtectedBranch::getId).collect(Collectors.toList()); - } - Form formData = new GitLabApiForm() - .withParam("name", externalStatusCheck.getName(), true) - .withParam("external_url", externalStatusCheck.getExternalUrl(), true) - .withParam("protected_branch_ids", protectedBranchIds); - Response response = post(Response.Status.CREATED, formData.asMap(), - "projects", getProjectIdOrPath(projectIdOrPath), "external_status_checks"); - return (response.readEntity(ExternalStatusCheck.class)); + /** + * Creates a new external status check using the information contained in the provided + * ExternalStatusCheck instance. Only the following fields from the ExternalStatusCheck instance + * are used: + * + *

+   *      name - Display name of external status check (required)
+   *      external url - URL of external status check resource (required)
+   *      protected branches - the id of the protected branches (optional)
+   * 
+ * + *
GitLab Endpoint: POST /projects/:id/external_status_checks
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param externalStatusCheck the ExternalStatusCheck instance with information for the new + * external status check + * @return an ExternalStatusCheck instance containing info on the newly created + * externalStatusCheck + * @throws GitLabApiException if any exception occurs + */ + public ExternalStatusCheck createExternalStatusCheck( + final Object projectIdOrPath, final ExternalStatusCheck externalStatusCheck) + throws GitLabApiException { + final List protectedBranchIds; + if (externalStatusCheck.getProtectedBranches() == null) { + protectedBranchIds = null; + } else { + protectedBranchIds = + externalStatusCheck.getProtectedBranches().stream() + .map(ExternalStatusCheckProtectedBranch::getId) + .collect(Collectors.toList()); } + final Form formData = + new GitLabApiForm() + .withParam("name", externalStatusCheck.getName(), true) + .withParam("external_url", externalStatusCheck.getExternalUrl(), true) + .withParam("protected_branch_ids", protectedBranchIds); + final Response response = + post( + Response.Status.CREATED, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "external_status_checks"); + return (response.readEntity(ExternalStatusCheck.class)); + } - /** - * Updates an existing external status check. - * - *
GitLab Endpoint: PUT /projects/:id/external_status_checks/:check_id
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param checkId ID of an external status check to update (required) - * @param name Display name of external status check (optional) - * @param externalUrl URL of external status check resource (optional) - * @param protectedBranchIds IDs of protected branches to scope the rule by (optional) - * @return an ExternalStatusCheck instance containing info on the newly created ExternalStatusCheck - * @throws GitLabApiException if any exception occurs - */ - public ExternalStatusCheck updateExternalStatusCheck(Object projectIdOrPath, Long checkId, String name, String externalUrl, List protectedBranchIds) throws GitLabApiException { - Form formData = new GitLabApiForm() - .withParam("name", name) - .withParam("external_url", externalUrl) - .withParam("protected_branch_ids", protectedBranchIds); - Response response = put(Response.Status.OK, formData.asMap(), - "projects", getProjectIdOrPath(projectIdOrPath), "external_status_checks", checkId); - return (response.readEntity(ExternalStatusCheck.class)); - } + /** + * Updates an existing external status check. + * + *
GitLab Endpoint: PUT /projects/:id/external_status_checks/:check_id
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param checkId ID of an external status check to update (required) + * @param name Display name of external status check (optional) + * @param externalUrl URL of external status check resource (optional) + * @param protectedBranchIds IDs of protected branches to scope the rule by (optional) + * @return an ExternalStatusCheck instance containing info on the newly created + * ExternalStatusCheck + * @throws GitLabApiException if any exception occurs + */ + public ExternalStatusCheck updateExternalStatusCheck( + final Object projectIdOrPath, + final Long checkId, + final String name, + final String externalUrl, + final List protectedBranchIds) + throws GitLabApiException { + final Form formData = + new GitLabApiForm() + .withParam("name", name) + .withParam("external_url", externalUrl) + .withParam("protected_branch_ids", protectedBranchIds); + final Response response = + put( + Response.Status.OK, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "external_status_checks", + checkId); + return (response.readEntity(ExternalStatusCheck.class)); + } - /** - * Updates an external status check using the information contained in the provided ExternalStatusCheck instance. Only the following - * fields from the ExternalStatusCheck instance are used: - *

-     *      id - the id of the external status check (required)
-     *      name - Display name of external status check (optional)
-     *      external url - URL of external status check resource (optional)
-     *      protected branches - the id of the protected branches (optional)
-     * 
- *
GitLab Endpoint: PUT /projects/:id/external_status_checks/:check_id
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param externalStatusCheck the ExternalStatusCheck instance with update information - * @return an ExternalStatusCheck instance containing info on the updated ExternalStatusCheck - * @throws GitLabApiException if any exception occurs - */ - public ExternalStatusCheck updateExternalStatusCheck(Object projectIdOrPath, ExternalStatusCheck externalStatusCheck) throws GitLabApiException { - if (externalStatusCheck == null || externalStatusCheck.getId() == null) { - throw new GitLabApiException("the specified external status check is null or has no id"); - } - List protectedBranchIds = getProtectedBranchIds(externalStatusCheck); - Form formData = new GitLabApiForm() - .withParam("name", externalStatusCheck.getName()) - .withParam("external_url", externalStatusCheck.getExternalUrl()) - .withParam("protected_branch_ids", protectedBranchIds); - Response response = put(Response.Status.OK, formData.asMap(), - "projects", getProjectIdOrPath(projectIdOrPath), "external_status_checks", externalStatusCheck.getId()); - return (response.readEntity(ExternalStatusCheck.class)); + /** + * Updates an external status check using the information contained in the provided + * ExternalStatusCheck instance. Only the following fields from the ExternalStatusCheck instance + * are used: + * + *

+   *      id - the id of the external status check (required)
+   *      name - Display name of external status check (optional)
+   *      external url - URL of external status check resource (optional)
+   *      protected branches - the id of the protected branches (optional)
+   * 
+ * + *
GitLab Endpoint: PUT /projects/:id/external_status_checks/:check_id
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param externalStatusCheck the ExternalStatusCheck instance with update information + * @return an ExternalStatusCheck instance containing info on the updated ExternalStatusCheck + * @throws GitLabApiException if any exception occurs + */ + public ExternalStatusCheck updateExternalStatusCheck( + final Object projectIdOrPath, final ExternalStatusCheck externalStatusCheck) + throws GitLabApiException { + if (externalStatusCheck == null || externalStatusCheck.getId() == null) { + throw new GitLabApiException("the specified external status check is null or has no id"); } + final List protectedBranchIds = getProtectedBranchIds(externalStatusCheck); + final Form formData = + new GitLabApiForm() + .withParam("name", externalStatusCheck.getName()) + .withParam("external_url", externalStatusCheck.getExternalUrl()) + .withParam("protected_branch_ids", protectedBranchIds); + final Response response = + put( + Response.Status.OK, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "external_status_checks", + externalStatusCheck.getId()); + return (response.readEntity(ExternalStatusCheck.class)); + } - private List getProtectedBranchIds(ExternalStatusCheck externalStatusCheck) { - if(externalStatusCheck.getProtectedBranches() == null) { - return null; - } - return externalStatusCheck.getProtectedBranches().stream().map(ExternalStatusCheckProtectedBranch::getId).collect(Collectors.toList()); + private List getProtectedBranchIds(final ExternalStatusCheck externalStatusCheck) { + if (externalStatusCheck.getProtectedBranches() == null) { + return null; } + return externalStatusCheck.getProtectedBranches().stream() + .map(ExternalStatusCheckProtectedBranch::getId) + .collect(Collectors.toList()); + } - /** - * Deletes an external status check. - * - *
GitLab Endpoint: DELETE /projects/:id/external_status_checks/:check_id
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param checkId ID of an external status check - * @throws GitLabApiException if any exception occurs - */ - public void deleteExternalStatusCheck(Object projectIdOrPath, Long checkId) throws GitLabApiException { - delete(Response.Status.NO_CONTENT, null, "projects", getProjectIdOrPath(projectIdOrPath), "external_status_checks", checkId); - } + /** + * Deletes an external status check. + * + *
GitLab Endpoint: DELETE /projects/:id/external_status_checks/:check_id
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param checkId ID of an external status check + * @throws GitLabApiException if any exception occurs + */ + public void deleteExternalStatusCheck(final Object projectIdOrPath, final Long checkId) + throws GitLabApiException { + delete( + Response.Status.NO_CONTENT, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "external_status_checks", + checkId); + } - /** - * Gets a list of all statuses of the external status checks for a given merge request. - * - *
GitLab Endpoint: GET /projects/:id/merge_requests/:merge_request_iid/status_checks
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param mergeRequestIid the merge request IID to get the statuses - * @return a List of ExternalStatusCheckStatus - * @throws GitLabApiException if any exception occurs - */ - public List getExternalStatusCheckStatuses(Object projectIdOrPath, Long mergeRequestIid) throws GitLabApiException { - return (getExternalStatusCheckStatuses(projectIdOrPath, mergeRequestIid, getDefaultPerPage()).all()); - } + /** + * Gets a list of all statuses of the external status checks for a given merge request. + * + *
+   * GitLab Endpoint: GET /projects/:id/merge_requests/:merge_request_iid/status_checks
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param mergeRequestIid the merge request IID to get the statuses + * @return a List of ExternalStatusCheckStatus + * @throws GitLabApiException if any exception occurs + */ + public List getExternalStatusCheckStatuses( + final Object projectIdOrPath, final Long mergeRequestIid) throws GitLabApiException { + return (getExternalStatusCheckStatuses(projectIdOrPath, mergeRequestIid, getDefaultPerPage()) + .all()); + } - /** - * Gets a Pager of all statuses of the external status checks for a given merge request. - * - *
GitLab Endpoint: GET /projects/:id/merge_requests/:merge_request_iid/status_checks
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param mergeRequestIid the merge request IID to get the statuses - * @param itemsPerPage the number of ExternalStatusCheckStatus instances that will be fetched per page - * @return the Pager of ExternalStatusCheckStatus instances - * @throws GitLabApiException if any exception occurs - */ - public Pager getExternalStatusCheckStatuses(Object projectIdOrPath, Long mergeRequestIid, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, ExternalStatusCheckStatus.class, itemsPerPage, null, - "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "status_checks")); - } + /** + * Gets a Pager of all statuses of the external status checks for a given merge request. + * + *
+   * GitLab Endpoint: GET /projects/:id/merge_requests/:merge_request_iid/status_checks
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param mergeRequestIid the merge request IID to get the statuses + * @param itemsPerPage the number of ExternalStatusCheckStatus instances that will be fetched per + * page + * @return the Pager of ExternalStatusCheckStatus instances + * @throws GitLabApiException if any exception occurs + */ + public Pager getExternalStatusCheckStatuses( + final Object projectIdOrPath, final Long mergeRequestIid, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, + ExternalStatusCheckStatus.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "merge_requests", + mergeRequestIid, + "status_checks")); + } - /** - * Gets a Stream of all statuses of the external status checks for a given merge request. - * - *
GitLab Endpoint: GET /projects/:id/merge_requests/:merge_request_iid/status_checks
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param mergeRequestIid the merge request IID to get the statuses - * @return a Stream of ExternalStatusCheckStatus - * @throws GitLabApiException if any exception occurs - */ - public Stream getExternalStatusCheckStatusesStream(Object projectIdOrPath, Long mergeRequestIid) throws GitLabApiException { - return (getExternalStatusCheckStatuses(projectIdOrPath, mergeRequestIid, getDefaultPerPage()).stream()); - } + /** + * Gets a Stream of all statuses of the external status checks for a given merge request. + * + *
+   * GitLab Endpoint: GET /projects/:id/merge_requests/:merge_request_iid/status_checks
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param mergeRequestIid the merge request IID to get the statuses + * @return a Stream of ExternalStatusCheckStatus + * @throws GitLabApiException if any exception occurs + */ + public Stream getExternalStatusCheckStatusesStream( + final Object projectIdOrPath, final Long mergeRequestIid) throws GitLabApiException { + return (getExternalStatusCheckStatuses(projectIdOrPath, mergeRequestIid, getDefaultPerPage()) + .stream()); + } - /** - * Set the status of an external status check for a given merge request. - * - *
GitLab Endpoint: POST /projects/:id/merge_requests/:merge_request_iid/status_check_responses
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param mergeRequestIid the merge request IID to get the statuses - * @param sha the commit SHA to set the status for (required) - * @param externalStatusCheckId ID of an external status check (required) - * @param status the status to set (optional) - * @return an ExternalStatusCheckResult instance containing info on the newly created status - * @throws GitLabApiException if any exception occurs - */ - public ExternalStatusCheckResult setStatusOfExternalStatusCheck(Object projectIdOrPath, Long mergeRequestIid, String sha, Long externalStatusCheckId, Status status) throws GitLabApiException { - Form formData = new GitLabApiForm() - .withParam("sha", sha) - .withParam("external_status_check_id", externalStatusCheckId) - .withParam("status", status); - Response response = post(Response.Status.CREATED, formData.asMap(), - "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "status_check_responses"); - return (response.readEntity(ExternalStatusCheckResult.class)); - } - - /** - * Retry the specified failed external status check for a single merge request. Even though the merge request hasn’t changed, this endpoint resends the current state of merge request to the defined external service. - * - *
GitLab Endpoint: POST /projects/:id/merge_requests/:merge_request_iid/status_checks/:external_status_check_id/retry
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param mergeRequestIid the merge request IID to get the statuses - * @param externalStatusCheckId ID of an external status check - * @throws GitLabApiException if any exception occurs - */ - public void retryExternalStatusCheck(Object projectIdOrPath, Long mergeRequestIid, Long externalStatusCheckId) throws GitLabApiException { - post(Response.Status.ACCEPTED, (Form)null, "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "status_checks", externalStatusCheckId, "retry"); - } + /** + * Set the status of an external status check for a given merge request. + * + *
+   * GitLab Endpoint: POST /projects/:id/merge_requests/:merge_request_iid/status_check_responses
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param mergeRequestIid the merge request IID to get the statuses + * @param sha the commit SHA to set the status for (required) + * @param externalStatusCheckId ID of an external status check (required) + * @param status the status to set (optional) + * @return an ExternalStatusCheckResult instance containing info on the newly created status + * @throws GitLabApiException if any exception occurs + */ + public ExternalStatusCheckResult setStatusOfExternalStatusCheck( + final Object projectIdOrPath, + final Long mergeRequestIid, + final String sha, + final Long externalStatusCheckId, + final Status status) + throws GitLabApiException { + final Form formData = + new GitLabApiForm() + .withParam("sha", sha) + .withParam("external_status_check_id", externalStatusCheckId) + .withParam("status", status); + final Response response = + post( + Response.Status.CREATED, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "merge_requests", + mergeRequestIid, + "status_check_responses"); + return (response.readEntity(ExternalStatusCheckResult.class)); + } + /** + * Retry the specified failed external status check for a single merge request. Even though the + * merge request hasn’t changed, this endpoint resends the current state of merge request to the + * defined external service. + * + *
+   * GitLab Endpoint: POST /projects/:id/merge_requests/:merge_request_iid/status_checks/:external_status_check_id/retry
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param mergeRequestIid the merge request IID to get the statuses + * @param externalStatusCheckId ID of an external status check + * @throws GitLabApiException if any exception occurs + */ + public void retryExternalStatusCheck( + final Object projectIdOrPath, final Long mergeRequestIid, final Long externalStatusCheckId) + throws GitLabApiException { + post( + Response.Status.ACCEPTED, + (Form) null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "merge_requests", + mergeRequestIid, + "status_checks", + externalStatusCheckId, + "retry"); + } } diff --git a/src/main/java/org/gitlab4j/api/GitLabApi.java b/src/main/java/org/gitlab4j/api/GitLabApi.java index ecc65d3d1..6409c172a 100644 --- a/src/main/java/org/gitlab4j/api/GitLabApi.java +++ b/src/main/java/org/gitlab4j/api/GitLabApi.java @@ -8,10 +8,8 @@ import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; import org.gitlab4j.api.Constants.TokenType; import org.gitlab4j.api.models.OauthTokenResponse; import org.gitlab4j.api.models.User; @@ -26,1741 +24,1928 @@ */ public class GitLabApi implements AutoCloseable { - private final static Logger LOGGER = Logger.getLogger(GitLabApi.class.getName()); - - /** GitLab4J default per page. GitLab will ignore anything over 100. */ - public static final int DEFAULT_PER_PAGE = 96; - - /** Specifies the version of the GitLab API to communicate with. */ - public enum ApiVersion { - V3, V4; - - public String getApiNamespace() { - return ("/api/" + name().toLowerCase()); - } - } - - // Used to keep track of GitLabApiExceptions on calls that return Optional - private static final Map optionalExceptionMap = - Collections.synchronizedMap(new WeakHashMap()); - - GitLabApiClient apiClient; - private ApiVersion apiVersion; - private String gitLabServerUrl; - private Map clientConfigProperties; - private int defaultPerPage = DEFAULT_PER_PAGE; - - private ApplicationsApi applicationsApi; - private ApplicationSettingsApi applicationSettingsApi; - private AuditEventApi auditEventApi; - private AwardEmojiApi awardEmojiApi; - private BoardsApi boardsApi; - private CommitsApi commitsApi; - private ContainerRegistryApi containerRegistryApi; - private DiscussionsApi discussionsApi; - private DeployKeysApi deployKeysApi; - private DeploymentsApi deploymentsApi; - private DeployTokensApi deployTokensApi; - private EnvironmentsApi environmentsApi; - private EpicsApi epicsApi; - private EventsApi eventsApi; - private ExternalStatusCheckApi externalStatusCheckApi; - private GroupApi groupApi; - private HealthCheckApi healthCheckApi; - private ImportExportApi importExportApi; - private IssuesApi issuesApi; - private JobApi jobApi; - private LabelsApi labelsApi; - private LicenseApi licenseApi; - private LicenseTemplatesApi licenseTemplatesApi; - private MarkdownApi markdownApi; - private MergeRequestApi mergeRequestApi; - private MilestonesApi milestonesApi; - private NamespaceApi namespaceApi; - private NotesApi notesApi; - private NotificationSettingsApi notificationSettingsApi; - private PackagesApi packagesApi; - private PipelineApi pipelineApi; - private ProjectApi projectApi; - private ProtectedBranchesApi protectedBranchesApi; - private ReleasesApi releasesApi; - private RepositoryApi repositoryApi; - private RepositoryFileApi repositoryFileApi; - private ResourceLabelEventsApi resourceLabelEventsApi; - private ResourceStateEventsApi resourceStateEventsApi; - private RunnersApi runnersApi; - private SearchApi searchApi; - private ServicesApi servicesApi; - private SnippetsApi snippetsApi; - private SystemHooksApi systemHooksApi; - private TagsApi tagsApi; - private TodosApi todosApi; - private UserApi userApi; - private WikisApi wikisApi; - private KeysApi keysApi; - - /** - * Get the GitLab4J shared Logger instance. - * - * @return the GitLab4J shared Logger instance - */ - public static final Logger getLogger() { - return (LOGGER); - } - - /** - * Constructs a GitLabApi instance set up to interact with the GitLab server - * using GitLab API version 4. This is the primary way to authenticate with - * the GitLab REST API. - * - * @param hostUrl the URL of the GitLab server - * @param personalAccessToken the private token to use for access to the API - */ - public GitLabApi(String hostUrl, String personalAccessToken) { - this(ApiVersion.V4, hostUrl, personalAccessToken, null); - } - - /** - * Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API version 4. - * - * @param hostUrl the URL of the GitLab server - * @param personalAccessToken the private token to use for access to the API - * @param secretToken use this token to validate received payloads - */ - public GitLabApi(String hostUrl, String personalAccessToken, String secretToken) { - this(ApiVersion.V4, hostUrl, TokenType.PRIVATE, personalAccessToken, secretToken); - } - - /** - *

Logs into GitLab using OAuth2 with the provided {@code username} and {@code password}, - * and creates a new {@code GitLabApi} instance using returned access token.

- * - * @param url GitLab URL - * @param username user name for which private token should be obtained - * @param password a CharSequence containing the password for a given {@code username} - * @return new {@code GitLabApi} instance configured for a user-specific token - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public static GitLabApi oauth2Login(String url, String username, CharSequence password) throws GitLabApiException { - return (GitLabApi.oauth2Login(ApiVersion.V4, url, username, password, null, null, false)); - } - - /** - *

Logs into GitLab using OAuth2 with the provided {@code username} and {@code password}, - * and creates a new {@code GitLabApi} instance using returned access token.

- * - * @param url GitLab URL - * @param username user name for which private token should be obtained - * @param password a char array holding the password for a given {@code username} - * @return new {@code GitLabApi} instance configured for a user-specific token - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public static GitLabApi oauth2Login(String url, String username, char[] password) throws GitLabApiException { - - try (SecretString secretPassword = new SecretString(password)) { - return (GitLabApi.oauth2Login(ApiVersion.V4, url, username, secretPassword, null, null, false)); - } - } - - /** - *

Logs into GitLab using OAuth2 with the provided {@code username} and {@code password}, - * and creates a new {@code GitLabApi} instance using returned access token.

- * - * @param url GitLab URL - * @param username user name for which private token should be obtained - * @param password a CharSequence containing the password for a given {@code username} - * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors - * @return new {@code GitLabApi} instance configured for a user-specific token - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public static GitLabApi oauth2Login(String url, String username, CharSequence password, boolean ignoreCertificateErrors) throws GitLabApiException { - return (GitLabApi.oauth2Login(ApiVersion.V4, url, username, password, null, null, ignoreCertificateErrors)); - } - - /** - *

Logs into GitLab using OAuth2 with the provided {@code username} and {@code password}, - * and creates a new {@code GitLabApi} instance using returned access token.

- * - * @param url GitLab URL - * @param username user name for which private token should be obtained - * @param password a char array holding the password for a given {@code username} - * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors - * @return new {@code GitLabApi} instance configured for a user-specific token - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public static GitLabApi oauth2Login(String url, String username, char[] password, boolean ignoreCertificateErrors) throws GitLabApiException { - - try (SecretString secretPassword = new SecretString(password)) { - return (GitLabApi.oauth2Login(ApiVersion.V4, url, username, secretPassword, null, null, ignoreCertificateErrors)); - } - } - - /** - *

Logs into GitLab using OAuth2 with the provided {@code username} and {@code password}, - * and creates a new {@code GitLabApi} instance using returned access token.

- * - * @param url GitLab URL - * @param username user name for which private token should be obtained - * @param password a CharSequence containing the password for a given {@code username} - * @param secretToken use this token to validate received payloads - * @param clientConfigProperties Map instance with additional properties for the Jersey client connection - * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors - * @return new {@code GitLabApi} instance configured for a user-specific token - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public static GitLabApi oauth2Login(String url, String username, CharSequence password, String secretToken, - Map clientConfigProperties, boolean ignoreCertificateErrors) throws GitLabApiException { - return (GitLabApi.oauth2Login(ApiVersion.V4, url, username, password, secretToken, clientConfigProperties, ignoreCertificateErrors)); - } - - /** - *

Logs into GitLab using OAuth2 with the provided {@code username} and {@code password}, - * and creates a new {@code GitLabApi} instance using returned access token.

- * - * @param url GitLab URL - * @param username user name for which private token should be obtained - * @param password a char array holding the password for a given {@code username} - * @param secretToken use this token to validate received payloads - * @param clientConfigProperties Map instance with additional properties for the Jersey client connection - * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors - * @return new {@code GitLabApi} instance configured for a user-specific token - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public static GitLabApi oauth2Login(String url, String username, char[] password, String secretToken, - Map clientConfigProperties, boolean ignoreCertificateErrors) throws GitLabApiException { - - try (SecretString secretPassword = new SecretString(password)) { - return (GitLabApi.oauth2Login(ApiVersion.V4, url, username, secretPassword, - secretToken, clientConfigProperties, ignoreCertificateErrors)); - } - } - - /** - *

Logs into GitLab using OAuth2 with the provided {@code username} and {@code password}, - * and creates a new {@code GitLabApi} instance using returned access token.

- * - * @param url GitLab URL - * @param apiVersion the ApiVersion specifying which version of the API to use - * @param username user name for which private token should be obtained - * @param password a char array holding the password for a given {@code username} - * @param secretToken use this token to validate received payloads - * @param clientConfigProperties Map instance with additional properties for the Jersey client connection - * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors - * @return new {@code GitLabApi} instance configured for a user-specific token - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public static GitLabApi oauth2Login(ApiVersion apiVersion, String url, String username, char[] password, String secretToken, - Map clientConfigProperties, boolean ignoreCertificateErrors) throws GitLabApiException { - - try (SecretString secretPassword = new SecretString(password)) { - return (GitLabApi.oauth2Login(apiVersion, url, username, secretPassword, - secretToken, clientConfigProperties, ignoreCertificateErrors)); - } - } - - /** - *

Logs into GitLab using OAuth2 with the provided {@code username} and {@code password}, - * and creates a new {@code GitLabApi} instance using returned access token.

- * - * @param url GitLab URL - * @param apiVersion the ApiVersion specifying which version of the API to use - * @param username user name for which private token should be obtained - * @param password password for a given {@code username} - * @param secretToken use this token to validate received payloads - * @param clientConfigProperties Map instance with additional properties for the Jersey client connection - * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors - * @return new {@code GitLabApi} instance configured for a user-specific token - * @throws GitLabApiException GitLabApiException if any exception occurs during execution - */ - public static GitLabApi oauth2Login(ApiVersion apiVersion, String url, String username, CharSequence password, - String secretToken, Map clientConfigProperties, boolean ignoreCertificateErrors) throws GitLabApiException { - - if (username == null || username.trim().length() == 0) { - throw new IllegalArgumentException("both username and email cannot be empty or null"); - } - - // Create a GitLabApi instance set up to be used to do an OAUTH2 login. - GitLabApi gitLabApi = new GitLabApi(apiVersion, url, (String)null); - gitLabApi.apiClient.setHostUrlToBaseUrl(); - - if (ignoreCertificateErrors) { - gitLabApi.setIgnoreCertificateErrors(true); - } - - class Oauth2Api extends AbstractApi { - Oauth2Api(GitLabApi gitlabApi) { - super(gitlabApi); - } - } - - try (Oauth2LoginStreamingOutput stream = new Oauth2LoginStreamingOutput(username, password)) { - - Response response = new Oauth2Api(gitLabApi).post(Response.Status.OK, stream, MediaType.APPLICATION_JSON, "oauth", "token"); - OauthTokenResponse oauthToken = response.readEntity(OauthTokenResponse.class); - gitLabApi = new GitLabApi(apiVersion, url, TokenType.OAUTH2_ACCESS, oauthToken.getAccessToken(), secretToken, clientConfigProperties); - if (ignoreCertificateErrors) { - gitLabApi.setIgnoreCertificateErrors(true); - } - - return (gitLabApi); - } - } - - /** - * Constructs a GitLabApi instance set up to interact with the GitLab server using the specified GitLab API version. - * - * @param apiVersion the ApiVersion specifying which version of the API to use - * @param hostUrl the URL of the GitLab server - * @param personalAccessToken the private token to use for access to the API - */ - public GitLabApi(ApiVersion apiVersion, String hostUrl, String personalAccessToken) { - this(apiVersion, hostUrl, personalAccessToken, null); - } - - /** - * Constructs a GitLabApi instance set up to interact with the GitLab server using the specified GitLab API version. - * - * @param apiVersion the ApiVersion specifying which version of the API to use - * @param hostUrl the URL of the GitLab server - * @param personalAccessToken the private token to use for access to the API - * @param secretToken use this token to validate received payloads - */ - public GitLabApi(ApiVersion apiVersion, String hostUrl, String personalAccessToken, String secretToken) { - this(apiVersion, hostUrl, personalAccessToken, secretToken, null); - } - - /** - * Constructs a GitLabApi instance set up to interact with the GitLab server using the specified GitLab API version. - * - * @param apiVersion the ApiVersion specifying which version of the API to use - * @param hostUrl the URL of the GitLab server - * @param tokenType the type of auth the token is for, PRIVATE or ACCESS - * @param authToken the token to use for access to the API - */ - public GitLabApi(ApiVersion apiVersion, String hostUrl, TokenType tokenType, String authToken) { - this(apiVersion, hostUrl, tokenType, authToken, null); - } - - /** - * Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API version 4. - * - * @param hostUrl the URL of the GitLab server - * @param tokenType the type of auth the token is for, PRIVATE or ACCESS - * @param authToken the token to use for access to the API - */ - public GitLabApi(String hostUrl, TokenType tokenType, String authToken) { - this(ApiVersion.V4, hostUrl, tokenType, authToken, null); - } - - /** - * Constructs a GitLabApi instance set up to interact with the GitLab server using the specified GitLab API version. - * - * @param apiVersion the ApiVersion specifying which version of the API to use - * @param hostUrl the URL of the GitLab server - * @param tokenType the type of auth the token is for, PRIVATE or ACCESS - * @param authToken the token to use for access to the API - * @param secretToken use this token to validate received payloads - */ - public GitLabApi(ApiVersion apiVersion, String hostUrl, TokenType tokenType, String authToken, String secretToken) { - this(apiVersion, hostUrl, tokenType, authToken, secretToken, null); - } - - /** - * Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API version 4. - * - * @param hostUrl the URL of the GitLab server - * @param tokenType the type of auth the token is for, PRIVATE or ACCESS - * @param authToken the token to use for access to the API - * @param secretToken use this token to validate received payloads - */ - public GitLabApi(String hostUrl, TokenType tokenType, String authToken, String secretToken) { - this(ApiVersion.V4, hostUrl, tokenType, authToken, secretToken); - } - - /** - * Constructs a GitLabApi instance set up to interact with the GitLab server specified by GitLab API version. - * - * @param apiVersion the ApiVersion specifying which version of the API to use - * @param hostUrl the URL of the GitLab server - * @param personalAccessToken to private token to use for access to the API - * @param secretToken use this token to validate received payloads - * @param clientConfigProperties Map instance with additional properties for the Jersey client connection - */ - public GitLabApi(ApiVersion apiVersion, String hostUrl, String personalAccessToken, String secretToken, Map clientConfigProperties) { - this(apiVersion, hostUrl, TokenType.PRIVATE, personalAccessToken, secretToken, clientConfigProperties); - } - - /** - * Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API version 4. - * - * @param hostUrl the URL of the GitLab server - * @param tokenType the type of auth the token is for, PRIVATE or ACCESS - * @param authToken the token to use for access to the API - * @param secretToken use this token to validate received payloads - * @param clientConfigProperties Map instance with additional properties for the Jersey client connection - */ - public GitLabApi(String hostUrl, TokenType tokenType, String authToken, String secretToken, Map clientConfigProperties) { - this(ApiVersion.V4, hostUrl, tokenType, authToken, secretToken, clientConfigProperties); - } - - /** - * Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API version 4. - * - * @param hostUrl the URL of the GitLab server - * @param personalAccessToken the private token to use for access to the API - * @param secretToken use this token to validate received payloads - * @param clientConfigProperties Map instance with additional properties for the Jersey client connection - */ - public GitLabApi(String hostUrl, String personalAccessToken, String secretToken, Map clientConfigProperties) { - this(ApiVersion.V4, hostUrl, TokenType.PRIVATE, personalAccessToken, secretToken, clientConfigProperties); - } - - /** - * Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API version 4. - * - * @param hostUrl the URL of the GitLab server - * @param personalAccessToken the private token to use for access to the API - * @param clientConfigProperties Map instance with additional properties for the Jersey client connection - */ - public GitLabApi(String hostUrl, String personalAccessToken, Map clientConfigProperties) { - this(ApiVersion.V4, hostUrl, TokenType.PRIVATE, personalAccessToken, null, clientConfigProperties); - } - - /** - * Constructs a GitLabApi instance set up to interact with the GitLab server specified by GitLab API version. - * - * @param apiVersion the ApiVersion specifying which version of the API to use - * @param hostUrl the URL of the GitLab server - * @param tokenType the type of auth the token is for, PRIVATE or ACCESS - * @param authToken to token to use for access to the API - * @param secretToken use this token to validate received payloads - * @param clientConfigProperties Map instance with additional properties for the Jersey client connection - */ - public GitLabApi(ApiVersion apiVersion, String hostUrl, TokenType tokenType, String authToken, String secretToken, Map clientConfigProperties) { - this.apiVersion = apiVersion; - this.gitLabServerUrl = hostUrl; - this.clientConfigProperties = clientConfigProperties; - apiClient = new GitLabApiClient(apiVersion, hostUrl, tokenType, authToken, secretToken, clientConfigProperties); - } - - /** - * Create a new GitLabApi instance that is logically a duplicate of this instance, with the exception of sudo state. - * - * @return a new GitLabApi instance that is logically a duplicate of this instance, with the exception of sudo state. - */ - public final GitLabApi duplicate() { - - Long sudoUserId = this.getSudoAsId(); - GitLabApi gitLabApi = new GitLabApi(apiVersion, gitLabServerUrl, - getTokenType(), getAuthToken(), getSecretToken(), clientConfigProperties); - if (sudoUserId != null) { - gitLabApi.apiClient.setSudoAsId(sudoUserId); - } - - if (getIgnoreCertificateErrors()) { - gitLabApi.setIgnoreCertificateErrors(true); - } - - gitLabApi.defaultPerPage = this.defaultPerPage; - return (gitLabApi); - } - - /** - * Close the underlying {@link javax.ws.rs.client.Client} and its associated resources. - */ - @Override - public void close() { - if (apiClient != null) { - apiClient.close(); - } - } - - /** - * Sets the per request connect and read timeout. - * - * @param connectTimeout the per request connect timeout in milliseconds, can be null to use default - * @param readTimeout the per request read timeout in milliseconds, can be null to use default - */ - public void setRequestTimeout(Integer connectTimeout, Integer readTimeout) { - apiClient.setRequestTimeout(connectTimeout, readTimeout); - } - - /** - * Fluent method that sets the per request connect and read timeout. - * - * @param connectTimeout the per request connect timeout in milliseconds, can be null to use default - * @param readTimeout the per request read timeout in milliseconds, can be null to use default - * @return this GitLabApi instance - */ - public GitLabApi withRequestTimeout(Integer connectTimeout, Integer readTimeout) { - apiClient.setRequestTimeout(connectTimeout, readTimeout); - return (this); - } - - /** - * Enable the logging of the requests to and the responses from the GitLab server API - * using the GitLab4J shared Logger instance and Level.FINE as the level. - * - * @return this GitLabApi instance - */ - public GitLabApi withRequestResponseLogging() { - enableRequestResponseLogging(); - return (this); - } - - /** - * Enable the logging of the requests to and the responses from the GitLab server API - * using the GitLab4J shared Logger instance. - * - * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) - * @return this GitLabApi instance - */ - public GitLabApi withRequestResponseLogging(Level level) { - enableRequestResponseLogging(level); - return (this); - } - - /** - * Enable the logging of the requests to and the responses from the GitLab server API. - * - * @param logger the Logger instance to log to - * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) - * @return this GitLabApi instance - */ - public GitLabApi withRequestResponseLogging(Logger logger, Level level) { - enableRequestResponseLogging(logger, level); - return (this); - } - - /** - * Enable the logging of the requests to and the responses from the GitLab server API - * using the GitLab4J shared Logger instance and Level.FINE as the level. - */ - public void enableRequestResponseLogging() { - enableRequestResponseLogging(LOGGER, Level.FINE); - } - - /** - * Enable the logging of the requests to and the responses from the GitLab server API - * using the GitLab4J shared Logger instance. Logging will NOT include entity logging and - * will mask PRIVATE-TOKEN and Authorization headers. - * - * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) - */ - public void enableRequestResponseLogging(Level level) { - enableRequestResponseLogging(LOGGER, level, 0); - } - - /** - * Enable the logging of the requests to and the responses from the GitLab server API using the - * specified logger. Logging will NOT include entity logging and will mask PRIVATE-TOKEN - * and Authorization headers.. - * - * @param logger the Logger instance to log to - * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) - */ - public void enableRequestResponseLogging(Logger logger, Level level) { - enableRequestResponseLogging(logger, level, 0); - } - - /** - * Enable the logging of the requests to and the responses from the GitLab server API using the - * GitLab4J shared Logger instance. Logging will mask PRIVATE-TOKEN and Authorization headers. - * - * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) - * @param maxEntitySize maximum number of entity bytes to be logged. When logging if the maxEntitySize - * is reached, the entity logging will be truncated at maxEntitySize and "...more..." will be added at - * the end of the log entry. If maxEntitySize is <= 0, entity logging will be disabled - */ - public void enableRequestResponseLogging(Level level, int maxEntitySize) { - enableRequestResponseLogging(LOGGER, level, maxEntitySize); - } - - /** - * Enable the logging of the requests to and the responses from the GitLab server API using the - * specified logger. Logging will mask PRIVATE-TOKEN and Authorization headers. - * - * @param logger the Logger instance to log to - * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) - * @param maxEntitySize maximum number of entity bytes to be logged. When logging if the maxEntitySize - * is reached, the entity logging will be truncated at maxEntitySize and "...more..." will be added at - * the end of the log entry. If maxEntitySize is <= 0, entity logging will be disabled - */ - public void enableRequestResponseLogging(Logger logger, Level level, int maxEntitySize) { - enableRequestResponseLogging(logger, level, maxEntitySize, MaskingLoggingFilter.DEFAULT_MASKED_HEADER_NAMES); - } - - /** - * Enable the logging of the requests to and the responses from the GitLab server API using the - * GitLab4J shared Logger instance. - * - * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) - * @param maskedHeaderNames a list of header names that should have the values masked - */ - public void enableRequestResponseLogging(Level level, List maskedHeaderNames) { - apiClient.enableRequestResponseLogging(LOGGER, level, 0, maskedHeaderNames); - } - - /** - * Enable the logging of the requests to and the responses from the GitLab server API using the - * specified logger. - * - * @param logger the Logger instance to log to - * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) - * @param maskedHeaderNames a list of header names that should have the values masked - */ - public void enableRequestResponseLogging(Logger logger, Level level, List maskedHeaderNames) { - apiClient.enableRequestResponseLogging(logger, level, 0, maskedHeaderNames); - } - - /** - * Enable the logging of the requests to and the responses from the GitLab server API using the - * GitLab4J shared Logger instance. - * - * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) - * @param maxEntitySize maximum number of entity bytes to be logged. When logging if the maxEntitySize - * is reached, the entity logging will be truncated at maxEntitySize and "...more..." will be added at - * the end of the log entry. If maxEntitySize is <= 0, entity logging will be disabled - * @param maskedHeaderNames a list of header names that should have the values masked - */ - public void enableRequestResponseLogging(Level level, int maxEntitySize, List maskedHeaderNames) { - apiClient.enableRequestResponseLogging(LOGGER, level, maxEntitySize, maskedHeaderNames); - } - - /** - * Enable the logging of the requests to and the responses from the GitLab server API using the - * specified logger. - * - * @param logger the Logger instance to log to - * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) - * @param maxEntitySize maximum number of entity bytes to be logged. When logging if the maxEntitySize - * is reached, the entity logging will be truncated at maxEntitySize and "...more..." will be added at - * the end of the log entry. If maxEntitySize is <= 0, entity logging will be disabled - * @param maskedHeaderNames a list of header names that should have the values masked - */ - public void enableRequestResponseLogging(Logger logger, Level level, int maxEntitySize, List maskedHeaderNames) { - apiClient.enableRequestResponseLogging(logger, level, maxEntitySize, maskedHeaderNames); - } - - /** - * Sets up all future calls to the GitLab API to be done as another user specified by sudoAsUsername. - * To revert back to normal non-sudo operation you must call unsudo(), or pass null as the username. - * - * @param sudoAsUsername the username to sudo as, null will turn off sudo - * @throws GitLabApiException if any exception occurs - */ - public void sudo(String sudoAsUsername) throws GitLabApiException { - - if (sudoAsUsername == null || sudoAsUsername.trim().length() == 0) { - apiClient.setSudoAsId(null); - return; - } - - // Get the User specified by username, if you are not an admin or the username is not found, this will fail - User user = getUserApi().getUser(sudoAsUsername); - if (user == null || user.getId() == null) { - throw new GitLabApiException("the specified username was not found"); - } - - Long sudoAsId = user.getId(); - apiClient.setSudoAsId(sudoAsId); - } - - /** - * Turns off the currently configured sudo as ID. - */ - public void unsudo() { - apiClient.setSudoAsId(null); - } - - /** - * Sets up all future calls to the GitLab API to be done as another user specified by provided user ID. - * To revert back to normal non-sudo operation you must call unsudo(), or pass null as the sudoAsId. - * - * @param sudoAsId the ID of the user to sudo as, null will turn off sudo - * @throws GitLabApiException if any exception occurs - */ - public void setSudoAsId(Long sudoAsId) throws GitLabApiException { - - if (sudoAsId == null) { - apiClient.setSudoAsId(null); - return; - } - - // Get the User specified by the sudoAsId, if you are not an admin or the username is not found, this will fail - User user = getUserApi().getUser(sudoAsId); - if (user == null || !user.getId().equals(sudoAsId)) { - throw new GitLabApiException("the specified user ID was not found"); - } - - apiClient.setSudoAsId(sudoAsId); - } - - /** - * Get the current sudo as ID, will return null if not in sudo mode. - * - * @return the current sudo as ID, will return null if not in sudo mode - */ - public Long getSudoAsId() { - return (apiClient.getSudoAsId()); - } - - /** - * Get the auth token being used by this client. - * - * @return the auth token being used by this client - */ - public String getAuthToken() { - return (apiClient.getAuthToken()); - } - - /** - * Set auth token supplier for gitlab api client. - * @param authTokenSupplier - supplier which provide actual auth token - */ - public void setAuthTokenSupplier(Supplier authTokenSupplier) { - apiClient.setAuthTokenSupplier(authTokenSupplier); - } - - /** - * Get the secret token. - * - * @return the secret token - */ - public String getSecretToken() { - return (apiClient.getSecretToken()); - } - - /** - * Get the TokenType this client is using. - * - * @return the TokenType this client is using - */ - public TokenType getTokenType() { - return (apiClient.getTokenType()); - } - - /** - * Return the GitLab API version that this instance is using. - * - * @return the GitLab API version that this instance is using - */ - public ApiVersion getApiVersion() { - return (apiVersion); - } - - /** - * Get the URL to the GitLab server. - * - * @return the URL to the GitLab server - */ - public String getGitLabServerUrl() { - return (gitLabServerUrl); - } - - /** - * Get the default number per page for calls that return multiple items. - * - * @return the default number per page for calls that return multiple item - */ - public int getDefaultPerPage() { - return (defaultPerPage); - } - - /** - * Set the default number per page for calls that return multiple items. - * - * @param defaultPerPage the new default number per page for calls that return multiple item - */ - public void setDefaultPerPage(int defaultPerPage) { - this.defaultPerPage = defaultPerPage; - } - - /** - * Return the GitLabApiClient associated with this instance. This is used by all the sub API classes - * to communicate with the GitLab API. - * - * @return the GitLabApiClient associated with this instance - */ - GitLabApiClient getApiClient() { - return (apiClient); - } - - /** - * Returns true if the API is setup to ignore SSL certificate errors, otherwise returns false. - * - * @return true if the API is setup to ignore SSL certificate errors, otherwise returns false - */ - public boolean getIgnoreCertificateErrors() { - return (apiClient.getIgnoreCertificateErrors()); - } - - /** - * Sets up the Jersey system ignore SSL certificate errors or not. - * - * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors - */ - public void setIgnoreCertificateErrors(boolean ignoreCertificateErrors) { - apiClient.setIgnoreCertificateErrors(ignoreCertificateErrors); - } - - /** - * Get the version info for the GitLab server using the GitLab Version API. - * - * @return the version info for the GitLab server - * @throws GitLabApiException if any exception occurs - */ - public Version getVersion() throws GitLabApiException { - - class VersionApi extends AbstractApi { - VersionApi(GitLabApi gitlabApi) { - super(gitlabApi); - } - } - - Response response = new VersionApi(this).get(Response.Status.OK, null, "version"); - return (response.readEntity(Version.class)); - } - - /** - * Gets the ApplicationsApi instance owned by this GitLabApi instance. The ApplicationsApi is used - * to perform all OAUTH application related API calls. - * - * @return the ApplicationsApi instance owned by this GitLabApi instance - */ - public ApplicationsApi getApplicationsApi() { - + private static final Logger LOGGER = Logger.getLogger(GitLabApi.class.getName()); + + /** GitLab4J default per page. GitLab will ignore anything over 100. */ + public static final int DEFAULT_PER_PAGE = 96; + + /** Specifies the version of the GitLab API to communicate with. */ + public enum ApiVersion { + V3, + V4; + + public String getApiNamespace() { + return ("/api/" + name().toLowerCase()); + } + } + + // Used to keep track of GitLabApiExceptions on calls that return Optional + private static final Map optionalExceptionMap = + Collections.synchronizedMap(new WeakHashMap()); + + GitLabApiClient apiClient; + private final ApiVersion apiVersion; + private final String gitLabServerUrl; + private final Map clientConfigProperties; + private int defaultPerPage = DEFAULT_PER_PAGE; + + private ApplicationsApi applicationsApi; + private ApplicationSettingsApi applicationSettingsApi; + private AuditEventApi auditEventApi; + private AwardEmojiApi awardEmojiApi; + private BoardsApi boardsApi; + private CommitsApi commitsApi; + private ContainerRegistryApi containerRegistryApi; + private DiscussionsApi discussionsApi; + private DeployKeysApi deployKeysApi; + private DeploymentsApi deploymentsApi; + private DeployTokensApi deployTokensApi; + private EnvironmentsApi environmentsApi; + private EpicsApi epicsApi; + private EventsApi eventsApi; + private ExternalStatusCheckApi externalStatusCheckApi; + private GroupApi groupApi; + private HealthCheckApi healthCheckApi; + private ImportExportApi importExportApi; + private IssuesApi issuesApi; + private JobApi jobApi; + private LabelsApi labelsApi; + private LicenseApi licenseApi; + private LicenseTemplatesApi licenseTemplatesApi; + private MarkdownApi markdownApi; + private MergeRequestApi mergeRequestApi; + private MilestonesApi milestonesApi; + private NamespaceApi namespaceApi; + private NotesApi notesApi; + private NotificationSettingsApi notificationSettingsApi; + private PackagesApi packagesApi; + private PipelineApi pipelineApi; + private ProjectApi projectApi; + private ProtectedBranchesApi protectedBranchesApi; + private ReleasesApi releasesApi; + private RepositoryApi repositoryApi; + private RepositoryFileApi repositoryFileApi; + private ResourceLabelEventsApi resourceLabelEventsApi; + private ResourceStateEventsApi resourceStateEventsApi; + private RunnersApi runnersApi; + private SearchApi searchApi; + private ServicesApi servicesApi; + private SnippetsApi snippetsApi; + private SystemHooksApi systemHooksApi; + private TagsApi tagsApi; + private TodosApi todosApi; + private UserApi userApi; + private WikisApi wikisApi; + private KeysApi keysApi; + + /** + * Get the GitLab4J shared Logger instance. + * + * @return the GitLab4J shared Logger instance + */ + public static final Logger getLogger() { + return (LOGGER); + } + + /** + * Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API + * version 4. This is the primary way to authenticate with the GitLab REST API. + * + * @param hostUrl the URL of the GitLab server + * @param personalAccessToken the private token to use for access to the API + */ + public GitLabApi(final String hostUrl, final String personalAccessToken) { + this(ApiVersion.V4, hostUrl, personalAccessToken, null); + } + + /** + * Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API + * version 4. + * + * @param hostUrl the URL of the GitLab server + * @param personalAccessToken the private token to use for access to the API + * @param secretToken use this token to validate received payloads + */ + public GitLabApi( + final String hostUrl, final String personalAccessToken, final String secretToken) { + this(ApiVersion.V4, hostUrl, TokenType.PRIVATE, personalAccessToken, secretToken); + } + + /** + * Logs into GitLab using OAuth2 with the provided {@code username} and {@code password}, and + * creates a new {@code GitLabApi} instance using returned access token. + * + * @param url GitLab URL + * @param username user name for which private token should be obtained + * @param password a CharSequence containing the password for a given {@code username} + * @return new {@code GitLabApi} instance configured for a user-specific token + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public static GitLabApi oauth2Login( + final String url, final String username, final CharSequence password) + throws GitLabApiException { + return (GitLabApi.oauth2Login(ApiVersion.V4, url, username, password, null, null, false)); + } + + /** + * Logs into GitLab using OAuth2 with the provided {@code username} and {@code password}, and + * creates a new {@code GitLabApi} instance using returned access token. + * + * @param url GitLab URL + * @param username user name for which private token should be obtained + * @param password a char array holding the password for a given {@code username} + * @return new {@code GitLabApi} instance configured for a user-specific token + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public static GitLabApi oauth2Login( + final String url, final String username, final char[] password) throws GitLabApiException { + + try (final SecretString secretPassword = new SecretString(password)) { + return (GitLabApi.oauth2Login( + ApiVersion.V4, url, username, secretPassword, null, null, false)); + } + } + + /** + * Logs into GitLab using OAuth2 with the provided {@code username} and {@code password}, and + * creates a new {@code GitLabApi} instance using returned access token. + * + * @param url GitLab URL + * @param username user name for which private token should be obtained + * @param password a CharSequence containing the password for a given {@code username} + * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate + * errors + * @return new {@code GitLabApi} instance configured for a user-specific token + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public static GitLabApi oauth2Login( + final String url, + final String username, + final CharSequence password, + final boolean ignoreCertificateErrors) + throws GitLabApiException { + return (GitLabApi.oauth2Login( + ApiVersion.V4, url, username, password, null, null, ignoreCertificateErrors)); + } + + /** + * Logs into GitLab using OAuth2 with the provided {@code username} and {@code password}, and + * creates a new {@code GitLabApi} instance using returned access token. + * + * @param url GitLab URL + * @param username user name for which private token should be obtained + * @param password a char array holding the password for a given {@code username} + * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate + * errors + * @return new {@code GitLabApi} instance configured for a user-specific token + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public static GitLabApi oauth2Login( + final String url, + final String username, + final char[] password, + final boolean ignoreCertificateErrors) + throws GitLabApiException { + + try (final SecretString secretPassword = new SecretString(password)) { + return (GitLabApi.oauth2Login( + ApiVersion.V4, url, username, secretPassword, null, null, ignoreCertificateErrors)); + } + } + + /** + * Logs into GitLab using OAuth2 with the provided {@code username} and {@code password}, and + * creates a new {@code GitLabApi} instance using returned access token. + * + * @param url GitLab URL + * @param username user name for which private token should be obtained + * @param password a CharSequence containing the password for a given {@code username} + * @param secretToken use this token to validate received payloads + * @param clientConfigProperties Map instance with additional properties for the Jersey client + * connection + * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate + * errors + * @return new {@code GitLabApi} instance configured for a user-specific token + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public static GitLabApi oauth2Login( + final String url, + final String username, + final CharSequence password, + final String secretToken, + final Map clientConfigProperties, + final boolean ignoreCertificateErrors) + throws GitLabApiException { + return (GitLabApi.oauth2Login( + ApiVersion.V4, + url, + username, + password, + secretToken, + clientConfigProperties, + ignoreCertificateErrors)); + } + + /** + * Logs into GitLab using OAuth2 with the provided {@code username} and {@code password}, and + * creates a new {@code GitLabApi} instance using returned access token. + * + * @param url GitLab URL + * @param username user name for which private token should be obtained + * @param password a char array holding the password for a given {@code username} + * @param secretToken use this token to validate received payloads + * @param clientConfigProperties Map instance with additional properties for the Jersey client + * connection + * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate + * errors + * @return new {@code GitLabApi} instance configured for a user-specific token + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public static GitLabApi oauth2Login( + final String url, + final String username, + final char[] password, + final String secretToken, + final Map clientConfigProperties, + final boolean ignoreCertificateErrors) + throws GitLabApiException { + + try (final SecretString secretPassword = new SecretString(password)) { + return (GitLabApi.oauth2Login( + ApiVersion.V4, + url, + username, + secretPassword, + secretToken, + clientConfigProperties, + ignoreCertificateErrors)); + } + } + + /** + * Logs into GitLab using OAuth2 with the provided {@code username} and {@code password}, and + * creates a new {@code GitLabApi} instance using returned access token. + * + * @param url GitLab URL + * @param apiVersion the ApiVersion specifying which version of the API to use + * @param username user name for which private token should be obtained + * @param password a char array holding the password for a given {@code username} + * @param secretToken use this token to validate received payloads + * @param clientConfigProperties Map instance with additional properties for the Jersey client + * connection + * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate + * errors + * @return new {@code GitLabApi} instance configured for a user-specific token + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public static GitLabApi oauth2Login( + final ApiVersion apiVersion, + final String url, + final String username, + final char[] password, + final String secretToken, + final Map clientConfigProperties, + final boolean ignoreCertificateErrors) + throws GitLabApiException { + + try (final SecretString secretPassword = new SecretString(password)) { + return (GitLabApi.oauth2Login( + apiVersion, + url, + username, + secretPassword, + secretToken, + clientConfigProperties, + ignoreCertificateErrors)); + } + } + + /** + * Logs into GitLab using OAuth2 with the provided {@code username} and {@code password}, and + * creates a new {@code GitLabApi} instance using returned access token. + * + * @param url GitLab URL + * @param apiVersion the ApiVersion specifying which version of the API to use + * @param username user name for which private token should be obtained + * @param password password for a given {@code username} + * @param secretToken use this token to validate received payloads + * @param clientConfigProperties Map instance with additional properties for the Jersey client + * connection + * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate + * errors + * @return new {@code GitLabApi} instance configured for a user-specific token + * @throws GitLabApiException GitLabApiException if any exception occurs during execution + */ + public static GitLabApi oauth2Login( + final ApiVersion apiVersion, + final String url, + final String username, + final CharSequence password, + final String secretToken, + final Map clientConfigProperties, + final boolean ignoreCertificateErrors) + throws GitLabApiException { + + if (username == null || username.trim().length() == 0) { + throw new IllegalArgumentException("both username and email cannot be empty or null"); + } + + // Create a GitLabApi instance set up to be used to do an OAUTH2 login. + GitLabApi gitLabApi = new GitLabApi(apiVersion, url, (String) null); + gitLabApi.apiClient.setHostUrlToBaseUrl(); + + if (ignoreCertificateErrors) { + gitLabApi.setIgnoreCertificateErrors(true); + } + + class Oauth2Api extends AbstractApi { + Oauth2Api(final GitLabApi gitlabApi) { + super(gitlabApi); + } + } + + try (final Oauth2LoginStreamingOutput stream = + new Oauth2LoginStreamingOutput(username, password)) { + + final Response response = + new Oauth2Api(gitLabApi) + .post(Response.Status.OK, stream, MediaType.APPLICATION_JSON, "oauth", "token"); + final OauthTokenResponse oauthToken = response.readEntity(OauthTokenResponse.class); + gitLabApi = + new GitLabApi( + apiVersion, + url, + TokenType.OAUTH2_ACCESS, + oauthToken.getAccessToken(), + secretToken, + clientConfigProperties); + if (ignoreCertificateErrors) { + gitLabApi.setIgnoreCertificateErrors(true); + } + + return (gitLabApi); + } + } + + /** + * Constructs a GitLabApi instance set up to interact with the GitLab server using the specified + * GitLab API version. + * + * @param apiVersion the ApiVersion specifying which version of the API to use + * @param hostUrl the URL of the GitLab server + * @param personalAccessToken the private token to use for access to the API + */ + public GitLabApi( + final ApiVersion apiVersion, final String hostUrl, final String personalAccessToken) { + this(apiVersion, hostUrl, personalAccessToken, null); + } + + /** + * Constructs a GitLabApi instance set up to interact with the GitLab server using the specified + * GitLab API version. + * + * @param apiVersion the ApiVersion specifying which version of the API to use + * @param hostUrl the URL of the GitLab server + * @param personalAccessToken the private token to use for access to the API + * @param secretToken use this token to validate received payloads + */ + public GitLabApi( + final ApiVersion apiVersion, + final String hostUrl, + final String personalAccessToken, + final String secretToken) { + this(apiVersion, hostUrl, personalAccessToken, secretToken, null); + } + + /** + * Constructs a GitLabApi instance set up to interact with the GitLab server using the specified + * GitLab API version. + * + * @param apiVersion the ApiVersion specifying which version of the API to use + * @param hostUrl the URL of the GitLab server + * @param tokenType the type of auth the token is for, PRIVATE or ACCESS + * @param authToken the token to use for access to the API + */ + public GitLabApi( + final ApiVersion apiVersion, + final String hostUrl, + final TokenType tokenType, + final String authToken) { + this(apiVersion, hostUrl, tokenType, authToken, null); + } + + /** + * Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API + * version 4. + * + * @param hostUrl the URL of the GitLab server + * @param tokenType the type of auth the token is for, PRIVATE or ACCESS + * @param authToken the token to use for access to the API + */ + public GitLabApi(final String hostUrl, final TokenType tokenType, final String authToken) { + this(ApiVersion.V4, hostUrl, tokenType, authToken, null); + } + + /** + * Constructs a GitLabApi instance set up to interact with the GitLab server using the specified + * GitLab API version. + * + * @param apiVersion the ApiVersion specifying which version of the API to use + * @param hostUrl the URL of the GitLab server + * @param tokenType the type of auth the token is for, PRIVATE or ACCESS + * @param authToken the token to use for access to the API + * @param secretToken use this token to validate received payloads + */ + public GitLabApi( + final ApiVersion apiVersion, + final String hostUrl, + final TokenType tokenType, + final String authToken, + final String secretToken) { + this(apiVersion, hostUrl, tokenType, authToken, secretToken, null); + } + + /** + * Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API + * version 4. + * + * @param hostUrl the URL of the GitLab server + * @param tokenType the type of auth the token is for, PRIVATE or ACCESS + * @param authToken the token to use for access to the API + * @param secretToken use this token to validate received payloads + */ + public GitLabApi( + final String hostUrl, + final TokenType tokenType, + final String authToken, + final String secretToken) { + this(ApiVersion.V4, hostUrl, tokenType, authToken, secretToken); + } + + /** + * Constructs a GitLabApi instance set up to interact with the GitLab server specified by GitLab + * API version. + * + * @param apiVersion the ApiVersion specifying which version of the API to use + * @param hostUrl the URL of the GitLab server + * @param personalAccessToken to private token to use for access to the API + * @param secretToken use this token to validate received payloads + * @param clientConfigProperties Map instance with additional properties for the Jersey client + * connection + */ + public GitLabApi( + final ApiVersion apiVersion, + final String hostUrl, + final String personalAccessToken, + final String secretToken, + final Map clientConfigProperties) { + this( + apiVersion, + hostUrl, + TokenType.PRIVATE, + personalAccessToken, + secretToken, + clientConfigProperties); + } + + /** + * Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API + * version 4. + * + * @param hostUrl the URL of the GitLab server + * @param tokenType the type of auth the token is for, PRIVATE or ACCESS + * @param authToken the token to use for access to the API + * @param secretToken use this token to validate received payloads + * @param clientConfigProperties Map instance with additional properties for the Jersey client + * connection + */ + public GitLabApi( + final String hostUrl, + final TokenType tokenType, + final String authToken, + final String secretToken, + final Map clientConfigProperties) { + this(ApiVersion.V4, hostUrl, tokenType, authToken, secretToken, clientConfigProperties); + } + + /** + * Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API + * version 4. + * + * @param hostUrl the URL of the GitLab server + * @param personalAccessToken the private token to use for access to the API + * @param secretToken use this token to validate received payloads + * @param clientConfigProperties Map instance with additional properties for the Jersey client + * connection + */ + public GitLabApi( + final String hostUrl, + final String personalAccessToken, + final String secretToken, + final Map clientConfigProperties) { + this( + ApiVersion.V4, + hostUrl, + TokenType.PRIVATE, + personalAccessToken, + secretToken, + clientConfigProperties); + } + + /** + * Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API + * version 4. + * + * @param hostUrl the URL of the GitLab server + * @param personalAccessToken the private token to use for access to the API + * @param clientConfigProperties Map instance with additional properties for the Jersey client + * connection + */ + public GitLabApi( + final String hostUrl, + final String personalAccessToken, + final Map clientConfigProperties) { + this( + ApiVersion.V4, + hostUrl, + TokenType.PRIVATE, + personalAccessToken, + null, + clientConfigProperties); + } + + /** + * Constructs a GitLabApi instance set up to interact with the GitLab server specified by GitLab + * API version. + * + * @param apiVersion the ApiVersion specifying which version of the API to use + * @param hostUrl the URL of the GitLab server + * @param tokenType the type of auth the token is for, PRIVATE or ACCESS + * @param authToken to token to use for access to the API + * @param secretToken use this token to validate received payloads + * @param clientConfigProperties Map instance with additional properties for the Jersey client + * connection + */ + public GitLabApi( + final ApiVersion apiVersion, + final String hostUrl, + final TokenType tokenType, + final String authToken, + final String secretToken, + final Map clientConfigProperties) { + this.apiVersion = apiVersion; + this.gitLabServerUrl = hostUrl; + this.clientConfigProperties = clientConfigProperties; + apiClient = + new GitLabApiClient( + apiVersion, hostUrl, tokenType, authToken, secretToken, clientConfigProperties); + } + + /** + * Create a new GitLabApi instance that is logically a duplicate of this instance, with the + * exception of sudo state. + * + * @return a new GitLabApi instance that is logically a duplicate of this instance, with the + * exception of sudo state. + */ + public final GitLabApi duplicate() { + + final Long sudoUserId = this.getSudoAsId(); + final GitLabApi gitLabApi = + new GitLabApi( + apiVersion, + gitLabServerUrl, + getTokenType(), + getAuthToken(), + getSecretToken(), + clientConfigProperties); + if (sudoUserId != null) { + gitLabApi.apiClient.setSudoAsId(sudoUserId); + } + + if (getIgnoreCertificateErrors()) { + gitLabApi.setIgnoreCertificateErrors(true); + } + + gitLabApi.defaultPerPage = this.defaultPerPage; + return (gitLabApi); + } + + /** Close the underlying {@link jakarta.ws.rs.client.Client} and its associated resources. */ + @Override + public void close() { + if (apiClient != null) { + apiClient.close(); + } + } + + /** + * Sets the per request connect and read timeout. + * + * @param connectTimeout the per request connect timeout in milliseconds, can be null to use + * default + * @param readTimeout the per request read timeout in milliseconds, can be null to use default + */ + public void setRequestTimeout(final Integer connectTimeout, final Integer readTimeout) { + apiClient.setRequestTimeout(connectTimeout, readTimeout); + } + + /** + * Fluent method that sets the per request connect and read timeout. + * + * @param connectTimeout the per request connect timeout in milliseconds, can be null to use + * default + * @param readTimeout the per request read timeout in milliseconds, can be null to use default + * @return this GitLabApi instance + */ + public GitLabApi withRequestTimeout(final Integer connectTimeout, final Integer readTimeout) { + apiClient.setRequestTimeout(connectTimeout, readTimeout); + return (this); + } + + /** + * Enable the logging of the requests to and the responses from the GitLab server API using the + * GitLab4J shared Logger instance and Level.FINE as the level. + * + * @return this GitLabApi instance + */ + public GitLabApi withRequestResponseLogging() { + enableRequestResponseLogging(); + return (this); + } + + /** + * Enable the logging of the requests to and the responses from the GitLab server API using the + * GitLab4J shared Logger instance. + * + * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) + * @return this GitLabApi instance + */ + public GitLabApi withRequestResponseLogging(final Level level) { + enableRequestResponseLogging(level); + return (this); + } + + /** + * Enable the logging of the requests to and the responses from the GitLab server API. + * + * @param logger the Logger instance to log to + * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) + * @return this GitLabApi instance + */ + public GitLabApi withRequestResponseLogging(final Logger logger, final Level level) { + enableRequestResponseLogging(logger, level); + return (this); + } + + /** + * Enable the logging of the requests to and the responses from the GitLab server API using the + * GitLab4J shared Logger instance and Level.FINE as the level. + */ + public void enableRequestResponseLogging() { + enableRequestResponseLogging(LOGGER, Level.FINE); + } + + /** + * Enable the logging of the requests to and the responses from the GitLab server API using the + * GitLab4J shared Logger instance. Logging will NOT include entity logging and will mask + * PRIVATE-TOKEN and Authorization headers. + * + * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) + */ + public void enableRequestResponseLogging(final Level level) { + enableRequestResponseLogging(LOGGER, level, 0); + } + + /** + * Enable the logging of the requests to and the responses from the GitLab server API using the + * specified logger. Logging will NOT include entity logging and will mask PRIVATE-TOKEN and + * Authorization headers.. + * + * @param logger the Logger instance to log to + * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) + */ + public void enableRequestResponseLogging(final Logger logger, final Level level) { + enableRequestResponseLogging(logger, level, 0); + } + + /** + * Enable the logging of the requests to and the responses from the GitLab server API using the + * GitLab4J shared Logger instance. Logging will mask PRIVATE-TOKEN and Authorization headers. + * + * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) + * @param maxEntitySize maximum number of entity bytes to be logged. When logging if the + * maxEntitySize is reached, the entity logging will be truncated at maxEntitySize and + * "...more..." will be added at the end of the log entry. If maxEntitySize is <= 0, entity + * logging will be disabled + */ + public void enableRequestResponseLogging(final Level level, final int maxEntitySize) { + enableRequestResponseLogging(LOGGER, level, maxEntitySize); + } + + /** + * Enable the logging of the requests to and the responses from the GitLab server API using the + * specified logger. Logging will mask PRIVATE-TOKEN and Authorization headers. + * + * @param logger the Logger instance to log to + * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) + * @param maxEntitySize maximum number of entity bytes to be logged. When logging if the + * maxEntitySize is reached, the entity logging will be truncated at maxEntitySize and + * "...more..." will be added at the end of the log entry. If maxEntitySize is <= 0, entity + * logging will be disabled + */ + public void enableRequestResponseLogging( + final Logger logger, final Level level, final int maxEntitySize) { + enableRequestResponseLogging( + logger, level, maxEntitySize, MaskingLoggingFilter.DEFAULT_MASKED_HEADER_NAMES); + } + + /** + * Enable the logging of the requests to and the responses from the GitLab server API using the + * GitLab4J shared Logger instance. + * + * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) + * @param maskedHeaderNames a list of header names that should have the values masked + */ + public void enableRequestResponseLogging( + final Level level, final List maskedHeaderNames) { + apiClient.enableRequestResponseLogging(LOGGER, level, 0, maskedHeaderNames); + } + + /** + * Enable the logging of the requests to and the responses from the GitLab server API using the + * specified logger. + * + * @param logger the Logger instance to log to + * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) + * @param maskedHeaderNames a list of header names that should have the values masked + */ + public void enableRequestResponseLogging( + final Logger logger, final Level level, final List maskedHeaderNames) { + apiClient.enableRequestResponseLogging(logger, level, 0, maskedHeaderNames); + } + + /** + * Enable the logging of the requests to and the responses from the GitLab server API using the + * GitLab4J shared Logger instance. + * + * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) + * @param maxEntitySize maximum number of entity bytes to be logged. When logging if the + * maxEntitySize is reached, the entity logging will be truncated at maxEntitySize and + * "...more..." will be added at the end of the log entry. If maxEntitySize is <= 0, entity + * logging will be disabled + * @param maskedHeaderNames a list of header names that should have the values masked + */ + public void enableRequestResponseLogging( + final Level level, final int maxEntitySize, final List maskedHeaderNames) { + apiClient.enableRequestResponseLogging(LOGGER, level, maxEntitySize, maskedHeaderNames); + } + + /** + * Enable the logging of the requests to and the responses from the GitLab server API using the + * specified logger. + * + * @param logger the Logger instance to log to + * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) + * @param maxEntitySize maximum number of entity bytes to be logged. When logging if the + * maxEntitySize is reached, the entity logging will be truncated at maxEntitySize and + * "...more..." will be added at the end of the log entry. If maxEntitySize is <= 0, entity + * logging will be disabled + * @param maskedHeaderNames a list of header names that should have the values masked + */ + public void enableRequestResponseLogging( + final Logger logger, + final Level level, + final int maxEntitySize, + final List maskedHeaderNames) { + apiClient.enableRequestResponseLogging(logger, level, maxEntitySize, maskedHeaderNames); + } + + /** + * Sets up all future calls to the GitLab API to be done as another user specified by + * sudoAsUsername. To revert back to normal non-sudo operation you must call unsudo(), or pass + * null as the username. + * + * @param sudoAsUsername the username to sudo as, null will turn off sudo + * @throws GitLabApiException if any exception occurs + */ + public void sudo(final String sudoAsUsername) throws GitLabApiException { + + if (sudoAsUsername == null || sudoAsUsername.trim().length() == 0) { + apiClient.setSudoAsId(null); + return; + } + + // Get the User specified by username, if you are not an admin or the username is not found, + // this will fail + final User user = getUserApi().getUser(sudoAsUsername); + if (user == null || user.getId() == null) { + throw new GitLabApiException("the specified username was not found"); + } + + final Long sudoAsId = user.getId(); + apiClient.setSudoAsId(sudoAsId); + } + + /** Turns off the currently configured sudo as ID. */ + public void unsudo() { + apiClient.setSudoAsId(null); + } + + /** + * Sets up all future calls to the GitLab API to be done as another user specified by provided + * user ID. To revert back to normal non-sudo operation you must call unsudo(), or pass null as + * the sudoAsId. + * + * @param sudoAsId the ID of the user to sudo as, null will turn off sudo + * @throws GitLabApiException if any exception occurs + */ + public void setSudoAsId(final Long sudoAsId) throws GitLabApiException { + + if (sudoAsId == null) { + apiClient.setSudoAsId(null); + return; + } + + // Get the User specified by the sudoAsId, if you are not an admin or the username is not found, + // this will fail + final User user = getUserApi().getUser(sudoAsId); + if (user == null || !user.getId().equals(sudoAsId)) { + throw new GitLabApiException("the specified user ID was not found"); + } + + apiClient.setSudoAsId(sudoAsId); + } + + /** + * Get the current sudo as ID, will return null if not in sudo mode. + * + * @return the current sudo as ID, will return null if not in sudo mode + */ + public Long getSudoAsId() { + return (apiClient.getSudoAsId()); + } + + /** + * Get the auth token being used by this client. + * + * @return the auth token being used by this client + */ + public String getAuthToken() { + return (apiClient.getAuthToken()); + } + + /** + * Set auth token supplier for gitlab api client. + * + * @param authTokenSupplier - supplier which provide actual auth token + */ + public void setAuthTokenSupplier(final Supplier authTokenSupplier) { + apiClient.setAuthTokenSupplier(authTokenSupplier); + } + + /** + * Get the secret token. + * + * @return the secret token + */ + public String getSecretToken() { + return (apiClient.getSecretToken()); + } + + /** + * Get the TokenType this client is using. + * + * @return the TokenType this client is using + */ + public TokenType getTokenType() { + return (apiClient.getTokenType()); + } + + /** + * Return the GitLab API version that this instance is using. + * + * @return the GitLab API version that this instance is using + */ + public ApiVersion getApiVersion() { + return (apiVersion); + } + + /** + * Get the URL to the GitLab server. + * + * @return the URL to the GitLab server + */ + public String getGitLabServerUrl() { + return (gitLabServerUrl); + } + + /** + * Get the default number per page for calls that return multiple items. + * + * @return the default number per page for calls that return multiple item + */ + public int getDefaultPerPage() { + return (defaultPerPage); + } + + /** + * Set the default number per page for calls that return multiple items. + * + * @param defaultPerPage the new default number per page for calls that return multiple item + */ + public void setDefaultPerPage(final int defaultPerPage) { + this.defaultPerPage = defaultPerPage; + } + + /** + * Return the GitLabApiClient associated with this instance. This is used by all the sub API + * classes to communicate with the GitLab API. + * + * @return the GitLabApiClient associated with this instance + */ + GitLabApiClient getApiClient() { + return (apiClient); + } + + /** + * Returns true if the API is setup to ignore SSL certificate errors, otherwise returns false. + * + * @return true if the API is setup to ignore SSL certificate errors, otherwise returns false + */ + public boolean getIgnoreCertificateErrors() { + return (apiClient.getIgnoreCertificateErrors()); + } + + /** + * Sets up the Jersey system ignore SSL certificate errors or not. + * + * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate + * errors + */ + public void setIgnoreCertificateErrors(final boolean ignoreCertificateErrors) { + apiClient.setIgnoreCertificateErrors(ignoreCertificateErrors); + } + + /** + * Get the version info for the GitLab server using the GitLab Version API. + * + * @return the version info for the GitLab server + * @throws GitLabApiException if any exception occurs + */ + public Version getVersion() throws GitLabApiException { + + class VersionApi extends AbstractApi { + VersionApi(final GitLabApi gitlabApi) { + super(gitlabApi); + } + } + + final Response response = new VersionApi(this).get(Response.Status.OK, null, "version"); + return (response.readEntity(Version.class)); + } + + /** + * Gets the ApplicationsApi instance owned by this GitLabApi instance. The ApplicationsApi is used + * to perform all OAUTH application related API calls. + * + * @return the ApplicationsApi instance owned by this GitLabApi instance + */ + public ApplicationsApi getApplicationsApi() { + + if (applicationsApi == null) { + synchronized (this) { if (applicationsApi == null) { - synchronized (this) { - if (applicationsApi == null) { - applicationsApi = new ApplicationsApi(this); - } - } + applicationsApi = new ApplicationsApi(this); } - - return (applicationsApi); + } } - /** - * Gets the ApplicationSettingsApi instance owned by this GitLabApi instance. The ApplicationSettingsApi is used - * to perform all application settingsrelated API calls. - * - * @return the ApplicationsApi instance owned by this GitLabApi instance - */ - public ApplicationSettingsApi getApplicationSettingsApi() { + return (applicationsApi); + } + + /** + * Gets the ApplicationSettingsApi instance owned by this GitLabApi instance. The + * ApplicationSettingsApi is used to perform all application settingsrelated API calls. + * + * @return the ApplicationsApi instance owned by this GitLabApi instance + */ + public ApplicationSettingsApi getApplicationSettingsApi() { + if (applicationSettingsApi == null) { + synchronized (this) { if (applicationSettingsApi == null) { - synchronized (this) { - if (applicationSettingsApi == null) { - applicationSettingsApi = new ApplicationSettingsApi(this); - } - } + applicationSettingsApi = new ApplicationSettingsApi(this); } - - return (applicationSettingsApi); + } } - /** - * Gets the AuditEventApi instance owned by this GitLabApi instance. The AuditEventApi is used - * to perform all instance audit event API calls. - * - * @return the AuditEventApi instance owned by this GitLabApi instance - */ - public AuditEventApi getAuditEventApi() { + return (applicationSettingsApi); + } + /** + * Gets the AuditEventApi instance owned by this GitLabApi instance. The AuditEventApi is used to + * perform all instance audit event API calls. + * + * @return the AuditEventApi instance owned by this GitLabApi instance + */ + public AuditEventApi getAuditEventApi() { + + if (auditEventApi == null) { + synchronized (this) { if (auditEventApi == null) { - synchronized (this) { - if (auditEventApi == null) { - auditEventApi = new AuditEventApi(this); - } - } + auditEventApi = new AuditEventApi(this); } - - return (auditEventApi); + } } - /** - * Gets the AwardEmojiApi instance owned by this GitLabApi instance. The AwardEmojiApi is used - * to perform all award emoji related API calls. - * - * @return the AwardEmojiApi instance owned by this GitLabApi instance - */ - public AwardEmojiApi getAwardEmojiApi() { + return (auditEventApi); + } + /** + * Gets the AwardEmojiApi instance owned by this GitLabApi instance. The AwardEmojiApi is used to + * perform all award emoji related API calls. + * + * @return the AwardEmojiApi instance owned by this GitLabApi instance + */ + public AwardEmojiApi getAwardEmojiApi() { + + if (awardEmojiApi == null) { + synchronized (this) { if (awardEmojiApi == null) { - synchronized (this) { - if (awardEmojiApi == null) { - awardEmojiApi = new AwardEmojiApi(this); - } - } + awardEmojiApi = new AwardEmojiApi(this); } - - return (awardEmojiApi); + } } - /** - * Gets the BoardsApi instance owned by this GitLabApi instance. The BoardsApi is used - * to perform all Issue Boards related API calls. - * - * @return the BoardsApi instance owned by this GitLabApi instance - */ - public BoardsApi getBoardsApi() { + return (awardEmojiApi); + } + + /** + * Gets the BoardsApi instance owned by this GitLabApi instance. The BoardsApi is used to perform + * all Issue Boards related API calls. + * + * @return the BoardsApi instance owned by this GitLabApi instance + */ + public BoardsApi getBoardsApi() { + if (boardsApi == null) { + synchronized (this) { if (boardsApi == null) { - synchronized (this) { - if (boardsApi == null) { - boardsApi = new BoardsApi(this); - } - } + boardsApi = new BoardsApi(this); } - - return (boardsApi); + } } - /** - * Gets the CommitsApi instance owned by this GitLabApi instance. The CommitsApi is used - * to perform all commit related API calls. - * - * @return the CommitsApi instance owned by this GitLabApi instance - */ - public CommitsApi getCommitsApi() { + return (boardsApi); + } + + /** + * Gets the CommitsApi instance owned by this GitLabApi instance. The CommitsApi is used to + * perform all commit related API calls. + * + * @return the CommitsApi instance owned by this GitLabApi instance + */ + public CommitsApi getCommitsApi() { + if (commitsApi == null) { + synchronized (this) { if (commitsApi == null) { - synchronized (this) { - if (commitsApi == null) { - commitsApi = new CommitsApi(this); - } - } + commitsApi = new CommitsApi(this); } - - return (commitsApi); + } } - /** - * Gets the ContainerRegistryApi instance owned by this GitLabApi instance. The ContainerRegistryApi is used - * to perform all Docker Registry related API calls. - * - * @return the ContainerRegistryApi instance owned by this GitLabApi instance - */ - public ContainerRegistryApi getContainerRegistryApi() { + return (commitsApi); + } + + /** + * Gets the ContainerRegistryApi instance owned by this GitLabApi instance. The + * ContainerRegistryApi is used to perform all Docker Registry related API calls. + * + * @return the ContainerRegistryApi instance owned by this GitLabApi instance + */ + public ContainerRegistryApi getContainerRegistryApi() { + if (containerRegistryApi == null) { + synchronized (this) { if (containerRegistryApi == null) { - synchronized (this) { - if (containerRegistryApi == null) { - containerRegistryApi = new ContainerRegistryApi(this); - } - } + containerRegistryApi = new ContainerRegistryApi(this); } - - return (containerRegistryApi); + } } - /** - * Gets the DeployKeysApi instance owned by this GitLabApi instance. The DeployKeysApi is used - * to perform all deploy key related API calls. - * - * @return the DeployKeysApi instance owned by this GitLabApi instance - */ - public DeployKeysApi getDeployKeysApi() { + return (containerRegistryApi); + } + /** + * Gets the DeployKeysApi instance owned by this GitLabApi instance. The DeployKeysApi is used to + * perform all deploy key related API calls. + * + * @return the DeployKeysApi instance owned by this GitLabApi instance + */ + public DeployKeysApi getDeployKeysApi() { + + if (deployKeysApi == null) { + synchronized (this) { if (deployKeysApi == null) { - synchronized (this) { - if (deployKeysApi == null) { - deployKeysApi = new DeployKeysApi(this); - } - } + deployKeysApi = new DeployKeysApi(this); } - - return (deployKeysApi); + } } - /** - * Gets the DeployKeysApi instance owned by this GitLabApi instance. The DeploymentsApi is used - * to perform all deployment related API calls. - * - * @return the DeploymentsApi instance owned by this GitLabApi instance - */ - public DeploymentsApi getDeploymentsApi() { + return (deployKeysApi); + } + /** + * Gets the DeployKeysApi instance owned by this GitLabApi instance. The DeploymentsApi is used to + * perform all deployment related API calls. + * + * @return the DeploymentsApi instance owned by this GitLabApi instance + */ + public DeploymentsApi getDeploymentsApi() { + + if (deploymentsApi == null) { + synchronized (this) { if (deploymentsApi == null) { - synchronized (this) { - if (deploymentsApi == null) { - deploymentsApi = new DeploymentsApi(this); - } - } + deploymentsApi = new DeploymentsApi(this); } - - return (deploymentsApi); + } } - /** - * Gets the DeployTokensApi instance owned by this GitLabApi instance. The DeployTokensApi is used - * to perform all deploy token related API calls. - * - * @return the DeployTokensApi instance owned by this GitLabApi instance - */ - public DeployTokensApi getDeployTokensApi(){ + return (deploymentsApi); + } + /** + * Gets the DeployTokensApi instance owned by this GitLabApi instance. The DeployTokensApi is used + * to perform all deploy token related API calls. + * + * @return the DeployTokensApi instance owned by this GitLabApi instance + */ + public DeployTokensApi getDeployTokensApi() { + + if (deployTokensApi == null) { + synchronized (this) { if (deployTokensApi == null) { - synchronized (this) { - if (deployTokensApi == null) { - deployTokensApi = new DeployTokensApi(this); - } - } + deployTokensApi = new DeployTokensApi(this); } - - return (deployTokensApi); + } } - /** - * Gets the DiscussionsApi instance owned by this GitLabApi instance. The DiscussionsApi is used - * to perform all discussion related API calls. - * - * @return the DiscussionsApi instance owned by this GitLabApi instance - */ - public DiscussionsApi getDiscussionsApi() { + return (deployTokensApi); + } + /** + * Gets the DiscussionsApi instance owned by this GitLabApi instance. The DiscussionsApi is used + * to perform all discussion related API calls. + * + * @return the DiscussionsApi instance owned by this GitLabApi instance + */ + public DiscussionsApi getDiscussionsApi() { + + if (discussionsApi == null) { + synchronized (this) { if (discussionsApi == null) { - synchronized (this) { - if (discussionsApi == null) { - discussionsApi = new DiscussionsApi(this); - } - } + discussionsApi = new DiscussionsApi(this); } - - return (discussionsApi); + } } - /** - * Gets the EnvironmentsApi instance owned by this GitLabApi instance. The EnvironmentsApi is used - * to perform all environment related API calls. - * - * @return the EnvironmentsApi instance owned by this GitLabApi instance - */ - public EnvironmentsApi getEnvironmentsApi() { + return (discussionsApi); + } + + /** + * Gets the EnvironmentsApi instance owned by this GitLabApi instance. The EnvironmentsApi is used + * to perform all environment related API calls. + * + * @return the EnvironmentsApi instance owned by this GitLabApi instance + */ + public EnvironmentsApi getEnvironmentsApi() { + if (environmentsApi == null) { + synchronized (this) { if (environmentsApi == null) { - synchronized (this) { - if (environmentsApi == null) { - environmentsApi = new EnvironmentsApi(this); - } - } + environmentsApi = new EnvironmentsApi(this); } - - return (environmentsApi); + } } - /** - * Gets the EpicsApi instance owned by this GitLabApi instance. The EpicsApi is used - * to perform all Epics and Epic Issues related API calls. - * - * @return the EpicsApi instance owned by this GitLabApi instance - */ - public EpicsApi getEpicsApi() { + return (environmentsApi); + } + + /** + * Gets the EpicsApi instance owned by this GitLabApi instance. The EpicsApi is used to perform + * all Epics and Epic Issues related API calls. + * + * @return the EpicsApi instance owned by this GitLabApi instance + */ + public EpicsApi getEpicsApi() { + if (epicsApi == null) { + synchronized (this) { if (epicsApi == null) { - synchronized (this) { - if (epicsApi == null) { - epicsApi = new EpicsApi(this); - } - } + epicsApi = new EpicsApi(this); } - - return (epicsApi); + } } - /** - * Gets the EventsApi instance owned by this GitLabApi instance. The EventsApi is used - * to perform all events related API calls. - * - * @return the EventsApi instance owned by this GitLabApi instance - */ - public EventsApi getEventsApi() { + return (epicsApi); + } + + /** + * Gets the EventsApi instance owned by this GitLabApi instance. The EventsApi is used to perform + * all events related API calls. + * + * @return the EventsApi instance owned by this GitLabApi instance + */ + public EventsApi getEventsApi() { + if (eventsApi == null) { + synchronized (this) { if (eventsApi == null) { - synchronized (this) { - if (eventsApi == null) { - eventsApi = new EventsApi(this); - } - } + eventsApi = new EventsApi(this); } - - return (eventsApi); + } } - /** - * Gets the ExternalStatusCheckApi instance owned by this GitLabApi instance. The ExternalStatusCheckApi is used - * to perform all the external status checks related API calls. - * - * @return the ExternalStatusCheckApi instance owned by this GitLabApi instance - */ - public ExternalStatusCheckApi getExternalStatusCheckApi() { + return (eventsApi); + } + /** + * Gets the ExternalStatusCheckApi instance owned by this GitLabApi instance. The + * ExternalStatusCheckApi is used to perform all the external status checks related API calls. + * + * @return the ExternalStatusCheckApi instance owned by this GitLabApi instance + */ + public ExternalStatusCheckApi getExternalStatusCheckApi() { + + if (externalStatusCheckApi == null) { + synchronized (this) { if (externalStatusCheckApi == null) { - synchronized (this) { - if (externalStatusCheckApi == null) { - externalStatusCheckApi = new ExternalStatusCheckApi(this); - } - } + externalStatusCheckApi = new ExternalStatusCheckApi(this); } - - return (externalStatusCheckApi); + } } + return (externalStatusCheckApi); + } - /** - * Gets the GroupApi instance owned by this GitLabApi instance. The GroupApi is used - * to perform all group related API calls. - * - * @return the GroupApi instance owned by this GitLabApi instance - */ - public GroupApi getGroupApi() { + /** + * Gets the GroupApi instance owned by this GitLabApi instance. The GroupApi is used to perform + * all group related API calls. + * + * @return the GroupApi instance owned by this GitLabApi instance + */ + public GroupApi getGroupApi() { + if (groupApi == null) { + synchronized (this) { if (groupApi == null) { - synchronized (this) { - if (groupApi == null) { - groupApi = new GroupApi(this); - } - } + groupApi = new GroupApi(this); } - - return (groupApi); + } } - /** - * Gets the HealthCheckApi instance owned by this GitLabApi instance. The HealthCheckApi is used - * to perform all admin level gitlab health monitoring. - * - * @return the HealthCheckApi instance owned by this GitLabApi instance - */ - public HealthCheckApi getHealthCheckApi() { + return (groupApi); + } + + /** + * Gets the HealthCheckApi instance owned by this GitLabApi instance. The HealthCheckApi is used + * to perform all admin level gitlab health monitoring. + * + * @return the HealthCheckApi instance owned by this GitLabApi instance + */ + public HealthCheckApi getHealthCheckApi() { + if (healthCheckApi == null) { + synchronized (this) { if (healthCheckApi == null) { - synchronized (this) { - if (healthCheckApi == null) { - healthCheckApi = new HealthCheckApi(this); - } - } + healthCheckApi = new HealthCheckApi(this); } - - return (healthCheckApi); + } } - /** - * Gets the ImportExportApi instance owned by this GitLabApi instance. The ImportExportApi is used - * to perform all project import/export related API calls. - * - * @return the ImportExportApi instance owned by this GitLabApi instance - */ - public ImportExportApi getImportExportApi() { + return (healthCheckApi); + } + /** + * Gets the ImportExportApi instance owned by this GitLabApi instance. The ImportExportApi is used + * to perform all project import/export related API calls. + * + * @return the ImportExportApi instance owned by this GitLabApi instance + */ + public ImportExportApi getImportExportApi() { + + if (importExportApi == null) { + synchronized (this) { if (importExportApi == null) { - synchronized (this) { - if (importExportApi == null) { - importExportApi = new ImportExportApi(this); - } - } + importExportApi = new ImportExportApi(this); } - - return (importExportApi); + } } - /** - * Gets the IssuesApi instance owned by this GitLabApi instance. The IssuesApi is used - * to perform all issue related API calls. - * - * @return the IssuesApi instance owned by this GitLabApi instance - */ - public IssuesApi getIssuesApi() { + return (importExportApi); + } + /** + * Gets the IssuesApi instance owned by this GitLabApi instance. The IssuesApi is used to perform + * all issue related API calls. + * + * @return the IssuesApi instance owned by this GitLabApi instance + */ + public IssuesApi getIssuesApi() { + + if (issuesApi == null) { + synchronized (this) { if (issuesApi == null) { - synchronized (this) { - if (issuesApi == null) { - issuesApi = new IssuesApi(this); - } - } + issuesApi = new IssuesApi(this); } - - return (issuesApi); + } } - /** - * Gets the JobApi instance owned by this GitLabApi instance. The JobApi is used - * to perform all jobs related API calls. - * - * @return the JobsApi instance owned by this GitLabApi instance - */ - public JobApi getJobApi() { + return (issuesApi); + } + + /** + * Gets the JobApi instance owned by this GitLabApi instance. The JobApi is used to perform all + * jobs related API calls. + * + * @return the JobsApi instance owned by this GitLabApi instance + */ + public JobApi getJobApi() { + if (jobApi == null) { + synchronized (this) { if (jobApi == null) { - synchronized (this) { - if (jobApi == null) { - jobApi = new JobApi(this); - } - } + jobApi = new JobApi(this); } - - return (jobApi); + } } - public LabelsApi getLabelsApi() { + return (jobApi); + } + + public LabelsApi getLabelsApi() { + if (labelsApi == null) { + synchronized (this) { if (labelsApi == null) { - synchronized (this) { - if (labelsApi == null) { - labelsApi = new LabelsApi(this); - } - } + labelsApi = new LabelsApi(this); } - - return (labelsApi); + } } - /** - * Gets the LicenseApi instance owned by this GitLabApi instance. The LicenseApi is used - * to perform all license related API calls. - * - * @return the LicenseApi instance owned by this GitLabApi instance - */ - public LicenseApi getLicenseApi() { + return (labelsApi); + } + + /** + * Gets the LicenseApi instance owned by this GitLabApi instance. The LicenseApi is used to + * perform all license related API calls. + * + * @return the LicenseApi instance owned by this GitLabApi instance + */ + public LicenseApi getLicenseApi() { + if (licenseApi == null) { + synchronized (this) { if (licenseApi == null) { - synchronized (this) { - if (licenseApi == null) { - licenseApi = new LicenseApi(this); - } - } + licenseApi = new LicenseApi(this); } - - return (licenseApi); + } } - /** - * Gets the LicenseTemplatesApi instance owned by this GitLabApi instance. The LicenseTemplatesApi is used - * to perform all license template related API calls. - * - * @return the LicenseTemplatesApi instance owned by this GitLabApi instance - */ - public LicenseTemplatesApi getLicenseTemplatesApi() { + return (licenseApi); + } + /** + * Gets the LicenseTemplatesApi instance owned by this GitLabApi instance. The LicenseTemplatesApi + * is used to perform all license template related API calls. + * + * @return the LicenseTemplatesApi instance owned by this GitLabApi instance + */ + public LicenseTemplatesApi getLicenseTemplatesApi() { + + if (licenseTemplatesApi == null) { + synchronized (this) { if (licenseTemplatesApi == null) { - synchronized (this) { - if (licenseTemplatesApi == null) { - licenseTemplatesApi = new LicenseTemplatesApi(this); - } - } + licenseTemplatesApi = new LicenseTemplatesApi(this); } - - return (licenseTemplatesApi); + } } + return (licenseTemplatesApi); + } - /** - * Gets the MarkdownApi instance owned by this GitLabApi instance. The MarkdownApi is used - * to perform all markdown related API calls. - * - * @return the MarkdownApi instance owned by this GitLabApi instance - */ - public MarkdownApi getMarkdownApi() { + /** + * Gets the MarkdownApi instance owned by this GitLabApi instance. The MarkdownApi is used to + * perform all markdown related API calls. + * + * @return the MarkdownApi instance owned by this GitLabApi instance + */ + public MarkdownApi getMarkdownApi() { + if (markdownApi == null) { + synchronized (this) { if (markdownApi == null) { - synchronized (this) { - if (markdownApi == null) { - markdownApi = new MarkdownApi(this); - } - } + markdownApi = new MarkdownApi(this); } - - return (markdownApi); + } } - /** - * Gets the MergeRequestApi instance owned by this GitLabApi instance. The MergeRequestApi is used - * to perform all merge request related API calls. - * - * @return the MergeRequestApi instance owned by this GitLabApi instance - */ - public MergeRequestApi getMergeRequestApi() { + return (markdownApi); + } + + /** + * Gets the MergeRequestApi instance owned by this GitLabApi instance. The MergeRequestApi is used + * to perform all merge request related API calls. + * + * @return the MergeRequestApi instance owned by this GitLabApi instance + */ + public MergeRequestApi getMergeRequestApi() { + if (mergeRequestApi == null) { + synchronized (this) { if (mergeRequestApi == null) { - synchronized (this) { - if (mergeRequestApi == null) { - mergeRequestApi = new MergeRequestApi(this); - } - } + mergeRequestApi = new MergeRequestApi(this); } - - return (mergeRequestApi); + } } - /** - * Gets the MilsestonesApi instance owned by this GitLabApi instance. - * - * @return the MilsestonesApi instance owned by this GitLabApi instance - */ - public MilestonesApi getMilestonesApi() { + return (mergeRequestApi); + } + /** + * Gets the MilsestonesApi instance owned by this GitLabApi instance. + * + * @return the MilsestonesApi instance owned by this GitLabApi instance + */ + public MilestonesApi getMilestonesApi() { + + if (milestonesApi == null) { + synchronized (this) { if (milestonesApi == null) { - synchronized (this) { - if (milestonesApi == null) { - milestonesApi = new MilestonesApi(this); - } - } + milestonesApi = new MilestonesApi(this); } - - return (milestonesApi); + } } - /** - * Gets the NamespaceApi instance owned by this GitLabApi instance. The NamespaceApi is used - * to perform all namespace related API calls. - * - * @return the NamespaceApi instance owned by this GitLabApi instance - */ - public NamespaceApi getNamespaceApi() { + return (milestonesApi); + } + /** + * Gets the NamespaceApi instance owned by this GitLabApi instance. The NamespaceApi is used to + * perform all namespace related API calls. + * + * @return the NamespaceApi instance owned by this GitLabApi instance + */ + public NamespaceApi getNamespaceApi() { + + if (namespaceApi == null) { + synchronized (this) { if (namespaceApi == null) { - synchronized (this) { - if (namespaceApi == null) { - namespaceApi = new NamespaceApi(this); - } - } + namespaceApi = new NamespaceApi(this); } - - return (namespaceApi); + } } - /** - * Gets the NotesApi instance owned by this GitLabApi instance. The NotesApi is used - * to perform all notes related API calls. - * - * @return the NotesApi instance owned by this GitLabApi instance - */ - public NotesApi getNotesApi() { + return (namespaceApi); + } + + /** + * Gets the NotesApi instance owned by this GitLabApi instance. The NotesApi is used to perform + * all notes related API calls. + * + * @return the NotesApi instance owned by this GitLabApi instance + */ + public NotesApi getNotesApi() { + if (notesApi == null) { + synchronized (this) { if (notesApi == null) { - synchronized (this) { - if (notesApi == null) { - notesApi = new NotesApi(this); - } - } + notesApi = new NotesApi(this); } - - return (notesApi); + } } - /** - * Gets the NotesApi instance owned by this GitLabApi instance. The NotesApi is used - * to perform all notes related API calls. - * - * @return the NotesApi instance owned by this GitLabApi instance - */ - public NotificationSettingsApi getNotificationSettingsApi() { + return (notesApi); + } + + /** + * Gets the NotesApi instance owned by this GitLabApi instance. The NotesApi is used to perform + * all notes related API calls. + * + * @return the NotesApi instance owned by this GitLabApi instance + */ + public NotificationSettingsApi getNotificationSettingsApi() { + if (notificationSettingsApi == null) { + synchronized (this) { if (notificationSettingsApi == null) { - synchronized (this) { - if (notificationSettingsApi == null) { - notificationSettingsApi = new NotificationSettingsApi(this); - } - } + notificationSettingsApi = new NotificationSettingsApi(this); } - - return (notificationSettingsApi); + } } - /** - * Gets the PackagesApi instance owned by this GitLabApi instance. The PackagesApi is used - * to perform all Package related API calls. - * - * @return the PackagesApi instance owned by this GitLabApi instance - */ - public PackagesApi getPackagesApi() { + return (notificationSettingsApi); + } + + /** + * Gets the PackagesApi instance owned by this GitLabApi instance. The PackagesApi is used to + * perform all Package related API calls. + * + * @return the PackagesApi instance owned by this GitLabApi instance + */ + public PackagesApi getPackagesApi() { + if (packagesApi == null) { + synchronized (this) { if (packagesApi == null) { - synchronized (this) { - if (packagesApi == null) { - packagesApi = new PackagesApi(this); - } - } + packagesApi = new PackagesApi(this); } - - return (packagesApi); + } } - /** - * Gets the PipelineApi instance owned by this GitLabApi instance. The PipelineApi is used - * to perform all pipeline related API calls. - * - * @return the PipelineApi instance owned by this GitLabApi instance - */ - public PipelineApi getPipelineApi() { + return (packagesApi); + } + /** + * Gets the PipelineApi instance owned by this GitLabApi instance. The PipelineApi is used to + * perform all pipeline related API calls. + * + * @return the PipelineApi instance owned by this GitLabApi instance + */ + public PipelineApi getPipelineApi() { + + if (pipelineApi == null) { + synchronized (this) { if (pipelineApi == null) { - synchronized (this) { - if (pipelineApi == null) { - pipelineApi = new PipelineApi(this); - } - } + pipelineApi = new PipelineApi(this); } - - return (pipelineApi); + } } - /** - * Gets the ProjectApi instance owned by this GitLabApi instance. The ProjectApi is used - * to perform all project related API calls. - * - * @return the ProjectApi instance owned by this GitLabApi instance - */ - public ProjectApi getProjectApi() { + return (pipelineApi); + } + /** + * Gets the ProjectApi instance owned by this GitLabApi instance. The ProjectApi is used to + * perform all project related API calls. + * + * @return the ProjectApi instance owned by this GitLabApi instance + */ + public ProjectApi getProjectApi() { + + if (projectApi == null) { + synchronized (this) { if (projectApi == null) { - synchronized (this) { - if (projectApi == null) { - projectApi = new ProjectApi(this); - } - } + projectApi = new ProjectApi(this); } - - return (projectApi); + } } - /** - * Gets the ProtectedBranchesApi instance owned by this GitLabApi instance. The ProtectedBranchesApi is used - * to perform all protection related actions on a branch of a project. - * - * @return the ProtectedBranchesApi instance owned by this GitLabApi instance - */ - public ProtectedBranchesApi getProtectedBranchesApi() { + return (projectApi); + } + + /** + * Gets the ProtectedBranchesApi instance owned by this GitLabApi instance. The + * ProtectedBranchesApi is used to perform all protection related actions on a branch of a + * project. + * + * @return the ProtectedBranchesApi instance owned by this GitLabApi instance + */ + public ProtectedBranchesApi getProtectedBranchesApi() { + if (this.protectedBranchesApi == null) { + synchronized (this) { if (this.protectedBranchesApi == null) { - synchronized (this) { - if (this.protectedBranchesApi == null) { - this.protectedBranchesApi = new ProtectedBranchesApi(this); - } - } + this.protectedBranchesApi = new ProtectedBranchesApi(this); } - - return (this.protectedBranchesApi); + } } - /** - * Gets the ReleasesApi instance owned by this GitLabApi instance. The ReleasesApi is used - * to perform all release related API calls. - * - * @return the ReleasesApi instance owned by this GitLabApi instance - */ - public ReleasesApi getReleasesApi() { + return (this.protectedBranchesApi); + } + + /** + * Gets the ReleasesApi instance owned by this GitLabApi instance. The ReleasesApi is used to + * perform all release related API calls. + * + * @return the ReleasesApi instance owned by this GitLabApi instance + */ + public ReleasesApi getReleasesApi() { + if (releasesApi == null) { + synchronized (this) { if (releasesApi == null) { - synchronized (this) { - if (releasesApi == null) { - releasesApi = new ReleasesApi(this); - } - } + releasesApi = new ReleasesApi(this); } - - return (releasesApi); + } } - /** - * Gets the RepositoryApi instance owned by this GitLabApi instance. The RepositoryApi is used - * to perform all repository related API calls. - * - * @return the RepositoryApi instance owned by this GitLabApi instance - */ - public RepositoryApi getRepositoryApi() { + return (releasesApi); + } + + /** + * Gets the RepositoryApi instance owned by this GitLabApi instance. The RepositoryApi is used to + * perform all repository related API calls. + * + * @return the RepositoryApi instance owned by this GitLabApi instance + */ + public RepositoryApi getRepositoryApi() { + if (repositoryApi == null) { + synchronized (this) { if (repositoryApi == null) { - synchronized (this) { - if (repositoryApi == null) { - repositoryApi = new RepositoryApi(this); - } - } + repositoryApi = new RepositoryApi(this); } - - return (repositoryApi); + } } - /** - * Gets the RepositoryFileApi instance owned by this GitLabApi instance. The RepositoryFileApi is used - * to perform all repository files related API calls. - * - * @return the RepositoryFileApi instance owned by this GitLabApi instance - */ - public RepositoryFileApi getRepositoryFileApi() { + return (repositoryApi); + } + /** + * Gets the RepositoryFileApi instance owned by this GitLabApi instance. The RepositoryFileApi is + * used to perform all repository files related API calls. + * + * @return the RepositoryFileApi instance owned by this GitLabApi instance + */ + public RepositoryFileApi getRepositoryFileApi() { + + if (repositoryFileApi == null) { + synchronized (this) { if (repositoryFileApi == null) { - synchronized (this) { - if (repositoryFileApi == null) { - repositoryFileApi = new RepositoryFileApi(this); - } - } + repositoryFileApi = new RepositoryFileApi(this); } - - return (repositoryFileApi); + } } - /** - * Gets the ResourceLabelEventsApi instance owned by this GitLabApi instance. The ResourceLabelEventsApi - * is used to perform all Resource Label Events related API calls. - * - * @return the ResourceLabelEventsApi instance owned by this GitLabApi instance - */ - public ResourceLabelEventsApi getResourceLabelEventsApi() { + return (repositoryFileApi); + } + /** + * Gets the ResourceLabelEventsApi instance owned by this GitLabApi instance. The + * ResourceLabelEventsApi is used to perform all Resource Label Events related API calls. + * + * @return the ResourceLabelEventsApi instance owned by this GitLabApi instance + */ + public ResourceLabelEventsApi getResourceLabelEventsApi() { + + if (resourceLabelEventsApi == null) { + synchronized (this) { if (resourceLabelEventsApi == null) { - synchronized (this) { - if (resourceLabelEventsApi == null) { - resourceLabelEventsApi = new ResourceLabelEventsApi(this); - } - } + resourceLabelEventsApi = new ResourceLabelEventsApi(this); } - - return (resourceLabelEventsApi); + } } - /** - * Gets the ResourceStateEventsApi instance owned by this GitLabApi instance. The ResourceStateEventsApi - * is used to perform all Resource State Events related API calls. - * - * @return the ResourceStateEventsApi instance owned by this GitLabApi instance - */ - public ResourceStateEventsApi getResourceStateEventsApi() { + return (resourceLabelEventsApi); + } + + /** + * Gets the ResourceStateEventsApi instance owned by this GitLabApi instance. The + * ResourceStateEventsApi is used to perform all Resource State Events related API calls. + * + * @return the ResourceStateEventsApi instance owned by this GitLabApi instance + */ + public ResourceStateEventsApi getResourceStateEventsApi() { + if (resourceStateEventsApi == null) { + synchronized (this) { if (resourceStateEventsApi == null) { - synchronized (this) { - if (resourceStateEventsApi == null) { - resourceStateEventsApi = new ResourceStateEventsApi(this); - } - } + resourceStateEventsApi = new ResourceStateEventsApi(this); } - - return (resourceStateEventsApi); + } } - /** - * Gets the RunnersApi instance owned by this GitLabApi instance. The RunnersApi is used - * to perform all Runner related API calls. - * - * @return the RunnerApi instance owned by this GitLabApi instance - */ - public RunnersApi getRunnersApi() { + return (resourceStateEventsApi); + } + + /** + * Gets the RunnersApi instance owned by this GitLabApi instance. The RunnersApi is used to + * perform all Runner related API calls. + * + * @return the RunnerApi instance owned by this GitLabApi instance + */ + public RunnersApi getRunnersApi() { + if (runnersApi == null) { + synchronized (this) { if (runnersApi == null) { - synchronized (this) { - if (runnersApi == null) { - runnersApi = new RunnersApi(this); - } - } + runnersApi = new RunnersApi(this); } - - return (runnersApi); + } } - /** - * Gets the SearchApi instance owned by this GitLabApi instance. The SearchApi is used - * to perform search related API calls. - * - * @return the SearchApi instance owned by this GitLabApi instance - */ - public SearchApi getSearchApi() { + return (runnersApi); + } + + /** + * Gets the SearchApi instance owned by this GitLabApi instance. The SearchApi is used to perform + * search related API calls. + * + * @return the SearchApi instance owned by this GitLabApi instance + */ + public SearchApi getSearchApi() { + if (searchApi == null) { + synchronized (this) { if (searchApi == null) { - synchronized (this) { - if (searchApi == null) { - searchApi = new SearchApi(this); - } - } + searchApi = new SearchApi(this); } - - return (searchApi); + } } - /** - * Gets the ServicesApi instance owned by this GitLabApi instance. The ServicesApi is used - * to perform all services related API calls. - * - * @return the ServicesApi instance owned by this GitLabApi instance - */ - public ServicesApi getServicesApi() { + return (searchApi); + } + /** + * Gets the ServicesApi instance owned by this GitLabApi instance. The ServicesApi is used to + * perform all services related API calls. + * + * @return the ServicesApi instance owned by this GitLabApi instance + */ + public ServicesApi getServicesApi() { + + if (servicesApi == null) { + synchronized (this) { if (servicesApi == null) { - synchronized (this) { - if (servicesApi == null) { - servicesApi = new ServicesApi(this); - } - } + servicesApi = new ServicesApi(this); } - - return (servicesApi); + } } - /** - * Gets the SystemHooksApi instance owned by this GitLabApi instance. All methods - * require administrator authorization. - * - * @return the SystemHooksApi instance owned by this GitLabApi instance - */ - public SystemHooksApi getSystemHooksApi() { + return (servicesApi); + } + /** + * Gets the SystemHooksApi instance owned by this GitLabApi instance. All methods require + * administrator authorization. + * + * @return the SystemHooksApi instance owned by this GitLabApi instance + */ + public SystemHooksApi getSystemHooksApi() { + + if (systemHooksApi == null) { + synchronized (this) { if (systemHooksApi == null) { - synchronized (this) { - if (systemHooksApi == null) { - systemHooksApi = new SystemHooksApi(this); - } - } + systemHooksApi = new SystemHooksApi(this); } - - return (systemHooksApi); + } } - /** - * Gets the TagsApi instance owned by this GitLabApi instance. The TagsApi is used - * to perform all tag and release related API calls. - * - * @return the TagsApi instance owned by this GitLabApi instance - */ - public TagsApi getTagsApi() { + return (systemHooksApi); + } + + /** + * Gets the TagsApi instance owned by this GitLabApi instance. The TagsApi is used to perform all + * tag and release related API calls. + * + * @return the TagsApi instance owned by this GitLabApi instance + */ + public TagsApi getTagsApi() { + if (tagsApi == null) { + synchronized (this) { if (tagsApi == null) { - synchronized (this) { - if (tagsApi == null) { - tagsApi = new TagsApi(this); - } - } + tagsApi = new TagsApi(this); } - - return (tagsApi); + } } - /** - * Gets the SnippetsApi instance owned by this GitLabApi instance. The SnippetsApi is used - * to perform all snippet related API calls. - * - * @return the SnippetsApi instance owned by this GitLabApi instance - */ - public SnippetsApi getSnippetApi() { + return (tagsApi); + } + + /** + * Gets the SnippetsApi instance owned by this GitLabApi instance. The SnippetsApi is used to + * perform all snippet related API calls. + * + * @return the SnippetsApi instance owned by this GitLabApi instance + */ + public SnippetsApi getSnippetApi() { + if (snippetsApi == null) { + synchronized (this) { if (snippetsApi == null) { - synchronized (this) { - if (snippetsApi == null) { - snippetsApi = new SnippetsApi(this); - } - } + snippetsApi = new SnippetsApi(this); } - - return snippetsApi; + } } - /** - * Gets the TodosApi instance owned by this GitLabApi instance. The TodosApi is used to perform all Todo related API calls. - * - * @return the TodosApi instance owned by this GitLabApi instance - */ - public TodosApi getTodosApi() { + return snippetsApi; + } + + /** + * Gets the TodosApi instance owned by this GitLabApi instance. The TodosApi is used to perform + * all Todo related API calls. + * + * @return the TodosApi instance owned by this GitLabApi instance + */ + public TodosApi getTodosApi() { + if (todosApi == null) { + synchronized (this) { if (todosApi == null) { - synchronized (this) { - if (todosApi == null) { - todosApi = new TodosApi(this); - } - } + todosApi = new TodosApi(this); } - - return todosApi; + } } - /** - * Gets the UserApi instance owned by this GitLabApi instance. The UserApi is used - * to perform all user related API calls. - * - * @return the UserApi instance owned by this GitLabApi instance - */ - public UserApi getUserApi() { + return todosApi; + } - if (userApi == null) { - synchronized (this) { - if (userApi == null) { - userApi = new UserApi(this); - } - } - } + /** + * Gets the UserApi instance owned by this GitLabApi instance. The UserApi is used to perform all + * user related API calls. + * + * @return the UserApi instance owned by this GitLabApi instance + */ + public UserApi getUserApi() { - return (userApi); - } - - /** - * Gets the WikisApi instance owned by this GitLabApi instance. The WikisApi is used to perform all wiki related API calls. - * - * @return the WikisApi instance owned by this GitLabApi instance - */ - public WikisApi getWikisApi() { - if (wikisApi == null) { - synchronized (this) { - if (wikisApi == null) { - wikisApi = new WikisApi(this); - } - } + if (userApi == null) { + synchronized (this) { + if (userApi == null) { + userApi = new UserApi(this); } - - return wikisApi; + } } - /** - * Gets the KeysApi instance owned by this GitLabApi instance. The KeysApi is used to look up users by their ssh key signatures - * - * @return the KeysApi instance owned by this GitLabApi instance - */ - public KeysApi getKeysAPI() { - synchronized (this) { - if (keysApi == null) { - keysApi = new KeysApi(this); - } - } - return keysApi; - } - - - /** - * Create and return an Optional instance associated with a GitLabApiException. - * - * @param the type of the Optional instance - * @param glae the GitLabApiException that was the result of a call to the GitLab API - * @return the created Optional instance - */ - protected static final Optional createOptionalFromException(GitLabApiException glae) { - Optional optional = Optional.empty(); - optionalExceptionMap.put(System.identityHashCode(optional), glae); - return (optional); - } - - /** - * Get the exception associated with the provided Optional instance, or null if no exception is - * associated with the Optional instance. - * - * @param optional the Optional instance to get the exception for - * @return the exception associated with the provided Optional instance, or null if no exception is - * associated with the Optional instance - */ - public static final GitLabApiException getOptionalException(Optional optional) { - return (optionalExceptionMap.get(System.identityHashCode(optional))); - } - - /** - * Return the Optional instances contained value, if present, otherwise throw the exception that is - * associated with the Optional instance. - * - * @param the type for the Optional parameter - * @param optional the Optional instance to get the value for - * @return the value of the Optional instance if no exception is associated with it - * @throws GitLabApiException if there was an exception associated with the Optional instance - */ - public static final T orElseThrow(Optional optional) throws GitLabApiException { - - GitLabApiException glea = getOptionalException(optional); - if (glea != null) { - throw (glea); - } + return (userApi); + } - return (optional.get()); - } + /** + * Gets the WikisApi instance owned by this GitLabApi instance. The WikisApi is used to perform + * all wiki related API calls. + * + * @return the WikisApi instance owned by this GitLabApi instance + */ + public WikisApi getWikisApi() { + if (wikisApi == null) { + synchronized (this) { + if (wikisApi == null) { + wikisApi = new WikisApi(this); + } + } + } + + return wikisApi; + } + + /** + * Gets the KeysApi instance owned by this GitLabApi instance. The KeysApi is used to look up + * users by their ssh key signatures + * + * @return the KeysApi instance owned by this GitLabApi instance + */ + public KeysApi getKeysAPI() { + synchronized (this) { + if (keysApi == null) { + keysApi = new KeysApi(this); + } + } + return keysApi; + } + + /** + * Create and return an Optional instance associated with a GitLabApiException. + * + * @param the type of the Optional instance + * @param glae the GitLabApiException that was the result of a call to the GitLab API + * @return the created Optional instance + */ + protected static final Optional createOptionalFromException( + final GitLabApiException glae) { + final Optional optional = Optional.empty(); + optionalExceptionMap.put(System.identityHashCode(optional), glae); + return (optional); + } + + /** + * Get the exception associated with the provided Optional instance, or null if no exception is + * associated with the Optional instance. + * + * @param optional the Optional instance to get the exception for + * @return the exception associated with the provided Optional instance, or null if no exception + * is associated with the Optional instance + */ + public static final GitLabApiException getOptionalException(final Optional optional) { + return (optionalExceptionMap.get(System.identityHashCode(optional))); + } + + /** + * Return the Optional instances contained value, if present, otherwise throw the exception that + * is associated with the Optional instance. + * + * @param the type for the Optional parameter + * @param optional the Optional instance to get the value for + * @return the value of the Optional instance if no exception is associated with it + * @throws GitLabApiException if there was an exception associated with the Optional instance + */ + public static final T orElseThrow(final Optional optional) throws GitLabApiException { + + final GitLabApiException glea = getOptionalException(optional); + if (glea != null) { + throw (glea); + } + + return (optional.get()); + } } diff --git a/src/main/java/org/gitlab4j/api/GitLabApiClient.java b/src/main/java/org/gitlab4j/api/GitLabApiClient.java index 169e185ce..01f1a92bf 100755 --- a/src/main/java/org/gitlab4j/api/GitLabApiClient.java +++ b/src/main/java/org/gitlab4j/api/GitLabApiClient.java @@ -1,5 +1,15 @@ package org.gitlab4j.api; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.ClientBuilder; +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.client.WebTarget; +import jakarta.ws.rs.core.Form; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.StreamingOutput; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -20,16 +30,6 @@ import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509ExtendedTrustManager; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.Form; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.StreamingOutput; import org.gitlab4j.api.Constants.TokenType; import org.gitlab4j.api.GitLabApi.ApiVersion; import org.gitlab4j.api.utils.JacksonJson; @@ -47,930 +47,1004 @@ import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; import org.glassfish.jersey.media.multipart.file.StreamDataBodyPart; - -/** - * This class utilizes the Jersey client package to communicate with a GitLab API endpoint. - */ +/** This class utilizes the Jersey client package to communicate with a GitLab API endpoint. */ public class GitLabApiClient implements AutoCloseable { - protected static final String PRIVATE_TOKEN_HEADER = "PRIVATE-TOKEN"; - protected static final String SUDO_HEADER = "Sudo"; - protected static final String AUTHORIZATION_HEADER = "Authorization"; - protected static final String X_GITLAB_TOKEN_HEADER = "X-Gitlab-Token"; - - private ClientConfig clientConfig; - private Client apiClient; - private String baseUrl; - private String hostUrl; - private TokenType tokenType = TokenType.PRIVATE; - private Supplier authToken; - private String secretToken; - private boolean ignoreCertificateErrors; - private SSLContext openSslContext; - private HostnameVerifier openHostnameVerifier; - private Long sudoAsId; - private Integer connectTimeout; - private Integer readTimeout; - - /** - * Construct an instance to communicate with a GitLab API server using the specified GitLab API version, - * server URL, private token, and secret token. - * - * @param apiVersion the ApiVersion specifying which version of the API to use - * @param hostUrl the URL to the GitLab API server - * @param privateToken the private token to authenticate with - */ - public GitLabApiClient(ApiVersion apiVersion, String hostUrl, String privateToken) { - this(apiVersion, hostUrl, TokenType.PRIVATE, privateToken, null); + protected static final String PRIVATE_TOKEN_HEADER = "PRIVATE-TOKEN"; + protected static final String SUDO_HEADER = "Sudo"; + protected static final String AUTHORIZATION_HEADER = "Authorization"; + protected static final String X_GITLAB_TOKEN_HEADER = "X-Gitlab-Token"; + + private final ClientConfig clientConfig; + private Client apiClient; + private final String baseUrl; + private String hostUrl; + private TokenType tokenType = TokenType.PRIVATE; + private Supplier authToken; + private final String secretToken; + private boolean ignoreCertificateErrors; + private SSLContext openSslContext; + private HostnameVerifier openHostnameVerifier; + private Long sudoAsId; + private Integer connectTimeout; + private Integer readTimeout; + + /** + * Construct an instance to communicate with a GitLab API server using the specified GitLab API + * version, server URL, private token, and secret token. + * + * @param apiVersion the ApiVersion specifying which version of the API to use + * @param hostUrl the URL to the GitLab API server + * @param privateToken the private token to authenticate with + */ + public GitLabApiClient(final ApiVersion apiVersion, final String hostUrl, final String privateToken) { + this(apiVersion, hostUrl, TokenType.PRIVATE, privateToken, null); + } + + /** + * Construct an instance to communicate with a GitLab API server using the specified GitLab API + * version, server URL, auth token type, private or access token, and secret token. + * + * @param apiVersion the ApiVersion specifying which version of the API to use + * @param hostUrl the URL to the GitLab API server + * @param tokenType the type of auth the token is for, PRIVATE or ACCESS + * @param authToken the token to authenticate with + */ + public GitLabApiClient( + final ApiVersion apiVersion, final String hostUrl, final TokenType tokenType, final String authToken) { + this(apiVersion, hostUrl, tokenType, authToken, null); + } + + /** + * Construct an instance to communicate with a GitLab API server using GitLab API version 4, and + * the specified server URL, private token, and secret token. + * + * @param hostUrl the URL to the GitLab API server + * @param privateToken the private token to authenticate with + */ + public GitLabApiClient(final String hostUrl, final String privateToken) { + this(ApiVersion.V4, hostUrl, TokenType.PRIVATE, privateToken, null); + } + + /** + * Construct an instance to communicate with a GitLab API server using GitLab API version 4, and + * the specified server URL, private token, and secret token. + * + * @param hostUrl the URL to the GitLab API server + * @param tokenType the type of auth the token is for, PRIVATE or ACCESS + * @param authToken the token to authenticate with + */ + public GitLabApiClient(final String hostUrl, final TokenType tokenType, final String authToken) { + this(ApiVersion.V4, hostUrl, tokenType, authToken, null); + } + + /** + * Construct an instance to communicate with a GitLab API server using the specified GitLab API + * version, server URL, private token, and secret token. + * + * @param apiVersion the ApiVersion specifying which version of the API to use + * @param hostUrl the URL to the GitLab API server + * @param privateToken the private token to authenticate with + * @param secretToken use this token to validate received payloads + */ + public GitLabApiClient( + final ApiVersion apiVersion, final String hostUrl, final String privateToken, final String secretToken) { + this(apiVersion, hostUrl, TokenType.PRIVATE, privateToken, secretToken, null); + } + + /** + * Construct an instance to communicate with a GitLab API server using the specified GitLab API + * version, server URL, private token, and secret token. + * + * @param apiVersion the ApiVersion specifying which version of the API to use + * @param hostUrl the URL to the GitLab API server + * @param tokenType the type of auth the token is for, PRIVATE or ACCESS + * @param authToken the token to authenticate with + * @param secretToken use this token to validate received payloads + */ + public GitLabApiClient( + final ApiVersion apiVersion, + final String hostUrl, + final TokenType tokenType, + final String authToken, + final String secretToken) { + this(apiVersion, hostUrl, tokenType, authToken, secretToken, null); + } + + /** + * Construct an instance to communicate with a GitLab API server using GitLab API version 4, and + * the specified server URL, private token, and secret token. + * + * @param hostUrl the URL to the GitLab API server + * @param privateToken the private token to authenticate with + * @param secretToken use this token to validate received payloads + */ + public GitLabApiClient(final String hostUrl, final String privateToken, final String secretToken) { + this(ApiVersion.V4, hostUrl, TokenType.PRIVATE, privateToken, secretToken, null); + } + + /** + * Construct an instance to communicate with a GitLab API server using GitLab API version 4, and + * the specified server URL, private token, and secret token. + * + * @param hostUrl the URL to the GitLab API server + * @param tokenType the type of auth the token is for, PRIVATE or ACCESS + * @param authToken the token to authenticate with + * @param secretToken use this token to validate received payloads + */ + public GitLabApiClient( + final String hostUrl, final TokenType tokenType, final String authToken, final String secretToken) { + this(ApiVersion.V4, hostUrl, tokenType, authToken, secretToken, null); + } + + /** + * Construct an instance to communicate with a GitLab API server using GitLab API version 4, and + * the specified server URL and private token. + * + * @param hostUrl the URL to the GitLab API server + * @param privateToken the private token to authenticate with + * @param secretToken use this token to validate received payloads + * @param clientConfigProperties the properties given to Jersey's clientconfig + */ + public GitLabApiClient( + final String hostUrl, + final String privateToken, + final String secretToken, + final Map clientConfigProperties) { + this( + ApiVersion.V4, + hostUrl, + TokenType.PRIVATE, + privateToken, + secretToken, + clientConfigProperties); + } + + /** + * Construct an instance to communicate with a GitLab API server using the specified GitLab API + * version, server URL and private token. + * + * @param apiVersion the ApiVersion specifying which version of the API to use + * @param hostUrl the URL to the GitLab API server + * @param privateToken the private token to authenticate with + * @param secretToken use this token to validate received payloads + * @param clientConfigProperties the properties given to Jersey's clientconfig + */ + public GitLabApiClient( + final ApiVersion apiVersion, + final String hostUrl, + final String privateToken, + final String secretToken, + final Map clientConfigProperties) { + this(apiVersion, hostUrl, TokenType.PRIVATE, privateToken, secretToken, clientConfigProperties); + } + + /** + * Construct an instance to communicate with a GitLab API server using the specified GitLab API + * version, server URL and private token. + * + * @param apiVersion the ApiVersion specifying which version of the API to use + * @param hostUrl the URL to the GitLab API server + * @param tokenType the type of auth the token is for, PRIVATE or ACCESS + * @param authToken the private token to authenticate with + * @param secretToken use this token to validate received payloads + * @param clientConfigProperties the properties given to Jersey's clientconfig + */ + public GitLabApiClient( + final ApiVersion apiVersion, + final String hostUrl, + final TokenType tokenType, + final String authToken, + String secretToken, + final Map clientConfigProperties) { + + // Remove the trailing "/" from the hostUrl if present + this.hostUrl = (hostUrl.endsWith("/") ? hostUrl.replaceAll("/$", "") : hostUrl); + this.baseUrl = this.hostUrl; + this.hostUrl += apiVersion.getApiNamespace(); + + this.tokenType = tokenType; + this.authToken = () -> authToken; + + if (secretToken != null) { + secretToken = secretToken.trim(); + secretToken = (secretToken.length() > 0 ? secretToken : null); } - /** - * Construct an instance to communicate with a GitLab API server using the specified GitLab API version, - * server URL, auth token type, private or access token, and secret token. - * - * @param apiVersion the ApiVersion specifying which version of the API to use - * @param hostUrl the URL to the GitLab API server - * @param tokenType the type of auth the token is for, PRIVATE or ACCESS - * @param authToken the token to authenticate with - */ - public GitLabApiClient(ApiVersion apiVersion, String hostUrl, TokenType tokenType, String authToken) { - this(apiVersion, hostUrl, tokenType, authToken, null); - } + this.secretToken = secretToken; - /** - * Construct an instance to communicate with a GitLab API server using GitLab API version 4, and the specified - * server URL, private token, and secret token. - * - * @param hostUrl the URL to the GitLab API server - * @param privateToken the private token to authenticate with - */ - public GitLabApiClient(String hostUrl, String privateToken) { - this(ApiVersion.V4, hostUrl, TokenType.PRIVATE, privateToken, null); - } + clientConfig = new ClientConfig(); + if (clientConfigProperties != null) { - /** - * Construct an instance to communicate with a GitLab API server using GitLab API version 4, and the specified - * server URL, private token, and secret token. - * - * @param hostUrl the URL to the GitLab API server - * @param tokenType the type of auth the token is for, PRIVATE or ACCESS - * @param authToken the token to authenticate with - */ - public GitLabApiClient(String hostUrl, TokenType tokenType, String authToken) { - this(ApiVersion.V4, hostUrl, tokenType, authToken, null); - } + if (clientConfigProperties.containsKey(ClientProperties.PROXY_URI)) { + clientConfig.connectorProvider(new ApacheConnectorProvider()); + } - /** - * Construct an instance to communicate with a GitLab API server using the specified GitLab API version, - * server URL, private token, and secret token. - * - * @param apiVersion the ApiVersion specifying which version of the API to use - * @param hostUrl the URL to the GitLab API server - * @param privateToken the private token to authenticate with - * @param secretToken use this token to validate received payloads - */ - public GitLabApiClient(ApiVersion apiVersion, String hostUrl, String privateToken, String secretToken) { - this(apiVersion, hostUrl, TokenType.PRIVATE, privateToken, secretToken, null); + for (final Map.Entry propertyEntry : clientConfigProperties.entrySet()) { + clientConfig.property(propertyEntry.getKey(), propertyEntry.getValue()); + } } - /** - * Construct an instance to communicate with a GitLab API server using the specified GitLab API version, - * server URL, private token, and secret token. - * - * @param apiVersion the ApiVersion specifying which version of the API to use - * @param hostUrl the URL to the GitLab API server - * @param tokenType the type of auth the token is for, PRIVATE or ACCESS - * @param authToken the token to authenticate with - * @param secretToken use this token to validate received payloads - */ - public GitLabApiClient(ApiVersion apiVersion, String hostUrl, TokenType tokenType, String authToken, String secretToken) { - this(apiVersion, hostUrl, tokenType, authToken, secretToken, null); + // Disable auto-discovery of feature and services lookup, this will force Jersey + // to use the features and services explicitly configured by gitlab4j + clientConfig.property(ClientProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true); + clientConfig.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, true); + + clientConfig.register(JacksonJson.class); + clientConfig.register(JacksonFeature.class); + clientConfig.register(MultiPartFeature.class); + } + + /** Close the underlying {@link Client} and its associated resources. */ + @Override + public void close() { + if (apiClient != null) { + apiClient.close(); } - - /** - * Construct an instance to communicate with a GitLab API server using GitLab API version 4, and the specified - * server URL, private token, and secret token. - * - * @param hostUrl the URL to the GitLab API server - * @param privateToken the private token to authenticate with - * @param secretToken use this token to validate received payloads - */ - public GitLabApiClient(String hostUrl, String privateToken, String secretToken) { - this(ApiVersion.V4, hostUrl, TokenType.PRIVATE, privateToken, secretToken, null); + } + + /** + * Enable the logging of the requests to and the responses from the GitLab server API. + * + * @param logger the Logger instance to log to + * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) + * @param maxEntityLength maximum number of entity bytes to be logged. When logging if the + * maxEntitySize is reached, the entity logging will be truncated at maxEntitySize and + * "...more..." will be added at the end of the log entry. If maxEntitySize is <= 0, entity + * logging will be disabled + * @param maskedHeaderNames a list of header names that should have the values masked + */ + void enableRequestResponseLogging( + final Logger logger, final Level level, final int maxEntityLength, final List maskedHeaderNames) { + + final MaskingLoggingFilter loggingFilter = + new MaskingLoggingFilter(logger, level, maxEntityLength, maskedHeaderNames); + clientConfig.register(loggingFilter); + + // Recreate the Client instance if already created. + if (apiClient != null) { + createApiClient(); } - - /** - * Construct an instance to communicate with a GitLab API server using GitLab API version 4, and the specified - * server URL, private token, and secret token. - * - * @param hostUrl the URL to the GitLab API server - * @param tokenType the type of auth the token is for, PRIVATE or ACCESS - * @param authToken the token to authenticate with - * @param secretToken use this token to validate received payloads - */ - public GitLabApiClient(String hostUrl, TokenType tokenType, String authToken, String secretToken) { - this(ApiVersion.V4, hostUrl, tokenType, authToken, secretToken, null); + } + + /** + * Sets the per request connect and read timeout. + * + * @param connectTimeout the per request connect timeout in milliseconds, can be null to use + * default + * @param readTimeout the per request read timeout in milliseconds, can be null to use default + */ + void setRequestTimeout(final Integer connectTimeout, final Integer readTimeout) { + this.connectTimeout = connectTimeout; + this.readTimeout = readTimeout; + } + + /** + * Get the auth token being used by this client. + * + * @return the auth token being used by this client + */ + String getAuthToken() { + return (authToken.get()); + } + + /** + * Get the secret token. + * + * @return the secret token + */ + String getSecretToken() { + return (secretToken); + } + + /** + * Get the TokenType this client is using. + * + * @return the TokenType this client is using + */ + TokenType getTokenType() { + return (tokenType); + } + + /** Set the ID of the user to sudo as. */ + Long getSudoAsId() { + return (sudoAsId); + } + + /** + * Set the ID of the user to sudo as. + * + * @param sudoAsId the ID of the user to sudo as + */ + void setSudoAsId(final Long sudoAsId) { + this.sudoAsId = sudoAsId; + } + + /** + * Construct a REST URL with the specified path arguments. + * + * @param pathArgs variable list of arguments used to build the URI + * @return a REST URL with the specified path arguments + * @throws IOException if an error occurs while constructing the URL + */ + protected URL getApiUrl(final Object... pathArgs) throws IOException { + final String url = appendPathArgs(this.hostUrl, pathArgs); + return (new URL(url)); + } + + /** + * Construct a REST URL with the specified path arguments using Gitlab base url. + * + * @param pathArgs variable list of arguments used to build the URI + * @return a REST URL with the specified path arguments + * @throws IOException if an error occurs while constructing the URL + */ + protected URL getUrlWithBase(final Object... pathArgs) throws IOException { + final String url = appendPathArgs(this.baseUrl, pathArgs); + return (new URL(url)); + } + + private String appendPathArgs(final String url, final Object... pathArgs) { + final StringBuilder urlBuilder = new StringBuilder(url); + for (final Object pathArg : pathArgs) { + if (pathArg != null) { + urlBuilder.append("/"); + urlBuilder.append(pathArg.toString()); + } } - - /** - * Construct an instance to communicate with a GitLab API server using GitLab API version 4, and the specified - * server URL and private token. - * - * @param hostUrl the URL to the GitLab API server - * @param privateToken the private token to authenticate with - * @param secretToken use this token to validate received payloads - * @param clientConfigProperties the properties given to Jersey's clientconfig - */ - public GitLabApiClient(String hostUrl, String privateToken, String secretToken, Map clientConfigProperties) { - this(ApiVersion.V4, hostUrl, TokenType.PRIVATE, privateToken, secretToken, clientConfigProperties); + return urlBuilder.toString(); + } + + /** + * Validates the secret token (X-GitLab-Token) header against the expected secret token, returns + * true if valid, otherwise returns false. + * + * @param response the Response instance sent from the GitLab server + * @return true if the response's secret token is valid, otherwise returns false + */ + protected boolean validateSecretToken(final Response response) { + + if (this.secretToken == null) return (true); + + final String secretToken = response.getHeaderString(X_GITLAB_TOKEN_HEADER); + if (secretToken == null) return (false); + + return (this.secretToken.equals(secretToken)); + } + + /** + * Perform an HTTP GET call with the specified query parameters and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param queryParams multivalue map of request parameters + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws IOException if an error occurs while constructing the URL + */ + protected Response get(final MultivaluedMap queryParams, final Object... pathArgs) + throws IOException { + final URL url = getApiUrl(pathArgs); + return (get(queryParams, url)); + } + + /** + * Perform an HTTP GET call with the specified query parameters and URL, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param queryParams multivalue map of request parameters + * @param url the fully formed path to the GitLab API endpoint + * @return a ClientResponse instance with the data returned from the endpoint + */ + protected Response get(final MultivaluedMap queryParams, final URL url) { + return (invocation(url, queryParams).get()); + } + + /** + * Perform an HTTP GET call with the specified query parameters and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param queryParams multivalue map of request parameters + * @param accepts if non-empty will set the Accepts header to this value + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws IOException if an error occurs while constructing the URL + */ + protected Response getWithAccepts( + final MultivaluedMap queryParams, final String accepts, final Object... pathArgs) + throws IOException { + final URL url = getApiUrl(pathArgs); + return (getWithAccepts(queryParams, url, accepts)); + } + + /** + * Perform an HTTP GET call with the specified query parameters and URL, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param queryParams multivalue map of request parameters + * @param url the fully formed path to the GitLab API endpoint + * @param accepts if non-empty will set the Accepts header to this value + * @return a ClientResponse instance with the data returned from the endpoint + */ + protected Response getWithAccepts( + final MultivaluedMap queryParams, final URL url, final String accepts) { + return (invocation(url, queryParams, accepts).get()); + } + + /** + * Perform an HTTP HEAD call with the specified query parameters and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param queryParams multivalue map of request parameters + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws IOException if an error occurs while constructing the URL + */ + protected Response head(final MultivaluedMap queryParams, final Object... pathArgs) + throws IOException { + final URL url = getApiUrl(pathArgs); + return (head(queryParams, url)); + } + + /** + * Perform an HTTP HEAD call with the specified query parameters and URL, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param queryParams multivalue map of request parameters + * @param url the fully formed path to the GitLab API endpoint + * @return a ClientResponse instance with the data returned from the endpoint + */ + protected Response head(final MultivaluedMap queryParams, final URL url) { + return (invocation(url, queryParams).head()); + } + + /** + * Perform an HTTP PATCH call with the specified query parameters and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param queryParams multivalue map of request parameters + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws IOException if an error occurs while constructing the URL + */ + protected Response patch(final MultivaluedMap queryParams, final Object... pathArgs) + throws IOException { + final URL url = getApiUrl(pathArgs); + return (patch(queryParams, url)); + } + + /** + * Perform an HTTP PATCH call with the specified query parameters and URL, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param queryParams multivalue map of request parameters + * @param url the fully formed path to the GitLab API endpoint + * @return a ClientResponse instance with the data returned from the endpoint + */ + protected Response patch(final MultivaluedMap queryParams, final URL url) { + final Entity empty = Entity.text(""); + // use "X-HTTP-Method-Override" header on POST to override to unsupported PATCH + return (invocation(url, queryParams).header("X-HTTP-Method-Override", "PATCH").post(empty)); + } + + /** + * Perform an HTTP POST call with the specified form data and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param formData the Form containing the name/value pairs + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws IOException if an error occurs while constructing the URL + */ + protected Response post(final Form formData, final Object... pathArgs) throws IOException { + final URL url = getApiUrl(pathArgs); + return post(formData, url); + } + + /** + * Perform an HTTP POST call with the specified form data and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param queryParams multivalue map of request parameters + * @param pathArgs variable list of arguments used to build the URI + * @return a Response instance with the data returned from the endpoint + * @throws IOException if an error occurs while constructing the URL + */ + protected Response post(final MultivaluedMap queryParams, final Object... pathArgs) + throws IOException { + final URL url = getApiUrl(pathArgs); + return post(queryParams, url); + } + + /** + * Perform an HTTP POST call with the specified form data and URL, returning a ClientResponse + * instance with the data returned from the endpoint. + * + * @param formData the Form containing the name/value pairs + * @param url the fully formed path to the GitLab API endpoint + * @return a ClientResponse instance with the data returned from the endpoint + */ + protected Response post(final Form formData, final URL url) { + if (formData instanceof GitLabApiForm) { + return (invocation(url, null) + .post(Entity.entity(formData.asMap(), MediaType.APPLICATION_FORM_URLENCODED_TYPE))); + } else if (formData != null) { + return (invocation(url, null) + .post(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED_TYPE))); + } else { + return (invocation(url, null) + .post(Entity.entity(new Form(), MediaType.APPLICATION_FORM_URLENCODED_TYPE))); } - - /** - * Construct an instance to communicate with a GitLab API server using the specified GitLab API version, - * server URL and private token. - * - * @param apiVersion the ApiVersion specifying which version of the API to use - * @param hostUrl the URL to the GitLab API server - * @param privateToken the private token to authenticate with - * @param secretToken use this token to validate received payloads - * @param clientConfigProperties the properties given to Jersey's clientconfig - */ - public GitLabApiClient(ApiVersion apiVersion, String hostUrl, String privateToken, String secretToken, Map clientConfigProperties) { - this(apiVersion, hostUrl, TokenType.PRIVATE, privateToken, secretToken, clientConfigProperties); - } - - /** - * Construct an instance to communicate with a GitLab API server using the specified GitLab API version, - * server URL and private token. - * - * @param apiVersion the ApiVersion specifying which version of the API to use - * @param hostUrl the URL to the GitLab API server - * @param tokenType the type of auth the token is for, PRIVATE or ACCESS - * @param authToken the private token to authenticate with - * @param secretToken use this token to validate received payloads - * @param clientConfigProperties the properties given to Jersey's clientconfig - */ - public GitLabApiClient(ApiVersion apiVersion, String hostUrl, TokenType tokenType, String authToken, String secretToken, Map clientConfigProperties) { - - // Remove the trailing "/" from the hostUrl if present - this.hostUrl = (hostUrl.endsWith("/") ? hostUrl.replaceAll("/$", "") : hostUrl); - this.baseUrl = this.hostUrl; - this.hostUrl += apiVersion.getApiNamespace(); - - this.tokenType = tokenType; - this.authToken = () -> authToken; - - if (secretToken != null) { - secretToken = secretToken.trim(); - secretToken = (secretToken.length() > 0 ? secretToken : null); - } - - this.secretToken = secretToken; - - clientConfig = new ClientConfig(); - if (clientConfigProperties != null) { - - if (clientConfigProperties.containsKey(ClientProperties.PROXY_URI)) { - clientConfig.connectorProvider(new ApacheConnectorProvider()); - } - - for (Map.Entry propertyEntry : clientConfigProperties.entrySet()) { - clientConfig.property(propertyEntry.getKey(), propertyEntry.getValue()); - } - } - - // Disable auto-discovery of feature and services lookup, this will force Jersey - // to use the features and services explicitly configured by gitlab4j - clientConfig.property(ClientProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true); - clientConfig.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, true); - - clientConfig.register(JacksonJson.class); - clientConfig.register(JacksonFeature.class); - clientConfig.register(MultiPartFeature.class); - } - - /** - * Close the underlying {@link Client} and its associated resources. - */ - @Override - public void close() { - if (apiClient != null) { - apiClient.close(); - } - } - - /** - * Enable the logging of the requests to and the responses from the GitLab server API. - * - * @param logger the Logger instance to log to - * @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) - * @param maxEntitySize maximum number of entity bytes to be logged. When logging if the maxEntitySize - * is reached, the entity logging will be truncated at maxEntitySize and "...more..." will be added at - * the end of the log entry. If maxEntitySize is <= 0, entity logging will be disabled - * @param maskedHeaderNames a list of header names that should have the values masked - */ - void enableRequestResponseLogging(Logger logger, Level level, int maxEntityLength, List maskedHeaderNames) { - - MaskingLoggingFilter loggingFilter = new MaskingLoggingFilter(logger, level, maxEntityLength, maskedHeaderNames); - clientConfig.register(loggingFilter); - - // Recreate the Client instance if already created. - if (apiClient != null) { - createApiClient(); - } - } - - /** - * Sets the per request connect and read timeout. - * - * @param connectTimeout the per request connect timeout in milliseconds, can be null to use default - * @param readTimeout the per request read timeout in milliseconds, can be null to use default - */ - void setRequestTimeout(Integer connectTimeout, Integer readTimeout) { - this.connectTimeout = connectTimeout; - this.readTimeout = readTimeout; - } - - /** - * Get the auth token being used by this client. - * - * @return the auth token being used by this client - */ - String getAuthToken() { - return (authToken.get()); - } - - /** - * Get the secret token. - * - * @return the secret token - */ - String getSecretToken() { - return (secretToken); - } - - /** - * Get the TokenType this client is using. - * - * @return the TokenType this client is using - */ - TokenType getTokenType() { - return (tokenType); - } - - /** - * Set the ID of the user to sudo as. - * - */ - Long getSudoAsId() { - return (sudoAsId); - } - - /** - * Set the ID of the user to sudo as. - * - * @param sudoAsId the ID of the user to sudo as - */ - void setSudoAsId(Long sudoAsId) { - this.sudoAsId = sudoAsId; - } - - /** - * Construct a REST URL with the specified path arguments. - * - * @param pathArgs variable list of arguments used to build the URI - * @return a REST URL with the specified path arguments - * @throws IOException if an error occurs while constructing the URL - */ - protected URL getApiUrl(Object... pathArgs) throws IOException { - String url = appendPathArgs(this.hostUrl, pathArgs); - return (new URL(url)); - } - - /** - * Construct a REST URL with the specified path arguments using - * Gitlab base url. - * - * @param pathArgs variable list of arguments used to build the URI - * @return a REST URL with the specified path arguments - * @throws IOException if an error occurs while constructing the URL - */ - protected URL getUrlWithBase(Object... pathArgs) throws IOException { - String url = appendPathArgs(this.baseUrl, pathArgs); - return (new URL(url)); - } - - private String appendPathArgs(String url, Object... pathArgs) { - StringBuilder urlBuilder = new StringBuilder(url); - for (Object pathArg : pathArgs) { - if (pathArg != null) { - urlBuilder.append("/"); - urlBuilder.append(pathArg.toString()); - } - } - return urlBuilder.toString(); - } - - /** - * Validates the secret token (X-GitLab-Token) header against the expected secret token, returns true if valid, - * otherwise returns false. - * - * @param response the Response instance sent from the GitLab server - * @return true if the response's secret token is valid, otherwise returns false - */ - protected boolean validateSecretToken(Response response) { - - if (this.secretToken == null) - return (true); - - String secretToken = response.getHeaderString(X_GITLAB_TOKEN_HEADER); - if (secretToken == null) - return (false); - - return (this.secretToken.equals(secretToken)); - } - - /** - * Perform an HTTP GET call with the specified query parameters and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param queryParams multivalue map of request parameters - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws IOException if an error occurs while constructing the URL - */ - protected Response get(MultivaluedMap queryParams, Object... pathArgs) throws IOException { - URL url = getApiUrl(pathArgs); - return (get(queryParams, url)); - } - - /** - * Perform an HTTP GET call with the specified query parameters and URL, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param queryParams multivalue map of request parameters - * @param url the fully formed path to the GitLab API endpoint - * @return a ClientResponse instance with the data returned from the endpoint - */ - protected Response get(MultivaluedMap queryParams, URL url) { - return (invocation(url, queryParams).get()); - } - - /** - * Perform an HTTP GET call with the specified query parameters and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param queryParams multivalue map of request parameters - * @param accepts if non-empty will set the Accepts header to this value - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws IOException if an error occurs while constructing the URL - */ - protected Response getWithAccepts(MultivaluedMap queryParams, String accepts, Object... pathArgs) throws IOException { - URL url = getApiUrl(pathArgs); - return (getWithAccepts(queryParams, url, accepts)); - } - - /** - * Perform an HTTP GET call with the specified query parameters and URL, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param queryParams multivalue map of request parameters - * @param url the fully formed path to the GitLab API endpoint - * @param accepts if non-empty will set the Accepts header to this value - * @return a ClientResponse instance with the data returned from the endpoint - */ - protected Response getWithAccepts(MultivaluedMap queryParams, URL url, String accepts) { - return (invocation(url, queryParams, accepts).get()); - } - - /** - * Perform an HTTP HEAD call with the specified query parameters and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param queryParams multivalue map of request parameters - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws IOException if an error occurs while constructing the URL - */ - protected Response head(MultivaluedMap queryParams, Object... pathArgs) throws IOException { - URL url = getApiUrl(pathArgs); - return (head(queryParams, url)); - } - - /** - * Perform an HTTP HEAD call with the specified query parameters and URL, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param queryParams multivalue map of request parameters - * @param url the fully formed path to the GitLab API endpoint - * @return a ClientResponse instance with the data returned from the endpoint - */ - protected Response head(MultivaluedMap queryParams, URL url) { - return (invocation(url, queryParams).head()); - } - - /** - * Perform an HTTP PATCH call with the specified query parameters and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param queryParams multivalue map of request parameters - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws IOException if an error occurs while constructing the URL - */ - protected Response patch(MultivaluedMap queryParams, Object... pathArgs) throws IOException { - URL url = getApiUrl(pathArgs); - return (patch(queryParams, url)); - } - - /** - * Perform an HTTP PATCH call with the specified query parameters and URL, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param queryParams multivalue map of request parameters - * @param url the fully formed path to the GitLab API endpoint - * @return a ClientResponse instance with the data returned from the endpoint - */ - protected Response patch(MultivaluedMap queryParams, URL url) { - Entity empty = Entity.text(""); - // use "X-HTTP-Method-Override" header on POST to override to unsupported PATCH - return (invocation(url, queryParams) - .header("X-HTTP-Method-Override", "PATCH").post(empty)); - } - - /** - * Perform an HTTP POST call with the specified form data and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param formData the Form containing the name/value pairs - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws IOException if an error occurs while constructing the URL - */ - protected Response post(Form formData, Object... pathArgs) throws IOException { - URL url = getApiUrl(pathArgs); - return post(formData, url); - } - - /** - * Perform an HTTP POST call with the specified form data and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param queryParams multivalue map of request parameters - * @param pathArgs variable list of arguments used to build the URI - * @return a Response instance with the data returned from the endpoint - * @throws IOException if an error occurs while constructing the URL - */ - protected Response post(MultivaluedMap queryParams, Object... pathArgs) throws IOException { - URL url = getApiUrl(pathArgs); - return post(queryParams, url); - } - - /** - * Perform an HTTP POST call with the specified form data and URL, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param formData the Form containing the name/value pairs - * @param url the fully formed path to the GitLab API endpoint - * @return a ClientResponse instance with the data returned from the endpoint - */ - protected Response post(Form formData, URL url) { - if (formData instanceof GitLabApiForm) { - return (invocation(url, null).post(Entity.entity(formData.asMap(), MediaType.APPLICATION_FORM_URLENCODED_TYPE))); - } else if (formData != null) { - return (invocation(url, null).post(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED_TYPE))); - } else { - return (invocation(url, null).post(Entity.entity(new Form(), MediaType.APPLICATION_FORM_URLENCODED_TYPE))); - } - } - - /** - * Perform an HTTP POST call with the specified form data and URL, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param queryParams multivalue map of request parametersformData the Form containing the name/value pairs - * @param url the fully formed path to the GitLab API endpoint - * @return a ClientResponse instance with the data returned from the endpoint - */ - protected Response post(MultivaluedMap queryParams, URL url) { - return (invocation(url, queryParams).post(Entity.entity(new Form(), MediaType.APPLICATION_FORM_URLENCODED_TYPE))); - } - - /** - * Perform an HTTP POST call with the specified payload object and URL, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param payload the object instance that will be serialized to JSON and used as the POST data - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws IOException if an error occurs while constructing the URL - */ - protected Response post(Object payload, Object... pathArgs) throws IOException { - URL url = getApiUrl(pathArgs); - Entity entity = Entity.entity(payload, MediaType.APPLICATION_JSON); - return (invocation(url, null).post(entity)); - } - - /** - * Perform an HTTP POST call with the specified StreamingOutput, MediaType, and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param stream the StreamingOutput instance that contains the POST data - * @param mediaType the content-type of the POST data - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws IOException if an error occurs while constructing the URL - */ - protected Response post(StreamingOutput stream, String mediaType, Object... pathArgs) throws IOException { - URL url = getApiUrl(pathArgs); - return (invocation(url, null).post(Entity.entity(stream, mediaType))); - } - - /** - * Perform a file upload using the specified media type, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param name the name for the form field that contains the file name - * @param fileToUpload a File instance pointing to the file to upload - * @param mediaTypeString unused; will be removed in the next major version - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws IOException if an error occurs while constructing the URL - */ - protected Response upload(String name, File fileToUpload, String mediaTypeString, Object... pathArgs) throws IOException { - return upload(name, fileToUpload, mediaTypeString, null, pathArgs); - } - - /** - * Perform a file upload using the specified media type, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param name the name for the form field that contains the file name - * @param fileToUpload a File instance pointing to the file to upload - * @param mediaTypeString unused; will be removed in the next major version - * @param formData the Form containing the name/value pairs - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws IOException if an error occurs while constructing the URL - */ - protected Response upload(String name, File fileToUpload, String mediaTypeString, Form formData, Object... pathArgs) throws IOException { - URL url = getApiUrl(pathArgs); - return (upload(name, fileToUpload, mediaTypeString, formData, url)); - } - - /** - * Perform a file upload using multipart/form-data, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param name the name for the form field that contains the file name - * @param fileToUpload a File instance pointing to the file to upload - * @param mediaTypeString unused; will be removed in the next major version - * @param formData the Form containing the name/value pairs - * @param url the fully formed path to the GitLab API endpoint - * @return a ClientResponse instance with the data returned from the endpoint - * @throws IOException if an error occurs while constructing the URL - */ - protected Response upload(String name, File fileToUpload, String mediaTypeString, Form formData, URL url) throws IOException { - FileDataBodyPart filePart = new FileDataBodyPart(name, fileToUpload); - return upload(filePart, formData, url); - } - - protected Response upload(String name, InputStream inputStream, String filename, String mediaTypeString, Object... pathArgs) throws IOException { - URL url = getApiUrl(pathArgs); - return (upload(name, inputStream, filename, mediaTypeString, null, url)); - } - - protected Response upload(String name, InputStream inputStream, String filename, String mediaTypeString, Form formData, URL url) throws IOException { - StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart(name, inputStream, filename); - return upload(streamDataBodyPart, formData, url); - } - - protected Response upload(BodyPart bodyPart, Form formData, URL url) throws IOException { - try (FormDataMultiPart multiPart = new FormDataMultiPart()) { - if (formData != null) { - formData.asMap().forEach((key, values) -> { - if (values != null) { - values.forEach(value -> multiPart.field(key, value)); - } + } + + /** + * Perform an HTTP POST call with the specified form data and URL, returning a ClientResponse + * instance with the data returned from the endpoint. + * + * @param queryParams multivalue map of request parametersformData the Form containing the + * name/value pairs + * @param url the fully formed path to the GitLab API endpoint + * @return a ClientResponse instance with the data returned from the endpoint + */ + protected Response post(final MultivaluedMap queryParams, final URL url) { + return (invocation(url, queryParams) + .post(Entity.entity(new Form(), MediaType.APPLICATION_FORM_URLENCODED_TYPE))); + } + + /** + * Perform an HTTP POST call with the specified payload object and URL, returning a ClientResponse + * instance with the data returned from the endpoint. + * + * @param payload the object instance that will be serialized to JSON and used as the POST data + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws IOException if an error occurs while constructing the URL + */ + protected Response post(final Object payload, final Object... pathArgs) throws IOException { + final URL url = getApiUrl(pathArgs); + final Entity entity = Entity.entity(payload, MediaType.APPLICATION_JSON); + return (invocation(url, null).post(entity)); + } + + /** + * Perform an HTTP POST call with the specified StreamingOutput, MediaType, and path objects, + * returning a ClientResponse instance with the data returned from the endpoint. + * + * @param stream the StreamingOutput instance that contains the POST data + * @param mediaType the content-type of the POST data + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws IOException if an error occurs while constructing the URL + */ + protected Response post(final StreamingOutput stream, final String mediaType, final Object... pathArgs) + throws IOException { + final URL url = getApiUrl(pathArgs); + return (invocation(url, null).post(Entity.entity(stream, mediaType))); + } + + /** + * Perform a file upload using the specified media type, returning a ClientResponse instance with + * the data returned from the endpoint. + * + * @param name the name for the form field that contains the file name + * @param fileToUpload a File instance pointing to the file to upload + * @param mediaTypeString unused; will be removed in the next major version + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws IOException if an error occurs while constructing the URL + */ + protected Response upload( + final String name, final File fileToUpload, final String mediaTypeString, final Object... pathArgs) + throws IOException { + return upload(name, fileToUpload, mediaTypeString, null, pathArgs); + } + + /** + * Perform a file upload using the specified media type, returning a ClientResponse instance with + * the data returned from the endpoint. + * + * @param name the name for the form field that contains the file name + * @param fileToUpload a File instance pointing to the file to upload + * @param mediaTypeString unused; will be removed in the next major version + * @param formData the Form containing the name/value pairs + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws IOException if an error occurs while constructing the URL + */ + protected Response upload( + final String name, final File fileToUpload, final String mediaTypeString, final Form formData, final Object... pathArgs) + throws IOException { + final URL url = getApiUrl(pathArgs); + return (upload(name, fileToUpload, mediaTypeString, formData, url)); + } + + /** + * Perform a file upload using multipart/form-data, returning a ClientResponse instance with the + * data returned from the endpoint. + * + * @param name the name for the form field that contains the file name + * @param fileToUpload a File instance pointing to the file to upload + * @param mediaTypeString unused; will be removed in the next major version + * @param formData the Form containing the name/value pairs + * @param url the fully formed path to the GitLab API endpoint + * @return a ClientResponse instance with the data returned from the endpoint + * @throws IOException if an error occurs while constructing the URL + */ + protected Response upload( + final String name, final File fileToUpload, final String mediaTypeString, final Form formData, final URL url) + throws IOException { + final FileDataBodyPart filePart = new FileDataBodyPart(name, fileToUpload); + return upload(filePart, formData, url); + } + + protected Response upload( + final String name, + final InputStream inputStream, + final String filename, + final String mediaTypeString, + final Object... pathArgs) + throws IOException { + final URL url = getApiUrl(pathArgs); + return (upload(name, inputStream, filename, mediaTypeString, null, url)); + } + + protected Response upload( + final String name, + final InputStream inputStream, + final String filename, + final String mediaTypeString, + final Form formData, + final URL url) + throws IOException { + final StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart(name, inputStream, filename); + return upload(streamDataBodyPart, formData, url); + } + + protected Response upload(final BodyPart bodyPart, final Form formData, final URL url) throws IOException { + try (final FormDataMultiPart multiPart = new FormDataMultiPart()) { + if (formData != null) { + formData + .asMap() + .forEach( + (key, values) -> { + if (values != null) { + values.forEach(value -> multiPart.field(key, value)); + } }); - } - - multiPart.bodyPart(bodyPart); - final Entity entity = Entity.entity(multiPart, Boundary.addBoundary(multiPart.getMediaType())); - return (invocation(url, null).post(entity)); - } - } + } - /** - * Perform a file upload using multipart/form-data using the HTTP PUT method, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param name the name for the form field that contains the file name - * @param fileToUpload a File instance pointing to the file to upload - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws IOException if an error occurs while constructing the URL - */ - protected Response putUpload(String name, File fileToUpload, Object... pathArgs) throws IOException { - URL url = getApiUrl(pathArgs); - return (putUpload(name, fileToUpload, url)); + multiPart.bodyPart(bodyPart); + final Entity entity = + Entity.entity(multiPart, Boundary.addBoundary(multiPart.getMediaType())); + return (invocation(url, null).post(entity)); } - - /** - * Perform a file upload using multipart/form-data using the HTTP PUT method, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param name the name for the form field that contains the file name - * @param fileToUpload a File instance pointing to the file to upload - - * @param url the fully formed path to the GitLab API endpoint - * @return a ClientResponse instance with the data returned from the endpoint - * @throws IOException if an error occurs while constructing the URL - */ - protected Response putUpload(String name, File fileToUpload, URL url) throws IOException { - - try (MultiPart multiPart = new FormDataMultiPart()) { - multiPart.bodyPart(new FileDataBodyPart(name, fileToUpload, MediaType.APPLICATION_OCTET_STREAM_TYPE)); - final Entity entity = Entity.entity(multiPart, Boundary.addBoundary(multiPart.getMediaType())); - return (invocation(url, null).put(entity)); - } + } + + /** + * Perform a file upload using multipart/form-data using the HTTP PUT method, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param name the name for the form field that contains the file name + * @param fileToUpload a File instance pointing to the file to upload + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws IOException if an error occurs while constructing the URL + */ + protected Response putUpload(final String name, final File fileToUpload, final Object... pathArgs) + throws IOException { + final URL url = getApiUrl(pathArgs); + return (putUpload(name, fileToUpload, url)); + } + + /** + * Perform a file upload using multipart/form-data using the HTTP PUT method, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param name the name for the form field that contains the file name + * @param fileToUpload a File instance pointing to the file to upload + * @param url the fully formed path to the GitLab API endpoint + * @return a ClientResponse instance with the data returned from the endpoint + * @throws IOException if an error occurs while constructing the URL + */ + protected Response putUpload(final String name, final File fileToUpload, final URL url) throws IOException { + + try (final MultiPart multiPart = new FormDataMultiPart()) { + multiPart.bodyPart( + new FileDataBodyPart(name, fileToUpload, MediaType.APPLICATION_OCTET_STREAM_TYPE)); + final Entity entity = + Entity.entity(multiPart, Boundary.addBoundary(multiPart.getMediaType())); + return (invocation(url, null).put(entity)); } - - /** - * Perform an HTTP PUT call with the specified form data and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param queryParams multivalue map of request parameters - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws IOException if an error occurs while constructing the URL - */ - protected Response put(MultivaluedMap queryParams, Object... pathArgs) throws IOException { - URL url = getApiUrl(pathArgs); - return (put(queryParams, url)); + } + + /** + * Perform an HTTP PUT call with the specified form data and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param queryParams multivalue map of request parameters + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws IOException if an error occurs while constructing the URL + */ + protected Response put(final MultivaluedMap queryParams, final Object... pathArgs) + throws IOException { + final URL url = getApiUrl(pathArgs); + return (put(queryParams, url)); + } + + /** + * Perform an HTTP PUT call with the specified form data and URL, returning a ClientResponse + * instance with the data returned from the endpoint. + * + * @param queryParams multivalue map of request parameters + * @param url the fully formed path to the GitLab API endpoint + * @return a ClientResponse instance with the data returned from the endpoint + */ + protected Response put(final MultivaluedMap queryParams, final URL url) { + if (queryParams == null || queryParams.isEmpty()) { + final Entity empty = Entity.text(""); + return (invocation(url, null).put(empty)); + } else { + return (invocation(url, null) + .put(Entity.entity(queryParams, MediaType.APPLICATION_FORM_URLENCODED_TYPE))); } - - /** - * Perform an HTTP PUT call with the specified form data and URL, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param queryParams multivalue map of request parameters - * @param url the fully formed path to the GitLab API endpoint - * @return a ClientResponse instance with the data returned from the endpoint - */ - protected Response put(MultivaluedMap queryParams, URL url) { - if (queryParams == null || queryParams.isEmpty()) { - Entity empty = Entity.text(""); - return (invocation(url, null).put(empty)); - } else { - return (invocation(url, null).put(Entity.entity(queryParams, MediaType.APPLICATION_FORM_URLENCODED_TYPE))); - } + } + + /** + * Perform an HTTP PUT call with the specified form data and path objects, returning a + * ClientResponse instance with the data returned from the endpoint. + * + * @param formData the Form containing the name/value pairs + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws IOException if an error occurs while constructing the URL + */ + protected Response put(final Form formData, final Object... pathArgs) throws IOException { + final URL url = getApiUrl(pathArgs); + return put(formData, url); + } + + /** + * Perform an HTTP PUT call with the specified form data and URL, returning a ClientResponse + * instance with the data returned from the endpoint. + * + * @param formData the Form containing the name/value pairs + * @param url the fully formed path to the GitLab API endpoint + * @return a ClientResponse instance with the data returned from the endpoint + */ + protected Response put(final Form formData, final URL url) { + if (formData instanceof GitLabApiForm) + return (invocation(url, null) + .put(Entity.entity(formData.asMap(), MediaType.APPLICATION_FORM_URLENCODED_TYPE))); + else + return (invocation(url, null) + .put(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED_TYPE))); + } + + /** + * Perform an HTTP PUT call with the specified payload object and URL, returning a ClientResponse + * instance with the data returned from the endpoint. + * + * @param payload the object instance that will be serialized to JSON and used as the PUT data + * @param pathArgs variable list of arguments used to build the URI + * @return a ClientResponse instance with the data returned from the endpoint + * @throws IOException if an error occurs while constructing the URL + */ + protected Response put(final Object payload, final Object... pathArgs) throws IOException { + final URL url = getApiUrl(pathArgs); + final Entity entity = Entity.entity(payload, MediaType.APPLICATION_JSON); + return (invocation(url, null).put(entity)); + } + + /** + * Perform an HTTP DELETE call with the specified form data and path objects, returning a Response + * instance with the data returned from the endpoint. + * + * @param queryParams multivalue map of request parameters + * @param pathArgs variable list of arguments used to build the URI + * @return a Response instance with the data returned from the endpoint + * @throws IOException if an error occurs while constructing the URL + */ + protected Response delete(final MultivaluedMap queryParams, final Object... pathArgs) + throws IOException { + return (delete(queryParams, getApiUrl(pathArgs))); + } + + /** + * Perform an HTTP DELETE call with the specified form data and URL, returning a Response instance + * with the data returned from the endpoint. + * + * @param queryParams multivalue map of request parameters + * @param url the fully formed path to the GitLab API endpoint + * @return a Response instance with the data returned from the endpoint + */ + protected Response delete(final MultivaluedMap queryParams, final URL url) { + return (invocation(url, queryParams).delete()); + } + + protected Invocation.Builder invocation(final URL url, final MultivaluedMap queryParams) { + return (invocation(url, queryParams, MediaType.APPLICATION_JSON)); + } + + protected Client createApiClient() { + + // Explicitly use an instance of the JerseyClientBuilder, this allows this + // library to work when both Jersey and Resteasy are present + final ClientBuilder clientBuilder = new JerseyClientBuilder().withConfig(clientConfig); + + // Register JacksonJson as the ObjectMapper provider. + clientBuilder.register(JacksonJson.class); + clientBuilder.register(JacksonFeature.class); + + if (ignoreCertificateErrors) { + clientBuilder.sslContext(openSslContext).hostnameVerifier(openHostnameVerifier); } - /** - * Perform an HTTP PUT call with the specified form data and path objects, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param formData the Form containing the name/value pairs - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws IOException if an error occurs while constructing the URL - */ - protected Response put(Form formData, Object... pathArgs) throws IOException { - URL url = getApiUrl(pathArgs); - return put(formData, url); - } - - /** - * Perform an HTTP PUT call with the specified form data and URL, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param formData the Form containing the name/value pairs - * @param url the fully formed path to the GitLab API endpoint - * @return a ClientResponse instance with the data returned from the endpoint - */ - protected Response put(Form formData, URL url) { - if (formData instanceof GitLabApiForm) - return (invocation(url, null).put(Entity.entity(formData.asMap(), MediaType.APPLICATION_FORM_URLENCODED_TYPE))); - else - return (invocation(url, null).put(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED_TYPE))); - } + apiClient = clientBuilder.build(); + return (apiClient); + } - /** - * Perform an HTTP PUT call with the specified payload object and URL, returning - * a ClientResponse instance with the data returned from the endpoint. - * - * @param payload the object instance that will be serialized to JSON and used as the PUT data - * @param pathArgs variable list of arguments used to build the URI - * @return a ClientResponse instance with the data returned from the endpoint - * @throws IOException if an error occurs while constructing the URL - */ - protected Response put(Object payload, Object... pathArgs) throws IOException { - URL url = getApiUrl(pathArgs); - Entity entity = Entity.entity(payload, MediaType.APPLICATION_JSON); - return (invocation(url, null).put(entity)); - } + protected Invocation.Builder invocation( + final URL url, final MultivaluedMap queryParams, final String accept) { - /** - * Perform an HTTP DELETE call with the specified form data and path objects, returning - * a Response instance with the data returned from the endpoint. - * - * @param queryParams multivalue map of request parameters - * @param pathArgs variable list of arguments used to build the URI - * @return a Response instance with the data returned from the endpoint - * @throws IOException if an error occurs while constructing the URL - */ - protected Response delete(MultivaluedMap queryParams, Object... pathArgs) throws IOException { - return (delete(queryParams, getApiUrl(pathArgs))); + if (apiClient == null) { + createApiClient(); } - /** - * Perform an HTTP DELETE call with the specified form data and URL, returning - * a Response instance with the data returned from the endpoint. - * - * @param queryParams multivalue map of request parameters - * @param url the fully formed path to the GitLab API endpoint - * @return a Response instance with the data returned from the endpoint - */ - protected Response delete(MultivaluedMap queryParams, URL url) { - return (invocation(url, queryParams).delete()); + WebTarget target = + apiClient.target(url.toExternalForm()).property(ClientProperties.FOLLOW_REDIRECTS, true); + if (queryParams != null) { + for (final Map.Entry> param : queryParams.entrySet()) { + target = target.queryParam(param.getKey(), param.getValue().toArray()); + } } - protected Invocation.Builder invocation(URL url, MultivaluedMap queryParams) { - return (invocation(url, queryParams, MediaType.APPLICATION_JSON)); + final String authHeader = + (tokenType == TokenType.OAUTH2_ACCESS ? AUTHORIZATION_HEADER : PRIVATE_TOKEN_HEADER); + final String authValue = + (tokenType == TokenType.OAUTH2_ACCESS ? "Bearer " + authToken.get() : authToken.get()); + Invocation.Builder builder = target.request(); + if (accept == null || accept.trim().length() == 0) { + builder = builder.header(authHeader, authValue); + } else { + builder = builder.header(authHeader, authValue).accept(accept); } - protected Client createApiClient() { - - // Explicitly use an instance of the JerseyClientBuilder, this allows this - // library to work when both Jersey and Resteasy are present - ClientBuilder clientBuilder = new JerseyClientBuilder().withConfig(clientConfig); - - // Register JacksonJson as the ObjectMapper provider. - clientBuilder.register(JacksonJson.class); - clientBuilder.register(JacksonFeature.class); - - if (ignoreCertificateErrors) { - clientBuilder.sslContext(openSslContext).hostnameVerifier(openHostnameVerifier); - } + // If sudo as ID is set add the Sudo header + if (sudoAsId != null && sudoAsId.intValue() > 0) + builder = builder.header(SUDO_HEADER, sudoAsId); - apiClient = clientBuilder.build(); - return (apiClient); + // Set the per request connect timeout + if (connectTimeout != null) { + builder.property(ClientProperties.CONNECT_TIMEOUT, connectTimeout); } - protected Invocation.Builder invocation(URL url, MultivaluedMap queryParams, String accept) { - - if (apiClient == null) { - createApiClient(); - } - - WebTarget target = apiClient.target(url.toExternalForm()).property(ClientProperties.FOLLOW_REDIRECTS, true); - if (queryParams != null) { - for (Map.Entry> param : queryParams.entrySet()) { - target = target.queryParam(param.getKey(), param.getValue().toArray()); - } - } - - String authHeader = (tokenType == TokenType.OAUTH2_ACCESS ? AUTHORIZATION_HEADER : PRIVATE_TOKEN_HEADER); - String authValue = (tokenType == TokenType.OAUTH2_ACCESS ? "Bearer " + authToken.get() : authToken.get()); - Invocation.Builder builder = target.request(); - if (accept == null || accept.trim().length() == 0) { - builder = builder.header(authHeader, authValue); - } else { - builder = builder.header(authHeader, authValue).accept(accept); - } - - // If sudo as ID is set add the Sudo header - if (sudoAsId != null && sudoAsId.intValue() > 0) - builder = builder.header(SUDO_HEADER, sudoAsId); - - // Set the per request connect timeout - if (connectTimeout != null) { - builder.property(ClientProperties.CONNECT_TIMEOUT, connectTimeout); - } - - // Set the per request read timeout - if (readTimeout != null) { - builder.property(ClientProperties.READ_TIMEOUT, readTimeout); - } - - return (builder); + // Set the per request read timeout + if (readTimeout != null) { + builder.property(ClientProperties.READ_TIMEOUT, readTimeout); } - /** - * Used to set the host URL to be used by OAUTH2 login in GitLabApi. - */ - void setHostUrlToBaseUrl() { - this.hostUrl = this.baseUrl; + return (builder); + } + + /** Used to set the host URL to be used by OAUTH2 login in GitLabApi. */ + void setHostUrlToBaseUrl() { + this.hostUrl = this.baseUrl; + } + + /** + * Returns true if the API is setup to ignore SSL certificate errors, otherwise returns false. + * + * @return true if the API is setup to ignore SSL certificate errors, otherwise returns false + */ + public boolean getIgnoreCertificateErrors() { + return (ignoreCertificateErrors); + } + + /** + * Sets up the Jersey system ignore SSL certificate errors or not. + * + * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate + * errors + */ + public void setIgnoreCertificateErrors(final boolean ignoreCertificateErrors) { + + if (this.ignoreCertificateErrors == ignoreCertificateErrors) { + return; } - /** - * Returns true if the API is setup to ignore SSL certificate errors, otherwise returns false. - * - * @return true if the API is setup to ignore SSL certificate errors, otherwise returns false - */ - public boolean getIgnoreCertificateErrors() { - return (ignoreCertificateErrors); - } + if (!ignoreCertificateErrors) { - /** - * Sets up the Jersey system ignore SSL certificate errors or not. - * - * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors - */ - public void setIgnoreCertificateErrors(boolean ignoreCertificateErrors) { - - if (this.ignoreCertificateErrors == ignoreCertificateErrors) { - return; - } - - if (!ignoreCertificateErrors) { - - this.ignoreCertificateErrors = false; - openSslContext = null; - openHostnameVerifier = null; - apiClient = null; - - } else { - - if (setupIgnoreCertificateErrors()) { - this.ignoreCertificateErrors = true; - apiClient = null; - } else { - this.ignoreCertificateErrors = false; - apiClient = null; - throw new RuntimeException("Unable to ignore certificate errors."); - } - } - } + this.ignoreCertificateErrors = false; + openSslContext = null; + openHostnameVerifier = null; + apiClient = null; - /** - * Sets up Jersey client to ignore certificate errors. - * - * @return true if successful at setting up to ignore certificate errors, otherwise returns false. - */ - private boolean setupIgnoreCertificateErrors() { + } else { - // Create a TrustManager that trusts all certificates - TrustManager[] trustAllCerts = new TrustManager[] { new X509ExtendedTrustManager() { + if (setupIgnoreCertificateErrors()) { + this.ignoreCertificateErrors = true; + apiClient = null; + } else { + this.ignoreCertificateErrors = false; + apiClient = null; + throw new RuntimeException("Unable to ignore certificate errors."); + } + } + } + + /** + * Sets up Jersey client to ignore certificate errors. + * + * @return true if successful at setting up to ignore certificate errors, otherwise returns false. + */ + private boolean setupIgnoreCertificateErrors() { + + // Create a TrustManager that trusts all certificates + final TrustManager[] trustAllCerts = + new TrustManager[] { + new X509ExtendedTrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { - return null; + return null; } @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - } + public void checkServerTrusted(final X509Certificate[] chain, final String authType) + throws CertificateException {} @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - } + public void checkClientTrusted(final X509Certificate[] chain, final String authType) + throws CertificateException {} @Override - public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { - } + public void checkClientTrusted(final X509Certificate[] chain, final String authType, final Socket socket) + throws CertificateException {} @Override - public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { - } + public void checkClientTrusted( + final X509Certificate[] chain, final String authType, final SSLEngine engine) + throws CertificateException {} @Override - public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { - } + public void checkServerTrusted(final X509Certificate[] chain, final String authType, final Socket socket) + throws CertificateException {} @Override - public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { - } - }}; + public void checkServerTrusted( + final X509Certificate[] chain, final String authType, final SSLEngine engine) + throws CertificateException {} + } + }; - // Ignore differences between given hostname and certificate hostname - HostnameVerifier hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } + // Ignore differences between given hostname and certificate hostname + final HostnameVerifier hostnameVerifier = + new HostnameVerifier() { + @Override + public boolean verify(final String hostname, final SSLSession session) { + return true; + } }; - try { - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(null, trustAllCerts, new SecureRandom()); - openSslContext = sslContext; - openHostnameVerifier = hostnameVerifier; - } catch (GeneralSecurityException ex) { - openSslContext = null; - openHostnameVerifier = null; - return (false); - } - - return (true); + try { + final SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, trustAllCerts, new SecureRandom()); + openSslContext = sslContext; + openHostnameVerifier = hostnameVerifier; + } catch (final GeneralSecurityException ex) { + openSslContext = null; + openHostnameVerifier = null; + return (false); } - /** - * Set auth token supplier for gitlab api client. - * @param authTokenSupplier - supplier which provide actual auth token - */ - public void setAuthTokenSupplier(Supplier authTokenSupplier) { - this.authToken = authTokenSupplier; - } + return (true); + } + + /** + * Set auth token supplier for gitlab api client. + * + * @param authTokenSupplier - supplier which provide actual auth token + */ + public void setAuthTokenSupplier(final Supplier authTokenSupplier) { + this.authToken = authTokenSupplier; + } } diff --git a/src/main/java/org/gitlab4j/api/GitLabApiException.java b/src/main/java/org/gitlab4j/api/GitLabApiException.java index 8af8ee82b..1131c703e 100755 --- a/src/main/java/org/gitlab4j/api/GitLabApiException.java +++ b/src/main/java/org/gitlab4j/api/GitLabApiException.java @@ -1,253 +1,249 @@ package org.gitlab4j.api; +import com.fasterxml.jackson.databind.JsonNode; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.Response.StatusType; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.StatusType; - import org.gitlab4j.api.utils.JacksonJson; -import com.fasterxml.jackson.databind.JsonNode; - /** - * This is the exception that will be thrown if any exception occurs while communicating - * with a GitLab API endpoint. + * This is the exception that will be thrown if any exception occurs while communicating with a + * GitLab API endpoint. */ public class GitLabApiException extends Exception { - private static final long serialVersionUID = 1L; - private StatusType statusInfo; - private int httpStatus; - private String message; - private Map> validationErrors; - - /** - * Create a GitLabApiException instance with the specified message. - * - * @param message the message for the exception - */ - public GitLabApiException(String message) { - super(message); + private static final long serialVersionUID = 1L; + private StatusType statusInfo; + private int httpStatus; + private String message; + private Map> validationErrors; + + /** + * Create a GitLabApiException instance with the specified message. + * + * @param message the message for the exception + */ + public GitLabApiException(final String message) { + super(message); + this.message = message; + } + + /** + * Create a GitLabApiException instance with the specified message and HTTP status code. + * + * @param message the message for the exception + * @param httpStatus the HTTP status code for the exception + */ + public GitLabApiException(final String message, final int httpStatus) { + super(message); + this.message = message; + this.httpStatus = httpStatus; + } + + /** + * Create a GitLabApiException instance based on the ClientResponse. + * + * @param response the JAX-RS response that caused the exception + */ + public GitLabApiException(final Response response) { + + super(); + statusInfo = response.getStatusInfo(); + httpStatus = response.getStatus(); + + if (response.hasEntity()) { + + try { + + final String message = response.readEntity(String.class); this.message = message; - } - - /** - * Create a GitLabApiException instance with the specified message and HTTP status code. - * - * @param message the message for the exception - * @param httpStatus the HTTP status code for the exception - */ - public GitLabApiException(String message, int httpStatus) { - super(message); - this.message = message; - this.httpStatus = httpStatus; - } - - /** - * Create a GitLabApiException instance based on the ClientResponse. - * - * @param response the JAX-RS response that caused the exception - */ - public GitLabApiException(Response response) { - super(); - statusInfo = response.getStatusInfo(); - httpStatus = response.getStatus(); + // Determine what is in the content of the response and process it accordingly + final MediaType mediaType = response.getMediaType(); + if (mediaType != null && "json".equals(mediaType.getSubtype())) { - if (response.hasEntity()) { + final JsonNode json = JacksonJson.toJsonNode(message); - try { + // First see if it is a "message", if so it is either a simple message, + // or a Map> of validation errors + final JsonNode jsonMessage = json.get("message"); + if (jsonMessage != null) { - String message = response.readEntity(String.class); - this.message = message; + // If the node is an object, then it is validation errors + if (jsonMessage.isObject()) { - // Determine what is in the content of the response and process it accordingly - MediaType mediaType = response.getMediaType(); - if (mediaType != null && "json".equals(mediaType.getSubtype())) { + final StringBuilder buf = new StringBuilder(); + validationErrors = new HashMap<>(); + final Iterator> fields = jsonMessage.fields(); + while (fields.hasNext()) { - JsonNode json = JacksonJson.toJsonNode(message); - - // First see if it is a "message", if so it is either a simple message, - // or a Map> of validation errors - JsonNode jsonMessage = json.get("message"); - if (jsonMessage != null) { - - // If the node is an object, then it is validation errors - if (jsonMessage.isObject()) { - - StringBuilder buf = new StringBuilder(); - validationErrors = new HashMap<>(); - Iterator> fields = jsonMessage.fields(); - while(fields.hasNext()) { - - Entry field = fields.next(); - String fieldName = field.getKey(); - List values = new ArrayList<>(); - validationErrors.put(fieldName, values); - for (JsonNode value : field.getValue()) { - values.add(value.asText()); - } - - if (values.size() > 0) { - buf.append((buf.length() > 0 ? ", " : "")).append(fieldName); - } - } + final Entry field = fields.next(); + final String fieldName = field.getKey(); + final List values = new ArrayList<>(); + validationErrors.put(fieldName, values); + for (final JsonNode value : field.getValue()) { + values.add(value.asText()); + } - if (buf.length() > 0) { - this.message = "The following fields have validation errors: " + buf.toString(); - } + if (values.size() > 0) { + buf.append((buf.length() > 0 ? ", " : "")).append(fieldName); + } + } - } else if (jsonMessage.isArray()) { + if (buf.length() > 0) { + this.message = "The following fields have validation errors: " + buf.toString(); + } - List values = new ArrayList<>(); - for (JsonNode value : jsonMessage) { - values.add(value.asText()); - } + } else if (jsonMessage.isArray()) { - if (values.size() > 0) { - this.message = String.join("\n", values); - } + final List values = new ArrayList<>(); + for (final JsonNode value : jsonMessage) { + values.add(value.asText()); + } - } else if (jsonMessage.isTextual()) { - this.message = jsonMessage.asText(); - } else { - this.message = jsonMessage.toString(); - } + if (values.size() > 0) { + this.message = String.join("\n", values); + } - } else { + } else if (jsonMessage.isTextual()) { + this.message = jsonMessage.asText(); + } else { + this.message = jsonMessage.toString(); + } - JsonNode jsonError = json.get("error"); - if (jsonError != null) { - this.message = jsonError.asText(); - } - } - } + } else { - } catch (Exception ignore) { + final JsonNode jsonError = json.get("error"); + if (jsonError != null) { + this.message = jsonError.asText(); } + } } - } - /** - * Create a GitLabApiException instance based on the exception. - * - * @param e the Exception to wrap - */ - public GitLabApiException(Exception e) { - super(e); - message = e.getMessage(); + } catch (final Exception ignore) { + } } - - /** - * Get the message associated with the exception. - * - * @return the message associated with the exception - */ - @Override - public final String getMessage() { - return (message != null ? message : getReason()); + } + + /** + * Create a GitLabApiException instance based on the exception. + * + * @param e the Exception to wrap + */ + public GitLabApiException(final Exception e) { + super(e); + message = e.getMessage(); + } + + /** + * Get the message associated with the exception. + * + * @return the message associated with the exception + */ + @Override + public final String getMessage() { + return (message != null ? message : getReason()); + } + + /** + * Returns the HTTP status reason message, returns null if the causing error was not an HTTP + * related exception. + * + * @return the HTTP status reason message + */ + public final String getReason() { + return (statusInfo != null ? statusInfo.getReasonPhrase() : null); + } + + /** + * Returns the HTTP status code that was the cause of the exception. returns 0 if the causing + * error was not an HTTP related exception + * + * @return the HTTP status code, returns 0 if the causing error was not an HTTP related exception + */ + public final int getHttpStatus() { + return (httpStatus); + } + + /** + * Returns true if this GitLabApiException was caused by validation errors on the GitLab server, + * otherwise returns false. + * + * @return true if this GitLabApiException was caused by validation errors on the GitLab server, + * otherwise returns false + */ + public boolean hasValidationErrors() { + return (validationErrors != null); + } + + /** + * Returns a Map<String, List<String>> instance containing validation errors if this + * GitLabApiException was caused by validation errors on the GitLab server, otherwise returns + * null. + * + * @return a Map<String, List<String>> instance containing validation errors if this + * GitLabApiException was caused by validation errors on the GitLab server, otherwise returns + * null + */ + public Map> getValidationErrors() { + return (validationErrors); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + httpStatus; + result = prime * result + ((message == null) ? 0 : message.hashCode()); + result = prime * result + ((statusInfo == null) ? 0 : statusInfo.hashCode()); + result = prime * result + ((validationErrors == null) ? 0 : validationErrors.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + + if (this == obj) { + return true; } - /** - * Returns the HTTP status reason message, returns null if the - * causing error was not an HTTP related exception. - * - * @return the HTTP status reason message - */ - public final String getReason() { - return (statusInfo != null ? statusInfo.getReasonPhrase() : null); + if (obj == null) { + return false; } - /** - * Returns the HTTP status code that was the cause of the exception. returns 0 if the - * causing error was not an HTTP related exception - * - * @return the HTTP status code, returns 0 if the causing error was not an HTTP related exception - */ - public final int getHttpStatus() { - return (httpStatus); + if (getClass() != obj.getClass()) { + return false; } - /** - * Returns true if this GitLabApiException was caused by validation errors on the GitLab server, - * otherwise returns false. - * - * @return true if this GitLabApiException was caused by validation errors on the GitLab server, - * otherwise returns false - */ - public boolean hasValidationErrors() { - return (validationErrors != null); + final GitLabApiException other = (GitLabApiException) obj; + if (httpStatus != other.httpStatus) { + return false; } - /** - * Returns a Map<String, List<String>> instance containing validation errors if this GitLabApiException - * was caused by validation errors on the GitLab server, otherwise returns null. - * - * @return a Map<String, List<String>> instance containing validation errors if this GitLabApiException - * was caused by validation errors on the GitLab server, otherwise returns null - */ - public Map> getValidationErrors() { - return (validationErrors); + if (message == null) { + if (other.message != null) return false; + } else if (!message.equals(other.message)) { + return false; } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + httpStatus; - result = prime * result + ((message == null) ? 0 : message.hashCode()); - result = prime * result + ((statusInfo == null) ? 0 : statusInfo.hashCode()); - result = prime * result + ((validationErrors == null) ? 0 : validationErrors.hashCode()); - return result; + if (statusInfo == null) { + if (other.statusInfo != null) return false; + } else if (!statusInfo.equals(other.statusInfo)) { + return false; } - @Override - public boolean equals(Object obj) { - - if (this == obj) { - return true; - } - - if (obj == null) { - return false; - } - - if (getClass() != obj.getClass()) { - return false; - } - - GitLabApiException other = (GitLabApiException) obj; - if (httpStatus != other.httpStatus) { - return false; - } - - if (message == null) { - if (other.message != null) - return false; - } else if (!message.equals(other.message)) { - return false; - } - - if (statusInfo == null) { - if (other.statusInfo != null) - return false; - } else if (!statusInfo.equals(other.statusInfo)) { - return false; - } - - if (validationErrors == null) { - if (other.validationErrors != null) - return false; - } else if (!validationErrors.equals(other.validationErrors)) { - return false; - } - - return true; + if (validationErrors == null) { + if (other.validationErrors != null) return false; + } else if (!validationErrors.equals(other.validationErrors)) { + return false; } + + return true; + } } diff --git a/src/main/java/org/gitlab4j/api/GitLabApiForm.java b/src/main/java/org/gitlab4j/api/GitLabApiForm.java index b9c09e608..03d0cab92 100644 --- a/src/main/java/org/gitlab4j/api/GitLabApiForm.java +++ b/src/main/java/org/gitlab4j/api/GitLabApiForm.java @@ -1,220 +1,224 @@ package org.gitlab4j.api; +import jakarta.ws.rs.core.Form; +import jakarta.ws.rs.core.MultivaluedHashMap; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; - -import javax.ws.rs.core.Form; -import javax.ws.rs.core.MultivaluedHashMap; - import org.gitlab4j.api.models.AccessLevel; import org.gitlab4j.api.models.Variable; import org.gitlab4j.api.utils.ISO8601; -/** - * This class extends the standard JAX-RS Form class to make it fluent. - */ +/** This class extends the standard JAX-RS Form class to make it fluent. */ public class GitLabApiForm extends Form { - public GitLabApiForm() { - super(); - } - - public GitLabApiForm(MultivaluedHashMap map) { - super(map); + public GitLabApiForm() { + super(); + } + + public GitLabApiForm(final MultivaluedHashMap map) { + super(map); + } + + /** + * Create a GitLabApiForm instance with the "page", and "per_page" parameters preset. + * + * @param page the value for the "page" parameter + * @param perPage the value for the "per_page" parameter + */ + public GitLabApiForm(final int page, final int perPage) { + super(); + withParam(AbstractApi.PAGE_PARAM, page); + withParam(AbstractApi.PER_PAGE_PARAM, (Integer) perPage); + } + + /** + * Fluent method for adding query and form parameters to a get() or post() call. + * + * @param name the name of the field/attribute to add + * @param value the value of the field/attribute to add + * @return this GitLabAPiForm instance + */ + public GitLabApiForm withParam(final String name, final Object value) throws IllegalArgumentException { + return (withParam(name, value, false)); + } + + /** + * Fluent method for adding Date query and form parameters to a get() or post() call. + * + * @param name the name of the field/attribute to add + * @param date the value of the field/attribute to add + * @return this GitLabAPiForm instance + */ + public GitLabApiForm withParam(final String name, final Date date) throws IllegalArgumentException { + return (withParam(name, date, false)); + } + + /** + * Fluent method for adding Date query and form parameters to a get() or post() call. + * + * @param name the name of the field/attribute to add + * @param date the value of the field/attribute to add + * @param required the field is required flag + * @return this GitLabAPiForm instance + * @throws IllegalArgumentException if a required parameter is null or empty + */ + public GitLabApiForm withParam(final String name, final Date date, final boolean required) + throws IllegalArgumentException { + return (withParam(name, (date == null ? null : ISO8601.toString(date)), required)); + } + + /** + * Fluent method for adding AccessLevel query and form parameters to a get() or post() call. + * + * @param name the name of the field/attribute to add + * @param level the value of the field/attribute to add + * @return this GitLabAPiForm instance + */ + public GitLabApiForm withParam(final String name, final AccessLevel level) throws IllegalArgumentException { + return (withParam(name, level, false)); + } + + /** + * Fluent method for adding AccessLevel query and form parameters to a get() or post() call. + * + * @param name the name of the field/attribute to add + * @param level the value of the field/attribute to add + * @param required the field is required flag + * @return this GitLabAPiForm instance + * @throws IllegalArgumentException if a required parameter is null or empty + */ + public GitLabApiForm withParam(final String name, final AccessLevel level, final boolean required) + throws IllegalArgumentException { + return (withParam(name, (level == null ? null : level.toValue()), required)); + } + + /** + * Fluent method for adding a List type query and form parameters to a get() or post() call. + * + * @param the type contained by the List + * @param name the name of the field/attribute to add + * @param values a List containing the values of the field/attribute to add + * @return this GitLabAPiForm instance + */ + public GitLabApiForm withParam(final String name, final List values) { + return (withParam(name, values, false)); + } + + /** + * Fluent method for adding a List type query and form parameters to a get() or post() call. + * + * @param the type contained by the List + * @param name the name of the field/attribute to add + * @param values a List containing the values of the field/attribute to add + * @param required the field is required flag + * @return this GitLabAPiForm instance + * @throws IllegalArgumentException if a required parameter is null or empty + */ + public GitLabApiForm withParam(final String name, final List values, final boolean required) + throws IllegalArgumentException { + + if (values == null || values.isEmpty()) { + if (required) { + throw new IllegalArgumentException(name + " cannot be empty or null"); + } + + return (this); } - /** - * Create a GitLabApiForm instance with the "page", and "per_page" parameters preset. - * - * @param page the value for the "page" parameter - * @param perPage the value for the "per_page" parameter - */ - public GitLabApiForm(int page, int perPage) { - super(); - withParam(AbstractApi.PAGE_PARAM, page); - withParam(AbstractApi.PER_PAGE_PARAM, (Integer)perPage); + for (final T value : values) { + if (value != null) { + this.param(name + "[]", value.toString()); + } } - /** - * Fluent method for adding query and form parameters to a get() or post() call. - * - * @param name the name of the field/attribute to add - * @param value the value of the field/attribute to add - * @return this GitLabAPiForm instance - */ - public GitLabApiForm withParam(String name, Object value) throws IllegalArgumentException { - return (withParam(name, value, false)); + return (this); + } + + /** + * Fluent method for adding an array of hash type query and form parameters to a get() or post() + * call. + * + * @param name the name of the field/attribute to add + * @param variables a Map containing array of hashes + * @param required the field is required flag + * @return this GitLabAPiForm instance + * @throws IllegalArgumentException if a required parameter is null or empty + */ + public GitLabApiForm withParam(final String name, final Map variables, final boolean required) + throws IllegalArgumentException { + + if (variables == null || variables.isEmpty()) { + if (required) { + throw new IllegalArgumentException(name + " cannot be empty or null"); + } + + return (this); } - /** - * Fluent method for adding Date query and form parameters to a get() or post() call. - * - * @param name the name of the field/attribute to add - * @param date the value of the field/attribute to add - * @return this GitLabAPiForm instance - */ - public GitLabApiForm withParam(String name, Date date) throws IllegalArgumentException { - return (withParam(name, date, false)); + for (final Entry variable : variables.entrySet()) { + final Object value = variable.getValue(); + if (value != null) { + this.param(name + "[][key]", variable.getKey()); + this.param(name + "[][value]", value.toString()); + } } - /** - * Fluent method for adding Date query and form parameters to a get() or post() call. - * - * @param name the name of the field/attribute to add - * @param date the value of the field/attribute to add - * @param required the field is required flag - * @return this GitLabAPiForm instance - * @throws IllegalArgumentException if a required parameter is null or empty - */ - public GitLabApiForm withParam(String name, Date date, boolean required) throws IllegalArgumentException { - return (withParam(name, (date == null ? null : ISO8601.toString(date)), required)); + return (this); + } + + /** + * Fluent method for adding query and form parameters to a get() or post() call. If required is + * true and value is null, will throw an IllegalArgumentException. + * + * @param name the name of the field/attribute to add + * @param value the value of the field/attribute to add + * @param required the field is required flag + * @return this GitLabAPiForm instance + * @throws IllegalArgumentException if a required parameter is null or empty + */ + public GitLabApiForm withParam(final String name, final Object value, final boolean required) + throws IllegalArgumentException { + + if (value == null) { + if (required) { + throw new IllegalArgumentException(name + " cannot be empty or null"); + } + + return (this); } - /** - * Fluent method for adding AccessLevel query and form parameters to a get() or post() call. - * - * @param name the name of the field/attribute to add - * @param level the value of the field/attribute to add - * @return this GitLabAPiForm instance - */ - public GitLabApiForm withParam(String name, AccessLevel level) throws IllegalArgumentException { - return (withParam(name, level, false)); + final String stringValue = value.toString(); + if (required && stringValue.trim().length() == 0) { + throw new IllegalArgumentException(name + " cannot be empty or null"); } - /** - * Fluent method for adding AccessLevel query and form parameters to a get() or post() call. - * - * @param name the name of the field/attribute to add - * @param level the value of the field/attribute to add - * @param required the field is required flag - * @return this GitLabAPiForm instance - * @throws IllegalArgumentException if a required parameter is null or empty - */ - public GitLabApiForm withParam(String name, AccessLevel level, boolean required) throws IllegalArgumentException { - return (withParam(name, (level == null ? null : level.toValue()), required)); + this.param(name.trim(), stringValue); + return (this); + } + + /** + * Fluent method for adding a List<Variable> type query and form parameters to a get(), + * post(), or put() call. + * + * @param variables the List of Variable to add + * @return this GitLabAPiForm instance + */ + public GitLabApiForm withParam(final List variables) { + + if (variables == null || variables.isEmpty()) { + return (this); } - /** - * Fluent method for adding a List type query and form parameters to a get() or post() call. - * - * @param the type contained by the List - * @param name the name of the field/attribute to add - * @param values a List containing the values of the field/attribute to add - * @return this GitLabAPiForm instance - */ - public GitLabApiForm withParam(String name, List values) { - return (withParam(name, values, false)); - } - - /** - * Fluent method for adding a List type query and form parameters to a get() or post() call. - * - * @param the type contained by the List - * @param name the name of the field/attribute to add - * @param values a List containing the values of the field/attribute to add - * @param required the field is required flag - * @return this GitLabAPiForm instance - * @throws IllegalArgumentException if a required parameter is null or empty - */ - public GitLabApiForm withParam(String name, List values, boolean required) throws IllegalArgumentException { - - if (values == null || values.isEmpty()) { - if (required) { - throw new IllegalArgumentException(name + " cannot be empty or null"); - } - - return (this); - } - - for (T value : values) { - if (value != null) { - this.param(name + "[]", value.toString()); - } - } - - return (this); - } - - /** - * Fluent method for adding an array of hash type query and form parameters to a get() or post() call. - * - * @param name the name of the field/attribute to add - * @param variables a Map containing array of hashes - * @param required the field is required flag - * @return this GitLabAPiForm instance - * @throws IllegalArgumentException if a required parameter is null or empty - */ - public GitLabApiForm withParam(String name, Map variables, boolean required) throws IllegalArgumentException { - - if (variables == null || variables.isEmpty()) { - if (required) { - throw new IllegalArgumentException(name + " cannot be empty or null"); - } - - return (this); - } - - for (Entry variable : variables.entrySet()) { - Object value = variable.getValue(); - if (value != null) { - this.param(name + "[][key]", variable.getKey()); - this.param(name + "[][value]", value.toString()); - } - } - - return (this); - } - - /** - * Fluent method for adding query and form parameters to a get() or post() call. - * If required is true and value is null, will throw an IllegalArgumentException. - * - * @param name the name of the field/attribute to add - * @param value the value of the field/attribute to add - * @param required the field is required flag - * @return this GitLabAPiForm instance - * @throws IllegalArgumentException if a required parameter is null or empty - */ - public GitLabApiForm withParam(String name, Object value, boolean required) throws IllegalArgumentException { - - if (value == null) { - if (required) { - throw new IllegalArgumentException(name + " cannot be empty or null"); - } - - return (this); - } - - String stringValue = value.toString(); - if (required && stringValue.trim().length() == 0) { - throw new IllegalArgumentException(name + " cannot be empty or null"); - } - - this.param(name.trim(), stringValue); - return (this); - } - - /** - * Fluent method for adding a List<Variable> type query and form parameters to a get(), post(), or put() call. - * - * @param variables the List of Variable to add - * @return this GitLabAPiForm instance - */ - public GitLabApiForm withParam(List variables) { - - if (variables == null || variables.isEmpty()) { - return (this); - } - - variables.forEach(v -> { - String value = v.getValue(); - if (value != null) { - this.param("variables[" + v.getKey() + "]", value); - } + variables.forEach( + v -> { + final String value = v.getValue(); + if (value != null) { + this.param("variables[" + v.getKey() + "]", value); + } }); - return (this); - } -} \ No newline at end of file + return (this); + } +} diff --git a/src/main/java/org/gitlab4j/api/GroupApi.java b/src/main/java/org/gitlab4j/api/GroupApi.java index 4b37ff496..b857eaf2a 100644 --- a/src/main/java/org/gitlab4j/api/GroupApi.java +++ b/src/main/java/org/gitlab4j/api/GroupApi.java @@ -5,13 +5,10 @@ import java.util.List; import java.util.Objects; import java.util.Optional; -import java.util.stream.Collectors; import java.util.stream.Stream; - -import javax.ws.rs.core.Form; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; - +import jakarta.ws.rs.core.Form; +import jakarta.ws.rs.core.GenericType; +import jakarta.ws.rs.core.Response; import org.gitlab4j.api.GitLabApi.ApiVersion; import org.gitlab4j.api.models.AccessLevel; import org.gitlab4j.api.models.AccessRequest; @@ -30,1917 +27,2550 @@ /** * This class implements the client side API for the GitLab groups calls. + * * @see Groups API at GitLab - * @see Group and project members API at GitLab - * @see Group and project access requests API + * @see Group and project members API at + * GitLab + * @see Group and project access + * requests API * @see Group badges API - * @see Group audit events API + * @see Group + * audit events API */ public class GroupApi extends AbstractApi { - public GroupApi(GitLabApi gitLabApi) { - super(gitLabApi); - } - - /** - *

Get a list of groups. (As user: my groups, as admin: all groups)

- * - * WARNING: Do not use this method to fetch groups from https://gitlab.com, - * gitlab.com has many 1,000's of public groups and it will a long time to fetch all of them. - * Instead use {@link #getGroups(int itemsPerPage)} which will return a Pager of Group instances. - * - *
GitLab Endpoint: GET /groups
- * - * @return the list of groups viewable by the authenticated user - * @throws GitLabApiException if any exception occurs - */ - public List getGroups() throws GitLabApiException { - - String url = this.gitLabApi.getGitLabServerUrl(); - if (url.startsWith("https://gitlab.com")) { - GitLabApi.getLogger().warning("Fetching all groups from " + url + - " may take many minutes to complete, use Pager getGroups(int) instead."); - } - - return (getGroups(getDefaultPerPage()).all()); - } - - /** - * Get a list of groups (As user: my groups, as admin: all groups) and in the specified page range. - * - *
GitLab Endpoint: GET /groups
- * - * @param page the page to get - * @param perPage the number of Group instances per page - * @return the list of groups viewable by the authenticated userin the specified page range - * @throws GitLabApiException if any exception occurs - */ - public List getGroups(int page, int perPage) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "groups"); - return (response.readEntity(new GenericType>() {})); - } - - /** - * Get a Pager of groups. (As user: my groups, as admin: all groups) - * - *
GitLab Endpoint: GET /groups
- * - * @param itemsPerPage the number of Group instances that will be fetched per page - * @return the list of groups viewable by the authenticated user - * @throws GitLabApiException if any exception occurs - */ - public Pager getGroups(int itemsPerPage) throws GitLabApiException { - return (new Pager(this, Group.class, itemsPerPage, null, "groups")); - } - - /** - * Get a Stream of groups. (As user: my groups, as admin: all groups) - * - *
GitLab Endpoint: GET /groups
- * - * @return a Stream of groups viewable by the authenticated user - * @throws GitLabApiException if any exception occurs - */ - public Stream getGroupsStream() throws GitLabApiException { - return (getGroups(getDefaultPerPage()).stream()); - } - - /** - * Get all groups that match your string in their name or path. - * - * @param search the group name or path search criteria - * @return a List containing matching Group instances - * @throws GitLabApiException if any exception occurs - */ - public List getGroups(String search) throws GitLabApiException { - return (getGroups(search, getDefaultPerPage()).all()); - } - - /** - * Get all groups that match your string in their name or path. - * - * @param search the group name or path search criteria - * @param page the page to get - * @param perPage the number of Group instances per page - * @return a List containing matching Group instances - * @throws GitLabApiException if any exception occurs - */ - public List getGroups(String search, int page, int perPage) throws GitLabApiException { - Form formData = new GitLabApiForm().withParam("search", search).withParam(PAGE_PARAM, page).withParam(PER_PAGE_PARAM, perPage); - Response response = get(Response.Status.OK, formData.asMap(), "groups"); - return (response.readEntity(new GenericType>() {})); - } - - /** - * Get all groups that match your string in their name or path. - * - * @param search the group name or path search criteria - * @param itemsPerPage the number of Group instances that will be fetched per page - * @return a Pager containing matching Group instances - * @throws GitLabApiException if any exception occurs - */ - public Pager getGroups(String search, int itemsPerPage) throws GitLabApiException { - Form formData = new GitLabApiForm().withParam("search", search); - return (new Pager(this, Group.class, itemsPerPage, formData.asMap(), "groups")); - } - - /** - * Get all groups that match your string in their name or path as a Stream. - * - * @param search the group name or path search criteria - * @return a Stream containing matching Group instances - * @throws GitLabApiException if any exception occurs - */ - public Stream getGroupsStream(String search) throws GitLabApiException { - return (getGroups(search, getDefaultPerPage()).stream()); - } - - /** - * Get a list of visible groups for the authenticated user using the provided filter. - * - *
GitLab Endpoint: GET /groups
- * - * @param filter the GroupFilter to match against - * @return a List<Group> of the matching groups - * @throws GitLabApiException if any exception occurs - */ - public List getGroups(GroupFilter filter) throws GitLabApiException { - return (getGroups(filter, getDefaultPerPage()).all()); - } - - /** - * Get a Pager of visible groups for the authenticated user using the provided filter. - * - *
GitLab Endpoint: GET /groups
- * - * @param filter the GroupFilter to match against - * @param itemsPerPage the number of Group instances that will be fetched per page - * @return a Pager containing matching Group instances - * @throws GitLabApiException if any exception occurs - */ - public Pager getGroups(GroupFilter filter, int itemsPerPage) throws GitLabApiException { - GitLabApiForm formData = filter.getQueryParams(); - return (new Pager(this, Group.class, itemsPerPage, formData.asMap(), "groups")); - } - - /** - * Get a Stream of visible groups for the authenticated user using the provided filter. - * - *
GitLab Endpoint: GET /groups
- * - * @param filter the GroupFilter to match against - * @return a Stream<Group> of the matching groups - * @throws GitLabApiException if any exception occurs - */ - public Stream getGroupsStream(GroupFilter filter) throws GitLabApiException { - return (getGroups(filter, getDefaultPerPage()).stream()); - } - - /** - * Get a list of visible direct subgroups in this group. - * - *
GitLab Endpoint: GET /groups/:id/subgroups
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @return a List<Group> containing the group's sub-groups - * @throws GitLabApiException if any exception occurs - * @since GitLab 10.3.0 - */ - public List getSubGroups(Object groupIdOrPath) throws GitLabApiException { - return (getSubGroups(groupIdOrPath, getDefaultPerPage()).all()); - } - - /** - * Get a Pager of visible direct subgroups in this group. - * - *
GitLab Endpoint: GET /groups/:id/subgroups
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param itemsPerPage the number of Group instances that will be fetched per page - * @return a Pager containing matching Group instances - * @throws GitLabApiException if any exception occurs - * @since GitLab 10.3.0 - */ - public Pager getSubGroups(Object groupIdOrPath, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, Group.class, itemsPerPage, null, "groups", getGroupIdOrPath(groupIdOrPath), "subgroups")); - } - - /** - * Get a Stream of visible direct subgroups in this group. - * - *
GitLab Endpoint: GET /groups/:id/subgroups
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @return a Stream<Group> containing the group's sub-groups - * @throws GitLabApiException if any exception occurs - * @since GitLab 10.3.0 - */ - public Stream getSubGroupsStream(Object groupIdOrPath) throws GitLabApiException { - return (getSubGroups(groupIdOrPath, getDefaultPerPage()).stream()); - } - - /** - * Get a list of visible direct subgroups in this group. - * - *
GitLab Endpoint: GET /groups/:id/subgroups
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param skipGroups skip the group IDs passed - * @param allAvailable show all the groups you have access to (defaults to false for authenticated users) - * @param search return the list of authorized groups matching the search criteria - * @param orderBy order groups by NAME or PATH. Default is NAME - * @param sortOrder order groups in ASC or DESC order. Default is ASC - * @param statistics include group statistics (admins only) - * @param owned limit to groups owned by the current user - * @return a List<Group> of the matching subgroups - * @throws GitLabApiException if any exception occurs - * @since GitLab 10.3.0 - */ - public List getSubGroups(Object groupIdOrPath, List skipGroups, Boolean allAvailable, String search, - GroupOrderBy orderBy, SortOrder sortOrder, Boolean statistics, Boolean owned) throws GitLabApiException { - return (getSubGroups(groupIdOrPath, skipGroups, allAvailable, search, orderBy, sortOrder, statistics, owned, getDefaultPerPage()).all()); - } - - /** - * Get a list of visible direct subgroups in this group. - * - *
GitLab Endpoint: GET /groups/:id/subgroups
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param skipGroups skip the group IDs passed - * @param allAvailable show all the groups you have access to (defaults to false for authenticated users) - * @param search return the list of authorized groups matching the search criteria - * @param orderBy order groups by NAME or PATH. Default is NAME - * @param sortOrder order groups in ASC or DESC order. Default is ASC - * @param statistics include group statistics (admins only) - * @param owned limit to groups owned by the current user - * @param page the page to get - * @param perPage the number of Group instances per page - * @return a List<Group> of the matching subgroups - * @throws GitLabApiException if any exception occurs - * @since GitLab 10.3.0 - */ - public List getSubGroups(Object groupIdOrPath, List skipGroups, Boolean allAvailable, String search, - GroupOrderBy orderBy, SortOrder sortOrder, Boolean statistics, Boolean owned, int page, int perPage) - throws GitLabApiException { - Form formData = new GitLabApiForm() - .withParam("skip_groups", skipGroups) - .withParam("all_available", allAvailable) - .withParam("search", search) - .withParam("order_by", orderBy) - .withParam("sort_order", sortOrder) - .withParam("statistics", statistics) - .withParam("owned", owned) - .withParam(PAGE_PARAM, page) - .withParam(PER_PAGE_PARAM, perPage); - Response response = get(Response.Status.OK, formData.asMap(), "groups", getGroupIdOrPath(groupIdOrPath), "subgroups"); - return (response.readEntity(new GenericType>() {})); - } - - /** - * Get a Pager of visible direct subgroups in this group. - * - *
GitLab Endpoint: GET /groups/:id/subgroups
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param skipGroups skip the group IDs passed - * @param allAvailable show all the groups you have access to (defaults to false for authenticated users) - * @param search return the list of authorized groups matching the search criteria - * @param orderBy order groups by NAME or PATH. Default is NAME - * @param sortOrder order groups in ASC or DESC order. Default is ASC - * @param statistics include group statistics (admins only) - * @param owned limit to groups owned by the current user - * @param itemsPerPage the number of Group instances that will be fetched per page - * @return a Pager containing matching Group instances - * @throws GitLabApiException if any exception occurs - * @since GitLab 10.3.0 - */ - public Pager getSubGroups(Object groupIdOrPath, List skipGroups, Boolean allAvailable, String search, - GroupOrderBy orderBy, SortOrder sortOrder, Boolean statistics, Boolean owned, int itemsPerPage) throws GitLabApiException { - Form formData = new GitLabApiForm() - .withParam("skip_groups", skipGroups) - .withParam("all_available", allAvailable) - .withParam("search", search) - .withParam("order_by", orderBy) - .withParam("sort_order", sortOrder) - .withParam("statistics", statistics) - .withParam("owned", owned); - return (new Pager(this, Group.class, itemsPerPage, formData.asMap(), "groups", getGroupIdOrPath(groupIdOrPath), "subgroups")); - } - - /** - * Get a Stream of visible direct subgroups in this group. - * - *
GitLab Endpoint: GET /groups/:id/subgroups
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param skipGroups skip the group IDs passed - * @param allAvailable show all the groups you have access to (defaults to false for authenticated users) - * @param search return the list of authorized groups matching the search criteria - * @param orderBy order groups by NAME or PATH. Default is NAME - * @param sortOrder order groups in ASC or DESC order. Default is ASC - * @param statistics include group statistics (admins only) - * @param owned limit to groups owned by the current user - * @return a Stream<Group> of the matching subgroups - * @throws GitLabApiException if any exception occurs - * @since GitLab 10.3.0 - */ - public Stream getSubGroupsStream(Object groupIdOrPath, List skipGroups, Boolean allAvailable, String search, - GroupOrderBy orderBy, SortOrder sortOrder, Boolean statistics, Boolean owned) throws GitLabApiException { - return (getSubGroups(groupIdOrPath, skipGroups, allAvailable, search, orderBy, sortOrder, statistics, owned, getDefaultPerPage()).stream()); - } - - /** - * Get a list of visible descendant groups of a given group for the authenticated user using the provided filter. - * - *
GitLab Endpoint: GET /groups/:id/descendant_groups
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param filter the GroupFilter to match against - * @return a List<Group> of the matching groups - * @throws GitLabApiException if any exception occurs - */ - public List getDescendantGroups(Object groupIdOrPath, GroupFilter filter) throws GitLabApiException { - return (getDescendantGroups(groupIdOrPath, filter, getDefaultPerPage()).all()); - } - - /** - * Get a Pager of visible descendant groups of a given group for the authenticated user using the provided filter. - * - *
GitLab Endpoint: GET /groups/:id/descendant_groups
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param filter the GroupFilter to match against - * @param itemsPerPage the number of Group instances that will be fetched per page - * @return a Pager containing matching Group instances - * @throws GitLabApiException if any exception occurs - */ - public Pager getDescendantGroups(Object groupIdOrPath, GroupFilter filter, int itemsPerPage) throws GitLabApiException { - GitLabApiForm formData = filter.getQueryParams(); - return (new Pager(this, Group.class, itemsPerPage, formData.asMap(), "groups", getGroupIdOrPath(groupIdOrPath), "descendant_groups")); - } - - /** - * Get a Stream of visible descendant groups of a given group for the authenticated user using the provided filter. - * - *
GitLab Endpoint: GET /groups/:id/descendant_groups
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param filter the GroupFilter to match against - * @return a Stream<Group> of the matching groups - * @throws GitLabApiException if any exception occurs - */ - public Stream getDescendantGroupsStream(Object groupIdOrPath, GroupFilter filter) throws GitLabApiException { - return (getDescendantGroups(groupIdOrPath, filter, getDefaultPerPage()).stream()); - } - - /** - * Get a list of projects belonging to the specified group ID and filter. - * - *
GitLab Endpoint: GET /groups/:id/projects
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param filter the GroupProjectsFilter instance holding the filter values for the query - * @return a List containing Project instances that belong to the group and match the provided filter - * @throws GitLabApiException if any exception occurs - */ - public List getProjects(Object groupIdOrPath, GroupProjectsFilter filter) throws GitLabApiException { - return (getProjects(groupIdOrPath, filter, getDefaultPerPage()).all()); - } - - /** - * Get a Pager of projects belonging to the specified group ID and filter. - * - *
GitLab Endpoint: GET /groups/:id/projects
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param filter the GroupProjectsFilter instance holding the filter values for the query - * @param itemsPerPage the number of Project instances that will be fetched per page - * @return a Pager containing Project instances that belong to the group and match the provided filter - * @throws GitLabApiException if any exception occurs - */ - public Pager getProjects(Object groupIdOrPath, GroupProjectsFilter filter, int itemsPerPage) throws GitLabApiException { - GitLabApiForm formData = filter.getQueryParams(); - return (new Pager(this, Project.class, itemsPerPage, formData.asMap(), "groups", getGroupIdOrPath(groupIdOrPath), "projects")); - } - - /** - * Get a Stream of projects belonging to the specified group ID and filter. - * - *
GitLab Endpoint: GET /groups/:id/projects
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param filter the GroupProjectsFilter instance holding the filter values for the query - * @return a Stream containing Project instances that belong to the group and match the provided filter - * @throws GitLabApiException if any exception occurs - */ - public Stream getProjectsStream(Object groupIdOrPath, GroupProjectsFilter filter) throws GitLabApiException { - return (getProjects(groupIdOrPath, filter, getDefaultPerPage()).stream()); - } - - /** - * Get a list of projects belonging to the specified group ID. - * - *
GitLab Endpoint: GET /groups/:id/projects
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @return a list of projects belonging to the specified group ID - * @throws GitLabApiException if any exception occurs - */ - public List getProjects(Object groupIdOrPath) throws GitLabApiException { - return (getProjects(groupIdOrPath, getDefaultPerPage()).all()); - } - - /** - * Get a list of projects belonging to the specified group ID in the specified page range. - * - *
GitLab Endpoint: GET /groups/:id/projects
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param page the page to get - * @param perPage the number of Project instances per page - * @return a list of projects belonging to the specified group ID in the specified page range - * @throws GitLabApiException if any exception occurs - */ - public List getProjects(Object groupIdOrPath, int page, int perPage) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "groups", getGroupIdOrPath(groupIdOrPath), "projects"); - return (response.readEntity(new GenericType>() {})); - } - - /** - * Get a Pager of projects belonging to the specified group ID. - * - *
GitLab Endpoint: GET /groups/:id/projects
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param itemsPerPage the number of Project instances that will be fetched per page - * @return a Pager of projects belonging to the specified group ID - * @throws GitLabApiException if any exception occurs - */ - public Pager getProjects(Object groupIdOrPath, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, Project.class, itemsPerPage, null, "groups", getGroupIdOrPath(groupIdOrPath), "projects")); - } - - /** - * Get a Stream of projects belonging to the specified group ID. - * - *
GitLab Endpoint: GET /groups/:id/projects
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @return a Stream of projects belonging to the specified group ID - * @throws GitLabApiException if any exception occurs - */ - public Stream getProjectsStream(Object groupIdOrPath) throws GitLabApiException { - return (getProjects(groupIdOrPath, getDefaultPerPage()).stream()); - } - - /** - * Get all details of a group. - * - *
GitLab Endpoint: GET /groups/:id
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @return the Group instance for the specified group path - * @throws GitLabApiException if any exception occurs - */ - public Group getGroup(Object groupIdOrPath) throws GitLabApiException { - Response response = get(Response.Status.OK, null, "groups", getGroupIdOrPath(groupIdOrPath)); - return (response.readEntity(Group.class)); - } - - /** - * Get all details of a group as an Optional instance. - * - *
GitLab Endpoint: GET /groups/:id
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @return the Group for the specified group path as an Optional instance - */ - public Optional getOptionalGroup(Object groupIdOrPath) { - try { - return (Optional.ofNullable(getGroup(groupIdOrPath))); - } catch (GitLabApiException glae) { - return (GitLabApi.createOptionalFromException(glae)); - } - } - - /** - * Creates a new project group. Available only for users who can create groups. - * - *
GitLab Endpoint: POST /groups
- * - * @param params a GroupParams instance holding the parameters for the group creation - * @return the created Group instance - * @throws GitLabApiException if any exception occurs - */ - public Group createGroup(GroupParams params) throws GitLabApiException { - Response response = post(Response.Status.CREATED, params.getForm(true), "groups"); - return (response.readEntity(Group.class)); - } - - /** - * Updates the project group. Only available to group owners and administrators. - * - *
GitLab Endpoint: PUT /groups
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param params the GroupParams instance holding the properties to update - * @return updated Group instance - * @throws GitLabApiException at any exception - */ - public Group updateGroup(Object groupIdOrPath, GroupParams params) throws GitLabApiException { - Response response = putWithFormData(Response.Status.OK, - params.getForm(false), "groups", getGroupIdOrPath(groupIdOrPath)); - return (response.readEntity(Group.class)); - } - - /** - * Creates a new project group. Available only for users who can create groups. - * - *
GitLab Endpoint: POST /groups
- * - * @param name the name of the group to add - * @param path the path for the group - * @return the created Group instance - * @throws GitLabApiException if any exception occurs - */ - public Group addGroup(String name, String path) throws GitLabApiException { - - Form formData = new Form(); - formData.param("name", name); - formData.param("path", path); - Response response = post(Response.Status.CREATED, formData, "groups"); - return (response.readEntity(Group.class)); - } - - public Group addGroup(Group group) throws GitLabApiException { - Form formData = new GitLabApiForm() - .withParam("name", group.getName(), true) - .withParam("path", group.getPath(), true) - .withParam("description", group.getDescription()) - .withParam("visibility", group.getVisibility()) - .withParam("lfs_enabled", group.getLfsEnabled()) - .withParam("request_access_enabled", group.getRequestAccessEnabled()) - .withParam("parent_id", isApiVersion(ApiVersion.V3) ? null : group.getParentId()); - Response response = post(Response.Status.CREATED, formData, "groups"); - return (response.readEntity(Group.class)); - } - - /** - * Creates a new project group. Available only for users who can create groups. - * - *
GitLab Endpoint: POST /groups
- * - * @param name the name of the group to add - * @param path the path for the group - * @param description (optional) - The group's description - * @param visibility (optional) - The group's visibility. Can be private, internal, or public. - * @param lfsEnabled (optional) - Enable/disable Large File Storage (LFS) for the projects in this group - * @param requestAccessEnabled (optional) - Allow users to request member access - * @param parentId (optional) - The parent group id for creating nested group - * @return the created Group instance - * @throws GitLabApiException if any exception occurs - */ - public Group addGroup(String name, String path, String description, Visibility visibility, - Boolean lfsEnabled, Boolean requestAccessEnabled, Long parentId) throws GitLabApiException { - - Form formData = new GitLabApiForm() - .withParam("name", name, true) - .withParam("path", path, true) - .withParam("description", description) - .withParam("visibility", visibility) - .withParam("lfs_enabled", lfsEnabled) - .withParam("request_access_enabled", requestAccessEnabled) - .withParam("parent_id", isApiVersion(ApiVersion.V3) ? null : parentId); - Response response = post(Response.Status.CREATED, formData, "groups"); - return (response.readEntity(Group.class)); - } - - /** - * Updates a project group. Available only for users who can create groups. - * - *
GitLab Endpoint: PUT /groups
- * - * @param group to update - * @return updated group instance - * @throws GitLabApiException at any exception - */ - public Group updateGroup(Group group) throws GitLabApiException { - Form formData = new GitLabApiForm() - .withParam("name", group.getName()) - .withParam("path", group.getPath()) - .withParam("description", group.getDescription()) - .withParam("visibility", group.getVisibility()) - .withParam("lfs_enabled", group.getLfsEnabled()) - .withParam("request_access_enabled", group.getRequestAccessEnabled()) - .withParam("parent_id", isApiVersion(ApiVersion.V3) ? null : group.getParentId()); - Response response = put(Response.Status.OK, formData.asMap(), "groups", group.getId()); - return (response.readEntity(Group.class)); - } - - /** - * Updates a project group. Available only for users who can create groups. - * - *
GitLab Endpoint: PUT /groups
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param name the name of the group to add - * @param path the path for the group - * @param description (optional) - The group's description - * @param visibility (optional) - The group's visibility. Can be private, internal, or public. - * @param lfsEnabled (optional) - Enable/disable Large File Storage (LFS) for the projects in this group - * @param requestAccessEnabled (optional) - Allow users to request member access - * @param parentId (optional) - The parent group id for creating nested group - * @return the updated Group instance - * @throws GitLabApiException if any exception occurs - */ - public Group updateGroup(Object groupIdOrPath, String name, String path, String description, Visibility visibility, - Boolean lfsEnabled, Boolean requestAccessEnabled, Long parentId) throws GitLabApiException { - - Form formData = new GitLabApiForm() - .withParam("name", name) - .withParam("path", path) - .withParam("description", description) - .withParam("visibility", visibility) - .withParam("lfs_enabled", lfsEnabled) - .withParam("request_access_enabled", requestAccessEnabled) - .withParam("parent_id", isApiVersion(ApiVersion.V3) ? null : parentId); - Response response = put(Response.Status.OK, formData.asMap(), "groups", getGroupIdOrPath(groupIdOrPath)); - return (response.readEntity(Group.class)); - } - - /** - * Creates a new project group. Available only for users who can create groups. - * - *
GitLab Endpoint: POST /groups
- * - * @param name the name of the group to add - * @param path the path for the group - * @param description (optional) - The group's description - * @param membershipLock (optional, boolean) - Prevent adding new members to project membership within this group - * @param shareWithGroupLock (optional, boolean) - Prevent sharing a project with another group within this group - * @param visibility (optional) - The group's visibility. Can be private, internal, or public. - * @param lfsEnabled (optional) - Enable/disable Large File Storage (LFS) for the projects in this group - * @param requestAccessEnabled (optional) - Allow users to request member access. - * @param parentId (optional) - The parent group id for creating nested group. - * @param sharedRunnersMinutesLimit (optional) - (admin-only) Pipeline minutes quota for this group - * @return the created Group instance - * @throws GitLabApiException if any exception occurs - * @deprecated Will be removed in version 6.0, replaced by {@link #addGroup(String, String, String, Visibility, - * Boolean, Boolean, Long)} - */ - @Deprecated - public Group addGroup(String name, String path, String description, Boolean membershipLock, - Boolean shareWithGroupLock, Visibility visibility, Boolean lfsEnabled, Boolean requestAccessEnabled, - Long parentId, Integer sharedRunnersMinutesLimit) throws GitLabApiException { - - Form formData = new GitLabApiForm() - .withParam("name", name) - .withParam("path", path) - .withParam("description", description) - .withParam("membership_lock", membershipLock) - .withParam("share_with_group_lock", shareWithGroupLock) - .withParam("visibility", visibility) - .withParam("lfs_enabled", lfsEnabled) - .withParam("request_access_enabled", requestAccessEnabled) - .withParam("parent_id", parentId) - .withParam("shared_runners_minutes_limit", sharedRunnersMinutesLimit); - Response response = post(Response.Status.CREATED, formData, "groups"); - return (response.readEntity(Group.class)); - } - - /** - * Updates a project group. Available only for users who can create groups. - * - *
GitLab Endpoint: PUT /groups
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param name the name of the group to add - * @param path the path for the group - * @param description (optional) - The group's description - * @param membershipLock (optional, boolean) - Prevent adding new members to project membership within this group - * @param shareWithGroupLock (optional, boolean) - Prevent sharing a project with another group within this group - * @param visibility (optional) - The group's visibility. Can be private, internal, or public. - * @param lfsEnabled (optional) - Enable/disable Large File Storage (LFS) for the projects in this group - * @param requestAccessEnabled (optional) - Allow users to request member access - * @param parentId (optional) - The parent group id for creating nested group - * @param sharedRunnersMinutesLimit (optional) - (admin-only) Pipeline minutes quota for this group - * @return the updated Group instance - * @throws GitLabApiException if any exception occurs - * @deprecated Will be removed in version 6.0, replaced by {@link #updateGroup(Object, String, String, String, - * Visibility, Boolean, Boolean, Long)} - */ - @Deprecated - public Group updateGroup(Object groupIdOrPath, String name, String path, String description, Boolean membershipLock, - Boolean shareWithGroupLock, Visibility visibility, Boolean lfsEnabled, Boolean requestAccessEnabled, - Long parentId, Integer sharedRunnersMinutesLimit) throws GitLabApiException { - - Form formData = new GitLabApiForm() - .withParam("name", name) - .withParam("path", path) - .withParam("description", description) - .withParam("membership_lock", membershipLock) - .withParam("share_with_group_lock", shareWithGroupLock) - .withParam("visibility", visibility) - .withParam("lfs_enabled", lfsEnabled) - .withParam("request_access_enabled", requestAccessEnabled) - .withParam("parent_id", parentId) - .withParam("shared_runners_minutes_limit", sharedRunnersMinutesLimit); - Response response = put(Response.Status.OK, formData.asMap(), "groups", getGroupIdOrPath(groupIdOrPath)); - return (response.readEntity(Group.class)); - } - - /** - * Removes group with all projects inside. - * - *
GitLab Endpoint: DELETE /groups/:id
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @throws GitLabApiException if any exception occurs - */ - public void deleteGroup(Object groupIdOrPath) throws GitLabApiException { - Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT); - delete(expectedStatus, null, "groups", getGroupIdOrPath(groupIdOrPath)); - } - - /** - * Get a list of group members viewable by the authenticated user. - * - *
GitLab Endpoint: GET /groups/:id/members
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @return a list of group members viewable by the authenticated user - * @throws GitLabApiException if any exception occurs - */ - public List getMembers(Object groupIdOrPath) throws GitLabApiException { - return (getMembers(groupIdOrPath, getDefaultPerPage()).all()); - } - - /** - * Get a list of group members viewable by the authenticated user in the specified page range. - * - *
GitLab Endpoint: GET /groups/:id/members
- * - *@param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param page the page to get - * @param perPage the number of Member instances per page - * @return a list of group members viewable by the authenticated user in the specified page range - * @throws GitLabApiException if any exception occurs - */ - public List getMembers(Object groupIdOrPath, int page, int perPage) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "groups", getGroupIdOrPath(groupIdOrPath), "members"); - return (response.readEntity(new GenericType>() {})); - } - - /** - * Get a Pager of group members viewable by the authenticated user. - * - *
GitLab Endpoint: GET /groups/:id/members
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param itemsPerPage the number of Member instances that will be fetched per page - * @return a list of group members viewable by the authenticated user - * @throws GitLabApiException if any exception occurs - */ - public Pager getMembers(Object groupIdOrPath, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, Member.class, itemsPerPage, null, "groups", getGroupIdOrPath(groupIdOrPath), "members")); - } - - /** - * Get a Stream of group members viewable by the authenticated user. - * - *
GitLab Endpoint: GET /groups/:id/members
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @return a Stream of group members viewable by the authenticated user - * @throws GitLabApiException if any exception occurs - */ - public Stream getMembersStream(Object groupIdOrPath) throws GitLabApiException { - return (getMembers(groupIdOrPath, getDefaultPerPage()).stream()); - } - - /** - * Get a group member viewable by the authenticated user. - * - *
GitLab Endpoint: GET /groups/:id/members/:id
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param userId the member ID of the member to get - * @return a member viewable by the authenticated user - * @throws GitLabApiException if any exception occurs - */ - public Member getMember(Object groupIdOrPath, long userId) throws GitLabApiException { - return (getMember(groupIdOrPath, userId, false)); - } - - /** - * Get a group member viewable by the authenticated user as an Optional instance. - * - *
GitLab Endpoint: GET /groups/:id/members/:id
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param userId the member ID of the member to get - * @return a member viewable by the authenticated user as an Optional instance - */ - public Optional getOptionalMember(Object groupIdOrPath, long userId) { - try { - return (Optional.ofNullable(getMember(groupIdOrPath, userId, false))); - } catch (GitLabApiException glae) { - return (GitLabApi.createOptionalFromException(glae)); - } - } - - /** - * Gets a group team member, optionally including inherited member. - * - *
GitLab Endpoint: GET /groups/:id/members/all/:user_id
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param userId the user ID of the member - * @param includeInherited if true will the member even if inherited thru an ancestor group - * @return the member specified by the project ID/user ID pair - * @throws GitLabApiException if any exception occurs - */ - public Member getMember(Object groupIdOrPath, Long userId, Boolean includeInherited) throws GitLabApiException { - Response response; - if (includeInherited) { - response = get(Response.Status.OK, null, "groups", getGroupIdOrPath(groupIdOrPath), "members", "all", userId); - } else { - response = get(Response.Status.OK, null, "groups", getGroupIdOrPath(groupIdOrPath), "members", userId); - } - return (response.readEntity(Member.class)); - } - - /** - * Gets a group team member, optionally including inherited member. - * - *
GitLab Endpoint: GET /groups/:id/members/all/:user_id
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param userId the user ID of the member - * @param includeInherited if true will the member even if inherited thru an ancestor group - * @return the member specified by the group ID/user ID pair as the value of an Optional - */ - public Optional getOptionalMember(Object groupIdOrPath, Long userId, Boolean includeInherited) { - try { - return (Optional.ofNullable(getMember(groupIdOrPath, userId, includeInherited))); - } catch (GitLabApiException glae) { - return (GitLabApi.createOptionalFromException(glae)); - } - } - - /** - * Gets a list of group members viewable by the authenticated user, including inherited members - * through ancestor groups. Returns multiple times the same user (with different member attributes) - * when the user is a member of the group and of one or more ancestor group. - * - *
GitLab Endpoint: GET /groups/:id/members/all
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @return a list of group members viewable by the authenticated user, including inherited members - * through ancestor groups - * @throws GitLabApiException if any exception occurs - */ - public List getAllMembers(Object groupIdOrPath) throws GitLabApiException { - return (getAllMembers(groupIdOrPath, null, null)); - } - - /** - * Gets a list of group members viewable by the authenticated user, including inherited members - * through ancestor groups. Returns multiple times the same user (with different member attributes) - * when the user is a member of the group and of one or more ancestor group. - * - *
GitLab Endpoint: GET /groups/:id/members/all
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param page the page to get - * @param perPage the number of Member instances per page - * @return a list of group members viewable by the authenticated user, including inherited members - * through ancestor groups in the specified page range - * @throws GitLabApiException if any exception occurs - * @deprecated Will be removed in version 6.0 - */ - @Deprecated - public List getAllMembers(Object groupIdOrPath, int page, int perPage) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), - "groups", getGroupIdOrPath(groupIdOrPath), "members", "all"); - return (response.readEntity(new GenericType>() {})); - } - - /** - * Gets a Pager of group members viewable by the authenticated user, including inherited members - * through ancestor groups. Returns multiple times the same user (with different member attributes) - * when the user is a member of the group and of one or more ancestor group. - * - *
GitLab Endpoint: GET /groups/:id/members/all
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param itemsPerPage the number of Member instances that will be fetched per page - * @return a Pager of group members viewable by the authenticated user, including inherited members - * through ancestor groups - * @throws GitLabApiException if any exception occurs - */ - public Pager getAllMembers(Object groupIdOrPath, int itemsPerPage) throws GitLabApiException { - return (getAllMembers(groupIdOrPath, null, null, itemsPerPage)); - } - - /** - * Gets a Stream of group members viewable by the authenticated user, including inherited members - * through ancestor groups. Returns multiple times the same user (with different member attributes) - * when the user is a member of the group and of one or more ancestor group. - * - *
GitLab Endpoint: GET /groups/:id/members/all
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @return a Stream of group members viewable by the authenticated user, including inherited members - * through ancestor groups - * @throws GitLabApiException if any exception occurs - */ - public Stream getAllMembersStream(Object groupIdOrPath) throws GitLabApiException { - return (getAllMembersStream(groupIdOrPath, null, null)); - } - - - /** - * Gets a list of group members viewable by the authenticated user, including inherited members - * through ancestor groups. Returns multiple times the same user (with different member attributes) - * when the user is a member of the group and of one or more ancestor group. - * - *
GitLab Endpoint: GET /groups/:id/members/all
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param query a query string to search for members - * @param userIds filter the results on the given user IDs - * @return the group members viewable by the authenticated user, including inherited members through ancestor groups - * @throws GitLabApiException if any exception occurs - */ - public List getAllMembers(Object groupIdOrPath, String query, List userIds) throws GitLabApiException { - return (getAllMembers(groupIdOrPath, query, userIds, getDefaultPerPage()).all()); - } - - /** - * Gets a Pager of group members viewable by the authenticated user, including inherited members - * through ancestor groups. Returns multiple times the same user (with different member attributes) - * when the user is a member of the group and of one or more ancestor group. - * - *
GitLab Endpoint: GET /groups/:id/members/all
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param query a query string to search for members - * @param userIds filter the results on the given user IDs - * @param itemsPerPage the number of Project instances that will be fetched per page - * @return a Pager of the group members viewable by the authenticated user, - * including inherited members through ancestor groups - * @throws GitLabApiException if any exception occurs - */ - public Pager getAllMembers(Object groupIdOrPath, String query, List userIds, int itemsPerPage) throws GitLabApiException { - GitLabApiForm form = new GitLabApiForm().withParam("query", query).withParam("user_ids", userIds); - return (new Pager(this, Member.class, itemsPerPage, form.asMap(), - "groups", getGroupIdOrPath(groupIdOrPath), "members", "all")); - } - - /** - * Gets a Stream of group members viewable by the authenticated user, including inherited members - * through ancestor groups. Returns multiple times the same user (with different member attributes) - * when the user is a member of the group and of one or more ancestor group. - * - *
GitLab Endpoint: GET /groups/:id/members/all
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param query a query string to search for members - * @param userIds filter the results on the given user IDs - * @return a Stream of the group members viewable by the authenticated user, - * including inherited members through ancestor groups - * @throws GitLabApiException if any exception occurs - */ - public Stream getAllMembersStream(Object groupIdOrPath, String query, List userIds) throws GitLabApiException { - return (getAllMembers(groupIdOrPath, query, userIds, getDefaultPerPage()).stream()); - } - - /** - * Adds a user to the list of group members. - * - *
GitLab Endpoint: POST /groups/:id/members
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param userId the user ID of the member to add, required - * @param accessLevel the access level for the new member, required - * @return a Member instance for the added user - * @throws GitLabApiException if any exception occurs - */ - public Member addMember(Object groupIdOrPath, Long userId, Integer accessLevel) throws GitLabApiException { - return (addMember(groupIdOrPath, userId, accessLevel, null)); - } - - /** - * Adds a user to the list of group members. - * - *
GitLab Endpoint: POST /groups/:id/members
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param userId the user ID of the member to add, required - * @param accessLevel the access level for the new member, required - * @return a Member instance for the added user - * @throws GitLabApiException if any exception occurs - */ - public Member addMember(Object groupIdOrPath, Long userId, AccessLevel accessLevel) throws GitLabApiException { - return (addMember(groupIdOrPath, userId, accessLevel.toValue(), null)); - } - - /** - * Adds a user to the list of group members. - * - *
GitLab Endpoint: POST /groups/:id/members
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param userId the user ID of the member to add, required - * @param accessLevel the access level for the new member, required - * @param expiresAt the date the membership in the group will expire, optional - * @return a Member instance for the added user - * @throws GitLabApiException if any exception occurs - */ - public Member addMember(Object groupIdOrPath, Long userId, AccessLevel accessLevel, Date expiresAt) throws GitLabApiException { - return (addMember(groupIdOrPath, userId, accessLevel.toValue(), expiresAt)); - } - - /** - * Adds a user to the list of group members. - * - *
GitLab Endpoint: POST /groups/:id/members
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param userId the user ID of the member to add, required - * @param accessLevel the access level for the new member, required - * @param expiresAt the date the membership in the group will expire, optional - * @return a Member instance for the added user - * @throws GitLabApiException if any exception occurs - */ - public Member addMember(Object groupIdOrPath, Long userId, Integer accessLevel, Date expiresAt) throws GitLabApiException { - - GitLabApiForm formData = new GitLabApiForm() - .withParam("user_id", userId, true) - .withParam("access_level", accessLevel, true) - .withParam("expires_at", expiresAt, false); - Response response = post(Response.Status.CREATED, formData, "groups", getGroupIdOrPath(groupIdOrPath), "members"); - return (response.readEntity(Member.class)); - } - - /** - * Updates a member of a group. - * - *
GitLab Endpoint: PUT /groups/:groupId/members/:userId
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param userId the user ID of the member to update, required - * @param accessLevel the new access level for the member, required - * @return the updated member - * @throws GitLabApiException if any exception occurs - */ - public Member updateMember(Object groupIdOrPath, Long userId, Integer accessLevel) throws GitLabApiException { - return (updateMember(groupIdOrPath, userId, accessLevel, null)); - } - - /** - * Updates a member of a group. - * - *
GitLab Endpoint: PUT /groups/:groupId/members/:userId
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param userId the user ID of the member to update, required - * @param accessLevel the new access level for the member, required - * @return the updated member - * @throws GitLabApiException if any exception occurs - */ - public Member updateMember(Object groupIdOrPath, Long userId, AccessLevel accessLevel) throws GitLabApiException { - return (updateMember(groupIdOrPath, userId, accessLevel.toValue(), null)); - } - - /** - * Updates a member of a group. - * - *
GitLab Endpoint: PUT /groups/:groupId/members/:userId
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param userId the user ID of the member to update, required - * @param accessLevel the new access level for the member, required - * @param expiresAt the date the membership in the group will expire, optional - * @return the updated member - * @throws GitLabApiException if any exception occurs - */ - public Member updateMember(Object groupIdOrPath, Long userId, AccessLevel accessLevel, Date expiresAt) throws GitLabApiException { - return (updateMember(groupIdOrPath, userId, accessLevel.toValue(), expiresAt)); - } - - /** - * Updates a member of a group. - * - *
GitLab Endpoint: PUT /groups/:groupId/members/:userId
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param userId the user ID of the member to update, required - * @param accessLevel the new access level for the member, required - * @param expiresAt the date the membership in the group will expire, optional - * @return the updated member - * @throws GitLabApiException if any exception occurs - */ - public Member updateMember(Object groupIdOrPath, Long userId, Integer accessLevel, Date expiresAt) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() - .withParam("access_level", accessLevel, true) - .withParam("expires_at", expiresAt, false); - Response response = put(Response.Status.OK, formData.asMap(), "groups", getGroupIdOrPath(groupIdOrPath), "members", userId); - return (response.readEntity(Member.class)); - } - - /** - * Removes member from the group. - * - *
GitLab Endpoint: DELETE /groups/:id/members/:user_id
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param userId the user ID of the member to remove - * @throws GitLabApiException if any exception occurs - */ - public void removeMember(Object groupIdOrPath, Long userId) throws GitLabApiException { - Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT); - delete(expectedStatus, null, "groups", getGroupIdOrPath(groupIdOrPath), "members", userId); - } - - /** - * Syncs the group with its linked LDAP group. Only available to group owners and administrators. - * - *
GitLab Endpoint: POST /groups/:id/ldap_sync
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @throws GitLabApiException if any exception occurs - */ - public void ldapSync(Object groupIdOrPath) throws GitLabApiException { - post(Response.Status.NO_CONTENT, (Form)null, "groups", getGroupIdOrPath(groupIdOrPath), "ldap_sync"); - } - - /** - * Adds an LDAP group link. - * - *
GitLab Endpoint: POST /groups/:id/ldap_group_links
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param cn the CN of a LDAP group - * @param groupAccess the minimum access level for members of the LDAP group - * @param provider the LDAP provider for the LDAP group - * @throws GitLabApiException if any exception occurs - */ - public void addLdapGroupLink(Object groupIdOrPath, String cn, AccessLevel groupAccess, String provider) throws GitLabApiException { - - if (groupAccess == null) { - throw new RuntimeException("groupAccess cannot be null or empty"); - } - - addLdapGroupLink(groupIdOrPath, cn, groupAccess.toValue(), provider); - } - - /** - * Adds an LDAP group link. - * - *
GitLab Endpoint: POST /groups/:id/ldap_group_links
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param cn the CN of a LDAP group - * @param groupAccess the minimum access level for members of the LDAP group - * @param provider the LDAP provider for the LDAP group - * @throws GitLabApiException if any exception occurs - */ - public void addLdapGroupLink(Object groupIdOrPath, String cn, Integer groupAccess, String provider) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() - .withParam("cn", cn, true) - .withParam("group_access", groupAccess, true) - .withParam("provider", provider, true); - post(Response.Status.CREATED, formData, "groups", getGroupIdOrPath(groupIdOrPath), "ldap_group_links"); - } - - /** - * Deletes an LDAP group link. - * - *
GitLab Endpoint: DELETE /groups/:id/ldap_group_links/:cn
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param cn the CN of the LDAP group link to delete - * @throws GitLabApiException if any exception occurs - */ - public void deleteLdapGroupLink(Object groupIdOrPath, String cn) throws GitLabApiException { - - if (cn == null || cn.trim().isEmpty()) { - throw new RuntimeException("cn cannot be null or empty"); - } - - delete(Response.Status.OK, null, "groups", getGroupIdOrPath(groupIdOrPath), "ldap_group_links", cn); - } - - /** - * Deletes an LDAP group link for a specific LDAP provider. - * - *
GitLab Endpoint: DELETE /groups/:id/ldap_group_links/:provider/:cn
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param cn the CN of the LDAP group link to delete - * @param provider the name of the LDAP provider - * @throws GitLabApiException if any exception occurs - */ - public void deleteLdapGroupLink(Object groupIdOrPath, String cn, String provider) throws GitLabApiException { - - if (cn == null || cn.trim().isEmpty()) { - throw new RuntimeException("cn cannot be null or empty"); - } - - if (provider == null || provider.trim().isEmpty()) { - throw new RuntimeException("LDAP provider cannot be null or empty"); - } - - delete(Response.Status.OK, null, "groups", getGroupIdOrPath(groupIdOrPath), "ldap_group_links", provider, cn); - } - - /** - * Get list of a group’s variables. - * - *
GitLab Endpoint: GET /groups/:id/variables
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @return a list of variables belonging to the specified group - * @throws GitLabApiException if any exception occurs - */ - public List getVariables(Object groupIdOrPath) throws GitLabApiException { - return (getVariables(groupIdOrPath, getDefaultPerPage()).all()); - } - - /** - * Get a list of variables for the specified group in the specified page range. - * - *
GitLab Endpoint: GET /groups/:id/variables
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param page the page to get - * @param perPage the number of Variable instances per page - * @return a list of variables belonging to the specified group in the specified page range - * @throws GitLabApiException if any exception occurs - */ - public List getVariables(Object groupIdOrPath, int page, int perPage) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "groups", getGroupIdOrPath(groupIdOrPath), "variables"); - return (response.readEntity(new GenericType>() {})); - } - - /** - * Get a Pager of variables belonging to the specified group. - * - *
GitLab Endpoint: GET /groups/:id/variables
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param itemsPerPage the number of Variable instances that will be fetched per page - * @return a Pager of variables belonging to the specified group - * @throws GitLabApiException if any exception occurs - */ - public Pager getVariables(Object groupIdOrPath, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, Variable.class, itemsPerPage, null, "groups", getGroupIdOrPath(groupIdOrPath), "variables")); - } - - /** - * Get a Stream of variables belonging to the specified group. - * - *
GitLab Endpoint: GET /groups/:id/variables
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @return a Stream of variables belonging to the specified group - * @throws GitLabApiException if any exception occurs - */ - public Stream getVariablesStream(Object groupIdOrPath) throws GitLabApiException { - return (getVariables(groupIdOrPath, getDefaultPerPage()).stream()); - } - - /** - * Get the details of a group variable. - * - *
GitLab Endpoint: GET /groups/:id/variables/:key
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param key the key of an existing variable, required - * @return the Variable instance for the specified group variable - * @throws GitLabApiException if any exception occurs - */ - public Variable getVariable(Object groupIdOrPath, String key) throws GitLabApiException { - Response response = get(Response.Status.OK, null, "groups", getGroupIdOrPath(groupIdOrPath), "variables", key); - return (response.readEntity(Variable.class)); - } - - /** - * Get the details of a group variable as an Optional instance. - * - *
GitLab Endpoint: GET /groups/:id/variables/:key
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param key the key of an existing variable, required - * @return the Variable for the specified group variable as an Optional instance - */ - public Optional getOptionalVariable(Object groupIdOrPath, String key) { - try { - return (Optional.ofNullable(getVariable(groupIdOrPath, key))); - } catch (GitLabApiException glae) { - return (GitLabApi.createOptionalFromException(glae)); - } - } - - /** - * Create a new group variable. - * - *
GitLab Endpoint: POST /groups/:id/variables
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param key the key of a variable; must have no more than 255 characters; only A-Z, a-z, 0-9, and _ are allowed, required - * @param value the value for the variable, required - * @param isProtected whether the variable is protected, optional - * @return a Variable instance with the newly created variable - * @throws GitLabApiException if any exception occurs during execution - */ - public Variable createVariable(Object groupIdOrPath, String key, String value, Boolean isProtected) throws GitLabApiException { - - return createVariable(groupIdOrPath, key, value, isProtected, false); - } - - /** - * Create a new group variable. - * - *
GitLab Endpoint: POST /groups/:id/variables
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param key the key of a variable; must have no more than 255 characters; only A-Z, a-z, 0-9, and _ are allowed, required - * @param value the value for the variable, required - * @param isProtected whether the variable is protected, optional - * @param masked whether the variable is masked, optional - * @return a Variable instance with the newly created variable - * @throws GitLabApiException if any exception occurs during execution - */ - public Variable createVariable(Object groupIdOrPath, String key, String value, Boolean isProtected, Boolean masked) throws GitLabApiException { - - GitLabApiForm formData = new GitLabApiForm() - .withParam("key", key, true) - .withParam("value", value, true) - .withParam("masked", masked) - .withParam("protected", isProtected); - Response response = post(Response.Status.CREATED, formData, "groups", getGroupIdOrPath(groupIdOrPath), "variables"); - return (response.readEntity(Variable.class)); - } - - /** - * Update a group variable. - * - *
GitLab Endpoint: PUT /groups/:id/variables/:key
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param key the key of an existing variable, required - * @param value the value for the variable, required - * @param isProtected whether the variable is protected, optional - * @return a Variable instance with the updated variable - * @throws GitLabApiException if any exception occurs during execution - */ - public Variable updateVariable(Object groupIdOrPath, String key, String value, Boolean isProtected) throws GitLabApiException { - - return updateVariable(groupIdOrPath, key, value, isProtected, false); - } - - /** - * Update a group variable. - * - *
GitLab Endpoint: PUT /groups/:id/variables/:key
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param key the key of an existing variable, required - * @param value the value for the variable, required - * @param isProtected whether the variable is protected, optional - * @param masked whether the variable is masked, optional - * @return a Variable instance with the updated variable - * @throws GitLabApiException if any exception occurs during execution - */ - public Variable updateVariable(Object groupIdOrPath, String key, String value, Boolean isProtected, Boolean masked) throws GitLabApiException { - - GitLabApiForm formData = new GitLabApiForm() - .withParam("value", value, true) - .withParam("masked", masked) - .withParam("protected", isProtected); - Response response = putWithFormData(Response.Status.CREATED, formData, "groups", getGroupIdOrPath(groupIdOrPath), "variables", key); - return (response.readEntity(Variable.class)); - } - - /** - * Deletes a group variable. - * - *
GitLab Endpoint: DELETE /groups/:id/variables/:key
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param key the key of an existing variable, required - * @throws GitLabApiException if any exception occurs - */ - public void deleteVariable(Object groupIdOrPath, String key) throws GitLabApiException { - delete(Response.Status.NO_CONTENT, null, "groups", getGroupIdOrPath(groupIdOrPath), "variables", key); - } - - /** - * Transfer a project to the Group namespace. Available only for admin users. - * - *
GitLab Endpoint: POST /groups/:id/projects/:project_id
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance, required - * @return the transferred Project instance - * @throws GitLabApiException if any exception occurs during execution - */ - public Project transferProject(Object groupIdOrPath, Object projectIdOrPath) throws GitLabApiException { - Response response = post(Response.Status.CREATED, (Form)null, "groups", getGroupIdOrPath(groupIdOrPath), - "projects", getProjectIdOrPath(projectIdOrPath)); - return (response.readEntity(Project.class)); - } - - /** - * Get a List of the group audit events viewable by Maintainer or an Owner of the group. - * - *
GET /groups/:id/audit_events
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param created_after Group audit events created on or after the given time. - * @param created_before Group audit events created on or before the given time. - * @return a List of group Audit events - * @throws GitLabApiException if any exception occurs - */ - public List getAuditEvents(Object groupIdOrPath, Date created_after, Date created_before) throws GitLabApiException { - return (getAuditEvents(groupIdOrPath, created_after, created_before, getDefaultPerPage()).all()); - } - - /** - * Get a Pager of the group audit events viewable by Maintainer or an Owner of the group. - * - *
GET /groups/:id/audit_events
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param created_after Group audit events created on or after the given time. - * @param created_before Group audit events created on or before the given time. - * @param itemsPerPage the number of Audit Event instances that will be fetched per page - * @return a Pager of group Audit events - * @throws GitLabApiException if any exception occurs - */ - public Pager getAuditEvents(Object groupIdOrPath, Date created_after, Date created_before, int itemsPerPage) throws GitLabApiException { - Form form = new GitLabApiForm() - .withParam("created_before", ISO8601.toString(created_after, false)) - .withParam("created_after", ISO8601.toString(created_before, false)); - return (new Pager(this, AuditEvent.class, itemsPerPage, form.asMap(), - "groups", getGroupIdOrPath(groupIdOrPath), "audit_events")); - } - - /** - * Get a Stream of the group audit events viewable by Maintainer or an Owner of the group. - * - *
GET /groups/:id/audit_events
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param created_after Group audit events created on or after the given time. - * @param created_before Group audit events created on or before the given time. - * @return a Stream of group Audit events - * @throws GitLabApiException if any exception occurs - */ - public Stream getAuditEventsStream(Object groupIdOrPath, Date created_after, Date created_before) throws GitLabApiException { - return (getAuditEvents(groupIdOrPath, created_after, created_before, getDefaultPerPage()).stream()); - } - - /** - * Get a specific audit event of a group. - * - *
GitLab Endpoint: GET /groups/:id/audit_events/:id_audit_event
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param auditEventId the auditEventId, required - * @return the group Audit event - * @throws GitLabApiException if any exception occurs - */ - public AuditEvent getAuditEvent(Object groupIdOrPath, Long auditEventId) throws GitLabApiException { - Response response = get(Response.Status.OK, null, "groups", getGroupIdOrPath(groupIdOrPath), "audit_events", auditEventId); - return (response.readEntity(AuditEvent.class)); - } - - /** - * Get a List of the group access requests viewable by the authenticated user. - * - *
GET /group/:id/access_requests
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @return a List of project AccessRequest instances accessible by the authenticated user - * @throws GitLabApiException if any exception occurs - */ - public List getAccessRequests(Object groupIdOrPath) throws GitLabApiException { - return (getAccessRequests(groupIdOrPath, getDefaultPerPage()).all()); - } - - /** - * Get a Pager of the group access requests viewable by the authenticated user. - * - *
GET /groups/:id/access_requests
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param itemsPerPage the number of AccessRequest instances that will be fetched per page - * @return a Pager of group AccessRequest instances accessible by the authenticated user - * @throws GitLabApiException if any exception occurs - */ - public Pager getAccessRequests(Object groupIdOrPath, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, AccessRequest.class, itemsPerPage, null, - "groups", getGroupIdOrPath(groupIdOrPath), "access_requests")); - } - - /** - * Get a Stream of the group access requests viewable by the authenticated user. - * - *
GET /groups/:id/access_requests
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @return a Stream of group AccessRequest instances accessible by the authenticated user - * @throws GitLabApiException if any exception occurs - */ - public Stream getAccessRequestsStream(Object groupIdOrPath) throws GitLabApiException { - return (getAccessRequests(groupIdOrPath, getDefaultPerPage()).stream()); - } - - /** - * Requests access for the authenticated user to the specified group. - * - *
POST /groups/:id/access_requests
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @return the created AccessRequest instance - * @throws GitLabApiException if any exception occurs - */ - public AccessRequest requestAccess(Object groupIdOrPath) throws GitLabApiException { - Response response = post(Response.Status.CREATED, (Form)null, "groups", getGroupIdOrPath(groupIdOrPath), "access_requests"); - return (response.readEntity(AccessRequest.class)); - } - - /** - * Approve access for the specified user to the specified group. - * - *
PUT /groups/:id/access_requests/:user_id/approve
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param userId the user ID to approve access for - * @param accessLevel the access level the user is approved for, if null will be developer (30) - * @return the approved AccessRequest instance - * @throws GitLabApiException if any exception occurs - */ - public AccessRequest approveAccessRequest(Object groupIdOrPath, Long userId, AccessLevel accessLevel) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm().withParam("access_level", accessLevel); - Response response = this.putWithFormData(Response.Status.CREATED, formData, - "groups", getGroupIdOrPath(groupIdOrPath), "access_requests", userId, "approve"); - return (response.readEntity(AccessRequest.class)); - } - - /** - * Deny access for the specified user to the specified group. - * - *
DELETE /groups/:id/access_requests/:user_id
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param userId the user ID to deny access for - * @throws GitLabApiException if any exception occurs - */ - public void denyAccessRequest(Object groupIdOrPath, Long userId) throws GitLabApiException { - delete(Response.Status.NO_CONTENT, null, - "groups", getGroupIdOrPath(groupIdOrPath), "access_requests", userId); - } - - /** - * Gets a list of a group’s badges and its group badges. - * - *
GitLab Endpoint: GET /groups/:id/badges
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @return a List of Badge instances for the specified group - * @throws GitLabApiException if any exception occurs - */ - public List getBadges(Object groupIdOrPath) throws GitLabApiException { + public GroupApi(final GitLabApi gitLabApi) { + super(gitLabApi); + } + + /** + * Get a list of groups. (As user: my groups, as admin: all groups) WARNING: Do + * not use this method to fetch groups from https://gitlab.com, gitlab.com has many 1,000's of + * public groups and it will a long time to fetch all of them. Instead use {@link #getGroups(int + * itemsPerPage)} which will return a Pager of Group instances. + * + *
GitLab Endpoint: GET /groups
+ * + * @return the list of groups viewable by the authenticated user + * @throws GitLabApiException if any exception occurs + */ + public List getGroups() throws GitLabApiException { + + final String url = this.gitLabApi.getGitLabServerUrl(); + if (url.startsWith("https://gitlab.com")) { + GitLabApi.getLogger() + .warning( + "Fetching all groups from " + + url + + " may take many minutes to complete, use Pager getGroups(int) instead."); + } + + return (getGroups(getDefaultPerPage()).all()); + } + + /** + * Get a list of groups (As user: my groups, as admin: all groups) and in the specified page + * range. + * + *
GitLab Endpoint: GET /groups
+ * + * @param page the page to get + * @param perPage the number of Group instances per page + * @return the list of groups viewable by the authenticated userin the specified page range + * @throws GitLabApiException if any exception occurs + */ + public List getGroups(final int page, final int perPage) throws GitLabApiException { + final Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "groups"); + return (response.readEntity(new GenericType>() {})); + } + + /** + * Get a Pager of groups. (As user: my groups, as admin: all groups) + * + *
GitLab Endpoint: GET /groups
+ * + * @param itemsPerPage the number of Group instances that will be fetched per page + * @return the list of groups viewable by the authenticated user + * @throws GitLabApiException if any exception occurs + */ + public Pager getGroups(final int itemsPerPage) throws GitLabApiException { + return (new Pager(this, Group.class, itemsPerPage, null, "groups")); + } + + /** + * Get a Stream of groups. (As user: my groups, as admin: all groups) + * + *
GitLab Endpoint: GET /groups
+ * + * @return a Stream of groups viewable by the authenticated user + * @throws GitLabApiException if any exception occurs + */ + public Stream getGroupsStream() throws GitLabApiException { + return (getGroups(getDefaultPerPage()).stream()); + } + + /** + * Get all groups that match your string in their name or path. + * + * @param search the group name or path search criteria + * @return a List containing matching Group instances + * @throws GitLabApiException if any exception occurs + */ + public List getGroups(final String search) throws GitLabApiException { + return (getGroups(search, getDefaultPerPage()).all()); + } + + /** + * Get all groups that match your string in their name or path. + * + * @param search the group name or path search criteria + * @param page the page to get + * @param perPage the number of Group instances per page + * @return a List containing matching Group instances + * @throws GitLabApiException if any exception occurs + */ + public List getGroups(final String search, final int page, final int perPage) + throws GitLabApiException { + final Form formData = + new GitLabApiForm() + .withParam("search", search) + .withParam(PAGE_PARAM, page) + .withParam(PER_PAGE_PARAM, perPage); + final Response response = get(Response.Status.OK, formData.asMap(), "groups"); + return (response.readEntity(new GenericType>() {})); + } + + /** + * Get all groups that match your string in their name or path. + * + * @param search the group name or path search criteria + * @param itemsPerPage the number of Group instances that will be fetched per page + * @return a Pager containing matching Group instances + * @throws GitLabApiException if any exception occurs + */ + public Pager getGroups(final String search, final int itemsPerPage) + throws GitLabApiException { + final Form formData = new GitLabApiForm().withParam("search", search); + return (new Pager(this, Group.class, itemsPerPage, formData.asMap(), "groups")); + } + + /** + * Get all groups that match your string in their name or path as a Stream. + * + * @param search the group name or path search criteria + * @return a Stream containing matching Group instances + * @throws GitLabApiException if any exception occurs + */ + public Stream getGroupsStream(final String search) throws GitLabApiException { + return (getGroups(search, getDefaultPerPage()).stream()); + } + + /** + * Get a list of visible groups for the authenticated user using the provided filter. + * + *
GitLab Endpoint: GET /groups
+ * + * @param filter the GroupFilter to match against + * @return a List<Group> of the matching groups + * @throws GitLabApiException if any exception occurs + */ + public List getGroups(final GroupFilter filter) throws GitLabApiException { + return (getGroups(filter, getDefaultPerPage()).all()); + } + + /** + * Get a Pager of visible groups for the authenticated user using the provided filter. + * + *
GitLab Endpoint: GET /groups
+ * + * @param filter the GroupFilter to match against + * @param itemsPerPage the number of Group instances that will be fetched per page + * @return a Pager containing matching Group instances + * @throws GitLabApiException if any exception occurs + */ + public Pager getGroups(final GroupFilter filter, final int itemsPerPage) + throws GitLabApiException { + final GitLabApiForm formData = filter.getQueryParams(); + return (new Pager(this, Group.class, itemsPerPage, formData.asMap(), "groups")); + } + + /** + * Get a Stream of visible groups for the authenticated user using the provided filter. + * + *
GitLab Endpoint: GET /groups
+ * + * @param filter the GroupFilter to match against + * @return a Stream<Group> of the matching groups + * @throws GitLabApiException if any exception occurs + */ + public Stream getGroupsStream(final GroupFilter filter) throws GitLabApiException { + return (getGroups(filter, getDefaultPerPage()).stream()); + } + + /** + * Get a list of visible direct subgroups in this group. + * + *
GitLab Endpoint: GET /groups/:id/subgroups
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @return a List<Group> containing the group's sub-groups + * @throws GitLabApiException if any exception occurs + * @since GitLab 10.3.0 + */ + public List getSubGroups(final Object groupIdOrPath) throws GitLabApiException { + return (getSubGroups(groupIdOrPath, getDefaultPerPage()).all()); + } + + /** + * Get a Pager of visible direct subgroups in this group. + * + *
GitLab Endpoint: GET /groups/:id/subgroups
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param itemsPerPage the number of Group instances that will be fetched per page + * @return a Pager containing matching Group instances + * @throws GitLabApiException if any exception occurs + * @since GitLab 10.3.0 + */ + public Pager getSubGroups(final Object groupIdOrPath, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, + Group.class, + itemsPerPage, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "subgroups")); + } + + /** + * Get a Stream of visible direct subgroups in this group. + * + *
GitLab Endpoint: GET /groups/:id/subgroups
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @return a Stream<Group> containing the group's sub-groups + * @throws GitLabApiException if any exception occurs + * @since GitLab 10.3.0 + */ + public Stream getSubGroupsStream(final Object groupIdOrPath) throws GitLabApiException { + return (getSubGroups(groupIdOrPath, getDefaultPerPage()).stream()); + } + + /** + * Get a list of visible direct subgroups in this group. + * + *
GitLab Endpoint: GET /groups/:id/subgroups
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param skipGroups skip the group IDs passed + * @param allAvailable show all the groups you have access to (defaults to false for authenticated + * users) + * @param search return the list of authorized groups matching the search criteria + * @param orderBy order groups by NAME or PATH. Default is NAME + * @param sortOrder order groups in ASC or DESC order. Default is ASC + * @param statistics include group statistics (admins only) + * @param owned limit to groups owned by the current user + * @return a List<Group> of the matching subgroups + * @throws GitLabApiException if any exception occurs + * @since GitLab 10.3.0 + */ + public List getSubGroups( + final Object groupIdOrPath, + final List skipGroups, + final Boolean allAvailable, + final String search, + final GroupOrderBy orderBy, + final SortOrder sortOrder, + final Boolean statistics, + final Boolean owned) + throws GitLabApiException { + return (getSubGroups( + groupIdOrPath, + skipGroups, + allAvailable, + search, + orderBy, + sortOrder, + statistics, + owned, + getDefaultPerPage()) + .all()); + } + + /** + * Get a list of visible direct subgroups in this group. + * + *
GitLab Endpoint: GET /groups/:id/subgroups
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param skipGroups skip the group IDs passed + * @param allAvailable show all the groups you have access to (defaults to false for authenticated + * users) + * @param search return the list of authorized groups matching the search criteria + * @param orderBy order groups by NAME or PATH. Default is NAME + * @param sortOrder order groups in ASC or DESC order. Default is ASC + * @param statistics include group statistics (admins only) + * @param owned limit to groups owned by the current user + * @param page the page to get + * @param perPage the number of Group instances per page + * @return a List<Group> of the matching subgroups + * @throws GitLabApiException if any exception occurs + * @since GitLab 10.3.0 + */ + public List getSubGroups( + final Object groupIdOrPath, + final List skipGroups, + final Boolean allAvailable, + final String search, + final GroupOrderBy orderBy, + final SortOrder sortOrder, + final Boolean statistics, + final Boolean owned, + final int page, + final int perPage) + throws GitLabApiException { + final Form formData = + new GitLabApiForm() + .withParam("skip_groups", skipGroups) + .withParam("all_available", allAvailable) + .withParam("search", search) + .withParam("order_by", orderBy) + .withParam("sort_order", sortOrder) + .withParam("statistics", statistics) + .withParam("owned", owned) + .withParam(PAGE_PARAM, page) + .withParam(PER_PAGE_PARAM, perPage); + final Response response = + get( + Response.Status.OK, + formData.asMap(), + "groups", + getGroupIdOrPath(groupIdOrPath), + "subgroups"); + return (response.readEntity(new GenericType>() {})); + } + + /** + * Get a Pager of visible direct subgroups in this group. + * + *
GitLab Endpoint: GET /groups/:id/subgroups
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param skipGroups skip the group IDs passed + * @param allAvailable show all the groups you have access to (defaults to false for authenticated + * users) + * @param search return the list of authorized groups matching the search criteria + * @param orderBy order groups by NAME or PATH. Default is NAME + * @param sortOrder order groups in ASC or DESC order. Default is ASC + * @param statistics include group statistics (admins only) + * @param owned limit to groups owned by the current user + * @param itemsPerPage the number of Group instances that will be fetched per page + * @return a Pager containing matching Group instances + * @throws GitLabApiException if any exception occurs + * @since GitLab 10.3.0 + */ + public Pager getSubGroups( + final Object groupIdOrPath, + final List skipGroups, + final Boolean allAvailable, + final String search, + final GroupOrderBy orderBy, + final SortOrder sortOrder, + final Boolean statistics, + final Boolean owned, + final int itemsPerPage) + throws GitLabApiException { + final Form formData = + new GitLabApiForm() + .withParam("skip_groups", skipGroups) + .withParam("all_available", allAvailable) + .withParam("search", search) + .withParam("order_by", orderBy) + .withParam("sort_order", sortOrder) + .withParam("statistics", statistics) + .withParam("owned", owned); + return (new Pager( + this, + Group.class, + itemsPerPage, + formData.asMap(), + "groups", + getGroupIdOrPath(groupIdOrPath), + "subgroups")); + } + + /** + * Get a Stream of visible direct subgroups in this group. + * + *
GitLab Endpoint: GET /groups/:id/subgroups
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param skipGroups skip the group IDs passed + * @param allAvailable show all the groups you have access to (defaults to false for authenticated + * users) + * @param search return the list of authorized groups matching the search criteria + * @param orderBy order groups by NAME or PATH. Default is NAME + * @param sortOrder order groups in ASC or DESC order. Default is ASC + * @param statistics include group statistics (admins only) + * @param owned limit to groups owned by the current user + * @return a Stream<Group> of the matching subgroups + * @throws GitLabApiException if any exception occurs + * @since GitLab 10.3.0 + */ + public Stream getSubGroupsStream( + final Object groupIdOrPath, + final List skipGroups, + final Boolean allAvailable, + final String search, + final GroupOrderBy orderBy, + final SortOrder sortOrder, + final Boolean statistics, + final Boolean owned) + throws GitLabApiException { + return (getSubGroups( + groupIdOrPath, + skipGroups, + allAvailable, + search, + orderBy, + sortOrder, + statistics, + owned, + getDefaultPerPage()) + .stream()); + } + + /** + * Get a list of visible descendant groups of a given group for the authenticated user using the + * provided filter. + * + *
GitLab Endpoint: GET /groups/:id/descendant_groups
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param filter the GroupFilter to match against + * @return a List<Group> of the matching groups + * @throws GitLabApiException if any exception occurs + */ + public List getDescendantGroups(final Object groupIdOrPath, final GroupFilter filter) + throws GitLabApiException { + return (getDescendantGroups(groupIdOrPath, filter, getDefaultPerPage()).all()); + } + + /** + * Get a Pager of visible descendant groups of a given group for the authenticated user using the + * provided filter. + * + *
GitLab Endpoint: GET /groups/:id/descendant_groups
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param filter the GroupFilter to match against + * @param itemsPerPage the number of Group instances that will be fetched per page + * @return a Pager containing matching Group instances + * @throws GitLabApiException if any exception occurs + */ + public Pager getDescendantGroups( + final Object groupIdOrPath, final GroupFilter filter, final int itemsPerPage) + throws GitLabApiException { + final GitLabApiForm formData = filter.getQueryParams(); + return (new Pager( + this, + Group.class, + itemsPerPage, + formData.asMap(), + "groups", + getGroupIdOrPath(groupIdOrPath), + "descendant_groups")); + } + + /** + * Get a Stream of visible descendant groups of a given group for the authenticated user using the + * provided filter. + * + *
GitLab Endpoint: GET /groups/:id/descendant_groups
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param filter the GroupFilter to match against + * @return a Stream<Group> of the matching groups + * @throws GitLabApiException if any exception occurs + */ + public Stream getDescendantGroupsStream( + final Object groupIdOrPath, final GroupFilter filter) throws GitLabApiException { + return (getDescendantGroups(groupIdOrPath, filter, getDefaultPerPage()).stream()); + } + + /** + * Get a list of projects belonging to the specified group ID and filter. + * + *
GitLab Endpoint: GET /groups/:id/projects
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param filter the GroupProjectsFilter instance holding the filter values for the query + * @return a List containing Project instances that belong to the group and match the provided + * filter + * @throws GitLabApiException if any exception occurs + */ + public List getProjects(final Object groupIdOrPath, final GroupProjectsFilter filter) + throws GitLabApiException { + return (getProjects(groupIdOrPath, filter, getDefaultPerPage()).all()); + } + + /** + * Get a Pager of projects belonging to the specified group ID and filter. + * + *
GitLab Endpoint: GET /groups/:id/projects
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param filter the GroupProjectsFilter instance holding the filter values for the query + * @param itemsPerPage the number of Project instances that will be fetched per page + * @return a Pager containing Project instances that belong to the group and match the provided + * filter + * @throws GitLabApiException if any exception occurs + */ + public Pager getProjects( + final Object groupIdOrPath, final GroupProjectsFilter filter, final int itemsPerPage) + throws GitLabApiException { + final GitLabApiForm formData = filter.getQueryParams(); + return (new Pager( + this, + Project.class, + itemsPerPage, + formData.asMap(), + "groups", + getGroupIdOrPath(groupIdOrPath), + "projects")); + } + + /** + * Get a Stream of projects belonging to the specified group ID and filter. + * + *
GitLab Endpoint: GET /groups/:id/projects
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param filter the GroupProjectsFilter instance holding the filter values for the query + * @return a Stream containing Project instances that belong to the group and match the provided + * filter + * @throws GitLabApiException if any exception occurs + */ + public Stream getProjectsStream( + final Object groupIdOrPath, final GroupProjectsFilter filter) throws GitLabApiException { + return (getProjects(groupIdOrPath, filter, getDefaultPerPage()).stream()); + } + + /** + * Get a list of projects belonging to the specified group ID. + * + *
GitLab Endpoint: GET /groups/:id/projects
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @return a list of projects belonging to the specified group ID + * @throws GitLabApiException if any exception occurs + */ + public List getProjects(final Object groupIdOrPath) throws GitLabApiException { + return (getProjects(groupIdOrPath, getDefaultPerPage()).all()); + } + + /** + * Get a list of projects belonging to the specified group ID in the specified page range. + * + *
GitLab Endpoint: GET /groups/:id/projects
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param page the page to get + * @param perPage the number of Project instances per page + * @return a list of projects belonging to the specified group ID in the specified page range + * @throws GitLabApiException if any exception occurs + */ + public List getProjects(final Object groupIdOrPath, final int page, final int perPage) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getPageQueryParams(page, perPage), + "groups", + getGroupIdOrPath(groupIdOrPath), + "projects"); + return (response.readEntity(new GenericType>() {})); + } + + /** + * Get a Pager of projects belonging to the specified group ID. + * + *
GitLab Endpoint: GET /groups/:id/projects
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param itemsPerPage the number of Project instances that will be fetched per page + * @return a Pager of projects belonging to the specified group ID + * @throws GitLabApiException if any exception occurs + */ + public Pager getProjects(final Object groupIdOrPath, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, + Project.class, + itemsPerPage, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "projects")); + } + + /** + * Get a Stream of projects belonging to the specified group ID. + * + *
GitLab Endpoint: GET /groups/:id/projects
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @return a Stream of projects belonging to the specified group ID + * @throws GitLabApiException if any exception occurs + */ + public Stream getProjectsStream(final Object groupIdOrPath) throws GitLabApiException { + return (getProjects(groupIdOrPath, getDefaultPerPage()).stream()); + } + + /** + * Get all details of a group. + * + *
GitLab Endpoint: GET /groups/:id
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @return the Group instance for the specified group path + * @throws GitLabApiException if any exception occurs + */ + public Group getGroup(final Object groupIdOrPath) throws GitLabApiException { + final Response response = + get(Response.Status.OK, null, "groups", getGroupIdOrPath(groupIdOrPath)); + return (response.readEntity(Group.class)); + } + + /** + * Get all details of a group as an Optional instance. + * + *
GitLab Endpoint: GET /groups/:id
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @return the Group for the specified group path as an Optional instance + */ + public Optional getOptionalGroup(final Object groupIdOrPath) { + try { + return (Optional.ofNullable(getGroup(groupIdOrPath))); + } catch (final GitLabApiException glae) { + return (GitLabApi.createOptionalFromException(glae)); + } + } + + /** + * Creates a new project group. Available only for users who can create groups. + * + *
GitLab Endpoint: POST /groups
+ * + * @param params a GroupParams instance holding the parameters for the group creation + * @return the created Group instance + * @throws GitLabApiException if any exception occurs + */ + public Group createGroup(final GroupParams params) throws GitLabApiException { + final Response response = post(Response.Status.CREATED, params.getForm(true), "groups"); + return (response.readEntity(Group.class)); + } + + /** + * Updates the project group. Only available to group owners and administrators. + * + *
GitLab Endpoint: PUT /groups
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param params the GroupParams instance holding the properties to update + * @return updated Group instance + * @throws GitLabApiException at any exception + */ + public Group updateGroup(final Object groupIdOrPath, final GroupParams params) + throws GitLabApiException { + final Response response = + putWithFormData( + Response.Status.OK, params.getForm(false), "groups", getGroupIdOrPath(groupIdOrPath)); + return (response.readEntity(Group.class)); + } + + /** + * Creates a new project group. Available only for users who can create groups. + * + *
GitLab Endpoint: POST /groups
+ * + * @param name the name of the group to add + * @param path the path for the group + * @return the created Group instance + * @throws GitLabApiException if any exception occurs + */ + public Group addGroup(final String name, final String path) throws GitLabApiException { + + final Form formData = new Form(); + formData.param("name", name); + formData.param("path", path); + final Response response = post(Response.Status.CREATED, formData, "groups"); + return (response.readEntity(Group.class)); + } + + public Group addGroup(final Group group) throws GitLabApiException { + final Form formData = + new GitLabApiForm() + .withParam("name", group.getName(), true) + .withParam("path", group.getPath(), true) + .withParam("description", group.getDescription()) + .withParam("visibility", group.getVisibility()) + .withParam("lfs_enabled", group.getLfsEnabled()) + .withParam("request_access_enabled", group.getRequestAccessEnabled()) + .withParam("parent_id", isApiVersion(ApiVersion.V3) ? null : group.getParentId()); + final Response response = post(Response.Status.CREATED, formData, "groups"); + return (response.readEntity(Group.class)); + } + + /** + * Creates a new project group. Available only for users who can create groups. + * + *
GitLab Endpoint: POST /groups
+ * + * @param name the name of the group to add + * @param path the path for the group + * @param description (optional) - The group's description + * @param visibility (optional) - The group's visibility. Can be private, internal, or public. + * @param lfsEnabled (optional) - Enable/disable Large File Storage (LFS) for the projects in this + * group + * @param requestAccessEnabled (optional) - Allow users to request member access + * @param parentId (optional) - The parent group id for creating nested group + * @return the created Group instance + * @throws GitLabApiException if any exception occurs + */ + public Group addGroup( + final String name, + final String path, + final String description, + final Visibility visibility, + final Boolean lfsEnabled, + final Boolean requestAccessEnabled, + final Long parentId) + throws GitLabApiException { + + final Form formData = + new GitLabApiForm() + .withParam("name", name, true) + .withParam("path", path, true) + .withParam("description", description) + .withParam("visibility", visibility) + .withParam("lfs_enabled", lfsEnabled) + .withParam("request_access_enabled", requestAccessEnabled) + .withParam("parent_id", isApiVersion(ApiVersion.V3) ? null : parentId); + final Response response = post(Response.Status.CREATED, formData, "groups"); + return (response.readEntity(Group.class)); + } + + /** + * Updates a project group. Available only for users who can create groups. + * + *
GitLab Endpoint: PUT /groups
+ * + * @param group to update + * @return updated group instance + * @throws GitLabApiException at any exception + */ + public Group updateGroup(final Group group) throws GitLabApiException { + final Form formData = + new GitLabApiForm() + .withParam("name", group.getName()) + .withParam("path", group.getPath()) + .withParam("description", group.getDescription()) + .withParam("visibility", group.getVisibility()) + .withParam("lfs_enabled", group.getLfsEnabled()) + .withParam("request_access_enabled", group.getRequestAccessEnabled()) + .withParam("parent_id", isApiVersion(ApiVersion.V3) ? null : group.getParentId()); + final Response response = put(Response.Status.OK, formData.asMap(), "groups", group.getId()); + return (response.readEntity(Group.class)); + } + + /** + * Updates a project group. Available only for users who can create groups. + * + *
GitLab Endpoint: PUT /groups
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param name the name of the group to add + * @param path the path for the group + * @param description (optional) - The group's description + * @param visibility (optional) - The group's visibility. Can be private, internal, or public. + * @param lfsEnabled (optional) - Enable/disable Large File Storage (LFS) for the projects in this + * group + * @param requestAccessEnabled (optional) - Allow users to request member access + * @param parentId (optional) - The parent group id for creating nested group + * @return the updated Group instance + * @throws GitLabApiException if any exception occurs + */ + public Group updateGroup( + final Object groupIdOrPath, + final String name, + final String path, + final String description, + final Visibility visibility, + final Boolean lfsEnabled, + final Boolean requestAccessEnabled, + final Long parentId) + throws GitLabApiException { + + final Form formData = + new GitLabApiForm() + .withParam("name", name) + .withParam("path", path) + .withParam("description", description) + .withParam("visibility", visibility) + .withParam("lfs_enabled", lfsEnabled) + .withParam("request_access_enabled", requestAccessEnabled) + .withParam("parent_id", isApiVersion(ApiVersion.V3) ? null : parentId); + final Response response = + put(Response.Status.OK, formData.asMap(), "groups", getGroupIdOrPath(groupIdOrPath)); + return (response.readEntity(Group.class)); + } + + /** + * Creates a new project group. Available only for users who can create groups. + * + *
GitLab Endpoint: POST /groups
+ * + * @param name the name of the group to add + * @param path the path for the group + * @param description (optional) - The group's description + * @param membershipLock (optional, boolean) - Prevent adding new members to project membership + * within this group + * @param shareWithGroupLock (optional, boolean) - Prevent sharing a project with another group + * within this group + * @param visibility (optional) - The group's visibility. Can be private, internal, or public. + * @param lfsEnabled (optional) - Enable/disable Large File Storage (LFS) for the projects in this + * group + * @param requestAccessEnabled (optional) - Allow users to request member access. + * @param parentId (optional) - The parent group id for creating nested group. + * @param sharedRunnersMinutesLimit (optional) - (admin-only) Pipeline minutes quota for this + * group + * @return the created Group instance + * @throws GitLabApiException if any exception occurs + * @deprecated Will be removed in version 6.0, replaced by {@link #addGroup(String, String, + * String, Visibility, Boolean, Boolean, Long)} + */ + @Deprecated + public Group addGroup( + final String name, + final String path, + final String description, + final Boolean membershipLock, + final Boolean shareWithGroupLock, + final Visibility visibility, + final Boolean lfsEnabled, + final Boolean requestAccessEnabled, + final Long parentId, + final Integer sharedRunnersMinutesLimit) + throws GitLabApiException { + + final Form formData = + new GitLabApiForm() + .withParam("name", name) + .withParam("path", path) + .withParam("description", description) + .withParam("membership_lock", membershipLock) + .withParam("share_with_group_lock", shareWithGroupLock) + .withParam("visibility", visibility) + .withParam("lfs_enabled", lfsEnabled) + .withParam("request_access_enabled", requestAccessEnabled) + .withParam("parent_id", parentId) + .withParam("shared_runners_minutes_limit", sharedRunnersMinutesLimit); + final Response response = post(Response.Status.CREATED, formData, "groups"); + return (response.readEntity(Group.class)); + } + + /** + * Updates a project group. Available only for users who can create groups. + * + *
GitLab Endpoint: PUT /groups
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param name the name of the group to add + * @param path the path for the group + * @param description (optional) - The group's description + * @param membershipLock (optional, boolean) - Prevent adding new members to project membership + * within this group + * @param shareWithGroupLock (optional, boolean) - Prevent sharing a project with another group + * within this group + * @param visibility (optional) - The group's visibility. Can be private, internal, or public. + * @param lfsEnabled (optional) - Enable/disable Large File Storage (LFS) for the projects in this + * group + * @param requestAccessEnabled (optional) - Allow users to request member access + * @param parentId (optional) - The parent group id for creating nested group + * @param sharedRunnersMinutesLimit (optional) - (admin-only) Pipeline minutes quota for this + * group + * @return the updated Group instance + * @throws GitLabApiException if any exception occurs + * @deprecated Will be removed in version 6.0, replaced by {@link #updateGroup(Object, String, + * String, String, Visibility, Boolean, Boolean, Long)} + */ + @Deprecated + public Group updateGroup( + final Object groupIdOrPath, + final String name, + final String path, + final String description, + final Boolean membershipLock, + final Boolean shareWithGroupLock, + final Visibility visibility, + final Boolean lfsEnabled, + final Boolean requestAccessEnabled, + final Long parentId, + final Integer sharedRunnersMinutesLimit) + throws GitLabApiException { + + final Form formData = + new GitLabApiForm() + .withParam("name", name) + .withParam("path", path) + .withParam("description", description) + .withParam("membership_lock", membershipLock) + .withParam("share_with_group_lock", shareWithGroupLock) + .withParam("visibility", visibility) + .withParam("lfs_enabled", lfsEnabled) + .withParam("request_access_enabled", requestAccessEnabled) + .withParam("parent_id", parentId) + .withParam("shared_runners_minutes_limit", sharedRunnersMinutesLimit); + final Response response = + put(Response.Status.OK, formData.asMap(), "groups", getGroupIdOrPath(groupIdOrPath)); + return (response.readEntity(Group.class)); + } + + /** + * Removes group with all projects inside. + * + *
GitLab Endpoint: DELETE /groups/:id
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @throws GitLabApiException if any exception occurs + */ + public void deleteGroup(final Object groupIdOrPath) throws GitLabApiException { + final Response.Status expectedStatus = + (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT); + delete(expectedStatus, null, "groups", getGroupIdOrPath(groupIdOrPath)); + } + + /** + * Get a list of group members viewable by the authenticated user. + * + *
GitLab Endpoint: GET /groups/:id/members
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @return a list of group members viewable by the authenticated user + * @throws GitLabApiException if any exception occurs + */ + public List getMembers(final Object groupIdOrPath) throws GitLabApiException { + return (getMembers(groupIdOrPath, getDefaultPerPage()).all()); + } + + /** + * Get a list of group members viewable by the authenticated user in the specified page range. + * + *
GitLab Endpoint: GET /groups/:id/members
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param page the page to get + * @param perPage the number of Member instances per page + * @return a list of group members viewable by the authenticated user in the specified page range + * @throws GitLabApiException if any exception occurs + */ + public List getMembers(final Object groupIdOrPath, final int page, final int perPage) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getPageQueryParams(page, perPage), + "groups", + getGroupIdOrPath(groupIdOrPath), + "members"); + return (response.readEntity(new GenericType>() {})); + } + + /** + * Get a Pager of group members viewable by the authenticated user. + * + *
GitLab Endpoint: GET /groups/:id/members
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param itemsPerPage the number of Member instances that will be fetched per page + * @return a list of group members viewable by the authenticated user + * @throws GitLabApiException if any exception occurs + */ + public Pager getMembers(final Object groupIdOrPath, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, + Member.class, + itemsPerPage, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "members")); + } + + /** + * Get a Stream of group members viewable by the authenticated user. + * + *
GitLab Endpoint: GET /groups/:id/members
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @return a Stream of group members viewable by the authenticated user + * @throws GitLabApiException if any exception occurs + */ + public Stream getMembersStream(final Object groupIdOrPath) throws GitLabApiException { + return (getMembers(groupIdOrPath, getDefaultPerPage()).stream()); + } + + /** + * Get a group member viewable by the authenticated user. + * + *
GitLab Endpoint: GET /groups/:id/members/:id
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param userId the member ID of the member to get + * @return a member viewable by the authenticated user + * @throws GitLabApiException if any exception occurs + */ + public Member getMember(final Object groupIdOrPath, final long userId) throws GitLabApiException { + return (getMember(groupIdOrPath, userId, false)); + } + + /** + * Get a group member viewable by the authenticated user as an Optional instance. + * + *
GitLab Endpoint: GET /groups/:id/members/:id
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param userId the member ID of the member to get + * @return a member viewable by the authenticated user as an Optional instance + */ + public Optional getOptionalMember(final Object groupIdOrPath, final long userId) { + try { + return (Optional.ofNullable(getMember(groupIdOrPath, userId, false))); + } catch (final GitLabApiException glae) { + return (GitLabApi.createOptionalFromException(glae)); + } + } + + /** + * Gets a group team member, optionally including inherited member. + * + *
GitLab Endpoint: GET /groups/:id/members/all/:user_id
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param userId the user ID of the member + * @param includeInherited if true will the member even if inherited thru an ancestor group + * @return the member specified by the project ID/user ID pair + * @throws GitLabApiException if any exception occurs + */ + public Member getMember( + final Object groupIdOrPath, final Long userId, final Boolean includeInherited) + throws GitLabApiException { + final Response response; + if (includeInherited) { + response = + get( + Response.Status.OK, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "members", + "all", + userId); + } else { + response = + get( + Response.Status.OK, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "members", + userId); + } + return (response.readEntity(Member.class)); + } + + /** + * Gets a group team member, optionally including inherited member. + * + *
GitLab Endpoint: GET /groups/:id/members/all/:user_id
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param userId the user ID of the member + * @param includeInherited if true will the member even if inherited thru an ancestor group + * @return the member specified by the group ID/user ID pair as the value of an Optional + */ + public Optional getOptionalMember( + final Object groupIdOrPath, final Long userId, final Boolean includeInherited) { + try { + return (Optional.ofNullable(getMember(groupIdOrPath, userId, includeInherited))); + } catch (final GitLabApiException glae) { + return (GitLabApi.createOptionalFromException(glae)); + } + } + + /** + * Gets a list of group members viewable by the authenticated user, including inherited members + * through ancestor groups. Returns multiple times the same user (with different member + * attributes) when the user is a member of the group and of one or more ancestor group. + * + *
GitLab Endpoint: GET /groups/:id/members/all
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @return a list of group members viewable by the authenticated user, including inherited members + * through ancestor groups + * @throws GitLabApiException if any exception occurs + */ + public List getAllMembers(final Object groupIdOrPath) throws GitLabApiException { + return (getAllMembers(groupIdOrPath, null, null)); + } + + /** + * Gets a list of group members viewable by the authenticated user, including inherited members + * through ancestor groups. Returns multiple times the same user (with different member + * attributes) when the user is a member of the group and of one or more ancestor group. + * + *
GitLab Endpoint: GET /groups/:id/members/all
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param page the page to get + * @param perPage the number of Member instances per page + * @return a list of group members viewable by the authenticated user, including inherited members + * through ancestor groups in the specified page range + * @throws GitLabApiException if any exception occurs + * @deprecated Will be removed in version 6.0 + */ + @Deprecated + public List getAllMembers(final Object groupIdOrPath, final int page, final int perPage) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getPageQueryParams(page, perPage), + "groups", + getGroupIdOrPath(groupIdOrPath), + "members", + "all"); + return (response.readEntity(new GenericType>() {})); + } + + /** + * Gets a Pager of group members viewable by the authenticated user, including inherited members + * through ancestor groups. Returns multiple times the same user (with different member + * attributes) when the user is a member of the group and of one or more ancestor group. + * + *
GitLab Endpoint: GET /groups/:id/members/all
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param itemsPerPage the number of Member instances that will be fetched per page + * @return a Pager of group members viewable by the authenticated user, including inherited + * members through ancestor groups + * @throws GitLabApiException if any exception occurs + */ + public Pager getAllMembers(final Object groupIdOrPath, final int itemsPerPage) + throws GitLabApiException { + return (getAllMembers(groupIdOrPath, null, null, itemsPerPage)); + } + + /** + * Gets a Stream of group members viewable by the authenticated user, including inherited members + * through ancestor groups. Returns multiple times the same user (with different member + * attributes) when the user is a member of the group and of one or more ancestor group. + * + *
GitLab Endpoint: GET /groups/:id/members/all
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @return a Stream of group members viewable by the authenticated user, including inherited + * members through ancestor groups + * @throws GitLabApiException if any exception occurs + */ + public Stream getAllMembersStream(final Object groupIdOrPath) throws GitLabApiException { + return (getAllMembersStream(groupIdOrPath, null, null)); + } + + /** + * Gets a list of group members viewable by the authenticated user, including inherited members + * through ancestor groups. Returns multiple times the same user (with different member + * attributes) when the user is a member of the group and of one or more ancestor group. + * + *
GitLab Endpoint: GET /groups/:id/members/all
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param query a query string to search for members + * @param userIds filter the results on the given user IDs + * @return the group members viewable by the authenticated user, including inherited members + * through ancestor groups + * @throws GitLabApiException if any exception occurs + */ + public List getAllMembers( + final Object groupIdOrPath, final String query, final List userIds) + throws GitLabApiException { + return (getAllMembers(groupIdOrPath, query, userIds, getDefaultPerPage()).all()); + } + + /** + * Gets a Pager of group members viewable by the authenticated user, including inherited members + * through ancestor groups. Returns multiple times the same user (with different member + * attributes) when the user is a member of the group and of one or more ancestor group. + * + *
GitLab Endpoint: GET /groups/:id/members/all
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param query a query string to search for members + * @param userIds filter the results on the given user IDs + * @param itemsPerPage the number of Project instances that will be fetched per page + * @return a Pager of the group members viewable by the authenticated user, including inherited + * members through ancestor groups + * @throws GitLabApiException if any exception occurs + */ + public Pager getAllMembers( + final Object groupIdOrPath, + final String query, + final List userIds, + final int itemsPerPage) + throws GitLabApiException { + final GitLabApiForm form = + new GitLabApiForm().withParam("query", query).withParam("user_ids", userIds); + return (new Pager( + this, + Member.class, + itemsPerPage, + form.asMap(), + "groups", + getGroupIdOrPath(groupIdOrPath), + "members", + "all")); + } + + /** + * Gets a Stream of group members viewable by the authenticated user, including inherited members + * through ancestor groups. Returns multiple times the same user (with different member + * attributes) when the user is a member of the group and of one or more ancestor group. + * + *
GitLab Endpoint: GET /groups/:id/members/all
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param query a query string to search for members + * @param userIds filter the results on the given user IDs + * @return a Stream of the group members viewable by the authenticated user, including inherited + * members through ancestor groups + * @throws GitLabApiException if any exception occurs + */ + public Stream getAllMembersStream( + final Object groupIdOrPath, final String query, final List userIds) + throws GitLabApiException { + return (getAllMembers(groupIdOrPath, query, userIds, getDefaultPerPage()).stream()); + } + + /** + * Adds a user to the list of group members. + * + *
GitLab Endpoint: POST /groups/:id/members
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param userId the user ID of the member to add, required + * @param accessLevel the access level for the new member, required + * @return a Member instance for the added user + * @throws GitLabApiException if any exception occurs + */ + public Member addMember(final Object groupIdOrPath, final Long userId, final Integer accessLevel) + throws GitLabApiException { + return (addMember(groupIdOrPath, userId, accessLevel, null)); + } + + /** + * Adds a user to the list of group members. + * + *
GitLab Endpoint: POST /groups/:id/members
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param userId the user ID of the member to add, required + * @param accessLevel the access level for the new member, required + * @return a Member instance for the added user + * @throws GitLabApiException if any exception occurs + */ + public Member addMember( + final Object groupIdOrPath, final Long userId, final AccessLevel accessLevel) + throws GitLabApiException { + return (addMember(groupIdOrPath, userId, accessLevel.toValue(), null)); + } + + /** + * Adds a user to the list of group members. + * + *
GitLab Endpoint: POST /groups/:id/members
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param userId the user ID of the member to add, required + * @param accessLevel the access level for the new member, required + * @param expiresAt the date the membership in the group will expire, optional + * @return a Member instance for the added user + * @throws GitLabApiException if any exception occurs + */ + public Member addMember( + final Object groupIdOrPath, + final Long userId, + final AccessLevel accessLevel, + final Date expiresAt) + throws GitLabApiException { + return (addMember(groupIdOrPath, userId, accessLevel.toValue(), expiresAt)); + } + + /** + * Adds a user to the list of group members. + * + *
GitLab Endpoint: POST /groups/:id/members
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param userId the user ID of the member to add, required + * @param accessLevel the access level for the new member, required + * @param expiresAt the date the membership in the group will expire, optional + * @return a Member instance for the added user + * @throws GitLabApiException if any exception occurs + */ + public Member addMember( + final Object groupIdOrPath, + final Long userId, + final Integer accessLevel, + final Date expiresAt) + throws GitLabApiException { + + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("user_id", userId, true) + .withParam("access_level", accessLevel, true) + .withParam("expires_at", expiresAt, false); + final Response response = + post( + Response.Status.CREATED, + formData, + "groups", + getGroupIdOrPath(groupIdOrPath), + "members"); + return (response.readEntity(Member.class)); + } + + /** + * Updates a member of a group. + * + *
GitLab Endpoint: PUT /groups/:groupId/members/:userId
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param userId the user ID of the member to update, required + * @param accessLevel the new access level for the member, required + * @return the updated member + * @throws GitLabApiException if any exception occurs + */ + public Member updateMember( + final Object groupIdOrPath, final Long userId, final Integer accessLevel) + throws GitLabApiException { + return (updateMember(groupIdOrPath, userId, accessLevel, null)); + } + + /** + * Updates a member of a group. + * + *
GitLab Endpoint: PUT /groups/:groupId/members/:userId
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param userId the user ID of the member to update, required + * @param accessLevel the new access level for the member, required + * @return the updated member + * @throws GitLabApiException if any exception occurs + */ + public Member updateMember( + final Object groupIdOrPath, final Long userId, final AccessLevel accessLevel) + throws GitLabApiException { + return (updateMember(groupIdOrPath, userId, accessLevel.toValue(), null)); + } + + /** + * Updates a member of a group. + * + *
GitLab Endpoint: PUT /groups/:groupId/members/:userId
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param userId the user ID of the member to update, required + * @param accessLevel the new access level for the member, required + * @param expiresAt the date the membership in the group will expire, optional + * @return the updated member + * @throws GitLabApiException if any exception occurs + */ + public Member updateMember( + final Object groupIdOrPath, + final Long userId, + final AccessLevel accessLevel, + final Date expiresAt) + throws GitLabApiException { + return (updateMember(groupIdOrPath, userId, accessLevel.toValue(), expiresAt)); + } + + /** + * Updates a member of a group. + * + *
GitLab Endpoint: PUT /groups/:groupId/members/:userId
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param userId the user ID of the member to update, required + * @param accessLevel the new access level for the member, required + * @param expiresAt the date the membership in the group will expire, optional + * @return the updated member + * @throws GitLabApiException if any exception occurs + */ + public Member updateMember( + final Object groupIdOrPath, + final Long userId, + final Integer accessLevel, + final Date expiresAt) + throws GitLabApiException { + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("access_level", accessLevel, true) + .withParam("expires_at", expiresAt, false); + final Response response = + put( + Response.Status.OK, + formData.asMap(), + "groups", + getGroupIdOrPath(groupIdOrPath), + "members", + userId); + return (response.readEntity(Member.class)); + } + + /** + * Removes member from the group. + * + *
GitLab Endpoint: DELETE /groups/:id/members/:user_id
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param userId the user ID of the member to remove + * @throws GitLabApiException if any exception occurs + */ + public void removeMember(final Object groupIdOrPath, final Long userId) + throws GitLabApiException { + final Response.Status expectedStatus = + (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT); + delete(expectedStatus, null, "groups", getGroupIdOrPath(groupIdOrPath), "members", userId); + } + + /** + * Syncs the group with its linked LDAP group. Only available to group owners and administrators. + * + *
GitLab Endpoint: POST /groups/:id/ldap_sync
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @throws GitLabApiException if any exception occurs + */ + public void ldapSync(final Object groupIdOrPath) throws GitLabApiException { + post( + Response.Status.NO_CONTENT, + (Form) null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "ldap_sync"); + } + + /** + * Adds an LDAP group link. + * + *
GitLab Endpoint: POST /groups/:id/ldap_group_links
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param cn the CN of a LDAP group + * @param groupAccess the minimum access level for members of the LDAP group + * @param provider the LDAP provider for the LDAP group + * @throws GitLabApiException if any exception occurs + */ + public void addLdapGroupLink( + final Object groupIdOrPath, + final String cn, + final AccessLevel groupAccess, + final String provider) + throws GitLabApiException { + + if (groupAccess == null) { + throw new RuntimeException("groupAccess cannot be null or empty"); + } + + addLdapGroupLink(groupIdOrPath, cn, groupAccess.toValue(), provider); + } + + /** + * Adds an LDAP group link. + * + *
GitLab Endpoint: POST /groups/:id/ldap_group_links
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param cn the CN of a LDAP group + * @param groupAccess the minimum access level for members of the LDAP group + * @param provider the LDAP provider for the LDAP group + * @throws GitLabApiException if any exception occurs + */ + public void addLdapGroupLink( + final Object groupIdOrPath, final String cn, final Integer groupAccess, final String provider) + throws GitLabApiException { + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("cn", cn, true) + .withParam("group_access", groupAccess, true) + .withParam("provider", provider, true); + post( + Response.Status.CREATED, + formData, + "groups", + getGroupIdOrPath(groupIdOrPath), + "ldap_group_links"); + } + + /** + * Deletes an LDAP group link. + * + *
GitLab Endpoint: DELETE /groups/:id/ldap_group_links/:cn
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param cn the CN of the LDAP group link to delete + * @throws GitLabApiException if any exception occurs + */ + public void deleteLdapGroupLink(final Object groupIdOrPath, final String cn) + throws GitLabApiException { + + if (cn == null || cn.trim().isEmpty()) { + throw new RuntimeException("cn cannot be null or empty"); + } + + delete( + Response.Status.OK, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "ldap_group_links", + cn); + } + + /** + * Deletes an LDAP group link for a specific LDAP provider. + * + *
GitLab Endpoint: DELETE /groups/:id/ldap_group_links/:provider/:cn
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param cn the CN of the LDAP group link to delete + * @param provider the name of the LDAP provider + * @throws GitLabApiException if any exception occurs + */ + public void deleteLdapGroupLink( + final Object groupIdOrPath, final String cn, final String provider) + throws GitLabApiException { + + if (cn == null || cn.trim().isEmpty()) { + throw new RuntimeException("cn cannot be null or empty"); + } + + if (provider == null || provider.trim().isEmpty()) { + throw new RuntimeException("LDAP provider cannot be null or empty"); + } + + delete( + Response.Status.OK, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "ldap_group_links", + provider, + cn); + } + + /** + * Get list of a group’s variables. + * + *
GitLab Endpoint: GET /groups/:id/variables
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @return a list of variables belonging to the specified group + * @throws GitLabApiException if any exception occurs + */ + public List getVariables(final Object groupIdOrPath) throws GitLabApiException { + return (getVariables(groupIdOrPath, getDefaultPerPage()).all()); + } + + /** + * Get a list of variables for the specified group in the specified page range. + * + *
GitLab Endpoint: GET /groups/:id/variables
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param page the page to get + * @param perPage the number of Variable instances per page + * @return a list of variables belonging to the specified group in the specified page range + * @throws GitLabApiException if any exception occurs + */ + public List getVariables(final Object groupIdOrPath, final int page, final int perPage) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getPageQueryParams(page, perPage), + "groups", + getGroupIdOrPath(groupIdOrPath), + "variables"); + return (response.readEntity(new GenericType>() {})); + } + + /** + * Get a Pager of variables belonging to the specified group. + * + *
GitLab Endpoint: GET /groups/:id/variables
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param itemsPerPage the number of Variable instances that will be fetched per page + * @return a Pager of variables belonging to the specified group + * @throws GitLabApiException if any exception occurs + */ + public Pager getVariables(final Object groupIdOrPath, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, + Variable.class, + itemsPerPage, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "variables")); + } + + /** + * Get a Stream of variables belonging to the specified group. + * + *
GitLab Endpoint: GET /groups/:id/variables
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @return a Stream of variables belonging to the specified group + * @throws GitLabApiException if any exception occurs + */ + public Stream getVariablesStream(final Object groupIdOrPath) throws GitLabApiException { + return (getVariables(groupIdOrPath, getDefaultPerPage()).stream()); + } + + /** + * Get the details of a group variable. + * + *
GitLab Endpoint: GET /groups/:id/variables/:key
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param key the key of an existing variable, required + * @return the Variable instance for the specified group variable + * @throws GitLabApiException if any exception occurs + */ + public Variable getVariable(final Object groupIdOrPath, final String key) + throws GitLabApiException { + final Response response = + get(Response.Status.OK, null, "groups", getGroupIdOrPath(groupIdOrPath), "variables", key); + return (response.readEntity(Variable.class)); + } + + /** + * Get the details of a group variable as an Optional instance. + * + *
GitLab Endpoint: GET /groups/:id/variables/:key
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param key the key of an existing variable, required + * @return the Variable for the specified group variable as an Optional instance + */ + public Optional getOptionalVariable(final Object groupIdOrPath, final String key) { + try { + return (Optional.ofNullable(getVariable(groupIdOrPath, key))); + } catch (final GitLabApiException glae) { + return (GitLabApi.createOptionalFromException(glae)); + } + } + + /** + * Create a new group variable. + * + *
GitLab Endpoint: POST /groups/:id/variables
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param key the key of a variable; must have no more than 255 characters; only A-Z, a-z, 0-9, + * and _ are allowed, required + * @param value the value for the variable, required + * @param isProtected whether the variable is protected, optional + * @return a Variable instance with the newly created variable + * @throws GitLabApiException if any exception occurs during execution + */ + public Variable createVariable( + final Object groupIdOrPath, final String key, final String value, final Boolean isProtected) + throws GitLabApiException { + + return createVariable(groupIdOrPath, key, value, isProtected, false); + } + + /** + * Create a new group variable. + * + *
GitLab Endpoint: POST /groups/:id/variables
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param key the key of a variable; must have no more than 255 characters; only A-Z, a-z, 0-9, + * and _ are allowed, required + * @param value the value for the variable, required + * @param isProtected whether the variable is protected, optional + * @param masked whether the variable is masked, optional + * @return a Variable instance with the newly created variable + * @throws GitLabApiException if any exception occurs during execution + */ + public Variable createVariable( + final Object groupIdOrPath, + final String key, + final String value, + final Boolean isProtected, + final Boolean masked) + throws GitLabApiException { + + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("key", key, true) + .withParam("value", value, true) + .withParam("masked", masked) + .withParam("protected", isProtected); + final Response response = + post( + Response.Status.CREATED, + formData, + "groups", + getGroupIdOrPath(groupIdOrPath), + "variables"); + return (response.readEntity(Variable.class)); + } + + /** + * Update a group variable. + * + *
GitLab Endpoint: PUT /groups/:id/variables/:key
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param key the key of an existing variable, required + * @param value the value for the variable, required + * @param isProtected whether the variable is protected, optional + * @return a Variable instance with the updated variable + * @throws GitLabApiException if any exception occurs during execution + */ + public Variable updateVariable( + final Object groupIdOrPath, final String key, final String value, final Boolean isProtected) + throws GitLabApiException { + + return updateVariable(groupIdOrPath, key, value, isProtected, false); + } + + /** + * Update a group variable. + * + *
GitLab Endpoint: PUT /groups/:id/variables/:key
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param key the key of an existing variable, required + * @param value the value for the variable, required + * @param isProtected whether the variable is protected, optional + * @param masked whether the variable is masked, optional + * @return a Variable instance with the updated variable + * @throws GitLabApiException if any exception occurs during execution + */ + public Variable updateVariable( + final Object groupIdOrPath, + final String key, + final String value, + final Boolean isProtected, + final Boolean masked) + throws GitLabApiException { + + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("value", value, true) + .withParam("masked", masked) + .withParam("protected", isProtected); + final Response response = + putWithFormData( + Response.Status.CREATED, + formData, + "groups", + getGroupIdOrPath(groupIdOrPath), + "variables", + key); + return (response.readEntity(Variable.class)); + } + + /** + * Deletes a group variable. + * + *
GitLab Endpoint: DELETE /groups/:id/variables/:key
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param key the key of an existing variable, required + * @throws GitLabApiException if any exception occurs + */ + public void deleteVariable(final Object groupIdOrPath, final String key) + throws GitLabApiException { + delete( + Response.Status.NO_CONTENT, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "variables", + key); + } + + /** + * Transfer a project to the Group namespace. Available only for admin users. + * + *
GitLab Endpoint: POST /groups/:id/projects/:project_id
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance, required + * @return the transferred Project instance + * @throws GitLabApiException if any exception occurs during execution + */ + public Project transferProject(final Object groupIdOrPath, final Object projectIdOrPath) + throws GitLabApiException { + final Response response = + post( + Response.Status.CREATED, + (Form) null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "projects", + getProjectIdOrPath(projectIdOrPath)); + return (response.readEntity(Project.class)); + } + + /** + * Get a List of the group audit events viewable by Maintainer or an Owner of the group. + * + *
GET /groups/:id/audit_events
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param created_after Group audit events created on or after the given time. + * @param created_before Group audit events created on or before the given time. + * @return a List of group Audit events + * @throws GitLabApiException if any exception occurs + */ + public List getAuditEvents( + final Object groupIdOrPath, final Date created_after, final Date created_before) + throws GitLabApiException { + return (getAuditEvents(groupIdOrPath, created_after, created_before, getDefaultPerPage()) + .all()); + } + + /** + * Get a Pager of the group audit events viewable by Maintainer or an Owner of the group. + * + *
GET /groups/:id/audit_events
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param created_after Group audit events created on or after the given time. + * @param created_before Group audit events created on or before the given time. + * @param itemsPerPage the number of Audit Event instances that will be fetched per page + * @return a Pager of group Audit events + * @throws GitLabApiException if any exception occurs + */ + public Pager getAuditEvents( + final Object groupIdOrPath, + final Date created_after, + final Date created_before, + final int itemsPerPage) + throws GitLabApiException { + final Form form = + new GitLabApiForm() + .withParam("created_before", ISO8601.toString(created_after, false)) + .withParam("created_after", ISO8601.toString(created_before, false)); + return (new Pager( + this, + AuditEvent.class, + itemsPerPage, + form.asMap(), + "groups", + getGroupIdOrPath(groupIdOrPath), + "audit_events")); + } + + /** + * Get a Stream of the group audit events viewable by Maintainer or an Owner of the group. + * + *
GET /groups/:id/audit_events
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param created_after Group audit events created on or after the given time. + * @param created_before Group audit events created on or before the given time. + * @return a Stream of group Audit events + * @throws GitLabApiException if any exception occurs + */ + public Stream getAuditEventsStream( + final Object groupIdOrPath, final Date created_after, final Date created_before) + throws GitLabApiException { + return (getAuditEvents(groupIdOrPath, created_after, created_before, getDefaultPerPage()) + .stream()); + } + + /** + * Get a specific audit event of a group. + * + *
GitLab Endpoint: GET /groups/:id/audit_events/:id_audit_event
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param auditEventId the auditEventId, required + * @return the group Audit event + * @throws GitLabApiException if any exception occurs + */ + public AuditEvent getAuditEvent(final Object groupIdOrPath, final Long auditEventId) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "audit_events", + auditEventId); + return (response.readEntity(AuditEvent.class)); + } + + /** + * Get a List of the group access requests viewable by the authenticated user. + * + *
GET /group/:id/access_requests
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @return a List of project AccessRequest instances accessible by the authenticated user + * @throws GitLabApiException if any exception occurs + */ + public List getAccessRequests(final Object groupIdOrPath) + throws GitLabApiException { + return (getAccessRequests(groupIdOrPath, getDefaultPerPage()).all()); + } + + /** + * Get a Pager of the group access requests viewable by the authenticated user. + * + *
GET /groups/:id/access_requests
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param itemsPerPage the number of AccessRequest instances that will be fetched per page + * @return a Pager of group AccessRequest instances accessible by the authenticated user + * @throws GitLabApiException if any exception occurs + */ + public Pager getAccessRequests(final Object groupIdOrPath, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, + AccessRequest.class, + itemsPerPage, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "access_requests")); + } + + /** + * Get a Stream of the group access requests viewable by the authenticated user. + * + *
GET /groups/:id/access_requests
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @return a Stream of group AccessRequest instances accessible by the authenticated user + * @throws GitLabApiException if any exception occurs + */ + public Stream getAccessRequestsStream(final Object groupIdOrPath) + throws GitLabApiException { + return (getAccessRequests(groupIdOrPath, getDefaultPerPage()).stream()); + } + + /** + * Requests access for the authenticated user to the specified group. + * + *
POST /groups/:id/access_requests
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @return the created AccessRequest instance + * @throws GitLabApiException if any exception occurs + */ + public AccessRequest requestAccess(final Object groupIdOrPath) throws GitLabApiException { + final Response response = + post( + Response.Status.CREATED, + (Form) null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "access_requests"); + return (response.readEntity(AccessRequest.class)); + } + + /** + * Approve access for the specified user to the specified group. + * + *
PUT /groups/:id/access_requests/:user_id/approve
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param userId the user ID to approve access for + * @param accessLevel the access level the user is approved for, if null will be developer (30) + * @return the approved AccessRequest instance + * @throws GitLabApiException if any exception occurs + */ + public AccessRequest approveAccessRequest( + final Object groupIdOrPath, final Long userId, final AccessLevel accessLevel) + throws GitLabApiException { + final GitLabApiForm formData = new GitLabApiForm().withParam("access_level", accessLevel); + final Response response = + this.putWithFormData( + Response.Status.CREATED, + formData, + "groups", + getGroupIdOrPath(groupIdOrPath), + "access_requests", + userId, + "approve"); + return (response.readEntity(AccessRequest.class)); + } + + /** + * Deny access for the specified user to the specified group. + * + *
DELETE /groups/:id/access_requests/:user_id
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param userId the user ID to deny access for + * @throws GitLabApiException if any exception occurs + */ + public void denyAccessRequest(final Object groupIdOrPath, final Long userId) + throws GitLabApiException { + delete( + Response.Status.NO_CONTENT, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "access_requests", + userId); + } + + /** + * Gets a list of a group’s badges and its group badges. + * + *
GitLab Endpoint: GET /groups/:id/badges
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @return a List of Badge instances for the specified group + * @throws GitLabApiException if any exception occurs + */ + public List getBadges(final Object groupIdOrPath) throws GitLabApiException { return getBadges(groupIdOrPath, null); - } - - /** - * Gets a list of a group’s badges, case-sensitively filtered on bagdeName if non-null. - * - *
GitLab Endpoint: GET /groups/:id/badges?name=:name
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param badgeName The name to filter on (case-sensitive), ignored if null. - * @return All badges of the GitLab item, case insensitively filtered on name. - * @throws GitLabApiException If any problem is encountered - */ - public List getBadges(Object groupIdOrPath, String badgeName) throws GitLabApiException { - Form queryParam = new GitLabApiForm().withParam("name", badgeName); - Response response = get(Response.Status.OK, queryParam.asMap(), "groups", getGroupIdOrPath(groupIdOrPath), "badges"); + } + + /** + * Gets a list of a group’s badges, case-sensitively filtered on bagdeName if non-null. + * + *
GitLab Endpoint: GET /groups/:id/badges?name=:name
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param badgeName The name to filter on (case-sensitive), ignored if null. + * @return All badges of the GitLab item, case insensitively filtered on name. + * @throws GitLabApiException If any problem is encountered + */ + public List getBadges(final Object groupIdOrPath, final String badgeName) + throws GitLabApiException { + final Form queryParam = new GitLabApiForm().withParam("name", badgeName); + final Response response = + get( + Response.Status.OK, + queryParam.asMap(), + "groups", + getGroupIdOrPath(groupIdOrPath), + "badges"); return (response.readEntity(new GenericType>() {})); - } - - /** - * Gets a badge of a group. - * - *
GitLab Endpoint: GET /groups/:id/badges/:badge_id
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param badgeId the ID of the badge to get - * @return a Badge instance for the specified group/badge ID pair - * @throws GitLabApiException if any exception occurs - */ - public Badge getBadge(Object groupIdOrPath, Long badgeId) throws GitLabApiException { - Response response = get(Response.Status.OK, null, "groups", getGroupIdOrPath(groupIdOrPath), "badges", badgeId); - return (response.readEntity(Badge.class)); - } - - /** - * Get an Optional instance with the value for the specified badge. - * - *
GitLab Endpoint: GET /groups/:id/badges/:badge_id
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param badgeId the ID of the badge to get - * @return an Optional instance with the specified badge as the value - */ - public Optional getOptionalBadge(Object groupIdOrPath, Long badgeId) { - try { - return (Optional.ofNullable(getBadge(groupIdOrPath, badgeId))); - } catch (GitLabApiException glae) { - return (GitLabApi.createOptionalFromException(glae)); - } - } - - /** - * Add a badge to a group. - * - *
GitLab Endpoint: POST /groups/:id/badges
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param linkUrl the URL of the badge link - * @param imageUrl the URL of the image link - * @return a Badge instance for the added badge - * @throws GitLabApiException if any exception occurs - */ - public Badge addBadge(Object groupIdOrPath, String linkUrl, String imageUrl) throws GitLabApiException { + } + + /** + * Gets a badge of a group. + * + *
GitLab Endpoint: GET /groups/:id/badges/:badge_id
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param badgeId the ID of the badge to get + * @return a Badge instance for the specified group/badge ID pair + * @throws GitLabApiException if any exception occurs + */ + public Badge getBadge(final Object groupIdOrPath, final Long badgeId) throws GitLabApiException { + final Response response = + get(Response.Status.OK, null, "groups", getGroupIdOrPath(groupIdOrPath), "badges", badgeId); + return (response.readEntity(Badge.class)); + } + + /** + * Get an Optional instance with the value for the specified badge. + * + *
GitLab Endpoint: GET /groups/:id/badges/:badge_id
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param badgeId the ID of the badge to get + * @return an Optional instance with the specified badge as the value + */ + public Optional getOptionalBadge(final Object groupIdOrPath, final Long badgeId) { + try { + return (Optional.ofNullable(getBadge(groupIdOrPath, badgeId))); + } catch (final GitLabApiException glae) { + return (GitLabApi.createOptionalFromException(glae)); + } + } + + /** + * Add a badge to a group. + * + *
GitLab Endpoint: POST /groups/:id/badges
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param linkUrl the URL of the badge link + * @param imageUrl the URL of the image link + * @return a Badge instance for the added badge + * @throws GitLabApiException if any exception occurs + */ + public Badge addBadge(final Object groupIdOrPath, final String linkUrl, final String imageUrl) + throws GitLabApiException { return addBadge(groupIdOrPath, null, linkUrl, imageUrl); - } - - /** - * Add a badge to a group. - * - *
GitLab Endpoint: POST /groups/:id/badges
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param name The name to give the badge (may be null) - * @param linkUrl the URL of the badge link - * @param imageUrl the URL of the image link - * @return A Badge instance for the added badge - * @throws GitLabApiException if any exception occurs - */ - public Badge addBadge(Object groupIdOrPath, String name, String linkUrl, String imageUrl) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() - .withParam("name", name, false) - .withParam("link_url", linkUrl, true) - .withParam("image_url", imageUrl, true); - Response response = post(Response.Status.OK, formData, "groups", getGroupIdOrPath(groupIdOrPath), "badges"); + } + + /** + * Add a badge to a group. + * + *
GitLab Endpoint: POST /groups/:id/badges
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param name The name to give the badge (may be null) + * @param linkUrl the URL of the badge link + * @param imageUrl the URL of the image link + * @return A Badge instance for the added badge + * @throws GitLabApiException if any exception occurs + */ + public Badge addBadge( + final Object groupIdOrPath, final String name, final String linkUrl, final String imageUrl) + throws GitLabApiException { + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("name", name, false) + .withParam("link_url", linkUrl, true) + .withParam("image_url", imageUrl, true); + final Response response = + post(Response.Status.OK, formData, "groups", getGroupIdOrPath(groupIdOrPath), "badges"); return (response.readEntity(Badge.class)); - } - - /** - * Edit a badge of a group. - * - *
GitLab Endpoint: PUT /groups/:id/badges
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param badgeId the ID of the badge to get - * @param linkUrl the URL of the badge link - * @param imageUrl the URL of the image link - * @return a Badge instance for the editted badge - * @throws GitLabApiException if any exception occurs - */ - public Badge editBadge(Object groupIdOrPath, Long badgeId, String linkUrl, String imageUrl) throws GitLabApiException { + } + + /** + * Edit a badge of a group. + * + *
GitLab Endpoint: PUT /groups/:id/badges
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param badgeId the ID of the badge to get + * @param linkUrl the URL of the badge link + * @param imageUrl the URL of the image link + * @return a Badge instance for the editted badge + * @throws GitLabApiException if any exception occurs + */ + public Badge editBadge( + final Object groupIdOrPath, final Long badgeId, final String linkUrl, final String imageUrl) + throws GitLabApiException { return (editBadge(groupIdOrPath, badgeId, null, linkUrl, imageUrl)); - } - - /** - * Edit a badge of a group. - * - *
GitLab Endpoint: PUT /groups/:id/badges
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param badgeId the ID of the badge to edit - * @param name The name of the badge to edit (may be null) - * @param linkUrl the URL of the badge link - * @param imageUrl the URL of the image link - * @return a Badge instance for the edited badge - * @throws GitLabApiException if any exception occurs - */ - public Badge editBadge(Object groupIdOrPath, Long badgeId, String name, String linkUrl, String imageUrl) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() - .withParam("name", name, false) - .withParam("link_url", linkUrl, false) - .withParam("image_url", imageUrl, false); - Response response = putWithFormData(Response.Status.OK, formData, "groups", getGroupIdOrPath(groupIdOrPath), "badges", badgeId); + } + + /** + * Edit a badge of a group. + * + *
GitLab Endpoint: PUT /groups/:id/badges
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param badgeId the ID of the badge to edit + * @param name The name of the badge to edit (may be null) + * @param linkUrl the URL of the badge link + * @param imageUrl the URL of the image link + * @return a Badge instance for the edited badge + * @throws GitLabApiException if any exception occurs + */ + public Badge editBadge( + final Object groupIdOrPath, + final Long badgeId, + final String name, + final String linkUrl, + final String imageUrl) + throws GitLabApiException { + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("name", name, false) + .withParam("link_url", linkUrl, false) + .withParam("image_url", imageUrl, false); + final Response response = + putWithFormData( + Response.Status.OK, + formData, + "groups", + getGroupIdOrPath(groupIdOrPath), + "badges", + badgeId); return (response.readEntity(Badge.class)); - } - - /** - * Remove a badge from a group. - * - *
GitLab Endpoint: DELETE /groups/:id/badges/:badge_id
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param badgeId the ID of the badge to remove - * @throws GitLabApiException if any exception occurs - */ - public void removeBadge(Object groupIdOrPath, Long badgeId) throws GitLabApiException { - delete(Response.Status.NO_CONTENT, null, "groups", getGroupIdOrPath(groupIdOrPath), "badges", badgeId); - } - - /** - * Returns how the link_url and image_url final URLs would be after resolving the placeholder interpolation. - * - *
GitLab Endpoint: GET /groups/:id/badges/render
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param linkUrl the URL of the badge link - * @param imageUrl the URL of the image link - * @return a Badge instance for the rendered badge - * @throws GitLabApiException if any exception occurs - */ - public Badge previewBadge(Object groupIdOrPath, String linkUrl, String imageUrl) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() - .withParam("link_url", linkUrl, true) - .withParam("image_url", imageUrl, true); - Response response = get(Response.Status.OK, formData.asMap(), "groups", getGroupIdOrPath(groupIdOrPath), "badges", "render"); - return (response.readEntity(Badge.class)); - } - - /** - * Uploads and sets the project avatar for the specified group. - * - *
GitLab Endpoint: PUT /groups/:id
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param avatarFile the File instance of the avatar file to upload - * @return the updated Group instance - * @throws GitLabApiException if any exception occurs - */ - public Group setGroupAvatar(Object groupIdOrPath, File avatarFile) throws GitLabApiException { - Response response = putUpload(Response.Status.OK, - "avatar", avatarFile, "groups", getGroupIdOrPath(groupIdOrPath)); - return (response.readEntity(Group.class)); - } - - /** - * Share group with another group. Returns 200 and the group details on success. - * - *
GitLab Endpoint: POST /groups/:id/share
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param shareWithGroupId the ID of the group to share with, required - * @param groupAccess the access level to grant the group, required - * @param expiresAt expiration date of the share, optional - * @return a Group instance holding the details of the shared group - * @throws GitLabApiException if any exception occurs - */ - public Group shareGroup(Object groupIdOrPath, Long shareWithGroupId, AccessLevel groupAccess, Date expiresAt) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm() - .withParam("group_id", shareWithGroupId, true) - .withParam("group_access", groupAccess, true) - .withParam("expires_at", expiresAt); - Response response = post(Response.Status.OK, formData, "groups", getGroupIdOrPath(groupIdOrPath), "share"); - return (response.readEntity(Group.class)); - } - - /** - * Unshare the group from another group. - * - *
GitLab Endpoint: DELETE /groups/:id/share/:group_id
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path - * @param sharedWithGroupId the ID of the group to unshare with, required - * @throws GitLabApiException if any exception occurs - */ - public void unshareGroup(Object groupIdOrPath, Long sharedWithGroupId) throws GitLabApiException { - delete(Response.Status.NO_CONTENT, null, - "groups", getGroupIdOrPath(groupIdOrPath), "share", sharedWithGroupId); - } - - /** - * Get all custom attributes for the specified group. - * - *
GitLab Endpoint: GET /groups/:id/custom_attributes
- * - * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance - * @return a list of group's CustomAttributes - * @throws GitLabApiException if any exception occurs - */ - public List getCustomAttributes(final Object groupIdOrPath) throws GitLabApiException { - return (getCustomAttributes(groupIdOrPath, getDefaultPerPage()).all()); - } - - /** - * Get a Pager of custom attributes for the specified group. - * - *
GitLab Endpoint: GET /groups/:id/custom_attributes
- * - * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance - * @param itemsPerPage the number of items per page - * @return a Pager of group's custom attributes - * @throws GitLabApiException if any exception occurs - */ - public Pager getCustomAttributes(final Object groupIdOrPath, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, CustomAttribute.class, itemsPerPage, null, - "groups", getGroupIdOrPath(groupIdOrPath), "custom_attributes")); - } - - /** - * Get a Stream of all custom attributes for the specified group. - * - *
GitLab Endpoint: GET /groups/:id/custom_attributes
- * - * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance - * @return a Stream of group's custom attributes - * @throws GitLabApiException if any exception occurs - */ - public Stream getCustomAttributesStream(final Object groupIdOrPath) throws GitLabApiException { - return (getCustomAttributes(groupIdOrPath, getDefaultPerPage()).stream()); - } - - /** - * Get a single custom attribute for the specified group. - * - *
GitLab Endpoint: GET /groups/:id/custom_attributes/:key
- * - * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance - * @param key the key for the custom attribute - * @return a CustomAttribute instance for the specified key - * @throws GitLabApiException if any exception occurs - */ - public CustomAttribute getCustomAttribute(final Object groupIdOrPath, final String key) throws GitLabApiException { - Response response = get(Response.Status.OK, null, - "groups", getGroupIdOrPath(groupIdOrPath), "custom_attributes", key); - return (response.readEntity(CustomAttribute.class)); - } - - /** - * Get an Optional instance with the value for a single custom attribute for the specified group. - * - *
GitLab Endpoint: GET /groups/:id/custom_attributes/:key
- * - * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance, required - * @param key the key for the custom attribute, required - * @return an Optional instance with the value for a single custom attribute for the specified group - */ - public Optional geOptionalCustomAttribute(final Object groupIdOrPath, final String key) { - try { - return (Optional.ofNullable(getCustomAttribute(groupIdOrPath, key))); - } catch (GitLabApiException glae) { - return (GitLabApi.createOptionalFromException(glae)); - } - } - - /** - * Set a custom attribute for the specified group. The attribute will be updated if it already exists, - * or newly created otherwise. - * - *
GitLab Endpoint: PUT /groups/:id/custom_attributes/:key
- * - * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance - * @param key the key for the custom attribute - * @param value the value for the customAttribute - * @return a CustomAttribute instance for the updated or created custom attribute - * @throws GitLabApiException if any exception occurs - */ - public CustomAttribute setCustomAttribute(final Object groupIdOrPath, final String key, final String value) throws GitLabApiException { - - if (Objects.isNull(key) || key.trim().isEmpty()) { - throw new IllegalArgumentException("Key cannot be null or empty"); - } - if (Objects.isNull(value) || value.trim().isEmpty()) { - throw new IllegalArgumentException("Value cannot be null or empty"); - } - - GitLabApiForm formData = new GitLabApiForm().withParam("value", value); - Response response = putWithFormData(Response.Status.OK, formData, - "groups", getGroupIdOrPath(groupIdOrPath), "custom_attributes", key); - return (response.readEntity(CustomAttribute.class)); - } - - /** - * Delete a custom attribute for the specified group. - * - *
GitLab Endpoint: DELETE /groups/:id/custom_attributes/:key
- * - * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance - * @param key the key of the custom attribute to delete - * @throws GitLabApiException if any exception occurs - */ - public void deleteCustomAttribute(final Object groupIdOrPath, final String key) throws GitLabApiException { - - if (Objects.isNull(key) || key.trim().isEmpty()) { - throw new IllegalArgumentException("Key can't be null or empty"); - } - - delete(Response.Status.OK, null, "groups", getGroupIdOrPath(groupIdOrPath), "custom_attributes", key); - } + } + + /** + * Remove a badge from a group. + * + *
GitLab Endpoint: DELETE /groups/:id/badges/:badge_id
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param badgeId the ID of the badge to remove + * @throws GitLabApiException if any exception occurs + */ + public void removeBadge(final Object groupIdOrPath, final Long badgeId) + throws GitLabApiException { + delete( + Response.Status.NO_CONTENT, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "badges", + badgeId); + } + + /** + * Returns how the link_url and image_url final URLs would be after resolving the placeholder + * interpolation. + * + *
GitLab Endpoint: GET /groups/:id/badges/render
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param linkUrl the URL of the badge link + * @param imageUrl the URL of the image link + * @return a Badge instance for the rendered badge + * @throws GitLabApiException if any exception occurs + */ + public Badge previewBadge(final Object groupIdOrPath, final String linkUrl, final String imageUrl) + throws GitLabApiException { + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("link_url", linkUrl, true) + .withParam("image_url", imageUrl, true); + final Response response = + get( + Response.Status.OK, + formData.asMap(), + "groups", + getGroupIdOrPath(groupIdOrPath), + "badges", + "render"); + return (response.readEntity(Badge.class)); + } + + /** + * Uploads and sets the project avatar for the specified group. + * + *
GitLab Endpoint: PUT /groups/:id
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param avatarFile the File instance of the avatar file to upload + * @return the updated Group instance + * @throws GitLabApiException if any exception occurs + */ + public Group setGroupAvatar(final Object groupIdOrPath, final File avatarFile) + throws GitLabApiException { + final Response response = + putUpload( + Response.Status.OK, "avatar", avatarFile, "groups", getGroupIdOrPath(groupIdOrPath)); + return (response.readEntity(Group.class)); + } + + /** + * Share group with another group. Returns 200 and the group details on success. + * + *
GitLab Endpoint: POST /groups/:id/share
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param shareWithGroupId the ID of the group to share with, required + * @param groupAccess the access level to grant the group, required + * @param expiresAt expiration date of the share, optional + * @return a Group instance holding the details of the shared group + * @throws GitLabApiException if any exception occurs + */ + public Group shareGroup( + final Object groupIdOrPath, + final Long shareWithGroupId, + final AccessLevel groupAccess, + final Date expiresAt) + throws GitLabApiException { + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("group_id", shareWithGroupId, true) + .withParam("group_access", groupAccess, true) + .withParam("expires_at", expiresAt); + final Response response = + post(Response.Status.OK, formData, "groups", getGroupIdOrPath(groupIdOrPath), "share"); + return (response.readEntity(Group.class)); + } + + /** + * Unshare the group from another group. + * + *
GitLab Endpoint: DELETE /groups/:id/share/:group_id
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path + * @param sharedWithGroupId the ID of the group to unshare with, required + * @throws GitLabApiException if any exception occurs + */ + public void unshareGroup(final Object groupIdOrPath, final Long sharedWithGroupId) + throws GitLabApiException { + delete( + Response.Status.NO_CONTENT, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "share", + sharedWithGroupId); + } + + /** + * Get all custom attributes for the specified group. + * + *
GitLab Endpoint: GET /groups/:id/custom_attributes
+ * + * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance + * @return a list of group's CustomAttributes + * @throws GitLabApiException if any exception occurs + */ + public List getCustomAttributes(final Object groupIdOrPath) + throws GitLabApiException { + return (getCustomAttributes(groupIdOrPath, getDefaultPerPage()).all()); + } + + /** + * Get a Pager of custom attributes for the specified group. + * + *
GitLab Endpoint: GET /groups/:id/custom_attributes
+ * + * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance + * @param itemsPerPage the number of items per page + * @return a Pager of group's custom attributes + * @throws GitLabApiException if any exception occurs + */ + public Pager getCustomAttributes( + final Object groupIdOrPath, final int itemsPerPage) throws GitLabApiException { + return (new Pager( + this, + CustomAttribute.class, + itemsPerPage, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "custom_attributes")); + } + + /** + * Get a Stream of all custom attributes for the specified group. + * + *
GitLab Endpoint: GET /groups/:id/custom_attributes
+ * + * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance + * @return a Stream of group's custom attributes + * @throws GitLabApiException if any exception occurs + */ + public Stream getCustomAttributesStream(final Object groupIdOrPath) + throws GitLabApiException { + return (getCustomAttributes(groupIdOrPath, getDefaultPerPage()).stream()); + } + + /** + * Get a single custom attribute for the specified group. + * + *
GitLab Endpoint: GET /groups/:id/custom_attributes/:key
+ * + * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance + * @param key the key for the custom attribute + * @return a CustomAttribute instance for the specified key + * @throws GitLabApiException if any exception occurs + */ + public CustomAttribute getCustomAttribute(final Object groupIdOrPath, final String key) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "custom_attributes", + key); + return (response.readEntity(CustomAttribute.class)); + } + + /** + * Get an Optional instance with the value for a single custom attribute for the specified group. + * + *
GitLab Endpoint: GET /groups/:id/custom_attributes/:key
+ * + * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance, + * required + * @param key the key for the custom attribute, required + * @return an Optional instance with the value for a single custom attribute for the specified + * group + */ + public Optional geOptionalCustomAttribute( + final Object groupIdOrPath, final String key) { + try { + return (Optional.ofNullable(getCustomAttribute(groupIdOrPath, key))); + } catch (final GitLabApiException glae) { + return (GitLabApi.createOptionalFromException(glae)); + } + } + + /** + * Set a custom attribute for the specified group. The attribute will be updated if it already + * exists, or newly created otherwise. + * + *
GitLab Endpoint: PUT /groups/:id/custom_attributes/:key
+ * + * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance + * @param key the key for the custom attribute + * @param value the value for the customAttribute + * @return a CustomAttribute instance for the updated or created custom attribute + * @throws GitLabApiException if any exception occurs + */ + public CustomAttribute setCustomAttribute( + final Object groupIdOrPath, final String key, final String value) throws GitLabApiException { + + if (Objects.isNull(key) || key.trim().isEmpty()) { + throw new IllegalArgumentException("Key cannot be null or empty"); + } + if (Objects.isNull(value) || value.trim().isEmpty()) { + throw new IllegalArgumentException("Value cannot be null or empty"); + } + + final GitLabApiForm formData = new GitLabApiForm().withParam("value", value); + final Response response = + putWithFormData( + Response.Status.OK, + formData, + "groups", + getGroupIdOrPath(groupIdOrPath), + "custom_attributes", + key); + return (response.readEntity(CustomAttribute.class)); + } + + /** + * Delete a custom attribute for the specified group. + * + *
GitLab Endpoint: DELETE /groups/:id/custom_attributes/:key
+ * + * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance + * @param key the key of the custom attribute to delete + * @throws GitLabApiException if any exception occurs + */ + public void deleteCustomAttribute(final Object groupIdOrPath, final String key) + throws GitLabApiException { + + if (Objects.isNull(key) || key.trim().isEmpty()) { + throw new IllegalArgumentException("Key can't be null or empty"); + } + + delete( + Response.Status.OK, + null, + "groups", + getGroupIdOrPath(groupIdOrPath), + "custom_attributes", + key); + } } diff --git a/src/main/java/org/gitlab4j/api/HealthCheckApi.java b/src/main/java/org/gitlab4j/api/HealthCheckApi.java index 104f8d9d2..5f0dfb4f7 100644 --- a/src/main/java/org/gitlab4j/api/HealthCheckApi.java +++ b/src/main/java/org/gitlab4j/api/HealthCheckApi.java @@ -1,14 +1,13 @@ package org.gitlab4j.api; -import org.gitlab4j.api.models.HealthCheckInfo; - -import javax.ws.rs.core.Response; import java.io.IOException; import java.net.URL; +import jakarta.ws.rs.core.Response; +import org.gitlab4j.api.models.HealthCheckInfo; public class HealthCheckApi extends AbstractApi { - public HealthCheckApi(GitLabApi gitLabApi) { + public HealthCheckApi(final GitLabApi gitLabApi) { super(gitLabApi); } @@ -37,13 +36,13 @@ public HealthCheckInfo getLiveness() throws GitLabApiException { * @throws GitLabApiException if any exception occurs * @deprecated */ - public HealthCheckInfo getLiveness(String token) throws GitLabApiException { + public HealthCheckInfo getLiveness(final String token) throws GitLabApiException { try { - URL livenessUrl = getApiClient().getUrlWithBase("-", "liveness"); - GitLabApiForm formData = new GitLabApiForm().withParam("token", token, false); - Response response = get(Response.Status.OK, formData.asMap(), livenessUrl); + final URL livenessUrl = getApiClient().getUrlWithBase("-", "liveness"); + final GitLabApiForm formData = new GitLabApiForm().withParam("token", token, false); + final Response response = get(Response.Status.OK, formData.asMap(), livenessUrl); return (response.readEntity(HealthCheckInfo.class)); - } catch (IOException ioe) { + } catch (final IOException ioe) { throw (new GitLabApiException(ioe)); } } @@ -73,13 +72,13 @@ public HealthCheckInfo getReadiness() throws GitLabApiException { * @throws GitLabApiException if any exception occurs * @deprecated */ - public HealthCheckInfo getReadiness(String token) throws GitLabApiException { + public HealthCheckInfo getReadiness(final String token) throws GitLabApiException { try { - URL readinessUrl = getApiClient().getUrlWithBase("-", "readiness"); - GitLabApiForm formData = new GitLabApiForm().withParam("token", token, false); - Response response = get(Response.Status.OK, formData.asMap(), readinessUrl); + final URL readinessUrl = getApiClient().getUrlWithBase("-", "readiness"); + final GitLabApiForm formData = new GitLabApiForm().withParam("token", token, false); + final Response response = get(Response.Status.OK, formData.asMap(), readinessUrl); return (response.readEntity(HealthCheckInfo.class)); - } catch (IOException ioe) { + } catch (final IOException ioe) { throw (new GitLabApiException(ioe)); } } diff --git a/src/main/java/org/gitlab4j/api/HookManager.java b/src/main/java/org/gitlab4j/api/HookManager.java index e3c098879..95d5d1001 100644 --- a/src/main/java/org/gitlab4j/api/HookManager.java +++ b/src/main/java/org/gitlab4j/api/HookManager.java @@ -1,66 +1,70 @@ - package org.gitlab4j.api; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; /** - * This interface provides a base class handler for processing GitLab Web Hook and System Hook callouts. + * This interface provides a base class handler for processing GitLab Web Hook and System Hook + * callouts. */ public interface HookManager { - /** - * Get the secret token that received hook events should be validated against. - * - * @return the secret token that received hook events should be validated against - */ - String getSecretToken(); - - /** - * Set the secret token that received hook events should be validated against. - * - * @param secretToken the secret token to verify against - */ - void setSecretToken(String secretToken); + /** + * Get the secret token that received hook events should be validated against. + * + * @return the secret token that received hook events should be validated against + */ + String getSecretToken(); - /** - * Validate the provided secret token against the reference secret token. Returns true if - * the secret token is valid or there is no reference secret token to validate against, - * otherwise returns false. - * - * @param secretToken the token to validate - * @return true if the secret token is valid or there is no reference secret token to validate against - */ - default public boolean isValidSecretToken(String secretToken) { - String ourSecretToken = getSecretToken(); - return (ourSecretToken == null || - ourSecretToken.trim().isEmpty() || - ourSecretToken.equals(secretToken) ? true : false); - } + /** + * Set the secret token that received hook events should be validated against. + * + * @param secretToken the secret token to verify against + */ + void setSecretToken(String secretToken); - /** - * Validate the provided secret token found in the HTTP header against the reference secret token. - * Returns true if the secret token is valid or there is no reference secret token to validate - * against, otherwise returns false. - * - * @param request the HTTP request to verify the secret token - * @return true if the secret token is valid or there is no reference secret token to validate against - */ - default public boolean isValidSecretToken(HttpServletRequest request) { + /** + * Validate the provided secret token against the reference secret token. Returns true if the + * secret token is valid or there is no reference secret token to validate against, otherwise + * returns false. + * + * @param secretToken the token to validate + * @return true if the secret token is valid or there is no reference secret token to validate + * against + */ + public default boolean isValidSecretToken(final String secretToken) { + final String ourSecretToken = getSecretToken(); + return (ourSecretToken == null + || ourSecretToken.trim().isEmpty() + || ourSecretToken.equals(secretToken) + ? true + : false); + } - if (getSecretToken() != null) { - String secretToken = request.getHeader("X-Gitlab-Token"); - return (isValidSecretToken(secretToken)); - } + /** + * Validate the provided secret token found in the HTTP header against the reference secret token. + * Returns true if the secret token is valid or there is no reference secret token to validate + * against, otherwise returns false. + * + * @param request the HTTP request to verify the secret token + * @return true if the secret token is valid or there is no reference secret token to validate + * against + */ + public default boolean isValidSecretToken(final HttpServletRequest request) { - return (true); + if (getSecretToken() != null) { + final String secretToken = request.getHeader("X-Gitlab-Token"); + return (isValidSecretToken(secretToken)); } - /** - * Parses and verifies an Event instance from the HTTP request and - * fires it off to the registered listeners. - * - * @param request the HttpServletRequest to read the Event instance from - * @throws GitLabApiException if the parsed event is not supported - */ - public void handleEvent(HttpServletRequest request) throws GitLabApiException; -} \ No newline at end of file + return (true); + } + + /** + * Parses and verifies an Event instance from the HTTP request and fires it off to the registered + * listeners. + * + * @param request the HttpServletRequest to read the Event instance from + * @throws GitLabApiException if the parsed event is not supported + */ + public void handleEvent(HttpServletRequest request) throws GitLabApiException; +} diff --git a/src/main/java/org/gitlab4j/api/ImportExportApi.java b/src/main/java/org/gitlab4j/api/ImportExportApi.java index 509eae1dd..2eb781b17 100644 --- a/src/main/java/org/gitlab4j/api/ImportExportApi.java +++ b/src/main/java/org/gitlab4j/api/ImportExportApi.java @@ -8,255 +8,315 @@ import java.nio.file.StandardCopyOption; import java.util.Date; import java.util.Map; - -import javax.ws.rs.core.Form; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import jakarta.ws.rs.core.Form; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; import org.gitlab4j.api.models.ExportStatus; import org.gitlab4j.api.models.ImportStatus; import org.gitlab4j.api.models.Project; /** * This class provides an entry point to all the GitLab API project import/export calls. - * @see Project import/export API at GitLab + * + * @see Project import/export + * API at GitLab */ public class ImportExportApi extends AbstractApi { - public ImportExportApi(GitLabApi gitLabApi) { - super(gitLabApi); - } - - /** - * Schedule an export. - * - *
GitLab Endpoint: POST /projects/:id/export
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @throws GitLabApiException if any exception occurs - */ - public void scheduleExport(Object projectIdOrPath) throws GitLabApiException { - scheduleExport(projectIdOrPath, null, null, null, null); - } - - /** - * Schedule an export. - * - *
GitLab Endpoint: POST /projects/:id/export
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param description overrides the project description, optional - * @throws GitLabApiException if any exception occurs - */ - public void scheduleExport(Object projectIdOrPath, String description) throws GitLabApiException { - scheduleExport(projectIdOrPath, description, null, null, null); - } + public ImportExportApi(final GitLabApi gitLabApi) { + super(gitLabApi); + } - /** - * Schedule an export. - * - *
GitLab Endpoint: POST /projects/:id/export
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param description overrides the project description, optional - * @param upload Mao that contains the information to upload the exported project to a web server - * @param uploadUrl the URL to upload the project - * @param uploadHttpMethod the HTTP method to upload the exported project. - * Only PUT and POST methods allowed. Default is PUT - * @throws GitLabApiException if any exception occurs - */ - public void scheduleExport(Object projectIdOrPath, String description, - Map upload, String uploadUrl, String uploadHttpMethod) throws GitLabApiException { + /** + * Schedule an export. + * + *
GitLab Endpoint: POST /projects/:id/export
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @throws GitLabApiException if any exception occurs + */ + public void scheduleExport(final Object projectIdOrPath) throws GitLabApiException { + scheduleExport(projectIdOrPath, null, null, null, null); + } - Form formData = new GitLabApiForm() - .withParam("description", description) - .withParam("upload", upload) - .withParam("upload[url]", uploadUrl) - .withParam("upload[http_method]", uploadHttpMethod); - post(Response.Status.ACCEPTED, formData, "projects", getProjectIdOrPath(projectIdOrPath), "export"); - } + /** + * Schedule an export. + * + *
GitLab Endpoint: POST /projects/:id/export
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param description overrides the project description, optional + * @throws GitLabApiException if any exception occurs + */ + public void scheduleExport(final Object projectIdOrPath, final String description) + throws GitLabApiException { + scheduleExport(projectIdOrPath, description, null, null, null); + } - /** - * Get the status of export. - * - *
GitLab Endpoint: GET /projects/:id/export
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @return an ExportStatus instance holding information on the export status - * @throws GitLabApiException if any exception occurs - */ - public ExportStatus getExportStatus(Object projectIdOrPath) throws GitLabApiException { - Response response = get(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), "export"); - return (response.readEntity(ExportStatus.class)); - } + /** + * Schedule an export. + * + *
GitLab Endpoint: POST /projects/:id/export
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param description overrides the project description, optional + * @param upload Mao that contains the information to upload the exported project to a web server + * @param uploadUrl the URL to upload the project + * @param uploadHttpMethod the HTTP method to upload the exported project. Only PUT and POST + * methods allowed. Default is PUT + * @throws GitLabApiException if any exception occurs + */ + public void scheduleExport( + final Object projectIdOrPath, + final String description, + final Map upload, + final String uploadUrl, + final String uploadHttpMethod) + throws GitLabApiException { - /** - * Download the finished export. - * - *
GitLab Endpoint: GET /projects/:id/export/download
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param directory the File instance of the directory to save the export file to, if null will use "java.io.tmpdir" - * @return a File instance pointing to the download of the project export file - * @throws GitLabApiException if any exception occurs - */ - public File downloadExport(Object projectIdOrPath, File directory) throws GitLabApiException { - return downloadExport(projectIdOrPath, directory, null); - } + final Form formData = + new GitLabApiForm() + .withParam("description", description) + .withParam("upload", upload) + .withParam("upload[url]", uploadUrl) + .withParam("upload[http_method]", uploadHttpMethod); + post( + Response.Status.ACCEPTED, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "export"); + } - /** - * Download the finished export. - * - *
GitLab Endpoint: GET /projects/:id/export/download
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param directory the File instance of the directory to save the export file to, if null will use "java.io.tmpdir" - * @param filename Name to give to the downloaded file. If null then we try to get from Content-Disposition header - * or to compute one from parameters - * @return a File instance pointing to the download of the project export file - * @throws GitLabApiException if any exception occurs - */ - public File downloadExport(Object projectIdOrPath, File directory, String filename) throws GitLabApiException { + /** + * Get the status of export. + * + *
GitLab Endpoint: GET /projects/:id/export
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @return an ExportStatus instance holding information on the export status + * @throws GitLabApiException if any exception occurs + */ + public ExportStatus getExportStatus(final Object projectIdOrPath) throws GitLabApiException { + final Response response = + get(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), "export"); + return (response.readEntity(ExportStatus.class)); + } - Response response = getWithAccepts(Response.Status.OK, null, MediaType.MEDIA_TYPE_WILDCARD, - "projects", getProjectIdOrPath(projectIdOrPath), "export", "download"); + /** + * Download the finished export. + * + *
GitLab Endpoint: GET /projects/:id/export/download
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param directory the File instance of the directory to save the export file to, if null will + * use "java.io.tmpdir" + * @return a File instance pointing to the download of the project export file + * @throws GitLabApiException if any exception occurs + */ + public File downloadExport(final Object projectIdOrPath, final File directory) + throws GitLabApiException { + return downloadExport(projectIdOrPath, directory, null); + } - if (directory == null) { - directory = new File(System.getProperty("java.io.tmpdir")); - } + /** + * Download the finished export. + * + *
GitLab Endpoint: GET /projects/:id/export/download
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param directory the File instance of the directory to save the export file to, if null will + * use "java.io.tmpdir" + * @param filename Name to give to the downloaded file. If null then we try to get from + * Content-Disposition header or to compute one from parameters + * @return a File instance pointing to the download of the project export file + * @throws GitLabApiException if any exception occurs + */ + public File downloadExport(final Object projectIdOrPath, File directory, String filename) + throws GitLabApiException { - if (filename == null) { + final Response response = + getWithAccepts( + Response.Status.OK, + null, + MediaType.MEDIA_TYPE_WILDCARD, + "projects", + getProjectIdOrPath(projectIdOrPath), + "export", + "download"); - // No filename provided - String disposition = response.getHeaderString("Content-Disposition"); - if (disposition == null) { + if (directory == null) { + directory = new File(System.getProperty("java.io.tmpdir")); + } - // On GitLab.com the Content-Disposition returned is null - String name = null; - if (projectIdOrPath instanceof Project) { - name = ((Project) projectIdOrPath).getPathWithNamespace().replace('/', '_'); - } else if(projectIdOrPath instanceof String) { - name = (String)projectIdOrPath; - } else if(projectIdOrPath instanceof Integer) { - name = "projectid-" + projectIdOrPath; - } + if (filename == null) { - // template = "YYYY-MM-DD_HH-MM-SS_{name}_export.tar.gz" - final String template = "%1$tY-%1$tm-%1$td_%1$tH-%1$tM-%1$tS_%2$s_export.tar.gz"; - filename = String.format(template, new Date(), name); + // No filename provided + final String disposition = response.getHeaderString("Content-Disposition"); + if (disposition == null) { - } else { - filename = disposition.replaceFirst("(?i)^.*filename=\"?([^\"]+)\"?.*$", "$1"); - } + // On GitLab.com the Content-Disposition returned is null + String name = null; + if (projectIdOrPath instanceof Project) { + name = ((Project) projectIdOrPath).getPathWithNamespace().replace('/', '_'); + } else if (projectIdOrPath instanceof String) { + name = (String) projectIdOrPath; + } else if (projectIdOrPath instanceof Integer) { + name = "projectid-" + projectIdOrPath; } - try { - - File file = new File(directory, filename); - InputStream in = response.readEntity(InputStream.class); - Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING); - return (file); + // template = "YYYY-MM-DD_HH-MM-SS_{name}_export.tar.gz" + final String template = "%1$tY-%1$tm-%1$td_%1$tH-%1$tM-%1$tS_%2$s_export.tar.gz"; + filename = String.format(template, new Date(), name); - } catch (IOException ioe) { - throw new GitLabApiException(ioe); - } + } else { + filename = disposition.replaceFirst("(?i)^.*filename=\"?([^\"]+)\"?.*$", "$1"); + } } - /** - *

Import an exported project. The following properties on the Project instance - * are utilized in the creation of the new project:

- *
    - *
  • defaultBranch (optional) - master by default
  • - *
  • description (optional) - short project description
  • - *
  • visibility (optional) - Limit by visibility public, internal, or private
  • - *
  • visibilityLevel (optional)
  • - *
  • issuesEnabled (optional) - Enable issues for this project
  • - *
  • mergeMethod (optional) - Set the merge method used
  • - *
  • mergeRequestsEnabled (optional) - Enable merge requests for this project
  • - *
  • wikiEnabled (optional) - Enable wiki for this project
  • - *
  • snippetsEnabled (optional) - Enable snippets for this project
  • - *
  • jobsEnabled (optional) - Enable jobs for this project
  • - *
  • containerRegistryEnabled (optional) - Enable container registry for this project
  • - *
  • sharedRunnersEnabled (optional) - Enable shared runners for this project
  • - *
  • publicJobs (optional) - If true, jobs can be viewed by non-project-members
  • - *
  • onlyAllowMergeIfPipelineSucceeds (optional) - Set whether merge requests can only be merged with successful jobs
  • - *
  • onlyAllowMergeIfAllDiscussionsAreResolved (optional) - Set whether merge requests can only be merged when all the discussions are resolved
  • - *
  • lfsEnabled (optional) - Enable LFS
  • - *
  • requestAccessEnabled (optional) - Allow users to request member access
  • - *
  • repositoryStorage (optional) - Which storage shard the repository is on. Available only to admins
  • - *
  • approvalsBeforeMerge (optional) - How many approvers should approve merge request by default
  • - *
  • printingMergeRequestLinkEnabled (optional) - Show link to create/view merge request when pushing from the command line
  • - *
  • resolveOutdatedDiffDiscussions (optional) - Automatically resolve merge request diffs discussions on lines changed with a push
  • - *
  • initialize_with_readme (optional) - Initialize project with README file
  • - *
  • packagesEnabled (optional) - Enable or disable mvn packages repository feature
  • - *
- *
GitLab Endpoint: POST /projects/import
- * - * @param namespaceIdOrPath the ID or path of the namespace that the project will be imported to. Defaults to the current user’s namespace - * @param exportFile the project export file to be imported - * @param path the name and path for the new project - * @param overwrite if there is a project with the same path the import will overwrite it. Defaults to false - * @param overrideParams overriding project params, supports all fields defined by the ProjectApi, optional - * @return an Importstatus instance with info for the project being imported to - * @throws GitLabApiException if any exception occurs - */ - public ImportStatus startImport(Object namespaceIdOrPath, File exportFile, String path, Boolean overwrite, Project overrideParams) throws GitLabApiException { + try { - URL url; - try { - url = getApiClient().getApiUrl("projects", "import"); - } catch (IOException ioe) { - throw new GitLabApiException(ioe); - } + final File file = new File(directory, filename); + final InputStream in = response.readEntity(InputStream.class); + Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING); + return (file); - GitLabApiForm formData = new GitLabApiForm() - .withParam("path", path, true) - .withParam("namespace", namespaceIdOrPath) - .withParam("overwrite", overwrite); + } catch (final IOException ioe) { + throw new GitLabApiException(ioe); + } + } - if (overrideParams != null) { - formData.withParam("default_branch", overrideParams.getDefaultBranch()) - .withParam("description", overrideParams.getDescription()) - .withParam("issues_enabled", overrideParams.getIssuesEnabled()) - .withParam("merge_method", overrideParams.getMergeMethod()) - .withParam("merge_requests_enabled", overrideParams.getMergeRequestsEnabled()) - .withParam("jobs_enabled", overrideParams.getJobsEnabled()) - .withParam("wiki_enabled", overrideParams.getWikiEnabled()) - .withParam("container_registry_enabled", overrideParams.getContainerRegistryEnabled()) - .withParam("snippets_enabled", overrideParams.getSnippetsEnabled()) - .withParam("shared_runners_enabled", overrideParams.getSharedRunnersEnabled()) - .withParam("public_jobs", overrideParams.getPublicJobs()) - .withParam("visibility_level", overrideParams.getVisibilityLevel()) - .withParam("only_allow_merge_if_pipeline_succeeds", overrideParams.getOnlyAllowMergeIfPipelineSucceeds()) - .withParam("only_allow_merge_if_all_discussions_are_resolved", overrideParams.getOnlyAllowMergeIfAllDiscussionsAreResolved()) - .withParam("lfs_enabled", overrideParams.getLfsEnabled()) - .withParam("request_access_enabled", overrideParams.getRequestAccessEnabled()) - .withParam("repository_storage", overrideParams.getRepositoryStorage()) - .withParam("approvals_before_merge", overrideParams.getApprovalsBeforeMerge()) - .withParam("printing_merge_request_link_enabled", overrideParams.getPrintingMergeRequestLinkEnabled()) - .withParam("resolve_outdated_diff_discussions", overrideParams.getResolveOutdatedDiffDiscussions()) - .withParam("initialize_with_readme", overrideParams.getInitializeWithReadme()) - .withParam("packages_enabled", overrideParams.getPackagesEnabled()) - .withParam("build_git_strategy", overrideParams.getBuildGitStrategy()) - .withParam("build_coverage_regex", overrideParams.getBuildCoverageRegex()) - .withParam("squash_option", overrideParams.getSquashOption()); - } + /** + * Import an exported project. The following properties on the Project instance are utilized in + * the creation of the new project: + * + *
    + *
  • defaultBranch (optional) - master by default + *
  • description (optional) - short project description + *
  • visibility (optional) - Limit by visibility public, internal, or private + *
  • visibilityLevel (optional) + *
  • issuesEnabled (optional) - Enable issues for this project + *
  • mergeMethod (optional) - Set the merge method used + *
  • mergeRequestsEnabled (optional) - Enable merge requests for this project + *
  • wikiEnabled (optional) - Enable wiki for this project + *
  • snippetsEnabled (optional) - Enable snippets for this project + *
  • jobsEnabled (optional) - Enable jobs for this project + *
  • containerRegistryEnabled (optional) - Enable container registry for this project + *
  • sharedRunnersEnabled (optional) - Enable shared runners for this project + *
  • publicJobs (optional) - If true, jobs can be viewed by non-project-members + *
  • onlyAllowMergeIfPipelineSucceeds (optional) - Set whether merge requests can only be + * merged with successful jobs + *
  • onlyAllowMergeIfAllDiscussionsAreResolved (optional) - Set whether merge requests can + * only be merged when all the discussions are resolved + *
  • lfsEnabled (optional) - Enable LFS + *
  • requestAccessEnabled (optional) - Allow users to request member access + *
  • repositoryStorage (optional) - Which storage shard the repository is on. Available only + * to admins + *
  • approvalsBeforeMerge (optional) - How many approvers should approve merge request by + * default + *
  • printingMergeRequestLinkEnabled (optional) - Show link to create/view merge request when + * pushing from the command line + *
  • resolveOutdatedDiffDiscussions (optional) - Automatically resolve merge request diffs + * discussions on lines changed with a push + *
  • initialize_with_readme (optional) - Initialize project with README file + *
  • packagesEnabled (optional) - Enable or disable mvn packages repository feature + *
+ * + *
GitLab Endpoint: POST /projects/import
+ * + * @param namespaceIdOrPath the ID or path of the namespace that the project will be imported to. + * Defaults to the current user’s namespace + * @param exportFile the project export file to be imported + * @param path the name and path for the new project + * @param overwrite if there is a project with the same path the import will overwrite it. + * Defaults to false + * @param overrideParams overriding project params, supports all fields defined by the ProjectApi, + * optional + * @return an Importstatus instance with info for the project being imported to + * @throws GitLabApiException if any exception occurs + */ + public ImportStatus startImport( + final Object namespaceIdOrPath, + final File exportFile, + final String path, + final Boolean overwrite, + final Project overrideParams) + throws GitLabApiException { - Response response = upload(Response.Status.CREATED, "file", exportFile, null, formData, url); - return (response.readEntity(ImportStatus.class)); + final URL url; + try { + url = getApiClient().getApiUrl("projects", "import"); + } catch (final IOException ioe) { + throw new GitLabApiException(ioe); } - /** - * Get the status of an import. - * - *
GitLab Endpoint: GET /projects/:id/import
- * - * @param projectIdOrPath the new (imported) project identifier in the form of an Long(ID), String(path), or Project instance - * @return an ImportStatus instance holding information on the import status - * @throws GitLabApiException if any exception occurs - */ - public ImportStatus getImportStatus(Object projectIdOrPath) throws GitLabApiException { - Response response = get(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), "import"); - return (response.readEntity(ImportStatus.class)); + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("path", path, true) + .withParam("namespace", namespaceIdOrPath) + .withParam("overwrite", overwrite); + + if (overrideParams != null) { + formData + .withParam("default_branch", overrideParams.getDefaultBranch()) + .withParam("description", overrideParams.getDescription()) + .withParam("issues_enabled", overrideParams.getIssuesEnabled()) + .withParam("merge_method", overrideParams.getMergeMethod()) + .withParam("merge_requests_enabled", overrideParams.getMergeRequestsEnabled()) + .withParam("jobs_enabled", overrideParams.getJobsEnabled()) + .withParam("wiki_enabled", overrideParams.getWikiEnabled()) + .withParam("container_registry_enabled", overrideParams.getContainerRegistryEnabled()) + .withParam("snippets_enabled", overrideParams.getSnippetsEnabled()) + .withParam("shared_runners_enabled", overrideParams.getSharedRunnersEnabled()) + .withParam("public_jobs", overrideParams.getPublicJobs()) + .withParam("visibility_level", overrideParams.getVisibilityLevel()) + .withParam( + "only_allow_merge_if_pipeline_succeeds", + overrideParams.getOnlyAllowMergeIfPipelineSucceeds()) + .withParam( + "only_allow_merge_if_all_discussions_are_resolved", + overrideParams.getOnlyAllowMergeIfAllDiscussionsAreResolved()) + .withParam("lfs_enabled", overrideParams.getLfsEnabled()) + .withParam("request_access_enabled", overrideParams.getRequestAccessEnabled()) + .withParam("repository_storage", overrideParams.getRepositoryStorage()) + .withParam("approvals_before_merge", overrideParams.getApprovalsBeforeMerge()) + .withParam( + "printing_merge_request_link_enabled", + overrideParams.getPrintingMergeRequestLinkEnabled()) + .withParam( + "resolve_outdated_diff_discussions", + overrideParams.getResolveOutdatedDiffDiscussions()) + .withParam("initialize_with_readme", overrideParams.getInitializeWithReadme()) + .withParam("packages_enabled", overrideParams.getPackagesEnabled()) + .withParam("build_git_strategy", overrideParams.getBuildGitStrategy()) + .withParam("build_coverage_regex", overrideParams.getBuildCoverageRegex()) + .withParam("squash_option", overrideParams.getSquashOption()); } + + final Response response = + upload(Response.Status.CREATED, "file", exportFile, null, formData, url); + return (response.readEntity(ImportStatus.class)); + } + + /** + * Get the status of an import. + * + *
GitLab Endpoint: GET /projects/:id/import
+ * + * @param projectIdOrPath the new (imported) project identifier in the form of an Long(ID), + * String(path), or Project instance + * @return an ImportStatus instance holding information on the import status + * @throws GitLabApiException if any exception occurs + */ + public ImportStatus getImportStatus(final Object projectIdOrPath) throws GitLabApiException { + final Response response = + get(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), "import"); + return (response.readEntity(ImportStatus.class)); + } } diff --git a/src/main/java/org/gitlab4j/api/IssuesApi.java b/src/main/java/org/gitlab4j/api/IssuesApi.java index 2c8ee532b..6cf945126 100644 --- a/src/main/java/org/gitlab4j/api/IssuesApi.java +++ b/src/main/java/org/gitlab4j/api/IssuesApi.java @@ -5,10 +5,8 @@ import java.util.List; import java.util.Optional; import java.util.stream.Stream; - -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; - +import jakarta.ws.rs.core.GenericType; +import jakarta.ws.rs.core.Response; import org.gitlab4j.api.GitLabApi.ApiVersion; import org.gitlab4j.api.models.Duration; import org.gitlab4j.api.models.Issue; @@ -23,434 +21,554 @@ /** * This class provides an entry point to all the GitLab API Issue calls. + * * @see Issues API at GitLab * @see Issue Links API at GitLab - * @see Issues Statistics API at GitLab + * @see Issues Statistics API at + * GitLab */ public class IssuesApi extends AbstractApi implements Constants { - public IssuesApi(GitLabApi gitLabApi) { - super(gitLabApi); - } - - /** - * Get all issues the authenticated user has access to. Only returns issues created by the current user. - * - *
GitLab Endpoint: GET /issues
- * - * @return a list of user's issues - * @throws GitLabApiException if any exception occurs - */ - public List getIssues() throws GitLabApiException { - return (getIssues(getDefaultPerPage()).all()); - } - - /** - * Get all issues the authenticated user has access to using the specified page and per page setting. Only returns issues created by the current user. - * - *
GitLab Endpoint: GET /issues
- * - * @param page the page to get - * @param perPage the number of issues per page - * @return the list of issues in the specified range - * @throws GitLabApiException if any exception occurs - */ - public List getIssues(int page, int perPage) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "issues"); - return (response.readEntity(new GenericType>() {})); - } - - /** - * Get a Pager of all issues the authenticated user has access to. Only returns issues created by the current user. - * - *
GitLab Endpoint: GET /issues
- *r - * @param itemsPerPage the number of issues per page - * @return the Pager of issues in the specified range - * @throws GitLabApiException if any exception occurs - */ - public Pager getIssues(int itemsPerPage) throws GitLabApiException { - return (new Pager(this, Issue.class, itemsPerPage, null, "issues")); - } - - /** - * Get all issues the authenticated user has access to as a Stream. Only returns issues created by the current user. - * - *
GitLab Endpoint: GET /issues
- * - * @return a Stream of user's issues - * @throws GitLabApiException if any exception occurs - */ - public Stream getIssuesStream() throws GitLabApiException { - return (getIssues(getDefaultPerPage()).stream()); - } - - /** - * Get a list of project's issues. - * - *
GitLab Endpoint: GET /projects/:id/issues
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @return a list of project's issues - * @throws GitLabApiException if any exception occurs - */ - public List getIssues(Object projectIdOrPath) throws GitLabApiException { - return (getIssues(projectIdOrPath, getDefaultPerPage()).all()); - } - - /** - * Get a list of project's issues using the specified page and per page settings. - * - *
GitLab Endpoint: GET /projects/:id/issues
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param page the page to get - * @param perPage the number of issues per page - * @return the list of issues in the specified range - * @throws GitLabApiException if any exception occurs - */ - public List getIssues(Object projectIdOrPath, int page, int perPage) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "projects", getProjectIdOrPath(projectIdOrPath), "issues"); - return (response.readEntity(new GenericType>() {})); - } - - /** - * Get a Pager of project's issues. - * - *
GitLab Endpoint: GET /projects/:id/issues
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param itemsPerPage the number of issues per page - * @return the Pager of issues in the specified range - * @throws GitLabApiException if any exception occurs - */ - public Pager getIssues(Object projectIdOrPath, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, Issue.class, itemsPerPage, null, "projects", getProjectIdOrPath(projectIdOrPath), "issues")); - } - - /** - * Get a Stream of project's issues. Only returns the first page - * - *
GitLab Endpoint: GET /projects/:id/issues
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @return a Stream of project's issues - * @throws GitLabApiException if any exception occurs - */ - public Stream getIssuesStream(Object projectIdOrPath) throws GitLabApiException { - return (getIssues(projectIdOrPath, getDefaultPerPage()).stream()); - } - - /** - * Get a list of project's issues. - * - *
GitLab Endpoint: GET /projects/:id/issues
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings - * @return the list of issues in the specified range. - * @throws GitLabApiException if any exception occurs - */ - public List getIssues(Object projectIdOrPath, IssueFilter filter) throws GitLabApiException { - return (getIssues(projectIdOrPath, filter, getDefaultPerPage()).all()); - } - - /** - * Get a list of project's issues. - * - *
GitLab Endpoint: GET /projects/:id/issues
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings. - * @param page the page to get. - * @param perPage the number of projects per page. - * @return the list of issues in the specified range. - * @throws GitLabApiException if any exception occurs - */ - public List getIssues(Object projectIdOrPath, IssueFilter filter, int page, int perPage) throws GitLabApiException { - GitLabApiForm formData = filter.getQueryParams(page, perPage); - Response response = get(Response.Status.OK, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "issues"); - return (response.readEntity(new GenericType>() {})); - } - - /** - * Get a list of project's issues. - * - *
GitLab Endpoint: GET /projects/:id/issues
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings. - * @param itemsPerPage the number of Project instances that will be fetched per page. - * @return the Pager of issues in the specified range. - * @throws GitLabApiException if any exception occurs - */ - public Pager getIssues(Object projectIdOrPath, IssueFilter filter, int itemsPerPage) throws GitLabApiException { - GitLabApiForm formData = filter.getQueryParams(); - return (new Pager(this, Issue.class, itemsPerPage, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "issues")); - } - - /** - * Get a Stream of project's issues. - * - *
GitLab Endpoint: GET /projects/:id/issues
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings - * @return a Stream of issues in the specified range. - * @throws GitLabApiException if any exception occurs - */ - public Stream getIssuesStream(Object projectIdOrPath, IssueFilter filter) throws GitLabApiException { - return (getIssues(projectIdOrPath, filter, getDefaultPerPage()).stream()); - } - - /** - * Get all issues the authenticated user has access to. - * By default it returns only issues created by the current user. - * - *
GitLab Endpoint: GET /issues
- * - * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings - * @return the list of issues in the specified range. - * @throws GitLabApiException if any exception occurs - */ - public List getIssues(IssueFilter filter) throws GitLabApiException { - return (getIssues(filter, getDefaultPerPage()).all()); - } - - /** - * Get all issues the authenticated user has access to. - * By default it returns only issues created by the current user. - * - *
GitLab Endpoint: GET /issues
- * - * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings. - * @param page the page to get. - * @param perPage the number of projects per page. - * @return the list of issues in the specified range. - * @throws GitLabApiException if any exception occurs - */ - public List getIssues(IssueFilter filter, int page, int perPage) throws GitLabApiException { - GitLabApiForm formData = filter.getQueryParams(page, perPage); - Response response = get(Response.Status.OK, formData.asMap(), "issues"); - return (response.readEntity(new GenericType>() {})); - } - - /** - * Get all issues the authenticated user has access to. - * By default it returns only issues created by the current user. - * - *
GitLab Endpoint: GET /issues
- * - * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings. - * @param itemsPerPage the number of Project instances that will be fetched per page. - * @return the Pager of issues in the specified range. - * @throws GitLabApiException if any exception occurs - */ - public Pager getIssues(IssueFilter filter, int itemsPerPage) throws GitLabApiException { - GitLabApiForm formData = filter.getQueryParams(); - return (new Pager(this, Issue.class, itemsPerPage, formData.asMap(), "issues")); - } - - /** - * Get all issues the authenticated user has access to. - * By default it returns only issues created by the current user. - * - *
GitLab Endpoint: GET /issues
- * - * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings - * @return the Stream of issues in the specified range. - * @throws GitLabApiException if any exception occurs - */ - public Stream getIssuesStream(IssueFilter filter) throws GitLabApiException { - return (getIssues(filter, getDefaultPerPage()).stream()); - } - - /** - * Get a list of a group’s issues. - * - *
GitLab Endpoint: GET /groups/:id/issues
- * - * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance - * @return a List of issues for the specified group - * @throws GitLabApiException if any exception occurs - */ - public List getGroupIssues(Object groupIdOrPath) throws GitLabApiException { - return (getGroupIssues(groupIdOrPath, null, getDefaultPerPage()).all()); - } - - /** - * Get a Pager of groups's issues. - * - *
GitLab Endpoint: GET /groups/:id/issues
- * - * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance - * @param itemsPerPage the number of Issue instances that will be fetched per page. - * @return the Pager of issues for the specified group - * @throws GitLabApiException if any exception occurs - */ - public Pager getGroupIssues(Object groupIdOrPath, int itemsPerPage) throws GitLabApiException { - return (getGroupIssues(groupIdOrPath, null, itemsPerPage)); - } - - /** - * Get a Stream of a group’s issues. - * - *
GitLab Endpoint: GET /groups/:id/issues
- * - * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance - * @return a Stream of issues for the specified group and filter - * @throws GitLabApiException if any exception occurs - */ - public Stream getGroupIssuesStream(Object groupIdOrPath) throws GitLabApiException { - return (getGroupIssues(groupIdOrPath, null, getDefaultPerPage()).stream()); - } - - /** - * Get a list of a group’s issues. - * - *
GitLab Endpoint: GET /groups/:id/issues
- * - * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance - * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings. - * @return a List of issues for the specified group and filter - * @throws GitLabApiException if any exception occurs - */ - public List getGroupIssues(Object groupIdOrPath, IssueFilter filter) throws GitLabApiException { - return (getGroupIssues(groupIdOrPath, filter, getDefaultPerPage()).all()); - } - - /** - * Get a list of groups's issues. - * - *
GitLab Endpoint: GET /groups/:id/issues
- * - * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance - * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings. - * @param itemsPerPage the number of Issue instances that will be fetched per page. - * @return the Pager of issues for the specified group and filter - * @throws GitLabApiException if any exception occurs - */ - public Pager getGroupIssues(Object groupIdOrPath, IssueFilter filter, int itemsPerPage) throws GitLabApiException { - GitLabApiForm formData = (filter != null ? filter.getQueryParams() : new GitLabApiForm()); - return (new Pager(this, Issue.class, itemsPerPage, formData.asMap(), - "groups", getGroupIdOrPath(groupIdOrPath), "issues")); - } - - /** - * Get a Stream of a group’s issues. - * - *
GitLab Endpoint: GET /groups/:id/issues
- * - * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance - * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings. - * @return a Stream of issues for the specified group and filter - * @throws GitLabApiException if any exception occurs - */ - public Stream getGroupIssuesStream(Object groupIdOrPath, IssueFilter filter) throws GitLabApiException { - return (getGroupIssues(groupIdOrPath, filter, getDefaultPerPage()).stream()); - } - - /** - * Get a single project issue. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the internal ID of a project's issue - * @return the specified Issue instance - * @throws GitLabApiException if any exception occurs - */ - public Issue getIssue(Object projectIdOrPath, Long issueIid) throws GitLabApiException { - Response response = get(Response.Status.OK, getDefaultPerPageParam(), - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid); - return (response.readEntity(Issue.class)); - } - - /** - * Get a single project issue as an Optional instance. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the internal ID of a project's issue - * @return the specified Issue as an Optional instance - */ - public Optional getOptionalIssue(Object projectIdOrPath, Long issueIid) { - try { - return (Optional.ofNullable(getIssue(projectIdOrPath, issueIid))); - } catch (GitLabApiException glae) { - return (GitLabApi.createOptionalFromException(glae)); - } - } - - /** - * Create an issue for the project. - * - *
GitLab Endpoint: POST /projects/:id/issues
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param title the title of an issue, required - * @param description the description of an issue, optional - * @return an instance of Issue - * @throws GitLabApiException if any exception occurs - */ - public Issue createIssue(Object projectIdOrPath, String title, String description) throws GitLabApiException { - return (createIssue(projectIdOrPath, title, description, null, null, null, null, null, null, null, null)); + public IssuesApi(final GitLabApi gitLabApi) { + super(gitLabApi); + } + + /** + * Get all issues the authenticated user has access to. Only returns issues created by the current + * user. + * + *
GitLab Endpoint: GET /issues
+ * + * @return a list of user's issues + * @throws GitLabApiException if any exception occurs + */ + public List getIssues() throws GitLabApiException { + return (getIssues(getDefaultPerPage()).all()); + } + + /** + * Get all issues the authenticated user has access to using the specified page and per page + * setting. Only returns issues created by the current user. + * + *
GitLab Endpoint: GET /issues
+ * + * @param page the page to get + * @param perPage the number of issues per page + * @return the list of issues in the specified range + * @throws GitLabApiException if any exception occurs + */ + public List getIssues(final int page, final int perPage) throws GitLabApiException { + final Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "issues"); + return (response.readEntity(new GenericType>() {})); + } + + /** + * Get a Pager of all issues the authenticated user has access to. Only returns issues created by + * the current user. + * + *
GitLab Endpoint: GET /issues
+ * + * r + * + * @param itemsPerPage the number of issues per page + * @return the Pager of issues in the specified range + * @throws GitLabApiException if any exception occurs + */ + public Pager getIssues(final int itemsPerPage) throws GitLabApiException { + return (new Pager(this, Issue.class, itemsPerPage, null, "issues")); + } + + /** + * Get all issues the authenticated user has access to as a Stream. Only returns issues created by + * the current user. + * + *
GitLab Endpoint: GET /issues
+ * + * @return a Stream of user's issues + * @throws GitLabApiException if any exception occurs + */ + public Stream getIssuesStream() throws GitLabApiException { + return (getIssues(getDefaultPerPage()).stream()); + } + + /** + * Get a list of project's issues. + * + *
GitLab Endpoint: GET /projects/:id/issues
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @return a list of project's issues + * @throws GitLabApiException if any exception occurs + */ + public List getIssues(final Object projectIdOrPath) throws GitLabApiException { + return (getIssues(projectIdOrPath, getDefaultPerPage()).all()); + } + + /** + * Get a list of project's issues using the specified page and per page settings. + * + *
GitLab Endpoint: GET /projects/:id/issues
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param page the page to get + * @param perPage the number of issues per page + * @return the list of issues in the specified range + * @throws GitLabApiException if any exception occurs + */ + public List getIssues(final Object projectIdOrPath, final int page, final int perPage) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getPageQueryParams(page, perPage), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues"); + return (response.readEntity(new GenericType>() {})); + } + + /** + * Get a Pager of project's issues. + * + *
GitLab Endpoint: GET /projects/:id/issues
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param itemsPerPage the number of issues per page + * @return the Pager of issues in the specified range + * @throws GitLabApiException if any exception occurs + */ + public Pager getIssues(final Object projectIdOrPath, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, + Issue.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues")); + } + + /** + * Get a Stream of project's issues. Only returns the first page + * + *
GitLab Endpoint: GET /projects/:id/issues
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @return a Stream of project's issues + * @throws GitLabApiException if any exception occurs + */ + public Stream getIssuesStream(final Object projectIdOrPath) throws GitLabApiException { + return (getIssues(projectIdOrPath, getDefaultPerPage()).stream()); + } + + /** + * Get a list of project's issues. + * + *
GitLab Endpoint: GET /projects/:id/issues
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings + * @return the list of issues in the specified range. + * @throws GitLabApiException if any exception occurs + */ + public List getIssues(final Object projectIdOrPath, final IssueFilter filter) + throws GitLabApiException { + return (getIssues(projectIdOrPath, filter, getDefaultPerPage()).all()); + } + + /** + * Get a list of project's issues. + * + *
GitLab Endpoint: GET /projects/:id/issues
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings. + * @param page the page to get. + * @param perPage the number of projects per page. + * @return the list of issues in the specified range. + * @throws GitLabApiException if any exception occurs + */ + public List getIssues( + final Object projectIdOrPath, final IssueFilter filter, final int page, final int perPage) + throws GitLabApiException { + final GitLabApiForm formData = filter.getQueryParams(page, perPage); + final Response response = + get( + Response.Status.OK, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues"); + return (response.readEntity(new GenericType>() {})); + } + + /** + * Get a list of project's issues. + * + *
GitLab Endpoint: GET /projects/:id/issues
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings. + * @param itemsPerPage the number of Project instances that will be fetched per page. + * @return the Pager of issues in the specified range. + * @throws GitLabApiException if any exception occurs + */ + public Pager getIssues( + final Object projectIdOrPath, final IssueFilter filter, final int itemsPerPage) + throws GitLabApiException { + final GitLabApiForm formData = filter.getQueryParams(); + return (new Pager( + this, + Issue.class, + itemsPerPage, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues")); + } + + /** + * Get a Stream of project's issues. + * + *
GitLab Endpoint: GET /projects/:id/issues
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings + * @return a Stream of issues in the specified range. + * @throws GitLabApiException if any exception occurs + */ + public Stream getIssuesStream(final Object projectIdOrPath, final IssueFilter filter) + throws GitLabApiException { + return (getIssues(projectIdOrPath, filter, getDefaultPerPage()).stream()); + } + + /** + * Get all issues the authenticated user has access to. By default it returns only issues created + * by the current user. + * + *
GitLab Endpoint: GET /issues
+ * + * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings + * @return the list of issues in the specified range. + * @throws GitLabApiException if any exception occurs + */ + public List getIssues(final IssueFilter filter) throws GitLabApiException { + return (getIssues(filter, getDefaultPerPage()).all()); + } + + /** + * Get all issues the authenticated user has access to. By default it returns only issues created + * by the current user. + * + *
GitLab Endpoint: GET /issues
+ * + * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings. + * @param page the page to get. + * @param perPage the number of projects per page. + * @return the list of issues in the specified range. + * @throws GitLabApiException if any exception occurs + */ + public List getIssues(final IssueFilter filter, final int page, final int perPage) + throws GitLabApiException { + final GitLabApiForm formData = filter.getQueryParams(page, perPage); + final Response response = get(Response.Status.OK, formData.asMap(), "issues"); + return (response.readEntity(new GenericType>() {})); + } + + /** + * Get all issues the authenticated user has access to. By default it returns only issues created + * by the current user. + * + *
GitLab Endpoint: GET /issues
+ * + * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings. + * @param itemsPerPage the number of Project instances that will be fetched per page. + * @return the Pager of issues in the specified range. + * @throws GitLabApiException if any exception occurs + */ + public Pager getIssues(final IssueFilter filter, final int itemsPerPage) + throws GitLabApiException { + final GitLabApiForm formData = filter.getQueryParams(); + return (new Pager(this, Issue.class, itemsPerPage, formData.asMap(), "issues")); + } + + /** + * Get all issues the authenticated user has access to. By default it returns only issues created + * by the current user. + * + *
GitLab Endpoint: GET /issues
+ * + * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings + * @return the Stream of issues in the specified range. + * @throws GitLabApiException if any exception occurs + */ + public Stream getIssuesStream(final IssueFilter filter) throws GitLabApiException { + return (getIssues(filter, getDefaultPerPage()).stream()); + } + + /** + * Get a list of a group’s issues. + * + *
GitLab Endpoint: GET /groups/:id/issues
+ * + * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance + * @return a List of issues for the specified group + * @throws GitLabApiException if any exception occurs + */ + public List getGroupIssues(final Object groupIdOrPath) throws GitLabApiException { + return (getGroupIssues(groupIdOrPath, null, getDefaultPerPage()).all()); + } + + /** + * Get a Pager of groups's issues. + * + *
GitLab Endpoint: GET /groups/:id/issues
+ * + * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance + * @param itemsPerPage the number of Issue instances that will be fetched per page. + * @return the Pager of issues for the specified group + * @throws GitLabApiException if any exception occurs + */ + public Pager getGroupIssues(final Object groupIdOrPath, final int itemsPerPage) + throws GitLabApiException { + return (getGroupIssues(groupIdOrPath, null, itemsPerPage)); + } + + /** + * Get a Stream of a group’s issues. + * + *
GitLab Endpoint: GET /groups/:id/issues
+ * + * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance + * @return a Stream of issues for the specified group and filter + * @throws GitLabApiException if any exception occurs + */ + public Stream getGroupIssuesStream(final Object groupIdOrPath) throws GitLabApiException { + return (getGroupIssues(groupIdOrPath, null, getDefaultPerPage()).stream()); + } + + /** + * Get a list of a group’s issues. + * + *
GitLab Endpoint: GET /groups/:id/issues
+ * + * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance + * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings. + * @return a List of issues for the specified group and filter + * @throws GitLabApiException if any exception occurs + */ + public List getGroupIssues(final Object groupIdOrPath, final IssueFilter filter) + throws GitLabApiException { + return (getGroupIssues(groupIdOrPath, filter, getDefaultPerPage()).all()); + } + + /** + * Get a list of groups's issues. + * + *
GitLab Endpoint: GET /groups/:id/issues
+ * + * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance + * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings. + * @param itemsPerPage the number of Issue instances that will be fetched per page. + * @return the Pager of issues for the specified group and filter + * @throws GitLabApiException if any exception occurs + */ + public Pager getGroupIssues( + final Object groupIdOrPath, final IssueFilter filter, final int itemsPerPage) + throws GitLabApiException { + final GitLabApiForm formData = (filter != null ? filter.getQueryParams() : new GitLabApiForm()); + return (new Pager( + this, + Issue.class, + itemsPerPage, + formData.asMap(), + "groups", + getGroupIdOrPath(groupIdOrPath), + "issues")); + } + + /** + * Get a Stream of a group’s issues. + * + *
GitLab Endpoint: GET /groups/:id/issues
+ * + * @param groupIdOrPath the group in the form of an Long(ID), String(path), or Group instance + * @param filter {@link IssueFilter} a IssueFilter instance with the filter settings. + * @return a Stream of issues for the specified group and filter + * @throws GitLabApiException if any exception occurs + */ + public Stream getGroupIssuesStream(final Object groupIdOrPath, final IssueFilter filter) + throws GitLabApiException { + return (getGroupIssues(groupIdOrPath, filter, getDefaultPerPage()).stream()); + } + + /** + * Get a single project issue. + * + *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param issueIid the internal ID of a project's issue + * @return the specified Issue instance + * @throws GitLabApiException if any exception occurs + */ + public Issue getIssue(final Object projectIdOrPath, final Long issueIid) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getDefaultPerPageParam(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid); + return (response.readEntity(Issue.class)); + } + + /** + * Get a single project issue as an Optional instance. + * + *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param issueIid the internal ID of a project's issue + * @return the specified Issue as an Optional instance + */ + public Optional getOptionalIssue(final Object projectIdOrPath, final Long issueIid) { + try { + return (Optional.ofNullable(getIssue(projectIdOrPath, issueIid))); + } catch (final GitLabApiException glae) { + return (GitLabApi.createOptionalFromException(glae)); } - - /** - * Create an issue for the project. - * - *
GitLab Endpoint: POST /projects/:id/issues
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param title the issue title of an issue, required - * @param description the description of an issue, optional - * @param confidential set the issue to be confidential, default is false, optional - * @param assigneeIds the IDs of the users to assign issue, optional - * @param milestoneId the ID of a milestone to assign issue, optional - * @param labels comma-separated label names for an issue, optional - * @param createdAt the date the issue was created at, optional - * @param dueDate the due date, optional - * @param mergeRequestToResolveId the IID of a merge request in which to resolve all issues. This will fill the issue with a default - * description and mark all discussions as resolved. When passing a description or title, these values will take precedence over the default values. Optional - * @param discussionToResolveId the ID of a discussion to resolve. This will fill in the issue with a default description and mark the discussion as resolved. - * Use in combination with merge_request_to_resolve_discussions_of. Optional - * @return an instance of Issue - * @throws GitLabApiException if any exception occurs - */ - public Issue createIssue(Object projectIdOrPath, String title, String description, Boolean confidential, List assigneeIds, Long milestoneId, String labels, - Date createdAt, Date dueDate, Long mergeRequestToResolveId, Long discussionToResolveId) throws GitLabApiException { - - return (createIssue(projectIdOrPath, title, description, confidential, assigneeIds, milestoneId, labels, createdAt, dueDate, mergeRequestToResolveId, discussionToResolveId, null)); - } - - /** - * Create an issue for the project. - * - *
GitLab Endpoint: POST /projects/:id/issues
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param title the issue title of an issue, required - * @param description the description of an issue, optional - * @param confidential set the issue to be confidential, default is false, optional - * @param assigneeIds the IDs of the users to assign issue, optional - * @param milestoneId the ID of a milestone to assign issue, optional - * @param labels comma-separated label names for an issue, optional - * @param createdAt the date the issue was created at, optional - * @param dueDate the due date, optional - * @param mergeRequestToResolveId the IID of a merge request in which to resolve all issues. This will fill the issue with a default - * description and mark all discussions as resolved. When passing a description or title, these values will take precedence over the default values. Optional - * @param discussionToResolveId the ID of a discussion to resolve. This will fill in the issue with a default description and mark the discussion as resolved. - * Use in combination with merge_request_to_resolve_discussions_of. Optional - * @param iterationTitle the iteration title of an issue, optional - * @return an instance of Issue - * @throws GitLabApiException if any exception occurs - */ - public Issue createIssue(Object projectIdOrPath, String title, String description, Boolean confidential, List assigneeIds, Long milestoneId, String labels, - Date createdAt, Date dueDate, Long mergeRequestToResolveId, Long discussionToResolveId, String iterationTitle) throws GitLabApiException { - - GitLabApiForm formData = new GitLabApiForm() + } + + /** + * Create an issue for the project. + * + *
GitLab Endpoint: POST /projects/:id/issues
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param title the title of an issue, required + * @param description the description of an issue, optional + * @return an instance of Issue + * @throws GitLabApiException if any exception occurs + */ + public Issue createIssue( + final Object projectIdOrPath, final String title, final String description) + throws GitLabApiException { + return (createIssue( + projectIdOrPath, title, description, null, null, null, null, null, null, null, null)); + } + + /** + * Create an issue for the project. + * + *
GitLab Endpoint: POST /projects/:id/issues
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param title the issue title of an issue, required + * @param description the description of an issue, optional + * @param confidential set the issue to be confidential, default is false, optional + * @param assigneeIds the IDs of the users to assign issue, optional + * @param milestoneId the ID of a milestone to assign issue, optional + * @param labels comma-separated label names for an issue, optional + * @param createdAt the date the issue was created at, optional + * @param dueDate the due date, optional + * @param mergeRequestToResolveId the IID of a merge request in which to resolve all issues. This + * will fill the issue with a default description and mark all discussions as resolved. When + * passing a description or title, these values will take precedence over the default values. + * Optional + * @param discussionToResolveId the ID of a discussion to resolve. This will fill in the issue + * with a default description and mark the discussion as resolved. Use in combination with + * merge_request_to_resolve_discussions_of. Optional + * @return an instance of Issue + * @throws GitLabApiException if any exception occurs + */ + public Issue createIssue( + final Object projectIdOrPath, + final String title, + final String description, + final Boolean confidential, + final List assigneeIds, + final Long milestoneId, + final String labels, + final Date createdAt, + final Date dueDate, + final Long mergeRequestToResolveId, + final Long discussionToResolveId) + throws GitLabApiException { + + return (createIssue( + projectIdOrPath, + title, + description, + confidential, + assigneeIds, + milestoneId, + labels, + createdAt, + dueDate, + mergeRequestToResolveId, + discussionToResolveId, + null)); + } + + /** + * Create an issue for the project. + * + *
GitLab Endpoint: POST /projects/:id/issues
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param title the issue title of an issue, required + * @param description the description of an issue, optional + * @param confidential set the issue to be confidential, default is false, optional + * @param assigneeIds the IDs of the users to assign issue, optional + * @param milestoneId the ID of a milestone to assign issue, optional + * @param labels comma-separated label names for an issue, optional + * @param createdAt the date the issue was created at, optional + * @param dueDate the due date, optional + * @param mergeRequestToResolveId the IID of a merge request in which to resolve all issues. This + * will fill the issue with a default description and mark all discussions as resolved. When + * passing a description or title, these values will take precedence over the default values. + * Optional + * @param discussionToResolveId the ID of a discussion to resolve. This will fill in the issue + * with a default description and mark the discussion as resolved. Use in combination with + * merge_request_to_resolve_discussions_of. Optional + * @param iterationTitle the iteration title of an issue, optional + * @return an instance of Issue + * @throws GitLabApiException if any exception occurs + */ + public Issue createIssue( + final Object projectIdOrPath, + final String title, + final String description, + final Boolean confidential, + final List assigneeIds, + final Long milestoneId, + final String labels, + final Date createdAt, + final Date dueDate, + final Long mergeRequestToResolveId, + final Long discussionToResolveId, + final String iterationTitle) + throws GitLabApiException { + + final GitLabApiForm formData = + new GitLabApiForm() .withParam("title", title, true) .withParam("description", description) .withParam("confidential", confidential) @@ -462,592 +580,838 @@ public Issue createIssue(Object projectIdOrPath, String title, String descriptio .withParam("merge_request_to_resolve_discussions_of", mergeRequestToResolveId) .withParam("discussion_to_resolve", discussionToResolveId) .withParam("iteration_title", iterationTitle); - Response response = post(Response.Status.CREATED, formData, "projects", getProjectIdOrPath(projectIdOrPath), "issues"); - return (response.readEntity(Issue.class)); - } - - /** - * Closes an existing project issue. - * - *
GitLab Endpoint: PUT /projects/:id/issues/:issue_iid
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance, required - * @param issueIid the issue IID to update, required - * @return an instance of the updated Issue - * @throws GitLabApiException if any exception occurs - */ - public Issue closeIssue(Object projectIdOrPath, Long issueIid) throws GitLabApiException { - - if (issueIid == null) { - throw new RuntimeException("issue IID cannot be null"); - } - - GitLabApiForm formData = new GitLabApiForm().withParam("state_event", StateEvent.CLOSE); - Response response = put(Response.Status.OK, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid); - return (response.readEntity(Issue.class)); - } - - /** - * Updates an existing project issue. This call can also be used to mark an issue as closed. - * - *
GitLab Endpoint: PUT /projects/:id/issues/:issue_iid
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance, required - * @param issueIid the issue IID to update, required - * @param title the title of an issue, optional - * @param description the description of an issue, optional - * @param confidential set the issue to be confidential, default is false, optional - * @param assigneeIds the IDs of the users to assign issue, optional - * @param milestoneId the ID of a milestone to assign issue, optional - * @param labels comma-separated label names for an issue, optional - * @param stateEvent the state event of an issue. Set close to close the issue and reopen to reopen it, optional - * @param updatedAt sets the updated date, requires admin or project owner rights, optional - * @param dueDate the due date, optional - * @return an instance of the updated Issue - * @throws GitLabApiException if any exception occurs - */ - public Issue updateIssue(Object projectIdOrPath, Long issueIid, String title, String description, Boolean confidential, List assigneeIds, - Long milestoneId, String labels, StateEvent stateEvent, Date updatedAt, Date dueDate) throws GitLabApiException { - - if (issueIid == null) { - throw new RuntimeException("issue IID cannot be null"); - } - - GitLabApiForm formData = new GitLabApiForm() - .withParam("title", title) - .withParam("description", description) - .withParam("confidential", confidential) - .withParam("assignee_ids", assigneeIds) - .withParam("milestone_id", milestoneId) - .withParam("labels", labels) - .withParam("state_event", stateEvent) - .withParam("updated_at", updatedAt) - .withParam("due_date", dueDate); - Response response = put(Response.Status.OK, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid); - return (response.readEntity(Issue.class)); - } - - /** - * Updates an existing project issue. This call can also be used to mark an issue as closed. - * - *
GitLab Endpoint: PUT /projects/:id/issues/:issue_iid
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance, required - * @param issueIid the issue IID to update, required - * @param assigneeId the ID of the user to assign issue to, required - * @return an instance of the updated Issue - * @throws GitLabApiException if any exception occurs - */ - public Issue assignIssue(Object projectIdOrPath, Long issueIid, Long assigneeId) throws GitLabApiException { - - if (issueIid == null) { - throw new RuntimeException("issue IID cannot be null"); - } - - GitLabApiForm formData = new GitLabApiForm().withParam("assignee_ids", Collections.singletonList(assigneeId)); - Response response = put(Response.Status.OK, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid); - return (response.readEntity(Issue.class)); - } - - /** - * Delete an issue. - * - *
GitLab Endpoint: DELETE /projects/:id/issues/:issue_iid
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance, required - * @param issueIid the internal ID of a project's issue - * @throws GitLabApiException if any exception occurs - */ - public void deleteIssue(Object projectIdOrPath, Long issueIid) throws GitLabApiException { - - if (issueIid == null) { - throw new RuntimeException("issue IID cannot be null"); - } - - Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT); - delete(expectedStatus, getDefaultPerPageParam(), "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid); - } - - /** - * Sets an estimated time of work in this issue - * - *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/time_estimate
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance, required - * @param issueIid the internal ID of a project's issue - * @param duration estimated time in seconds - * @return a TimeSTats instance - * @throws GitLabApiException if any exception occurs - */ - public TimeStats estimateTime(Object projectIdOrPath, Long issueIid, int duration) throws GitLabApiException { - return (estimateTime(projectIdOrPath, issueIid, new Duration(duration))); - } - - /** - * Sets an estimated time of work in this issue - * - *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/time_estimate
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance, required - * @param issueIid the internal ID of a project's issue - * @param duration Human readable format, e.g. 3h30m - * @return a TimeSTats instance - * @throws GitLabApiException if any exception occurs - */ - public TimeStats estimateTime(Object projectIdOrPath, Long issueIid, String duration) throws GitLabApiException { - return (estimateTime(projectIdOrPath, issueIid, new Duration(duration))); - } - - /** - * Sets an estimated time of work in this issue - * - *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/time_estimate
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the internal ID of a project's issue - * @param duration set the estimate of time to this duration - * @return a TimeSTats instance - * @throws GitLabApiException if any exception occurs - */ - public TimeStats estimateTime(Object projectIdOrPath, Long issueIid, Duration duration) throws GitLabApiException { - - if (issueIid == null) { - throw new RuntimeException("issue IID cannot be null"); - } - - String durationString = (duration != null ? DurationUtils.toString(duration.getSeconds(), false) : null); - GitLabApiForm formData = new GitLabApiForm().withParam("duration", durationString, true); - - Response response = post(Response.Status.OK, formData.asMap(), - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "time_estimate"); - return (response.readEntity(TimeStats.class)); - } - - /** - * Resets the estimated time for this issue to 0 seconds. - * - *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/reset_time_estimate
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the internal ID of a project's issue - * @return a TimeSTats instance - * @throws GitLabApiException if any exception occurs - */ - public TimeStats resetEstimatedTime(Object projectIdOrPath, Long issueIid) throws GitLabApiException { - - if (issueIid == null) { - throw new RuntimeException("issue IID cannot be null"); - } - - Response response = post(Response.Status.OK, new GitLabApiForm().asMap(), "projects", - getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "reset_time_estimate"); - return (response.readEntity(TimeStats.class)); - } - - /** - * Adds spent time for this issue - * - *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/add_spent_time
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the internal ID of a project's issue - * @param duration the duration in seconds - * @return a TimeSTats instance - * @throws GitLabApiException if any exception occurs - */ - public TimeStats addSpentTime(Object projectIdOrPath, Long issueIid, int duration) throws GitLabApiException { - return (addSpentTime(projectIdOrPath, issueIid, new Duration(duration))); - } - - /** - * Adds spent time for this issue - * - *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/add_spent_time
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the internal ID of a project's issue - * @param duration Human readable format, e.g. 3h30m - * @return a TimeSTats instance - * @throws GitLabApiException if any exception occurs - */ - public TimeStats addSpentTime(Object projectIdOrPath, Long issueIid, String duration) throws GitLabApiException { - return (addSpentTime(projectIdOrPath, issueIid, new Duration(duration))); - } - - /** - * Adds spent time for this issue - * - *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/add_spent_time
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the internal ID of a project's issue - * @param duration the duration of time spent - * @return a TimeSTats instance - * @throws GitLabApiException if any exception occurs - */ - public TimeStats addSpentTime(Object projectIdOrPath, Long issueIid, Duration duration) throws GitLabApiException { - - if (issueIid == null) { - throw new RuntimeException("issue IID cannot be null"); - } - - String durationString = (duration != null ? DurationUtils.toString(duration.getSeconds(), false) : null); - GitLabApiForm formData = new GitLabApiForm().withParam("duration", durationString, true); - - Response response = post(Response.Status.CREATED, formData.asMap(), - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "add_spent_time"); - return (response.readEntity(TimeStats.class)); - } - - /** - * Resets the total spent time for this issue to 0 seconds. - * - *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/reset_spent_time
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the internal ID of a project's issue - * @return a TimeSTats instance - * @throws GitLabApiException if any exception occurs - */ - public TimeStats resetSpentTime(Object projectIdOrPath, Long issueIid) throws GitLabApiException { - - if (issueIid == null) { - throw new RuntimeException("issue IID cannot be null"); - } - - Response response = post(Response.Status.OK, new GitLabApiForm().asMap(), - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "reset_spent_time"); - return (response.readEntity(TimeStats.class)); - } - - /** - * Get time tracking stats. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/time_stats
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the internal ID of a project's issue - * @return a TimeStats instance - * @throws GitLabApiException if any exception occurs - */ - public TimeStats getTimeTrackingStats(Object projectIdOrPath, Long issueIid) throws GitLabApiException { - - if (issueIid == null) { - throw new RuntimeException("issue IID cannot be null"); - } - - Response response = get(Response.Status.OK, new GitLabApiForm().asMap(), - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "time_stats"); - return (response.readEntity(TimeStats.class)); - } - - /** - * Get time tracking stats as an Optional instance - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/time_stats
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the internal ID of a project's issue - * @return a TimeStats as an Optional instance - */ - public Optional getOptionalTimeTrackingStats(Object projectIdOrPath, Long issueIid) { - try { - return (Optional.ofNullable(getTimeTrackingStats(projectIdOrPath, issueIid))); - } catch (GitLabApiException glae) { - return (GitLabApi.createOptionalFromException(glae)); - } - } - - /** - * Get list containing all the merge requests that will close issue when merged. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/closed_by
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param issueIid the internal ID of a project's issue - * @return a List containing all the merge requests what will close the issue when merged. - * @throws GitLabApiException if any exception occurs - */ - public List getClosedByMergeRequests(Object projectIdOrPath, Long issueIid) throws GitLabApiException { - return (getClosedByMergeRequests(projectIdOrPath, issueIid, getDefaultPerPage()).all()); - } - - /** - * Get list containing all the merge requests that will close issue when merged. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/closed_by
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param issueIid the internal ID of a project's issue - * @param page the page to get - * @param perPage the number of issues per page - * @return a List containing all the merge requests what will close the issue when merged. - * @throws GitLabApiException if any exception occurs - */ - public List getClosedByMergeRequests(Object projectIdOrPath, Long issueIid, int page, int perPage) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "closed_by"); - return (response.readEntity(new GenericType>() { })); - } - - /** - * Get a Pager containing all the merge requests that will close issue when merged. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/closed_by
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param issueIid the internal ID of a project's issue - * @param itemsPerPage the number of Issue instances that will be fetched per page - * @return a Pager containing all the issues that would be closed by merging the provided merge request - * @throws GitLabApiException if any exception occurs - */ - public Pager getClosedByMergeRequests(Object projectIdOrPath, Long issueIid, int itemsPerPage) throws GitLabApiException { - return new Pager(this, MergeRequest.class, itemsPerPage, null, - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "closed_by"); - } - - /** - * Get list containing all the merge requests that will close issue when merged. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/closed_by
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param issueIid the internal ID of a project's issue - * @return a List containing all the merge requests what will close the issue when merged. - * @throws GitLabApiException if any exception occurs - */ - public Stream getClosedByMergeRequestsStream(Object projectIdOrPath, Long issueIid) throws GitLabApiException { - return (getClosedByMergeRequests(projectIdOrPath, issueIid, getDefaultPerPage()).stream()); + final Response response = + post( + Response.Status.CREATED, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues"); + return (response.readEntity(Issue.class)); + } + + /** + * Closes an existing project issue. + * + *
GitLab Endpoint: PUT /projects/:id/issues/:issue_iid
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance, required + * @param issueIid the issue IID to update, required + * @return an instance of the updated Issue + * @throws GitLabApiException if any exception occurs + */ + public Issue closeIssue(final Object projectIdOrPath, final Long issueIid) + throws GitLabApiException { + + if (issueIid == null) { + throw new RuntimeException("issue IID cannot be null"); } - /** - * Get a list of related issues of a given issue, sorted by the relationship creation datetime (ascending). - * Issues will be filtered according to the user authorizations. - * - *

NOTE: Only available in GitLab Starter, GitLab Bronze, and higher tiers.

- * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/links
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the internal ID of a project's issue - * @return a list of related issues of a given issue, sorted by the relationship creation datetime (ascending) - * @throws GitLabApiException if any exception occurs - */ - public List getIssueLinks(Object projectIdOrPath, Long issueIid) throws GitLabApiException { - return (getIssueLinks(projectIdOrPath, issueIid, getDefaultPerPage()).all()); + final GitLabApiForm formData = new GitLabApiForm().withParam("state_event", StateEvent.CLOSE); + final Response response = + put( + Response.Status.OK, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid); + return (response.readEntity(Issue.class)); + } + + /** + * Updates an existing project issue. This call can also be used to mark an issue as closed. + * + *
GitLab Endpoint: PUT /projects/:id/issues/:issue_iid
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance, required + * @param issueIid the issue IID to update, required + * @param title the title of an issue, optional + * @param description the description of an issue, optional + * @param confidential set the issue to be confidential, default is false, optional + * @param assigneeIds the IDs of the users to assign issue, optional + * @param milestoneId the ID of a milestone to assign issue, optional + * @param labels comma-separated label names for an issue, optional + * @param stateEvent the state event of an issue. Set close to close the issue and reopen to + * reopen it, optional + * @param updatedAt sets the updated date, requires admin or project owner rights, optional + * @param dueDate the due date, optional + * @return an instance of the updated Issue + * @throws GitLabApiException if any exception occurs + */ + public Issue updateIssue( + final Object projectIdOrPath, + final Long issueIid, + final String title, + final String description, + final Boolean confidential, + final List assigneeIds, + final Long milestoneId, + final String labels, + final StateEvent stateEvent, + final Date updatedAt, + final Date dueDate) + throws GitLabApiException { + + if (issueIid == null) { + throw new RuntimeException("issue IID cannot be null"); } - /** - * Get a Pager of related issues of a given issue, sorted by the relationship creation datetime (ascending). - * Issues will be filtered according to the user authorizations. - * - *

NOTE: Only available in GitLab Starter, GitLab Bronze, and higher tiers.

- * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/links
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the internal ID of a project's issue - * @param itemsPerPage the number of issues per page - * @return a Pager of related issues of a given issue, sorted by the relationship creation datetime (ascending) - * @throws GitLabApiException if any exception occurs - */ - public Pager getIssueLinks(Object projectIdOrPath, Long issueIid, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, Issue.class, itemsPerPage, null, - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "links")); - } - - /** - * Get a Stream of related issues of a given issue, sorted by the relationship creation datetime (ascending). - * Issues will be filtered according to the user authorizations. - * - *

NOTE: Only available in GitLab Starter, GitLab Bronze, and higher tiers.

- * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/links
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the internal ID of a project's issue - * @return a Stream of related issues of a given issue, sorted by the relationship creation datetime (ascending) - * @throws GitLabApiException if any exception occurs - */ - public Stream getIssueLinksStream(Object projectIdOrPath, Long issueIid) throws GitLabApiException { - return (getIssueLinks(projectIdOrPath, issueIid, getDefaultPerPage()).stream()); - } - - /** - * Creates a two-way relation between two issues. User must be allowed to update both issues in order to succeed. - * - *

NOTE: Only available in GitLab Starter, GitLab Bronze, and higher tiers.

- * - *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/links
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the internal ID of a project's issue - * @param targetProjectIdOrPath the project in the form of an Long(ID), String(path), or Project instance of the target project - * @param targetIssueIid the internal ID of a target project’s issue - * @return an instance of IssueLink holding the link relationship - * @throws GitLabApiException if any exception occurs - */ - public IssueLink createIssueLink(Object projectIdOrPath, Long issueIid, - Object targetProjectIdOrPath, Long targetIssueIid) throws GitLabApiException { - - GitLabApiForm formData = new GitLabApiForm() - .withParam("target_project_id", getProjectIdOrPath(targetProjectIdOrPath), true) - .withParam("target_issue_iid", targetIssueIid, true); - - Response response = post(Response.Status.OK, formData.asMap(), - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "links"); - return (response.readEntity(IssueLink.class)); - } - - /** - * Deletes an issue link, thus removes the two-way relationship. - * - *

NOTE: Only available in GitLab Starter, GitLab Bronze, and higher tiers.

- * - *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/links/:issue_link_id
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the internal ID of a project's issue, required - * @param issueLinkId the ID of an issue relationship, required - * @return an instance of IssueLink holding the deleted link relationship - * @throws GitLabApiException if any exception occurs - */ - public IssueLink deleteIssueLink(Object projectIdOrPath, Long issueIid, Long issueLinkId) throws GitLabApiException { - Response response = delete(Response.Status.OK, null, - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "links", issueLinkId); - return (response.readEntity(IssueLink.class)); - } - - /** - * Get list of participants for an issue. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/participants
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the IID of the issue to get the participants for - * @return a List containing all participants for the specified issue - * @throws GitLabApiException if any exception occurs - */ - public List getParticipants(Object projectIdOrPath, Long issueIid) throws GitLabApiException { - return (getParticipants(projectIdOrPath, issueIid, getDefaultPerPage()).all()); + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("title", title) + .withParam("description", description) + .withParam("confidential", confidential) + .withParam("assignee_ids", assigneeIds) + .withParam("milestone_id", milestoneId) + .withParam("labels", labels) + .withParam("state_event", stateEvent) + .withParam("updated_at", updatedAt) + .withParam("due_date", dueDate); + final Response response = + put( + Response.Status.OK, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid); + return (response.readEntity(Issue.class)); + } + + /** + * Updates an existing project issue. This call can also be used to mark an issue as closed. + * + *
GitLab Endpoint: PUT /projects/:id/issues/:issue_iid
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance, required + * @param issueIid the issue IID to update, required + * @param assigneeId the ID of the user to assign issue to, required + * @return an instance of the updated Issue + * @throws GitLabApiException if any exception occurs + */ + public Issue assignIssue(final Object projectIdOrPath, final Long issueIid, final Long assigneeId) + throws GitLabApiException { + + if (issueIid == null) { + throw new RuntimeException("issue IID cannot be null"); } - /** - * Get list of participants for an issue and in the specified page range. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/participants
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the IID of the issue to get the participants for - * @param page the page to get - * @param perPage the number of projects per page - * @return a List containing all participants for the specified issue - * @throws GitLabApiException if any exception occurs - */ - public List getParticipants(Object projectIdOrPath, Long issueIid, int page, int perPage) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "participants"); - return (response.readEntity(new GenericType>() { })); + final GitLabApiForm formData = + new GitLabApiForm().withParam("assignee_ids", Collections.singletonList(assigneeId)); + final Response response = + put( + Response.Status.OK, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid); + return (response.readEntity(Issue.class)); + } + + /** + * Delete an issue. + * + *
GitLab Endpoint: DELETE /projects/:id/issues/:issue_iid
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance, required + * @param issueIid the internal ID of a project's issue + * @throws GitLabApiException if any exception occurs + */ + public void deleteIssue(final Object projectIdOrPath, final Long issueIid) + throws GitLabApiException { + + if (issueIid == null) { + throw new RuntimeException("issue IID cannot be null"); } - /** - * Get a Pager of the participants for an issue. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/participants
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the IID of the issue to get the participants for - * @param itemsPerPage the number of Participant instances that will be fetched per page - * @return a Pager containing all participants for the specified issue - * @throws GitLabApiException if any exception occurs - */ - public Pager getParticipants(Object projectIdOrPath, Long issueIid, int itemsPerPage) throws GitLabApiException { - return new Pager(this, Participant.class, itemsPerPage, null, - "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "participants"); + final Response.Status expectedStatus = + (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT); + delete( + expectedStatus, + getDefaultPerPageParam(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid); + } + + /** + * Sets an estimated time of work in this issue + * + *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/time_estimate
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance, required + * @param issueIid the internal ID of a project's issue + * @param duration estimated time in seconds + * @return a TimeSTats instance + * @throws GitLabApiException if any exception occurs + */ + public TimeStats estimateTime( + final Object projectIdOrPath, final Long issueIid, final int duration) + throws GitLabApiException { + return (estimateTime(projectIdOrPath, issueIid, new Duration(duration))); + } + + /** + * Sets an estimated time of work in this issue + * + *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/time_estimate
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance, required + * @param issueIid the internal ID of a project's issue + * @param duration Human readable format, e.g. 3h30m + * @return a TimeSTats instance + * @throws GitLabApiException if any exception occurs + */ + public TimeStats estimateTime( + final Object projectIdOrPath, final Long issueIid, final String duration) + throws GitLabApiException { + return (estimateTime(projectIdOrPath, issueIid, new Duration(duration))); + } + + /** + * Sets an estimated time of work in this issue + * + *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/time_estimate
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param issueIid the internal ID of a project's issue + * @param duration set the estimate of time to this duration + * @return a TimeSTats instance + * @throws GitLabApiException if any exception occurs + */ + public TimeStats estimateTime( + final Object projectIdOrPath, final Long issueIid, final Duration duration) + throws GitLabApiException { + + if (issueIid == null) { + throw new RuntimeException("issue IID cannot be null"); } - /** - * Get Stream of participants for an issue. - * - *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/participants
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @param issueIid the IID of the issue to get the participants for - * @return a Stream containing all participants for the specified issue - * @throws GitLabApiException if any exception occurs - */ - public Stream getParticipantsStream(Object projectIdOrPath, Long issueIid) throws GitLabApiException { - return (getParticipants(projectIdOrPath, issueIid, getDefaultPerPage()).stream()); + final String durationString = + (duration != null ? DurationUtils.toString(duration.getSeconds(), false) : null); + final GitLabApiForm formData = new GitLabApiForm().withParam("duration", durationString, true); + + final Response response = + post( + Response.Status.OK, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "time_estimate"); + return (response.readEntity(TimeStats.class)); + } + + /** + * Resets the estimated time for this issue to 0 seconds. + * + *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/reset_time_estimate
+   * 
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param issueIid the internal ID of a project's issue + * @return a TimeSTats instance + * @throws GitLabApiException if any exception occurs + */ + public TimeStats resetEstimatedTime(final Object projectIdOrPath, final Long issueIid) + throws GitLabApiException { + + if (issueIid == null) { + throw new RuntimeException("issue IID cannot be null"); } - /** - * Gets issues count statistics on all issues the authenticated user has access to. By default it returns - * only issues created by the current user. To get all issues, use parameter scope=all. - * - *
GitLab Endpoint: GET /issues_statistics
- * - * @param filter {@link IssuesStatisticsFilter} a IssuesStatisticsFilter instance with the filter settings. - * @return an IssuesStatistics instance with the statistics for the matched issues. - * @throws GitLabApiException if any exception occurs - */ - public IssuesStatistics getIssuesStatistics(IssuesStatisticsFilter filter) throws GitLabApiException { - GitLabApiForm formData = filter.getQueryParams(); - Response response = get(Response.Status.OK, formData.asMap(), "issues_statistics"); - return (response.readEntity(IssuesStatistics.class)); + final Response response = + post( + Response.Status.OK, + new GitLabApiForm().asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "reset_time_estimate"); + return (response.readEntity(TimeStats.class)); + } + + /** + * Adds spent time for this issue + * + *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/add_spent_time
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param issueIid the internal ID of a project's issue + * @param duration the duration in seconds + * @return a TimeSTats instance + * @throws GitLabApiException if any exception occurs + */ + public TimeStats addSpentTime( + final Object projectIdOrPath, final Long issueIid, final int duration) + throws GitLabApiException { + return (addSpentTime(projectIdOrPath, issueIid, new Duration(duration))); + } + + /** + * Adds spent time for this issue + * + *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/add_spent_time
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param issueIid the internal ID of a project's issue + * @param duration Human readable format, e.g. 3h30m + * @return a TimeSTats instance + * @throws GitLabApiException if any exception occurs + */ + public TimeStats addSpentTime( + final Object projectIdOrPath, final Long issueIid, final String duration) + throws GitLabApiException { + return (addSpentTime(projectIdOrPath, issueIid, new Duration(duration))); + } + + /** + * Adds spent time for this issue + * + *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/add_spent_time
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param issueIid the internal ID of a project's issue + * @param duration the duration of time spent + * @return a TimeSTats instance + * @throws GitLabApiException if any exception occurs + */ + public TimeStats addSpentTime( + final Object projectIdOrPath, final Long issueIid, final Duration duration) + throws GitLabApiException { + + if (issueIid == null) { + throw new RuntimeException("issue IID cannot be null"); } - /** - * Gets issues count statistics for given group. - * - *
GitLab Endpoint: GET /groups/:groupId/issues_statistics
- * - * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path, required - * @param filter {@link IssuesStatisticsFilter} a IssuesStatisticsFilter instance with the filter settings - * @return an IssuesStatistics instance with the statistics for the matched issues - * @throws GitLabApiException if any exception occurs - */ - public IssuesStatistics getGroupIssuesStatistics(Object groupIdOrPath, IssuesStatisticsFilter filter) throws GitLabApiException { - GitLabApiForm formData = filter.getQueryParams(); - Response response = get(Response.Status.OK, formData.asMap(), "groups", this.getGroupIdOrPath(groupIdOrPath), "issues_statistics"); - return (response.readEntity(IssuesStatistics.class)); + final String durationString = + (duration != null ? DurationUtils.toString(duration.getSeconds(), false) : null); + final GitLabApiForm formData = new GitLabApiForm().withParam("duration", durationString, true); + + final Response response = + post( + Response.Status.CREATED, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "add_spent_time"); + return (response.readEntity(TimeStats.class)); + } + + /** + * Resets the total spent time for this issue to 0 seconds. + * + *
GitLab Endpoint: POST /projects/:id/issues/:issue_iid/reset_spent_time
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param issueIid the internal ID of a project's issue + * @return a TimeSTats instance + * @throws GitLabApiException if any exception occurs + */ + public TimeStats resetSpentTime(final Object projectIdOrPath, final Long issueIid) + throws GitLabApiException { + + if (issueIid == null) { + throw new RuntimeException("issue IID cannot be null"); } - /** - * Gets issues count statistics for given project. - * - *
GitLab Endpoint: GET /projects/:projectId/issues_statistics
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance, required - * @param filter {@link IssuesStatisticsFilter} a IssuesStatisticsFilter instance with the filter settings. - * @return an IssuesStatistics instance with the statistics for the matched issues - * @throws GitLabApiException if any exception occurs - */ - public IssuesStatistics geProjectIssuesStatistics(Object projectIdOrPath, IssuesStatisticsFilter filter) throws GitLabApiException { - GitLabApiForm formData = filter.getQueryParams(); - Response response = get(Response.Status.OK, formData.asMap(), "projects", this.getProjectIdOrPath(projectIdOrPath), "issues_statistics"); - return (response.readEntity(IssuesStatistics.class)); + final Response response = + post( + Response.Status.OK, + new GitLabApiForm().asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "reset_spent_time"); + return (response.readEntity(TimeStats.class)); + } + + /** + * Get time tracking stats. + * + *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/time_stats
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param issueIid the internal ID of a project's issue + * @return a TimeStats instance + * @throws GitLabApiException if any exception occurs + */ + public TimeStats getTimeTrackingStats(final Object projectIdOrPath, final Long issueIid) + throws GitLabApiException { + + if (issueIid == null) { + throw new RuntimeException("issue IID cannot be null"); } - /** - *

Moves an issue to a different project. If the target project equals the source project or - * the user has insufficient permissions to move an issue, error 400 together with an - * explaining error message is returned.

- * - *

If a given label and/or milestone with the same name also exists in the target project, - * it will then be assigned to the issue that is being moved.

- * - *
GitLab Endpoint: POST /projects/:projectId/issues/:issue_iid/move
- * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance, required - * @param issueIid the IID of the issue to move - * @param toProjectId the ID of the project to move the issue to - * @return an Issue instance for the moved issue - * @throws GitLabApiException if any exception occurs - */ - public Issue moveIssue(Object projectIdOrPath, Long issueIid, Object toProjectId) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm().withParam("to_project_id", toProjectId, true); - Response response = post(Response.Status.OK, formData, - "projects", this.getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "move"); - return (response.readEntity(Issue.class)); + final Response response = + get( + Response.Status.OK, + new GitLabApiForm().asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "time_stats"); + return (response.readEntity(TimeStats.class)); + } + + /** + * Get time tracking stats as an Optional instance + * + *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/time_stats
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param issueIid the internal ID of a project's issue + * @return a TimeStats as an Optional instance + */ + public Optional getOptionalTimeTrackingStats( + final Object projectIdOrPath, final Long issueIid) { + try { + return (Optional.ofNullable(getTimeTrackingStats(projectIdOrPath, issueIid))); + } catch (final GitLabApiException glae) { + return (GitLabApi.createOptionalFromException(glae)); } + } + + /** + * Get list containing all the merge requests that will close issue when merged. + * + *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/closed_by
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param issueIid the internal ID of a project's issue + * @return a List containing all the merge requests what will close the issue when merged. + * @throws GitLabApiException if any exception occurs + */ + public List getClosedByMergeRequests( + final Object projectIdOrPath, final Long issueIid) throws GitLabApiException { + return (getClosedByMergeRequests(projectIdOrPath, issueIid, getDefaultPerPage()).all()); + } + + /** + * Get list containing all the merge requests that will close issue when merged. + * + *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/closed_by
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param issueIid the internal ID of a project's issue + * @param page the page to get + * @param perPage the number of issues per page + * @return a List containing all the merge requests what will close the issue when merged. + * @throws GitLabApiException if any exception occurs + */ + public List getClosedByMergeRequests( + final Object projectIdOrPath, final Long issueIid, final int page, final int perPage) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getPageQueryParams(page, perPage), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "closed_by"); + return (response.readEntity(new GenericType>() {})); + } + + /** + * Get a Pager containing all the merge requests that will close issue when merged. + * + *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/closed_by
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param issueIid the internal ID of a project's issue + * @param itemsPerPage the number of Issue instances that will be fetched per page + * @return a Pager containing all the issues that would be closed by merging the provided merge + * request + * @throws GitLabApiException if any exception occurs + */ + public Pager getClosedByMergeRequests( + final Object projectIdOrPath, final Long issueIid, final int itemsPerPage) + throws GitLabApiException { + return new Pager( + this, + MergeRequest.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "closed_by"); + } + + /** + * Get list containing all the merge requests that will close issue when merged. + * + *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/closed_by
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param issueIid the internal ID of a project's issue + * @return a List containing all the merge requests what will close the issue when merged. + * @throws GitLabApiException if any exception occurs + */ + public Stream getClosedByMergeRequestsStream( + final Object projectIdOrPath, final Long issueIid) throws GitLabApiException { + return (getClosedByMergeRequests(projectIdOrPath, issueIid, getDefaultPerPage()).stream()); + } + + /** + * Get a list of related issues of a given issue, sorted by the relationship creation datetime + * (ascending). Issues will be filtered according to the user authorizations. + * + *

NOTE: Only available in GitLab Starter, GitLab Bronze, and higher tiers. + * + *

GitLab Endpoint: GET /projects/:id/issues/:issue_iid/links
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param issueIid the internal ID of a project's issue + * @return a list of related issues of a given issue, sorted by the relationship creation datetime + * (ascending) + * @throws GitLabApiException if any exception occurs + */ + public List getIssueLinks(final Object projectIdOrPath, final Long issueIid) + throws GitLabApiException { + return (getIssueLinks(projectIdOrPath, issueIid, getDefaultPerPage()).all()); + } + + /** + * Get a Pager of related issues of a given issue, sorted by the relationship creation datetime + * (ascending). Issues will be filtered according to the user authorizations. + * + *

NOTE: Only available in GitLab Starter, GitLab Bronze, and higher tiers. + * + *

GitLab Endpoint: GET /projects/:id/issues/:issue_iid/links
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param issueIid the internal ID of a project's issue + * @param itemsPerPage the number of issues per page + * @return a Pager of related issues of a given issue, sorted by the relationship creation + * datetime (ascending) + * @throws GitLabApiException if any exception occurs + */ + public Pager getIssueLinks( + final Object projectIdOrPath, final Long issueIid, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, + Issue.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "links")); + } + + /** + * Get a Stream of related issues of a given issue, sorted by the relationship creation datetime + * (ascending). Issues will be filtered according to the user authorizations. + * + *

NOTE: Only available in GitLab Starter, GitLab Bronze, and higher tiers. + * + *

GitLab Endpoint: GET /projects/:id/issues/:issue_iid/links
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param issueIid the internal ID of a project's issue + * @return a Stream of related issues of a given issue, sorted by the relationship creation + * datetime (ascending) + * @throws GitLabApiException if any exception occurs + */ + public Stream getIssueLinksStream(final Object projectIdOrPath, final Long issueIid) + throws GitLabApiException { + return (getIssueLinks(projectIdOrPath, issueIid, getDefaultPerPage()).stream()); + } + + /** + * Creates a two-way relation between two issues. User must be allowed to update both issues in + * order to succeed. + * + *

NOTE: Only available in GitLab Starter, GitLab Bronze, and higher tiers. + * + *

GitLab Endpoint: POST /projects/:id/issues/:issue_iid/links
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param issueIid the internal ID of a project's issue + * @param targetProjectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance of the target project + * @param targetIssueIid the internal ID of a target project’s issue + * @return an instance of IssueLink holding the link relationship + * @throws GitLabApiException if any exception occurs + */ + public IssueLink createIssueLink( + final Object projectIdOrPath, + final Long issueIid, + final Object targetProjectIdOrPath, + final Long targetIssueIid) + throws GitLabApiException { + + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("target_project_id", getProjectIdOrPath(targetProjectIdOrPath), true) + .withParam("target_issue_iid", targetIssueIid, true); + + final Response response = + post( + Response.Status.OK, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "links"); + return (response.readEntity(IssueLink.class)); + } + + /** + * Deletes an issue link, thus removes the two-way relationship. + * + *

NOTE: Only available in GitLab Starter, GitLab Bronze, and higher tiers. + * + *

GitLab Endpoint: POST /projects/:id/issues/:issue_iid/links/:issue_link_id
+   * 
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param issueIid the internal ID of a project's issue, required + * @param issueLinkId the ID of an issue relationship, required + * @return an instance of IssueLink holding the deleted link relationship + * @throws GitLabApiException if any exception occurs + */ + public IssueLink deleteIssueLink( + final Object projectIdOrPath, final Long issueIid, final Long issueLinkId) + throws GitLabApiException { + final Response response = + delete( + Response.Status.OK, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "links", + issueLinkId); + return (response.readEntity(IssueLink.class)); + } + + /** + * Get list of participants for an issue. + * + *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/participants
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param issueIid the IID of the issue to get the participants for + * @return a List containing all participants for the specified issue + * @throws GitLabApiException if any exception occurs + */ + public List getParticipants(final Object projectIdOrPath, final Long issueIid) + throws GitLabApiException { + return (getParticipants(projectIdOrPath, issueIid, getDefaultPerPage()).all()); + } + + /** + * Get list of participants for an issue and in the specified page range. + * + *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/participants
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param issueIid the IID of the issue to get the participants for + * @param page the page to get + * @param perPage the number of projects per page + * @return a List containing all participants for the specified issue + * @throws GitLabApiException if any exception occurs + */ + public List getParticipants( + final Object projectIdOrPath, final Long issueIid, final int page, final int perPage) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getPageQueryParams(page, perPage), + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "participants"); + return (response.readEntity(new GenericType>() {})); + } + + /** + * Get a Pager of the participants for an issue. + * + *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/participants
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param issueIid the IID of the issue to get the participants for + * @param itemsPerPage the number of Participant instances that will be fetched per page + * @return a Pager containing all participants for the specified issue + * @throws GitLabApiException if any exception occurs + */ + public Pager getParticipants( + final Object projectIdOrPath, final Long issueIid, final int itemsPerPage) + throws GitLabApiException { + return new Pager( + this, + Participant.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "participants"); + } + + /** + * Get Stream of participants for an issue. + * + *
GitLab Endpoint: GET /projects/:id/issues/:issue_iid/participants
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance + * @param issueIid the IID of the issue to get the participants for + * @return a Stream containing all participants for the specified issue + * @throws GitLabApiException if any exception occurs + */ + public Stream getParticipantsStream( + final Object projectIdOrPath, final Long issueIid) throws GitLabApiException { + return (getParticipants(projectIdOrPath, issueIid, getDefaultPerPage()).stream()); + } + + /** + * Gets issues count statistics on all issues the authenticated user has access to. By default it + * returns only issues created by the current user. To get all issues, use parameter scope=all. + * + *
GitLab Endpoint: GET /issues_statistics
+ * + * @param filter {@link IssuesStatisticsFilter} a IssuesStatisticsFilter instance with the filter + * settings. + * @return an IssuesStatistics instance with the statistics for the matched issues. + * @throws GitLabApiException if any exception occurs + */ + public IssuesStatistics getIssuesStatistics(final IssuesStatisticsFilter filter) + throws GitLabApiException { + final GitLabApiForm formData = filter.getQueryParams(); + final Response response = get(Response.Status.OK, formData.asMap(), "issues_statistics"); + return (response.readEntity(IssuesStatistics.class)); + } + + /** + * Gets issues count statistics for given group. + * + *
GitLab Endpoint: GET /groups/:groupId/issues_statistics
+ * + * @param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID + * or path, required + * @param filter {@link IssuesStatisticsFilter} a IssuesStatisticsFilter instance with the filter + * settings + * @return an IssuesStatistics instance with the statistics for the matched issues + * @throws GitLabApiException if any exception occurs + */ + public IssuesStatistics getGroupIssuesStatistics( + final Object groupIdOrPath, final IssuesStatisticsFilter filter) throws GitLabApiException { + final GitLabApiForm formData = filter.getQueryParams(); + final Response response = + get( + Response.Status.OK, + formData.asMap(), + "groups", + this.getGroupIdOrPath(groupIdOrPath), + "issues_statistics"); + return (response.readEntity(IssuesStatistics.class)); + } + + /** + * Gets issues count statistics for given project. + * + *
GitLab Endpoint: GET /projects/:projectId/issues_statistics
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance, required + * @param filter {@link IssuesStatisticsFilter} a IssuesStatisticsFilter instance with the filter + * settings. + * @return an IssuesStatistics instance with the statistics for the matched issues + * @throws GitLabApiException if any exception occurs + */ + public IssuesStatistics geProjectIssuesStatistics( + final Object projectIdOrPath, final IssuesStatisticsFilter filter) throws GitLabApiException { + final GitLabApiForm formData = filter.getQueryParams(); + final Response response = + get( + Response.Status.OK, + formData.asMap(), + "projects", + this.getProjectIdOrPath(projectIdOrPath), + "issues_statistics"); + return (response.readEntity(IssuesStatistics.class)); + } + + /** + * Moves an issue to a different project. If the target project equals the source project or the + * user has insufficient permissions to move an issue, error 400 together with an explaining error + * message is returned. + * + *

If a given label and/or milestone with the same name also exists in the target project, it + * will then be assigned to the issue that is being moved. + * + *

GitLab Endpoint: POST /projects/:projectId/issues/:issue_iid/move
+ * + * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project + * instance, required + * @param issueIid the IID of the issue to move + * @param toProjectId the ID of the project to move the issue to + * @return an Issue instance for the moved issue + * @throws GitLabApiException if any exception occurs + */ + public Issue moveIssue( + final Object projectIdOrPath, final Long issueIid, final Object toProjectId) + throws GitLabApiException { + final GitLabApiForm formData = + new GitLabApiForm().withParam("to_project_id", toProjectId, true); + final Response response = + post( + Response.Status.OK, + formData, + "projects", + this.getProjectIdOrPath(projectIdOrPath), + "issues", + issueIid, + "move"); + return (response.readEntity(Issue.class)); + } } diff --git a/src/main/java/org/gitlab4j/api/JobApi.java b/src/main/java/org/gitlab4j/api/JobApi.java index 6b2d4d4c0..8cd6f0b84 100644 --- a/src/main/java/org/gitlab4j/api/JobApi.java +++ b/src/main/java/org/gitlab4j/api/JobApi.java @@ -1,5 +1,10 @@ package org.gitlab4j.api; +import jakarta.ws.rs.core.Form; +import jakarta.ws.rs.core.GenericType; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.Response.Status; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -9,585 +14,827 @@ import java.util.List; import java.util.Optional; import java.util.stream.Stream; -import javax.ws.rs.core.Form; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; import org.gitlab4j.api.models.ArtifactsFile; import org.gitlab4j.api.models.Job; import org.gitlab4j.api.models.JobAttributes; -/** - * This class provides an entry point to all the GitLab API job calls. - */ +/** This class provides an entry point to all the GitLab API job calls. */ public class JobApi extends AbstractApi implements Constants { - public JobApi(GitLabApi gitLabApi) { - super(gitLabApi); + public JobApi(final GitLabApi gitLabApi) { + super(gitLabApi); + } + + /** + * Get a list of jobs in a project. + * + *
GitLab Endpoint: GET /projects/:id/jobs
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @return a list containing the jobs for the specified project ID + * @throws GitLabApiException if any exception occurs during execution + */ + public List getJobs(final Object projectIdOrPath) throws GitLabApiException { + return (getJobs(projectIdOrPath, getDefaultPerPage()).all()); + } + + /** + * Get a list of jobs in a project in the specified page range. + * + *
GitLab Endpoint: GET /projects/:id/jobs
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path to get the jobs for + * @param page the page to get + * @param perPage the number of Job instances per page + * @return a list containing the jobs for the specified project ID in the specified page range + * @throws GitLabApiException if any exception occurs during execution + */ + public List getJobs(final Object projectIdOrPath, final int page, final int perPage) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getPageQueryParams(page, perPage), + "projects", + getProjectIdOrPath(projectIdOrPath), + "jobs"); + return (response.readEntity(new GenericType>() {})); + } + + /** + * Get a Pager of jobs in a project. + * + *
GitLab Endpoint: GET /projects/:id/jobs
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path to get the jobs for + * @param itemsPerPage the number of Job instances that will be fetched per page + * @return a Pager containing the jobs for the specified project ID + * @throws GitLabApiException if any exception occurs during execution + */ + public Pager getJobs(final Object projectIdOrPath, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, + Job.class, + itemsPerPage, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "jobs")); + } + + /** + * Get a Stream of jobs in a project. + * + *
GitLab Endpoint: GET /projects/:id/jobs
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @return a Stream containing the jobs for the specified project ID + * @throws GitLabApiException if any exception occurs during execution + */ + public Stream getJobsStream(final Object projectIdOrPath) throws GitLabApiException { + return (getJobs(projectIdOrPath, getDefaultPerPage()).stream()); + } + + /** + * Get a list of jobs in a project. + * + *
GitLab Endpoint: GET /projects/:id/jobs
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path to get the jobs for + * @param scope the scope of jobs, one of: CREATED, PENDING, RUNNING, FAILED, SUCCESS, CANCELED, + * SKIPPED, MANUAL + * @return a list containing the jobs for the specified project ID + * @throws GitLabApiException if any exception occurs during execution + */ + public List getJobs(final Object projectIdOrPath, final JobScope scope) + throws GitLabApiException { + return (getJobs(projectIdOrPath, scope, getDefaultPerPage()).all()); + } + + /** + * Get a list of jobs in a project. + * + *
GitLab Endpoint: GET /projects/:id/jobs
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path to get the jobs for + * @param scope the scope of jobs, one of: CREATED, PENDING, RUNNING, FAILED, SUCCESS, CANCELED, + * SKIPPED, MANUAL + * @param itemsPerPage the number of Job instances that will be fetched per page + * @return a list containing the jobs for the specified project ID + * @throws GitLabApiException if any exception occurs during execution + */ + public Pager getJobs( + final Object projectIdOrPath, final JobScope scope, final int itemsPerPage) + throws GitLabApiException { + final GitLabApiForm formData = new GitLabApiForm().withParam("scope", scope); + return (new Pager( + this, + Job.class, + itemsPerPage, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "jobs")); + } + + /** + * Get a Stream of jobs in a project. + * + *
GitLab Endpoint: GET /projects/:id/jobs
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path to get the jobs for + * @param scope the scope of jobs, one of: CREATED, PENDING, RUNNING, FAILED, SUCCESS, CANCELED, + * SKIPPED, MANUAL + * @return a Stream containing the jobs for the specified project ID + * @throws GitLabApiException if any exception occurs during execution + */ + public Stream getJobsStream(final Object projectIdOrPath, final JobScope scope) + throws GitLabApiException { + return (getJobs(projectIdOrPath, scope, getDefaultPerPage()).stream()); + } + + /** + * Get a list of jobs in a pipeline. + * + *
GitLab Endpoint: GET /projects/:id/pipelines/:pipeline_id/jobs
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path to get the pipelines for + * @param pipelineId the pipeline ID to get the list of jobs for + * @return a list containing the jobs for the specified project ID and pipeline ID + * @throws GitLabApiException if any exception occurs during execution + */ + public List getJobsForPipeline(final Object projectIdOrPath, final long pipelineId) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getDefaultPerPageParam(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "pipelines", + pipelineId, + "jobs"); + return (response.readEntity(new GenericType>() {})); + } + + /** + * Get a list of jobs in a pipeline. + * + *
GitLab Endpoint: GET /projects/:id/pipelines/:pipeline_id/jobs
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path to get the pipelines for + * @param pipelineId the pipeline ID to get the list of jobs for + * @param scope the scope of jobs, one of: CREATED, PENDING, RUNNING, FAILED, SUCCESS, CANCELED, + * SKIPPED, MANUAL + * @return a list containing the jobs for the specified project ID and pipeline ID + * @throws GitLabApiException if any exception occurs during execution + */ + public List getJobsForPipeline( + final Object projectIdOrPath, final long pipelineId, final JobScope scope) + throws GitLabApiException { + final GitLabApiForm formData = + new GitLabApiForm() + .withParam("scope", scope) + .withParam(PER_PAGE_PARAM, getDefaultPerPage()); + final Response response = + get( + Response.Status.OK, + formData.asMap(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "pipelines", + pipelineId, + "jobs"); + return (response.readEntity(new GenericType>() {})); + } + + /** + * Get a Pager of jobs in a pipeline. + * + *
GitLab Endpoint: GET /projects/:id/pipelines/:pipeline_id/jobs
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path to get the pipelines for + * @param pipelineId the pipeline ID to get the list of jobs for + * @param itemsPerPage the number of Job instances that will be fetched per page + * @return a list containing the jobs for the specified project ID and pipeline ID + * @throws GitLabApiException if any exception occurs during execution + */ + public Pager getJobsForPipeline( + final Object projectIdOrPath, final long pipelineId, final int itemsPerPage) + throws GitLabApiException { + return (new Pager( + this, + Job.class, + itemsPerPage, + getDefaultPerPageParam(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "pipelines", + pipelineId, + "jobs")); + } + + /** + * Get a Stream of jobs in a pipeline. + * + *
GitLab Endpoint: GET /projects/:id/pipelines/:pipeline_id/jobs
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param pipelineId the pipeline ID to get the list of jobs for + * @return a Stream containing the jobs for the specified project ID + * @throws GitLabApiException if any exception occurs during execution + */ + public Stream getJobsStream(final Object projectIdOrPath, final long pipelineId) + throws GitLabApiException { + return (getJobsForPipeline(projectIdOrPath, pipelineId, getDefaultPerPage()).stream()); + } + + /** + * Get single job in a project. + * + *
GitLab Endpoint: GET /projects/:id/jobs/:job_id
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path to get the job for + * @param jobId the job ID to get + * @return a single job for the specified project ID + * @throws GitLabApiException if any exception occurs during execution + */ + public Job getJob(final Object projectIdOrPath, final Long jobId) throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "jobs", + jobId); + return (response.readEntity(Job.class)); + } + + /** + * Get single job in a project as an Optional instance. + * + *
GitLab Endpoint: GET /projects/:id/jobs/:job_id
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path to get the job for + * @param jobId the job ID to get + * @return a single job for the specified project ID as an Optional intance + */ + public Optional getOptionalJob(final Object projectIdOrPath, final Long jobId) { + try { + return (Optional.ofNullable(getJob(projectIdOrPath, jobId))); + } catch (final GitLabApiException glae) { + return (GitLabApi.createOptionalFromException(glae)); } - - /** - * Get a list of jobs in a project. - * - *
GitLab Endpoint: GET /projects/:id/jobs
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @return a list containing the jobs for the specified project ID - * @throws GitLabApiException if any exception occurs during execution - */ - public List getJobs(Object projectIdOrPath) throws GitLabApiException { - return (getJobs(projectIdOrPath, getDefaultPerPage()).all()); - } - - /** - * Get a list of jobs in a project in the specified page range. - * - *
GitLab Endpoint: GET /projects/:id/jobs
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path to get the jobs for - * @param page the page to get - * @param perPage the number of Job instances per page - * @return a list containing the jobs for the specified project ID in the specified page range - * @throws GitLabApiException if any exception occurs during execution - */ - public List getJobs(Object projectIdOrPath, int page, int perPage) throws GitLabApiException { - Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "projects", getProjectIdOrPath(projectIdOrPath), "jobs"); - return (response.readEntity(new GenericType>() {})); - } - - /** - * Get a Pager of jobs in a project. - * - *
GitLab Endpoint: GET /projects/:id/jobs
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path to get the jobs for - * @param itemsPerPage the number of Job instances that will be fetched per page - * @return a Pager containing the jobs for the specified project ID - * @throws GitLabApiException if any exception occurs during execution - */ - public Pager getJobs(Object projectIdOrPath, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, Job.class, itemsPerPage, null, "projects", getProjectIdOrPath(projectIdOrPath), "jobs")); - } - - /** - * Get a Stream of jobs in a project. - * - *
GitLab Endpoint: GET /projects/:id/jobs
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @return a Stream containing the jobs for the specified project ID - * @throws GitLabApiException if any exception occurs during execution - */ - public Stream getJobsStream(Object projectIdOrPath) throws GitLabApiException { - return (getJobs(projectIdOrPath, getDefaultPerPage()).stream()); + } + + /** + * Download the artifacts file from the given reference name and job provided the job finished + * successfully. The file will be saved to the specified directory. If the file already exists in + * the directory it will be overwritten. + * + *
GitLab Endpoint: GET /projects/:id/jobs/artifacts/:ref_name/download?job=name
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param ref the ref from a repository + * @param jobName the name of the job to download the artifacts for + * @param directory the File instance of the directory to save the file to, if null will use + * "java.io.tmpdir" + * @return a File instance pointing to the download of the specified artifacts file + * @throws GitLabApiException if any exception occurs + */ + public File downloadArtifactsFile( + final Object projectIdOrPath, final String ref, final String jobName, File directory) + throws GitLabApiException { + + final Form formData = new GitLabApiForm().withParam("job", jobName, true); + final Response response = + getWithAccepts( + Response.Status.OK, + formData.asMap(), + MediaType.MEDIA_TYPE_WILDCARD, + "projects", + getProjectIdOrPath(projectIdOrPath), + "jobs", + "artifacts", + urlEncode(ref), + "download"); + + try { + + if (directory == null) directory = new File(System.getProperty("java.io.tmpdir")); + + final String filename = jobName + "-artifacts.zip"; + final File file = new File(directory, filename); + + final InputStream in = response.readEntity(InputStream.class); + Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING); + return (file); + + } catch (final IOException ioe) { + throw new GitLabApiException(ioe); } - - /** - * Get a list of jobs in a project. - * - *
GitLab Endpoint: GET /projects/:id/jobs
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path to get the jobs for - * @param scope the scope of jobs, one of: CREATED, PENDING, RUNNING, FAILED, SUCCESS, CANCELED, SKIPPED, MANUAL - * @return a list containing the jobs for the specified project ID - * @throws GitLabApiException if any exception occurs during execution - */ - public List getJobs(Object projectIdOrPath, JobScope scope) throws GitLabApiException { - return (getJobs(projectIdOrPath, scope, getDefaultPerPage()).all()); - } - - /** - * Get a list of jobs in a project. - * - *
GitLab Endpoint: GET /projects/:id/jobs
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path to get the jobs for - * @param scope the scope of jobs, one of: CREATED, PENDING, RUNNING, FAILED, SUCCESS, CANCELED, SKIPPED, MANUAL - * @param itemsPerPage the number of Job instances that will be fetched per page - * @return a list containing the jobs for the specified project ID - * @throws GitLabApiException if any exception occurs during execution - */ - public Pager getJobs(Object projectIdOrPath, JobScope scope, int itemsPerPage) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm().withParam("scope", scope); - return (new Pager(this, Job.class, itemsPerPage, formData.asMap(), - "projects", getProjectIdOrPath(projectIdOrPath), "jobs")); + } + + /** + * Get an InputStream pointing to the artifacts file from the given reference name and job + * provided the job finished successfully. The file will be saved to the specified directory. If + * the file already exists in the directory it will be overwritten. + * + *
GitLab Endpoint: GET /projects/:id/jobs/artifacts/:ref_name/download?job=name
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param ref the ref from a repository + * @param jobName the name of the job to download the artifacts for + * @return an InputStream to read the specified artifacts file from + * @throws GitLabApiException if any exception occurs + */ + public InputStream downloadArtifactsFile( + final Object projectIdOrPath, final String ref, final String jobName) + throws GitLabApiException { + final Form formData = new GitLabApiForm().withParam("job", jobName, true); + final Response response = + getWithAccepts( + Response.Status.OK, + formData.asMap(), + MediaType.MEDIA_TYPE_WILDCARD, + "projects", + getProjectIdOrPath(projectIdOrPath), + "jobs", + "artifacts", + urlEncode(ref), + "download"); + return (response.readEntity(InputStream.class)); + } + + /** + * Download the job artifacts file for the specified job ID. The artifacts file will be saved in + * the specified directory with the following name pattern: job-{jobid}-artifacts.zip. If the file + * already exists in the directory it will be overwritten. + * + *
GitLab Endpoint: GET /projects/:id/jobs/:job_id/artifacts
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param jobId the job ID to get the artifacts for + * @param directory the File instance of the directory to save the file to, if null will use + * "java.io.tmpdir" + * @return a File instance pointing to the download of the specified job artifacts file + * @throws GitLabApiException if any exception occurs + */ + public File downloadArtifactsFile(final Object projectIdOrPath, final Long jobId, File directory) + throws GitLabApiException { + + final Response response = + getWithAccepts( + Response.Status.OK, + null, + MediaType.MEDIA_TYPE_WILDCARD, + "projects", + getProjectIdOrPath(projectIdOrPath), + "jobs", + jobId, + "artifacts"); + try { + + if (directory == null) directory = new File(System.getProperty("java.io.tmpdir")); + + final String filename = "job-" + jobId + "-artifacts.zip"; + final File file = new File(directory, filename); + + final InputStream in = response.readEntity(InputStream.class); + Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING); + return (file); + + } catch (final IOException ioe) { + throw new GitLabApiException(ioe); } - - /** - * Get a Stream of jobs in a project. - * - *
GitLab Endpoint: GET /projects/:id/jobs
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path to get the jobs for - * @param scope the scope of jobs, one of: CREATED, PENDING, RUNNING, FAILED, SUCCESS, CANCELED, SKIPPED, MANUAL - * @return a Stream containing the jobs for the specified project ID - * @throws GitLabApiException if any exception occurs during execution - */ - public Stream getJobsStream(Object projectIdOrPath, JobScope scope) throws GitLabApiException { - return (getJobs(projectIdOrPath, scope, getDefaultPerPage()).stream()); + } + + /** + * Get an InputStream pointing to the job artifacts file for the specified job ID. + * + *
GitLab Endpoint: GET /projects/:id/jobs/:job_id/artifacts
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param jobId the job ID to get the artifacts for + * @return an InputStream to read the specified job artifacts file + * @throws GitLabApiException if any exception occurs + */ + public InputStream downloadArtifactsFile(final Object projectIdOrPath, final Long jobId) + throws GitLabApiException { + final Response response = + getWithAccepts( + Response.Status.OK, + null, + MediaType.MEDIA_TYPE_WILDCARD, + "projects", + getProjectIdOrPath(projectIdOrPath), + "jobs", + jobId, + "artifacts"); + return (response.readEntity(InputStream.class)); + } + + /** + * Download a single artifact file from within the job's artifacts archive. + * + *

Only a single file is going to be extracted from the archive and streamed to a client. + * + *

GitLab Endpoint: GET /projects/:id/jobs/:job_id/artifacts/*artifact_path
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param jobId the unique job identifier + * @param artifactsFile an ArtifactsFile instance for the artifact to download + * @param directory the File instance of the directory to save the file to, if null will use + * "java.io.tmpdir" + * @return a File instance pointing to the download of the specified artifacts file + * @throws GitLabApiException if any exception occurs + */ + public File downloadArtifactsFile( + final Object projectIdOrPath, + final Long jobId, + final ArtifactsFile artifactsFile, + File directory) + throws GitLabApiException { + + final Response response = + get( + Response.Status.OK, + getDefaultPerPageParam(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "jobs", + jobId, + "artifacts", + artifactsFile.getFilename()); + try { + + if (directory == null) directory = new File(System.getProperty("java.io.tmpdir")); + + final String filename = artifactsFile.getFilename(); + final File file = new File(directory, filename); + + final InputStream in = response.readEntity(InputStream.class); + Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING); + return (file); + + } catch (final IOException ioe) { + throw new GitLabApiException(ioe); } - - /** - * Get a list of jobs in a pipeline. - * - *
GitLab Endpoint: GET /projects/:id/pipelines/:pipeline_id/jobs
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path to get the pipelines for - * @param pipelineId the pipeline ID to get the list of jobs for - * @return a list containing the jobs for the specified project ID and pipeline ID - * @throws GitLabApiException if any exception occurs during execution - */ - public List getJobsForPipeline(Object projectIdOrPath, long pipelineId) throws GitLabApiException { - Response response = get(Response.Status.OK, getDefaultPerPageParam(), - "projects", getProjectIdOrPath(projectIdOrPath), "pipelines", pipelineId, "jobs"); - return (response.readEntity(new GenericType>() {})); - } - - /** - * Get a list of jobs in a pipeline. - * - *
GitLab Endpoint: GET /projects/:id/pipelines/:pipeline_id/jobs
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path to get the pipelines for - * @param pipelineId the pipeline ID to get the list of jobs for - * @param scope the scope of jobs, one of: CREATED, PENDING, RUNNING, FAILED, SUCCESS, CANCELED, SKIPPED, MANUAL - * @return a list containing the jobs for the specified project ID and pipeline ID - * @throws GitLabApiException if any exception occurs during execution - */ - public List getJobsForPipeline(Object projectIdOrPath, long pipelineId, JobScope scope) throws GitLabApiException { - GitLabApiForm formData = new GitLabApiForm().withParam("scope", scope).withParam(PER_PAGE_PARAM, getDefaultPerPage()); - Response response = get(Response.Status.OK, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "pipelines", pipelineId, "jobs"); - return (response.readEntity(new GenericType>() {})); + } + + /** + * Download a single artifact file from within the job's artifacts archive. + * + *

Only a single file is going to be extracted from the archive and streamed to a client. + * + *

GitLab Endpoint: GET /projects/:id/jobs/:job_id/artifacts/*artifact_path
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param jobId the unique job identifier + * @param artifactsFile an ArtifactsFile instance for the artifact to download + * @return an InputStream to read the specified artifacts file from + * @throws GitLabApiException if any exception occurs + */ + public InputStream downloadArtifactsFile( + final Object projectIdOrPath, final Long jobId, final ArtifactsFile artifactsFile) + throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getDefaultPerPageParam(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "jobs", + jobId, + "artifacts", + artifactsFile.getFilename()); + return (response.readEntity(InputStream.class)); + } + + /** + * Download a single artifact file from within the job's artifacts archive. + * + *

Only a single file is going to be extracted from the archive and streamed to a client. + * + *

GitLab Endpoint: GET /projects/:id/jobs/:job_id/artifacts/*artifact_path
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param jobId the unique job identifier + * @param artifactPath the Path to a file inside the artifacts archive + * @param directory the File instance of the directory to save the file to, if null will use + * "java.io.tmpdir" + * @return a File instance pointing to the download of the specified artifacts file + * @throws GitLabApiException if any exception occurs + */ + public File downloadSingleArtifactsFile( + final Object projectIdOrPath, final Long jobId, final Path artifactPath, File directory) + throws GitLabApiException { + + final String path = artifactPath.toString().replace("\\", "/"); + final Response response = + get( + Response.Status.OK, + getDefaultPerPageParam(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "jobs", + jobId, + "artifacts", + path); + try { + + if (directory == null) directory = new File(System.getProperty("java.io.tmpdir")); + + final String filename = artifactPath.getFileName().toString(); + final File file = new File(directory, filename); + + final InputStream in = response.readEntity(InputStream.class); + Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING); + return (file); + + } catch (final IOException ioe) { + throw new GitLabApiException(ioe); } - - /** - * Get a Pager of jobs in a pipeline. - * - *
GitLab Endpoint: GET /projects/:id/pipelines/:pipeline_id/jobs
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path to get the pipelines for - * @param pipelineId the pipeline ID to get the list of jobs for - * @param itemsPerPage the number of Job instances that will be fetched per page - * @return a list containing the jobs for the specified project ID and pipeline ID - * @throws GitLabApiException if any exception occurs during execution - */ - public Pager getJobsForPipeline(Object projectIdOrPath, long pipelineId, int itemsPerPage) throws GitLabApiException { - return (new Pager(this, Job.class, itemsPerPage, getDefaultPerPageParam(), - "projects", getProjectIdOrPath(projectIdOrPath), "pipelines", pipelineId, "jobs")); - } - - /** - * Get a Stream of jobs in a pipeline. - *
GitLab Endpoint: GET /projects/:id/pipelines/:pipeline_id/jobs
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param pipelineId the pipeline ID to get the list of jobs for - * @return a Stream containing the jobs for the specified project ID - * @throws GitLabApiException if any exception occurs during execution - */ - public Stream getJobsStream(Object projectIdOrPath, long pipelineId) throws GitLabApiException { - return (getJobsForPipeline(projectIdOrPath, pipelineId, getDefaultPerPage()).stream()); - } - - /** - * Get single job in a project. - * - *
GitLab Endpoint: GET /projects/:id/jobs/:job_id
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path to get the job for - * @param jobId the job ID to get - * @return a single job for the specified project ID - * @throws GitLabApiException if any exception occurs during execution - */ - public Job getJob(Object projectIdOrPath, Long jobId) throws GitLabApiException { - Response response = get(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), "jobs", jobId); - return (response.readEntity(Job.class)); - } - - /** - * Get single job in a project as an Optional instance. - * - *
GitLab Endpoint: GET /projects/:id/jobs/:job_id
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path to get the job for - * @param jobId the job ID to get - * @return a single job for the specified project ID as an Optional intance - */ - public Optional getOptionalJob(Object projectIdOrPath, Long jobId) { - try { - return (Optional.ofNullable(getJob(projectIdOrPath, jobId))); - } catch (GitLabApiException glae) { - return (GitLabApi.createOptionalFromException(glae)); - } - } - - /** - * Download the artifacts file from the given reference name and job provided the job finished successfully. - * The file will be saved to the specified directory. If the file already exists in the directory it will - * be overwritten. - * - *
GitLab Endpoint: GET /projects/:id/jobs/artifacts/:ref_name/download?job=name
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param ref the ref from a repository - * @param jobName the name of the job to download the artifacts for - * @param directory the File instance of the directory to save the file to, if null will use "java.io.tmpdir" - * @return a File instance pointing to the download of the specified artifacts file - * @throws GitLabApiException if any exception occurs - */ - public File downloadArtifactsFile(Object projectIdOrPath, String ref, String jobName, File directory) throws GitLabApiException { - - Form formData = new GitLabApiForm().withParam("job", jobName, true); - Response response = getWithAccepts(Response.Status.OK, formData.asMap(), MediaType.MEDIA_TYPE_WILDCARD, - "projects", getProjectIdOrPath(projectIdOrPath), "jobs", "artifacts", urlEncode(ref), "download"); - - try { - - if (directory == null) - directory = new File(System.getProperty("java.io.tmpdir")); - - String filename = jobName + "-artifacts.zip"; - File file = new File(directory, filename); - - InputStream in = response.readEntity(InputStream.class); - Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING); - return (file); - - } catch (IOException ioe) { - throw new GitLabApiException(ioe); - } - } - - /** - * Get an InputStream pointing to the artifacts file from the given reference name and job - * provided the job finished successfully. The file will be saved to the specified directory. - * If the file already exists in the directory it will be overwritten. - * - *
GitLab Endpoint: GET /projects/:id/jobs/artifacts/:ref_name/download?job=name
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param ref the ref from a repository - * @param jobName the name of the job to download the artifacts for - * @return an InputStream to read the specified artifacts file from - * @throws GitLabApiException if any exception occurs - */ - public InputStream downloadArtifactsFile(Object projectIdOrPath, String ref, String jobName) throws GitLabApiException { - Form formData = new GitLabApiForm().withParam("job", jobName, true); - Response response = getWithAccepts(Response.Status.OK, formData.asMap(), MediaType.MEDIA_TYPE_WILDCARD, - "projects", getProjectIdOrPath(projectIdOrPath), "jobs", "artifacts", urlEncode(ref), "download"); - return (response.readEntity(InputStream.class)); - } - - /** - * Download the job artifacts file for the specified job ID. The artifacts file will be saved in the - * specified directory with the following name pattern: job-{jobid}-artifacts.zip. If the file already - * exists in the directory it will be overwritten. - * - *
GitLab Endpoint: GET /projects/:id/jobs/:job_id/artifacts
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param jobId the job ID to get the artifacts for - * @param directory the File instance of the directory to save the file to, if null will use "java.io.tmpdir" - * @return a File instance pointing to the download of the specified job artifacts file - * @throws GitLabApiException if any exception occurs - */ - public File downloadArtifactsFile(Object projectIdOrPath, Long jobId, File directory) throws GitLabApiException { - - Response response = getWithAccepts(Response.Status.OK, null, MediaType.MEDIA_TYPE_WILDCARD, - "projects", getProjectIdOrPath(projectIdOrPath), "jobs", jobId, "artifacts"); - try { - - if (directory == null) - directory = new File(System.getProperty("java.io.tmpdir")); - - String filename = "job-" + jobId + "-artifacts.zip"; - File file = new File(directory, filename); - - InputStream in = response.readEntity(InputStream.class); - Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING); - return (file); - - } catch (IOException ioe) { - throw new GitLabApiException(ioe); - } - } - - /** - * Get an InputStream pointing to the job artifacts file for the specified job ID. - * - *
GitLab Endpoint: GET /projects/:id/jobs/:job_id/artifacts
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param jobId the job ID to get the artifacts for - * @return an InputStream to read the specified job artifacts file - * @throws GitLabApiException if any exception occurs - */ - public InputStream downloadArtifactsFile(Object projectIdOrPath, Long jobId) throws GitLabApiException { - Response response = getWithAccepts(Response.Status.OK, null, MediaType.MEDIA_TYPE_WILDCARD, - "projects", getProjectIdOrPath(projectIdOrPath), "jobs", jobId, "artifacts"); - return (response.readEntity(InputStream.class)); - } - - /** - * Download a single artifact file from within the job's artifacts archive. - * - * Only a single file is going to be extracted from the archive and streamed to a client. - * - *
GitLab Endpoint: GET /projects/:id/jobs/:job_id/artifacts/*artifact_path
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param jobId the unique job identifier - * @param artifactsFile an ArtifactsFile instance for the artifact to download - * @param directory the File instance of the directory to save the file to, if null will use "java.io.tmpdir" - * @return a File instance pointing to the download of the specified artifacts file - * @throws GitLabApiException if any exception occurs - */ - public File downloadArtifactsFile(Object projectIdOrPath, Long jobId, ArtifactsFile artifactsFile, File directory) throws GitLabApiException { - - Response response = get(Response.Status.OK, getDefaultPerPageParam(), - "projects", getProjectIdOrPath(projectIdOrPath), "jobs", jobId, "artifacts", artifactsFile.getFilename()); - try { - - if (directory == null) - directory = new File(System.getProperty("java.io.tmpdir")); - - String filename = artifactsFile.getFilename(); - File file = new File(directory, filename); - - InputStream in = response.readEntity(InputStream.class); - Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING); - return (file); - - } catch (IOException ioe) { - throw new GitLabApiException(ioe); - } - } - - /** - * Download a single artifact file from within the job's artifacts archive. - * - * Only a single file is going to be extracted from the archive and streamed to a client. - * - *
GitLab Endpoint: GET /projects/:id/jobs/:job_id/artifacts/*artifact_path
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param jobId the unique job identifier - * @param artifactsFile an ArtifactsFile instance for the artifact to download - * @return an InputStream to read the specified artifacts file from - * @throws GitLabApiException if any exception occurs - */ - public InputStream downloadArtifactsFile(Object projectIdOrPath, Long jobId, ArtifactsFile artifactsFile) throws GitLabApiException { - Response response = get(Response.Status.OK, getDefaultPerPageParam(), - "projects", getProjectIdOrPath(projectIdOrPath), "jobs", jobId, "artifacts", artifactsFile.getFilename()); - return (response.readEntity(InputStream.class)); - } - - /** - * Download a single artifact file from within the job's artifacts archive. - * - * Only a single file is going to be extracted from the archive and streamed to a client. - * - *
GitLab Endpoint: GET /projects/:id/jobs/:job_id/artifacts/*artifact_path
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param jobId the unique job identifier - * @param artifactPath the Path to a file inside the artifacts archive - * @param directory the File instance of the directory to save the file to, if null will use "java.io.tmpdir" - * @return a File instance pointing to the download of the specified artifacts file - * @throws GitLabApiException if any exception occurs - */ - public File downloadSingleArtifactsFile(Object projectIdOrPath, Long jobId, Path artifactPath, File directory) throws GitLabApiException { - - String path = artifactPath.toString().replace("\\", "/"); - Response response = get(Response.Status.OK, getDefaultPerPageParam(), - "projects", getProjectIdOrPath(projectIdOrPath), "jobs", jobId, "artifacts", path); - try { - - if (directory == null) - directory = new File(System.getProperty("java.io.tmpdir")); - - String filename = artifactPath.getFileName().toString(); - File file = new File(directory, filename); - - InputStream in = response.readEntity(InputStream.class); - Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING); - return (file); - - } catch (IOException ioe) { - throw new GitLabApiException(ioe); - } - } - - /** - * Download a single artifact file from within the job's artifacts archive. - * - * Only a single file is going to be extracted from the archive and streamed to a client. - * - *
GitLab Endpoint: GET /projects/:id/jobs/:job_id/artifacts/*artifact_path
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param jobId the unique job identifier - * @param artifactPath the Path to a file inside the artifacts archive - * @return an InputStream to read the specified artifacts file from - * @throws GitLabApiException if any exception occurs - */ - public InputStream downloadSingleArtifactsFile(Object projectIdOrPath, Long jobId, Path artifactPath) throws GitLabApiException { - String path = artifactPath.toString().replace("\\", "/"); - Response response = get(Response.Status.OK, getDefaultPerPageParam(), - "projects", getProjectIdOrPath(projectIdOrPath), "jobs", jobId, "artifacts", path); - return (response.readEntity(InputStream.class)); - } - - /** - * Get a trace of a specific job of a project - * - *
GitLab Endpoint: GET /projects/:id/jobs/:id/trace
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * to get the specified job's trace for - * @param jobId the job ID to get the trace for - * @return a String containing the specified job's trace - * @throws GitLabApiException if any exception occurs during execution - */ - public String getTrace(Object projectIdOrPath, Long jobId) throws GitLabApiException { - Response response = get(Response.Status.OK, getDefaultPerPageParam(), - "projects", getProjectIdOrPath(projectIdOrPath), "jobs", jobId, "trace"); - return (response.readEntity(String.class)); - } - - /** - * Cancel specified job in a project. - * - *
GitLab Endpoint: POST /projects/:id/jobs/:job_id/cancel
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param jobId the ID to cancel job - * @return job instance which just canceled - * @throws GitLabApiException if any exception occurs during execution - * @deprecated replaced by {@link #cancelJob(Object, Long)} - */ - @Deprecated - public Job cancleJob(Object projectIdOrPath, Long jobId) throws GitLabApiException { - return (cancelJob(projectIdOrPath, jobId)); - } - - /** - * Cancel specified job in a project. - * - *
GitLab Endpoint: POST /projects/:id/jobs/:job_id/cancel
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param jobId the ID to cancel job - * @return job instance which just canceled - * @throws GitLabApiException if any exception occurs during execution - */ - public Job cancelJob(Object projectIdOrPath, Long jobId) throws GitLabApiException { - GitLabApiForm formData = null; - Response response = post(Response.Status.CREATED, formData, "projects", getProjectIdOrPath(projectIdOrPath), "jobs", jobId, "cancel"); - return (response.readEntity(Job.class)); - } - - /** - * Retry specified job in a project. - * - *
GitLab Endpoint: POST /projects/:id/jobs/:job_id/retry
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param jobId the ID to retry job - * @return job instance which just retried - * @throws GitLabApiException if any exception occurs during execution - */ - public Job retryJob(Object projectIdOrPath, Long jobId) throws GitLabApiException { - GitLabApiForm formData = null; - Response response = post(Status.CREATED, formData, "projects", getProjectIdOrPath(projectIdOrPath), "jobs", jobId, "retry"); - return (response.readEntity(Job.class)); - } - - /** - * Erase specified job in a project. - * - *
GitLab Endpoint: POST /projects/:id/jobs/:job_id/erase
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param jobId the ID to erase job - * @return job instance which just erased - * @throws GitLabApiException if any exception occurs during execution - */ - public Job eraseJob(Object projectIdOrPath, Long jobId) throws GitLabApiException { - GitLabApiForm formData = null; - Response response = post(Status.CREATED, formData, "projects", getProjectIdOrPath(projectIdOrPath), "jobs", jobId, "erase"); - return (response.readEntity(Job.class)); - } - - /** - * Play specified job in a project. - * - *
GitLab Endpoint: POST /projects/:id/jobs/:job_id/play
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param jobId the ID to play job - * @return job instance which just played - * @throws GitLabApiException if any exception occurs during execution - */ - public Job playJob(Object projectIdOrPath, Long jobId) throws GitLabApiException { - return playJob(projectIdOrPath, jobId, null); - } - - /** - * Play specified job with parameters in a project. - * - *
-     * GitLab Endpoint: POST /projects/:id/jobs/:job_id/play
-     * 
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID - * or path - * @param jobId the ID to play job - * @param jobAttributes attributes for the played job - * @return job instance which just played - * @throws GitLabApiException if any exception occurs during execution - */ - public Job playJob(Object projectIdOrPath, Long jobId, JobAttributes jobAttributes) - throws GitLabApiException { - Response response; - if (jobAttributes == null) { - GitLabApiForm formData = null; - response = post(Status.CREATED, formData, "projects", - getProjectIdOrPath(projectIdOrPath), "jobs", jobId, "play"); - } else { - response = post(Status.CREATED, jobAttributes, "projects", - getProjectIdOrPath(projectIdOrPath), "jobs", jobId, "play"); - } - return (response.readEntity(Job.class)); - } - - /** - * Prevents artifacts from being deleted when expiration is set. - * - *
GitLab Endpoint: POST /projects/:id/jobs/:job_id/keep
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param jobId the ID to keep artifacts for - * @return the Job instance that was just modified - * @throws GitLabApiException if any exception occurs during execution - */ - public Job keepArtifacts(Object projectIdOrPath, Long jobId) throws GitLabApiException { - GitLabApiForm formData = null; - Response response = post(Status.OK, formData, "projects", getProjectIdOrPath(projectIdOrPath), "jobs", jobId, "keep"); - return (response.readEntity(Job.class)); - } - - /** - * Delete artifacts of a job. - * - *
GitLab Endpoint: DELETE /projects/:id/jobs/:job_id/artifacts
- * - * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path - * @param jobId the ID to delete artifacts for - * @throws GitLabApiException if any exception occurs during execution - */ - public void deleteArtifacts(Object projectIdOrPath, Long jobId) throws GitLabApiException { - delete(Status.NO_CONTENT, null, "projects", getProjectIdOrPath(projectIdOrPath), "jobs", jobId, "artifacts"); + } + + /** + * Download a single artifact file from within the job's artifacts archive. + * + *

Only a single file is going to be extracted from the archive and streamed to a client. + * + *

GitLab Endpoint: GET /projects/:id/jobs/:job_id/artifacts/*artifact_path
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param jobId the unique job identifier + * @param artifactPath the Path to a file inside the artifacts archive + * @return an InputStream to read the specified artifacts file from + * @throws GitLabApiException if any exception occurs + */ + public InputStream downloadSingleArtifactsFile( + final Object projectIdOrPath, final Long jobId, final Path artifactPath) + throws GitLabApiException { + final String path = artifactPath.toString().replace("\\", "/"); + final Response response = + get( + Response.Status.OK, + getDefaultPerPageParam(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "jobs", + jobId, + "artifacts", + path); + return (response.readEntity(InputStream.class)); + } + + /** + * Get a trace of a specific job of a project + * + *
GitLab Endpoint: GET /projects/:id/jobs/:id/trace
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path to get the specified job's trace for + * @param jobId the job ID to get the trace for + * @return a String containing the specified job's trace + * @throws GitLabApiException if any exception occurs during execution + */ + public String getTrace(final Object projectIdOrPath, final Long jobId) throws GitLabApiException { + final Response response = + get( + Response.Status.OK, + getDefaultPerPageParam(), + "projects", + getProjectIdOrPath(projectIdOrPath), + "jobs", + jobId, + "trace"); + return (response.readEntity(String.class)); + } + + /** + * Cancel specified job in a project. + * + *
GitLab Endpoint: POST /projects/:id/jobs/:job_id/cancel
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param jobId the ID to cancel job + * @return job instance which just canceled + * @throws GitLabApiException if any exception occurs during execution + * @deprecated replaced by {@link #cancelJob(Object, Long)} + */ + @Deprecated + public Job cancleJob(final Object projectIdOrPath, final Long jobId) throws GitLabApiException { + return (cancelJob(projectIdOrPath, jobId)); + } + + /** + * Cancel specified job in a project. + * + *
GitLab Endpoint: POST /projects/:id/jobs/:job_id/cancel
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param jobId the ID to cancel job + * @return job instance which just canceled + * @throws GitLabApiException if any exception occurs during execution + */ + public Job cancelJob(final Object projectIdOrPath, final Long jobId) throws GitLabApiException { + final GitLabApiForm formData = null; + final Response response = + post( + Response.Status.CREATED, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "jobs", + jobId, + "cancel"); + return (response.readEntity(Job.class)); + } + + /** + * Retry specified job in a project. + * + *
GitLab Endpoint: POST /projects/:id/jobs/:job_id/retry
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param jobId the ID to retry job + * @return job instance which just retried + * @throws GitLabApiException if any exception occurs during execution + */ + public Job retryJob(final Object projectIdOrPath, final Long jobId) throws GitLabApiException { + final GitLabApiForm formData = null; + final Response response = + post( + Status.CREATED, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "jobs", + jobId, + "retry"); + return (response.readEntity(Job.class)); + } + + /** + * Erase specified job in a project. + * + *
GitLab Endpoint: POST /projects/:id/jobs/:job_id/erase
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param jobId the ID to erase job + * @return job instance which just erased + * @throws GitLabApiException if any exception occurs during execution + */ + public Job eraseJob(final Object projectIdOrPath, final Long jobId) throws GitLabApiException { + final GitLabApiForm formData = null; + final Response response = + post( + Status.CREATED, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "jobs", + jobId, + "erase"); + return (response.readEntity(Job.class)); + } + + /** + * Play specified job in a project. + * + *
GitLab Endpoint: POST /projects/:id/jobs/:job_id/play
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param jobId the ID to play job + * @return job instance which just played + * @throws GitLabApiException if any exception occurs during execution + */ + public Job playJob(final Object projectIdOrPath, final Long jobId) throws GitLabApiException { + return playJob(projectIdOrPath, jobId, null); + } + + /** + * Play specified job with parameters in a project. + * + *
+   * GitLab Endpoint: POST /projects/:id/jobs/:job_id/play
+   * 
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param jobId the ID to play job + * @param jobAttributes attributes for the played job + * @return job instance which just played + * @throws GitLabApiException if any exception occurs during execution + */ + public Job playJob( + final Object projectIdOrPath, final Long jobId, final JobAttributes jobAttributes) + throws GitLabApiException { + final Response response; + if (jobAttributes == null) { + final GitLabApiForm formData = null; + response = + post( + Status.CREATED, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "jobs", + jobId, + "play"); + } else { + response = + post( + Status.CREATED, + jobAttributes, + "projects", + getProjectIdOrPath(projectIdOrPath), + "jobs", + jobId, + "play"); } + return (response.readEntity(Job.class)); + } + + /** + * Prevents artifacts from being deleted when expiration is set. + * + *
GitLab Endpoint: POST /projects/:id/jobs/:job_id/keep
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param jobId the ID to keep artifacts for + * @return the Job instance that was just modified + * @throws GitLabApiException if any exception occurs during execution + */ + public Job keepArtifacts(final Object projectIdOrPath, final Long jobId) + throws GitLabApiException { + final GitLabApiForm formData = null; + final Response response = + post( + Status.OK, + formData, + "projects", + getProjectIdOrPath(projectIdOrPath), + "jobs", + jobId, + "keep"); + return (response.readEntity(Job.class)); + } + + /** + * Delete artifacts of a job. + * + *
GitLab Endpoint: DELETE /projects/:id/jobs/:job_id/artifacts
+ * + * @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or + * path + * @param jobId the ID to delete artifacts for + * @throws GitLabApiException if any exception occurs during execution + */ + public void deleteArtifacts(final Object projectIdOrPath, final Long jobId) + throws GitLabApiException { + delete( + Status.NO_CONTENT, + null, + "projects", + getProjectIdOrPath(projectIdOrPath), + "jobs", + jobId, + "artifacts"); + } } diff --git a/src/main/java/org/gitlab4j/api/KeysApi.java b/src/main/java/org/gitlab4j/api/KeysApi.java index 29265ff81..fd48fe71f 100644 --- a/src/main/java/org/gitlab4j/api/KeysApi.java +++ b/src/main/java/org/gitlab4j/api/KeysApi.java @@ -1,18 +1,17 @@ package org.gitlab4j.api; -import org.gitlab4j.api.models.Key; - -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; import java.util.Collections; +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; +import org.gitlab4j.api.models.Key; /** * See: * https://docs.gitlab.com/ee/api/keys.html#get-user-by-fingerprint-of-ssh-key */ public class KeysApi extends AbstractApi { - public KeysApi(GitLabApi gitLabApi) { + public KeysApi(final GitLabApi gitLabApi) { super(gitLabApi); } @@ -21,10 +20,10 @@ public KeysApi(GitLabApi gitLabApi) { * @return The Key which includes the user who owns the key * @throws GitLabApiException If anything goes wrong */ - public Key getUserBySSHKeyFingerprint(String fingerprint) throws GitLabApiException { - MultivaluedMap queryParams = new MultivaluedHashMap<>(); + public Key getUserBySSHKeyFingerprint(final String fingerprint) throws GitLabApiException { + final MultivaluedMap queryParams = new MultivaluedHashMap<>(); queryParams.put("fingerprint", Collections.singletonList(fingerprint)); - Response response = get(Response.Status.OK, queryParams, "keys"); + final Response response = get(Response.Status.OK, queryParams, "keys"); return response.readEntity(Key.class); } } diff --git a/src/main/java/org/gitlab4j/api/LabelsApi.java b/src/main/java/org/gitlab4j/api/LabelsApi.java index b8ba967f5..c654c3b54 100644 --- a/src/main/java/org/gitlab4j/api/LabelsApi.java +++ b/src/main/java/org/gitlab4j/api/LabelsApi.java @@ -3,10 +3,8 @@ import java.util.List; import java.util.Optional; import java.util.stream.Stream; - -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; - +import jakarta.ws.rs.core.GenericType; +import jakarta.ws.rs.core.Response; import org.gitlab4j.api.models.Label; /** @@ -17,549 +15,740 @@ */ public class LabelsApi extends AbstractApi { - public LabelsApi(GitLabApi gitLabApi) { - super(gitLabApi); - } - - /** - * Get all labels of the specified project. - * - * @param projectIdOrPath the project in the form of an Long(ID), String(path), or Project instance - * @return a list of project's labels - * @throws GitLabApiException if any exception occurs - */ - public List