]> source.dussan.org Git - gitblit.git/commitdiff
Fairly complete json rpc interface to view/control Gitblit data objects.
authorJames Moger <james.moger@gitblit.com>
Sun, 2 Oct 2011 19:37:24 +0000 (15:37 -0400)
committerJames Moger <james.moger@gitblit.com>
Sun, 2 Oct 2011 19:37:24 +0000 (15:37 -0400)
12 files changed:
src/com/gitblit/Constants.java
src/com/gitblit/FederationPullExecutor.java
src/com/gitblit/GitBlit.java
src/com/gitblit/GitBlitException.java
src/com/gitblit/JsonServlet.java
src/com/gitblit/RpcServlet.java
src/com/gitblit/models/FederationSet.java [new file with mode: 0644]
src/com/gitblit/utils/FederationUtils.java
src/com/gitblit/utils/JsonUtils.java
src/com/gitblit/utils/RpcUtils.java
tests/com/gitblit/tests/FederationTests.java
tests/com/gitblit/tests/RpcTests.java

index 3862a9db1e309eca2dd1e94177b811b96d2a74da..5b4b0b6ab2c66c44ae1caee723a2f639c16a0152 100644 (file)
@@ -52,7 +52,7 @@ public class Constants {
        public static final String SYNDICATION_PATH = "/feed/";\r
 \r
        public static final String FEDERATION_PATH = "/federation/";\r
-       \r
+\r
        public static final String RPC_PATH = "/rpc/";\r
 \r
        public static final String BORDER = "***********************************************************";\r
@@ -202,8 +202,10 @@ public class Constants {
         */\r
        public static enum RpcRequest {\r
                LIST_REPOSITORIES, CREATE_REPOSITORY, EDIT_REPOSITORY, DELETE_REPOSITORY,\r
-               LIST_USERS, CREATE_USER, EDIT_USER, DELETE_USER;\r
-               \r
+               LIST_USERS, CREATE_USER, EDIT_USER, DELETE_USER, LIST_REPOSITORY_MEMBERS,\r
+               SET_REPOSITORY_MEMBERS, LIST_FEDERATION_REGISTRATIONS, LIST_FEDERATION_RESULTS,\r
+               LIST_FEDERATION_PROPOSALS, LIST_FEDERATION_SETS;\r
+\r
                public static RpcRequest fromName(String name) {\r
                        for (RpcRequest type : values()) {\r
                                if (type.name().equalsIgnoreCase(name)) {\r
@@ -212,11 +214,11 @@ public class Constants {
                        }\r
                        return LIST_REPOSITORIES;\r
                }\r
-               \r
+\r
                public boolean exceeds(RpcRequest type) {\r
                        return this.ordinal() > type.ordinal();\r
                }\r
-               \r
+\r
                @Override\r
                public String toString() {\r
                        return name();\r
index ef089d037a43b39b3c8afd51069c3fe653051251..b190e7b589d89b5651b84f5cbdc1523856fda61e 100644 (file)
@@ -19,6 +19,7 @@ import static org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
 \r
 import java.io.File;\r
 import java.io.FileOutputStream;\r
+import java.io.IOException;\r
 import java.net.InetAddress;\r
 import java.text.MessageFormat;\r
 import java.util.ArrayList;\r
@@ -43,6 +44,7 @@ import org.slf4j.LoggerFactory;
 \r
 import com.gitblit.Constants.FederationPullStatus;\r
 import com.gitblit.Constants.FederationStrategy;\r
+import com.gitblit.GitBlitException.ForbiddenException;\r
 import com.gitblit.models.FederationModel;\r
 import com.gitblit.models.RepositoryModel;\r
 import com.gitblit.models.UserModel;\r
@@ -81,8 +83,8 @@ public class FederationPullExecutor implements Runnable {
         * \r
         * @param registrations\r
         * @param isDaemon\r
-        *            if true, registrations are rescheduled in perpetuity. if false,\r
-        *            the federation pull operation is executed once.\r
+        *            if true, registrations are rescheduled in perpetuity. if\r
+        *            false, the federation pull operation is executed once.\r
         */\r
        public FederationPullExecutor(List<FederationModel> registrations, boolean isDaemon) {\r
                this.registrations = registrations;\r
@@ -169,7 +171,7 @@ public class FederationPullExecutor implements Runnable {
                        } else {\r
                                repositoryName = registrationFolder + "/" + repository.name;\r
                        }\r
-                       \r
+\r
                        if (registration.bare) {\r
                                // bare repository, ensure .git suffix\r
                                if (!repositoryName.toLowerCase().endsWith(DOT_GIT_EXT)) {\r
@@ -178,7 +180,8 @@ public class FederationPullExecutor implements Runnable {
                        } else {\r
                                // normal repository, strip .git suffix\r
                                if (repositoryName.toLowerCase().endsWith(DOT_GIT_EXT)) {\r
-                                       repositoryName = repositoryName.substring(0, repositoryName.indexOf(DOT_GIT_EXT));\r
+                                       repositoryName = repositoryName.substring(0,\r
+                                                       repositoryName.indexOf(DOT_GIT_EXT));\r
                                }\r
                        }\r
 \r
@@ -190,7 +193,8 @@ public class FederationPullExecutor implements Runnable {
                                StoredConfig config = existingRepository.getConfig();\r
                                config.load();\r
                                String origin = config.getString("remote", "origin", "url");\r
-                               RevCommit commit = JGitUtils.getCommit(existingRepository, "refs/remotes/origin/master");\r
+                               RevCommit commit = JGitUtils.getCommit(existingRepository,\r
+                                               "refs/remotes/origin/master");\r
                                if (commit != null) {\r
                                        fetchHead = commit.getName();\r
                                }\r
@@ -209,7 +213,7 @@ public class FederationPullExecutor implements Runnable {
                                        Constants.FEDERATION_USER, registration.token);\r
                        logger.info(MessageFormat.format("Pulling federated repository {0} from {1} @ {2}",\r
                                        repository.name, registration.name, registration.url));\r
-                                               \r
+\r
                        CloneResult result = JGitUtils.cloneRepository(registrationFolderFile, repository.name,\r
                                        cloneUrl, registration.bare, credentials);\r
                        Repository r = GitBlit.self().getRepository(repositoryName);\r
@@ -255,7 +259,7 @@ public class FederationPullExecutor implements Runnable {
                                // preserve local settings\r
                                repository.isFrozen = rm.isFrozen;\r
                                repository.federationStrategy = rm.federationStrategy;\r
-                               \r
+\r
                                // merge federation sets\r
                                Set<String> federationSets = new HashSet<String>();\r
                                if (rm.federationSets != null) {\r
@@ -317,13 +321,12 @@ public class FederationPullExecutor implements Runnable {
                                        }\r
                                }\r
                        }\r
-               } catch (Exception e) {\r
-                       // a 403 error code is normal for a PULL_REPOSITORIES token\r
-                       if (!e.getMessage().contains("403")) {\r
-                               logger.warn(MessageFormat.format(\r
-                                               "Failed to retrieve USERS from federated gitblit ({0} @ {1})",\r
-                                               registration.name, registration.url), e);\r
-                       }\r
+               } catch (ForbiddenException e) {\r
+                       // ignore forbidden exceptions\r
+               } catch (IOException e) {\r
+                       logger.warn(MessageFormat.format(\r
+                                       "Failed to retrieve USERS from federated gitblit ({0} @ {1})",\r
+                                       registration.name, registration.url), e);\r
                }\r
 \r
                try {\r
@@ -337,13 +340,12 @@ public class FederationPullExecutor implements Runnable {
                                properties.store(os, null);\r
                                os.close();\r
                        }\r
-               } catch (Exception e) {\r
-                       // a 403 error code is normal for a PULL_REPOSITORIES token\r
-                       if (!e.getMessage().contains("403")) {\r
-                               logger.warn(MessageFormat.format(\r
-                                               "Failed to retrieve SETTINGS from federated gitblit ({0} @ {1})",\r
-                                               registration.name, registration.url), e);\r
-                       }\r
+               } catch (ForbiddenException e) {\r
+                       // ignore forbidden exceptions\r
+               } catch (IOException e) {\r
+                       logger.warn(MessageFormat.format(\r
+                                       "Failed to retrieve SETTINGS from federated gitblit ({0} @ {1})",\r
+                                       registration.name, registration.url), e);\r
                }\r
        }\r
 \r
index e86fcf6036edf491bb94ef16783513ffe2e4d83e..73ec29e01538e515e3c892f4227ccaba6a3dee87 100644 (file)
@@ -59,6 +59,7 @@ import com.gitblit.Constants.FederationStrategy;
 import com.gitblit.Constants.FederationToken;\r
 import com.gitblit.models.FederationModel;\r
 import com.gitblit.models.FederationProposal;\r
+import com.gitblit.models.FederationSet;\r
 import com.gitblit.models.RepositoryModel;\r
 import com.gitblit.models.UserModel;\r
 import com.gitblit.utils.FederationUtils;\r
@@ -873,6 +874,29 @@ public class GitBlit implements ServletContextListener {
                return null;\r
        }\r
 \r
+       /**\r
+        * Returns the list of federation sets.\r
+        * \r
+        * @return list of federation sets\r
+        */\r
+       public List<FederationSet> getFederationSets(String gitblitUrl) {\r
+               List<FederationSet> list = new ArrayList<FederationSet>();\r
+               // generate standard tokens\r
+               for (FederationToken type : FederationToken.values()) {\r
+                       FederationSet fset = new FederationSet(type.toString(), type, getFederationToken(type));\r
+                       fset.repositories = getRepositories(gitblitUrl, fset.token);\r
+                       list.add(fset);\r
+               }\r
+               // generate tokens for federation sets\r
+               for (String set : settings.getStrings(Keys.federation.sets)) {\r
+                       FederationSet fset = new FederationSet(set, FederationToken.REPOSITORIES,\r
+                                       getFederationToken(set));\r
+                       fset.repositories = getRepositories(gitblitUrl, fset.token);\r
+                       list.add(fset);\r
+               }\r
+               return list;\r
+       }\r
+\r
        /**\r
         * Returns the list of possible federation tokens for this Gitblit instance.\r
         * \r
@@ -1025,7 +1049,8 @@ public class GitBlit implements ServletContextListener {
                        });\r
                        for (File file : files) {\r
                                String json = com.gitblit.utils.FileUtils.readContent(file, null);\r
-                               FederationProposal proposal = JsonUtils.fromJsonString(json, FederationProposal.class);\r
+                               FederationProposal proposal = JsonUtils.fromJsonString(json,\r
+                                               FederationProposal.class);\r
                                list.add(proposal);\r
                        }\r
                }\r
index 032e41f7e2c333c336f6b00a98dbc11547adc1c3..af32003a45c2f0ff1a26f75cbaa65ff5e6009408 100644 (file)
  */\r
 package com.gitblit;\r
 \r
+import java.io.IOException;\r
+\r
 /**\r
  * GitBlitException is a marginally useful class. :)\r
  * \r
  * @author James Moger\r
  * \r
  */\r
-public class GitBlitException extends Exception {\r
+public class GitBlitException extends IOException {\r
 \r
        private static final long serialVersionUID = 1L;\r
 \r
        public GitBlitException(String message) {\r
                super(message);\r
        }\r
+\r
+       /**\r
+        * Exception to indicate that the client should prompt for credentials\r
+        * because the requested action requires authentication.\r
+        */\r
+       public static class UnauthorizedException extends GitBlitException {\r
+\r
+               private static final long serialVersionUID = 1L;\r
+\r
+               public UnauthorizedException(String message) {\r
+                       super(message);\r
+               }\r
+       }\r
+\r
+       /**\r
+        * Exception to indicate that the requested action can not be executed by\r
+        * the specified user.\r
+        */\r
+       public static class ForbiddenException extends GitBlitException {\r
+\r
+               private static final long serialVersionUID = 1L;\r
+\r
+               public ForbiddenException(String message) {\r
+                       super(message);\r
+               }\r
+       }\r
 }\r
index b1d1053d072edb82196ba2f7ddd56e341a0bf8c7..ad1d67b630cb843ce332cff3f4cc7f730a2a442a 100644 (file)
@@ -17,6 +17,7 @@ package com.gitblit;
 \r
 import java.io.BufferedReader;\r
 import java.io.IOException;\r
+import java.lang.reflect.Type;\r
 import java.text.MessageFormat;\r
 \r
 import javax.servlet.ServletException;\r
@@ -27,6 +28,7 @@ import javax.servlet.http.HttpServletResponse;
 import org.slf4j.Logger;\r
 import org.slf4j.LoggerFactory;\r
 \r
+import com.gitblit.utils.StringUtils;\r
 import com.google.gson.Gson;\r
 import com.google.gson.GsonBuilder;\r
 \r
@@ -72,6 +74,30 @@ public abstract class JsonServlet extends HttpServlet {
 \r
        protected <X> X deserialize(HttpServletRequest request, HttpServletResponse response,\r
                        Class<X> clazz) throws IOException {\r
+               String json = readJson(request, response);\r
+               if (StringUtils.isEmpty(json)) {\r
+                       return null;\r
+               }\r
+\r
+               Gson gson = new Gson();\r
+               X object = gson.fromJson(json.toString(), clazz);\r
+               return object;\r
+       }\r
+\r
+       protected <X> X deserialize(HttpServletRequest request, HttpServletResponse response, Type type)\r
+                       throws IOException {\r
+               String json = readJson(request, response);\r
+               if (StringUtils.isEmpty(json)) {\r
+                       return null;\r
+               }\r
+\r
+               Gson gson = new Gson();\r
+               X object = gson.fromJson(json.toString(), type);\r
+               return object;\r
+       }\r
+\r
+       private String readJson(HttpServletRequest request, HttpServletResponse response)\r
+                       throws IOException {\r
                BufferedReader reader = request.getReader();\r
                StringBuilder json = new StringBuilder();\r
                String line = null;\r
@@ -86,10 +112,7 @@ public abstract class JsonServlet extends HttpServlet {
                        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);\r
                        return null;\r
                }\r
-\r
-               Gson gson = new Gson();\r
-               X object = gson.fromJson(json.toString(), clazz);\r
-               return object;\r
+               return json.toString();\r
        }\r
 \r
        protected void serialize(HttpServletResponse response, Object o) throws IOException {\r
index 9d26ee031bd3ba6eb8eec4b3739db662b4070f95..4dee31901bf6e4fc87de1a1efe747d6355b4e5dc 100644 (file)
@@ -18,6 +18,7 @@ package com.gitblit;
 import java.io.IOException;\r
 import java.text.MessageFormat;\r
 import java.util.ArrayList;\r
+import java.util.Collection;\r
 import java.util.HashMap;\r
 import java.util.List;\r
 import java.util.Map;\r
@@ -30,6 +31,7 @@ import com.gitblit.Constants.RpcRequest;
 import com.gitblit.models.RepositoryModel;\r
 import com.gitblit.models.UserModel;\r
 import com.gitblit.utils.HttpUtils;\r
+import com.gitblit.utils.RpcUtils;\r
 \r
 /**\r
  * Handles remote procedure calls.\r
@@ -57,6 +59,7 @@ public class RpcServlet extends JsonServlet {
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)\r
                        throws ServletException, IOException {\r
                RpcRequest reqType = RpcRequest.fromName(request.getParameter("req"));\r
+               String objectName = request.getParameter("name");\r
                logger.info(MessageFormat.format("Rpc {0} request from {1}", reqType,\r
                                request.getRemoteAddr()));\r
 \r
@@ -88,6 +91,78 @@ public class RpcServlet extends JsonServlet {
                                users.add(GitBlit.self().getUserModel(name));\r
                        }\r
                        result = users;\r
+               } else if (RpcRequest.CREATE_REPOSITORY.equals(reqType)) {\r
+                       // create repository\r
+                       RepositoryModel model = deserialize(request, response, RepositoryModel.class);\r
+                       GitBlit.self().updateRepositoryModel(model.name, model, true);\r
+               } else if (RpcRequest.EDIT_REPOSITORY.equals(reqType)) {\r
+                       // edit repository\r
+                       RepositoryModel model = deserialize(request, response, RepositoryModel.class);\r
+                       // name parameter specifies original repository name in event of\r
+                       // rename\r
+                       String repoName = objectName;\r
+                       if (repoName == null) {\r
+                               repoName = model.name;\r
+                       }\r
+                       GitBlit.self().updateRepositoryModel(repoName, model, false);\r
+               } else if (RpcRequest.DELETE_REPOSITORY.equals(reqType)) {\r
+                       // delete repository\r
+                       RepositoryModel model = deserialize(request, response, RepositoryModel.class);\r
+                       GitBlit.self().deleteRepositoryModel(model);\r
+               } else if (RpcRequest.CREATE_USER.equals(reqType)) {\r
+                       // create user\r
+                       UserModel model = deserialize(request, response, UserModel.class);\r
+                       GitBlit.self().updateUserModel(model.username, model, true);\r
+               } else if (RpcRequest.EDIT_USER.equals(reqType)) {\r
+                       // edit user\r
+                       UserModel model = deserialize(request, response, UserModel.class);\r
+                       // name parameter specifies original user name in event of rename\r
+                       String username = objectName;\r
+                       if (username == null) {\r
+                               username = model.username;\r
+                       }\r
+                       GitBlit.self().updateUserModel(username, model, false);\r
+               } else if (RpcRequest.DELETE_USER.equals(reqType)) {\r
+                       // delete user\r
+                       UserModel model = deserialize(request, response, UserModel.class);\r
+                       GitBlit.self().deleteUser(model.username);\r
+               } else if (RpcRequest.LIST_REPOSITORY_MEMBERS.equals(reqType)) {\r
+                       // get repository members\r
+                       RepositoryModel model = GitBlit.self().getRepositoryModel(objectName);\r
+                       result = GitBlit.self().getRepositoryUsers(model);\r
+               } else if (RpcRequest.SET_REPOSITORY_MEMBERS.equals(reqType)) {\r
+                       // update repository access list\r
+                       RepositoryModel model = GitBlit.self().getRepositoryModel(objectName);\r
+                       Collection<String> names = deserialize(request, response, RpcUtils.NAMES_TYPE);\r
+                       List<String> users = new ArrayList<String>(names);\r
+                       if (!GitBlit.self().setRepositoryUsers(model, users)) {\r
+                               response.setStatus(HttpServletResponse.SC_BAD_REQUEST);\r
+                       }\r
+               } else if (RpcRequest.LIST_FEDERATION_REGISTRATIONS.equals(reqType)) {\r
+                       // return the list of federation registrations\r
+                       result = GitBlit.self().getFederationRegistrations();\r
+               } else if (RpcRequest.LIST_FEDERATION_RESULTS.equals(reqType)) {\r
+                       // return the list of federation result registrations\r
+                       if (GitBlit.canFederate()) {\r
+                               result = GitBlit.self().getFederationResultRegistrations();\r
+                       } else {\r
+                               response.sendError(HttpServletResponse.SC_FORBIDDEN);\r
+                       }\r
+               } else if (RpcRequest.LIST_FEDERATION_PROPOSALS.equals(reqType)) {\r
+                       // return the list of federation proposals\r
+                       if (GitBlit.canFederate()) {\r
+                               result = GitBlit.self().getPendingFederationProposals();\r
+                       } else {\r
+                               response.sendError(HttpServletResponse.SC_FORBIDDEN);\r
+                       }\r
+               } else if (RpcRequest.LIST_FEDERATION_SETS.equals(reqType)) {\r
+                       // return the list of federation sets\r
+                       if (GitBlit.canFederate()) {\r
+                               String gitblitUrl = HttpUtils.getGitblitURL(request);\r
+                               result = GitBlit.self().getFederationSets(gitblitUrl);\r
+                       } else {\r
+                               response.sendError(HttpServletResponse.SC_FORBIDDEN);\r
+                       }\r
                }\r
 \r
                // send the result of the request\r
diff --git a/src/com/gitblit/models/FederationSet.java b/src/com/gitblit/models/FederationSet.java
new file mode 100644 (file)
index 0000000..357689c
--- /dev/null
@@ -0,0 +1,58 @@
+/*\r
+ * Copyright 2011 gitblit.com.\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *     http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package com.gitblit.models;\r
+\r
+import java.io.Serializable;\r
+import java.util.Map;\r
+\r
+import com.gitblit.Constants.FederationToken;\r
+\r
+/**\r
+ * Represents a group of repositories.\r
+ */\r
+public class FederationSet implements Serializable {\r
+\r
+       private static final long serialVersionUID = 1L;\r
+\r
+       public String name;\r
+\r
+       public String token;\r
+\r
+       public FederationToken tokenType;\r
+\r
+       public Map<String, RepositoryModel> repositories;\r
+\r
+       /**\r
+        * The constructor for a federation set.\r
+        * \r
+        * @param name\r
+        *            the name of this federation set\r
+        * @param tokenType\r
+        *            the type of token of this federation set\r
+        * @param token\r
+        *            the federation token\r
+        */\r
+       public FederationSet(String name, FederationToken tokenType, String token) {\r
+               this.name = name;\r
+               this.tokenType = tokenType;\r
+               this.token = token;\r
+       }\r
+\r
+       @Override\r
+       public String toString() {\r
+               return "Federation Set (" + name + ")";\r
+       }\r
+}\r
index d04a7a3102faf1cb83beaae4bff4256dafdb1310..324aa67e7368431de1f7ef64322ce71b836b9e4b 100644 (file)
@@ -49,16 +49,13 @@ import com.google.gson.reflect.TypeToken;
  */\r
 public class FederationUtils {\r
 \r
-       public static final Type REPOSITORIES_TYPE = new TypeToken<Map<String, RepositoryModel>>() {\r
+       private static final Type REPOSITORIES_TYPE = new TypeToken<Map<String, RepositoryModel>>() {\r
        }.getType();\r
 \r
-       public static final Type SETTINGS_TYPE = new TypeToken<Map<String, String>>() {\r
+       private static final Type SETTINGS_TYPE = new TypeToken<Map<String, String>>() {\r
        }.getType();\r
 \r
-       public static final Type USERS_TYPE = new TypeToken<Collection<UserModel>>() {\r
-       }.getType();\r
-\r
-       public static final Type RESULTS_TYPE = new TypeToken<List<FederationModel>>() {\r
+       private static final Type USERS_TYPE = new TypeToken<Collection<UserModel>>() {\r
        }.getType();\r
 \r
        private static final Logger LOGGER = LoggerFactory.getLogger(FederationUtils.class);\r
@@ -276,10 +273,11 @@ public class FederationUtils {
         * @return a collection of UserModel objects\r
         * @throws Exception\r
         */\r
-       public static Collection<UserModel> getUsers(FederationModel registration) throws Exception {\r
+       public static List<UserModel> getUsers(FederationModel registration) throws Exception {\r
                String url = asLink(registration.url, registration.token, FederationRequest.PULL_USERS);\r
                Collection<UserModel> models = JsonUtils.retrieveJson(url, USERS_TYPE);\r
-               return models;\r
+               List<UserModel> list = new ArrayList<UserModel>(models);\r
+               return list;\r
        }\r
 \r
        /**\r
index a697b7a50b53e09a829a08635f0143250276bc14..1edfc583ff22a79506b3d5ea9f83516429e61cb0 100644 (file)
@@ -16,6 +16,7 @@
 package com.gitblit.utils;\r
 \r
 import java.io.BufferedReader;\r
+import java.io.IOException;\r
 import java.io.InputStream;\r
 import java.io.InputStreamReader;\r
 import java.io.OutputStream;\r
@@ -36,6 +37,10 @@ import javax.net.ssl.SSLSession;
 import javax.net.ssl.TrustManager;\r
 import javax.net.ssl.X509TrustManager;\r
 \r
+import org.eclipse.jgit.util.Base64;\r
+\r
+import com.gitblit.GitBlitException.ForbiddenException;\r
+import com.gitblit.GitBlitException.UnauthorizedException;\r
 import com.gitblit.models.RepositoryModel;\r
 import com.gitblit.models.UserModel;\r
 import com.google.gson.Gson;\r
@@ -43,7 +48,7 @@ import com.google.gson.GsonBuilder;
 import com.google.gson.reflect.TypeToken;\r
 \r
 /**\r
- * Utility methods for gson calls to a Gitblit server.\r
+ * Utility methods for json calls to a Gitblit server.\r
  * \r
  * @author James Moger\r
  * \r
@@ -98,7 +103,7 @@ public class JsonUtils {
                Gson gson = new Gson();\r
                return gson.fromJson(json, clazz);\r
        }\r
-       \r
+\r
        /**\r
         * Convert a json string to an object of the specified type.\r
         * \r
@@ -116,11 +121,27 @@ public class JsonUtils {
         * \r
         * @param url\r
         * @param type\r
-        * @return\r
-        * @throws Exception\r
+        * @return the deserialized object\r
+        * @throws {@link IOException}\r
         */\r
-       public static <X> X retrieveJson(String url, Type type) throws Exception {\r
-               String json = retrieveJsonString(url);\r
+       public static <X> X retrieveJson(String url, Type type) throws IOException,\r
+                       UnauthorizedException {\r
+               return retrieveJson(url, type, null, null);\r
+       }\r
+\r
+       /**\r
+        * Reads a gson object from the specified url.\r
+        * \r
+        * @param url\r
+        * @param type\r
+        * @param username\r
+        * @param password\r
+        * @return the deserialized object\r
+        * @throws {@link IOException}\r
+        */\r
+       public static <X> X retrieveJson(String url, Type type, String username, char[] password)\r
+                       throws IOException {\r
+               String json = retrieveJsonString(url, username, password);\r
                if (StringUtils.isEmpty(json)) {\r
                        return null;\r
                }\r
@@ -133,29 +154,42 @@ public class JsonUtils {
         * \r
         * @param url\r
         * @return the JSON message as a string\r
-        * @throws Exception\r
+        * @throws {@link IOException}\r
         */\r
-       public static String retrieveJsonString(String url) throws Exception {\r
-               URL urlObject = new URL(url);\r
-               URLConnection conn = urlObject.openConnection();\r
-               conn.setRequestProperty("Accept-Charset", CHARSET);\r
-               conn.setUseCaches(false);\r
-               conn.setDoInput(true);\r
-               if (conn instanceof HttpsURLConnection) {\r
-                       HttpsURLConnection secureConn = (HttpsURLConnection) conn;\r
-                       secureConn.setSSLSocketFactory(SSL_CONTEXT.getSocketFactory());\r
-                       secureConn.setHostnameVerifier(HOSTNAME_VERIFIER);\r
-               }\r
-               InputStream is = conn.getInputStream();\r
-               BufferedReader reader = new BufferedReader(new InputStreamReader(is, CHARSET));\r
-               StringBuilder json = new StringBuilder();\r
-               char[] buffer = new char[4096];\r
-               int len = 0;\r
-               while ((len = reader.read(buffer)) > -1) {\r
-                       json.append(buffer, 0, len);\r
+       public static String retrieveJsonString(String url, String username, char[] password)\r
+                       throws IOException {\r
+               try {\r
+                       URL urlObject = new URL(url);\r
+                       URLConnection conn = urlObject.openConnection();\r
+                       conn.setRequestProperty("Accept-Charset", CHARSET);\r
+                       setAuthorization(conn, username, password);\r
+                       conn.setUseCaches(false);\r
+                       conn.setDoInput(true);\r
+                       if (conn instanceof HttpsURLConnection) {\r
+                               HttpsURLConnection secureConn = (HttpsURLConnection) conn;\r
+                               secureConn.setSSLSocketFactory(SSL_CONTEXT.getSocketFactory());\r
+                               secureConn.setHostnameVerifier(HOSTNAME_VERIFIER);\r
+                       }\r
+                       InputStream is = conn.getInputStream();\r
+                       BufferedReader reader = new BufferedReader(new InputStreamReader(is, CHARSET));\r
+                       StringBuilder json = new StringBuilder();\r
+                       char[] buffer = new char[4096];\r
+                       int len = 0;\r
+                       while ((len = reader.read(buffer)) > -1) {\r
+                               json.append(buffer, 0, len);\r
+                       }\r
+                       is.close();\r
+                       return json.toString();\r
+               } catch (IOException e) {\r
+                       if (e.getMessage().indexOf("401") > -1) {\r
+                               // unauthorized\r
+                               throw new UnauthorizedException(url);\r
+                       } else if (e.getMessage().indexOf("403") > -1) {\r
+                               // requested url is forbidden by the requesting user\r
+                               throw new ForbiddenException(url);\r
+                       }\r
+                       throw e;\r
                }\r
-               is.close();\r
-               return json.toString();\r
        }\r
 \r
        /**\r
@@ -166,29 +200,67 @@ public class JsonUtils {
         * @param json\r
         *            the json message to send\r
         * @return the http request result code\r
-        * @throws Exception\r
+        * @throws {@link IOException}\r
         */\r
-       public static int sendJsonString(String url, String json) throws Exception {\r
-               byte[] jsonBytes = json.getBytes(CHARSET);\r
-               URL urlObject = new URL(url);\r
-               URLConnection conn = urlObject.openConnection();\r
-               conn.setRequestProperty("Content-Type", "text/plain;charset=" + CHARSET);\r
-               conn.setRequestProperty("Content-Length", "" + jsonBytes.length);\r
-               conn.setUseCaches(false);\r
-               conn.setDoOutput(true);\r
-               if (conn instanceof HttpsURLConnection) {\r
-                       HttpsURLConnection secureConn = (HttpsURLConnection) conn;\r
-                       secureConn.setSSLSocketFactory(SSL_CONTEXT.getSocketFactory());\r
-                       secureConn.setHostnameVerifier(HOSTNAME_VERIFIER);\r
-               }\r
+       public static int sendJsonString(String url, String json) throws IOException {\r
+               return sendJsonString(url, json, null, null);\r
+       }\r
 \r
-               // write json body\r
-               OutputStream os = conn.getOutputStream();\r
-               os.write(jsonBytes);\r
-               os.close();\r
+       /**\r
+        * Sends a JSON message.\r
+        * \r
+        * @param url\r
+        *            the url to write to\r
+        * @param json\r
+        *            the json message to send\r
+        * @param username\r
+        * @param password\r
+        * @return the http request result code\r
+        * @throws {@link IOException}\r
+        */\r
+       public static int sendJsonString(String url, String json, String username, char[] password)\r
+                       throws IOException {\r
+               try {\r
+                       byte[] jsonBytes = json.getBytes(CHARSET);\r
+                       URL urlObject = new URL(url);\r
+                       URLConnection conn = urlObject.openConnection();\r
+                       conn.setRequestProperty("Content-Type", "text/plain;charset=" + CHARSET);\r
+                       conn.setRequestProperty("Content-Length", "" + jsonBytes.length);\r
+                       setAuthorization(conn, username, password);\r
+                       conn.setUseCaches(false);\r
+                       conn.setDoOutput(true);\r
+                       if (conn instanceof HttpsURLConnection) {\r
+                               HttpsURLConnection secureConn = (HttpsURLConnection) conn;\r
+                               secureConn.setSSLSocketFactory(SSL_CONTEXT.getSocketFactory());\r
+                               secureConn.setHostnameVerifier(HOSTNAME_VERIFIER);\r
+                       }\r
 \r
-               int status = ((HttpURLConnection) conn).getResponseCode();\r
-               return status;\r
+                       // write json body\r
+                       OutputStream os = conn.getOutputStream();\r
+                       os.write(jsonBytes);\r
+                       os.close();\r
+\r
+                       int status = ((HttpURLConnection) conn).getResponseCode();\r
+                       return status;\r
+               } catch (IOException e) {\r
+                       if (e.getMessage().indexOf("401") > -1) {\r
+                               // unauthorized\r
+                               throw new UnauthorizedException(url);\r
+                       } else if (e.getMessage().indexOf("403") > -1) {\r
+                               // requested url is forbidden by the requesting user\r
+                               throw new ForbiddenException(url);\r
+                       }\r
+                       throw e;\r
+               }\r
+       }\r
+\r
+       private static void setAuthorization(URLConnection conn, String username, char[] password) {\r
+               if (!StringUtils.isEmpty(username) && (password != null && password.length > 0)) {\r
+                       conn.setRequestProperty(\r
+                                       "Authorization",\r
+                                       "Basic "\r
+                                                       + Base64.encodeBytes((username + ":" + new String(password)).getBytes()));\r
+               }\r
        }\r
 \r
        /**\r
index 919c7bb3869b442452309d98febbad623d8569a8..715ecb57c7104fed7bcb75820cdd1b6d513f2695 100644 (file)
  */\r
 package com.gitblit.utils;\r
 \r
+import java.io.IOException;\r
 import java.lang.reflect.Type;\r
+import java.util.ArrayList;\r
 import java.util.Collection;\r
+import java.util.List;\r
 import java.util.Map;\r
 \r
 import com.gitblit.Constants;\r
 import com.gitblit.Constants.RpcRequest;\r
+import com.gitblit.models.FederationModel;\r
+import com.gitblit.models.FederationProposal;\r
+import com.gitblit.models.FederationSet;\r
 import com.gitblit.models.RepositoryModel;\r
 import com.gitblit.models.UserModel;\r
 import com.google.gson.reflect.TypeToken;\r
@@ -33,10 +39,22 @@ import com.google.gson.reflect.TypeToken;
  */\r
 public class RpcUtils {\r
 \r
-       public static final Type REPOSITORIES_TYPE = new TypeToken<Map<String, RepositoryModel>>() {\r
+       public static final Type NAMES_TYPE = new TypeToken<Collection<String>>() {\r
        }.getType();\r
 \r
-       public static final Type USERS_TYPE = new TypeToken<Collection<UserModel>>() {\r
+       private static final Type REPOSITORIES_TYPE = new TypeToken<Map<String, RepositoryModel>>() {\r
+       }.getType();\r
+\r
+       private static final Type USERS_TYPE = new TypeToken<Collection<UserModel>>() {\r
+       }.getType();\r
+\r
+       private static final Type REGISTRATIONS_TYPE = new TypeToken<Collection<FederationModel>>() {\r
+       }.getType();\r
+\r
+       private static final Type PROPOSALS_TYPE = new TypeToken<Collection<FederationProposal>>() {\r
+       }.getType();\r
+\r
+       private static final Type SETS_TYPE = new TypeToken<Collection<FederationSet>>() {\r
        }.getType();\r
 \r
        /**\r
@@ -48,26 +66,45 @@ public class RpcUtils {
         * @return\r
         */\r
        public static String asLink(String remoteURL, RpcRequest req) {\r
+               return asLink(remoteURL, req, null);\r
+       }\r
+\r
+       /**\r
+        * \r
+        * @param remoteURL\r
+        *            the url of the remote gitblit instance\r
+        * @param req\r
+        *            the rpc request type\r
+        * @param name\r
+        *            the name of the actionable object\r
+        * @return\r
+        */\r
+       public static String asLink(String remoteURL, RpcRequest req, String name) {\r
                if (remoteURL.length() > 0 && remoteURL.charAt(remoteURL.length() - 1) == '/') {\r
                        remoteURL = remoteURL.substring(0, remoteURL.length() - 1);\r
                }\r
                if (req == null) {\r
                        req = RpcRequest.LIST_REPOSITORIES;\r
                }\r
-               return remoteURL + Constants.RPC_PATH + "?req=" + req.name().toLowerCase();\r
+               return remoteURL + Constants.RPC_PATH + "?req=" + req.name().toLowerCase()\r
+                               + (name == null ? "" : ("&name=" + name));\r
        }\r
-       \r
+\r
        /**\r
         * Retrieves a map of the repositories at the remote gitblit instance keyed\r
         * by the repository clone url.\r
         * \r
         * @param serverUrl\r
+        * @param account\r
+        * @param password\r
         * @return a map of cloneable repositories\r
-        * @throws Exception\r
+        * @throws IOException\r
         */\r
-       public static Map<String, RepositoryModel> getRepositories(String serverUrl) throws Exception {\r
+       public static Map<String, RepositoryModel> getRepositories(String serverUrl, String account,\r
+                       char[] password) throws IOException {\r
                String url = asLink(serverUrl, RpcRequest.LIST_REPOSITORIES);\r
-               Map<String, RepositoryModel> models = JsonUtils.retrieveJson(url, REPOSITORIES_TYPE);\r
+               Map<String, RepositoryModel> models = JsonUtils.retrieveJson(url, REPOSITORIES_TYPE,\r
+                               account, password);\r
                return models;\r
        }\r
 \r
@@ -75,12 +112,243 @@ public class RpcUtils {
         * Tries to pull the gitblit user accounts from the remote gitblit instance.\r
         * \r
         * @param serverUrl\r
+        * @param account\r
+        * @param password\r
         * @return a collection of UserModel objects\r
-        * @throws Exception\r
+        * @throws IOException\r
         */\r
-       public static Collection<UserModel> getUsers(String serverUrl) throws Exception {\r
+       public static List<UserModel> getUsers(String serverUrl, String account, char[] password)\r
+                       throws IOException {\r
                String url = asLink(serverUrl, RpcRequest.LIST_USERS);\r
-               Collection<UserModel> models = JsonUtils.retrieveJson(url, USERS_TYPE);\r
-               return models;\r
+               Collection<UserModel> models = JsonUtils.retrieveJson(url, USERS_TYPE, account, password);\r
+               List<UserModel> list = new ArrayList<UserModel>(models);\r
+               return list;\r
+       }\r
+\r
+       /**\r
+        * Create a repository on the Gitblit server.\r
+        * \r
+        * @param repository\r
+        * @param serverUrl\r
+        * @param account\r
+        * @param password\r
+        * @return true if the action succeeded\r
+        * @throws IOException\r
+        */\r
+       public static boolean createRepository(RepositoryModel repository, String serverUrl,\r
+                       String account, char[] password) throws IOException {\r
+               return doAction(RpcRequest.CREATE_REPOSITORY, null, repository, serverUrl, account,\r
+                               password);\r
+\r
+       }\r
+\r
+       /**\r
+        * Send a revised version of the repository model to the Gitblit server.\r
+        * \r
+        * @param repository\r
+        * @param serverUrl\r
+        * @param account\r
+        * @param password\r
+        * @return true if the action succeeded\r
+        * @throws IOException\r
+        */\r
+       public static boolean updateRepository(String repositoryName, RepositoryModel repository,\r
+                       String serverUrl, String account, char[] password) throws IOException {\r
+               return doAction(RpcRequest.EDIT_REPOSITORY, repositoryName, repository, serverUrl, account,\r
+                               password);\r
+       }\r
+\r
+       /**\r
+        * Delete a repository from the Gitblit server.\r
+        * \r
+        * @param repository\r
+        * @param serverUrl\r
+        * @param account\r
+        * @param password\r
+        * @return true if the action succeeded\r
+        * @throws IOException\r
+        */\r
+       public static boolean deleteRepository(RepositoryModel repository, String serverUrl,\r
+                       String account, char[] password) throws IOException {\r
+               return doAction(RpcRequest.DELETE_REPOSITORY, null, repository, serverUrl, account,\r
+                               password);\r
+\r
+       }\r
+\r
+       /**\r
+        * Create a user on the Gitblit server.\r
+        * \r
+        * @param user\r
+        * @param serverUrl\r
+        * @param account\r
+        * @param password\r
+        * @return true if the action succeeded\r
+        * @throws IOException\r
+        */\r
+       public static boolean createUser(UserModel user, String serverUrl, String account,\r
+                       char[] password) throws IOException {\r
+               return doAction(RpcRequest.CREATE_USER, null, user, serverUrl, account, password);\r
+\r
+       }\r
+\r
+       /**\r
+        * Send a revised version of the user model to the Gitblit server.\r
+        * \r
+        * @param user\r
+        * @param serverUrl\r
+        * @param account\r
+        * @param password\r
+        * @return true if the action succeeded\r
+        * @throws IOException\r
+        */\r
+       public static boolean updateUser(String username, UserModel user, String serverUrl,\r
+                       String account, char[] password) throws IOException {\r
+               return doAction(RpcRequest.EDIT_USER, username, user, serverUrl, account, password);\r
+\r
+       }\r
+\r
+       /**\r
+        * Deletes a user from the Gitblit server.\r
+        * \r
+        * @param user\r
+        * @param serverUrl\r
+        * @param account\r
+        * @param password\r
+        * @return true if the action succeeded\r
+        * @throws IOException\r
+        */\r
+       public static boolean deleteUser(UserModel user, String serverUrl, String account,\r
+                       char[] password) throws IOException {\r
+               return doAction(RpcRequest.DELETE_USER, null, user, serverUrl, account, password);\r
+       }\r
+\r
+       /**\r
+        * Retrieves the list of users that can access the specified repository.\r
+        * \r
+        * @param repository\r
+        * @param serverUrl\r
+        * @param account\r
+        * @param password\r
+        * @return list of members\r
+        * @throws IOException\r
+        */\r
+       public static List<String> getRepositoryMembers(RepositoryModel repository, String serverUrl,\r
+                       String account, char[] password) throws IOException {\r
+               String url = asLink(serverUrl, RpcRequest.LIST_REPOSITORY_MEMBERS, repository.name);\r
+               Collection<String> list = JsonUtils.retrieveJson(url, NAMES_TYPE, account, password);\r
+               return new ArrayList<String>(list);\r
+       }\r
+\r
+       /**\r
+        * Sets the repository membership list.\r
+        * \r
+        * @param repository\r
+        * @param memberships\r
+        * @param serverUrl\r
+        * @param account\r
+        * @param password\r
+        * @return true if the action succeeded\r
+        * @throws IOException\r
+        */\r
+       public static boolean setRepositoryMembers(RepositoryModel repository,\r
+                       List<String> memberships, String serverUrl, String account, char[] password)\r
+                       throws IOException {\r
+               return doAction(RpcRequest.SET_REPOSITORY_MEMBERS, repository.name, memberships, serverUrl,\r
+                               account, password);\r
+       }\r
+\r
+       /**\r
+        * Retrieves the list of federation registrations. These are the list of\r
+        * registrations that this Gitblit instance is pulling from.\r
+        * \r
+        * @param serverUrl\r
+        * @param account\r
+        * @param password\r
+        * @return a collection of FederationRegistration objects\r
+        * @throws IOException\r
+        */\r
+       public static List<FederationModel> getFederationRegistrations(String serverUrl,\r
+                       String account, char[] password) throws IOException {\r
+               String url = asLink(serverUrl, RpcRequest.LIST_FEDERATION_REGISTRATIONS);\r
+               Collection<FederationModel> registrations = JsonUtils.retrieveJson(url, REGISTRATIONS_TYPE,\r
+                               account, password);\r
+               List<FederationModel> list = new ArrayList<FederationModel>(registrations);\r
+               return list;\r
+       }\r
+\r
+       /**\r
+        * Retrieves the list of federation result registrations. These are the\r
+        * results reported back to this Gitblit instance from a federation client.\r
+        * \r
+        * @param serverUrl\r
+        * @param account\r
+        * @param password\r
+        * @return a collection of FederationRegistration objects\r
+        * @throws IOException\r
+        */\r
+       public static List<FederationModel> getFederationResultRegistrations(String serverUrl,\r
+                       String account, char[] password) throws IOException {\r
+               String url = asLink(serverUrl, RpcRequest.LIST_FEDERATION_RESULTS);\r
+               Collection<FederationModel> registrations = JsonUtils.retrieveJson(url, REGISTRATIONS_TYPE,\r
+                               account, password);\r
+               List<FederationModel> list = new ArrayList<FederationModel>(registrations);\r
+               return list;\r
+       }\r
+       \r
+       /**\r
+        * Retrieves the list of federation proposals.\r
+        * \r
+        * @param serverUrl\r
+        * @param account\r
+        * @param password\r
+        * @return a collection of FederationProposal objects\r
+        * @throws IOException\r
+        */\r
+       public static List<FederationProposal> getFederationProposals(String serverUrl,\r
+                       String account, char[] password) throws IOException {\r
+               String url = asLink(serverUrl, RpcRequest.LIST_FEDERATION_PROPOSALS);\r
+               Collection<FederationProposal> proposals = JsonUtils.retrieveJson(url, PROPOSALS_TYPE,\r
+                               account, password);\r
+               List<FederationProposal> list = new ArrayList<FederationProposal>(proposals);\r
+               return list;\r
+       }\r
+       \r
+       /**\r
+        * Retrieves the list of federation repository sets.\r
+        * \r
+        * @param serverUrl\r
+        * @param account\r
+        * @param password\r
+        * @return a collection of FederationSet objects\r
+        * @throws IOException\r
+        */\r
+       public static List<FederationSet> getFederationSets(String serverUrl,\r
+                       String account, char[] password) throws IOException {\r
+               String url = asLink(serverUrl, RpcRequest.LIST_FEDERATION_SETS);\r
+               Collection<FederationSet> sets = JsonUtils.retrieveJson(url, SETS_TYPE,\r
+                               account, password);\r
+               List<FederationSet> list = new ArrayList<FederationSet>(sets);\r
+               return list;\r
+       }\r
+\r
+       /**\r
+        * Do the specified administrative action on the Gitblit server.\r
+        * \r
+        * @param request\r
+        * @param name\r
+        *            the name of the object (may be null)\r
+        * @param object\r
+        * @param serverUrl\r
+        * @param account\r
+        * @param password\r
+        * @return true if the action succeeded\r
+        * @throws IOException\r
+        */\r
+       protected static boolean doAction(RpcRequest request, String name, Object object,\r
+                       String serverUrl, String account, char[] password) throws IOException {\r
+               String url = asLink(serverUrl, request, name);\r
+               String json = JsonUtils.toJsonString(object);\r
+               int resultCode = JsonUtils.sendJsonString(url, json, account, password);\r
+               return resultCode == 200;\r
        }\r
 }\r
index 8af3167174473a2cf5308a85b993a0a06aad27aa..66bb949c1832b876d0d4a416d18e70e6b7eedf63 100644 (file)
@@ -64,12 +64,6 @@ public class FederationTests extends TestCase {
                Thread.sleep(2500);\r
        }\r
 \r
-       public void testDeserialization() throws Exception {\r
-               String json = "{\"https://localhost:8443/git/a.b.c.orphan.git\":{\"name\":\"a.b.c.orphan.git\",\"description\":\"\",\"owner\":\"\",\"lastChange\":\"Jul 22, 2011 3:15:07 PM\",\"hasCommits\":true,\"showRemoteBranches\":false,\"useTickets\":false,\"useDocs\":false,\"accessRestriction\":\"NONE\",\"isFrozen\":false,\"showReadme\":false,\"isFederated\":false},\"https://localhost:8443/git/test/jgit.git\":{\"name\":\"test/jgit.git\",\"description\":\"\",\"owner\":\"\",\"lastChange\":\"Jul 13, 2011 9:42:33 AM\",\"hasCommits\":true,\"showRemoteBranches\":true,\"useTickets\":false,\"useDocs\":false,\"accessRestriction\":\"NONE\",\"isFrozen\":false,\"showReadme\":false,\"isFederated\":false},\"https://localhost:8443/git/test/helloworld.git\":{\"name\":\"test/helloworld.git\",\"description\":\"\",\"owner\":\"\",\"lastChange\":\"Jul 15, 2008 7:26:48 PM\",\"hasCommits\":true,\"showRemoteBranches\":false,\"useTickets\":false,\"useDocs\":false,\"accessRestriction\":\"NONE\",\"isFrozen\":false,\"showReadme\":false,\"isFederated\":false},\"https://localhost:8443/git/working/ticgit\":{\"name\":\"working/ticgit\",\"description\":\"\",\"owner\":\"\",\"lastChange\":\"Jul 22, 2011 10:35:27 AM\",\"hasCommits\":true,\"showRemoteBranches\":false,\"useTickets\":false,\"useDocs\":false,\"accessRestriction\":\"NONE\",\"isFrozen\":false,\"showReadme\":false,\"isFederated\":false},\"https://localhost:8443/git/ticgit.git\":{\"name\":\"ticgit.git\",\"description\":\"\",\"owner\":\"\",\"lastChange\":\"Jul 22, 2011 10:35:27 AM\",\"hasCommits\":true,\"showRemoteBranches\":true,\"useTickets\":true,\"useDocs\":true,\"accessRestriction\":\"NONE\",\"isFrozen\":false,\"showReadme\":false,\"isFederated\":false},\"https://localhost:8443/git/helloworld.git\":{\"name\":\"helloworld.git\",\"description\":\"\",\"owner\":\"\",\"lastChange\":\"Jul 15, 2008 7:26:48 PM\",\"hasCommits\":true,\"showRemoteBranches\":false,\"useTickets\":false,\"useDocs\":false,\"accessRestriction\":\"NONE\",\"isFrozen\":false,\"showReadme\":false,\"isFederated\":false},\"https://localhost:8443/git/test/helloworld3.git\":{\"name\":\"test/helloworld3.git\",\"description\":\"\",\"owner\":\"\",\"lastChange\":\"Jul 15, 2008 7:26:48 PM\",\"hasCommits\":true,\"showRemoteBranches\":false,\"useTickets\":false,\"useDocs\":false,\"accessRestriction\":\"NONE\",\"isFrozen\":false,\"showReadme\":false,\"isFederated\":false},\"https://localhost:8443/git/test/bluez-gnome.git\":{\"name\":\"test/bluez-gnome.git\",\"description\":\"\",\"owner\":\"\",\"lastChange\":\"Dec 19, 2008 6:35:33 AM\",\"hasCommits\":true,\"showRemoteBranches\":false,\"useTickets\":false,\"useDocs\":false,\"accessRestriction\":\"NONE\",\"isFrozen\":false,\"showReadme\":false,\"isFederated\":false}}";            \r
-               Map<String, RepositoryModel> models = JsonUtils.fromJsonString(json, FederationUtils.REPOSITORIES_TYPE);\r
-               assertEquals(8, models.size());\r
-       }\r
-\r
        public void testProposal() throws Exception {\r
                // create dummy repository data\r
                Map<String, RepositoryModel> repositories = new HashMap<String, RepositoryModel>();\r
@@ -96,9 +90,9 @@ public class FederationTests extends TestCase {
 \r
        public void testPullRepositories() throws Exception {\r
                try {\r
-                       String url = FederationUtils.asLink("http://localhost:" + port,\r
-                                       "testtoken", FederationRequest.PULL_REPOSITORIES);\r
-                       String json = JsonUtils.retrieveJsonString(url);\r
+                       String url = FederationUtils.asLink("http://localhost:" + port, "testtoken",\r
+                                       FederationRequest.PULL_REPOSITORIES);\r
+                       String json = JsonUtils.retrieveJsonString(url, null, null);\r
                } catch (IOException e) {\r
                        if (!e.getMessage().contains("403")) {\r
                                throw e;\r
index e140fb46778682b067b3f4139db6c6d9c8c111e2..cb98a560dc460132339add22169ae6c047aa7de6 100644 (file)
 package com.gitblit.tests;\r
 \r
 import java.io.IOException;\r
+import java.util.List;\r
 import java.util.Map;\r
 \r
 import junit.framework.TestCase;\r
 \r
+import com.gitblit.Constants.AccessRestrictionType;\r
+import com.gitblit.GitBlitException.UnauthorizedException;\r
+import com.gitblit.models.FederationModel;\r
+import com.gitblit.models.FederationProposal;\r
+import com.gitblit.models.FederationSet;\r
 import com.gitblit.models.RepositoryModel;\r
+import com.gitblit.models.UserModel;\r
 import com.gitblit.utils.RpcUtils;\r
 \r
+/**\r
+ * Tests all the rpc client utility methods, the rpc filter and rpc servlet.\r
+ * \r
+ * @author James Moger\r
+ * \r
+ */\r
 public class RpcTests extends TestCase {\r
 \r
-       public void testListRepositories() throws Exception {\r
-               Map<String, RepositoryModel> map = null;\r
+       String url = "https://localhost:8443";\r
+       String account = "admin";\r
+       String password = "admin";\r
+\r
+       public void testListRepositories() throws IOException {\r
+               Map<String, RepositoryModel> map = RpcUtils.getRepositories(url, null, null);\r
+               assertTrue("Repository list is null!", map != null);\r
+               assertTrue("Repository list is empty!", map.size() > 0);\r
+       }\r
+\r
+       public void testListUsers() throws IOException {\r
+               List<UserModel> list = null;\r
                try {\r
-                       map = RpcUtils.getRepositories("https://localhost:8443");\r
-               } catch (IOException e) {\r
-                       if (!e.getMessage().contains("403")) {\r
-                               throw e;\r
+                       list = RpcUtils.getUsers(url, null, null);\r
+               } catch (UnauthorizedException e) {\r
+               }\r
+               assertTrue("Server allows anyone to admin!", list == null);\r
+\r
+               list = RpcUtils.getUsers(url, "admin", "admin".toCharArray());\r
+               assertTrue("User list is empty!", list.size() > 0);\r
+       }\r
+\r
+       public void testUserAdministration() throws IOException {\r
+               UserModel user = new UserModel("garbage");\r
+               user.canAdmin = true;\r
+               user.password = "whocares";\r
+\r
+               // create\r
+               assertTrue("Failed to create user!",\r
+                               RpcUtils.createUser(user, url, account, password.toCharArray()));\r
+\r
+               UserModel retrievedUser = findUser(user.username);\r
+               assertTrue("Failed to find " + user.username, retrievedUser != null);\r
+               assertTrue("Retrieved user can not administer Gitblit", retrievedUser.canAdmin);\r
+\r
+               // rename and toggle admin permission\r
+               String originalName = user.username;\r
+               user.username = "garbage2";\r
+               user.canAdmin = false;\r
+               assertTrue("Failed to update user!",\r
+                               RpcUtils.updateUser(originalName, user, url, account, password.toCharArray()));\r
+\r
+               retrievedUser = findUser(user.username);\r
+               assertTrue("Failed to find " + user.username, retrievedUser != null);\r
+               assertTrue("Retrieved user did not update", !retrievedUser.canAdmin);\r
+\r
+               // delete\r
+               assertTrue("Failed to delete " + user.username,\r
+                               RpcUtils.deleteUser(retrievedUser, url, account, password.toCharArray()));\r
+\r
+               retrievedUser = findUser(user.username);\r
+               assertTrue("Failed to delete " + user.username, retrievedUser == null);\r
+       }\r
+\r
+       private UserModel findUser(String name) throws IOException {\r
+               List<UserModel> users = RpcUtils.getUsers(url, account, password.toCharArray());\r
+               UserModel retrievedUser = null;\r
+               for (UserModel model : users) {\r
+                       if (model.username.equalsIgnoreCase(name)) {\r
+                               retrievedUser = model;\r
+                               break;\r
                        }\r
                }\r
-               assertTrue("Repository list is null!", map != null);\r
-               assertTrue("Repository list is empty!", map.size() > 0);\r
+               return retrievedUser;\r
+       }\r
+\r
+       public void testRepositoryAdministration() throws IOException {\r
+               RepositoryModel model = new RepositoryModel();\r
+               model.name = "garbagerepo.git";\r
+               model.description = "created by RpcUtils";\r
+               model.owner = "garbage";\r
+               model.accessRestriction = AccessRestrictionType.VIEW;\r
+\r
+               // create\r
+               assertTrue("Failed to create repository!",\r
+                               RpcUtils.createRepository(model, url, account, password.toCharArray()));\r
+\r
+               RepositoryModel retrievedRepository = findRepository(model.name);\r
+               assertTrue("Failed to find " + model.name, retrievedRepository != null);\r
+               assertTrue("Access retriction type is wrong",\r
+                               AccessRestrictionType.VIEW.equals(retrievedRepository.accessRestriction));\r
+\r
+               // rename and change access restriciton\r
+               String originalName = model.name;\r
+               model.name = "garbagerepo2.git";\r
+               model.accessRestriction = AccessRestrictionType.PUSH;\r
+               assertTrue("Failed to update repository!", RpcUtils.updateRepository(originalName, model,\r
+                               url, account, password.toCharArray()));\r
+\r
+               retrievedRepository = findRepository(model.name);\r
+               assertTrue("Failed to find " + model.name, retrievedRepository != null);\r
+               assertTrue("Access retriction type is wrong",\r
+                               AccessRestrictionType.PUSH.equals(retrievedRepository.accessRestriction));\r
+\r
+               // memberships\r
+               String testMember = "justadded";\r
+               List<String> members = RpcUtils.getRepositoryMembers(retrievedRepository, url, account,\r
+                               password.toCharArray());\r
+               assertTrue("Membership roster is not empty!", members.size() == 0);\r
+               members.add(testMember);\r
+               assertTrue(\r
+                               "Failed to set memberships!",\r
+                               RpcUtils.setRepositoryMembers(retrievedRepository, members, url, account,\r
+                                               password.toCharArray()));\r
+               members = RpcUtils.getRepositoryMembers(retrievedRepository, url, account,\r
+                               password.toCharArray());\r
+               boolean foundMember = false;\r
+               for (String member : members) {\r
+                       if (member.equalsIgnoreCase(testMember)) {\r
+                               foundMember = true;\r
+                               break;\r
+                       }\r
+               }\r
+               assertTrue("Failed to find member!", foundMember);\r
+\r
+               // delete\r
+               assertTrue("Failed to delete " + model.name, RpcUtils.deleteRepository(retrievedRepository,\r
+                               url, account, password.toCharArray()));\r
+\r
+               retrievedRepository = findRepository(model.name);\r
+               assertTrue("Failed to delete " + model.name, retrievedRepository == null);\r
+       }\r
+\r
+       private RepositoryModel findRepository(String name) throws IOException {\r
+               Map<String, RepositoryModel> repositories = RpcUtils.getRepositories(url, account,\r
+                               password.toCharArray());\r
+               RepositoryModel retrievedRepository = null;\r
+               for (RepositoryModel model : repositories.values()) {\r
+                       if (model.name.equalsIgnoreCase(name)) {\r
+                               retrievedRepository = model;\r
+                               break;\r
+                       }\r
+               }\r
+               return retrievedRepository;\r
+       }\r
+\r
+       public void testFederationRegistrations() throws Exception {\r
+               List<FederationModel> registrations = RpcUtils.getFederationRegistrations(url, account,\r
+                               password.toCharArray());\r
+               assertTrue("No federation registrations wre retrieved!", registrations.size() > 0);\r
+       }\r
+\r
+       public void testFederationResultRegistrations() throws Exception {\r
+               List<FederationModel> registrations = RpcUtils.getFederationResultRegistrations(url,\r
+                               account, password.toCharArray());\r
+               assertTrue("No federation result registrations were retrieved!", registrations.size() > 0);\r
+       }\r
+       \r
+       public void testFederationProposals() throws Exception {\r
+               List<FederationProposal> proposals = RpcUtils.getFederationProposals(url,\r
+                               account, password.toCharArray());\r
+               assertTrue("No federation proposals were retrieved!", proposals.size() > 0);\r
+       }\r
+       \r
+       public void testFederationSets() throws Exception {\r
+               List<FederationSet> sets = RpcUtils.getFederationSets(url,\r
+                               account, password.toCharArray());\r
+               assertTrue("No federation sets were retrieved!", sets.size() > 0);\r
        }\r
 }\r