Commit 9226d480 authored by Greg Messner's avatar Greg Messner
Browse files

Standardized code formatting.

parent 58daa255
......@@ -6,242 +6,255 @@ import javax.ws.rs.core.Response;
import java.net.URL;
/**
* This class is the base class for all the sub API classes. It provides implementations of
* delete(), get(), post() and put() that are re-used by all the sub-classes.
* This class is the base class for all the sub API classes. It provides implementations of
* delete(), get(), post() and put() that are re-used by all the sub-classes.
*
* @author Greg Messner <greg@messners.com>
*
*/
public abstract class AbstractApi {
private GitLabApi gitLabApi;
public AbstractApi (GitLabApi gitLabApi) {
this.gitLabApi = gitLabApi;
}
protected GitLabApiClient getApiClient () {
return (gitLabApi.getApiClient());
}
/**
* 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
* @param pathArgs
* @return a ClientResponse instance with the data returned from the endpoint
* @throws GitLabApiException
*/
protected Response get (Response.Status expectedStatus, MultivaluedMap<String, String> 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 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
* @param url
* @return a ClientResponse instance with the data returned from the endpoint
* @throws GitLabApiException
*/
protected Response get (Response.Status expectedStatus, MultivaluedMap<String, String> queryParams, URL url)
throws GitLabApiException {
try {
return validate(getApiClient().get(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
* @param pathArgs
* @return a ClientResponse instance with the data returned from the endpoint
* @throws GitLabApiException
*/
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 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
* @param url
* @return a ClientResponse instance with the data returned from the endpoint
* @throws GitLabApiException
*/
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 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
* @param pathArgs
* @return a ClientResponse instance with the data returned from the endpoint
* @throws GitLabApiException
*/
protected Response put (Response.Status expectedStatus, MultivaluedMap<String, String> 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
* @param url
* @return a ClientResponse instance with the data returned from the endpoint
* @throws GitLabApiException
*/
protected Response put (Response.Status expectedStatus, MultivaluedMap<String, String> queryParams, URL url) throws GitLabApiException {
try {
return validate(getApiClient().put(queryParams, 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
* @param pathArgs
* @return a ClientResponse instance with the data returned from the endpoint
* @throws GitLabApiException
*/
protected Response delete (Response.Status expectedStatus, MultivaluedMap<String, String> 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
* @param url
* @return a ClientResponse instance with the data returned from the endpoint
* @throws GitLabApiException
*/
protected Response delete (Response.Status expectedStatus, MultivaluedMap<String, String> 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
* @param name
* @param value
*/
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
* @param name
* @param value
* @param required
* @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().trim();
if (required && stringValue.length() == 0) {
throw new IllegalArgumentException(name + " cannot be empty or null");
}
formData.param(name, stringValue);
}
/**
* Validates response.
* @param response response
* @param expected expected respone status
* @return original response if the response status is expected
* @throws GitLabApiException in case of unexpected response status
*/
protected Response validate(Response response, Response.Status expected) throws GitLabApiException {
if (response.getStatus() != expected.getStatusCode()) {
throw new GitLabApiException(response);
}
return response;
}
/**
* Wraps exception if needed
* @param thrown exception
* @return never returns
* @throws GitLabApiException always
*/
protected GitLabApiException handle(Exception thrown) throws GitLabApiException {
if (thrown instanceof GitLabApiException) { throw (GitLabApiException) thrown; }
throw new GitLabApiException(thrown);
}
private GitLabApi gitLabApi;
public AbstractApi(GitLabApi gitLabApi) {
this.gitLabApi = gitLabApi;
}
protected GitLabApiClient getApiClient() {
return (gitLabApi.getApiClient());
}
/**
* 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
* @param pathArgs
* @return a ClientResponse instance with the data returned from the endpoint
* @throws GitLabApiException
*/
protected Response get(Response.Status expectedStatus, MultivaluedMap<String, String> 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 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
* @param url
* @return a ClientResponse instance with the data returned from the endpoint
* @throws GitLabApiException
*/
protected Response get(Response.Status expectedStatus, MultivaluedMap<String, String> queryParams, URL url) throws GitLabApiException {
try {
return validate(getApiClient().get(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
* @param pathArgs
* @return a ClientResponse instance with the data returned from the endpoint
* @throws GitLabApiException
*/
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 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
* @param pathArgs
* @return a ClientResponse instance with the data returned from the endpoint
* @throws GitLabApiException
*/
protected Response post(Response.Status expectedStatus, MultivaluedMap<String, String> 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
* @param url
* @return a ClientResponse instance with the data returned from the endpoint
* @throws GitLabApiException
*/
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 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
* @param pathArgs
* @return a ClientResponse instance with the data returned from the endpoint
* @throws GitLabApiException
*/
protected Response put(Response.Status expectedStatus, MultivaluedMap<String, String> 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
* @param url
* @return a ClientResponse instance with the data returned from the endpoint
* @throws GitLabApiException
*/
protected Response put(Response.Status expectedStatus, MultivaluedMap<String, String> queryParams, URL url) throws GitLabApiException {
try {
return validate(getApiClient().put(queryParams, 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
* @param pathArgs
* @return a ClientResponse instance with the data returned from the endpoint
* @throws GitLabApiException
*/
protected Response delete(Response.Status expectedStatus, MultivaluedMap<String, String> 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
* @param url
* @return a ClientResponse instance with the data returned from the endpoint
* @throws GitLabApiException
*/
protected Response delete(Response.Status expectedStatus, MultivaluedMap<String, String> 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
* @param name
* @param value
*/
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
* @param name
* @param value
* @param required
* @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().trim();
if (required && stringValue.length() == 0) {
throw new IllegalArgumentException(name + " cannot be empty or null");
}
formData.param(name, stringValue);
}
/**
* Validates response.
*
* @param response response
* @param expected expected respone status
* @return original response if the response status is expected
* @throws GitLabApiException in case of unexpected response status
*/
protected Response validate(Response response, Response.Status expected) throws GitLabApiException {
if (response.getStatus() != expected.getStatusCode()) {
throw new GitLabApiException(response);
}
return (response);
}
/**
* Wraps exception if needed
*
* @param thrown exception
* @return never returns
* @throws GitLabApiException always
*/
protected GitLabApiException handle(Exception thrown) throws GitLabApiException {
if (thrown instanceof GitLabApiException) {
throw (GitLabApiException) thrown;
}
throw new GitLabApiException(thrown);
}
}
......@@ -14,55 +14,52 @@ import java.util.List;
*/
public class CommitsApi extends AbstractApi {
public CommitsApi (GitLabApi gitLabApi) {
super(gitLabApi);
}
/**
* Get a list of repository commits in a project.
*
* GET /projects/:id/repository/commits
*
* @param projectId
* @return a List<Commit> containing the commits for the specified project ID
* @throws GitLabApiException
*/
public List<Commit> getCommits (int projectId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId, "repository", "commits");
return (response.readEntity(new GenericType<List<Commit>>(){}));
}
public CommitsApi(GitLabApi gitLabApi) {
super(gitLabApi);
}
/**
* Get a specific commit identified by the commit hash or name of a branch or tag.
*
* GET /projects/:id/repository/commits/:sha
*
* @param projectId
* @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
*/
public Commit getCommits (int projectId, String sha) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId, "repository", "commits", sha);
return (response.readEntity(Commit.class));
}
/**
* Get a list of repository commits in a project.
*
* GET /projects/:id/repository/commits
*
* @param projectId
* @return a List<Commit> containing the commits for the specified project ID
* @throws GitLabApiException
*/
public List<Commit> getCommits(int projectId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId, "repository", "commits");
return (response.readEntity(new GenericType<List<Commit>>() {
}));
}
/**
* Get the diff of a commit in a project.
*
* GET /projects/:id/repository/commits/:sha/diff
*
* @param projectId
* @param sha a commit hash or name of a branch or tag
* @return the Diff instance for the specified project ID/sha pair
* @throws GitLabApiException
*/
public Diff getDiff (int projectId, String sha) throws GitLabApiException {
Response response = get(Response.Status.OK, null,
"projects", projectId, "repository", "commits", sha, "diff");
return (response.readEntity(Diff.class));
}
/**
* Get a specific commit identified by the commit hash or name of a branch or tag.
*
* GET /projects/:id/repository/commits/:sha
*
* @param projectId
* @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
*/
public Commit getCommits(int projectId, String sha) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId, "repository", "commits", sha);
return (response.readEntity(Commit.class));
}
/**
* Get the diff of a commit in a project.
*
* GET /projects/:id/repository/commits/:sha/diff
*
* @param projectId
* @param sha a commit hash or name of a branch or tag
* @return the Diff instance for the specified project ID/sha pair
* @throws GitLabApiException
*/
public Diff getDiff(int projectId, String sha) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId, "repository", "commits", sha, "diff");
return (response.readEntity(Diff.class));
}
}
\ No newline at end of file
......@@ -35,283 +35,292 @@ import java.util.Map;
* @author Greg Messner <greg@messners.com>
*/
public class GitLabApiClient {
protected static final String PRIVATE_TOKEN_HEADER = "PRIVATE-TOKEN";
protected static final String API_NAMESPACE = "/api/v3";
private ClientConfig clientConfig;
private Client apiClient;
private String hostUrl;
private String privateToken;
private static boolean ignoreCertificateErrors;
private static SSLSocketFactory defaultSocketFactory;
/**
* Construct an instance to communicate with a GitLab API server using the specified
* server URL and private token.
*
* @param hostUrl the URL to the GitLab API server
* @param privateToken the private token to authenticate with
*/
public GitLabApiClient (String hostUrl, String privateToken) {
// Remove the trailing "/" from the hostUrl if present
this.hostUrl = (hostUrl.endsWith("/") ? hostUrl.replaceAll("/$", "") : hostUrl) + API_NAMESPACE;
this.privateToken = privateToken;
clientConfig = new ClientConfig();
clientConfig.register(JacksonJson.class);
}
/**
* 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 (GitLabApiClient.ignoreCertificateErrors);
}
/**
* Sets up the Jersey system ignore SSL certificate errors or not.
*
* <p><strong>WARNING: Setting this to true will affect ALL uses of HttpsURLConnection and Jersey.<strong><p>
*
* @param ignoreCertificateErrors
*/
public void setIgnoreCerificateErrors (boolean ignoreCertificateErrors) {
if (GitLabApiClient.ignoreCertificateErrors == ignoreCertificateErrors) {
return;
}
if (ignoreCertificateErrors == false) {
GitLabApiClient.ignoreCertificateErrors = false;
HttpsURLConnection.setDefaultSSLSocketFactory(GitLabApiClient.defaultSocketFactory);
return;
}
SSLSocketFactory defaultSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
if (ignoreCertificateErrors() == true) {
GitLabApiClient.ignoreCertificateErrors = true;
GitLabApiClient.defaultSocketFactory = defaultSocketFactory;
} else {
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 ignoreCertificateErrors () {
// Create a TrustManager that trusts all certificates
TrustManager[ ] certs = new TrustManager[ ] {
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
}
};
// Now set the default SSLSocketFactory to use the just created TrustManager
SSLSocketFactory defaultSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, certs, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
HttpsURLConnection.getDefaultSSLSocketFactory();
} catch (GeneralSecurityException ex) {
HttpsURLConnection.setDefaultSSLSocketFactory(defaultSocketFactory);
return (false);
}
return (true);
}
/**
* Construct a REST URL with the specified path arguments.
*
* @param pathArgs
* @return a REST URL with the specified path arguments
* @throws IOException
*/
protected URL getApiUrl (Object ... pathArgs) throws IOException {
StringBuilder url = new StringBuilder();
url.append(hostUrl);
for (Object pathArg : pathArgs) {
url.append("/");
url.append(pathArg.toString());
}
return (new URL(url.toString()));
protected static final String PRIVATE_TOKEN_HEADER = "PRIVATE-TOKEN";
protected static final String API_NAMESPACE = "/api/v3";
private ClientConfig clientConfig;
private Client apiClient;
private String hostUrl;
private String privateToken;
private static boolean ignoreCertificateErrors;
private static SSLSocketFactory defaultSocketFactory;
/**
* Construct an instance to communicate with a GitLab API server using the specified
* server URL and private token.
*
* @param hostUrl the URL to the GitLab API server
* @param privateToken the private token to authenticate with
*/
public GitLabApiClient(String hostUrl, String privateToken) {
// Remove the trailing "/" from the hostUrl if present
this.hostUrl = (hostUrl.endsWith("/") ? hostUrl.replaceAll("/$", "") : hostUrl) + API_NAMESPACE;
this.privateToken = privateToken;
clientConfig = new ClientConfig();
clientConfig.register(JacksonJson.class);
}
/**
* 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 (GitLabApiClient.ignoreCertificateErrors);
}
/**
* Sets up the Jersey system ignore SSL certificate errors or not.
*
* <p>
* <strong>WARNING: Setting this to true will affect ALL uses of HttpsURLConnection and Jersey.<strong>
* <p>
*
* @param ignoreCertificateErrors
*/
public void setIgnoreCerificateErrors(boolean ignoreCertificateErrors) {
if (GitLabApiClient.ignoreCertificateErrors == ignoreCertificateErrors) {
return;
}
if (ignoreCertificateErrors == false) {
GitLabApiClient.ignoreCertificateErrors = false;
HttpsURLConnection.setDefaultSSLSocketFactory(GitLabApiClient.defaultSocketFactory);
return;
}
SSLSocketFactory defaultSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
if (ignoreCertificateErrors() == true) {
GitLabApiClient.ignoreCertificateErrors = true;
GitLabApiClient.defaultSocketFactory = defaultSocketFactory;
} else {
throw new RuntimeException("Unable to ignore certificate errors.");
}
}
/**
* 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
* @param pathArgs
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException
*/
protected Response get (MultivaluedMap<String, String> 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
* @param url
* @return a ClientResponse instance with the data returned from the endpoint
*/
protected Response get (MultivaluedMap<String, String> queryParams, URL url) {
return invocation(url, queryParams).get();
}
/**
* 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
* @param pathArgs
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException
*/
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 URL, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param formData
* @param url
* @return a ClientResponse instance with the data returned from the endpoint
*/
protected Response post (Form formData, URL url) {
return invocation(url, null).post(Entity.entity(formData, 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 queryParams
* @param pathArgs
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException
*/
protected Response put (MultivaluedMap<String, String> queryParams, Object ... pathArgs)
throws IOException {
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
* @param url
* @return a ClientResponse instance with the data returned from the endpoint
*/
protected Response put (MultivaluedMap<String, String> queryParams, URL url) {
return invocation(url, null).put(Entity.entity(queryParams, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
}
/**
* 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
* @param pathArgs
* @return a Response instance with the data returned from the endpoint
* @throws IOException
*/
protected Response delete (MultivaluedMap<String, String> queryParams, 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
* @param url
* @return a Response instance with the data returned from the endpoint
*/
protected Response delete (MultivaluedMap<String, String> queryParams, URL url) {
return invocation(url, queryParams).delete();
}
protected class AcceptAllHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
}
protected Invocation.Builder invocation(URL url, MultivaluedMap<String, String> queryParams) {
if (apiClient == null) {
apiClient = ClientBuilder.newBuilder()
.withConfig(clientConfig)
.sslContext(getSslContext())
.hostnameVerifier(new AcceptAllHostnameVerifier())
.build();
}
WebTarget target = apiClient.target(url.toExternalForm()).property(ClientProperties.FOLLOW_REDIRECTS, true);
if (queryParams != null) {
for (Map.Entry<String, List<String>> param : queryParams.entrySet()) {
target = target.queryParam(param.getKey(), param.getValue().toArray());
}
}
return target.request().header(PRIVATE_TOKEN_HEADER, privateToken).accept(MediaType.APPLICATION_JSON);
}
private SSLContext getSslContext() {
try {
return SSLContext.getDefault();
} catch (NoSuchAlgorithmException e) {
throw new UnsupportedOperationException(e);
}
}
/**
* Sets up Jersey client to ignore certificate errors.
*
* @return true if successful at setting up to ignore certificate errors, otherwise returns false.
*/
private boolean ignoreCertificateErrors() {
// Create a TrustManager that trusts all certificates
TrustManager[] certs = new TrustManager[] { new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
} };
// Now set the default SSLSocketFactory to use the just created TrustManager
SSLSocketFactory defaultSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, certs, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
HttpsURLConnection.getDefaultSSLSocketFactory();
} catch (GeneralSecurityException ex) {
HttpsURLConnection.setDefaultSSLSocketFactory(defaultSocketFactory);
return (false);
}
return (true);
}
/**
* Construct a REST URL with the specified path arguments.
*
* @param pathArgs
* @return a REST URL with the specified path arguments
* @throws IOException
*/
protected URL getApiUrl(Object... pathArgs) throws IOException {
StringBuilder url = new StringBuilder();
url.append(hostUrl);
for (Object pathArg : pathArgs) {
if (pathArg != null) {
url.append("/");
url.append(pathArg.toString());
}
}
return (new URL(url.toString()));
}
/**
* 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
* @param pathArgs
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException
*/
protected Response get(MultivaluedMap<String, String> 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
* @param url
* @return a ClientResponse instance with the data returned from the endpoint
*/
protected Response get(MultivaluedMap<String, String> queryParams, URL url) {
return (invocation(url, queryParams).get());
}
/**
* 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
* @param pathArgs
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException
*/
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 formData
* @param pathArgs
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException
*/
protected Response post(MultivaluedMap<String, String> 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
* @param url
* @return a ClientResponse instance with the data returned from the endpoint
*/
protected Response post(Form formData, URL url) {
return (invocation(url, null).post(Entity.entity(formData, 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 formData
* @param url
* @return a ClientResponse instance with the data returned from the endpoint
*/
protected Response post(MultivaluedMap<String, String> queryParams, URL url) {
return (invocation(url, queryParams).post(null));
}
/**
* 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
* @param pathArgs
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException
*/
protected Response put(MultivaluedMap<String, String> queryParams, Object... pathArgs) throws IOException {
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
* @param url
* @return a ClientResponse instance with the data returned from the endpoint
*/
protected Response put(MultivaluedMap<String, String> queryParams, URL url) {
return (invocation(url, null).put(Entity.entity(queryParams, MediaType.APPLICATION_FORM_URLENCODED_TYPE)));
}
/**
* 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
* @param pathArgs
* @return a Response instance with the data returned from the endpoint
* @throws IOException
*/
protected Response delete(MultivaluedMap<String, String> queryParams, 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
* @param url
* @return a Response instance with the data returned from the endpoint
*/
protected Response delete(MultivaluedMap<String, String> queryParams, URL url) {
return (invocation(url, queryParams).delete());
}
protected class AcceptAllHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String s, SSLSession sslSession) {
return (true);
}
}
protected Invocation.Builder invocation(URL url, MultivaluedMap<String, String> queryParams) {
if (apiClient == null) {
apiClient = ClientBuilder.newBuilder().withConfig(clientConfig).sslContext(getSslContext()).hostnameVerifier(new AcceptAllHostnameVerifier()).build();
}
WebTarget target = apiClient.target(url.toExternalForm()).property(ClientProperties.FOLLOW_REDIRECTS, true);
if (queryParams != null) {
for (Map.Entry<String, List<String>> param : queryParams.entrySet()) {
target = target.queryParam(param.getKey(), param.getValue().toArray());
}
}
return (target.request().header(PRIVATE_TOKEN_HEADER, privateToken).accept(MediaType.APPLICATION_JSON));
}
private SSLContext getSslContext() {
try {
return SSLContext.getDefault();
} catch (NoSuchAlgorithmException e) {
throw new UnsupportedOperationException(e);
}
}
}
......@@ -5,7 +5,6 @@ import com.messners.gitlab.api.models.ErrorMessage;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.StatusType;
/**
* This is the exception that will be thrown if any exception occurs while communicating
* with a GitLab API endpoint.
......@@ -15,73 +14,70 @@ import javax.ws.rs.core.Response.StatusType;
*/
public class GitLabApiException extends Exception {
private static final long serialVersionUID = 1L;
private StatusType statusInfo;
private int httpStatus;
private String message;
/**
* Create a GitLabApiException instance based on the ClientResponse.
*
* @param response
*/
public GitLabApiException (Response response) {
super();
statusInfo = response.getStatusInfo();
httpStatus = response.getStatus();
private static final long serialVersionUID = 1L;
private StatusType statusInfo;
private int httpStatus;
private String message;
/**
* Create a GitLabApiException instance based on the ClientResponse.
*
* @param response
*/
public GitLabApiException(Response response) {
super();
statusInfo = response.getStatusInfo();
httpStatus = response.getStatus();
if (response.hasEntity()) {
try {
ErrorMessage errorMessage = response.readEntity(ErrorMessage.class);
message = errorMessage.getMessage();
} catch (Exception ignore) {
}
}
}
/**
* Create a GitLabApiException instance based on the exception.
*
* @param e
*/
public GitLabApiException(Exception e) {
super(e);
message = e.getMessage();
}
if (response.hasEntity()) {
try {
ErrorMessage errorMessage = response.readEntity(ErrorMessage.class);
message = errorMessage.getMessage();
} catch (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
*/
public GitLabApiException (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 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 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);
}
}
......@@ -15,132 +15,127 @@ import java.util.List;
*/
public class GroupApi extends AbstractApi {
GroupApi (GitLabApi gitLabApi) {
super(gitLabApi);
}
/**
* Get a list of groups. (As user: my groups, as admin: all groups)
*
* GET /groups
*
* @return the list of groups viewable by the authenticated user
* @throws GitLabApiException
*/
public List<Group> getGroups () throws GitLabApiException {
Response response = get(Response.Status.OK, null, "groups");
return (response.readEntity(new GenericType<List<Group>>() {}));
}
/**
* Get all details of a group.
*
* GET /groups/:id
*
* @param groupId
* @return the Group instance for the specified group ID
* @throws GitLabApiException
*/
public Group getGroup (int groupId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "groups", groupId);
return (response.readEntity(Group.class));
}
/**
* Creates a new project group. Available only for admin.
*
* POST /groups
*
* @param name
* @param path
*/
public void addGroup (String name, String path) throws GitLabApiException {
Form formData = new Form();
formData.param("name", name);
formData.param("path", path);
post(Response.Status.OK, formData, "groups");
}
/**
* Removes group with all projects inside.
*
* DELETE /groups/:id
*
* @param groupId
* @throws GitLabApiException
*/
public void deleteGroup (Integer groupId) throws GitLabApiException {
if (groupId == null) {
throw new RuntimeException("groupId cannot be null");
}
delete(Response.Status.OK, null, "groups", groupId);
}
/**
* Removes group with all projects inside.
*
* DELETE /groups/:id
*
* @param group
* @throws GitLabApiException
*/
public void deleteGroup (Group group) throws GitLabApiException {
deleteGroup(group.getId());
}
/**
* Get a list of group members viewable by the authenticated user.
*
* GET /groups/:id/members
*
* @return a list of group members viewable by the authenticated user
* @throws GitLabApiException
*/
public List<Member> getMembers (int groupId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "groups", groupId, "members");
return (response.readEntity(new GenericType<List<Member>>() {}));
}
/**
* Adds a user to the list of group members.
*
* POST /groups/:id/members
*
* @param groupId
* @param userId
* @param accessLevel
* @return a Member instance for the added user
* @throws GitLabApiException
*/
public Member addMember (Integer groupId, Integer userId, Integer accessLevel) throws GitLabApiException {
Form formData = new Form();
formData.param("user_id", userId.toString());
formData.param("access_level", accessLevel.toString());
Response response = post(Response.Status.OK, formData, "groups", groupId, "members");
return (response.readEntity(Member.class));
}
/**
* Removes member from the group team.
*
* DELETE /groups/:id/members/:user_id
*
* @param projectId
* @param userId
* @throws GitLabApiException
*/
public void removeMember (Integer projectId, Integer userId) throws GitLabApiException {
delete(Response.Status.OK, null, "groups", projectId, "members", userId);
}
GroupApi(GitLabApi gitLabApi) {
super(gitLabApi);
}
/**
* Get a list of groups. (As user: my groups, as admin: all groups)
*
* GET /groups
*
* @return the list of groups viewable by the authenticated user
* @throws GitLabApiException
*/
public List<Group> getGroups() throws GitLabApiException {
Response response = get(Response.Status.OK, null, "groups");
return (response.readEntity(new GenericType<List<Group>>() {
}));
}
/**
* Get all details of a group.
*
* GET /groups/:id
*
* @param groupId
* @return the Group instance for the specified group ID
* @throws GitLabApiException
*/
public Group getGroup(int groupId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "groups", groupId);
return (response.readEntity(Group.class));
}
/**
* Creates a new project group. Available only for admin.
*
* POST /groups
*
* @param name
* @param path
*/
public void addGroup(String name, String path) throws GitLabApiException {
Form formData = new Form();
formData.param("name", name);
formData.param("path", path);
post(Response.Status.OK, formData, "groups");
}
/**
* Removes group with all projects inside.
*
* DELETE /groups/:id
*
* @param groupId
* @throws GitLabApiException
*/
public void deleteGroup(Integer groupId) throws GitLabApiException {
if (groupId == null) {
throw new RuntimeException("groupId cannot be null");
}
delete(Response.Status.OK, null, "groups", groupId);
}
/**
* Removes group with all projects inside.
*
* DELETE /groups/:id
*
* @param group
* @throws GitLabApiException
*/
public void deleteGroup(Group group) throws GitLabApiException {
deleteGroup(group.getId());
}
/**
* Get a list of group members viewable by the authenticated user.
*
* GET /groups/:id/members
*
* @return a list of group members viewable by the authenticated user
* @throws GitLabApiException
*/
public List<Member> getMembers(int groupId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "groups", groupId, "members");
return (response.readEntity(new GenericType<List<Member>>() {
}));
}
/**
* Adds a user to the list of group members.
*
* POST /groups/:id/members
*
* @param groupId
* @param userId
* @param accessLevel
* @return a Member instance for the added user
* @throws GitLabApiException
*/
public Member addMember(Integer groupId, Integer userId, Integer accessLevel) throws GitLabApiException {
Form formData = new Form();
formData.param("user_id", userId.toString());
formData.param("access_level", accessLevel.toString());
Response response = post(Response.Status.OK, formData, "groups", groupId, "members");
return (response.readEntity(Member.class));
}
/**
* Removes member from the group team.
*
* DELETE /groups/:id/members/:user_id
*
* @param projectId
* @param userId
* @throws GitLabApiException
*/
public void removeMember(Integer projectId, Integer userId) throws GitLabApiException {
delete(Response.Status.OK, null, "groups", projectId, "members", userId);
}
}
......@@ -12,109 +12,103 @@ import java.util.TimeZone;
* @author Greg Messner <greg@messners.com>
*/
public class ISO8601 {
public static final String PATTERN = "yyyy-MM-dd'T'HH:mm:ssZ";
public static final String OUTPUT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'";
public static final String ALTERNATE_PATTERN = "yyyy-MM-dd HH:mm:ss";
private static final SimpleDateFormat iso8601Format;
private static final SimpleDateFormat iso8601OutputFormat;
private static final SimpleDateFormat iso8601AlternateFormat;
static {
iso8601Format = new SimpleDateFormat(PATTERN);
iso8601Format.setLenient(true);
iso8601Format.setTimeZone(TimeZone.getTimeZone("GMT"));
iso8601OutputFormat = new SimpleDateFormat(OUTPUT_PATTERN);
iso8601OutputFormat.setLenient(true);
iso8601OutputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
iso8601AlternateFormat = new SimpleDateFormat(ALTERNATE_PATTERN);
iso8601AlternateFormat.setLenient(true);
iso8601AlternateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
}
/**
* Get a ISO8601 formatted string for the current date and time.
*
* @return a ISO8601 formatted string for the current date and time
*/
public static String getTimestamp () {
return iso8601Format.format(new Date());
}
/**
* Get a ISO8601 formatted string for the provided Calendar instance.
*
* @param cal the Calendar instance to get the ISO8601 formatted string for
* @return a ISO8601 formatted string for the provided Calendar instance, or null if call is null
*/
public static String toString (Calendar cal) {
if (cal == null) {
return (null);
}
return toString(cal.getTime());
}
/**
* Get a ISO8601 formatted string for the provided Date instance.
*
* @param date the Date instance to get the ISO8601 formatted string for
* @return a ISO8601 formatted string for the provided Date instance, or null if date is null
*/
public static synchronized String toString (Date date) {
if (date == null) {
return (null);
}
return iso8601OutputFormat.format(date);
}
/**
* Parses an ISO8601 formatted string a returns a Date instance.
*
* @param dateTimeString the ISO8601 formatted string
* @return a Date instance for the ISO8601 formatted string
* @throws ParseException if the provided string is not in the proper format
*/
public static Date toDate (String dateTimeString) throws ParseException {
if (dateTimeString == null) {
return (null);
}
dateTimeString = dateTimeString.trim();
SimpleDateFormat fmt;
if (dateTimeString.length() > 10) {
fmt = (dateTimeString.charAt(10) == 'T' ?
(dateTimeString.endsWith("Z") ? iso8601OutputFormat : iso8601Format) : iso8601AlternateFormat);
} else {
fmt = iso8601Format;
}
synchronized (fmt) {
return (fmt.parse(dateTimeString));
}
}
/**
* Parses an ISO8601 formatted string a returns a Calendar instance.
*
* @param dateTimeString the ISO8601 formatted string
* @return a Calendar instance for the ISO8601 formatted string
* @throws ParseException if the provided string is not in the proper format
*/
public static Calendar toCalendar (String dateTimeString) throws ParseException {
Date date = toDate(dateTimeString);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return (cal);
}
public static final String PATTERN = "yyyy-MM-dd'T'HH:mm:ssZ";
public static final String OUTPUT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'";
public static final String ALTERNATE_PATTERN = "yyyy-MM-dd HH:mm:ss";
private static final SimpleDateFormat iso8601Format;
private static final SimpleDateFormat iso8601OutputFormat;
private static final SimpleDateFormat iso8601AlternateFormat;
static {
iso8601Format = new SimpleDateFormat(PATTERN);
iso8601Format.setLenient(true);
iso8601Format.setTimeZone(TimeZone.getTimeZone("GMT"));
iso8601OutputFormat = new SimpleDateFormat(OUTPUT_PATTERN);
iso8601OutputFormat.setLenient(true);
iso8601OutputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
iso8601AlternateFormat = new SimpleDateFormat(ALTERNATE_PATTERN);
iso8601AlternateFormat.setLenient(true);
iso8601AlternateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
}
/**
* Get a ISO8601 formatted string for the current date and time.
*
* @return a ISO8601 formatted string for the current date and time
*/
public static String getTimestamp() {
return (iso8601Format.format(new Date()));
}
/**
* Get a ISO8601 formatted string for the provided Calendar instance.
*
* @param cal the Calendar instance to get the ISO8601 formatted string for
* @return a ISO8601 formatted string for the provided Calendar instance, or null if call is null
*/
public static String toString(Calendar cal) {
if (cal == null) {
return (null);
}
return (toString(cal.getTime()));
}
/**
* Get a ISO8601 formatted string for the provided Date instance.
*
* @param date the Date instance to get the ISO8601 formatted string for
* @return a ISO8601 formatted string for the provided Date instance, or null if date is null
*/
public static synchronized String toString(Date date) {
if (date == null) {
return (null);
}
return (iso8601OutputFormat.format(date));
}
/**
* Parses an ISO8601 formatted string a returns a Date instance.
*
* @param dateTimeString the ISO8601 formatted string
* @return a Date instance for the ISO8601 formatted string
* @throws ParseException if the provided string is not in the proper format
*/
public static Date toDate(String dateTimeString) throws ParseException {
if (dateTimeString == null) {
return (null);
}
dateTimeString = dateTimeString.trim();
SimpleDateFormat fmt;
if (dateTimeString.length() > 10) {
fmt = (dateTimeString.charAt(10) == 'T' ? (dateTimeString.endsWith("Z") ? iso8601OutputFormat : iso8601Format) : iso8601AlternateFormat);
} else {
fmt = iso8601Format;
}
synchronized (fmt) {
return (fmt.parse(dateTimeString));
}
}
/**
* Parses an ISO8601 formatted string a returns a Calendar instance.
*
* @param dateTimeString the ISO8601 formatted string
* @return a Calendar instance for the ISO8601 formatted string
* @throws ParseException if the provided string is not in the proper format
*/
public static Calendar toCalendar(String dateTimeString) throws ParseException {
Date date = toDate(dateTimeString);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return (cal);
}
}
......@@ -27,7 +27,7 @@ import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.map.module.SimpleModule;
/**
/**
* Jackson JSON Configuration and utility class.
*
* @author Greg Messner <greg@messners.com>
......@@ -36,42 +36,41 @@ import org.codehaus.jackson.map.module.SimpleModule;
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JacksonJson extends JacksonJaxbJsonProvider implements ContextResolver<ObjectMapper> {
private final ObjectMapper objectMapper;
public JacksonJson () {
objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(Inclusion.NON_NULL);
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.configure(SerializationConfig.Feature.WRITE_ENUMS_USING_TO_STRING, Boolean.TRUE);
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationConfig.Feature.READ_ENUMS_USING_TO_STRING, Boolean.TRUE);
SimpleModule module = new SimpleModule("GitLabApiJsonModule", new Version(1, 0, 0, null));
module.addSerializer(Date.class, new JsonDateSerializer());
objectMapper.registerModule(module);
}
private final ObjectMapper objectMapper;
public JacksonJson() {
objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(Inclusion.NON_NULL);
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.configure(SerializationConfig.Feature.WRITE_ENUMS_USING_TO_STRING, Boolean.TRUE);
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationConfig.Feature.READ_ENUMS_USING_TO_STRING, Boolean.TRUE);
SimpleModule module = new SimpleModule("GitLabApiJsonModule", new Version(1, 0, 0, null));
module.addSerializer(Date.class, new JsonDateSerializer());
objectMapper.registerModule(module);
}
/**
*
*/
@Override
public ObjectMapper getContext (Class<?> objectType) {
public ObjectMapper getContext(Class<?> objectType) {
return (objectMapper);
}
/**
* Gets the ObjectMapper contained by this instance.
*
* @return the ObjectMapper contained by this instance
*/
public ObjectMapper getObjectMapper () {
return (objectMapper);
public ObjectMapper getObjectMapper() {
return (objectMapper);
}
/**
* Unmarshal the JSON data on the specified Reader instance to an instance of the provided class.
*
......@@ -82,68 +81,63 @@ public class JacksonJson extends JacksonJaxbJsonProvider implements ContextResol
* @throws JsonMappingException
* @throws IOException
*/
public <T> T unmarshal (Class<T> returnType, Reader reader)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = getContext(returnType);
return (objectMapper.readValue(reader, returnType));
}
/**
* Unmarshal the JSON data contained by the string and populate an instance of the provided returnType class.
public <T> T unmarshal(Class<T> returnType, Reader reader) throws JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = getContext(returnType);
return (objectMapper.readValue(reader, returnType));
}
/**
* Unmarshal the JSON data contained by the string and populate an instance of the provided returnType class.
*
* @param returnType an instance of this type class will be returned
* @param postData
* @return an instance of the provided class containing the parsed data from the string
* @throws JsonParseException
* @throws JsonMappingException
* @throws IOException
*/
public <T> T unmarshal (Class<T> returnType, String postData)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = getContext(returnType);
return (objectMapper.readValue(postData, returnType));
}
/**
* Marshals the supplied object out as a formatted JSON string.
*
* @param object the object to output as a JSON string
* @return a String containing the JSON for the specified object
*/
public <T> String marshal (final T object) {
if (object == null) {
throw new IllegalArgumentException("object parameter is null");
}
ObjectWriter writer = objectMapper.writer().withDefaultPrettyPrinter();
String results = null;
try {
results = writer.writeValueAsString(object);
} catch (JsonGenerationException e) {
System.err.println("JsonGenerationException, message=" + e.getMessage());
} catch (JsonMappingException e) {
e.printStackTrace();
System.err.println("JsonMappingException, message=" + e.getMessage());
} catch (IOException e) {
System.err.println("IOException, message=" + e.getMessage());
}
return (results);
}
/**
* JsonSerializer for serializing ISO8601 formatted dates.
*/
public static class JsonDateSerializer extends JsonSerializer<Date> {
@Override
public void serialize(java.util.Date date, JsonGenerator gen, SerializerProvider provider)
throws IOException, JsonProcessingException {
String iso8601String = ISO8601.toString(date);
gen.writeString(iso8601String);
}
}
* @param postData
* @return an instance of the provided class containing the parsed data from the string
* @throws JsonParseException
* @throws JsonMappingException
* @throws IOException
*/
public <T> T unmarshal(Class<T> returnType, String postData) throws JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = getContext(returnType);
return (objectMapper.readValue(postData, returnType));
}
/**
* Marshals the supplied object out as a formatted JSON string.
*
* @param object the object to output as a JSON string
* @return a String containing the JSON for the specified object
*/
public <T> String marshal(final T object) {
if (object == null) {
throw new IllegalArgumentException("object parameter is null");
}
ObjectWriter writer = objectMapper.writer().withDefaultPrettyPrinter();
String results = null;
try {
results = writer.writeValueAsString(object);
} catch (JsonGenerationException e) {
System.err.println("JsonGenerationException, message=" + e.getMessage());
} catch (JsonMappingException e) {
e.printStackTrace();
System.err.println("JsonMappingException, message=" + e.getMessage());
} catch (IOException e) {
System.err.println("IOException, message=" + e.getMessage());
}
return (results);
}
/**
* JsonSerializer for serializing ISO8601 formatted dates.
*/
public static class JsonDateSerializer extends JsonSerializer<Date> {
@Override
public void serialize(java.util.Date date, JsonGenerator gen, SerializerProvider provider) throws IOException, JsonProcessingException {
String iso8601String = ISO8601.toString(date);
gen.writeString(iso8601String);
}
}
}
\ No newline at end of file
......@@ -9,135 +9,131 @@ import javax.ws.rs.core.Response;
import java.util.List;
/**
* This class implements the client side API for the GitLab merge request calls.
* This class implements the client side API for the GitLab merge request calls.
*
* @author Greg Messner <greg@messners.com>
*/
public class MergeRequestApi extends AbstractApi {
MergeRequestApi (GitLabApi gitLabApi) {
super(gitLabApi);
}
/**
* Get all merge requests for the specified project.
*
* GET /projects/:id/merge_requests
*
* @param projectId the project ID to get the merge requests for
* @return all merge requests for the specified project
* @throws GitLabApiException
*/
public List<MergeRequest> getMergeRequests (Integer projectId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId, "merge_requests");
return (response.readEntity(new GenericType<List<MergeRequest>>() {}));
}
/**
* Get information about a single merge request.
*
* GET /projects/:id/merge_request/:merge_request_id
*
* @param projectId
* @param mergeRequestId
* @return the specified MergeRequest instance
* @throws GitLabApiException
*/
public MergeRequest getMergeRequest (Integer projectId, Integer mergeRequestId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId, "merge_request", mergeRequestId);
return (response.readEntity(MergeRequest.class));
}
/**
* Creates a merge request and optionally assigns a reviewer to it.
*
* POST /projects/:id/merge_requests
*
* @param projectId the ID of a project, required
* @param sourceBranch the source branch, required
* @param targetBranch the target branch, required
* @param title the title for the merge request, required
* @param description the description of the merge request
* @param assigneeId the Assignee user ID, optional
* @return the created MergeRequest instance
* @throws GitLabApiException
*/
public MergeRequest createMergeRequest (Integer projectId, String sourceBranch, String targetBranch, String title, String description, Integer assigneeId)
throws GitLabApiException {
if (projectId == null) {
throw new RuntimeException("projectId cannot be null");
}
Form formData = new Form();
addFormParam(formData, "source_branch", sourceBranch, true);
addFormParam(formData, "target_branch", targetBranch, true);
addFormParam(formData, "title", title, true);
addFormParam(formData, "description", description, false);
addFormParam(formData, "assignee_id", assigneeId, false);
Response response = post(Response.Status.CREATED, formData, "projects", projectId, "merge_requests");
return (response.readEntity(MergeRequest.class));
}
/**
* Updates an existing merge request. You can change branches, title, or even close the MR.
*
* PUT /projects/:id/merge_request/:merge_request_id
*
* @param projectId
* @param mergeRequestId
* @param sourceBranch
* @param targetBranch
* @param title
* @param description
* @param assigneeId
* @return the updated merge request
* @throws GitLabApiException
*/
public MergeRequest updateMergeRequest (Integer projectId, Integer mergeRequestId,
String sourceBranch, String targetBranch, String title, String description, Integer assigneeId) throws GitLabApiException {
if (projectId == null) {
throw new RuntimeException("mergeRequestId cannot be null");
}
if (mergeRequestId == null) {
throw new RuntimeException("projectId cannot be null");
}
Form formData = new Form();
addFormParam(formData, "source_branch", sourceBranch, false);
addFormParam(formData, "target_branch", targetBranch, false);
addFormParam(formData, "title", title, false);
addFormParam(formData, "description", description, false);
addFormParam(formData, "assignee_id", assigneeId, false);
Response response = put(Response.Status.OK, formData.asMap(), "projects", projectId, "merge_request", mergeRequestId);
return (response.readEntity(MergeRequest.class));
}
/**
* Adds a comment to a merge request.
*
* POST /projects/:id/merge_request/:merge_request_id/comments
*
* @param projectId
* @param mergeRequestId
* @param comments
* @return the added merge request comment
* @throws GitLabApiException
*/
public MergeRequestComment addMergeRequestComment (Integer projectId, Integer mergeRequestId, String comments) throws GitLabApiException {
Form formData = new Form();
formData.param("note", comments);
Response response = post(Response.Status.OK, formData, "projects", projectId, "merge_request", mergeRequestId, "comments");
return (response.readEntity(MergeRequestComment.class));
}
MergeRequestApi(GitLabApi gitLabApi) {
super(gitLabApi);
}
/**
* Get all merge requests for the specified project.
*
* GET /projects/:id/merge_requests
*
* @param projectId the project ID to get the merge requests for
* @return all merge requests for the specified project
* @throws GitLabApiException
*/
public List<MergeRequest> getMergeRequests(Integer projectId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId, "merge_requests");
return (response.readEntity(new GenericType<List<MergeRequest>>() {
}));
}
/**
* Get information about a single merge request.
*
* GET /projects/:id/merge_request/:merge_request_id
*
* @param projectId
* @param mergeRequestId
* @return the specified MergeRequest instance
* @throws GitLabApiException
*/
public MergeRequest getMergeRequest(Integer projectId, Integer mergeRequestId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId, "merge_request", mergeRequestId);
return (response.readEntity(MergeRequest.class));
}
/**
* Creates a merge request and optionally assigns a reviewer to it.
*
* POST /projects/:id/merge_requests
*
* @param projectId the ID of a project, required
* @param sourceBranch the source branch, required
* @param targetBranch the target branch, required
* @param title the title for the merge request, required
* @param description the description of the merge request
* @param assigneeId the Assignee user ID, optional
* @return the created MergeRequest instance
* @throws GitLabApiException
*/
public MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title, String description, Integer assigneeId)
throws GitLabApiException {
if (projectId == null) {
throw new RuntimeException("projectId cannot be null");
}
Form formData = new Form();
addFormParam(formData, "source_branch", sourceBranch, true);
addFormParam(formData, "target_branch", targetBranch, true);
addFormParam(formData, "title", title, true);
addFormParam(formData, "description", description, false);
addFormParam(formData, "assignee_id", assigneeId, false);
Response response = post(Response.Status.CREATED, formData, "projects", projectId, "merge_requests");
return (response.readEntity(MergeRequest.class));
}
/**
* Updates an existing merge request. You can change branches, title, or even close the MR.
*
* PUT /projects/:id/merge_request/:merge_request_id
*
* @param projectId
* @param mergeRequestId
* @param sourceBranch
* @param targetBranch
* @param title
* @param description
* @param assigneeId
* @return the updated merge request
* @throws GitLabApiException
*/
public MergeRequest updateMergeRequest(Integer projectId, Integer mergeRequestId, String sourceBranch, String targetBranch, String title, String description,
Integer assigneeId) throws GitLabApiException {
if (projectId == null) {
throw new RuntimeException("mergeRequestId cannot be null");
}
if (mergeRequestId == null) {
throw new RuntimeException("projectId cannot be null");
}
Form formData = new Form();
addFormParam(formData, "source_branch", sourceBranch, false);
addFormParam(formData, "target_branch", targetBranch, false);
addFormParam(formData, "title", title, false);
addFormParam(formData, "description", description, false);
addFormParam(formData, "assignee_id", assigneeId, false);
Response response = put(Response.Status.OK, formData.asMap(), "projects", projectId, "merge_request", mergeRequestId);
return (response.readEntity(MergeRequest.class));
}
/**
* Adds a comment to a merge request.
*
* POST /projects/:id/merge_request/:merge_request_id/comments
*
* @param projectId
* @param mergeRequestId
* @param comments
* @return the added merge request comment
* @throws GitLabApiException
*/
public MergeRequestComment addMergeRequestComment(Integer projectId, Integer mergeRequestId, String comments) throws GitLabApiException {
Form formData = new Form();
formData.param("note", comments);
Response response = post(Response.Status.OK, formData, "projects", projectId, "merge_request", mergeRequestId, "comments");
return (response.readEntity(MergeRequestComment.class));
}
}
package com.messners.gitlab.api;
import com.messners.gitlab.api.models.Branch;
import com.messners.gitlab.api.models.Tag;
import com.messners.gitlab.api.models.TreeItem;
import java.util.List;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.Response;
import java.util.List;
import com.messners.gitlab.api.models.Branch;
import com.messners.gitlab.api.models.Tag;
import com.messners.gitlab.api.models.TreeItem;
/**
* This class provides an entry point to all the GitLab API repository calls.
......@@ -31,8 +32,7 @@ public class RepositoryApi extends AbstractApi {
*/
public List<Branch> getBranches(Integer projectId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId, "repository", "branches");
return (response.readEntity(new GenericType<List<Branch>>() {
}));
return (response.readEntity(new GenericType<List<Branch>>() {}));
}
/**
......@@ -62,13 +62,29 @@ public class RepositoryApi extends AbstractApi {
* @throws GitLabApiException
*/
public Branch createBranch(Integer projectId, String branchName, String ref) throws GitLabApiException {
Form formData = new Form();
formData.param("branch_name ", branchName);
formData.param("ref ", ref);
Response response = post(Response.Status.OK, formData, "projects", projectId, "repository", "branches");
addFormParam(formData, "branch_name", branchName, true);
addFormParam(formData, "ref", ref, true);
Response response = post(Response.Status.CREATED, formData.asMap(), "projects", projectId, "repository", "branches");
return (response.readEntity(Branch.class));
}
/**
* Delete a single project repository branch. This is an idempotent function,
* protecting an already protected repository branch will not produce an error.
*
* DELETE /projects/:id/repository/branches/:branch
*
* @param projectId
* @param branchName
* @return the branch info for the protected branch
* @throws GitLabApiException
*/
public void deleteBranch(Integer projectId, String branchName) throws GitLabApiException {
delete(Response.Status.OK, null, "projects", projectId, "repository", "branches", branchName);
}
/**
* Protects a single project repository branch. This is an idempotent function,
* protecting an already protected repository branch will not produce an error.
......
......@@ -5,7 +5,6 @@ import com.messners.gitlab.api.models.Session;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.Response;
/**
* This class implements the client side API for the GitLab login call.
*
......@@ -14,35 +13,33 @@ import javax.ws.rs.core.Response;
*/
public class SessionApi extends AbstractApi {
public SessionApi (GitLabApi gitLabApi) {
super(gitLabApi);
}
/**
* Login to get private token.
*
* POST /session
*
* @param username
* @param email
* @param password
* @return a Session instance with info on the logged in user
* @throws GitLabApiException
*/
public Session login (String username, String email, String password) throws GitLabApiException {
if ((username == null || username.trim().length() == 0)
&& (email == null || email.trim().length() == 0)) {
throw new IllegalArgumentException("both username and email cannot be empty or null");
}
Form formData = new Form();
addFormParam(formData, "email", email, false);
addFormParam(formData, "password", password, true);
addFormParam(formData, "login", username, false);
Response response = post(Response.Status.CREATED, formData, "session");
return (response.readEntity(Session.class));
}
public SessionApi(GitLabApi gitLabApi) {
super(gitLabApi);
}
/**
* Login to get private token.
*
* POST /session
*
* @param username
* @param email
* @param password
* @return a Session instance with info on the logged in user
* @throws GitLabApiException
*/
public Session login(String username, String email, String password) throws GitLabApiException {
if ((username == null || username.trim().length() == 0) && (email == null || email.trim().length() == 0)) {
throw new IllegalArgumentException("both username and email cannot be empty or null");
}
Form formData = new Form();
addFormParam(formData, "email", email, false);
addFormParam(formData, "password", password, true);
addFormParam(formData, "login", username, false);
Response response = post(Response.Status.CREATED, formData, "session");
return (response.readEntity(Session.class));
}
}
......@@ -10,59 +10,57 @@ import com.messners.gitlab.api.models.User;
public class UserApi extends AbstractApi {
UserApi (GitLabApi gitLabApi) {
super(gitLabApi);
}
/**
* Get a list of users. Only returns the first page
*
* GET /users
*
* @return a list of Users, this list will only contain the first 20 users in the system.
* @throws GitLabApiException
*/
public List<User> getUsers () throws GitLabApiException {
Response response = get(Response.Status.OK, null, "users");
return (response.readEntity(new GenericType<List<User>>() {}));
}
/**
* Get a list of users using the specified page and per page settings.
*
* GET /users
*
* @param page
* @param perPage
* @return the list of Users in the specified range
* @throws GitLabApiException
*/
public List<User> getUsers (int page, int perPage) throws GitLabApiException {
Form formData = new Form();
addFormParam(formData, "page", page, false);
addFormParam(formData, "per_page", perPage, false);
Response response = get(Response.Status.OK, formData.asMap(), "users");
return (response.readEntity(new GenericType<List<User>>() {}));
}
/**
* Get a single user.
*
* GET /users/:id
*
* @param userId
* @return the User instance for the specified user ID
* @throws GitLabApiException
*/
public User getUser (int userId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "users", userId);
return (response.readEntity(User.class));
}
UserApi(GitLabApi gitLabApi) {
super(gitLabApi);
}
/**
* Get a list of users. Only returns the first page
*
* GET /users
*
* @return a list of Users, this list will only contain the first 20 users in the system.
* @throws GitLabApiException
*/
public List<User> getUsers() throws GitLabApiException {
Response response = get(Response.Status.OK, null, "users");
return (response.readEntity(new GenericType<List<User>>() {
}));
}
/**
* Get a list of users using the specified page and per page settings.
*
* GET /users
*
* @param page
* @param perPage
* @return the list of Users in the specified range
* @throws GitLabApiException
*/
public List<User> getUsers(int page, int perPage) throws GitLabApiException {
Form formData = new Form();
addFormParam(formData, "page", page, false);
addFormParam(formData, "per_page", perPage, false);
Response response = get(Response.Status.OK, formData.asMap(), "users");
return (response.readEntity(new GenericType<List<User>>() {
}));
}
/**
* Get a single user.
*
* GET /users/:id
*
* @param userId
* @return the User instance for the specified user ID
* @throws GitLabApiException
*/
public User getUser(int userId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "users", userId);
return (response.readEntity(User.class));
}
/**
* Search users by Email or username
......@@ -70,125 +68,122 @@ public class UserApi extends AbstractApi {
* GET /users?search=:email_or_username
*
* @param emailOrUsername
* @return the User List with the email or username like emailOrUsername
* @throws GitLabApiException
* @return the User List with the email or username like emailOrUsername
* @throws GitLabApiException
*/
public List<User> findUsers(String emailOrUsername) throws GitLabApiException {
Form formData = new Form();
public List<User> findUsers(String emailOrUsername) throws GitLabApiException {
Form formData = new Form();
addFormParam(formData, "search", emailOrUsername, true);
Response response = get(Response.Status.OK, formData.asMap(), "users");
return (response.readEntity(new GenericType<List<User>>() {}));
return (response.readEntity(new GenericType<List<User>>() {
}));
}
/**
* Creates a new user. Note only administrators can create new users.
*
* POST /users
*
* email (required) - Email
* password (required) - Password
* username (required) - Username
* name (required) - Name
* skype (optional) - Skype ID
* linkedin (optional) - Linkedin
* twitter (optional) - Twitter account
* website_url (optional) - Website url
* projects_limit (optional) - Number of projects user can create
* extern_uid (optional) - External UID
* provider (optional) - External provider name
* bio (optional) - User's bio
* admin (optional) - User is admin - true or false (default)
* can_create_group (optional) - User can create groups - true or false
*
* @param user
* @return created User instance
* @throws GitLabApiException
*/
public User createUser(User user, String password, Integer projectsLimit) throws GitLabApiException {
Form formData = user2form(user, projectsLimit, password, true);
Response response = post(Response.Status.CREATED, formData, "users");
return (response.readEntity(User.class));
}
/**
* Modifies an existing user. Only administrators can change attributes of a user.
*
* PUT /users/:id
*
* email (required) - Email
* password (required) - Password
* username (required) - Username
* name (required) - Name
* skype (optional) - Skype ID
* linkedin (optional) - Linkedin
* twitter (optional) - Twitter account
* website_url (optional) - Website url
* projects_limit (optional) - Number of projects user can create
* extern_uid (optional) - External UID
* provider (optional) - External provider name
* bio (optional) - User's bio
* admin (optional) - User is admin - true or false (default)
* can_create_group (optional) - User can create groups - true or false
*
* @param user
* @return the modified User instance
* @throws GitLabApiException
*/
public User modifyUser(User user, String password, Integer projectsLimit) throws GitLabApiException {
Form form = user2form(user, projectsLimit, password, false);
Response response = put(Response.Status.OK, form.asMap(), "users", user.getId());
return (response.readEntity(User.class));
}
/**
* Deletes a user. Available only for administrators.
*
* DELETE /users/:id
*
* @param userId
* @throws GitLabApiException
*/
public void deleteUser(Integer userId) throws GitLabApiException {
if (userId == null) {
throw new RuntimeException("userId cannot be null");
}
delete(Response.Status.OK, null, "users", userId);
}
/**
* Deletes a user. Available only for administrators.
*
* DELETE /users/:id
*
* @param user
* @throws GitLabApiException
*/
public void deleteUser(User user) throws GitLabApiException {
deleteUser(user.getId());
}
/**
* Creates a new user. Note only administrators can create new users.
*
* POST /users
*
* email (required) - Email
* password (required) - Password
* username (required) - Username
* name (required) - Name
* skype (optional) - Skype ID
* linkedin (optional) - Linkedin
* twitter (optional) - Twitter account
* website_url (optional) - Website url
* projects_limit (optional) - Number of projects user can create
* extern_uid (optional) - External UID
* provider (optional) - External provider name
* bio (optional) - User's bio
* admin (optional) - User is admin - true or false (default)
* can_create_group (optional) - User can create groups - true or false
*
* @param user
* @return created User instance
* @throws GitLabApiException
*/
public User createUser (User user, String password, Integer projectsLimit) throws GitLabApiException {
Form formData = user2form(user, projectsLimit, password, true);
Response response = post(Response.Status.CREATED, formData, "users");
return (response.readEntity(User.class));
}
/**
* Modifies an existing user. Only administrators can change attributes of a user.
*
* PUT /users/:id
*
* email (required) - Email
* password (required) - Password
* username (required) - Username
* name (required) - Name
* skype (optional) - Skype ID
* linkedin (optional) - Linkedin
* twitter (optional) - Twitter account
* website_url (optional) - Website url
* projects_limit (optional) - Number of projects user can create
* extern_uid (optional) - External UID
* provider (optional) - External provider name
* bio (optional) - User's bio
* admin (optional) - User is admin - true or false (default)
* can_create_group (optional) - User can create groups - true or false
*
* @param user
* @return the modified User instance
* @throws GitLabApiException
*/
public User modifyUser (User user, String password, Integer projectsLimit) throws GitLabApiException {
Form form = user2form(user, projectsLimit, password, false);
Response response = put(Response.Status.OK, form.asMap(), "users", user.getId());
return (response.readEntity(User.class));
}
/**
* Deletes a user. Available only for administrators.
*
* DELETE /users/:id
*
* @param userId
* @throws GitLabApiException
*/
public void deleteUser (Integer userId) throws GitLabApiException {
if (userId == null) {
throw new RuntimeException("userId cannot be null");
}
delete(Response.Status.OK, null, "users", userId);
}
/**
* Deletes a user. Available only for administrators.
*
* DELETE /users/:id
*
* @param user
* @throws GitLabApiException
*/
public void deleteUser (User user) throws GitLabApiException {
deleteUser(user.getId());
}
private Form user2form(User user, Integer projectsLimit, String password, boolean isCreate) {
Form form = new Form();
addFormParam(form, "email", user.getEmail(), isCreate);
addFormParam(form, "password", password, isCreate);
addFormParam(form, "username", user.getUsername(), isCreate);
addFormParam(form, "name", user.getName(), isCreate);
addFormParam(form, "skype", user.getSkype(), false);
addFormParam(form, "linkedin", user.getLinkedin(), false);
addFormParam(form, "twitter", user.getTwitter(), false);
addFormParam(form, "website_url", user.getWebsiteUrl(), false);
addFormParam(form, "projects_limit", projectsLimit, false);
addFormParam(form, "extern_uid", user.getExternUid(), false);
addFormParam(form, "provider", user.getProvider(), false);
addFormParam(form, "bio", user.getBio(), false);
addFormParam(form, "admin", user.getIsAdmin(), false);
addFormParam(form, "can_create_group", user.getCanCreateGroup(), false);
return form;
}
private Form user2form(User user, Integer projectsLimit, String password, boolean isCreate) {
Form form = new Form();
addFormParam(form, "email", user.getEmail(), isCreate);
addFormParam(form, "password", password, isCreate);
addFormParam(form, "username", user.getUsername(), isCreate);
addFormParam(form, "name", user.getName(), isCreate);
addFormParam(form, "skype", user.getSkype(), false);
addFormParam(form, "linkedin", user.getLinkedin(), false);
addFormParam(form, "twitter", user.getTwitter(), false);
addFormParam(form, "website_url", user.getWebsiteUrl(), false);
addFormParam(form, "projects_limit", projectsLimit, false);
addFormParam(form, "extern_uid", user.getExternUid(), false);
addFormParam(form, "provider", user.getProvider(), false);
addFormParam(form, "bio", user.getBio(), false);
addFormParam(form, "admin", user.getIsAdmin(), false);
addFormParam(form, "can_create_group", user.getCanCreateGroup(), false);
return form;
}
}
......@@ -35,250 +35,250 @@ import com.messners.gitlab.api.models.TreeItem;
import com.messners.gitlab.api.models.User;
public class TestGitLabApiBeans {
private static JacksonJson jacksonJson;
public TestGitLabApiBeans () {
super();
}
@BeforeClass
public static void setup () {
jacksonJson = new JacksonJson();
}
@Test
public void testBranch () {
try {
Branch branch = makeFakeApiCall(Branch.class, "branch");
assertTrue(compareJson(branch, "branch"));
branch = makeFakeApiCall(Branch.class, "bad-branch");
assertTrue(!Branch.isValid(branch));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testDiff () {
try {
Diff diff = makeFakeApiCall(Diff.class, "diff");
assertTrue(compareJson(diff, "diff"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testEvent () {
try {
Event event = makeFakeApiCall(Event.class, "event");
assertTrue(compareJson(event, "event"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testGroup () {
try {
Group group = makeFakeApiCall(Group.class, "group");
assertTrue(compareJson(group, "group"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testIssue () {
try {
Issue issue = makeFakeApiCall(Issue.class, "issue");
assertTrue(compareJson(issue, "issue"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testProjectHook () {
try {
ProjectHook hook = makeFakeApiCall(ProjectHook.class, "hook");
assertTrue(compareJson(hook, "hook"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testKey () {
try {
Key key = makeFakeApiCall(Key.class, "key");
assertTrue(compareJson(key, "key"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testMember () {
try {
Member member = makeFakeApiCall(Member.class, "member");
assertTrue(compareJson(member, "member"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testMergeRequestComment () {
try {
MergeRequestComment mergeRequestComment = makeFakeApiCall(MergeRequestComment.class, "merge-request-comment");
assertTrue(compareJson(mergeRequestComment, "merge-request-comment"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testMergeRequest () {
try {
MergeRequest mergeRequest = makeFakeApiCall(MergeRequest.class, "merge-request");
assertTrue(compareJson(mergeRequest, "merge-request"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testMilestone () {
try {
Milestone milestone = makeFakeApiCall(Milestone.class, "milestone");
assertTrue(compareJson(milestone, "milestone"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testNote () {
try {
Note note = makeFakeApiCall(Note.class, "note");
assertTrue(compareJson(note, "note"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testProject () {
try {
Project project = makeFakeApiCall(Project.class, "project");
assertTrue(compareJson(project, "project"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testProjectSnippet () {
try {
ProjectSnippet projectSnippet = makeFakeApiCall(ProjectSnippet.class, "project-snippet");
assertTrue(compareJson(projectSnippet, "project-snippet"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testSession () {
try {
Session session = makeFakeApiCall(Session.class, "session");
assertTrue(compareJson(session, "session"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testSystemHook () {
try {
SystemHook systemHook = makeFakeApiCall(SystemHook.class, "system-hook");
assertTrue(compareJson(systemHook, "system-hook"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testTag () {
try {
Tag tag = makeFakeApiCall(Tag.class, "tag");
assertTrue(compareJson(tag, "tag"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testTree () {
try {
InputStreamReader reader = new InputStreamReader(GitLabApi.class.getResourceAsStream("tree.json"));
ObjectMapper objectMapper = jacksonJson.getContext(null);
List<TreeItem> tree = objectMapper.readValue(reader, new TypeReference<List<TreeItem>>(){});
assertTrue(compareJson(tree, "tree"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testUser () {
try {
User user = makeFakeApiCall(User.class, "user");
assertTrue(compareJson(user, "user"));
} catch (Exception e) {
e.printStackTrace();
}
}
private <T> T makeFakeApiCall (Class<T> returnType, String file) throws JsonParseException, JsonMappingException, IOException {
InputStreamReader reader = new InputStreamReader(GitLabApi.class.getResourceAsStream(file + ".json"));
ObjectMapper objectMapper = jacksonJson.getContext(returnType);
return (objectMapper.readValue(reader, returnType));
}
private <T> boolean compareJson (T apiObject, String file) throws IOException {
InputStreamReader reader = new InputStreamReader(GitLabApi.class.getResourceAsStream(file + ".json"));
String objectJson = jacksonJson.marshal(apiObject);
JsonNode tree1 = jacksonJson.getObjectMapper().readTree(objectJson.getBytes());
JsonNode tree2 = jacksonJson.getObjectMapper().readTree(reader);
boolean sameJson = tree1.equals(tree2);
return (sameJson);
}
private static JacksonJson jacksonJson;
public TestGitLabApiBeans() {
super();
}
@BeforeClass
public static void setup() {
jacksonJson = new JacksonJson();
}
@Test
public void testBranch() {
try {
Branch branch = makeFakeApiCall(Branch.class, "branch");
assertTrue(compareJson(branch, "branch"));
branch = makeFakeApiCall(Branch.class, "bad-branch");
assertTrue(!Branch.isValid(branch));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testDiff() {
try {
Diff diff = makeFakeApiCall(Diff.class, "diff");
assertTrue(compareJson(diff, "diff"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testEvent() {
try {
Event event = makeFakeApiCall(Event.class, "event");
assertTrue(compareJson(event, "event"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testGroup() {
try {
Group group = makeFakeApiCall(Group.class, "group");
assertTrue(compareJson(group, "group"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testIssue() {
try {
Issue issue = makeFakeApiCall(Issue.class, "issue");
assertTrue(compareJson(issue, "issue"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testProjectHook() {
try {
ProjectHook hook = makeFakeApiCall(ProjectHook.class, "hook");
assertTrue(compareJson(hook, "hook"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testKey() {
try {
Key key = makeFakeApiCall(Key.class, "key");
assertTrue(compareJson(key, "key"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testMember() {
try {
Member member = makeFakeApiCall(Member.class, "member");
assertTrue(compareJson(member, "member"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testMergeRequestComment() {
try {
MergeRequestComment mergeRequestComment = makeFakeApiCall(MergeRequestComment.class, "merge-request-comment");
assertTrue(compareJson(mergeRequestComment, "merge-request-comment"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testMergeRequest() {
try {
MergeRequest mergeRequest = makeFakeApiCall(MergeRequest.class, "merge-request");
assertTrue(compareJson(mergeRequest, "merge-request"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testMilestone() {
try {
Milestone milestone = makeFakeApiCall(Milestone.class, "milestone");
assertTrue(compareJson(milestone, "milestone"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testNote() {
try {
Note note = makeFakeApiCall(Note.class, "note");
assertTrue(compareJson(note, "note"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testProject() {
try {
Project project = makeFakeApiCall(Project.class, "project");
assertTrue(compareJson(project, "project"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testProjectSnippet() {
try {
ProjectSnippet projectSnippet = makeFakeApiCall(ProjectSnippet.class, "project-snippet");
assertTrue(compareJson(projectSnippet, "project-snippet"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testSession() {
try {
Session session = makeFakeApiCall(Session.class, "session");
assertTrue(compareJson(session, "session"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testSystemHook() {
try {
SystemHook systemHook = makeFakeApiCall(SystemHook.class, "system-hook");
assertTrue(compareJson(systemHook, "system-hook"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testTag() {
try {
Tag tag = makeFakeApiCall(Tag.class, "tag");
assertTrue(compareJson(tag, "tag"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testTree() {
try {
InputStreamReader reader = new InputStreamReader(GitLabApi.class.getResourceAsStream("tree.json"));
ObjectMapper objectMapper = jacksonJson.getContext(null);
List<TreeItem> tree = objectMapper.readValue(reader, new TypeReference<List<TreeItem>>() {
});
assertTrue(compareJson(tree, "tree"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testUser() {
try {
User user = makeFakeApiCall(User.class, "user");
assertTrue(compareJson(user, "user"));
} catch (Exception e) {
e.printStackTrace();
}
}
private <T> T makeFakeApiCall(Class<T> returnType, String file) throws JsonParseException, JsonMappingException, IOException {
InputStreamReader reader = new InputStreamReader(GitLabApi.class.getResourceAsStream(file + ".json"));
ObjectMapper objectMapper = jacksonJson.getContext(returnType);
return (objectMapper.readValue(reader, returnType));
}
private <T> boolean compareJson(T apiObject, String file) throws IOException {
InputStreamReader reader = new InputStreamReader(GitLabApi.class.getResourceAsStream(file + ".json"));
String objectJson = jacksonJson.marshal(apiObject);
JsonNode tree1 = jacksonJson.getObjectMapper().readTree(objectJson.getBytes());
JsonNode tree2 = jacksonJson.getObjectMapper().readTree(reader);
boolean sameJson = tree1.equals(tree2);
return (sameJson);
}
}
......@@ -16,65 +16,65 @@ import com.messners.gitlab.api.webhook.EventObject;
import com.messners.gitlab.api.webhook.PushEvent;
public class TestGitLabApiEvents {
private static JacksonJson jacksonJson;
public TestGitLabApiEvents () {
super();
}
@BeforeClass
public static void setup () {
jacksonJson = new JacksonJson();
}
@Test
public void testIssueEvent () {
try {
EventObject issueEvent = makeFakeApiCall(EventObject.class, "issue-event");
assertTrue(compareJson(issueEvent, "issue-event"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testMergeRequestEvent () {
try {
EventObject mergeRequestEvent = makeFakeApiCall(EventObject.class, "merge-request-event");
assertTrue(compareJson(mergeRequestEvent, "merge-request-event"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testPushEvent () {
try {
PushEvent pushEvent = makeFakeApiCall(PushEvent.class, "push-event");
assertTrue(compareJson(pushEvent, "push-event"));
} catch (Exception e) {
e.printStackTrace();
}
}
private <T> T makeFakeApiCall (Class<T> returnType, String file) throws JsonParseException, JsonMappingException, IOException {
InputStreamReader reader = new InputStreamReader(GitLabApi.class.getResourceAsStream(file + ".json"));
ObjectMapper objectMapper = jacksonJson.getContext(returnType);
return (objectMapper.readValue(reader, returnType));
}
private <T> boolean compareJson (T apiObject, String file) throws IOException {
InputStreamReader reader = new InputStreamReader(GitLabApi.class.getResourceAsStream(file + ".json"));
String objectJson = jacksonJson.marshal(apiObject);
JsonNode tree1 = jacksonJson.getObjectMapper().readTree(objectJson.getBytes());
JsonNode tree2 = jacksonJson.getObjectMapper().readTree(reader);
boolean sameJson = tree1.equals(tree2);
return (sameJson);
}
private static JacksonJson jacksonJson;
public TestGitLabApiEvents() {
super();
}
@BeforeClass
public static void setup() {
jacksonJson = new JacksonJson();
}
@Test
public void testIssueEvent() {
try {
EventObject issueEvent = makeFakeApiCall(EventObject.class, "issue-event");
assertTrue(compareJson(issueEvent, "issue-event"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testMergeRequestEvent() {
try {
EventObject mergeRequestEvent = makeFakeApiCall(EventObject.class, "merge-request-event");
assertTrue(compareJson(mergeRequestEvent, "merge-request-event"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testPushEvent() {
try {
PushEvent pushEvent = makeFakeApiCall(PushEvent.class, "push-event");
assertTrue(compareJson(pushEvent, "push-event"));
} catch (Exception e) {
e.printStackTrace();
}
}
private <T> T makeFakeApiCall(Class<T> returnType, String file) throws JsonParseException, JsonMappingException, IOException {
InputStreamReader reader = new InputStreamReader(GitLabApi.class.getResourceAsStream(file + ".json"));
ObjectMapper objectMapper = jacksonJson.getContext(returnType);
return (objectMapper.readValue(reader, returnType));
}
private <T> boolean compareJson(T apiObject, String file) throws IOException {
InputStreamReader reader = new InputStreamReader(GitLabApi.class.getResourceAsStream(file + ".json"));
String objectJson = jacksonJson.marshal(apiObject);
JsonNode tree1 = jacksonJson.getObjectMapper().readTree(objectJson.getBytes());
JsonNode tree2 = jacksonJson.getObjectMapper().readTree(reader);
boolean sameJson = tree1.equals(tree2);
return (sameJson);
}
}
......@@ -4,23 +4,23 @@ import java.io.IOException;
import java.io.Reader;
public class Utils {
/**
* Reads the content of a Reader instance and returns it as a String.
*
* @param reader
* @return the content of a Reader instance as a String
* @throws IOException
*/
public static String getReaderContentAsString (Reader reader) throws IOException {
int count;
final char[] buffer = new char[2048];
final StringBuilder out = new StringBuilder();
while ((count = reader.read(buffer, 0, buffer.length)) >= 0) {
out.append(buffer, 0, count);
}
return (out.toString());
}
/**
* Reads the content of a Reader instance and returns it as a String.
*
* @param reader
* @return the content of a Reader instance as a String
* @throws IOException
*/
public static String getReaderContentAsString(Reader reader) throws IOException {
int count;
final char[] buffer = new char[2048];
final StringBuilder out = new StringBuilder();
while ((count = reader.read(buffer, 0, buffer.length)) >= 0) {
out.append(buffer, 0, count);
}
return (out.toString());
}
}
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment