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