Merge branch 'stable-2.14' * stable-2.14: Remove System.out.println Change-Id: I0211a7726d1c888dd8d7fff4b68da5fedc09d8a6
diff --git a/github-oauth/pom.xml b/github-oauth/pom.xml index d1b4ccc..f56068a 100644 --- a/github-oauth/pom.xml +++ b/github-oauth/pom.xml
@@ -21,7 +21,7 @@ <parent> <groupId>com.googlesource.gerrit.plugins.github</groupId> <artifactId>github-parent</artifactId> - <version>2.14-SNAPSHOT</version> + <version>2.15-rc3</version> </parent> <artifactId>github-oauth</artifactId> <name>Gerrit Code Review - GitHub OAuth login</name>
diff --git a/github-oauth/src/main/java/com/google/gerrit/httpd/XGerritAuth.java b/github-oauth/src/main/java/com/google/gerrit/httpd/XGerritAuth.java index 4fd0734..457f627 100644 --- a/github-oauth/src/main/java/com/google/gerrit/httpd/XGerritAuth.java +++ b/github-oauth/src/main/java/com/google/gerrit/httpd/XGerritAuth.java
@@ -18,7 +18,6 @@ import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; - import javax.servlet.http.Cookie; @Singleton @@ -27,14 +26,14 @@ private WebSessionManager manager; @Inject - public XGerritAuth(WebSessionManagerFactory managerFactory, + public XGerritAuth( + WebSessionManagerFactory managerFactory, @Named(WebSessionManager.CACHE_NAME) Cache<String, Val> cache) { this.manager = managerFactory.create(cache); } public String getAuthValue(Cookie gerritCookie) { - Val session = - manager.get(new WebSessionManager.Key(gerritCookie.getValue())); + Val session = manager.get(new WebSessionManager.Key(gerritCookie.getValue())); return session.getAuth(); } }
diff --git a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/groups/OrganizationStructure.java b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/groups/OrganizationStructure.java index d577a62..8a56d0f 100644 --- a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/groups/OrganizationStructure.java +++ b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/groups/OrganizationStructure.java
@@ -14,14 +14,13 @@ package com.googlesource.gerrit.plugins.github.groups; +import com.google.common.base.MoreObjects; import java.io.Serializable; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; -import com.google.common.base.MoreObjects; - public class OrganizationStructure implements Serializable { private static final long serialVersionUID = 1L; @@ -29,8 +28,7 @@ public Set<String> put(String organisation, String team) { HashSet<String> userTeams = - MoreObjects.firstNonNull(teams.get(organisation), - new HashSet<String>()); + MoreObjects.firstNonNull(teams.get(organisation), new HashSet<String>()); userTeams.add(team); return teams.put(organisation, userTeams); } @@ -48,8 +46,7 @@ return teams .entrySet() .stream() - .map( - org -> "Organization " + org.getKey() + " Teams: " + org.getValue()) + .map(org -> "Organization " + org.getKey() + " Teams: " + org.getValue()) .collect(Collectors.joining(" : ")); } -} \ No newline at end of file +}
diff --git a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/AuthenticatedHttpRequest.java b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/AuthenticatedHttpRequest.java index 5475fcf..bcbe705 100644 --- a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/AuthenticatedHttpRequest.java +++ b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/AuthenticatedHttpRequest.java
@@ -14,22 +14,19 @@ package com.googlesource.gerrit.plugins.github.oauth; import com.google.common.collect.Iterators; - import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; public class AuthenticatedHttpRequest extends HttpServletRequestWrapper { private HashMap<String, String> headers = new HashMap<>(); - public AuthenticatedHttpRequest(HttpServletRequest request, - String... headerNamesValues) { + public AuthenticatedHttpRequest(HttpServletRequest request, String... headerNamesValues) { super(request); - for (int i = 0; i < headerNamesValues.length;) { + for (int i = 0; i < headerNamesValues.length; ) { String name = headerNamesValues[i++]; String value = headerNamesValues[i++]; if (name != null && value != null) {
diff --git a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/AuthenticatedLoginHttpRequest.java b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/AuthenticatedLoginHttpRequest.java index 2c5469b..8142259 100644 --- a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/AuthenticatedLoginHttpRequest.java +++ b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/AuthenticatedLoginHttpRequest.java
@@ -17,8 +17,8 @@ public class AuthenticatedLoginHttpRequest extends AuthenticatedPathHttpRequest { - public AuthenticatedLoginHttpRequest(HttpServletRequest request, - String userHeader, String username) { + public AuthenticatedLoginHttpRequest( + HttpServletRequest request, String userHeader, String username) { super(request, "/login", userHeader, username); } }
diff --git a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/AuthenticatedLoginHttpResponse.java b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/AuthenticatedLoginHttpResponse.java index e9bd369..26a1041 100644 --- a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/AuthenticatedLoginHttpResponse.java +++ b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/AuthenticatedLoginHttpResponse.java
@@ -20,7 +20,6 @@ import java.util.Collection; import java.util.Collections; import java.util.Locale; - import javax.servlet.ServletOutputStream; import javax.servlet.ServletResponse; import javax.servlet.WriteListener; @@ -41,7 +40,7 @@ @Override public void addCookie(Cookie cookie) { - if(cookie.getName().equals(OAuthWebFilter.GERRIT_COOKIE_NAME)) { + if (cookie.getName().equals(OAuthWebFilter.GERRIT_COOKIE_NAME)) { this.gerritCookie = cookie; } } @@ -51,16 +50,13 @@ } @Override - public void addDateHeader(String name, long date) { - } - - @Override - public void addHeader(String name, String value) { - } + public void addDateHeader(String name, long date) {} @Override - public void addIntHeader(String name, int value) { - } + public void addHeader(String name, String value) {} + + @Override + public void addIntHeader(String name, int value) {} @Override public boolean containsHeader(String name) { @@ -103,16 +99,13 @@ } @Override - public void setDateHeader(String name, long date) { - } + public void setDateHeader(String name, long date) {} @Override - public void setHeader(String name, String value) { - } + public void setHeader(String name, String value) {} @Override - public void setIntHeader(String name, int value) { - } + public void setIntHeader(String name, int value) {} @Override public void setStatus(int sc, String sm) { @@ -125,8 +118,7 @@ } @Override - public void flushBuffer() throws IOException { - } + public void flushBuffer() throws IOException {} @Override public int getBufferSize() { @@ -151,16 +143,15 @@ @Override public ServletOutputStream getOutputStream() throws IOException { return new ServletOutputStream() { - + @Override public void write(int b) throws IOException { outputStream.write(b); } - + @Override - public void setWriteListener(WriteListener arg0) { - } - + public void setWriteListener(WriteListener arg0) {} + @Override public boolean isReady() { return true; @@ -175,8 +166,7 @@ @Override public PrintWriter getWriter() throws IOException { - return new PrintWriter(new OutputStreamWriter(outputStream, - characterEncoding)); + return new PrintWriter(new OutputStreamWriter(outputStream, characterEncoding)); } @Override @@ -195,16 +185,13 @@ } @Override - public void reset() { - } + public void reset() {} @Override - public void resetBuffer() { - } + public void resetBuffer() {} @Override - public void setBufferSize(int size) { - } + public void setBufferSize(int size) {} @Override public void setCharacterEncoding(String charset) { @@ -212,12 +199,10 @@ } @Override - public void setContentLength(int len) { - } + public void setContentLength(int len) {} @Override - public void setContentLengthLong(long length) { - } + public void setContentLengthLong(long length) {} @Override public void setContentType(String type) { @@ -225,10 +210,8 @@ } @Override - public void setLocale(Locale loc) { - } + public void setLocale(Locale loc) {} @Override - public void setResponse(ServletResponse response) { - } + public void setResponse(ServletResponse response) {} }
diff --git a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/AuthenticatedPathHttpRequest.java b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/AuthenticatedPathHttpRequest.java index 53f7075..9fec9c0 100644 --- a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/AuthenticatedPathHttpRequest.java +++ b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/AuthenticatedPathHttpRequest.java
@@ -13,8 +13,6 @@ // limitations under the License. package com.googlesource.gerrit.plugins.github.oauth; - - import javax.servlet.http.HttpServletRequest; public class AuthenticatedPathHttpRequest extends AuthenticatedHttpRequest { @@ -24,8 +22,8 @@ private String requestURI; private String requestPath; - public AuthenticatedPathHttpRequest(HttpServletRequest request, String requestPath, - String userHeader, String username) { + public AuthenticatedPathHttpRequest( + HttpServletRequest request, String requestPath, String userHeader, String username) { super(request, userHeader, username); this.requestPath = requestPath; @@ -41,14 +39,12 @@ @Override public StringBuffer getRequestURL() { - return new StringBuffer(requestURL.substring(0, - requestURL.indexOf(requestURI)) - + getRequestURI()); + return new StringBuffer( + requestURL.substring(0, requestURL.indexOf(requestURI)) + getRequestURI()); } @Override public String getServletPath() { return requestPath; } - }
diff --git a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/GitHubHttpConnector.java b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/GitHubHttpConnector.java index 9881404..22a95d2 100644 --- a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/GitHubHttpConnector.java +++ b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/GitHubHttpConnector.java
@@ -14,14 +14,12 @@ package com.googlesource.gerrit.plugins.github.oauth; +import com.google.inject.Inject; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; - import org.kohsuke.github.HttpConnector; -import com.google.inject.Inject; - public class GitHubHttpConnector implements HttpConnector { private final GitHubOAuthConfig config; @@ -39,5 +37,4 @@ huc.setReadTimeout((int) config.httpReadTimeout); return huc; } - }
diff --git a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/GitHubLogin.java b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/GitHubLogin.java index 63ddb5d..1625b81 100644 --- a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/GitHubLogin.java +++ b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/GitHubLogin.java
@@ -16,6 +16,12 @@ import static java.util.concurrent.TimeUnit.DAYS; +import com.google.common.base.MoreObjects; +import com.google.common.base.Strings; +import com.google.inject.Inject; +import com.google.inject.Singleton; +import com.googlesource.gerrit.plugins.github.oauth.OAuthProtocol.AccessToken; +import com.googlesource.gerrit.plugins.github.oauth.OAuthProtocol.Scope; import java.io.IOException; import java.io.Serializable; import java.util.Arrays; @@ -25,13 +31,10 @@ import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; - import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import lombok.Getter; - import org.kohsuke.github.GHMyself; import org.kohsuke.github.GitHub; import org.kohsuke.github.GitHubBuilder; @@ -39,20 +42,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.base.MoreObjects; -import com.google.common.base.Strings; -import com.google.inject.Inject; -import com.google.inject.Singleton; -import com.googlesource.gerrit.plugins.github.oauth.OAuthProtocol.AccessToken; -import com.googlesource.gerrit.plugins.github.oauth.OAuthProtocol.Scope; - public class GitHubLogin implements Serializable { private static final long serialVersionUID = 1L; private static final Logger log = LoggerFactory.getLogger(GitHubLogin.class); - private static final List<Scope> DEFAULT_SCOPES = Arrays.asList( - Scope.PUBLIC_REPO, Scope.USER_EMAIL, Scope.READ_ORG); - private static final long SCOPE_COOKIE_NEVER_EXPIRES = DAYS - .toSeconds(50 * 365); + private static final List<Scope> DEFAULT_SCOPES = + Arrays.asList(Scope.PUBLIC_REPO, Scope.USER_EMAIL, Scope.READ_ORG); + private static final long SCOPE_COOKIE_NEVER_EXPIRES = DAYS.toSeconds(50 * 365); @Singleton public static class Provider extends HttpSessionProvider<GitHubLogin> { @@ -62,8 +57,7 @@ } } - @Getter - private AccessToken token; + @Getter private AccessToken token; private String state; @@ -86,8 +80,7 @@ } @Inject - public GitHubLogin(GitHubOAuthConfig config, - GitHubHttpConnector httpConnector) { + public GitHubLogin(GitHubOAuthConfig config, GitHubHttpConnector httpConnector) { this.config = config; this.httpConnector = httpConnector; } @@ -96,8 +89,12 @@ return token != null; } - public void login(HttpServletRequest request, - HttpServletResponse response, OAuthProtocol oauth, Scope... scopes) throws IOException { + public void login( + HttpServletRequest request, + HttpServletResponse response, + OAuthProtocol oauth, + Scope... scopes) + throws IOException { log.debug("Login " + this); if (OAuthProtocol.isOAuthFinal(request)) { @@ -112,13 +109,10 @@ } else { Set<String> configuredScopesProfiles = config.scopes.keySet(); String scopeRequested = getScopesKey(request, response); - if (Strings.isNullOrEmpty(scopeRequested) - && configuredScopesProfiles.size() > 1) { - response.sendRedirect(config.scopeSelectionUrl); + if (Strings.isNullOrEmpty(scopeRequested) && configuredScopesProfiles.size() > 1) { + response.sendRedirect(config.getScopeSelectionUrl(request)); } else { - this.loginScopes = - getScopes(MoreObjects.firstNonNull(scopeRequested, "scopes"), - scopes); + this.loginScopes = getScopes(MoreObjects.firstNonNull(scopeRequested, "scopes"), scopes); log.debug("Login-PHASE1 " + this); state = oauth.loginPhase1(request, response, loginScopes); } @@ -137,8 +131,7 @@ @Override public String toString() { - return "GitHubLogin [token=" + token + ", scopes=" - + loginScopes + "]"; + return "GitHubLogin [token=" + token + ", scopes=" + loginScopes + "]"; } public GitHub getHub() throws IOException { @@ -146,29 +139,27 @@ return null; } return new GitHubBuilder() - .withEndpoint(config.gitHubApiUrl) - .withOAuthToken(token.accessToken) - .withConnector(httpConnector) - .build(); + .withEndpoint(config.gitHubApiUrl) + .withOAuthToken(token.accessToken) + .withConnector(httpConnector) + .build(); } - private String getScopesKey(HttpServletRequest request, - HttpServletResponse response) { + private String getScopesKey(HttpServletRequest request, HttpServletResponse response) { String scopeRequested = request.getParameter("scope"); if (scopeRequested == null) { scopeRequested = getScopesKeyFromCookie(request); } boolean rememberScope = - Strings.nullToEmpty(request.getParameter("rememberScope")) - .equalsIgnoreCase("on"); + Strings.nullToEmpty(request.getParameter("rememberScope")).equalsIgnoreCase("on"); if (scopeRequested != null && rememberScope) { Cookie scopeCookie = new Cookie("scope", scopeRequested); scopeCookie.setPath("/"); scopeCookie.setMaxAge((int) SCOPE_COOKIE_NEVER_EXPIRES); response.addCookie(scopeCookie); } - + return scopeRequested; } @@ -194,7 +185,6 @@ } private List<Scope> scopesForKey(String baseScopeKey) { - return MoreObjects - .firstNonNull(config.scopes.get(baseScopeKey), DEFAULT_SCOPES); + return MoreObjects.firstNonNull(config.scopes.get(baseScopeKey), DEFAULT_SCOPES); } }
diff --git a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/GitHubLogoutServletResponse.java b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/GitHubLogoutServletResponse.java index 9f4709e..fe55930 100644 --- a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/GitHubLogoutServletResponse.java +++ b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/GitHubLogoutServletResponse.java
@@ -14,9 +14,7 @@ package com.googlesource.gerrit.plugins.github.oauth; import com.google.common.base.MoreObjects; - import java.io.IOException; - import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper;
diff --git a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/GitHubOAuthConfig.java b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/GitHubOAuthConfig.java index 7478c0a..319a850 100644 --- a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/GitHubOAuthConfig.java +++ b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/GitHubOAuthConfig.java
@@ -13,37 +13,36 @@ // limitations under the License. package com.googlesource.gerrit.plugins.github.oauth; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -import lombok.Getter; - -import org.eclipse.jgit.lib.Config; - import com.google.common.base.CharMatcher; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Maps; import com.google.gerrit.extensions.client.AuthType; +import com.google.gerrit.httpd.CanonicalWebUrl; import com.google.gerrit.server.config.AuthConfig; -import com.google.gerrit.server.config.CanonicalWebUrl; import com.google.gerrit.server.config.ConfigUtil; import com.google.gerrit.server.config.GerritServerConfig; import com.google.inject.Inject; import com.google.inject.Singleton; import com.googlesource.gerrit.plugins.github.oauth.OAuthProtocol.Scope; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import javax.servlet.http.HttpServletRequest; +import lombok.Getter; +import org.eclipse.jgit.lib.Config; @Singleton -public -class GitHubOAuthConfig { +public class GitHubOAuthConfig { + private final Config config; + private final CanonicalWebUrl canonicalWebUrl; + public static final String CONF_SECTION = "github"; public static final String GITHUB_OAUTH_AUTHORIZE = "/login/oauth/authorize"; - public static final String GITHUB_OAUTH_ACCESS_TOKEN = - "/login/oauth/access_token"; + public static final String GITHUB_OAUTH_ACCESS_TOKEN = "/login/oauth/access_token"; public static final String GITHUB_GET_USER = "/user"; public static final String GERRIT_OAUTH_FINAL = "/oauth"; public static final String GITHUB_URL_DEFAULT = "https://github.com"; @@ -59,42 +58,39 @@ public final String logoutRedirectUrl; public final String httpHeader; public final String gitHubOAuthUrl; - public final String oAuthFinalRedirectUrl; public final String gitHubOAuthAccessTokenUrl; public final boolean enabled; - @Getter - public final Map<String, List<OAuthProtocol.Scope>> scopes; + @Getter public final Map<String, List<OAuthProtocol.Scope>> scopes; public final int fileUpdateMaxRetryCount; public final int fileUpdateMaxRetryIntervalMsec; public final String oauthHttpHeader; - @Getter - public final String scopeSelectionUrl; public final long httpConnectionTimeout; public final long httpReadTimeout; @Inject - protected - GitHubOAuthConfig(@GerritServerConfig Config config, - @CanonicalWebUrl String canonicalWebUrl, - AuthConfig authConfig) { + protected GitHubOAuthConfig( + @GerritServerConfig Config config, CanonicalWebUrl canonicalWebUrl, AuthConfig authConfig) { + this.config = config; + this.canonicalWebUrl = canonicalWebUrl; + httpHeader = Preconditions.checkNotNull( config.getString("auth", null, "httpHeader"), "HTTP Header for GitHub user must be provided"); gitHubUrl = - trimTrailingSlash(MoreObjects.firstNonNull( - config.getString(CONF_SECTION, null, "url"), GITHUB_URL_DEFAULT)); + trimTrailingSlash( + MoreObjects.firstNonNull( + config.getString(CONF_SECTION, null, "url"), GITHUB_URL_DEFAULT)); gitHubApiUrl = - trimTrailingSlash(MoreObjects.firstNonNull( - config.getString(CONF_SECTION, null, "apiUrl"), - GITHUB_API_URL_DEFAULT)); + trimTrailingSlash( + MoreObjects.firstNonNull( + config.getString(CONF_SECTION, null, "apiUrl"), GITHUB_API_URL_DEFAULT)); gitHubClientId = Preconditions.checkNotNull( - config.getString(CONF_SECTION, null, "clientId"), - "GitHub `clientId` must be provided"); + config.getString(CONF_SECTION, null, "clientId"), "GitHub `clientId` must be provided"); gitHubClientSecret = Preconditions.checkNotNull( config.getString(CONF_SECTION, null, "clientSecret"), @@ -103,37 +99,39 @@ oauthHttpHeader = config.getString("auth", null, "httpExternalIdHeader"); gitHubOAuthUrl = gitHubUrl + GITHUB_OAUTH_AUTHORIZE; gitHubOAuthAccessTokenUrl = gitHubUrl + GITHUB_OAUTH_ACCESS_TOKEN; - logoutRedirectUrl = - config.getString(CONF_SECTION, null, "logoutRedirectUrl"); - oAuthFinalRedirectUrl = - trimTrailingSlash(canonicalWebUrl) + GERRIT_OAUTH_FINAL; - scopeSelectionUrl = - trimTrailingSlash(canonicalWebUrl) - + MoreObjects.firstNonNull( - config.getString(CONF_SECTION, null, "scopeSelectionUrl"), - GITHUB_PLUGIN_OAUTH_SCOPE); + logoutRedirectUrl = config.getString(CONF_SECTION, null, "logoutRedirectUrl"); - enabled = - config.getString("auth", null, "type").equalsIgnoreCase( - AuthType.HTTP.toString()); + enabled = config.getString("auth", null, "type").equalsIgnoreCase(AuthType.HTTP.toString()); scopes = getScopes(config); - fileUpdateMaxRetryCount = - config.getInt(CONF_SECTION, "fileUpdateMaxRetryCount", 3); + fileUpdateMaxRetryCount = config.getInt(CONF_SECTION, "fileUpdateMaxRetryCount", 3); fileUpdateMaxRetryIntervalMsec = config.getInt(CONF_SECTION, "fileUpdateMaxRetryIntervalMsec", 3000); httpConnectionTimeout = TimeUnit.MILLISECONDS.convert( - ConfigUtil.getTimeUnit(config, - CONF_SECTION, null, "httpConnectionTimeout", - 30, TimeUnit.SECONDS), TimeUnit.SECONDS); + ConfigUtil.getTimeUnit( + config, CONF_SECTION, null, "httpConnectionTimeout", 30, TimeUnit.SECONDS), + TimeUnit.SECONDS); httpReadTimeout = TimeUnit.MILLISECONDS.convert( - ConfigUtil.getTimeUnit(config, - CONF_SECTION, null, "httpReadTimeout", - 30, TimeUnit.SECONDS), TimeUnit.SECONDS); + ConfigUtil.getTimeUnit( + config, CONF_SECTION, null, "httpReadTimeout", 30, TimeUnit.SECONDS), + TimeUnit.SECONDS); + } + + public String getOAuthFinalRedirectUrl(HttpServletRequest req) { + return req == null + ? GERRIT_OAUTH_FINAL + : trimTrailingSlash(canonicalWebUrl.get(req)) + GERRIT_OAUTH_FINAL; + } + + public String getScopeSelectionUrl(HttpServletRequest req) { + String canonicalUrl = req == null ? "" : trimTrailingSlash(canonicalWebUrl.get(req)); + return canonicalUrl + + MoreObjects.firstNonNull( + config.getString(CONF_SECTION, null, "scopeSelectionUrl"), GITHUB_PLUGIN_OAUTH_SCOPE); } private Map<String, List<Scope>> getScopes(Config config) {
diff --git a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/GsonProvider.java b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/GsonProvider.java index fd004c0..40d0da2 100644 --- a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/GsonProvider.java +++ b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/GsonProvider.java
@@ -25,7 +25,8 @@ @Override public Gson get() { - return new GsonBuilder().setFieldNamingPolicy( - FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); + return new GsonBuilder() + .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) + .create(); } }
diff --git a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/HttpSessionProvider.java b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/HttpSessionProvider.java index 79fdbc0..fdde648 100644 --- a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/HttpSessionProvider.java +++ b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/HttpSessionProvider.java
@@ -15,17 +15,14 @@ import com.google.inject.Inject; import com.google.inject.Provider; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; public abstract class HttpSessionProvider<T> implements ScopedProvider<T> { - @Inject - private Provider<T> provider; + @Inject private Provider<T> provider; - @Inject - private Provider<HttpServletRequest> httpRequestProvider; + @Inject private Provider<HttpServletRequest> httpRequestProvider; @Override public T get() {
diff --git a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/IdentifiedUserGitHubLoginProvider.java b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/IdentifiedUserGitHubLoginProvider.java index 4c92e2e..c5c7161 100644 --- a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/IdentifiedUserGitHubLoginProvider.java +++ b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/IdentifiedUserGitHubLoginProvider.java
@@ -14,30 +14,26 @@ package com.googlesource.gerrit.plugins.github.oauth; -import java.io.IOException; -import java.util.Collection; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.google.gerrit.common.Nullable; -import com.google.gerrit.reviewdb.client.AccountExternalId; import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.account.AccountCache; import com.google.gerrit.server.account.AccountState; -import com.google.gerrit.server.account.ExternalId; +import com.google.gerrit.server.account.externalids.ExternalId; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import com.googlesource.gerrit.plugins.github.oauth.OAuthProtocol.AccessToken; +import java.io.IOException; +import java.util.Collection; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @Singleton -public class IdentifiedUserGitHubLoginProvider implements - UserScopedProvider<GitHubLogin> { - private static final Logger log = LoggerFactory - .getLogger(IdentifiedUserGitHubLoginProvider.class); +public class IdentifiedUserGitHubLoginProvider implements UserScopedProvider<GitHubLogin> { + private static final Logger log = + LoggerFactory.getLogger(IdentifiedUserGitHubLoginProvider.class); public static final String EXTERNAL_ID_PREFIX = - AccountExternalId.SCHEME_EXTERNAL + OAuthWebFilter.GITHUB_EXT_ID; + ExternalId.SCHEME_EXTERNAL + ":" + OAuthWebFilter.GITHUB_EXT_ID; private final Provider<IdentifiedUser> userProvider; private final GitHubOAuthConfig config; @@ -83,7 +79,7 @@ AccountState account = accountCache.getByUsername(username); Collection<ExternalId> externalIds = account.getExternalIds(); for (ExternalId accountExternalId : externalIds) { - String key = accountExternalId.asAccountExternalId().getKey().get(); + String key = accountExternalId.key().get(); if (key.startsWith(EXTERNAL_ID_PREFIX)) { return new AccessToken(key.substring(EXTERNAL_ID_PREFIX.length())); }
diff --git a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthCache.java b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthCache.java index 7cdc825..955c86d 100644 --- a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthCache.java +++ b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthCache.java
@@ -20,15 +20,13 @@ import com.google.inject.Module; import com.google.inject.Singleton; import com.google.inject.name.Named; - import com.googlesource.gerrit.plugins.github.oauth.OAuthProtocol.AccessToken; - import java.util.concurrent.ExecutionException; @Singleton public class OAuthCache { private static final String CACHE_NAME = "github_oauth"; - + public static class Loader extends CacheLoader<AccessToken, String> { private GitHubLogin ghLogin; @@ -48,22 +46,20 @@ return new CacheModule() { @Override protected void configure() { - cache(CACHE_NAME, AccessToken.class, String.class) - .loader(Loader.class); + cache(CACHE_NAME, AccessToken.class, String.class).loader(Loader.class); bind(OAuthCache.class); } }; } private LoadingCache<AccessToken, String> byAccesToken; - + @Inject public OAuthCache(@Named(CACHE_NAME) LoadingCache<AccessToken, String> byAccessToken) { this.byAccesToken = byAccessToken; } - - public String getLoginByAccessToken(AccessToken accessToken) - throws ExecutionException { + + public String getLoginByAccessToken(AccessToken accessToken) throws ExecutionException { return byAccesToken.get(accessToken); } }
diff --git a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthFilter.java b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthFilter.java index ce997bd..d68749e 100644 --- a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthFilter.java +++ b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthFilter.java
@@ -19,14 +19,9 @@ import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; - -import org.apache.commons.lang.StringUtils; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.util.Set; import java.util.regex.Pattern; - import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -34,27 +29,23 @@ import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; +import org.apache.commons.lang.StringUtils; +import org.slf4j.LoggerFactory; @Singleton public class OAuthFilter implements Filter { - private static final org.slf4j.Logger log = LoggerFactory - .getLogger(OAuthFilter.class); - private static Pattern GIT_HTTP_REQUEST_PATTERN = Pattern - .compile(GitOverHttpServlet.URL_REGEX); - private static final Set<String> GERRIT_STATIC_RESOURCES_EXTS = Sets - .newHashSet("css", "png", "jpg", "gif", "woff", "otf", - "ttf", "map", "js", "swf", "txt"); - private static final Set<String> GERRIT_WHITELISTED_PATHS = Sets - .newHashSet("Documentation"); - private static final Set<String> GERRIT_WHITELISTED_PAGES = Sets - .newHashSet("scope.html"); + private static final org.slf4j.Logger log = LoggerFactory.getLogger(OAuthFilter.class); + private static Pattern GIT_HTTP_REQUEST_PATTERN = Pattern.compile(GitOverHttpServlet.URL_REGEX); + private static final Set<String> GERRIT_STATIC_RESOURCES_EXTS = + Sets.newHashSet("css", "png", "jpg", "gif", "woff", "otf", "ttf", "map", "js", "swf", "txt"); + private static final Set<String> GERRIT_WHITELISTED_PATHS = Sets.newHashSet("Documentation"); + private static final Set<String> GERRIT_WHITELISTED_PAGES = Sets.newHashSet("scope.html"); private final GitHubOAuthConfig config; private final OAuthWebFilter webFilter; @Inject - public OAuthFilter(GitHubOAuthConfig config, - OAuthWebFilter webFilter, Injector injector) { + public OAuthFilter(GitHubOAuthConfig config, OAuthWebFilter webFilter, Injector injector) { this.config = config; this.webFilter = webFilter; } @@ -65,8 +56,8 @@ } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; String requestUrl = httpRequest.getRequestURI(); @@ -85,13 +76,13 @@ public static boolean skipOAuth(HttpServletRequest httpRequest) { return isStaticResource(httpRequest) - || isRpcCall(httpRequest) || isAuthenticatedRestCall(httpRequest) + || isRpcCall(httpRequest) + || isAuthenticatedRestCall(httpRequest) || isWhitelisted(httpRequest); } private static boolean isAuthenticatedRestCall(HttpServletRequest httpRequest) { - return !StringUtils.isEmpty(httpRequest - .getHeader(XGerritAuth.X_GERRIT_AUTH)); + return !StringUtils.isEmpty(httpRequest.getHeader(XGerritAuth.X_GERRIT_AUTH)); } private static boolean isStaticResource(HttpServletRequest httpRequest) { @@ -101,16 +92,14 @@ return false; } - boolean staticResource = - GERRIT_STATIC_RESOURCES_EXTS.contains(pathExt.toLowerCase()); - return staticResource; + return GERRIT_STATIC_RESOURCES_EXTS.contains(pathExt.toLowerCase()); } private static boolean isWhitelisted(HttpServletRequest httpRequest) { String[] requestPathParts = httpRequest.getRequestURI().split("/"); - return (requestPathParts.length > 1 && (GERRIT_WHITELISTED_PATHS - .contains(requestPathParts[1]) || GERRIT_WHITELISTED_PAGES - .contains(requestPathParts[requestPathParts.length - 1]))); + return (requestPathParts.length > 1 + && (GERRIT_WHITELISTED_PATHS.contains(requestPathParts[1]) + || GERRIT_WHITELISTED_PAGES.contains(requestPathParts[requestPathParts.length - 1]))); } private static boolean isRpcCall(HttpServletRequest httpRequest) {
diff --git a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthGitWrappedResponse.java b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthGitWrappedResponse.java index 947d931..4253ea2 100644 --- a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthGitWrappedResponse.java +++ b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthGitWrappedResponse.java
@@ -14,13 +14,11 @@ package com.googlesource.gerrit.plugins.github.oauth; import java.io.IOException; - import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; public class OAuthGitWrappedResponse extends HttpServletResponseWrapper { - public static final String GIT_REALM_NAME = - "GitHub authentication for Gerrit Code Review"; + public static final String GIT_REALM_NAME = "GitHub authentication for Gerrit Code Review"; private static final String GIT_AUTHENTICATION_BASIC = "Basic "; private static final String WWW_AUTHENTICATE = "WWW-Authenticate";
diff --git a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthProtocol.java b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthProtocol.java index f1ef494..ddbbec9 100644 --- a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthProtocol.java +++ b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthProtocol.java
@@ -4,21 +4,12 @@ import com.google.common.base.Strings; import com.google.common.io.BaseEncoding; import com.google.common.io.CharStreams; +import com.google.gerrit.extensions.auth.oauth.OAuthToken; +import com.google.gerrit.extensions.auth.oauth.OAuthVerifier; import com.google.gson.Gson; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; - -import org.apache.http.HttpResponse; -import org.apache.http.NameValuePair; -import org.apache.http.client.HttpClient; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.util.EntityUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -32,166 +23,131 @@ import java.util.List; import java.util.Objects; import java.util.Set; - import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import lombok.Getter; - -import com.google.gerrit.extensions.auth.oauth.OAuthToken; -import com.google.gerrit.extensions.auth.oauth.OAuthVerifier; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.HttpClient; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @Singleton public class OAuthProtocol { /** * Supported OAuth Scopes. * - * OAuth authorization scopes as defined in GitHub API at: + * <p>OAuth authorization scopes as defined in GitHub API at: * https://developer.github.com/v3/oauth/#scopes */ public static enum Scope { /** - * Grants read-only access to public information (includes public user - * profile info, public repository info, and gists) + * Grants read-only access to public information (includes public user profile info, public + * repository info, and gists) */ DEFAULT("", "Read-only public information"), /** - * Grants read/write access to profile info only. Note that this scope - * includes user:email and user:follow. + * Grants read/write access to profile info only. Note that this scope includes user:email and + * user:follow. */ USER("user", "Read/write profile info"), - /** - * Grants read access to a user’s email addresses. - */ + /** Grants read access to a user’s email addresses. */ USER_EMAIL("user:email", "Read-only user's e-mail"), - /** - * Grants access to follow or unfollow other users. - */ + /** Grants access to follow or unfollow other users. */ USER_FOLLOW("user:follow", "(Un)Follow users"), /** - * Grants read/write access to code, commit statuses, collaborators, and - * deployment statuses for public repositories. Also - * required for starring public repositories. + * Grants read/write access to code, commit statuses, collaborators, and deployment statuses for + * public repositories. Also required for starring public repositories. */ PUBLIC_REPO("public_repo", "Read/write to public repositories"), /** - * Grants read/write access to code, commit statuses, collaborators, and - * deployment statuses for public and private repositories and - * organizations. + * Grants read/write access to code, commit statuses, collaborators, and deployment statuses for + * public and private repositories and organizations. */ REPO("repo", "Read/write to all public/private repositories"), /** - * Grants access to deployment statuses for public and private repositories. - * This scope is only necessary to grant other users or services access to - * deployment statuses, without granting access to the code. + * Grants access to deployment statuses for public and private repositories. This scope is only + * necessary to grant other users or services access to deployment statuses, without granting + * access to the code. */ REPO_DEPLOYMENT("repo_deployment", "Read-only deployment statuses"), /** - * Grants read/write access to public and private repository commit - * statuses. This scope is only necessary to grant other users or services - * access to private repository commit statuses without granting access to - * the code. + * Grants read/write access to public and private repository commit statuses. This scope is only + * necessary to grant other users or services access to private repository commit statuses + * without granting access to the code. */ REPO_STATUS("repo:status", "Read/write commit statuses"), - /** - * Grants access to delete admin-able repositories. - */ + /** Grants access to delete admin-able repositories. */ DELETE_REPO("delete_repo", "Delete repositories"), - /** - * Grants read access to a user’s notifications. repo also provides this - * access. - */ + /** Grants read access to a user’s notifications. repo also provides this access. */ NOTIFICATIONS("notifications", "Read user's notifications"), - /** - * Grants write access to gists. - */ + /** Grants write access to gists. */ GIST("gist", "Write Gists"), - /** - * Grants read and ping access to hooks in public or private repositories. - */ - READ_REPO_HOOK("read:repo_hook", - "Read/ping public/private repositories' hooks"), + /** Grants read and ping access to hooks in public or private repositories. */ + READ_REPO_HOOK("read:repo_hook", "Read/ping public/private repositories' hooks"), + + /** Grants read, write, and ping access to hooks in public or private repositories. */ + WRITE_REPO_HOOK("write:repo_hook", "Read/write/ping public/private repositories' hooks"), + + /** Grants read, write, ping, and delete access to hooks in public or private repositories. */ + ADMIN_REPO_HOOK( + "admin:repo_hook", "Read/write/ping/delete access to public/private repositories' hooks"), /** - * Grants read, write, and ping access to hooks in public or private - * repositories. + * Grants read, write, ping, and delete access to organization hooks. Note: OAuth tokens will + * only be able to perform these actions on organization hooks which were created by the OAuth + * application. Personal access tokens will only be able to perform these actions on + * organization hooks created by a user. */ - WRITE_REPO_HOOK("write:repo_hook", - "Read/write/ping public/private repositories' hooks"), + ADMIN_ORG_HOOK( + "admin:org_hook", "Read/write/ping/delete access to public/private organizations' hooks"), - /** - * Grants read, write, ping, and delete access to hooks in public or private - * repositories. - */ - ADMIN_REPO_HOOK("admin:repo_hook", - "Read/write/ping/delete access to public/private repositories' hooks"), - - /** - * Grants read, write, ping, and delete access to organization hooks. Note: - * OAuth tokens will only be able to perform these actions on organization - * hooks which were created by the OAuth application. Personal access tokens - * will only be able to perform these actions on organization hooks created - * by a user. - */ - ADMIN_ORG_HOOK("admin:org_hook", - "Read/write/ping/delete access to public/private organizations' hooks"), - - /** - * Read-only access to organization, teams, and membership. - */ + /** Read-only access to organization, teams, and membership. */ READ_ORG("read:org", "Read-only organizations"), - /** - * Publicize and un-publicize organization membership. - */ + /** Publicize and un-publicize organization membership. */ WRITE_ORG("write:org", "(Un)Publicize organizations membership"), - /** - * Fully manage organization, teams, and memberships. - */ + /** Fully manage organization, teams, and memberships. */ ADMIN_ORG("admin:org", "Manage organizations, teams and memberships"), - /** - * List and view details for public keys. - */ + /** List and view details for public keys. */ READ_PUBLIC_KEY("read:public_key", "Read-only user's public keys"), - /** - * Create, list, and view details for public keys. - */ + /** Create, list, and view details for public keys. */ WRITE_PUBLIC_KEY("write:public_key", "Read/write/list user's public keys"), - /** - * Fully manage public keys. - */ + /** Fully manage public keys. */ ADMIN_PUBLIC_KEY("admin:public_key", "Fully manage user's public keys"); - @Getter - private final String value; + @Getter private final String value; - @Getter - private final String description; + @Getter private final String description; private Scope(final String value, final String description) { this.value = value; this.description = description; } } + private static final String ME_SEPARATOR = ","; - private static final Logger log = LoggerFactory - .getLogger(OAuthProtocol.class); + private static final Logger log = LoggerFactory.getLogger(OAuthProtocol.class); private static final String FINAL_URL_PARAM = "final"; private static SecureRandom randomState = newRandomGenerator(); @@ -207,8 +163,7 @@ public String errorUri; public String raw; - public AccessToken() { - } + public AccessToken() {} public AccessToken(String token) { this(token, ""); @@ -223,17 +178,20 @@ @Override public String toString() { if (isError()) { - return "Error AccessToken [error=" + error + ", error_description=" - + errorDescription + ", error_uri=" + errorUri + "]"; + return "Error AccessToken [error=" + + error + + ", error_description=" + + errorDescription + + ", error_uri=" + + errorUri + + "]"; } - return "AccessToken [access_token=" + accessToken + ", token_type=" - + tokenType + "]"; + return "AccessToken [access_token=" + accessToken + ", token_type=" + tokenType + "]"; } @Override public int hashCode() { - return Objects.hash(accessToken, tokenType, error, errorDescription, - errorUri); + return Objects.hash(accessToken, tokenType, error, errorDescription, errorUri); } @Override @@ -268,7 +226,8 @@ } @Inject - public OAuthProtocol(GitHubOAuthConfig config, + public OAuthProtocol( + GitHubOAuthConfig config, PooledHttpClientProvider httpClientProvider, /* * We need to explicitly tell Guice which Provider<> we need as this class @@ -285,31 +244,40 @@ try { return SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { - throw new IllegalArgumentException( - "No SecureRandom available for GitHub authentication", e); + throw new IllegalArgumentException("No SecureRandom available for GitHub authentication", e); } } - public String getAuthorizationUrl(String scopesString, String state) { - return config.gitHubOAuthUrl + "?client_id=" + config.gitHubClientId + public String getAuthorizationUrl(String scopesString, String state, HttpServletRequest req) { + return config.gitHubOAuthUrl + + "?client_id=" + + config.gitHubClientId + getURLEncodedParameter("&scope=", scopesString) - + getURLEncodedParameter("&redirect_uri=", config.oAuthFinalRedirectUrl) + + getURLEncodedParameter("&redirect_uri=", config.getOAuthFinalRedirectUrl(req)) + getURLEncodedParameter("&state=", state); } - public String loginPhase1(HttpServletRequest request, - HttpServletResponse response, Set<Scope> scopes) throws IOException { + public String loginPhase1( + HttpServletRequest request, HttpServletResponse response, Set<Scope> scopes) + throws IOException { String scopesString = getScope(scopes); - log.debug("Initiating GitHub Login for ClientId=" + config.gitHubClientId - + " Scopes=" + scopesString); + log.debug( + "Initiating GitHub Login for ClientId=" + + config.gitHubClientId + + " Scopes=" + + scopesString); String state = newRandomState(request.getRequestURI().toString()); - log.debug("Initiating GitHub Login for ClientId=" + config.gitHubClientId + " Scopes=" + scopesString); - response.sendRedirect(getAuthorizationUrl(scopesString, state)); + log.debug( + "Initiating GitHub Login for ClientId=" + + config.gitHubClientId + + " Scopes=" + + scopesString); + response.sendRedirect(getAuthorizationUrl(scopesString, state, request)); return state; } public String getScope(Set<Scope> scopes) { - if(scopes.size() <= 0) { + if (scopes.size() <= 0) { return ""; } @@ -358,12 +326,12 @@ return OAuthProtocol.isOAuthLogin(httpRequest) || OAuthProtocol.isOAuthFinal(httpRequest); } - public AccessToken loginPhase2(HttpServletRequest request, - HttpServletResponse response, String state) throws IOException { + public AccessToken loginPhase2( + HttpServletRequest request, HttpServletResponse response, String state) throws IOException { String requestState = request.getParameter("state"); if (!Objects.equals(state, requestState)) { - throw new IOException("Invalid authentication state: expected '" + state - + "' but was '" + requestState + "'"); + throw new IOException( + "Invalid authentication state: expected '" + state + "' but was '" + requestState + "'"); } return getAccessToken(new OAuthVerifier(request.getParameter("code"))); @@ -380,21 +348,21 @@ HttpResponse postResponse = httpProvider.get().execute(post); if (postResponse.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) { - log.error("POST " + config.gitHubOAuthAccessTokenUrl - + " request for access token failed with status " - + postResponse.getStatusLine()); + log.error( + "POST " + + config.gitHubOAuthAccessTokenUrl + + " request for access token failed with status " + + postResponse.getStatusLine()); EntityUtils.consume(postResponse.getEntity()); throw new IOException("GitHub OAuth request failed"); } InputStream content = postResponse.getEntity().getContent(); String tokenJsonString = - CharStreams.toString(new InputStreamReader(content, - StandardCharsets.UTF_8)); + CharStreams.toString(new InputStreamReader(content, StandardCharsets.UTF_8)); AccessToken token = gson.fromJson(tokenJsonString, AccessToken.class); if (token.isError()) { - log.error("POST " + config.gitHubOAuthAccessTokenUrl - + " returned an error token: " + token); + log.error("POST " + config.gitHubOAuthAccessTokenUrl + " returned an error token: " + token); throw new IOException("Invalid GitHub OAuth token"); } @@ -403,8 +371,7 @@ private static String getURLEncodedParameter(String prefix, String url) { try { - return Strings.isNullOrEmpty(url) ? - "" : (prefix + URLEncoder.encode(url,"UTF-8")); + return Strings.isNullOrEmpty(url) ? "" : (prefix + URLEncoder.encode(url, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Cannot find UTF-8 encoding", e); } @@ -434,5 +401,4 @@ public String toString() { return "OAuthProtocol"; } - }
diff --git a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthTokenException.java b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthTokenException.java index 3ee1291..ce88429 100644 --- a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthTokenException.java +++ b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthTokenException.java
@@ -23,5 +23,4 @@ } private static final long serialVersionUID = -2177841968402814337L; - }
diff --git a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthWebFilter.java b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthWebFilter.java index af2d9d5..316d1bb 100644 --- a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthWebFilter.java +++ b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/OAuthWebFilter.java
@@ -13,24 +13,14 @@ // limitations under the License. package com.googlesource.gerrit.plugins.github.oauth; - import com.google.gerrit.server.config.SitePaths; import com.google.inject.Inject; import com.google.inject.Singleton; - -import org.apache.commons.lang.StringUtils; -import org.eclipse.jgit.errors.ConfigInvalidException; -import org.eclipse.jgit.storage.file.FileBasedConfig; -import org.eclipse.jgit.util.FS; -import org.kohsuke.github.GHMyself; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.attribute.FileTime; import java.util.Random; import java.util.Set; - import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -41,11 +31,16 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; +import org.apache.commons.lang.StringUtils; +import org.eclipse.jgit.errors.ConfigInvalidException; +import org.eclipse.jgit.storage.file.FileBasedConfig; +import org.eclipse.jgit.util.FS; +import org.kohsuke.github.GHMyself; +import org.slf4j.LoggerFactory; @Singleton public class OAuthWebFilter implements Filter { - private static final org.slf4j.Logger log = LoggerFactory - .getLogger(OAuthWebFilter.class); + private static final org.slf4j.Logger log = LoggerFactory.getLogger(OAuthWebFilter.class); public static final String GERRIT_COOKIE_NAME = "GerritAccount"; public static final String GITHUB_EXT_ID = "github_oauth:"; @@ -56,11 +51,12 @@ private final OAuthProtocol oauth; @Inject - public OAuthWebFilter(GitHubOAuthConfig config, + public OAuthWebFilter( + GitHubOAuthConfig config, SitePaths sites, OAuthProtocol oauth, - // We need to explicitly tell Guice the correct implementation - // as this filter is instantiated with a standard Gerrit WebModule + // We need to explicitly tell Guice the correct implementation + // as this filter is instantiated with a standard Gerrit WebModule GitHubLogin.Provider loginProvider) { this.config = config; this.sites = sites; @@ -69,17 +65,16 @@ } @Override - public void init(FilterConfig filterConfig) throws ServletException { - } + public void init(FilterConfig filterConfig) throws ServletException {} @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; - log.debug("OAuthWebFilter(" + httpRequest.getRequestURL() + ") code=" - + request.getParameter("code")); + log.debug( + "OAuthWebFilter(" + httpRequest.getRequestURL() + ") code=" + request.getParameter("code")); Cookie gerritCookie = getGerritCookie(httpRequest); try { @@ -89,14 +84,16 @@ login(request, httpRequest, httpResponse, ghLogin); } else { if (OAuthProtocol.isOAuthLogout(httpRequest)) { - httpResponse = - (HttpServletResponse) logout(request, httpResponse, chain, httpRequest); + httpResponse = (HttpServletResponse) logout(request, httpResponse, chain, httpRequest); } if (ghLogin != null && ghLogin.isLoggedIn()) { httpRequest = - new AuthenticatedHttpRequest(httpRequest, config.httpHeader, - ghLogin.getMyself().getLogin(), config.oauthHttpHeader, + new AuthenticatedHttpRequest( + httpRequest, + config.httpHeader, + ghLogin.getMyself().getLogin(), + config.oauthHttpHeader, GITHUB_EXT_ID + ghLogin.getToken().accessToken); } @@ -106,8 +103,7 @@ HttpSession httpSession = httpRequest.getSession(); if (gerritCookie != null && httpSession != null) { String gerritCookieValue = gerritCookie.getValue(); - String gerritSessionValue = - (String) httpSession.getAttribute("GerritAccount"); + String gerritSessionValue = (String) httpSession.getAttribute("GerritAccount"); if (gerritSessionValue == null) { httpSession.setAttribute("GerritAccount", gerritCookieValue); @@ -118,32 +114,38 @@ } } - private void login(ServletRequest request, HttpServletRequest httpRequest, - HttpServletResponse httpResponse, GitHubLogin ghLogin) throws IOException { + private void login( + ServletRequest request, + HttpServletRequest httpRequest, + HttpServletResponse httpResponse, + GitHubLogin ghLogin) + throws IOException { ghLogin.login(httpRequest, httpResponse, oauth); if (ghLogin.isLoggedIn()) { GHMyself myself = ghLogin.getMyself(); String user = myself.getLogin(); - updateSecureConfigWithRetry(ghLogin.getHub().getMyOrganizations().keySet(), - user, ghLogin.getToken().accessToken); + updateSecureConfigWithRetry( + ghLogin.getHub().getMyOrganizations().keySet(), user, ghLogin.getToken().accessToken); } } - private ServletResponse logout(ServletRequest request, - ServletResponse response, FilterChain chain, + private ServletResponse logout( + ServletRequest request, + ServletResponse response, + FilterChain chain, HttpServletRequest httpRequest) { getGitHubLogin(request).logout(); - return new GitHubLogoutServletResponse((HttpServletResponse) response, - config.logoutRedirectUrl); + return new GitHubLogoutServletResponse( + (HttpServletResponse) response, config.logoutRedirectUrl); } private GitHubLogin getGitHubLogin(ServletRequest request) { return loginProvider.get((HttpServletRequest) request); } - private void updateSecureConfigWithRetry(Set<String> organisations, - String user, String access_token) { + private void updateSecureConfigWithRetry( + Set<String> organisations, String user, String access_token) { int retryCount = 0; while (retryCount < config.fileUpdateMaxRetryCount) { @@ -152,68 +154,68 @@ return; } catch (IOException e) { retryCount++; - int retryInterval = - retryRandom.nextInt(config.fileUpdateMaxRetryIntervalMsec); - log.warn("Error whilst trying to update " - + sites.secure_config - + (retryCount < config.fileUpdateMaxRetryCount ? ": attempt #" - + retryCount + " will be retried after " + retryInterval - + " msecs" : ""), e); + int retryInterval = retryRandom.nextInt(config.fileUpdateMaxRetryIntervalMsec); + log.warn( + "Error whilst trying to update " + + sites.secure_config + + (retryCount < config.fileUpdateMaxRetryCount + ? ": attempt #" + + retryCount + + " will be retried after " + + retryInterval + + " msecs" + : ""), + e); try { Thread.sleep(retryInterval); } catch (InterruptedException e1) { - log.error("Thread has been cancelled before retrying to save " - + sites.secure_config); + log.error("Thread has been cancelled before retrying to save " + sites.secure_config); return; } } catch (ConfigInvalidException e) { - log.error("Cannot update " + sites.secure_config - + " as the file is corrupted", e); + log.error("Cannot update " + sites.secure_config + " as the file is corrupted", e); return; } } } - private synchronized void updateSecureConfig(Set<String> organisations, - String user, String access_token) throws IOException, - ConfigInvalidException { + private synchronized void updateSecureConfig( + Set<String> organisations, String user, String access_token) + throws IOException, ConfigInvalidException { FileBasedConfig currentSecureConfig = new FileBasedConfig(sites.secure_config.toFile(), FS.DETECTED); FileTime currentSecureConfigUpdateTs = Files.getLastModifiedTime(sites.secure_config); currentSecureConfig.load(); - boolean configUpdate = - updateConfigSection(currentSecureConfig, user, user, access_token); + boolean configUpdate = updateConfigSection(currentSecureConfig, user, user, access_token); for (String organisation : organisations) { - configUpdate |= - updateConfigSection(currentSecureConfig, organisation, user, - access_token); + configUpdate |= updateConfigSection(currentSecureConfig, organisation, user, access_token); } if (!configUpdate) { return; } - log.info("Updating " + sites.secure_config + " credentials for user " - + user); + log.info("Updating " + sites.secure_config + " credentials for user " + user); - FileTime secureConfigCurrentModifiedTime = - Files.getLastModifiedTime(sites.secure_config); + FileTime secureConfigCurrentModifiedTime = Files.getLastModifiedTime(sites.secure_config); if (!secureConfigCurrentModifiedTime.equals(currentSecureConfigUpdateTs)) { - throw new ConcurrentFileBasedConfigWriteException("File " - + sites.secure_config + " was written at " - + secureConfigCurrentModifiedTime - + " while was trying to update security for user " + user); + throw new ConcurrentFileBasedConfigWriteException( + "File " + + sites.secure_config + + " was written at " + + secureConfigCurrentModifiedTime + + " while was trying to update security for user " + + user); } currentSecureConfig.save(); } - private boolean updateConfigSection(FileBasedConfig c, String section, - String user, String password) { + private boolean updateConfigSection( + FileBasedConfig c, String section, String user, String password) { String configUser = c.getString("remote", section, "username"); String configPassword = c.getString("remote", section, "password"); - if (!StringUtils.equals(configUser, user) - || StringUtils.equals(configPassword, password)) { + if (!StringUtils.equals(configUser, user) || StringUtils.equals(configPassword, password)) { return false; }
diff --git a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/PooledHttpClientProvider.java b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/PooledHttpClientProvider.java index 4376242..06f73a7 100644 --- a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/PooledHttpClientProvider.java +++ b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/PooledHttpClientProvider.java
@@ -19,7 +19,7 @@ import com.google.gerrit.server.config.GerritServerConfig; import com.google.inject.Inject; import com.google.inject.Provider; - +import java.net.URL; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; @@ -30,16 +30,13 @@ import org.apache.http.impl.client.ProxyAuthenticationStrategy; import org.eclipse.jgit.lib.Config; -import java.net.URL; - public class PooledHttpClientProvider implements Provider<HttpClient> { private final int maxTotalConnection; private final int maxConnectionPerRoute; private final ProxyProperties proxy; @Inject - PooledHttpClientProvider(@GerritServerConfig Config config, - ProxyProperties proxyProperties) { + PooledHttpClientProvider(@GerritServerConfig Config config, ProxyProperties proxyProperties) { this.proxy = proxyProperties; URL proxyUrl = proxyProperties.getProxyUrl(); if (proxyUrl != null) { @@ -49,10 +46,8 @@ setProxyProperty("proxyPassword", proxyProperties.getPassword()); } - maxConnectionPerRoute = config.getInt("http", null, - "pooledMaxConnectionsPerRoute", 16); - maxTotalConnection = config.getInt("http", null, - "pooledMaxTotalConnections", 32); + maxConnectionPerRoute = config.getInt("http", null, "pooledMaxConnectionsPerRoute", 16); + maxTotalConnection = config.getInt("http", null, "pooledMaxTotalConnections", 32); } private static void setProxyProperty(String property, String value) { @@ -64,24 +59,22 @@ @Override public HttpClient get() { - HttpClientBuilder builder = HttpClientBuilder - .create() - .setMaxConnPerRoute(maxConnectionPerRoute) - .setMaxConnTotal(maxTotalConnection); + HttpClientBuilder builder = + HttpClientBuilder.create() + .setMaxConnPerRoute(maxConnectionPerRoute) + .setMaxConnTotal(maxTotalConnection); if (proxy.getProxyUrl() != null) { URL url = proxy.getProxyUrl(); builder.setProxy(new HttpHost(url.getHost(), url.getPort())); if (!Strings.isNullOrEmpty(proxy.getUsername()) && !Strings.isNullOrEmpty(proxy.getPassword())) { - UsernamePasswordCredentials creds = new UsernamePasswordCredentials( - proxy.getUsername(), proxy.getPassword()); + UsernamePasswordCredentials creds = + new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials(new AuthScope(url.getHost(), - url.getPort()), creds); + credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()), creds); builder.setDefaultCredentialsProvider(credsProvider); - builder.setProxyAuthenticationStrategy( - new ProxyAuthenticationStrategy()); + builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); } }
diff --git a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/ScopedProvider.java b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/ScopedProvider.java index 9cc4f3a..9c68dde 100644 --- a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/ScopedProvider.java +++ b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/ScopedProvider.java
@@ -14,11 +14,9 @@ package com.googlesource.gerrit.plugins.github.oauth; import com.google.inject.Provider; - import javax.servlet.http.HttpServletRequest; - -public interface ScopedProvider<T> extends Provider<T>{ +public interface ScopedProvider<T> extends Provider<T> { T get(HttpServletRequest request); HttpServletRequest getScopedRequest();
diff --git a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/UserScopedProvider.java b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/UserScopedProvider.java index 93f474d..698f067 100644 --- a/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/UserScopedProvider.java +++ b/github-oauth/src/main/java/com/googlesource/gerrit/plugins/github/oauth/UserScopedProvider.java
@@ -18,5 +18,6 @@ import com.google.inject.Provider; public interface UserScopedProvider<T> extends Provider<T> { - @Nullable T get(String username); + @Nullable + T get(String username); }
diff --git a/github-plugin/pom.xml b/github-plugin/pom.xml index eac938b..21c5b61 100644 --- a/github-plugin/pom.xml +++ b/github-plugin/pom.xml
@@ -20,7 +20,7 @@ <parent> <artifactId>github-parent</artifactId> <groupId>com.googlesource.gerrit.plugins.github</groupId> - <version>2.14-SNAPSHOT</version> + <version>2.15-rc3</version> </parent> <artifactId>github-plugin</artifactId>
diff --git a/github-plugin/src/main/java/com/google/gerrit/server/account/AccountImporter.java b/github-plugin/src/main/java/com/google/gerrit/server/account/AccountImporter.java index cc05a43..dd8f712 100644 --- a/github-plugin/src/main/java/com/google/gerrit/server/account/AccountImporter.java +++ b/github-plugin/src/main/java/com/google/gerrit/server/account/AccountImporter.java
@@ -23,53 +23,48 @@ import com.google.gerrit.extensions.restapi.UnprocessableEntityException; import com.google.gerrit.reviewdb.client.Account; import com.google.gerrit.reviewdb.client.Account.Id; -import com.google.gerrit.reviewdb.client.AccountExternalId; -import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.server.account.CreateAccount.Factory; +import com.google.gerrit.server.account.externalids.ExternalId; +import com.google.gerrit.server.account.externalids.ExternalIdsUpdate; import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; -import com.google.inject.Provider; - +import java.io.IOException; import org.apache.http.HttpStatus; import org.eclipse.jgit.errors.ConfigInvalidException; -import java.io.IOException; -import java.util.Arrays; - public class AccountImporter { private final Factory createAccountFactory; - private final Provider<ReviewDb> schema; + private final ExternalIdsUpdate.Server externalIdsUpdateServer; @Inject - public AccountImporter(final CreateAccount.Factory createAccountFactory, - final Provider<ReviewDb> schema) { + public AccountImporter( + final CreateAccount.Factory createAccountFactory, + ExternalIdsUpdate.Server externalIdsUpdateServer) { this.createAccountFactory = createAccountFactory; - this.schema = schema; + this.externalIdsUpdateServer = externalIdsUpdateServer; } public Account.Id importAccount(String login, String name, String email) throws IOException, BadRequestException, ResourceConflictException, - UnprocessableEntityException, OrmException, ConfigInvalidException { - try (ReviewDb db = schema.get()) { - CreateAccount createAccount = createAccountFactory.create(login); - AccountInput accountInput = new AccountInput(); - accountInput.email = email; - accountInput.username = login; - accountInput.name = MoreObjects.firstNonNull(name, login); - Response<AccountInfo> accountResponse = - createAccount.apply(TopLevelResource.INSTANCE, accountInput); - if (accountResponse.statusCode() != HttpStatus.SC_CREATED) { - throw new IOException("Cannot import GitHub account " + login - + ": HTTP Status " + accountResponse.statusCode()); - } - Id accountId = new Account.Id( - accountResponse.value()._accountId.intValue()); - db.accountExternalIds().insert( - Arrays - .asList(new AccountExternalId(accountId, - new AccountExternalId.Key(AccountExternalId.SCHEME_GERRIT, - login)))); - return accountId; + UnprocessableEntityException, OrmException, ConfigInvalidException { + CreateAccount createAccount = createAccountFactory.create(login); + AccountInput accountInput = new AccountInput(); + accountInput.email = email; + accountInput.username = login; + accountInput.name = MoreObjects.firstNonNull(name, login); + Response<AccountInfo> accountResponse = + createAccount.apply(TopLevelResource.INSTANCE, accountInput); + if (accountResponse.statusCode() != HttpStatus.SC_CREATED) { + throw new IOException( + "Cannot import GitHub account " + + login + + ": HTTP Status " + + accountResponse.statusCode()); } + Id accountId = new Account.Id(accountResponse.value()._accountId.intValue()); + externalIdsUpdateServer + .create() + .insert(ExternalId.create(ExternalId.SCHEME_GERRIT, login, accountId)); + return accountId; } }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GitHubConfig.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GitHubConfig.java index 249a61e..a6646b1 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GitHubConfig.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GitHubConfig.java
@@ -15,20 +15,18 @@ import com.google.common.base.MoreObjects; import com.google.common.collect.Maps; +import com.google.gerrit.httpd.CanonicalWebUrl; import com.google.gerrit.server.config.AllProjectsNameProvider; import com.google.gerrit.server.config.AuthConfig; -import com.google.gerrit.server.config.CanonicalWebUrl; import com.google.gerrit.server.config.GerritServerConfig; import com.google.gerrit.server.config.SitePaths; import com.google.inject.Inject; import com.google.inject.Singleton; import com.googlesource.gerrit.plugins.github.oauth.GitHubOAuthConfig; - -import org.eclipse.jgit.lib.Config; - import java.net.MalformedURLException; import java.nio.file.Path; import java.util.HashMap; +import org.eclipse.jgit.lib.Config; @Singleton public class GitHubConfig extends GitHubOAuthConfig { @@ -39,12 +37,9 @@ private static final String FROM_TO_REDIRECT_SEPARATOR = "R>"; private static final String CONF_JOB_POOL_LIMIT = "jobPoolLimit"; private static final String CONF_JOB_EXEC_TIMEOUT = "jobExecTimeout"; - private static final String CONF_PULL_REQUEST_LIST_LIMIT = - "pullRequestListLimit"; - private static final String CONF_REPOSITORY_LIST_PAGE_SIZE = - "repositoryListPageSize"; - private static final String CONF_REPOSITORY_LIST_LIMIT = - "repositoryListLimit"; + private static final String CONF_PULL_REQUEST_LIST_LIMIT = "pullRequestListLimit"; + private static final String CONF_REPOSITORY_LIST_PAGE_SIZE = "repositoryListPageSize"; + private static final String CONF_REPOSITORY_LIST_LIMIT = "repositoryListLimit"; private static final String CONF_PUBLIC_BASE_PROJECT = "publicBaseProject"; private static final String CONF_PRIVATE_BASE_PROJECT = "privateBaseProject"; private static final String CONF_WEBHOOK_SECRET = "webhookSecret"; @@ -72,53 +67,46 @@ } } - @Inject - public GitHubConfig(@GerritServerConfig Config config, - final SitePaths site, + public GitHubConfig( + @GerritServerConfig Config config, + final SitePaths site, AllProjectsNameProvider allProjectsNameProvider, - @CanonicalWebUrl String canonicalWebUrl, + CanonicalWebUrl canonicalWebUrl, AuthConfig authConfig) throws MalformedURLException { super(config, canonicalWebUrl, authConfig); - String[] wizardFlows = - config.getStringList(CONF_SECTION, null, CONF_WIZARD_FLOW); + String[] wizardFlows = config.getStringList(CONF_SECTION, null, CONF_WIZARD_FLOW); for (String fromTo : wizardFlows) { boolean redirect = fromTo.indexOf(FROM_TO_REDIRECT_SEPARATOR) > 0; int sepPos = getSepPos(fromTo, redirect); String fromPage = fromTo.substring(0, sepPos).trim(); NextPage toPage = - new NextPage(fromTo.substring( - sepPos + getSeparator(redirect).length() + 1).trim(), redirect); + new NextPage( + fromTo.substring(sepPos + getSeparator(redirect).length() + 1).trim(), redirect); wizardFromTo.put(fromPage, toPage); } jobPoolLimit = config.getInt(CONF_SECTION, CONF_JOB_POOL_LIMIT, 5); jobExecTimeout = config.getInt(CONF_SECTION, CONF_JOB_EXEC_TIMEOUT, 10); - pullRequestListLimit = - config.getInt(CONF_SECTION, CONF_PULL_REQUEST_LIST_LIMIT, 50); - repositoryListPageSize = - config.getInt(CONF_SECTION, CONF_REPOSITORY_LIST_PAGE_SIZE, 50); - repositoryListLimit = - config.getInt(CONF_SECTION, CONF_REPOSITORY_LIST_LIMIT, 50); + pullRequestListLimit = config.getInt(CONF_SECTION, CONF_PULL_REQUEST_LIST_LIMIT, 50); + repositoryListPageSize = config.getInt(CONF_SECTION, CONF_REPOSITORY_LIST_PAGE_SIZE, 50); + repositoryListLimit = config.getInt(CONF_SECTION, CONF_REPOSITORY_LIST_LIMIT, 50); gitDir = site.resolve(config.getString("gerrit", null, "basePath")); if (gitDir == null) { throw new IllegalStateException("gerrit.basePath must be configured"); } - privateBaseProject = - config.getString(CONF_SECTION, null, CONF_PRIVATE_BASE_PROJECT); - publicBaseProject = - config.getString(CONF_SECTION, null, CONF_PUBLIC_BASE_PROJECT); + privateBaseProject = config.getString(CONF_SECTION, null, CONF_PRIVATE_BASE_PROJECT); + publicBaseProject = config.getString(CONF_SECTION, null, CONF_PUBLIC_BASE_PROJECT); allProjectsName = allProjectsNameProvider.get().toString(); webhookSecret = config.getString(CONF_SECTION, null, CONF_WEBHOOK_SECRET); webhookUser = config.getString(CONF_SECTION, null, CONF_WEBHOOK_USER); } private String getSeparator(boolean redirect) { - String separator = - redirect ? FROM_TO_REDIRECT_SEPARATOR : FROM_TO_SEPARATOR; + String separator = redirect ? FROM_TO_REDIRECT_SEPARATOR : FROM_TO_SEPARATOR; return separator; } @@ -135,7 +123,7 @@ } public String getBaseProject(boolean isPrivateProject) { - return MoreObjects.firstNonNull(isPrivateProject ? privateBaseProject - : publicBaseProject, allProjectsName); + return MoreObjects.firstNonNull( + isPrivateProject ? privateBaseProject : publicBaseProject, allProjectsName); } }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GitHubOAuthServiceProvider.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GitHubOAuthServiceProvider.java index 0a617fc..6c2cb84 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GitHubOAuthServiceProvider.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GitHubOAuthServiceProvider.java
@@ -14,34 +14,30 @@ package com.googlesource.gerrit.plugins.github; -import java.io.IOException; - -import org.kohsuke.github.GHMyself; -import org.kohsuke.github.GitHub; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.google.common.collect.Sets; import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider; import com.google.gerrit.extensions.auth.oauth.OAuthToken; import com.google.gerrit.extensions.auth.oauth.OAuthUserInfo; import com.google.gerrit.extensions.auth.oauth.OAuthVerifier; -import com.google.gerrit.reviewdb.client.AccountExternalId; +import com.google.gerrit.server.account.externalids.ExternalId; import com.google.inject.Inject; import com.googlesource.gerrit.plugins.github.oauth.GitHubOAuthConfig; import com.googlesource.gerrit.plugins.github.oauth.OAuthProtocol; +import java.io.IOException; +import org.kohsuke.github.GHMyself; +import org.kohsuke.github.GitHub; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class GitHubOAuthServiceProvider implements OAuthServiceProvider { public static final String VERSION = "2.10.3"; - private static final Logger log = LoggerFactory - .getLogger(GitHubOAuthServiceProvider.class); + private static final Logger log = LoggerFactory.getLogger(GitHubOAuthServiceProvider.class); private final GitHubOAuthConfig config; private final OAuthProtocol oauth; @Inject - public GitHubOAuthServiceProvider(GitHubOAuthConfig config, - OAuthProtocol oauth) { + public GitHubOAuthServiceProvider(GitHubOAuthConfig config, OAuthProtocol oauth) { this.config = config; this.oauth = oauth; } @@ -49,7 +45,7 @@ @Override public String getAuthorizationUrl() { return oauth.getAuthorizationUrl( - oauth.getScope(Sets.newHashSet(config.getDefaultScopes())), null); + oauth.getScope(Sets.newHashSet(config.getDefaultScopes())), null, null); } @Override @@ -68,8 +64,8 @@ GitHub hub = GitHub.connectUsingOAuth(oauthToken); GHMyself myself = hub.getMyself(); String login = myself.getLogin(); - return new OAuthUserInfo(AccountExternalId.SCHEME_GERRIT + login, login, - myself.getEmail(), myself.getName(), null); + return new OAuthUserInfo( + ExternalId.SCHEME_GERRIT + login, login, myself.getEmail(), myself.getName(), null); } @Override
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GitHubTopMenu.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GitHubTopMenu.java index 66ed7e1..5ff5363 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GitHubTopMenu.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GitHubTopMenu.java
@@ -24,7 +24,6 @@ import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; - import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -37,17 +36,21 @@ private final AuthConfig authConfig; @Inject - public GitHubTopMenu(@PluginName String pluginName, + public GitHubTopMenu( + @PluginName String pluginName, Provider<CurrentUser> userProvider, AuthConfig authConfig, GitHubConfig ghConfig) { String baseUrl = "/plugins/" + pluginName; this.menuEntries = - Arrays.asList(new MenuEntry("GitHub", Arrays.asList( - getItem("Scope", ghConfig.scopeSelectionUrl), - getItem("Profile", baseUrl + "/static/account.html"), - getItem("Repositories", baseUrl + "/static/repositories.html"), - getItem("Pull Requests", baseUrl + "/static/pullrequests.html")))); + Arrays.asList( + new MenuEntry( + "GitHub", + Arrays.asList( + getItem("Scope", ghConfig.getScopeSelectionUrl(null)), + getItem("Profile", baseUrl + "/static/account.html"), + getItem("Repositories", baseUrl + "/static/repositories.html"), + getItem("Pull Requests", baseUrl + "/static/pullrequests.html")))); this.userProvider = userProvider; this.authConfig = authConfig; } @@ -58,7 +61,8 @@ @Override public List<MenuEntry> getEntries() { - if (userProvider.get() instanceof IdentifiedUser && + if (userProvider.get() instanceof IdentifiedUser + && // Only with HTTP authentication we can transparently trigger OAuth if needed authConfig.getAuthType().equals(AuthType.HTTP)) { return menuEntries;
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GitHubURL.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GitHubURL.java index a53c76e..c6841d2 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GitHubURL.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GitHubURL.java
@@ -14,7 +14,6 @@ package com.googlesource.gerrit.plugins.github; import com.google.inject.BindingAnnotation; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -23,6 +22,4 @@ @Target({ElementType.PARAMETER, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @BindingAnnotation -public @interface GitHubURL { - -} +public @interface GitHubURL {}
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GitHubURLProvider.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GitHubURLProvider.java index ae5ca0f..e64b586 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GitHubURLProvider.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GitHubURLProvider.java
@@ -29,5 +29,4 @@ public String get() { return gitHubUrl; } - }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GuiceHttpModule.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GuiceHttpModule.java index 744823e..12acdb2 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GuiceHttpModule.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GuiceHttpModule.java
@@ -13,9 +13,6 @@ // limitations under the License. package com.googlesource.gerrit.plugins.github; -import org.apache.http.client.HttpClient; -import org.apache.velocity.runtime.RuntimeInstance; - import com.google.gerrit.extensions.annotations.Exports; import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider; import com.google.inject.TypeLiteral; @@ -38,6 +35,8 @@ import com.googlesource.gerrit.plugins.github.velocity.VelocityStaticServlet; import com.googlesource.gerrit.plugins.github.velocity.VelocityViewServlet; import com.googlesource.gerrit.plugins.github.wizard.VelocityControllerServlet; +import org.apache.http.client.HttpClient; +import org.apache.velocity.runtime.RuntimeInstance; public class GuiceHttpModule extends ServletModule { @@ -50,29 +49,39 @@ install(new FactoryModuleBuilder().build(RemoteSiteUser.Factory.class)); - install(new FactoryModuleBuilder().implement(GitCloneStep.class, - GitCloneStep.class).build(GitCloneStep.Factory.class)); - install(new FactoryModuleBuilder().implement(CreateProjectStep.class, - CreateProjectStep.class).build(CreateProjectStep.Factory.class)); - install(new FactoryModuleBuilder().implement(ReplicateProjectStep.class, - ReplicateProjectStep.class).build(ReplicateProjectStep.Factory.class)); - install(new FactoryModuleBuilder().implement(PullRequestImportJob.class, - PullRequestImportJob.class).build(PullRequestImportJob.Factory.class)); - install(new FactoryModuleBuilder().implement(GitHubRepository.class, - GitHubRepository.class).build(GitHubRepository.Factory.class)); + install( + new FactoryModuleBuilder() + .implement(GitCloneStep.class, GitCloneStep.class) + .build(GitCloneStep.Factory.class)); + install( + new FactoryModuleBuilder() + .implement(CreateProjectStep.class, CreateProjectStep.class) + .build(CreateProjectStep.Factory.class)); + install( + new FactoryModuleBuilder() + .implement(ReplicateProjectStep.class, ReplicateProjectStep.class) + .build(ReplicateProjectStep.Factory.class)); + install( + new FactoryModuleBuilder() + .implement(PullRequestImportJob.class, PullRequestImportJob.class) + .build(PullRequestImportJob.Factory.class)); + install( + new FactoryModuleBuilder() + .implement(GitHubRepository.class, GitHubRepository.class) + .build(GitHubRepository.Factory.class)); - bind(RuntimeInstance.class).annotatedWith( - Names.named("PluginRuntimeInstance")).toProvider( - PluginVelocityRuntimeProvider.class); + bind(RuntimeInstance.class) + .annotatedWith(Names.named("PluginRuntimeInstance")) + .toProvider(PluginVelocityRuntimeProvider.class); - bind(String.class).annotatedWith(GitHubURL.class).toProvider( - GitHubURLProvider.class); + bind(String.class).annotatedWith(GitHubURL.class).toProvider(GitHubURLProvider.class); - bind(OAuthServiceProvider.class).annotatedWith( - Exports.named("github")).to(GitHubOAuthServiceProvider.class); + bind(OAuthServiceProvider.class) + .annotatedWith(Exports.named("github")) + .to(GitHubOAuthServiceProvider.class); - serve("*.css", "*.js", "*.png", "*.jpg", "*.woff", "*.gif", "*.ttf").with( - VelocityStaticServlet.class); + serve("*.css", "*.js", "*.png", "*.jpg", "*.woff", "*.gif", "*.ttf") + .with(VelocityStaticServlet.class); serve("*.gh").with(VelocityControllerServlet.class); serve("/webhook").with(WebhookServlet.class);
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GuiceModule.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GuiceModule.java index 0521cef..2014f1d 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GuiceModule.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GuiceModule.java
@@ -41,8 +41,8 @@ public class GuiceModule extends AbstractModule { @Override protected void configure() { - bind(new TypeLiteral<UserScopedProvider<GitHubLogin>>() {}).to( - IdentifiedUserGitHubLoginProvider.class); + bind(new TypeLiteral<UserScopedProvider<GitHubLogin>>() {}) + .to(IdentifiedUserGitHubLoginProvider.class); install(GitHubGroupsCache.module()); @@ -50,21 +50,18 @@ DynamicSet.bind(binder(), GroupBackend.class).to(GitHubGroupBackend.class); DynamicSet.bind(binder(), EventListener.class).to(ReplicationStatusListener.class); - install(new FactoryModuleBuilder() - .build(GitHubOrganisationGroup.Factory.class)); - install(new FactoryModuleBuilder() - .build(GitHubGroupMembership.Factory.class)); + install(new FactoryModuleBuilder().build(GitHubOrganisationGroup.Factory.class)); + install(new FactoryModuleBuilder().build(GitHubGroupMembership.Factory.class)); - install(new RestApiModule() { - @Override - protected void configure() { - get(ProjectResource.PROJECT_KIND, "replication").to( - ListProjectReplicationStatus.class); - } - }); + install( + new RestApiModule() { + @Override + protected void configure() { + get(ProjectResource.PROJECT_KIND, "replication").to(ListProjectReplicationStatus.class); + } + }); - bind(ReplicationStatusStore.class).to(ReplicationStatusFlatFile.class) - .in(Scopes.SINGLETON); + bind(ReplicationStatusStore.class).to(ReplicationStatusFlatFile.class).in(Scopes.SINGLETON); bind(Gson.class).toProvider(GerritGsonProvider.class); } }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/InitGitHub.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/InitGitHub.java index 5a78252..6e5975d 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/InitGitHub.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/InitGitHub.java
@@ -13,31 +13,30 @@ // limitations under the License. package com.googlesource.gerrit.plugins.github; -import java.net.URISyntaxException; - import com.google.common.base.Strings; import com.google.gerrit.pgm.init.api.ConsoleUI; import com.google.gerrit.pgm.init.api.InitStep; import com.google.gerrit.pgm.init.api.InitUtil; import com.google.gerrit.pgm.init.api.Section; import com.google.inject.Inject; +import java.net.URISyntaxException; public class InitGitHub implements InitStep { private static final String GITHUB_URL = "https://github.com"; private static final String GITHUB_API_URL = "https://api.github.com"; private static final String GITHUB_REGISTER_APPLICATION_PATH = "/settings/applications/new"; private static final String GERRIT_OAUTH_CALLBACK_PATH = "oauth"; - + private final ConsoleUI ui; private final Section auth; private final Section httpd; private final Section github; private final Section gerrit; - + public enum OAuthType { /* Legacy Gerrit/HTTP authentication for GitHub through HTTP Header enrichment */ HTTP, - + /* New native Gerrit/OAuth authentication provider */ OAUTH } @@ -57,14 +56,14 @@ github.string("GitHub URL", "url", GITHUB_URL); github.string("GitHub API URL", "apiUrl", GITHUB_API_URL); - ui.message("\nNOTE: You might need to configure a proxy using http.proxy" - + " if you run Gerrit behind a firewall.\n"); + ui.message( + "\nNOTE: You might need to configure a proxy using http.proxy" + + " if you run Gerrit behind a firewall.\n"); String gerritUrl = getAssumedCanonicalWebUrl(); ui.header("GitHub OAuth registration and credentials"); ui.message( - "Register Gerrit as GitHub application on:\n" + - "%s%s\n\n", + "Register Gerrit as GitHub application on:\n" + "%s%s\n\n", github.get("url"), GITHUB_REGISTER_APPLICATION_PATH); ui.message("Settings (assumed Gerrit URL: %s)\n", gerritUrl); ui.message("* Application name: Gerrit Code Review\n"); @@ -74,14 +73,13 @@ github.string("GitHub Client ID", "clientId", null); github.passwordForKey("GitHub Client Secret", "clientSecret"); - + OAuthType authType = auth.select("Gerrit OAuth implementation", "type", OAuthType.HTTP); if (authType.equals(OAuthType.HTTP)) { auth.string("HTTP Authentication Header", "httpHeader", "GITHUB_USER"); - httpd.set("filterClass", - "com.googlesource.gerrit.plugins.github.oauth.OAuthFilter"); + httpd.set("filterClass", "com.googlesource.gerrit.plugins.github.oauth.OAuthFilter"); authSetDefault("httpExternalIdHeader", "GITHUB_OAUTH_TOKEN"); - authSetDefault("loginUrl","/login"); + authSetDefault("loginUrl", "/login"); authSetDefault("loginText", "Sign-in with GitHub"); authSetDefault("registerPageUrl", "/#/register"); } else { @@ -114,6 +112,5 @@ } @Override - public void postRun() throws Exception { - } + public void postRun() throws Exception {} }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/InvalidGitHubConfigException.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/InvalidGitHubConfigException.java index bfe6d20..908e875 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/InvalidGitHubConfigException.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/InvalidGitHubConfigException.java
@@ -17,6 +17,9 @@ private static final long serialVersionUID = 7006333621290095732L; public InvalidGitHubConfigException(String fromTo) { - super("Invalid configuration: invalid value " + fromTo + ": expected 'from-page.html => to-page.html"); + super( + "Invalid configuration: invalid value " + + fromTo + + ": expected 'from-page.html => to-page.html"); } }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/OnStartStop.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/OnStartStop.java index ee55271..5887731 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/OnStartStop.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/OnStartStop.java
@@ -17,7 +17,6 @@ import com.google.gerrit.extensions.events.LifecycleListener; import com.google.inject.Inject; import com.google.inject.Singleton; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -26,8 +25,7 @@ private static final Logger LOG = LoggerFactory.getLogger(OnStartStop.class); @Inject - public OnStartStop() { - } + public OnStartStop() {} @Override public void start() {
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/filters/GitHubOAuthFilter.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/filters/GitHubOAuthFilter.java index c143cb1..60f3132 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/filters/GitHubOAuthFilter.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/filters/GitHubOAuthFilter.java
@@ -15,11 +15,10 @@ import com.google.common.base.Predicate; import com.google.common.collect.Collections2; -import com.google.gerrit.reviewdb.client.AccountExternalId; import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.account.AccountCache; -import com.google.gerrit.server.account.ExternalId; +import com.google.gerrit.server.account.externalids.ExternalId; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; @@ -29,13 +28,8 @@ import com.googlesource.gerrit.plugins.github.oauth.OAuthProtocol.AccessToken; import com.googlesource.gerrit.plugins.github.oauth.OAuthWebFilter; import com.googlesource.gerrit.plugins.github.oauth.ScopedProvider; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.util.Collection; - import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -43,6 +37,8 @@ import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @Singleton public class GitHubOAuthFilter implements Filter { @@ -53,7 +49,8 @@ private final AccountCache accountCache; @Inject - public GitHubOAuthFilter(ScopedProvider<GitHubLogin> loginProvider, + public GitHubOAuthFilter( + ScopedProvider<GitHubLogin> loginProvider, Provider<CurrentUser> userProvider, AccountCache accountCache) { this.loginProvider = loginProvider; @@ -62,55 +59,54 @@ } @Override - public void init(FilterConfig filterConfig) throws ServletException { - } + public void init(FilterConfig filterConfig) throws ServletException {} @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { GitHubLogin hubLogin = loginProvider.get((HttpServletRequest) request); LOG.debug("GitHub login: " + hubLogin); CurrentUser user = userProvider.get(); if (!hubLogin.isLoggedIn() && !OAuthFilter.skipOAuth((HttpServletRequest) request) && user.isIdentifiedUser()) { - AccountExternalId gitHubExtId = getGitHubExternalId(user); + ExternalId gitHubExtId = getGitHubExternalId(user); String oauthToken = - gitHubExtId.getSchemeRest() - .substring(OAuthWebFilter.GITHUB_EXT_ID.length()); + gitHubExtId + .key() + .get() + .substring( + ExternalId.SCHEME_EXTERNAL.length() + OAuthWebFilter.GITHUB_EXT_ID.length() + 1); hubLogin.login(new AccessToken(oauthToken)); } chain.doFilter(request, response); } - private AccountExternalId getGitHubExternalId(CurrentUser user) { + private ExternalId getGitHubExternalId(CurrentUser user) { Collection<ExternalId> accountExtIds = - accountCache.get(((IdentifiedUser) user).getAccountId()) - .getExternalIds(); + accountCache.get(((IdentifiedUser) user).getAccountId()).getExternalIds(); Collection<ExternalId> gitHubExtId = - Collections2.filter(accountExtIds, + Collections2.filter( + accountExtIds, new Predicate<ExternalId>() { @Override public boolean apply(ExternalId externalId) { - return externalId - .key() - .get() - .startsWith( - IdentifiedUserGitHubLoginProvider.EXTERNAL_ID_PREFIX); + return externalId + .key() + .get() + .startsWith(IdentifiedUserGitHubLoginProvider.EXTERNAL_ID_PREFIX); } }); if (gitHubExtId.isEmpty()) { - throw new IllegalStateException("Current Gerrit user " - + user.getUserName() + " has no GitHub OAuth external ID"); + throw new IllegalStateException( + "Current Gerrit user " + user.getUserName() + " has no GitHub OAuth external ID"); } - return gitHubExtId.iterator().next().asAccountExternalId(); + return gitHubExtId.iterator().next(); } @Override - public void destroy() { - } - + public void destroy() {} }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/AbstractCloneJob.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/AbstractCloneJob.java index 7308b28..4421841 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/AbstractCloneJob.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/AbstractCloneJob.java
@@ -14,7 +14,6 @@ package com.googlesource.gerrit.plugins.github.git; import com.google.inject.ProvisionException; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -27,9 +26,9 @@ protected String getErrorDescription(Throwable exception) { LOG.error("Job " + this + " FAILED", exception); - if(GitException.class.isAssignableFrom(exception.getClass())) { + if (GitException.class.isAssignableFrom(exception.getClass())) { return ((GitException) exception).getErrorDescription(); - } else if(ProvisionException.class.isAssignableFrom(exception.getClass())){ + } else if (ProvisionException.class.isAssignableFrom(exception.getClass())) { Throwable cause = exception.getCause(); if (cause != null) { return getErrorDescription(cause); @@ -39,5 +38,4 @@ return "Internal error"; } } - }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/BatchImporter.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/BatchImporter.java index 21dfb37..f26188d 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/BatchImporter.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/BatchImporter.java
@@ -14,7 +14,6 @@ package com.googlesource.gerrit.plugins.github.git; import com.google.gerrit.server.IdentifiedUser; - import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; @@ -48,5 +47,4 @@ jobs.put(new Integer(idx), pullRequestImportJob); executor.exec(pullRequestImportJob); } - }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/CreateProjectStep.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/CreateProjectStep.java index 87e089f..e67fcd4 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/CreateProjectStep.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/CreateProjectStep.java
@@ -30,10 +30,8 @@ import com.google.gerrit.server.project.ProjectCache; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; - import com.googlesource.gerrit.plugins.github.GitHubConfig; import com.googlesource.gerrit.plugins.github.GitHubURL; - import org.eclipse.jgit.lib.ProgressMonitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,7 +42,7 @@ private static final String TAGS_REFS = "refs/tags/*"; private static final String CODE_REVIEW_LABEL = "Code-Review"; private static final String VERIFIED_LABEL = "Verified"; - + private final String organisation; private final String repository; @@ -57,15 +55,17 @@ private GitHubConfig config; public interface Factory { - CreateProjectStep create(@Assisted("organisation") String organisation, + CreateProjectStep create( + @Assisted("organisation") String organisation, @Assisted("name") String repository, @Assisted("description") String description, @Assisted("username") String username); } @Inject - public CreateProjectStep(@GitHubURL String gitHubUrl, - MetaDataUpdate.User metaDataUpdateFactory, + public CreateProjectStep( + @GitHubURL String gitHubUrl, + MetaDataUpdate.User metaDataUpdateFactory, GroupBackend groupBackend, ProjectCache projectCache, GitHubRepository.Factory ghRepoFactory, @@ -86,27 +86,29 @@ this.username = username; this.config = gitHubConfig; } - + private void setProjectPermissions() { addPermissions(AccessSection.ALL, Permission.OWNER); - addPermissions(CODE_REVIEW_REFS, Permission.READ, Permission.PUSH, - Permission.REMOVE_REVIEWER, Permission.SUBMIT, Permission.REBASE); + addPermissions( + CODE_REVIEW_REFS, + Permission.READ, + Permission.PUSH, + Permission.REMOVE_REVIEWER, + Permission.SUBMIT, + Permission.REBASE); PermissionRule reviewRange = new PermissionRule(getMyGroup()); reviewRange.setMin(new Integer(-2)); reviewRange.setMax(new Integer(+2)); - addPermission(CODE_REVIEW_REFS, Permission.LABEL + CODE_REVIEW_LABEL, - reviewRange); + addPermission(CODE_REVIEW_REFS, Permission.LABEL + CODE_REVIEW_LABEL, reviewRange); PermissionRule verifiedRange = new PermissionRule(getMyGroup()); verifiedRange.setMin(new Integer(-1)); verifiedRange.setMax(new Integer(+1)); - addPermission(CODE_REVIEW_REFS, Permission.LABEL + VERIFIED_LABEL, - verifiedRange); + addPermission(CODE_REVIEW_REFS, Permission.LABEL + VERIFIED_LABEL, verifiedRange); - addPermissions(AccessSection.HEADS, Permission.READ, Permission.CREATE, - Permission.PUSH_MERGE); + addPermissions(AccessSection.HEADS, Permission.READ, Permission.CREATE, Permission.PUSH_MERGE); PermissionRule forcePush = new PermissionRule(getMyGroup()); forcePush.setForce(Boolean.TRUE); @@ -118,7 +120,7 @@ removeTag.setForce(Boolean.TRUE); addPermission(TAGS_REFS, Permission.PUSH, removeTag); } - + private void addPermissions(String refSpec, String... permissions) { AccessSection accessSection = projectConfig.getAccessSection(refSpec, true); for (String permission : permissions) { @@ -136,13 +138,11 @@ } private void addPermission(String refSpec, String action, PermissionRule rule) { - projectConfig.getAccessSection(refSpec, true).getPermission(action, true) - .add(rule); + projectConfig.getAccessSection(refSpec, true).getPermission(action, true).add(rule); } - + private GroupReference getMyGroup() { - GroupDescription.Basic g = - groupBackend.get(AccountGroup.UUID.parse("user:" + username)); + GroupDescription.Basic g = groupBackend.get(AccountGroup.UUID.parse("user:" + username)); return projectConfig.resolve(GroupReference.forGroup(g)); } @@ -165,13 +165,13 @@ projectConfig.commit(md); projectCache.onCreateProject(getProjectNameKey()); } finally { - if(md != null) { + if (md != null) { md.close(); } progress.endTask(); } } - + private void setProjectSettings() { Project project = projectConfig.getProject(); project.setParentName(config.getBaseProject(getRepository().isPrivate()));
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/ErrorJob.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/ErrorJob.java index 5ba4adf..629226d 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/ErrorJob.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/ErrorJob.java
@@ -23,8 +23,7 @@ private Throwable exception; private GitJobStatus status; - public ErrorJob(int idx, String organisation, String repository, - Throwable e) { + public ErrorJob(int idx, String organisation, String repository, Throwable e) { this.idx = idx; this.organisation = organisation; this.repository = repository; @@ -54,11 +53,8 @@ } @Override - public void cancel() { - } + public void cancel() {} @Override - public void run() { - } - + public void run() {} }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitCloneFailedException.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitCloneFailedException.java index 9a47143..8d36f80 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitCloneFailedException.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitCloneFailedException.java
@@ -32,8 +32,7 @@ return ""; } else if (JGitInternalException.class.isAssignableFrom(cause.getClass())) { Throwable innerCause = cause.getCause(); - return innerCause != null ? getCauseDescription(cause.getCause()) - : "JGit internal error"; + return innerCause != null ? getCauseDescription(cause.getCause()) : "JGit internal error"; } else { return getDecamelisedName(cause); } @@ -42,17 +41,16 @@ private String getDecamelisedName(Throwable cause) { StringBuilder name = new StringBuilder(); String causeName = cause.getClass().getName(); - causeName = causeName.substring(causeName.lastIndexOf('.')+1); + causeName = causeName.substring(causeName.lastIndexOf('.') + 1); for (char causeChar : causeName.toCharArray()) { - if(Character.isUpperCase(causeChar)) { + if (Character.isUpperCase(causeChar)) { name.append(" "); name.append(Character.toLowerCase(causeChar)); } else { name.append(causeChar); } } - + return name.toString(); } - }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitCloneStep.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitCloneStep.java index 06bd28b..44fc1a1 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitCloneStep.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitCloneStep.java
@@ -15,18 +15,15 @@ import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; - import com.googlesource.gerrit.plugins.github.GitHubConfig; - +import java.io.File; +import java.io.IOException; import org.apache.commons.io.FileUtils; import org.eclipse.jgit.api.CloneCommand; import org.eclipse.jgit.lib.ProgressMonitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.File; -import java.io.IOException; - public class GitCloneStep extends ImportStep { private static final Logger LOG = LoggerFactory.getLogger(GitImporter.class); @@ -34,27 +31,25 @@ private File destinationDirectory; public interface Factory { - GitCloneStep create(@Assisted("organisation") String organisation, - @Assisted("name") String repository); + GitCloneStep create( + @Assisted("organisation") String organisation, @Assisted("name") String repository); } @Inject - public GitCloneStep(GitHubConfig gitConfig, + public GitCloneStep( + GitHubConfig gitConfig, GitHubRepository.Factory gitHubRepoFactory, @Assisted("organisation") String organisation, @Assisted("name") String repository) - throws GitDestinationAlreadyExistsException, - GitDestinationNotWritableException { + throws GitDestinationAlreadyExistsException, GitDestinationNotWritableException { super(gitConfig.gitHubUrl, organisation, repository, gitHubRepoFactory); LOG.debug("GitHub Clone " + organisation + "/" + repository); this.gitDir = gitConfig.gitDir.toFile(); - this.destinationDirectory = - getDestinationDirectory(organisation, repository); + this.destinationDirectory = getDestinationDirectory(organisation, repository); } - + private File getDestinationDirectory(String organisation, String repository) - throws GitDestinationAlreadyExistsException, - GitDestinationNotWritableException { + throws GitDestinationAlreadyExistsException, GitDestinationNotWritableException { File orgDirectory = new File(gitDir, organisation); File destDirectory = new File(orgDirectory, repository + ".git"); if (destDirectory.exists() && isNotEmpty(destDirectory)) { @@ -71,8 +66,9 @@ } @Override - public void doImport(ProgressMonitor progress) throws GitCloneFailedException, - GitDestinationAlreadyExistsException, GitDestinationNotWritableException { + public void doImport(ProgressMonitor progress) + throws GitCloneFailedException, GitDestinationAlreadyExistsException, + GitDestinationNotWritableException { CloneCommand clone = new CloneCommand(); clone.setCredentialsProvider(getRepository().getCredentialsProvider()); String sourceUri = getSourceUri(); @@ -101,10 +97,10 @@ @Override public boolean rollback() { File gitDirectory = destinationDirectory; - if(!gitDirectory.exists()) { + if (!gitDirectory.exists()) { return false; } - + try { FileUtils.deleteDirectory(gitDirectory); return true;
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitDestinationAlreadyExistsException.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitDestinationAlreadyExistsException.java index 5c4e9d4..b9088f4 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitDestinationAlreadyExistsException.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitDestinationAlreadyExistsException.java
@@ -19,8 +19,7 @@ private static final long serialVersionUID = -6202681486717426148L; public GitDestinationAlreadyExistsException(File destDirectory) { - super("Output Git destination " + destDirectory - + " already exists and cannot be overwritten"); + super("Output Git destination " + destDirectory + " already exists and cannot be overwritten"); } @Override
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitDestinationNotWritableException.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitDestinationNotWritableException.java index ec55861..cc0bb60 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitDestinationNotWritableException.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitDestinationNotWritableException.java
@@ -26,5 +26,4 @@ public String getErrorDescription() { return "Output destination directory is not writeable"; } - }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitException.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitException.java index 3b60bb7..d73e7e2 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitException.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitException.java
@@ -35,5 +35,4 @@ } public abstract String getErrorDescription(); - }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitHubRepository.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitHubRepository.java index c78b7e4..09e3fb7 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitHubRepository.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitHubRepository.java
@@ -15,11 +15,11 @@ import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; - import com.googlesource.gerrit.plugins.github.GitHubURL; import com.googlesource.gerrit.plugins.github.oauth.GitHubLogin; import com.googlesource.gerrit.plugins.github.oauth.ScopedProvider; - +import java.io.IOException; +import lombok.experimental.Delegate; import org.eclipse.jgit.errors.UnsupportedCredentialItem; import org.eclipse.jgit.transport.CredentialItem; import org.eclipse.jgit.transport.CredentialsProvider; @@ -27,25 +27,19 @@ import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; -import java.io.IOException; - -import lombok.experimental.Delegate; - public class GitHubRepository extends GHRepository { public interface Factory { - GitHubRepository create(@Assisted("organisation") String organisation, - @Assisted("repository") String repository); + GitHubRepository create( + @Assisted("organisation") String organisation, @Assisted("repository") String repository); } - private final String organisation; private final String repository; private final String cloneUrl; private final String username; private final String password; - @Delegate - private GHRepository ghRepository; + @Delegate private GHRepository ghRepository; public String getCloneUrl() { return cloneUrl.replace("://", "://" + username + "@"); @@ -60,10 +54,12 @@ } @Inject - public GitHubRepository(ScopedProvider<GitHubLogin> ghLoginProvider, + public GitHubRepository( + ScopedProvider<GitHubLogin> ghLoginProvider, @GitHubURL String gitHubUrl, @Assisted("organisation") String organisation, - @Assisted("repository") String repository) throws IOException { + @Assisted("repository") String repository) + throws IOException { this.cloneUrl = gitHubUrl + "/" + organisation + "/" + repository + ".git"; this.organisation = organisation; this.repository = repository; @@ -71,8 +67,7 @@ GitHub gh = ghLogin.getHub(); this.username = ghLogin.getMyself().getLogin(); this.password = ghLogin.getToken().accessToken; - this.ghRepository = - gh.getRepository(organisation + "/" + repository); + this.ghRepository = gh.getRepository(organisation + "/" + repository); } public CredentialsProvider getCredentialsProvider() { @@ -98,8 +93,7 @@ } @Override - public boolean get(URIish uri, CredentialItem... items) - throws UnsupportedCredentialItem { + public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem { String user = uri.getUser(); if (user == null) { user = GitHubRepository.this.username;
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitHubUser.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitHubUser.java index f929e62..2109ea9 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitHubUser.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitHubUser.java
@@ -16,21 +16,15 @@ import com.google.common.base.Optional; import com.google.common.base.Strings; - +import java.io.IOException; +import lombok.Getter; import org.kohsuke.github.GHUser; import org.kohsuke.github.GitUser; -import java.io.IOException; - -import lombok.Getter; - public class GitHubUser { - @Getter - private final String login; - @Getter - private final String name; - @Getter - private final String email; + @Getter private final String login; + @Getter private final String name; + @Getter private final String email; private GitHubUser(GHUser gitHubUser, GitUser author) throws IOException { this.login = initLogin(gitHubUser).or(generateLogin(author.getName())); @@ -43,24 +37,20 @@ } private static Optional<String> initLogin(GHUser gitHubUser) { - return Optional.fromNullable(gitHubUser != null ? gitHubUser.getLogin() - : null); + return Optional.fromNullable(gitHubUser != null ? gitHubUser.getLogin() : null); } - private static Optional<String> initEmail(GHUser gitHubUser) - throws IOException { - return Optional.fromNullable(gitHubUser != null ? Strings - .emptyToNull(gitHubUser.getEmail()) : null); + private static Optional<String> initEmail(GHUser gitHubUser) throws IOException { + return Optional.fromNullable( + gitHubUser != null ? Strings.emptyToNull(gitHubUser.getEmail()) : null); } - private static Optional<String> initFullName(GHUser gitHubUser) - throws IOException { - return Optional.fromNullable(gitHubUser != null ? Strings - .emptyToNull(gitHubUser.getName()) : null); + private static Optional<String> initFullName(GHUser gitHubUser) throws IOException { + return Optional.fromNullable( + gitHubUser != null ? Strings.emptyToNull(gitHubUser.getName()) : null); } - public static GitHubUser from(GHUser gitHubUser, GitUser author) - throws IOException { + public static GitHubUser from(GHUser gitHubUser, GitUser author) throws IOException { return new GitHubUser(gitHubUser, author); } }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitImportJob.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitImportJob.java index b633b67..dda0205 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitImportJob.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitImportJob.java
@@ -14,11 +14,9 @@ package com.googlesource.gerrit.plugins.github.git; import com.googlesource.gerrit.plugins.github.git.GitJobStatus.Code; - import org.eclipse.jgit.lib.ProgressMonitor; -public class GitImportJob extends AbstractCloneJob implements Runnable, - ProgressMonitor, GitJob { +public class GitImportJob extends AbstractCloneJob implements Runnable, ProgressMonitor, GitJob { private int currTask; private int totUnits; private int currUnit; @@ -47,7 +45,7 @@ for (ImportStep importStep : importSteps) { importStep.doImport(this); } - status.update(GitJobStatus.Code.COMPLETE,"Done","Done: repository replicated to Gerrit."); + status.update(GitJobStatus.Code.COMPLETE, "Done", "Done: repository replicated to Gerrit."); } catch (Exception e) { if (status.getStatus() == GitJobStatus.Code.SYNC) { this.exception = e; @@ -85,14 +83,13 @@ case CANCELLED: return "Cancelled"; default: - return "Phase-" + currTask + " / " + task + " (" + lastPercentage - + "%)"; + return "Phase-" + currTask + " / " + task + " (" + lastPercentage + "%)"; } } /* * (non-Javadoc) - * + * * @see com.googlesource.gerrit.plugins.github.git.CloneJob#getStatus() */ @Override @@ -111,7 +108,7 @@ if (percentage > lastPercentage) { lastPercentage = percentage; } - + status.update(Code.SYNC, status.getShortDescription(), getStatusDescription()); } @@ -129,8 +126,7 @@ } @Override - public void endTask() { - } + public void endTask() {} @Override public void beginTask(String taskName, int totalUnits) { @@ -139,7 +135,7 @@ this.totUnits = totalUnits; this.currUnit = 0; this.lastPercentage = 0; - + status.update(Code.SYNC, status.getShortDescription(), getStatusDescription()); } @@ -150,8 +146,7 @@ @Override public String toString() { - return "CloneJob#" + index + " " + getOrganisation() + "/" - + getRepository(); + return "CloneJob#" + index + " " + getOrganisation() + "/" + getRepository(); } @Override @@ -163,5 +158,4 @@ public String getRepository() { return repository; } - }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitImporter.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitImporter.java index 6d2fb3a..f36257d 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitImporter.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitImporter.java
@@ -16,9 +16,7 @@ import com.google.gerrit.server.IdentifiedUser; import com.google.inject.Inject; import com.google.inject.Singleton; - import com.googlesource.gerrit.plugins.github.oauth.HttpSessionProvider; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -32,11 +30,12 @@ private final CreateProjectStep.Factory projectFactory; private final ReplicateProjectStep.Factory replicateFactory; - @Inject - public GitImporter(GitCloneStep.Factory cloneFactory, + public GitImporter( + GitCloneStep.Factory cloneFactory, CreateProjectStep.Factory projectFactory, - ReplicateProjectStep.Factory replicateFactory, JobExecutor executor, + ReplicateProjectStep.Factory replicateFactory, + JobExecutor executor, IdentifiedUser user) { super(executor, user); this.cloneFactory = cloneFactory; @@ -44,18 +43,14 @@ this.replicateFactory = replicateFactory; } - public void clone(int idx, String organisation, String repository, - String description) { + public void clone(int idx, String organisation, String repository, String description) { try { GitCloneStep cloneStep = cloneFactory.create(organisation, repository); CreateProjectStep projectStep = - projectFactory.create(organisation, repository, description, - user.getUserName()); - ReplicateProjectStep replicateStep = - replicateFactory.create(organisation, repository); + projectFactory.create(organisation, repository, description, user.getUserName()); + ReplicateProjectStep replicateStep = replicateFactory.create(organisation, repository); GitImportJob gitCloneJob = - new GitImportJob(idx, organisation, repository, cloneStep, - projectStep, replicateStep); + new GitImportJob(idx, organisation, repository, cloneStep, projectStep, replicateStep); log.debug("New Git clone job created: " + gitCloneJob); schedule(idx, gitCloneJob); } catch (Throwable e) {
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitJob.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitJob.java index 404c22e..0aa14e2 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitJob.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitJob.java
@@ -24,5 +24,4 @@ String getRepository(); public abstract void cancel(); - }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitJobStatus.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitJobStatus.java index c9bfb43..c95b986 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitJobStatus.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/GitJobStatus.java
@@ -15,15 +15,16 @@ import com.google.gson.Gson; import com.google.gson.stream.JsonWriter; - import java.io.IOException; import java.io.PrintWriter; - public class GitJobStatus { public enum Code { - SYNC, COMPLETE, FAILED, CANCELLED; + SYNC, + COMPLETE, + FAILED, + CANCELLED; @Override public String toString() {
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/ImportStep.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/ImportStep.java index 71a1869..bdc9182 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/ImportStep.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/ImportStep.java
@@ -14,16 +14,17 @@ package com.googlesource.gerrit.plugins.github.git; import com.googlesource.gerrit.plugins.github.GitHubURL; - import org.eclipse.jgit.lib.ProgressMonitor; public abstract class ImportStep { private final GitHubRepository gitHubRepository; - public ImportStep(@GitHubURL String gitHubUrl, String organisation, - String repository, GitHubRepository.Factory ghRepoFactory) { - this.gitHubRepository = - ghRepoFactory.create(organisation, repository); + public ImportStep( + @GitHubURL String gitHubUrl, + String organisation, + String repository, + GitHubRepository.Factory ghRepoFactory) { + this.gitHubRepository = ghRepoFactory.create(organisation, repository); } protected String getSourceUri() {
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/JobCancelledException.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/JobCancelledException.java index db8107e..22c5ec3 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/JobCancelledException.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/JobCancelledException.java
@@ -15,5 +15,4 @@ public class JobCancelledException extends Exception { private static final long serialVersionUID = 4358474273091335160L; - }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/JobExecutor.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/JobExecutor.java index 67dae23..a7f93b2 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/JobExecutor.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/JobExecutor.java
@@ -16,9 +16,7 @@ import com.google.gerrit.server.util.RequestScopePropagator; import com.google.inject.Inject; import com.google.inject.Singleton; - import com.googlesource.gerrit.plugins.github.GitHubConfig; - import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; @@ -31,17 +29,16 @@ private final GitHubConfig config; @Inject - public JobExecutor(final RequestScopePropagator requestScopePropagator, - final GitHubConfig config) { + public JobExecutor( + final RequestScopePropagator requestScopePropagator, final GitHubConfig config) { this.requestScopePropagator = requestScopePropagator; this.config = config; - this.executor = Executors - .newScheduledThreadPool(config.jobPoolLimit); + this.executor = Executors.newScheduledThreadPool(config.jobPoolLimit); } public void exec(GitJob job) { - executor.schedule(requestScopePropagator.wrap(job), - getRandomExecutionDelay(job), TimeUnit.SECONDS); + executor.schedule( + requestScopePropagator.wrap(job), getRandomExecutionDelay(job), TimeUnit.SECONDS); } private int getRandomExecutionDelay(GitJob job) {
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/PullRequestCreateChange.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/PullRequestCreateChange.java index 1af821b..e053920 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/PullRequestCreateChange.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/PullRequestCreateChange.java
@@ -19,6 +19,9 @@ import com.google.gerrit.common.TimeUtil; import com.google.gerrit.common.errors.EmailException; import com.google.gerrit.extensions.restapi.RestApiException; +import com.google.gerrit.index.query.QueryParseException; +import com.google.gerrit.index.query.QueryProcessor; +import com.google.gerrit.index.query.QueryResult; import com.google.gerrit.reviewdb.client.Account; import com.google.gerrit.reviewdb.client.Branch; import com.google.gerrit.reviewdb.client.Change; @@ -31,16 +34,12 @@ import com.google.gerrit.server.change.ChangeInserter; import com.google.gerrit.server.change.PatchSetInserter; import com.google.gerrit.server.git.IntegrationException; -import com.google.gerrit.server.git.validators.CommitValidators.Policy; -import com.google.gerrit.server.project.ChangeControl; +import com.google.gerrit.server.notedb.ChangeNotes; import com.google.gerrit.server.project.InvalidChangeOperationException; import com.google.gerrit.server.project.NoSuchChangeException; import com.google.gerrit.server.project.NoSuchProjectException; import com.google.gerrit.server.project.ProjectControl; import com.google.gerrit.server.project.RefControl; -import com.google.gerrit.server.query.QueryParseException; -import com.google.gerrit.server.query.QueryProcessor; -import com.google.gerrit.server.query.QueryResult; import com.google.gerrit.server.query.change.ChangeData; import com.google.gerrit.server.query.change.ChangeQueryBuilder; import com.google.gerrit.server.query.change.ChangeQueryProcessor; @@ -50,7 +49,9 @@ import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import com.google.inject.Provider; - +import java.io.IOException; +import java.util.Collections; +import java.util.List; import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.lib.ObjectId; @@ -63,13 +64,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.util.Collections; -import java.util.List; - public class PullRequestCreateChange { - private static final Logger LOG = LoggerFactory - .getLogger(PullRequestCreateChange.class); + private static final Logger LOG = LoggerFactory.getLogger(PullRequestCreateChange.class); private static final FooterKey CHANGE_ID = new FooterKey("Change-Id"); private final ChangeInserter.Factory changeInserterFactory; @@ -82,7 +78,8 @@ private final ChangeQueryBuilder changeQuery; @Inject - PullRequestCreateChange(ChangeInserter.Factory changeInserterFactory, + PullRequestCreateChange( + ChangeInserter.Factory changeInserterFactory, PatchSetInserter.Factory patchSetInserterFactory, ProjectControl.Factory projectControlFactory, IdentifiedUser.GenericFactory userFactory, @@ -100,49 +97,66 @@ this.changeQuery = changeQuery; } - public Change.Id addCommitToChange(ReviewDb db, final Project project, - final Repository repo, final String destinationBranch, - final Account.Id pullRequestOwner, final RevCommit pullRequestCommit, - final String pullRequestMessage, final String topic) - throws NoSuchChangeException, EmailException, OrmException, - MissingObjectException, IncorrectObjectTypeException, IOException, - InvalidChangeOperationException, IntegrationException, NoSuchProjectException, - UpdateException, RestApiException { + public Change.Id addCommitToChange( + ReviewDb db, + final Project project, + final Repository repo, + final String destinationBranch, + final Account.Id pullRequestOwner, + final RevCommit pullRequestCommit, + final String pullRequestMessage, + final String topic) + throws NoSuchChangeException, EmailException, OrmException, MissingObjectException, + IncorrectObjectTypeException, IOException, InvalidChangeOperationException, + IntegrationException, NoSuchProjectException, UpdateException, RestApiException { try (BatchUpdate bu = - updateFactory.create(db, project.getNameKey(), - userFactory.create(pullRequestOwner), TimeUtil.nowTs())) { + updateFactory.create( + db, project.getNameKey(), userFactory.create(pullRequestOwner), TimeUtil.nowTs())) { - return internalAddCommitToChange(db, bu, project, repo, - destinationBranch, pullRequestOwner, pullRequestCommit, - pullRequestMessage, topic); + return internalAddCommitToChange( + db, + bu, + project, + repo, + destinationBranch, + pullRequestOwner, + pullRequestCommit, + pullRequestMessage, + topic); } } - public Change.Id internalAddCommitToChange(ReviewDb db, BatchUpdate bu, - final Project project, final Repository repo, - final String destinationBranch, final Account.Id pullRequestOwner, - final RevCommit pullRequestCommit, final String pullRequestMesage, - final String topic) throws InvalidChangeOperationException, IOException, - NoSuchProjectException, OrmException, UpdateException, RestApiException { + public Change.Id internalAddCommitToChange( + ReviewDb db, + BatchUpdate bu, + final Project project, + final Repository repo, + final String destinationBranch, + final Account.Id pullRequestOwner, + final RevCommit pullRequestCommit, + final String pullRequestMesage, + final String topic) + throws InvalidChangeOperationException, IOException, NoSuchProjectException, OrmException, + UpdateException, RestApiException { if (destinationBranch == null || destinationBranch.length() == 0) { - throw new InvalidChangeOperationException( - "Destination branch cannot be null or empty"); + throw new InvalidChangeOperationException("Destination branch cannot be null or empty"); } Ref destRef = repo.findRef(destinationBranch); if (destRef == null) { - throw new InvalidChangeOperationException("Branch " + destinationBranch - + " does not exist."); + throw new InvalidChangeOperationException("Branch " + destinationBranch + " does not exist."); } RefControl refControl = - projectControlFactory.controlFor(project.getNameKey()).controlForRef( - destinationBranch); + projectControlFactory.controlFor(project.getNameKey()).controlForRef(destinationBranch); String pullRequestSha1 = pullRequestCommit.getId().getName(); List<ChangeData> existingChanges = queryChangesForSha1(pullRequestSha1); if (!existingChanges.isEmpty()) { - LOG.debug("Pull request commit ID " + pullRequestSha1 - + " has been already uploaded as Change-Id=" + existingChanges.get(0).getId()); + LOG.debug( + "Pull request commit ID " + + pullRequestSha1 + + " has been already uploaded as Change-Id=" + + existingChanges.get(0).getId()); return null; } @@ -153,20 +167,27 @@ changeKey = new Change.Key(idStr); } else { final ObjectId computedChangeId = - ChangeIdUtil.computeChangeId(pullRequestCommit.getTree(), - pullRequestCommit, pullRequestCommit.getAuthorIdent(), - pullRequestCommit.getCommitterIdent(), pullRequestMesage); + ChangeIdUtil.computeChangeId( + pullRequestCommit.getTree(), + pullRequestCommit, + pullRequestCommit.getAuthorIdent(), + pullRequestCommit.getCommitterIdent(), + pullRequestMesage); changeKey = new Change.Key("I" + computedChangeId.name()); } String branchName = destRef.getName(); List<ChangeData> destChanges = - queryProvider.get().byBranchKey( - new Branch.NameKey(project.getNameKey(), - branchName.startsWith(REFS_HEADS) - ? branchName.substring(REFS_HEADS.length()) : branchName), - changeKey); + queryProvider + .get() + .byBranchKey( + new Branch.NameKey( + project.getNameKey(), + branchName.startsWith(REFS_HEADS) + ? branchName.substring(REFS_HEADS.length()) + : branchName), + changeKey); if (destChanges.size() > 1) { throw new InvalidChangeOperationException( @@ -179,19 +200,24 @@ if (destChanges.size() == 1) { // The change key exists on the destination branch: adding a new // patch-set - Change destChange = destChanges.get(0).change(); - ChangeControl changeControl = - projectControlFactory.controlFor(project.getNameKey()) - .controlForIndexedChange(destChange); - insertPatchSet(bu, repo, destChange, pullRequestCommit, changeControl, - pullRequestMesage); + ChangeData destChangeData = destChanges.get(0); + Change destChange = destChangeData.change(); + insertPatchSet(bu, repo, destChange, pullRequestCommit, destChangeData.notes(), pullRequestMesage); return destChange.getId(); } // Change key not found on destination branch. We can create a new // change. - return createNewChange(db, bu, changeKey, project.getNameKey(), destRef, - pullRequestOwner, pullRequestCommit, refControl, pullRequestMesage, + return createNewChange( + db, + bu, + changeKey, + project.getNameKey(), + destRef, + pullRequestOwner, + pullRequestCommit, + refControl, + pullRequestMesage, topic); } @@ -201,47 +227,57 @@ results = qp.query(changeQuery.commit(pullRequestSha1)); return results.entities(); } catch (OrmException | QueryParseException e) { - LOG.error("Invalid SHA1 " + pullRequestSha1 - + ": cannot query changes for this pull request", e); + LOG.error( + "Invalid SHA1 " + pullRequestSha1 + ": cannot query changes for this pull request", e); return Collections.emptyList(); } } - private void insertPatchSet(BatchUpdate bu, Repository git, Change change, - RevCommit cherryPickCommit, ChangeControl changeControl, - String pullRequestMessage) throws IOException, UpdateException, - RestApiException { + private void insertPatchSet( + BatchUpdate bu, + Repository git, + Change change, + RevCommit cherryPickCommit, + ChangeNotes changeNotes, + String pullRequestMessage) + throws IOException, UpdateException, RestApiException { try (RevWalk revWalk = new RevWalk(git)) { - PatchSet.Id psId = - ChangeUtil.nextPatchSetId(git, change.currentPatchSetId()); + PatchSet.Id psId = ChangeUtil.nextPatchSetId(git, change.currentPatchSetId()); PatchSetInserter patchSetInserter = - patchSetInserterFactory.create(changeControl, psId, cherryPickCommit); + patchSetInserterFactory.create(changeNotes, psId, cherryPickCommit); patchSetInserter.setMessage(pullRequestMessage); - patchSetInserter.setValidatePolicy(Policy.NONE); + patchSetInserter.setValidate(false); bu.addOp(change.getId(), patchSetInserter); bu.execute(); } } - private Change.Id createNewChange(ReviewDb db, BatchUpdate bu, - Change.Key changeKey, Project.NameKey project, Ref destRef, - Account.Id pullRequestOwner, RevCommit pullRequestCommit, - RefControl refControl, String pullRequestMessage, String topic) - throws OrmException, UpdateException, RestApiException { + private Change.Id createNewChange( + ReviewDb db, + BatchUpdate bu, + Change.Key changeKey, + Project.NameKey project, + Ref destRef, + Account.Id pullRequestOwner, + RevCommit pullRequestCommit, + RefControl refControl, + String pullRequestMessage, + String topic) + throws OrmException, UpdateException, RestApiException, IOException { Change change = - new Change(changeKey, new Change.Id(db.nextChangeId()), - pullRequestOwner, new Branch.NameKey(project, destRef.getName()), + new Change( + changeKey, + new Change.Id(db.nextChangeId()), + pullRequestOwner, + new Branch.NameKey(project, destRef.getName()), TimeUtil.nowTs()); if (topic != null) { change.setTopic(topic); } ChangeInserter ins = - changeInserterFactory.create( - change.getId(), - pullRequestCommit, - refControl.getRefName()); + changeInserterFactory.create(change.getId(), pullRequestCommit, refControl.getRefName()); ins.setMessage(pullRequestMessage); bu.insertChange(ins);
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/PullRequestImportJob.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/PullRequestImportJob.java index ecce058..646737e 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/PullRequestImportJob.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/PullRequestImportJob.java
@@ -20,13 +20,13 @@ import com.google.gerrit.extensions.restapi.ResourceConflictException; import com.google.gerrit.extensions.restapi.UnprocessableEntityException; import com.google.gerrit.reviewdb.client.Account; -import com.google.gerrit.reviewdb.client.AccountExternalId; import com.google.gerrit.reviewdb.client.Change.Id; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.reviewdb.client.Project.NameKey; -import com.google.gerrit.reviewdb.server.AccountExternalIdAccess; import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.server.account.AccountImporter; +import com.google.gerrit.server.account.externalids.ExternalId; +import com.google.gerrit.server.account.externalids.ExternalIds; import com.google.gerrit.server.git.GitRepositoryManager; import com.google.gerrit.server.project.ProjectCache; import com.google.gerrit.server.project.ProjectState; @@ -34,11 +34,12 @@ import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.assistedinject.Assisted; - import com.googlesource.gerrit.plugins.github.git.GitJobStatus.Code; import com.googlesource.gerrit.plugins.github.oauth.GitHubLogin; import com.googlesource.gerrit.plugins.github.oauth.ScopedProvider; - +import java.io.IOException; +import java.util.List; +import java.util.Optional; import org.eclipse.jgit.api.FetchCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; @@ -60,20 +61,18 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.util.List; - public class PullRequestImportJob implements GitJob, ProgressMonitor { public interface Factory { - PullRequestImportJob create(@Assisted("index") int jobIndex, + PullRequestImportJob create( + @Assisted("index") int jobIndex, @Assisted("organisation") String organisation, - @Assisted("name") String repository, @Assisted int pullRequestId, + @Assisted("name") String repository, + @Assisted int pullRequestId, @Assisted PullRequestImportType importType); } - private static final Logger LOG = LoggerFactory - .getLogger(PullRequestImportJob.class); + private static final Logger LOG = LoggerFactory.getLogger(PullRequestImportJob.class); private static final String TOPIC_FORMAT = "GitHub #%d"; @@ -84,6 +83,7 @@ private final int prId; private final GitRepositoryManager repoMgr; private final int jobIndex; + private final ExternalIds externalIds; private PullRequestCreateChange createChange; private Project project; private GitJobStatus status; @@ -92,15 +92,19 @@ private AccountImporter accountImporter; @Inject - public PullRequestImportJob(GitRepositoryManager repoMgr, + public PullRequestImportJob( + GitRepositoryManager repoMgr, PullRequestCreateChange createChange, ProjectCache projectCache, - Provider<ReviewDb> schema, AccountImporter accountImporter, + Provider<ReviewDb> schema, + AccountImporter accountImporter, GitHubRepository.Factory gitHubRepoFactory, ScopedProvider<GitHubLogin> ghLoginProvider, + ExternalIds externalIds, @Assisted("index") int jobIndex, @Assisted("organisation") String organisation, - @Assisted("name") String repoName, @Assisted int pullRequestId) { + @Assisted("name") String repoName, + @Assisted int pullRequestId) { this.jobIndex = jobIndex; this.repoMgr = repoMgr; this.ghLogin = ghLoginProvider.get(); @@ -113,12 +117,12 @@ this.status = new GitJobStatus(jobIndex); this.schema = schema; this.accountImporter = accountImporter; + this.externalIds = externalIds; } - private Project fetchGerritProject(ProjectCache projectCache, - String fetchOrganisation, String fetchRepoName) { - NameKey projectNameKey = - Project.NameKey.parse(fetchOrganisation + "/" + fetchRepoName); + private Project fetchGerritProject( + ProjectCache projectCache, String fetchOrganisation, String fetchRepoName) { + NameKey projectNameKey = Project.NameKey.parse(fetchOrganisation + "/" + fetchRepoName); ProjectState projectState = projectCache.get(projectNameKey); return projectState.getProject(); } @@ -132,27 +136,33 @@ exitWhenCancelled(); try (Repository gitRepo = - repoMgr.openRepository(new Project.NameKey(organisation + "/" - + repoName))) { + repoMgr.openRepository(new Project.NameKey(organisation + "/" + repoName))) { exitWhenCancelled(); fetchGitHubPullRequest(gitRepo, pr); exitWhenCancelled(); List<Id> changeIds = addPullRequestToChange(db, pr, gitRepo); - status.update(GitJobStatus.Code.COMPLETE, "Imported", - "PullRequest imported as Changes " + changeIds); + status.update( + GitJobStatus.Code.COMPLETE, "Imported", "PullRequest imported as Changes " + changeIds); } } catch (JobCancelledException e) { status.update(GitJobStatus.Code.CANCELLED); } catch (Throwable e) { - LOG.error("Pull request " + prId + " into repository " + organisation - + "/" + repoName + " was failed", e); - status.update(GitJobStatus.Code.FAILED, "Failed", e.getLocalizedMessage()); + LOG.error( + "Pull request " + + prId + + " into repository " + + organisation + + "/" + + repoName + + " was failed", + e); + status.update(GitJobStatus.Code.FAILED, "Failed", e.getLocalizedMessage()); } } - private List<Id> addPullRequestToChange(ReviewDb db, GHPullRequest pr, - Repository gitRepo) throws Exception { + private List<Id> addPullRequestToChange(ReviewDb db, GHPullRequest pr, Repository gitRepo) + throws Exception { String destinationBranch = REFS_HEADS + pr.getBase().getRef(); List<Id> prChanges = Lists.newArrayList(); ObjectId baseObjectId = ObjectId.fromString(pr.getBase().getSha()); @@ -165,10 +175,11 @@ int patchNr = 1; for (GHPullRequestCommitDetail ghCommitDetail : pr.listCommits()) { - status.update(Code.SYNC, "Patch #" + patchNr, "Patch#" + patchNr - + ": Inserting PullRequest into Gerrit"); - RevCommit revCommit = - walk.parseCommit(ObjectId.fromString(ghCommitDetail.getSha())); + status.update( + Code.SYNC, + "Patch #" + patchNr, + "Patch#" + patchNr + ": Inserting PullRequest into Gerrit"); + RevCommit revCommit = walk.parseCommit(ObjectId.fromString(ghCommitDetail.getSha())); GHUser prUser = pr.getUser(); GitUser commitAuthor = ghCommitDetail.getCommit().getAuthor(); @@ -176,8 +187,13 @@ Account.Id pullRequestOwner = getOrRegisterAccount(db, gitHubUser); Id changeId = - createChange.addCommitToChange(db, project, gitRepo, - destinationBranch, pullRequestOwner, revCommit, + createChange.addCommitToChange( + db, + project, + gitRepo, + destinationBranch, + pullRequestOwner, + revCommit, getChangeMessage(pr), String.format(TOPIC_FORMAT, new Integer(pr.getNumber()))); if (changeId != null) { @@ -190,30 +206,39 @@ } private com.google.gerrit.reviewdb.client.Account.Id getOrRegisterAccount( - ReviewDb db, GitHubUser author) throws BadRequestException, - ResourceConflictException, UnprocessableEntityException, OrmException, - IOException, ConfigInvalidException { - return getOrRegisterAccount(db, author.getLogin(), author.getName(), - author.getEmail()); + ReviewDb db, GitHubUser author) + throws BadRequestException, ResourceConflictException, UnprocessableEntityException, + OrmException, IOException, ConfigInvalidException { + return getOrRegisterAccount(db, author.getLogin(), author.getName(), author.getEmail()); } private com.google.gerrit.reviewdb.client.Account.Id getOrRegisterAccount( ReviewDb db, String login, String name, String email) throws OrmException, BadRequestException, ResourceConflictException, - UnprocessableEntityException, IOException, ConfigInvalidException { - AccountExternalId.Key userExtKey = - new AccountExternalId.Key(AccountExternalId.SCHEME_USERNAME, login); - AccountExternalIdAccess gerritExtIds = db.accountExternalIds(); - AccountExternalId userExtId = gerritExtIds.get(userExtKey); - if (userExtId == null) { - return accountImporter.importAccount(login, name, email); + UnprocessableEntityException, IOException, ConfigInvalidException { + Optional<ExternalId> gerritId = externalIdByScheme(ExternalId.SCHEME_GERRIT, login); + if (gerritId.isPresent()) { + return gerritId.get().accountId(); } - return userExtId.getAccountId(); + return accountImporter.importAccount(login, name, email); + } + + private Optional<ExternalId> externalIdByScheme(String scheme, String id) { + try { + return Optional.ofNullable(externalIds.get(ExternalId.Key.create(scheme, id))); + } catch (IOException | ConfigInvalidException e) { + LOG.error("Unable to get external id for " + scheme + ":" + id, e); + return Optional.empty(); + } } private String getChangeMessage(GHPullRequest pr) { - return "GitHub Pull Request: " + pr.getUrl() + "\n\n" + pr.getTitle() - + "\n\n" + pr.getBody().replaceAll("\n", "\n\n"); + return "GitHub Pull Request: " + + pr.getUrl() + + "\n\n" + + pr.getTitle() + + "\n\n" + + pr.getBody().replaceAll("\n", "\n\n"); } private void exitWhenCancelled() throws JobCancelledException { @@ -229,8 +254,9 @@ try (Git git = Git.wrap(gitRepo)) { FetchCommand fetch = git.fetch(); fetch.setRemote(ghRepository.getCloneUrl()); - fetch.setRefSpecs(new RefSpec("+refs/pull/" + pr.getNumber() - + "/head:refs/remotes/origin/pr/" + pr.getNumber())); + fetch.setRefSpecs( + new RefSpec( + "+refs/pull/" + pr.getNumber() + "/head:refs/remotes/origin/pr/" + pr.getNumber())); fetch.setProgressMonitor(this); fetch.setCredentialsProvider(ghRepository.getCredentialsProvider()); fetch.call(); @@ -262,8 +288,7 @@ if (ghLogin.getMyself().getLogin().equals(organisation)) { return ghLogin.getMyself().getRepository(repoName); } - return ghLogin.getHub().getOrganization(organisation) - .getRepository(repoName); + return ghLogin.getHub().getOrganization(organisation).getRepository(repoName); } @Override @@ -282,8 +307,7 @@ } @Override - public void endTask() { - } + public void endTask() {} @Override public boolean isCancelled() { @@ -291,10 +315,8 @@ } @Override - public void start(int tot) { - } + public void start(int tot) {} @Override - public void update(int progress) { - } + public void update(int progress) {} }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/PullRequestImporter.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/PullRequestImporter.java index 3acdf9d..bc525ab 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/PullRequestImporter.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/PullRequestImporter.java
@@ -16,32 +16,35 @@ import com.google.gerrit.server.IdentifiedUser; import com.google.inject.Inject; import com.google.inject.servlet.SessionScoped; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SessionScoped public class PullRequestImporter extends BatchImporter { private static final Logger log = LoggerFactory.getLogger(PullRequestImporter.class); - + private final PullRequestImportJob.Factory prImportJobProvider; - + @Inject - public PullRequestImporter(JobExecutor executor, IdentifiedUser user, - PullRequestImportJob.Factory prImportJobProvider) { + public PullRequestImporter( + JobExecutor executor, IdentifiedUser user, PullRequestImportJob.Factory prImportJobProvider) { super(executor, user); this.prImportJobProvider = prImportJobProvider; } - public void importPullRequest(int idx, String organisation, String repoName, - int pullRequestId, PullRequestImportType importType) { + public void importPullRequest( + int idx, + String organisation, + String repoName, + int pullRequestId, + PullRequestImportType importType) { try { - PullRequestImportJob pullRequestImportJob = prImportJobProvider.create(idx, organisation, repoName, pullRequestId, importType); + PullRequestImportJob pullRequestImportJob = + prImportJobProvider.create(idx, organisation, repoName, pullRequestId, importType); log.debug("New Pull request import job created: " + pullRequestImportJob); schedule(idx, pullRequestImportJob); } catch (Throwable e) { schedule(idx, new ErrorJob(idx, organisation, repoName, e)); } - } }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/ReplicateProjectStep.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/ReplicateProjectStep.java index 27e3368..b321127 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/ReplicateProjectStep.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/ReplicateProjectStep.java
@@ -13,15 +13,12 @@ // limitations under the License. package com.googlesource.gerrit.plugins.github.git; -import java.io.IOException; - import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; - import com.googlesource.gerrit.plugins.github.GitHubURL; import com.googlesource.gerrit.plugins.github.oauth.GitHubLogin; import com.googlesource.gerrit.plugins.github.oauth.ScopedProvider; - +import java.io.IOException; import org.eclipse.jgit.lib.ProgressMonitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,18 +31,19 @@ private final String gitHubUrl; public interface Factory { - ReplicateProjectStep create(@Assisted("organisation") String organisation, - @Assisted("name") String repository); + ReplicateProjectStep create( + @Assisted("organisation") String organisation, @Assisted("name") String repository); } - @Inject - public ReplicateProjectStep(final ReplicationConfig replicationConfig, + public ReplicateProjectStep( + final ReplicationConfig replicationConfig, final GitHubRepository.Factory gitHubRepoFactory, final ScopedProvider<GitHubLogin> ghLoginProvider, @GitHubURL String gitHubUrl, @Assisted("organisation") String organisation, - @Assisted("name") String repository) throws IOException { + @Assisted("name") String repository) + throws IOException { super(gitHubUrl, organisation, repository, gitHubRepoFactory); LOG.debug("Gerrit ReplicateProject " + organisation + "/" + repository); this.replicationConfig = replicationConfig; @@ -63,8 +61,8 @@ progress.update(1); replicationConfig.addSecureCredentials(authUsername, authToken); progress.update(1); - replicationConfig.addReplicationRemote(authUsername, gitHubUrl - + "/${name}.git", repositoryName); + replicationConfig.addReplicationRemote( + authUsername, gitHubUrl + "/${name}.git", repositoryName); progress.endTask(); } @@ -72,5 +70,4 @@ public boolean rollback() { return false; } - }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/ReplicationConfig.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/ReplicationConfig.java index 103d43e..bd9ee79 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/ReplicationConfig.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/git/ReplicationConfig.java
@@ -16,16 +16,14 @@ import com.google.gerrit.server.config.SitePaths; import com.google.inject.Inject; import com.google.inject.Singleton; - -import org.eclipse.jgit.errors.ConfigInvalidException; -import org.eclipse.jgit.storage.file.FileBasedConfig; -import org.eclipse.jgit.util.FS; - import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import org.eclipse.jgit.errors.ConfigInvalidException; +import org.eclipse.jgit.storage.file.FileBasedConfig; +import org.eclipse.jgit.util.FS; @Singleton public class ReplicationConfig { @@ -35,30 +33,28 @@ @Inject public ReplicationConfig(final SitePaths site) { replicationConf = - new FileBasedConfig(new File(site.etc_dir.toFile(), "replication.config"), - FS.DETECTED); + new FileBasedConfig(new File(site.etc_dir.toFile(), "replication.config"), FS.DETECTED); secureConf = new FileBasedConfig(site.secure_config.toFile(), FS.DETECTED); } - public synchronized void addSecureCredentials(String authUsername, String authToken) throws IOException, - ConfigInvalidException { + public synchronized void addSecureCredentials(String authUsername, String authToken) + throws IOException, ConfigInvalidException { secureConf.load(); secureConf.setString("remote", authUsername, "username", authUsername); secureConf.setString("remote", authUsername, "password", authToken); secureConf.save(); } - public synchronized void addReplicationRemote(String username, String url, - String projectName) throws IOException, ConfigInvalidException { + public synchronized void addReplicationRemote(String username, String url, String projectName) + throws IOException, ConfigInvalidException { replicationConf.load(); replicationConf.setString("remote", username, "url", url); List<String> projects = - new ArrayList<>(Arrays.asList(replicationConf.getStringList( - "remote", username, "projects"))); + new ArrayList<>( + Arrays.asList(replicationConf.getStringList("remote", username, "projects"))); projects.add(projectName); replicationConf.setStringList("remote", username, "projects", projects); replicationConf.setString("remote", username, "push", "refs/*:refs/*"); replicationConf.save(); } - }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubGroup.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubGroup.java index 95158ff..e6d0793 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubGroup.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubGroup.java
@@ -16,18 +16,15 @@ import com.google.gerrit.common.data.GroupDescription.Basic; import com.google.gerrit.reviewdb.client.AccountGroup.UUID; - import lombok.Getter; public abstract class GitHubGroup implements Basic { public static final String UUID_PREFIX = "github:"; public static final String NAME_PREFIX = "github/"; - @Getter - protected final UUID groupUUID; + @Getter protected final UUID groupUUID; - @Getter - protected final String url; + @Getter protected final String url; GitHubGroup(UUID groupUUID, String url) { this.groupUUID = groupUUID;
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubGroupBackend.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubGroupBackend.java index 88045b4..c2a0faa 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubGroupBackend.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubGroupBackend.java
@@ -28,27 +28,23 @@ import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.account.GroupBackend; import com.google.gerrit.server.account.GroupMembership; -import com.google.gerrit.server.project.ProjectControl; +import com.google.gerrit.server.project.ProjectState; import com.google.inject.Inject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.Collection; import java.util.Collections; import java.util.Set; import java.util.concurrent.ExecutionException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class GitHubGroupBackend implements GroupBackend { - private static final Logger log = LoggerFactory - .getLogger(GitHubGroupBackend.class); + private static final Logger log = LoggerFactory.getLogger(GitHubGroupBackend.class); private final GitHubGroupMembership.Factory ghMembershipProvider; private final GitHubGroupsCache ghOrganisationCache; @Inject GitHubGroupBackend( - GitHubGroupMembership.Factory ghMembershipProvider, - GitHubGroupsCache ghOrganisationCache) { + GitHubGroupMembership.Factory ghMembershipProvider, GitHubGroupsCache ghOrganisationCache) { this.ghMembershipProvider = ghMembershipProvider; this.ghOrganisationCache = ghOrganisationCache; } @@ -65,13 +61,12 @@ @Override public Basic get(UUID uuid) { - checkArgument(handles(uuid), "{} is not a valid GitHub Group UUID", - uuid.get()); + checkArgument(handles(uuid), "{} is not a valid GitHub Group UUID", uuid.get()); return GitHubOrganisationGroup.fromUUID(uuid); } @Override - public Collection<GroupReference> suggest(String name, ProjectControl project) { + public Collection<GroupReference> suggest(String name, ProjectState project) { if (!name.startsWith(NAME_PREFIX)) { return Collections.emptyList(); } @@ -81,31 +76,25 @@ public Set<GroupReference> listByPrefix(String orgNamePrefix) { try { - log.debug("Listing user's organisations starting with '{}'", - orgNamePrefix); + log.debug("Listing user's organisations starting with '{}'", orgNamePrefix); String[] namePrefixParts = orgNamePrefix.toLowerCase().split("/"); - String orgNamePrefixLowercase = - namePrefixParts.length > 0 ? namePrefixParts[0] : ""; - String teamNameLowercase = - namePrefixParts.length > 1 ? namePrefixParts[1] : ""; + String orgNamePrefixLowercase = namePrefixParts.length > 0 ? namePrefixParts[0] : ""; + String teamNameLowercase = namePrefixParts.length > 1 ? namePrefixParts[1] : ""; Set<String> ghOrgs = ghOrganisationCache.getOrganizationsForCurrentUser(); log.debug("Full list of user's organisations: {}", ghOrgs); - Builder<GroupReference> orgGroups = - new ImmutableSet.Builder<>(); + Builder<GroupReference> orgGroups = new ImmutableSet.Builder<>(); for (String organizationName : ghOrgs) { if (organizationName.toLowerCase().startsWith(orgNamePrefixLowercase)) { - GroupReference teamGroupRef = - GitHubOrganisationGroup.groupReference(organizationName); + GroupReference teamGroupRef = GitHubOrganisationGroup.groupReference(organizationName); - if ((orgNamePrefixLowercase.length() > 0 && orgNamePrefix - .endsWith("/")) || teamNameLowercase.length() > 0) { + if ((orgNamePrefixLowercase.length() > 0 && orgNamePrefix.endsWith("/")) + || teamNameLowercase.length() > 0) { for (String teamName : ghOrganisationCache.getTeamsForCurrentUser(organizationName)) { if (teamName.toLowerCase().startsWith(teamNameLowercase)) { - orgGroups.add(GitHubTeamGroup.groupReference(teamGroupRef, - teamName)); + orgGroups.add(GitHubTeamGroup.groupReference(teamGroupRef, teamName)); } } } else { @@ -115,8 +104,7 @@ } return orgGroups.build(); } catch (ExecutionException e) { - log.warn("Cannot get GitHub organisations matching '" + orgNamePrefix - + "'", e); + log.warn("Cannot get GitHub organisations matching '" + orgNamePrefix + "'", e); } return Collections.emptySet();
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubGroupMembership.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubGroupMembership.java index 62e01ba..ce18918 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubGroupMembership.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubGroupMembership.java
@@ -19,7 +19,6 @@ import com.google.gerrit.server.account.GroupMembership; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; - import java.util.Set; public class GitHubGroupMembership implements GroupMembership { @@ -30,11 +29,11 @@ } @Inject - GitHubGroupMembership(GitHubGroupsCache ghOrganisationCache, - @Assisted String username) { + GitHubGroupMembership(GitHubGroupsCache ghOrganisationCache, @Assisted String username) { this.groups = - new ImmutableSet.Builder<UUID>().addAll( - ghOrganisationCache.getGroupsForUser(username)).build(); + new ImmutableSet.Builder<UUID>() + .addAll(ghOrganisationCache.getGroupsForUser(username)) + .build(); } @Override
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubGroupsCache.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubGroupsCache.java index 5370f03..d0bf3ea 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubGroupsCache.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubGroupsCache.java
@@ -30,11 +30,6 @@ import com.googlesource.gerrit.plugins.github.groups.OrganizationStructure; import com.googlesource.gerrit.plugins.github.oauth.GitHubLogin; import com.googlesource.gerrit.plugins.github.oauth.UserScopedProvider; - -import org.kohsuke.github.GHTeam; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.FileNotFoundException; import java.io.IOException; import java.util.Collections; @@ -42,19 +37,19 @@ import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ExecutionException; +import org.kohsuke.github.GHTeam; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @Singleton public class GitHubGroupsCache { - private static final Logger log = LoggerFactory - .getLogger(GitHubGroupsCache.class); + private static final Logger log = LoggerFactory.getLogger(GitHubGroupsCache.class); private static final String ORGS_CACHE_NAME = "groups"; protected static final long GROUPS_CACHE_TTL_MINS = 60; public static final String EVERYONE_TEAM_NAME = "Everyone"; - public static class OrganisationLoader extends - CacheLoader<String, OrganizationStructure> { - private static final Logger logger = LoggerFactory - .getLogger(OrganisationLoader.class); + public static class OrganisationLoader extends CacheLoader<String, OrganizationStructure> { + private static final Logger logger = LoggerFactory.getLogger(OrganisationLoader.class); private final UserScopedProvider<GitHubLogin> ghLoginProvider; @Inject @@ -84,15 +79,11 @@ return orgsTeams; } - private void loadOrganisationsAndTeams(String username, - OrganizationStructure orgsTeams, GitHubLogin ghLogin) - throws IOException { - logger.debug("Getting list of organisations/teams for user '{}'", - username); - Map<String, Set<GHTeam>> myOrganisationsLogins = - ghLogin.getHub().getMyTeams(); - for (Entry<String, Set<GHTeam>> teamsOrg : myOrganisationsLogins - .entrySet()) { + private void loadOrganisationsAndTeams( + String username, OrganizationStructure orgsTeams, GitHubLogin ghLogin) throws IOException { + logger.debug("Getting list of organisations/teams for user '{}'", username); + Map<String, Set<GHTeam>> myOrganisationsLogins = ghLogin.getHub().getMyTeams(); + for (Entry<String, Set<GHTeam>> teamsOrg : myOrganisationsLogins.entrySet()) { orgsTeams.put(teamsOrg.getKey(), EVERYONE_TEAM_NAME); for (GHTeam team : teamsOrg.getValue()) { orgsTeams.put(teamsOrg.getKey(), team.getName()); @@ -100,11 +91,9 @@ } } - private void loadOrganisations(String username, - OrganizationStructure orgsTeams, GitHubLogin ghLogin) - throws IOException { - logger.debug("Getting list of public organisations for user '{}'", - username); + private void loadOrganisations( + String username, OrganizationStructure orgsTeams, GitHubLogin ghLogin) throws IOException { + logger.debug("Getting list of public organisations for user '{}'", username); Set<String> organisations = ghLogin.getMyOrganisationsLogins(); for (String org : organisations) { orgsTeams.put(org, EVERYONE_TEAM_NAME); @@ -117,8 +106,8 @@ @Override protected void configure() { persist(ORGS_CACHE_NAME, String.class, OrganizationStructure.class) - .expireAfterWrite(GROUPS_CACHE_TTL_MINS, MINUTES).loader( - OrganisationLoader.class); + .expireAfterWrite(GROUPS_CACHE_TTL_MINS, MINUTES) + .loader(OrganisationLoader.class); bind(GitHubGroupsCache.class); } }; @@ -150,11 +139,17 @@ Set<String> getTeamsForUser(String organizationName, String username) { try { - return new ImmutableSet.Builder<String>().addAll( - orgTeamsByUsername.get(username).get(organizationName)).build(); + return new ImmutableSet.Builder<String>() + .addAll(orgTeamsByUsername.get(username).get(organizationName)) + .build(); } catch (ExecutionException e) { - log.warn("Cannot get Teams membership for organisation '" - + organizationName + "' and user '" + username + "'", e); + log.warn( + "Cannot get Teams membership for organisation '" + + organizationName + + "' and user '" + + username + + "'", + e); return Collections.emptySet(); } } @@ -169,8 +164,7 @@ groupsBuilder.add(GitHubOrganisationGroup.uuid(org)); for (String team : getTeamsForUser(org, username)) { - groupsBuilder.add(GitHubTeamGroup.uuid( - GitHubOrganisationGroup.uuid(org), team)); + groupsBuilder.add(GitHubTeamGroup.uuid(GitHubOrganisationGroup.uuid(org), team)); } } return groupsBuilder.build();
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubOrganisationGroup.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubOrganisationGroup.java index 7dca217..563e9d0 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubOrganisationGroup.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubOrganisationGroup.java
@@ -26,15 +26,15 @@ public class GitHubOrganisationGroup extends GitHubGroup implements Basic { public interface Factory { - GitHubOrganisationGroup get(@Assisted("orgName") String orgName, - @Assisted("orgUrl") @Nullable String orgUrl); + GitHubOrganisationGroup get( + @Assisted("orgName") String orgName, @Assisted("orgUrl") @Nullable String orgUrl); } private final String orgName; @Inject - GitHubOrganisationGroup(@Assisted("orgName") String orgName, - @Assisted("orgUrl") @Nullable String orgUrl) { + GitHubOrganisationGroup( + @Assisted("orgName") String orgName, @Assisted("orgUrl") @Nullable String orgUrl) { super(uuid(orgName), orgUrl); this.orgName = orgName; } @@ -45,10 +45,8 @@ } public static GitHubOrganisationGroup fromUUID(UUID uuid) { - checkArgument(uuid.get().startsWith(UUID_PREFIX), "Invalid GitHub UUID '" - + uuid + "'"); - return new GitHubOrganisationGroup(uuid.get().substring( - UUID_PREFIX.length()), null); + checkArgument(uuid.get().startsWith(UUID_PREFIX), "Invalid GitHub UUID '" + uuid + "'"); + return new GitHubOrganisationGroup(uuid.get().substring(UUID_PREFIX.length()), null); } public static UUID uuid(String orgName) {
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubTeamGroup.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubTeamGroup.java index cd53736..105716a 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubTeamGroup.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/group/GitHubTeamGroup.java
@@ -23,16 +23,20 @@ public class GitHubTeamGroup extends GitHubGroup { public interface Factory { - GitHubTeamGroup get(@Assisted GitHubOrganisationGroup orgGroup, - @Assisted String teamName, @Nullable String teamUrl); + GitHubTeamGroup get( + @Assisted GitHubOrganisationGroup orgGroup, + @Assisted String teamName, + @Nullable String teamUrl); } private final GitHubOrganisationGroup orgGroup; private final String teamName; @Inject - GitHubTeamGroup(@Assisted GitHubOrganisationGroup orgGroup, - @Assisted String teamName, @Nullable String teamUrl) { + GitHubTeamGroup( + @Assisted GitHubOrganisationGroup orgGroup, + @Assisted String teamName, + @Nullable String teamUrl) { super(uuid(orgGroup.getGroupUUID(), teamName), teamUrl); this.orgGroup = orgGroup; this.teamName = teamName; @@ -47,9 +51,8 @@ return new AccountGroup.UUID(orgUUID.get() + "/" + teamName); } - public static GroupReference groupReference(GroupReference orgReference, - String teamName) { - return new GroupReference(uuid(orgReference.getUUID(), teamName), - orgReference.getName() + "/" + teamName); + public static GroupReference groupReference(GroupReference orgReference, String teamName) { + return new GroupReference( + uuid(orgReference.getUUID(), teamName), orgReference.getName() + "/" + teamName); } }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/notification/PingHandler.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/notification/PingHandler.java index bbedb71..72a3afb 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/notification/PingHandler.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/notification/PingHandler.java
@@ -14,23 +14,19 @@ package com.googlesource.gerrit.plugins.github.notification; +import com.google.inject.Singleton; import java.io.IOException; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.inject.Singleton; - /** * Handles ping event in github webhook. * - * @see <a href="https://developer.github.com/webhooks/#ping-event">Ping - * Event</a> + * @see <a href="https://developer.github.com/webhooks/#ping-event">Ping Event</a> */ @Singleton class PingHandler implements WebhookEventHandler<PingHandler.Ping> { - private static final Logger logger = - LoggerFactory.getLogger(PingHandler.class); + private static final Logger logger = LoggerFactory.getLogger(PingHandler.class); static class Ping { String zen;
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/notification/PullRequestHandler.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/notification/PullRequestHandler.java index 017d3d2..540b98a 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/notification/PullRequestHandler.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/notification/PullRequestHandler.java
@@ -14,30 +14,26 @@ package com.googlesource.gerrit.plugins.github.notification; -import java.io.IOException; - -import org.kohsuke.github.GHEventPayload.PullRequest; -import org.kohsuke.github.GHRepository; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import com.googlesource.gerrit.plugins.github.git.PullRequestImportType; import com.googlesource.gerrit.plugins.github.git.PullRequestImporter; +import java.io.IOException; +import org.kohsuke.github.GHEventPayload.PullRequest; +import org.kohsuke.github.GHRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Handles pull_request event in github webhook. * - * @see <a href= - * "https://developer.github.com/v3/activity/events/types/#pullrequestevent"> - * Pull Request Event</a> + * @see <a href= "https://developer.github.com/v3/activity/events/types/#pullrequestevent"> Pull + * Request Event</a> */ @Singleton class PullRequestHandler implements WebhookEventHandler<PullRequest> { - private static final Logger logger = LoggerFactory - .getLogger(PullRequestHandler.class); + private static final Logger logger = LoggerFactory.getLogger(PullRequestHandler.class); private final Provider<PullRequestImporter> prImportProvider; @Inject @@ -55,8 +51,8 @@ String organization = repository.getOwnerName(); String name = repository.getName(); logger.info("Importing {}/{}#{}", organization, name, prNumber); - prImporter.importPullRequest(0, organization, name, prNumber.intValue(), - PullRequestImportType.Commits); + prImporter.importPullRequest( + 0, organization, name, prNumber.intValue(), PullRequestImportType.Commits); logger.info("Imported {}/{}#{}", organization, name, prNumber); return true; }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/notification/WebhookEventHandler.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/notification/WebhookEventHandler.java index b0ab094..3008bde 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/notification/WebhookEventHandler.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/notification/WebhookEventHandler.java
@@ -15,23 +15,19 @@ package com.googlesource.gerrit.plugins.github.notification; import java.io.IOException; - import org.kohsuke.github.GHEvent; /** - * Abstract interface to handler which is responsible for a specific github - * webhook event type. + * Abstract interface to handler which is responsible for a specific github webhook event type. * - * Implementation classes must be named by the convention which - * {@link WebhookServlet#getWebhookClassName(GHEvent)} defines. + * <p>Implementation classes must be named by the convention which {@link + * WebhookServlet#getWebhookClassName(GHEvent)} defines. * * @param <T> Type of payload. Must be consistent to the event type. - * * @return true if the event has been successfully processed */ interface WebhookEventHandler<T> { Class<T> getPayloadType(); - boolean doAction(T payload) - throws IOException; -} \ No newline at end of file + boolean doAction(T payload) throws IOException; +}
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/notification/WebhookServlet.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/notification/WebhookServlet.java index 5e79304..64eb8c7 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/notification/WebhookServlet.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/notification/WebhookServlet.java
@@ -19,30 +19,6 @@ import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.security.InvalidKeyException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.binary.Hex; -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Strings; @@ -59,25 +35,43 @@ import com.googlesource.gerrit.plugins.github.oauth.GitHubLogin; import com.googlesource.gerrit.plugins.github.oauth.ScopedProvider; import com.googlesource.gerrit.plugins.github.oauth.UserScopedProvider; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.security.InvalidKeyException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.apache.commons.codec.DecoderException; +import org.apache.commons.codec.binary.Hex; +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * Handles webhook callbacks sent from Github. Delegates requests to - * implementations of {@link WebhookEventHandler}. + * Handles webhook callbacks sent from Github. Delegates requests to implementations of {@link + * WebhookEventHandler}. */ @Singleton public class WebhookServlet extends HttpServlet { private static final long serialVersionUID = 1L; - private static final Logger logger = - LoggerFactory.getLogger(WebhookServlet.class); + private static final Logger logger = LoggerFactory.getLogger(WebhookServlet.class); - private static final String PACKAGE_NAME = - WebhookServlet.class.getPackage().getName(); + private static final String PACKAGE_NAME = WebhookServlet.class.getPackage().getName(); private static final String SIGNATURE_PREFIX = "sha1="; private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1"; private final Gson gson; - private final Map<String, WebhookEventHandler<?>> handlerByName = - new ConcurrentHashMap<>(); + private final Map<String, WebhookEventHandler<?>> handlerByName = new ConcurrentHashMap<>(); private final Injector injector; private final GitHubConfig config; @@ -86,9 +80,12 @@ private final DynamicItem<WebSession> session; @Inject - public WebhookServlet(UserScopedProvider<GitHubLogin> loginProvider, + public WebhookServlet( + UserScopedProvider<GitHubLogin> loginProvider, ScopedProvider<GitHubLogin> requestScopedLoginProvider, - GitHubConfig config, Gson gson, DynamicItem<WebSession> session, + GitHubConfig config, + Gson gson, + DynamicItem<WebSession> session, Injector injector) { this.loginProvider = loginProvider; this.requestScopedLoginProvider = requestScopedLoginProvider; @@ -125,16 +122,15 @@ private String eventClassName(String name) { String[] nameParts = name.split("_"); List<String> classNameParts = - Lists.transform(Arrays.asList(nameParts), + Lists.transform( + Arrays.asList(nameParts), new Function<String, String>() { @Override public String apply(String part) { - return Character.toUpperCase(part.charAt(0)) - + part.substring(1); + return Character.toUpperCase(part.charAt(0)) + part.substring(1); } }); - return PACKAGE_NAME + "." + Joiner.on("").join(classNameParts) - + "Handler"; + return PACKAGE_NAME + "." + Joiner.on("").join(classNameParts) + "Handler"; } @Override @@ -146,8 +142,7 @@ return; } - WebhookEventHandler<?> handler = - getWebhookHandler(req.getHeader("X-Github-Event")); + WebhookEventHandler<?> handler = getWebhookHandler(req.getHeader("X-Github-Event")); if (handler == null) { resp.sendError(SC_NOT_FOUND); return; @@ -155,8 +150,7 @@ try (BufferedReader reader = req.getReader()) { String body = Joiner.on("\n").join(CharStreams.readLines(reader)); - if (!validateSignature(req.getHeader("X-Hub-Signature"), body, - req.getCharacterEncoding())) { + if (!validateSignature(req.getHeader("X-Hub-Signature"), body, req.getCharacterEncoding())) { logger.error("Signature mismatch to the payload"); resp.sendError(SC_FORBIDDEN); return; @@ -167,7 +161,8 @@ if (login == null || !login.isLoggedIn()) { logger.error( "Cannot login to github as {}. {}.webhookUser is not correctly configured?", - config.webhookUser, GitHubConfig.CONF_SECTION); + config.webhookUser, + GitHubConfig.CONF_SECTION); resp.setStatus(SC_INTERNAL_SERVER_ERROR); return; } @@ -187,8 +182,8 @@ if (payload != null) { return handler.doAction(payload); } - logger.error("Cannot decode JSON payload '" + jsonBody + "' into " - + handler.getPayloadType().getName()); + logger.error( + "Cannot decode JSON payload '" + jsonBody + "' into " + handler.getPayloadType().getName()); return false; } @@ -197,16 +192,16 @@ * * @param signatureHeader signature HTTP request header of a github webhook * @param payload HTTP request body - * @return true if webhook secret is not configured or signatureHeader is - * valid against payload and the secret, false if otherwise. + * @return true if webhook secret is not configured or signatureHeader is valid against payload + * and the secret, false if otherwise. * @throws UnsupportedEncodingException */ - private boolean validateSignature(String signatureHeader, String body, - String encoding) throws UnsupportedEncodingException { + private boolean validateSignature(String signatureHeader, String body, String encoding) + throws UnsupportedEncodingException { byte[] payload = body.getBytes(encoding == null ? "UTF-8" : encoding); if (config.webhookSecret == null || config.webhookSecret.equals("")) { - logger.debug("{}.webhookSecret not configured. Skip signature validation", - GitHubConfig.CONF_SECTION); + logger.debug( + "{}.webhookSecret not configured. Skip signature validation", GitHubConfig.CONF_SECTION); return true; } @@ -216,8 +211,7 @@ } byte[] signature; try { - signature = Hex.decodeHex( - signatureHeader.substring(SIGNATURE_PREFIX.length()).toCharArray()); + signature = Hex.decodeHex(signatureHeader.substring(SIGNATURE_PREFIX.length()).toCharArray()); } catch (DecoderException e) { logger.error("Invalid signature: {}", signatureHeader); return false; @@ -231,12 +225,11 @@ * @param payload payload to calculate a signature for * @return signature of the payload * @see <a href= - * "https://developer.github.com/webhooks/securing/#validating-payloads-from-github"> - * Validating payloads from GitHub</a> + * "https://developer.github.com/webhooks/securing/#validating-payloads-from-github"> + * Validating payloads from GitHub</a> */ private byte[] getExpectedSignature(byte[] payload) { - SecretKeySpec key = - new SecretKeySpec(config.webhookSecret.getBytes(), HMAC_SHA1_ALGORITHM); + SecretKeySpec key = new SecretKeySpec(config.webhookSecret.getBytes(), HMAC_SHA1_ALGORITHM); Mac hmac; try { hmac = Mac.getInstance(HMAC_SHA1_ALGORITHM); @@ -244,8 +237,7 @@ } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Hmac SHA1 must be supported", e); } catch (InvalidKeyException e) { - throw new IllegalStateException( - "Hmac SHA1 must be compatible to Hmac SHA1 Secret Key", e); + throw new IllegalStateException("Hmac SHA1 must be compatible to Hmac SHA1 Secret Key", e); } return hmac.doFinal(payload); }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/Destination.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/Destination.java index 193024e..b1b2df3 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/Destination.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/Destination.java
@@ -28,14 +28,12 @@ import com.google.gerrit.server.project.NoSuchProjectException; import com.google.gerrit.server.project.ProjectControl; import com.google.inject.Injector; - -import org.eclipse.jgit.lib.Config; -import org.eclipse.jgit.transport.RemoteConfig; -import org.eclipse.jgit.transport.URIish; - import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.List; +import org.eclipse.jgit.lib.Config; +import org.eclipse.jgit.transport.RemoteConfig; +import org.eclipse.jgit.transport.URIish; public class Destination { private final RemoteConfig remote; @@ -43,33 +41,31 @@ private final String remoteNameStyle; private final CurrentUser remoteUser; - Destination(final Injector injector, final RemoteConfig rc, final Config cfg, + Destination( + final Injector injector, + final RemoteConfig rc, + final Config cfg, final RemoteSiteUser.Factory replicationUserFactory, final PluginUser pluginUser, final GroupBackend groupBackend) { remote = rc; remoteNameStyle = - MoreObjects.firstNonNull( - cfg.getString("remote", rc.getName(), "remoteNameStyle"), "slash"); + MoreObjects.firstNonNull(cfg.getString("remote", rc.getName(), "remoteNameStyle"), "slash"); - String[] authGroupNames = - cfg.getStringList("remote", rc.getName(), "authGroup"); + String[] authGroupNames = cfg.getStringList("remote", rc.getName(), "authGroup"); if (authGroupNames.length > 0) { ImmutableSet.Builder<AccountGroup.UUID> builder = ImmutableSet.builder(); for (String name : authGroupNames) { - GroupReference g = - GroupBackends.findExactSuggestion(groupBackend, name); + GroupReference g = GroupBackends.findExactSuggestion(groupBackend, name); if (g != null) { builder.add(g.getUUID()); } else { - GitHubDestinations.log.warn(String.format( - "Group \"%s\" not recognized, removing from authGroup", name)); + GitHubDestinations.log.warn( + String.format("Group \"%s\" not recognized, removing from authGroup", name)); } } - remoteUser = - replicationUserFactory - .create(new ListGroupMembership(builder.build())); + remoteUser = replicationUserFactory.create(new ListGroupMembership(builder.build())); } else { remoteUser = pluginUser; } @@ -77,8 +73,7 @@ projectControlFactory = injector.getInstance(ProjectControl.Factory.class); } - ProjectControl controlFor(Project.NameKey project) - throws NoSuchProjectException { + ProjectControl controlFor(Project.NameKey project) throws NoSuchProjectException { return projectControlFactory.controlFor(project); } @@ -95,12 +90,10 @@ } else if (remoteNameStyle.equals("underscore")) { name = name.replace("/", "_"); } else if (!remoteNameStyle.equals("slash")) { - GitHubDestinations.log.debug(String.format( - "Unknown remoteNameStyle: %s, falling back to slash", - remoteNameStyle)); + GitHubDestinations.log.debug( + String.format("Unknown remoteNameStyle: %s, falling back to slash", remoteNameStyle)); } - String replacedPath = - GitHubDestinations.replaceName(uri.getPath(), name); + String replacedPath = GitHubDestinations.replaceName(uri.getPath(), name); if (replacedPath != null) { uri = uri.setPath(replacedPath); r.add(uri); @@ -125,8 +118,7 @@ // context. In the path part of a URI space should be %20, but in form // data // space is '+'. Our cleanup replace fixes these two issues. - return URLEncoder.encode(str, "UTF-8").replaceAll("%2[fF]", "/") - .replace("+", "%20"); + return URLEncoder.encode(str, "UTF-8").replaceAll("%2[fF]", "/").replace("+", "%20"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/GitHubDestinations.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/GitHubDestinations.java index 92cea4e..585244b 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/GitHubDestinations.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/GitHubDestinations.java
@@ -21,16 +21,6 @@ import com.google.gerrit.server.config.SitePaths; import com.google.inject.Inject; import com.google.inject.Injector; - -import org.eclipse.jgit.errors.ConfigInvalidException; -import org.eclipse.jgit.storage.file.FileBasedConfig; -import org.eclipse.jgit.transport.RefSpec; -import org.eclipse.jgit.transport.RemoteConfig; -import org.eclipse.jgit.transport.URIish; -import org.eclipse.jgit.util.FS; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; @@ -39,6 +29,14 @@ import java.util.Collections; import java.util.List; import java.util.Set; +import org.eclipse.jgit.errors.ConfigInvalidException; +import org.eclipse.jgit.storage.file.FileBasedConfig; +import org.eclipse.jgit.transport.RefSpec; +import org.eclipse.jgit.transport.RemoteConfig; +import org.eclipse.jgit.transport.URIish; +import org.eclipse.jgit.util.FS; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** Manages automatic replication to remote repositories. */ public class GitHubDestinations { @@ -57,7 +55,6 @@ private final Injector injector; private final List<Destination> configs; - private final RemoteSiteUser.Factory replicationUserFactory; private final PluginUser pluginUser; private final GroupBackend groupBackend; @@ -65,9 +62,12 @@ private final List<String> organisations; @Inject - GitHubDestinations(final Injector i, final SitePaths site, + GitHubDestinations( + final Injector i, + final SitePaths site, final RemoteSiteUser.Factory ruf, - final GroupBackend gb, final PluginUser pu) + final GroupBackend gb, + final PluginUser pu) throws ConfigInvalidException, IOException { injector = i; pluginUser = pu; @@ -92,17 +92,16 @@ throws ConfigInvalidException, IOException { if (!Files.exists(cfgPath) || Files.size(cfgPath) == 0) { return Collections.emptyList(); - } - + } + FileBasedConfig cfg = new FileBasedConfig(cfgPath.toFile(), FS.DETECTED); try { cfg.load(); } catch (ConfigInvalidException e) { - throw new ConfigInvalidException(String.format( - "Config file %s is invalid: %s", cfg.getFile(), e.getMessage()), e); + throw new ConfigInvalidException( + String.format("Config file %s is invalid: %s", cfg.getFile(), e.getMessage()), e); } catch (IOException e) { - throw new IOException(String.format("Cannot read %s: %s", cfg.getFile(), - e.getMessage()), e); + throw new IOException(String.format("Cannot read %s: %s", cfg.getFile(), e.getMessage()), e); } ImmutableList.Builder<Destination> dest = ImmutableList.builder(); @@ -113,9 +112,10 @@ for (URIish u : c.getURIs()) { if (u.getPath() == null || !u.getPath().contains("${name}")) { - throw new ConfigInvalidException(String.format( - "remote.%s.url \"%s\" lacks ${name} placeholder in %s", - c.getName(), u, cfg.getFile())); + throw new ConfigInvalidException( + String.format( + "remote.%s.url \"%s\" lacks ${name} placeholder in %s", + c.getName(), u, cfg.getFile())); } } @@ -127,19 +127,16 @@ } if (c.getPushRefSpecs().isEmpty()) { - c.addPushRefSpec(new RefSpec().setSourceDestination("refs/*", "refs/*") - .setForceUpdate(true)); + c.addPushRefSpec( + new RefSpec().setSourceDestination("refs/*", "refs/*").setForceUpdate(true)); } - dest.add(new Destination(injector, c, cfg, - replicationUserFactory, pluginUser, - groupBackend)); + dest.add(new Destination(injector, c, cfg, replicationUserFactory, pluginUser, groupBackend)); } return dest.build(); } - private static List<RemoteConfig> allRemotes(FileBasedConfig cfg) - throws ConfigInvalidException { + private static List<RemoteConfig> allRemotes(FileBasedConfig cfg) throws ConfigInvalidException { Set<String> names = cfg.getSubsections("remote"); List<RemoteConfig> result = Lists.newArrayListWithCapacity(names.size()); for (String name : names) { @@ -148,8 +145,8 @@ result.add(new RemoteConfig(cfg, name)); } } catch (URISyntaxException e) { - throw new ConfigInvalidException(String.format( - "remote %s has invalid URL in %s", name, cfg.getFile())); + throw new ConfigInvalidException( + String.format("remote %s has invalid URL in %s", name, cfg.getFile())); } } return result;
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ListProjectReplicationStatus.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ListProjectReplicationStatus.java index 868ac5b..87ac175 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ListProjectReplicationStatus.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ListProjectReplicationStatus.java
@@ -30,8 +30,8 @@ } @Override - public Object apply(ProjectResource resource) throws AuthException, - BadRequestException, ResourceConflictException, Exception { + public Object apply(ProjectResource resource) + throws AuthException, BadRequestException, ResourceConflictException, Exception { return statusStore.list(resource.getNameKey()); } }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/RemoteSiteUser.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/RemoteSiteUser.java index 42f6857..26def83 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/RemoteSiteUser.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/RemoteSiteUser.java
@@ -15,7 +15,6 @@ package com.googlesource.gerrit.plugins.github.replication; import com.google.gerrit.server.CurrentUser; -import com.google.gerrit.server.account.CapabilityControl; import com.google.gerrit.server.account.GroupMembership; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; @@ -28,9 +27,7 @@ private final GroupMembership effectiveGroups; @Inject - RemoteSiteUser(CapabilityControl.Factory capabilityControlFactory, - @Assisted GroupMembership authGroups) { - super(capabilityControlFactory); + RemoteSiteUser(@Assisted GroupMembership authGroups) { effectiveGroups = authGroups; }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ReplicationStatusFlatFile.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ReplicationStatusFlatFile.java index 4d5a033..70723d2 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ReplicationStatusFlatFile.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ReplicationStatusFlatFile.java
@@ -18,6 +18,12 @@ import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; import static java.nio.file.StandardOpenOption.WRITE; +import com.google.gerrit.extensions.annotations.PluginData; +import com.google.gerrit.reviewdb.client.Project; +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.google.inject.Inject; +import com.google.inject.Provider; import java.io.IOException; import java.io.Reader; import java.nio.charset.StandardCharsets; @@ -29,36 +35,26 @@ import java.util.ArrayList; import java.util.List; -import com.google.gerrit.extensions.annotations.PluginData; -import com.google.gerrit.reviewdb.client.Project; -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import com.google.inject.Inject; -import com.google.inject.Provider; - public class ReplicationStatusFlatFile implements ReplicationStatusStore { private final Path pluginData; private final Gson gson; @Inject - public ReplicationStatusFlatFile(@PluginData Path pluginData, - Provider<Gson> gsonProvider) { + public ReplicationStatusFlatFile(@PluginData Path pluginData, Provider<Gson> gsonProvider) { this.pluginData = pluginData; this.gson = gsonProvider.get(); } @Override - public void set(Project.NameKey projectKey, String refKey, - JsonObject statusEvent) throws IOException { - Path replicationStatusPath = - getReplicationStatusPath(projectKey.get() + "/" + refKey); - Files.write(replicationStatusPath, statusEvent.toString().getBytes(), - TRUNCATE_EXISTING, CREATE, WRITE); + public void set(Project.NameKey projectKey, String refKey, JsonObject statusEvent) + throws IOException { + Path replicationStatusPath = getReplicationStatusPath(projectKey.get() + "/" + refKey); + Files.write( + replicationStatusPath, statusEvent.toString().getBytes(), TRUNCATE_EXISTING, CREATE, WRITE); } private Path getReplicationStatusPath(String key) throws IOException { - Path projectPath = - pluginData.resolve(getSanitizedKey(key) + ".replication-error.json"); + Path projectPath = pluginData.resolve(getSanitizedKey(key) + ".replication-error.json"); Files.createDirectories(projectPath.getParent()); return projectPath; } @@ -72,20 +68,20 @@ public List<JsonObject> list(Project.NameKey parentKey) throws IOException { Path projectPath = pluginData.resolve(getSanitizedKey(parentKey.get())); final List<JsonObject> entries = new ArrayList<>(); - Files.walkFileTree(projectPath, new SimpleFileVisitor<Path>() { + Files.walkFileTree( + projectPath, + new SimpleFileVisitor<Path>() { - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) - throws IOException { - try (Reader fileReader = - Files.newBufferedReader(file, StandardCharsets.UTF_8)) { - JsonObject json = gson.fromJson(fileReader, JsonObject.class); - entries.add(json); - } - return FileVisitResult.CONTINUE; - } - }); + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) + throws IOException { + try (Reader fileReader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { + JsonObject json = gson.fromJson(fileReader, JsonObject.class); + entries.add(json); + } + return FileVisitResult.CONTINUE; + } + }); return entries; } - }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ReplicationStatusListener.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ReplicationStatusListener.java index 49358a9..89fe432 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ReplicationStatusListener.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ReplicationStatusListener.java
@@ -14,11 +14,6 @@ package com.googlesource.gerrit.plugins.github.replication; -import java.io.IOException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.google.gerrit.common.EventListener; import com.google.gerrit.reviewdb.client.Project.NameKey; import com.google.gerrit.server.events.Event; @@ -28,19 +23,21 @@ import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; +import java.io.IOException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @Singleton public class ReplicationStatusListener implements EventListener { private static final String REF_REPLICATED_EVENT = "ref-replicated"; - private static Logger log = LoggerFactory - .getLogger(ReplicationStatusListener.class); + private static Logger log = LoggerFactory.getLogger(ReplicationStatusListener.class); private final ReplicationStatusStore statusStore; private final Gson gson; @Inject - public ReplicationStatusListener(ReplicationStatusStore statusStore, - Provider<Gson> gsonProvider) { + public ReplicationStatusListener( + ReplicationStatusStore statusStore, Provider<Gson> gsonProvider) { this.statusStore = statusStore; this.gson = gsonProvider.get(); } @@ -57,8 +54,12 @@ try { statusStore.set(projectNameKey, refKey, eventJson); } catch (IOException e) { - log.error("Unable to update replication status for event " + eventJson - + " on project " + projectNameKey, e); + log.error( + "Unable to update replication status for event " + + eventJson + + " on project " + + projectNameKey, + e); } } }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ReplicationStatusStore.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ReplicationStatusStore.java index 75c1872..ba03105 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ReplicationStatusStore.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ReplicationStatusStore.java
@@ -14,16 +14,15 @@ package com.googlesource.gerrit.plugins.github.replication; +import com.google.gerrit.reviewdb.client.Project; +import com.google.gson.JsonObject; import java.io.IOException; import java.util.List; -import com.google.gerrit.reviewdb.client.Project; -import com.google.gson.JsonObject; - public interface ReplicationStatusStore { - public void set(Project.NameKey projectKey, String refKey, - JsonObject statusEvent) throws IOException; + public void set(Project.NameKey projectKey, String refKey, JsonObject statusEvent) + throws IOException; public List<JsonObject> list(Project.NameKey projectKey) throws IOException; }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/velocity/PluginVelocityModel.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/velocity/PluginVelocityModel.java index 8b4236b..4970e1d 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/velocity/PluginVelocityModel.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/velocity/PluginVelocityModel.java
@@ -15,7 +15,6 @@ import com.google.inject.Inject; import com.google.inject.servlet.RequestScoped; - import org.apache.velocity.VelocityContext; @RequestScoped
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/velocity/PluginVelocityRuntimeProvider.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/velocity/PluginVelocityRuntimeProvider.java index b0ef350..7f5ed56 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/velocity/PluginVelocityRuntimeProvider.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/velocity/PluginVelocityRuntimeProvider.java
@@ -20,28 +20,21 @@ import com.google.inject.Provider; import com.google.inject.ProvisionException; import com.google.inject.Singleton; - +import java.net.URL; +import java.net.URLClassLoader; +import java.util.Properties; import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.RuntimeInstance; import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; import org.apache.velocity.runtime.resource.loader.JarResourceLoader; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.Properties; - @Singleton public class PluginVelocityRuntimeProvider implements Provider<RuntimeInstance> { - private static final String VELOCITY_FILE_RESOURCE_LOADER_PATH = - "file.resource.loader.path"; - private static final String VELOCITY_FILE_RESOURCE_LOADER_CLASS = - "file.resource.loader.class"; - private static final String VELOCITY_CLASS_RESOURCE_LOADER_CLASS = - "class.resource.loader.class"; - private static final String VELOCITY_JAR_RESOURCE_LOADER_CLASS = - "jar.resource.loader.class"; - private static final String VELOCITY_JAR_RESOURCE_LOADER_PATH = - "jar.resource.loader.path"; + private static final String VELOCITY_FILE_RESOURCE_LOADER_PATH = "file.resource.loader.path"; + private static final String VELOCITY_FILE_RESOURCE_LOADER_CLASS = "file.resource.loader.class"; + private static final String VELOCITY_CLASS_RESOURCE_LOADER_CLASS = "class.resource.loader.class"; + private static final String VELOCITY_JAR_RESOURCE_LOADER_CLASS = "jar.resource.loader.class"; + private static final String VELOCITY_JAR_RESOURCE_LOADER_PATH = "jar.resource.loader.path"; private static final String VELOCITY_RESOURCE_LOADER = "resource.loader"; private final SitePaths site; private String pluginName; @@ -58,20 +51,17 @@ Properties p = new Properties(); p.setProperty(RuntimeConstants.VM_PERM_INLINE_LOCAL, "true"); - p.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, - Slf4jLogChute.class.getName()); + p.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, Slf4jLogChute.class.getName()); p.setProperty(RuntimeConstants.RUNTIME_REFERENCES_STRICT, "true"); p.setProperty("runtime.log.logsystem.log4j.category", "velocity"); p.setProperty(VELOCITY_RESOURCE_LOADER, "file, class, jar"); - p.setProperty(VELOCITY_FILE_RESOURCE_LOADER_CLASS, pkg - + ".FileResourceLoader"); - p.setProperty(VELOCITY_FILE_RESOURCE_LOADER_PATH, + p.setProperty(VELOCITY_FILE_RESOURCE_LOADER_CLASS, pkg + ".FileResourceLoader"); + p.setProperty( + VELOCITY_FILE_RESOURCE_LOADER_PATH, site.static_dir.getParent().toAbsolutePath().toString()); - p.setProperty(VELOCITY_CLASS_RESOURCE_LOADER_CLASS, - ClasspathResourceLoader.class.getName()); - p.setProperty(VELOCITY_JAR_RESOURCE_LOADER_CLASS, - JarResourceLoader.class.getName()); + p.setProperty(VELOCITY_CLASS_RESOURCE_LOADER_CLASS, ClasspathResourceLoader.class.getName()); + p.setProperty(VELOCITY_JAR_RESOURCE_LOADER_CLASS, JarResourceLoader.class.getName()); p.setProperty(VELOCITY_JAR_RESOURCE_LOADER_PATH, detectPluginJar()); RuntimeInstance ri = new RuntimeInstance(); @@ -86,8 +76,7 @@ private String detectPluginJar() { ClassLoader myClassLoader = this.getClass().getClassLoader(); if (!URLClassLoader.class.isAssignableFrom(myClassLoader.getClass())) { - throw new IllegalStateException(pluginName - + " plugin can be loaded only from a Jar file"); + throw new IllegalStateException(pluginName + " plugin can be loaded only from a Jar file"); } @SuppressWarnings("resource") @@ -99,8 +88,11 @@ } } - throw new IllegalStateException("Cannot find any Jar file in " + pluginName - + " plugin class loader URLs " + jarUrls - + ": unable to initialize Velocity resource loading."); + throw new IllegalStateException( + "Cannot find any Jar file in " + + pluginName + + " plugin class loader URLs " + + jarUrls + + ": unable to initialize Velocity resource loading."); } }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/velocity/VelocityStaticServlet.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/velocity/VelocityStaticServlet.java index 15b698b..46119af 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/velocity/VelocityStaticServlet.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/velocity/VelocityStaticServlet.java
@@ -21,13 +21,6 @@ import com.google.inject.Provider; import com.google.inject.Singleton; import com.google.inject.name.Named; - -import org.apache.commons.io.IOUtils; -import org.apache.velocity.runtime.RuntimeInstance; -import org.apache.velocity.runtime.resource.Resource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -35,18 +28,22 @@ import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.zip.GZIPOutputStream; - import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.commons.io.IOUtils; +import org.apache.velocity.runtime.RuntimeInstance; +import org.apache.velocity.runtime.resource.Resource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** Sends static content using Velocity resource resolver */ @SuppressWarnings("serial") @Singleton public class VelocityStaticServlet extends HttpServlet { - private static final Logger log = LoggerFactory - .getLogger(VelocityStaticServlet.class); + private static final Logger log = LoggerFactory.getLogger(VelocityStaticServlet.class); private static final Map<String, String> MIME_TYPES = Maps.newHashMap(); + static { MIME_TYPES.put("html", "text/html"); MIME_TYPES.put("htm", "text/html"); @@ -89,7 +86,7 @@ return out.toByteArray(); } - private final RuntimeInstance velocity; + private final RuntimeInstance velocity; @Inject VelocityStaticServlet( @@ -133,8 +130,8 @@ } @Override - protected void doGet(final HttpServletRequest req, - final HttpServletResponse rsp) throws IOException { + protected void doGet(final HttpServletRequest req, final HttpServletResponse rsp) + throws IOException { final Resource p = local(req); if (p == null) { CacheHeaders.setNotCacheable(rsp); @@ -144,8 +141,7 @@ final String type = contentType(p.getName()); final byte[] tosend; - if (!type.equals("application/x-javascript") - && RPCServletUtils.acceptsGzipEncoding(req)) { + if (!type.equals("application/x-javascript") && RPCServletUtils.acceptsGzipEncoding(req)) { rsp.setHeader("Content-Encoding", "gzip"); tosend = compress(readResource(p)); } else {
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/velocity/VelocityViewServlet.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/velocity/VelocityViewServlet.java index 1e5f447..85197dd 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/velocity/VelocityViewServlet.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/velocity/VelocityViewServlet.java
@@ -22,7 +22,15 @@ import com.googlesource.gerrit.plugins.github.GitHubConfig; import com.googlesource.gerrit.plugins.github.oauth.GitHubLogin; import com.googlesource.gerrit.plugins.github.oauth.ScopedProvider; - +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Map.Entry; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.apache.http.HttpStatus; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; @@ -31,21 +39,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Map.Entry; - -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - @Singleton public class VelocityViewServlet extends HttpServlet { - private static final Logger log = LoggerFactory - .getLogger(VelocityViewServlet.class); + private static final Logger log = LoggerFactory.getLogger(VelocityViewServlet.class); private static final String STATIC_PREFIX = "/static/"; private static final long serialVersionUID = 529071287765413268L; private final RuntimeInstance velocityRuntime; @@ -58,7 +54,7 @@ public VelocityViewServlet( @Named("PluginRuntimeInstance") final RuntimeInstance velocityRuntime, Provider<PluginVelocityModel> modelProvider, - ScopedProvider<GitHubLogin> loginProvider, + ScopedProvider<GitHubLogin> loginProvider, Provider<CurrentUser> userProvider, GitHubConfig config) { @@ -69,7 +65,6 @@ this.config = config; } - @Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { @@ -78,9 +73,7 @@ String pathInfo = STATIC_PREFIX - + MoreObjects.firstNonNull( - (String) req.getAttribute("destUrl"), - req.getPathInfo()); + + MoreObjects.firstNonNull((String) req.getAttribute("destUrl"), req.getPathInfo()); try { Template template = velocityRuntime.getTemplate(pathInfo, "UTF-8"); @@ -94,8 +87,7 @@ resp.sendError(HttpStatus.SC_NOT_FOUND); } catch (Exception e) { log.error("Error executing velocity template " + pathInfo, e); - resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, - e.getLocalizedMessage()); + resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getLocalizedMessage()); } } @@ -104,7 +96,7 @@ GitHubLogin gitHubLogin = loginProvider.get(request); model.put("myself", gitHubLogin.getMyself()); model.put("config", config); - + CurrentUser user = userProvider.get(); if (user.isIdentifiedUser()) { model.put("user", user);
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/AccountController.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/AccountController.java index 13085c4..1ede315 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/AccountController.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/AccountController.java
@@ -18,23 +18,27 @@ import com.google.common.collect.Sets; import com.google.gerrit.extensions.common.SshKeyInfo; import com.google.gerrit.extensions.restapi.RawInput; -import com.google.gerrit.reviewdb.client.Account; import com.google.gerrit.reviewdb.client.Account.Id; -import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.account.AccountCache; -import com.google.gerrit.server.account.AccountException; import com.google.gerrit.server.account.AccountManager; import com.google.gerrit.server.account.AccountResource; import com.google.gerrit.server.account.AddSshKey; import com.google.gerrit.server.account.AuthRequest; import com.google.gerrit.server.account.AuthResult; import com.google.gerrit.server.account.GetSshKeys; -import com.google.gwtorm.server.OrmException; +import com.google.gerrit.server.account.PutName; +import com.google.gerrit.server.account.PutPreferred; import com.google.inject.Inject; -import com.google.inject.Provider; import com.googlesource.gerrit.plugins.github.oauth.GitHubLogin; - +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashSet; +import java.util.List; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.eclipse.jgit.errors.ConfigInvalidException; import org.kohsuke.github.GHKey; @@ -43,41 +47,39 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - public class AccountController implements VelocityController { - private static final Logger log = LoggerFactory - .getLogger(AccountController.class); + private static final Logger log = LoggerFactory.getLogger(AccountController.class); private final AddSshKey restAddSshKey; private final GetSshKeys restGetSshKeys; private final AccountManager accountManager; - private final Provider<ReviewDb> dbProvider; private final AccountCache accountCache; + private final PutPreferred putPreferred; + private final PutName putName; @Inject - public AccountController(final AddSshKey restAddSshKey, - final GetSshKeys restGetSshKeys, final AccountManager accountManager, - final Provider<ReviewDb> dbProvider, final AccountCache accountCache) { + public AccountController( + final AddSshKey restAddSshKey, + final GetSshKeys restGetSshKeys, + final AccountManager accountManager, + final AccountCache accountCache, + final PutPreferred putPreferred, + final PutName putName) { this.restAddSshKey = restAddSshKey; this.restGetSshKeys = restGetSshKeys; this.accountManager = accountManager; - this.dbProvider = dbProvider; this.accountCache = accountCache; + this.putPreferred = putPreferred; + this.putName = putName; } @Override - public void doAction(IdentifiedUser user, GitHubLogin hubLogin, - HttpServletRequest req, HttpServletResponse resp, ControllerErrors errors) + public void doAction( + IdentifiedUser user, + GitHubLogin hubLogin, + HttpServletRequest req, + HttpServletResponse resp, + ControllerErrors errors) throws ServletException, IOException { try { setAccountIdentity(user, req); @@ -90,34 +92,35 @@ } } - private void setAccountIdentity(IdentifiedUser user, HttpServletRequest req) throws ServletException, ConfigInvalidException { + private void setAccountIdentity(IdentifiedUser user, HttpServletRequest req) + throws ServletException, ConfigInvalidException { String fullName = req.getParameter("fullname"); String email = req.getParameter("email"); try { Id accountId = user.getAccountId(); - AuthResult result = - accountManager.link(accountId, AuthRequest.forEmail(email)); - log.debug("Account {} linked to email {}: result = {}", accountId, email, - result); + AuthResult result = accountManager.link(accountId, AuthRequest.forEmail(email)); + log.debug("Account {} linked to email {}: result = {}", accountId, email, result); - Account a = dbProvider.get().accounts().get(accountId); - a.setPreferredEmail(email); - a.setFullName(fullName); - dbProvider.get().accounts().update(Collections.singleton(a)); + putPreferred.apply(new AccountResource.Email(user, email), null); + PutName.Input nameInput = new PutName.Input(); + nameInput.name = fullName; + putName.apply(user, nameInput); log.debug( "Account {} updated with preferredEmail = {} and fullName = {}", - accountId, email, fullName); + accountId, + email, + fullName); accountCache.evict(accountId); log.debug("Account cache evicted for {}", accountId); - } catch (AccountException | OrmException | IOException e) { - throw new ServletException("Cannot associate email '" + email - + "' to current user '" + user + "'", e); + } catch (Exception e) { + throw new ServletException( + "Cannot associate email '" + email + "' to current user '" + user + "'", e); } } - private void setAccoutPublicKeys(IdentifiedUser user, GitHubLogin hubLogin, - HttpServletRequest req) throws IOException { + private void setAccoutPublicKeys( + IdentifiedUser user, GitHubLogin hubLogin, HttpServletRequest req) throws IOException { GHMyself myself = hubLogin.getMyself(); List<GHVerifiedKey> githubKeys = myself.getPublicVerifiedKeys(); HashSet<String> gerritKeys = Sets.newHashSet(getCurrentGerritSshKeys(user)); @@ -125,7 +128,8 @@ String sshKeyCheckedParam = "key_check_" + ghKey.getId(); String sshKeyWithLabel = ghKey.getKey() + " " + ghKey.getTitle(); String checked = req.getParameter(sshKeyCheckedParam); - if (checked != null && checked.equalsIgnoreCase("on") + if (checked != null + && checked.equalsIgnoreCase("on") && !gerritKeys.contains(ghKey.getKey())) { addSshKey(user, sshKeyWithLabel); gerritKeys.add(ghKey.getKey()); @@ -133,19 +137,19 @@ } } - private List<String> getCurrentGerritSshKeys(final IdentifiedUser user) - throws IOException { + private List<String> getCurrentGerritSshKeys(final IdentifiedUser user) throws IOException { AccountResource res = new AccountResource(user); try { List<SshKeyInfo> keysInfo = restGetSshKeys.apply(res); - return Lists.transform(keysInfo, new Function<SshKeyInfo, String>() { + return Lists.transform( + keysInfo, + new Function<SshKeyInfo, String>() { - @Override - public String apply(SshKeyInfo keyInfo) { - return StringUtils.substringBeforeLast(keyInfo.sshPublicKey, " "); - } - - }); + @Override + public String apply(SshKeyInfo keyInfo) { + return StringUtils.substringBeforeLast(keyInfo.sshPublicKey, " "); + } + }); } catch (Exception e) { log.error("User list keys failed", e); throw new IOException("Cannot get list of user keys", e); @@ -155,26 +159,26 @@ private void addSshKey(final IdentifiedUser user, final String sshKeyWithLabel) throws IOException { AccountResource res = new AccountResource(user); - final ByteArrayInputStream keyIs = - new ByteArrayInputStream(sshKeyWithLabel.getBytes()); + final ByteArrayInputStream keyIs = new ByteArrayInputStream(sshKeyWithLabel.getBytes()); AddSshKey.Input key = new AddSshKey.Input(); - key.raw = new RawInput() { + key.raw = + new RawInput() { - @Override - public InputStream getInputStream() throws IOException { - return keyIs; - } + @Override + public InputStream getInputStream() throws IOException { + return keyIs; + } - @Override - public String getContentType() { - return "text/plain"; - } + @Override + public String getContentType() { + return "text/plain"; + } - @Override - public long getContentLength() { - return sshKeyWithLabel.length(); - } - }; + @Override + public long getContentLength() { + return sshKeyWithLabel.length(); + } + }; try { restAddSshKey.apply(res, key); } catch (Exception e) {
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/ControllerErrors.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/ControllerErrors.java index 49a4a84..289c397 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/ControllerErrors.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/ControllerErrors.java
@@ -16,14 +16,12 @@ import com.google.gerrit.server.IdentifiedUser; import com.google.inject.Inject; import com.google.inject.Singleton; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class ControllerErrors { - private static final Logger log = LoggerFactory - .getLogger(ControllerErrors.class); + private static final Logger log = LoggerFactory.getLogger(ControllerErrors.class); private final IdentifiedUser user; @@ -33,8 +31,11 @@ } public void submit(Exception e) { - log.error(String.format("User:%s Controller:%s Exception:%s '%s'", - getUser(), getController(), e.getClass(), e.getLocalizedMessage()), e); + log.error( + String.format( + "User:%s Controller:%s Exception:%s '%s'", + getUser(), getController(), e.getClass(), e.getLocalizedMessage()), + e); } private String getController() {
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/JobStatusController.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/JobStatusController.java index 5489282..d31e283 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/JobStatusController.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/JobStatusController.java
@@ -16,25 +16,20 @@ import com.google.common.collect.Lists; import com.google.gson.Gson; import com.google.gson.stream.JsonWriter; - import com.googlesource.gerrit.plugins.github.git.BatchImporter; import com.googlesource.gerrit.plugins.github.git.GitJob; import com.googlesource.gerrit.plugins.github.git.GitJobStatus; - import java.io.IOException; import java.util.Collection; import java.util.List; - import javax.servlet.http.HttpServletResponse; - - public class JobStatusController { public JobStatusController() { super(); } - + protected void respondWithJobStatusJson(HttpServletResponse resp, BatchImporter cloner) throws IOException { Collection<GitJob> jobs = cloner.getJobs(); @@ -46,6 +41,4 @@ new Gson().toJson(jobListStatus, jobListStatus.getClass(), writer); } } - - }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/PullRequestImportController.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/PullRequestImportController.java index 747f388..1a2ee89 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/PullRequestImportController.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/PullRequestImportController.java
@@ -17,14 +17,11 @@ import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; - import com.googlesource.gerrit.plugins.github.git.PullRequestImportType; import com.googlesource.gerrit.plugins.github.git.PullRequestImporter; import com.googlesource.gerrit.plugins.github.oauth.GitHubLogin; - import java.io.IOException; import java.util.Map.Entry; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -35,39 +32,37 @@ private Provider<PullRequestImporter> prImportProvider; @Inject - public PullRequestImportController( - final Provider<PullRequestImporter> pullRequestsImporter) { + public PullRequestImportController(final Provider<PullRequestImporter> pullRequestsImporter) { this.prImportProvider = pullRequestsImporter; } @Override - public void doAction(IdentifiedUser user, GitHubLogin hubLogin, - HttpServletRequest req, HttpServletResponse resp, ControllerErrors errors) + public void doAction( + IdentifiedUser user, + GitHubLogin hubLogin, + HttpServletRequest req, + HttpServletResponse resp, + ControllerErrors errors) throws ServletException, IOException { String organisation = req.getParameter("organisation"); PullRequestImporter prImporter = prImportProvider.get(); for (Entry<String, String[]> param : req.getParameterMap().entrySet()) { String name = param.getKey(); - if (name.endsWith(".selected") && param.getValue().length == 1 + if (name.endsWith(".selected") + && param.getValue().length == 1 && param.getValue()[0].equalsIgnoreCase("on")) { - String paramPrefix = - name.substring(0, name.length() - ".selected".length()); + String paramPrefix = name.substring(0, name.length() - ".selected".length()); int idx = Integer.parseInt(req.getParameter(paramPrefix + ".idx")); PullRequestImportType importType = - PullRequestImportType.valueOf(req.getParameter(paramPrefix - + ".type")); - - int pullRequestId = - Integer.parseInt(req.getParameter(paramPrefix + ".id")); - String repoName = - req.getParameter(paramPrefix + ".repo"); + PullRequestImportType.valueOf(req.getParameter(paramPrefix + ".type")); - prImporter.importPullRequest(idx, organisation, repoName, - pullRequestId, importType); + int pullRequestId = Integer.parseInt(req.getParameter(paramPrefix + ".id")); + String repoName = req.getParameter(paramPrefix + ".repo"); + + prImporter.importPullRequest(idx, organisation, repoName, pullRequestId, importType); } } - } }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/PullRequestImportStatusController.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/PullRequestImportStatusController.java index 0a9d2c7..730b29f 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/PullRequestImportStatusController.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/PullRequestImportStatusController.java
@@ -16,12 +16,9 @@ import com.google.gerrit.server.IdentifiedUser; import com.google.inject.Inject; import com.google.inject.Provider; - import com.googlesource.gerrit.plugins.github.git.PullRequestImporter; import com.googlesource.gerrit.plugins.github.oauth.GitHubLogin; - import java.io.IOException; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -38,8 +35,12 @@ } @Override - public void doAction(IdentifiedUser user, GitHubLogin hubLogin, - HttpServletRequest req, HttpServletResponse resp, ControllerErrors errors) + public void doAction( + IdentifiedUser user, + GitHubLogin hubLogin, + HttpServletRequest req, + HttpServletResponse resp, + ControllerErrors errors) throws ServletException, IOException { respondWithJobStatusJson(resp, pullRequestsImporter.get()); }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/PullRequestListController.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/PullRequestListController.java index 3faa6b4..6d0bdcb 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/PullRequestListController.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/PullRequestListController.java
@@ -17,13 +17,13 @@ import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Maps; +import com.google.gerrit.index.query.QueryParseException; +import com.google.gerrit.index.query.QueryProcessor; import com.google.gerrit.reviewdb.client.Project.NameKey; import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.git.GitRepositoryManager; import com.google.gerrit.server.project.ProjectCache; -import com.google.gerrit.server.query.QueryParseException; -import com.google.gerrit.server.query.QueryProcessor; import com.google.gerrit.server.query.change.ChangeData; import com.google.gerrit.server.query.change.ChangeQueryBuilder; import com.google.gerrit.server.query.change.ChangeQueryProcessor; @@ -36,7 +36,16 @@ import com.google.inject.Singleton; import com.googlesource.gerrit.plugins.github.GitHubConfig; import com.googlesource.gerrit.plugins.github.oauth.GitHubLogin; - +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.PrintWriter; +import java.text.SimpleDateFormat; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.lib.Repository; import org.kohsuke.github.GHIssueState; @@ -46,22 +55,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.PrintWriter; -import java.text.SimpleDateFormat; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - @Singleton public class PullRequestListController implements VelocityController { - private static final Logger LOG = LoggerFactory - .getLogger(PullRequestListController.class); + private static final Logger LOG = LoggerFactory.getLogger(PullRequestListController.class); private static final String DATE_FMT = "yyyy-MM-dd HH:mm z"; private final GitHubConfig config; @@ -72,7 +68,8 @@ private final ChangeQueryBuilder changeQuery; @Inject - public PullRequestListController(ProjectCache projectsCache, + public PullRequestListController( + ProjectCache projectsCache, GitRepositoryManager repoMgr, Provider<ReviewDb> schema, GitHubConfig config, @@ -87,8 +84,12 @@ } @Override - public void doAction(IdentifiedUser user, GitHubLogin hubLogin, - HttpServletRequest req, HttpServletResponse resp, ControllerErrors errors) + public void doAction( + IdentifiedUser user, + GitHubLogin hubLogin, + HttpServletRequest req, + HttpServletResponse resp, + ControllerErrors errors) throws ServletException, IOException { try (PrintWriter out = resp.getWriter()) { SimpleDateFormat dateFmt = new SimpleDateFormat(DATE_FMT); @@ -110,11 +111,10 @@ prObj.add("id", new JsonPrimitive(new Integer(pr.getNumber()))); prObj.add("title", new JsonPrimitive(pr.getTitle())); prObj.add("body", new JsonPrimitive(pr.getBody())); - prObj.add("author", new JsonPrimitive(pr.getUser() == null ? "" : pr - .getUser().getLogin())); + prObj.add( + "author", new JsonPrimitive(pr.getUser() == null ? "" : pr.getUser().getLogin())); prObj.add("status", new JsonPrimitive(pr.getState().name())); - prObj.add("date", - new JsonPrimitive(dateFmt.format(pr.getUpdatedAt()))); + prObj.add("date", new JsonPrimitive(dateFmt.format(pr.getUpdatedAt()))); prArray.add(prObj); } @@ -128,28 +128,24 @@ } private Map<String, List<GHPullRequest>> getPullRequests( - GitHubLogin hubLogin, String organisation, String repository) - throws IOException { + GitHubLogin hubLogin, String organisation, String repository) throws IOException { return getPullRequests( - hubLogin, - projectsCache.byName(organisation + "/" - + Strings.nullToEmpty(repository))); + hubLogin, projectsCache.byName(organisation + "/" + Strings.nullToEmpty(repository))); } - private Map<String, List<GHPullRequest>> getPullRequests(GitHubLogin login, - Iterable<NameKey> repos) throws IOException { + private Map<String, List<GHPullRequest>> getPullRequests( + GitHubLogin login, Iterable<NameKey> repos) throws IOException { int numPullRequests = 0; Map<String, List<GHPullRequest>> allPullRequests = Maps.newHashMap(); try (ReviewDb db = schema.get()) { for (NameKey gerritRepoName : repos) { try (Repository gitRepo = repoMgr.openRepository(gerritRepoName)) { String ghRepoName = gerritRepoName.get().split("/")[1]; - Optional<GHRepository> githubRepo = - getGHRepository(login, gerritRepoName); + Optional<GHRepository> githubRepo = getGHRepository(login, gerritRepoName); if (githubRepo.isPresent()) { numPullRequests = - collectPullRequestsFromGitHubRepository(numPullRequests, db, - allPullRequests, gitRepo, ghRepoName, githubRepo); + collectPullRequestsFromGitHubRepository( + numPullRequests, db, allPullRequests, gitRepo, ghRepoName, githubRepo); } } } @@ -157,19 +153,21 @@ } } - private int collectPullRequestsFromGitHubRepository(int numPullRequests, ReviewDb db, - Map<String, List<GHPullRequest>> allPullRequests, Repository gitRepo, - String ghRepoName, Optional<GHRepository> githubRepo) + private int collectPullRequestsFromGitHubRepository( + int numPullRequests, + ReviewDb db, + Map<String, List<GHPullRequest>> allPullRequests, + Repository gitRepo, + String ghRepoName, + Optional<GHRepository> githubRepo) throws IncorrectObjectTypeException, IOException { List<GHPullRequest> repoPullRequests = Lists.newArrayList(); int count = numPullRequests; if (count < config.pullRequestListLimit) { - for (GHPullRequest ghPullRequest : githubRepo.get() - .listPullRequests(GHIssueState.OPEN)) { + for (GHPullRequest ghPullRequest : githubRepo.get().listPullRequests(GHIssueState.OPEN)) { - if (isAnyCommitOfPullRequestToBeImported(db, gitRepo, - ghPullRequest)) { + if (isAnyCommitOfPullRequestToBeImported(db, gitRepo, ghPullRequest)) { repoPullRequests.add(ghPullRequest); count++; } @@ -183,8 +181,8 @@ return count; } - private Optional<GHRepository> getGHRepository(GitHubLogin login, - NameKey gerritRepoName) throws IOException { + private Optional<GHRepository> getGHRepository(GitHubLogin login, NameKey gerritRepoName) + throws IOException { try { return Optional.of(login.getHub().getRepository(gerritRepoName.get())); } catch (FileNotFoundException e) { @@ -193,21 +191,18 @@ } } - private boolean isAnyCommitOfPullRequestToBeImported(ReviewDb db, - Repository gitRepo, GHPullRequest ghPullRequest) + private boolean isAnyCommitOfPullRequestToBeImported( + ReviewDb db, Repository gitRepo, GHPullRequest ghPullRequest) throws IncorrectObjectTypeException, IOException { boolean pullRequestToImport = false; try { - for (GHPullRequestCommitDetail pullRequestCommit : ghPullRequest - .listCommits()) { + for (GHPullRequestCommitDetail pullRequestCommit : ghPullRequest.listCommits()) { pullRequestToImport |= - qp.query(changeQuery.commit(pullRequestCommit.getSha())) - .entities().isEmpty(); + qp.query(changeQuery.commit(pullRequestCommit.getSha())).entities().isEmpty(); } return pullRequestToImport; } catch (OrmException | QueryParseException e) { - LOG.error("Unable to query Gerrit changes for pull-request " - + ghPullRequest.getNumber(), e); + LOG.error("Unable to query Gerrit changes for pull-request " + ghPullRequest.getNumber(), e); return false; } }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/RepositoriesCloneCancelController.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/RepositoriesCloneCancelController.java index 7667eeb..4cb1d7d 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/RepositoriesCloneCancelController.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/RepositoriesCloneCancelController.java
@@ -16,13 +16,10 @@ import com.google.gerrit.server.IdentifiedUser; import com.google.inject.Inject; import com.google.inject.Singleton; - import com.googlesource.gerrit.plugins.github.git.GitImporter; import com.googlesource.gerrit.plugins.github.oauth.GitHubLogin; import com.googlesource.gerrit.plugins.github.oauth.ScopedProvider; - import java.io.IOException; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -38,10 +35,13 @@ } @Override - public void doAction(IdentifiedUser user, GitHubLogin hubLogin, - HttpServletRequest req, HttpServletResponse resp, ControllerErrors errors) + public void doAction( + IdentifiedUser user, + GitHubLogin hubLogin, + HttpServletRequest req, + HttpServletResponse resp, + ControllerErrors errors) throws ServletException, IOException { clonerProvider.get(req).cancel(); } - }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/RepositoriesCloneController.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/RepositoriesCloneController.java index 72e2a91..6177033 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/RepositoriesCloneController.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/RepositoriesCloneController.java
@@ -15,15 +15,12 @@ import com.google.gerrit.server.IdentifiedUser; import com.google.inject.Inject; - import com.googlesource.gerrit.plugins.github.git.GitImporter; import com.googlesource.gerrit.plugins.github.oauth.GitHubLogin; import com.googlesource.gerrit.plugins.github.oauth.ScopedProvider; - import java.io.IOException; import java.util.Map.Entry; import java.util.Set; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -38,10 +35,14 @@ } @Override - public void doAction(IdentifiedUser user, GitHubLogin hubLogin, - HttpServletRequest req, HttpServletResponse resp, - ControllerErrors errorMgr) throws ServletException, IOException { - + public void doAction( + IdentifiedUser user, + GitHubLogin hubLogin, + HttpServletRequest req, + HttpServletResponse resp, + ControllerErrors errorMgr) + throws ServletException, IOException { + GitImporter gitCloner = cloneProvider.get(req); gitCloner.reset(); Set<Entry<String, String[]>> params = req.getParameterMap().entrySet(); @@ -49,29 +50,25 @@ String paramName = param.getKey(); String[] paramValue = param.getValue(); - if (!paramName.startsWith(REPO_PARAM_PREFIX) || paramValue.length != 1 + if (!paramName.startsWith(REPO_PARAM_PREFIX) + || paramValue.length != 1 || paramName.split("_").length != 2) { continue; } String repoIdxString = paramName.split("_")[1]; - if(!Character.isDigit(repoIdxString.charAt(0))) { + if (!Character.isDigit(repoIdxString.charAt(0))) { continue; } - + int repoIdx = Integer.parseInt(repoIdxString); - String organisation = - req.getParameter(REPO_PARAM_PREFIX + repoIdx + "_organisation"); - String repository = - req.getParameter(REPO_PARAM_PREFIX + repoIdx + "_repository"); - String description = - req.getParameter(REPO_PARAM_PREFIX + repoIdx + "_description"); + String organisation = req.getParameter(REPO_PARAM_PREFIX + repoIdx + "_organisation"); + String repository = req.getParameter(REPO_PARAM_PREFIX + repoIdx + "_repository"); + String description = req.getParameter(REPO_PARAM_PREFIX + repoIdx + "_description"); try { - gitCloner.clone(repoIdx, organisation, repository, - description); + gitCloner.clone(repoIdx, organisation, repository, description); } catch (Exception e) { errorMgr.submit(e); } - } } }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/RepositoriesCloneStatusController.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/RepositoriesCloneStatusController.java index e8c2f05..ad823b2 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/RepositoriesCloneStatusController.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/RepositoriesCloneStatusController.java
@@ -16,19 +16,17 @@ import com.google.gerrit.server.IdentifiedUser; import com.google.inject.Inject; import com.google.inject.Singleton; - import com.googlesource.gerrit.plugins.github.git.GitImporter; import com.googlesource.gerrit.plugins.github.oauth.GitHubLogin; import com.googlesource.gerrit.plugins.github.oauth.ScopedProvider; - import java.io.IOException; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Singleton -public class RepositoriesCloneStatusController extends JobStatusController implements VelocityController { +public class RepositoriesCloneStatusController extends JobStatusController + implements VelocityController { private ScopedProvider<GitImporter> clonerProvider; @Inject @@ -37,8 +35,12 @@ } @Override - public void doAction(IdentifiedUser user, GitHubLogin hubLogin, - HttpServletRequest req, HttpServletResponse resp, ControllerErrors errors) + public void doAction( + IdentifiedUser user, + GitHubLogin hubLogin, + HttpServletRequest req, + HttpServletResponse resp, + ControllerErrors errors) throws ServletException, IOException { respondWithJobStatusJson(resp, clonerProvider.get(req)); }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/RepositoriesListController.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/RepositoriesListController.java index 281e3bd..4174c20 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/RepositoriesListController.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/RepositoriesListController.java
@@ -24,7 +24,10 @@ import com.google.inject.Singleton; import com.googlesource.gerrit.plugins.github.GitHubConfig; import com.googlesource.gerrit.plugins.github.oauth.GitHubLogin; - +import java.io.IOException; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.kohsuke.github.GHMyself.RepositoryListFilter; import org.kohsuke.github.GHOrganization; import org.kohsuke.github.GHRepository; @@ -33,36 +36,31 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - @Singleton public class RepositoriesListController implements VelocityController { private static final Logger log = LoggerFactory.getLogger(RepositoriesListController.class); private final ProjectCache projects; private final GitHubConfig config; - @Inject - public RepositoriesListController(final ProjectCache projects, - final GitHubConfig config) { + public RepositoriesListController(final ProjectCache projects, final GitHubConfig config) { this.projects = projects; this.config = config; } @Override - public void doAction(IdentifiedUser user, GitHubLogin hubLogin, - HttpServletRequest req, HttpServletResponse resp, ControllerErrors errors) + public void doAction( + IdentifiedUser user, + GitHubLogin hubLogin, + HttpServletRequest req, + HttpServletResponse resp, + ControllerErrors errors) throws ServletException, IOException { String organisation = req.getParameter("organisation"); JsonArray jsonRepos = new JsonArray(); int numRepos = 0; - PagedIterator<GHRepository> repoIter = - getRepositories(hubLogin, organisation).iterator(); + PagedIterator<GHRepository> repoIter = getRepositories(hubLogin, organisation).iterator(); while (repoIter.hasNext() && numRepos < config.repositoryListLimit) { GHRepository ghRepository = repoIter.next(); @@ -73,27 +71,28 @@ repository.add("name", new JsonPrimitive(ghRepository.getName())); repository.add("organisation", new JsonPrimitive(organisation)); repository.add( - "description", - new JsonPrimitive(Strings.nullToEmpty(ghRepository - .getDescription()))); - repository - .add("private", new JsonPrimitive(new Boolean(ghRepository.isPrivate()))); + "description", new JsonPrimitive(Strings.nullToEmpty(ghRepository.getDescription()))); + repository.add("private", new JsonPrimitive(new Boolean(ghRepository.isPrivate()))); jsonRepos.add(repository); numRepos++; } } else { - log.warn("Skipping repository {} because user {} has no push/pull access to it", - ghRepository.getName(), user.getUserName()); + log.warn( + "Skipping repository {} because user {} has no push/pull access to it", + ghRepository.getName(), + user.getUserName()); } } resp.getWriter().println(jsonRepos.toString()); } - private PagedIterable<GHRepository> getRepositories(GitHubLogin hubLogin, - String organisation) throws IOException { + private PagedIterable<GHRepository> getRepositories(GitHubLogin hubLogin, String organisation) + throws IOException { if (organisation.equals(hubLogin.getMyself().getLogin())) { - return hubLogin.getMyself().listRepositories(config.repositoryListPageSize, RepositoryListFilter.OWNER); + return hubLogin + .getMyself() + .listRepositories(config.repositoryListPageSize, RepositoryListFilter.OWNER); } GHOrganization ghOrganisation = hubLogin.getMyself().getAllOrganizations().byLogin(organisation);
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/VelocityController.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/VelocityController.java index 12da108..83c130b 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/VelocityController.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/VelocityController.java
@@ -14,20 +14,19 @@ package com.googlesource.gerrit.plugins.github.wizard; import com.google.gerrit.server.IdentifiedUser; - import com.googlesource.gerrit.plugins.github.oauth.GitHubLogin; - import java.io.IOException; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - - public interface VelocityController { - void doAction(IdentifiedUser user, GitHubLogin hubLogin, - HttpServletRequest req, HttpServletResponse resp, ControllerErrors errors) + void doAction( + IdentifiedUser user, + GitHubLogin hubLogin, + HttpServletRequest req, + HttpServletResponse resp, + ControllerErrors errors) throws ServletException, IOException; }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/VelocityControllerServlet.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/VelocityControllerServlet.java index bd908e7..845399e 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/VelocityControllerServlet.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/VelocityControllerServlet.java
@@ -18,29 +18,24 @@ import com.google.inject.Injector; import com.google.inject.Provider; import com.google.inject.Singleton; - import com.googlesource.gerrit.plugins.github.GitHubConfig; import com.googlesource.gerrit.plugins.github.GitHubConfig.NextPage; import com.googlesource.gerrit.plugins.github.oauth.GitHubLogin; import com.googlesource.gerrit.plugins.github.oauth.ScopedProvider; - -import org.apache.http.HttpStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.IOException; - import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.http.HttpStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @Singleton public class VelocityControllerServlet extends HttpServlet { private static final long serialVersionUID = 5565594120346641704L; - private static final Logger log = LoggerFactory - .getLogger(VelocityControllerServlet.class); + private static final Logger log = LoggerFactory.getLogger(VelocityControllerServlet.class); private static final String CONTROLLER_PACKAGE = VelocityControllerServlet.class.getPackage().getName(); private final ScopedProvider<GitHubLogin> loginProvider; @@ -50,9 +45,12 @@ private final GitHubConfig githubConfig; @Inject - public VelocityControllerServlet(final ScopedProvider<GitHubLogin> loginProvider, - Provider<IdentifiedUser> userProvider, final Injector injector, - Provider<ControllerErrors> errorsProvider, GitHubConfig githubConfig) { + public VelocityControllerServlet( + final ScopedProvider<GitHubLogin> loginProvider, + Provider<IdentifiedUser> userProvider, + final Injector injector, + Provider<ControllerErrors> errorsProvider, + GitHubConfig githubConfig) { this.loginProvider = loginProvider; this.userProvider = userProvider; this.injector = injector; @@ -70,12 +68,11 @@ try { Class<? extends VelocityController> controllerClass = - (Class<? extends VelocityController>) Class - .forName(CONTROLLER_PACKAGE + "." + controllerName + "Controller"); + (Class<? extends VelocityController>) + Class.forName(CONTROLLER_PACKAGE + "." + controllerName + "Controller"); controller = injector.getInstance(controllerClass); } catch (ClassNotFoundException e) { - log.debug("Cannot find any controller for servlet " - + req.getServletPath()); + log.debug("Cannot find any controller for servlet " + req.getServletPath()); redirectToNextStep(req, resp); return; } @@ -85,8 +82,7 @@ WrappedResponse wrappedResp = new WrappedResponse(resp); controller.doAction(user, hubLogin, req, wrappedResp, errorsProvider.get()); - if (wrappedResp.getStatus() == 0 || - wrappedResp.getStatus() == HttpStatus.SC_OK) { + if (wrappedResp.getStatus() == 0 || wrappedResp.getStatus() == HttpStatus.SC_OK) { redirectToNextStep(req, resp); } } @@ -100,8 +96,7 @@ String[] controllerNameParts = reqServletName.split("-"); for (String namePart : controllerNameParts) { - controllerName.append(Character.toUpperCase(namePart.charAt(0)) - + namePart.substring(1)); + controllerName.append(Character.toUpperCase(namePart.charAt(0)) + namePart.substring(1)); } return controllerName.toString(); } @@ -120,8 +115,8 @@ return string; } - private void redirectToNextStep(HttpServletRequest req, - HttpServletResponse resp) throws IOException, ServletException { + private void redirectToNextStep(HttpServletRequest req, HttpServletResponse resp) + throws IOException, ServletException { String sourceUri = req.getPathInfo(); int pathPos = sourceUri.lastIndexOf('/') + 1; String sourcePage = sourceUri.substring(pathPos); @@ -144,7 +139,6 @@ } private String nextPageURL(String sourcePath, NextPage nextPage) { - return nextPage.uri.startsWith("/") ? nextPage.uri - : sourcePath + nextPage.uri; + return nextPage.uri.startsWith("/") ? nextPage.uri : sourcePath + nextPage.uri; } }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/WrappedResponse.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/WrappedResponse.java index 89fb9a8..013a890 100644 --- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/WrappedResponse.java +++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/wizard/WrappedResponse.java
@@ -21,5 +21,4 @@ public WrappedResponse(HttpServletResponse response) { super(response); } - }
diff --git a/pom.xml b/pom.xml index 4ae3dcf..3ce9c3d 100644 --- a/pom.xml +++ b/pom.xml
@@ -18,7 +18,7 @@ <modelVersion>4.0.0</modelVersion> <groupId>com.googlesource.gerrit.plugins.github</groupId> <artifactId>github-parent</artifactId> - <version>2.14-SNAPSHOT</version> + <version>2.15-rc3</version> <name>Gerrit Code Review - GitHub integration</name> <url>http://www.gerritforge.com</url> <packaging>pom</packaging>