]> source.dussan.org Git - gitblit.git/commitdiff
Refactored federation servlet and utils. Started rpc servlet and utils.
authorJames Moger <james.moger@gitblit.com>
Sat, 1 Oct 2011 21:30:48 +0000 (17:30 -0400)
committerJames Moger <james.moger@gitblit.com>
Sat, 1 Oct 2011 21:30:48 +0000 (17:30 -0400)
13 files changed:
distrib/gitblit.properties
src/WEB-INF/web.xml
src/com/gitblit/Constants.java
src/com/gitblit/FederationServlet.java
src/com/gitblit/GitBlit.java
src/com/gitblit/JsonServlet.java [new file with mode: 0644]
src/com/gitblit/RpcServlet.java [new file with mode: 0644]
src/com/gitblit/utils/FederationUtils.java
src/com/gitblit/utils/JsonUtils.java [new file with mode: 0644]
src/com/gitblit/utils/RpcUtils.java [new file with mode: 0644]
src/com/gitblit/wicket/panels/FederationTokensPanel.java
tests/com/gitblit/tests/FederationTests.java
tests/com/gitblit/tests/RpcTests.java [new file with mode: 0644]

index 5493b25b4b37274de45447309c7da5347d93bbd9..2876382dea6690ef8a38c6fdee38ac084cc50a37 100644 (file)
@@ -87,6 +87,12 @@ web.siteName =
 # SINCE 0.5.0 \r
 web.allowAdministration = true\r
 \r
+# Allows remote clients to list repositories and administer the Gitblit instance\r
+# if they have administrator permissions.\r
+#\r
+# SINCE 0.6.1 \r
+web.enableRpcServlet = false\r
+\r
 # Allow dynamic zip downloads.\r
 #\r
 # SINCE 0.5.0   \r
index d557725955ccf6e142b263c4b78ad811b539cdfe..0a6cea97d9a57bc1a67b78b7345e6f772396072b 100644 (file)
                <url-pattern>/federation/*</url-pattern>\r
        </servlet-mapping>      \r
        \r
-\r
+       \r
+       <!-- Rpc Servlet\r
+                <url-pattern> MUST match: \r
+                       * com.gitblit.Constants.RPC_PATH                 \r
+                       * Wicket Filter ignorePaths parameter -->\r
+       <servlet>\r
+               <servlet-name>RpcServlet</servlet-name>\r
+               <servlet-class>com.gitblit.RpcServlet</servlet-class>           \r
+       </servlet>\r
+       <servlet-mapping>\r
+               <servlet-name>RpcServlet</servlet-name>\r
+               <url-pattern>/rpc/*</url-pattern>\r
+       </servlet-mapping>      \r
+       \r
+       \r
        <!-- Git Access Restriction Filter\r
                 <url-pattern> MUST match: \r
                        * GitServlet\r
                <url-pattern>/zip/*</url-pattern>\r
        </filter-mapping>\r
                \r
+               \r
        <!-- Wicket Filter -->\r
     <filter>\r
         <filter-name>wicketFilter</filter-name>\r
                * Zipfilter <url-pattern>\r
                * ZipServlet <url-pattern>\r
                * com.gitblit.Constants.ZIP_PATH\r
-               * FederationServlet <url-pattern> -->\r
-            <param-value>git/,feed/,zip/,federation/</param-value>\r
+               * FederationServlet <url-pattern>\r
+               * RpcServlet <url-pattern> -->\r
+            <param-value>git/,feed/,zip/,federation/,rpc/</param-value>\r
         </init-param>\r
     </filter>\r
     <filter-mapping>\r
index f4541c9fd6c5fffe4c6250f50a02423149de01c4..63a877f42eaabde5316a16992f332bdfd8156abd 100644 (file)
@@ -52,6 +52,8 @@ public class Constants {
        public static final String SYNDICATION_PATH = "/feed/";\r
 \r
        public static final String FEDERATION_PATH = "/federation/";\r
+       \r
+       public static final String RPC_PATH = "/rpc/";\r
 \r
        public static final String BORDER = "***********************************************************";\r
 \r
@@ -193,4 +195,27 @@ public class Constants {
                        return name();\r
                }\r
        }\r
+\r
+       /**\r
+        * Enumeration representing the possible remote procedure call requests from\r
+        * a client.\r
+        */\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
+               public static RpcRequest fromName(String name) {\r
+                       for (RpcRequest type : values()) {\r
+                               if (type.name().equalsIgnoreCase(name)) {\r
+                                       return type;\r
+                               }\r
+                       }\r
+                       return LIST_REPOSITORIES;\r
+               }\r
+               \r
+               @Override\r
+               public String toString() {\r
+                       return name();\r
+               }\r
+       }\r
 }\r
index 7dc5d6a911a2c45f6feb2487f258a31a7f0a76cf..0be1066f6ffeb87f49303b5c828aae567783a3b9 100644 (file)
@@ -15,7 +15,6 @@
  */\r
 package com.gitblit;\r
 \r
-import java.io.BufferedReader;\r
 import java.text.MessageFormat;\r
 import java.util.ArrayList;\r
 import java.util.Date;\r
@@ -23,24 +22,16 @@ import java.util.HashMap;
 import java.util.List;\r
 import java.util.Map;\r
 \r
-import javax.servlet.http.HttpServlet;\r
 import javax.servlet.http.HttpServletResponse;\r
 \r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-\r
 import com.gitblit.Constants.FederationRequest;\r
-import com.gitblit.Constants.FederationToken;\r
 import com.gitblit.models.FederationModel;\r
 import com.gitblit.models.FederationProposal;\r
-import com.gitblit.models.RepositoryModel;\r
 import com.gitblit.models.UserModel;\r
 import com.gitblit.utils.FederationUtils;\r
 import com.gitblit.utils.HttpUtils;\r
 import com.gitblit.utils.StringUtils;\r
 import com.gitblit.utils.TimeUtils;\r
-import com.google.gson.Gson;\r
-import com.google.gson.GsonBuilder;\r
 \r
 /**\r
  * Handles federation requests.\r
@@ -48,67 +39,25 @@ import com.google.gson.GsonBuilder;
  * @author James Moger\r
  * \r
  */\r
-public class FederationServlet extends HttpServlet {\r
+public class FederationServlet extends JsonServlet {\r
 \r
        private static final long serialVersionUID = 1L;\r
 \r
-       private transient Logger logger = LoggerFactory.getLogger(FederationServlet.class);\r
-\r
        public FederationServlet() {\r
                super();\r
        }\r
 \r
        /**\r
-        * Returns an url to this servlet for the specified parameters.\r
-        * \r
-        * @param sourceURL\r
-        *            the url of the source gitblit instance\r
-        * @param token\r
-        *            the federation token of the source gitblit instance\r
-        * @param req\r
-        *            the pull type request\r
-        */\r
-       public static String asFederationLink(String sourceURL, String token, FederationRequest req) {\r
-               return asFederationLink(sourceURL, null, token, req, null);\r
-       }\r
-\r
-       /**\r
-        * \r
-        * @param remoteURL\r
-        *            the url of the remote gitblit instance\r
-        * @param tokenType\r
-        *            the type of federation token of a gitblit instance\r
-        * @param token\r
-        *            the federation token of a gitblit instance\r
-        * @param req\r
-        *            the pull type request\r
-        * @param myURL\r
-        *            the url of this gitblit instance\r
-        * @return\r
-        */\r
-       public static String asFederationLink(String remoteURL, FederationToken tokenType,\r
-                       String token, FederationRequest req, String myURL) {\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 = FederationRequest.PULL_REPOSITORIES;\r
-               }\r
-               return remoteURL + Constants.FEDERATION_PATH + "?req=" + req.name().toLowerCase()\r
-                               + (token == null ? "" : ("&token=" + token))\r
-                               + (tokenType == null ? "" : ("&tokenType=" + tokenType.name().toLowerCase()))\r
-                               + (myURL == null ? "" : ("&url=" + StringUtils.encodeURL(myURL)));\r
-       }\r
-\r
-       /**\r
-        * Returns the list of repositories for federation requests.\r
+        * Processes a federation request.\r
         * \r
         * @param request\r
         * @param response\r
         * @throws javax.servlet.ServletException\r
         * @throws java.io.IOException\r
         */\r
-       private void processRequest(javax.servlet.http.HttpServletRequest request,\r
+\r
+       @Override\r
+       protected void processRequest(javax.servlet.http.HttpServletRequest request,\r
                        javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException,\r
                        java.io.IOException {\r
                FederationRequest reqType = FederationRequest.fromName(request.getParameter("req"));\r
@@ -137,26 +86,11 @@ public class FederationServlet extends HttpServlet {
 \r
                if (FederationRequest.PROPOSAL.equals(reqType)) {\r
                        // Receive a gitblit federation proposal\r
-                       BufferedReader reader = request.getReader();\r
-                       StringBuilder json = new StringBuilder();\r
-                       String line = null;\r
-                       while ((line = reader.readLine()) != null) {\r
-                               json.append(line);\r
-                       }\r
-                       reader.close();\r
-\r
-                       // check to see if we have proposal data\r
-                       if (json.length() == 0) {\r
-                               logger.error(MessageFormat.format("Failed to receive proposal data from {0}",\r
-                                               request.getRemoteAddr()));\r
-                               response.setStatus(HttpServletResponse.SC_BAD_REQUEST);\r
+                       FederationProposal proposal = deserialize(request, response, FederationProposal.class);\r
+                       if (proposal == null) {\r
                                return;\r
                        }\r
-\r
-                       // deserialize the proposal\r
-                       Gson gson = new Gson();\r
-                       FederationProposal proposal = gson.fromJson(json.toString(), FederationProposal.class);\r
-\r
+                       \r
                        // reject proposal, if not receipt prohibited\r
                        if (!GitBlit.getBoolean(Keys.federation.allowProposals, false)) {\r
                                logger.error(MessageFormat.format("Rejected {0} federation proposal from {1}",\r
@@ -193,25 +127,13 @@ public class FederationServlet extends HttpServlet {
                        String remoteId = StringUtils.decodeFromHtml(request.getParameter("url"));\r
                        String identification = MessageFormat.format("{0} ({1})", remoteId,\r
                                        request.getRemoteAddr());\r
-                       BufferedReader reader = request.getReader();\r
-                       StringBuilder json = new StringBuilder();\r
-                       String line = null;\r
-                       while ((line = reader.readLine()) != null) {\r
-                               json.append(line);\r
-                       }\r
-                       reader.close();\r
 \r
-                       // check to see if we have repository data\r
-                       if (json.length() == 0) {\r
-                               logger.error(MessageFormat.format(\r
-                                               "Failed to receive pulled repositories list from {0}", identification));\r
-                               response.setStatus(HttpServletResponse.SC_BAD_REQUEST);\r
+                       // deserialize the status data\r
+                       FederationModel results = deserialize(request, response, FederationModel.class);\r
+                       if (results == null) {\r
                                return;\r
                        }\r
 \r
-                       // deserialize the status data\r
-                       Gson gson = new Gson();\r
-                       FederationModel results = gson.fromJson(json.toString(), FederationModel.class);\r
                        // setup the last and netx pull dates\r
                        results.lastPull = new Date();\r
                        int mins = TimeUtils.convertFrequencyToMinutes(results.frequency);\r
@@ -279,25 +201,7 @@ public class FederationServlet extends HttpServlet {
                        }\r
                }\r
 \r
-               if (result != null) {\r
-                       // Send JSON response\r
-                       Gson gson = new GsonBuilder().setPrettyPrinting().create();\r
-                       String json = gson.toJson(result);\r
-                       response.getWriter().append(json);\r
-               }\r
-       }\r
-\r
-       @Override\r
-       protected void doPost(javax.servlet.http.HttpServletRequest request,\r
-                       javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException,\r
-                       java.io.IOException {\r
-               processRequest(request, response);\r
-       }\r
-\r
-       @Override\r
-       protected void doGet(javax.servlet.http.HttpServletRequest request,\r
-                       javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException,\r
-                       java.io.IOException {\r
-               processRequest(request, response);\r
+               // send the result of the request\r
+               serialize(response, result);\r
        }\r
 }\r
index c35340ac55ca262e2a970679bd4652c69ce44661..e86fcf6036edf491bb94ef16783513ffe2e4d83e 100644 (file)
@@ -63,9 +63,8 @@ import com.gitblit.models.RepositoryModel;
 import com.gitblit.models.UserModel;\r
 import com.gitblit.utils.FederationUtils;\r
 import com.gitblit.utils.JGitUtils;\r
+import com.gitblit.utils.JsonUtils;\r
 import com.gitblit.utils.StringUtils;\r
-import com.google.gson.Gson;\r
-import com.google.gson.GsonBuilder;\r
 \r
 /**\r
  * GitBlit is the servlet context listener singleton that acts as the core for\r
@@ -978,8 +977,7 @@ public class GitBlit implements ServletContextListener {
         */\r
        public boolean submitFederationProposal(FederationProposal proposal, String gitblitUrl) {\r
                // convert proposal to json\r
-               Gson gson = new GsonBuilder().setPrettyPrinting().create();\r
-               String json = gson.toJson(proposal);\r
+               String json = JsonUtils.toJsonString(proposal);\r
 \r
                try {\r
                        // make the proposals folder\r
@@ -1025,10 +1023,9 @@ public class GitBlit implements ServletContextListener {
                                                        && file.getName().toLowerCase().endsWith(Constants.PROPOSAL_EXT);\r
                                }\r
                        });\r
-                       Gson gson = new Gson();\r
                        for (File file : files) {\r
                                String json = com.gitblit.utils.FileUtils.readContent(file, null);\r
-                               FederationProposal proposal = gson.fromJson(json, FederationProposal.class);\r
+                               FederationProposal proposal = JsonUtils.fromJsonString(json, FederationProposal.class);\r
                                list.add(proposal);\r
                        }\r
                }\r
diff --git a/src/com/gitblit/JsonServlet.java b/src/com/gitblit/JsonServlet.java
new file mode 100644 (file)
index 0000000..b1d1053
--- /dev/null
@@ -0,0 +1,103 @@
+/*\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;\r
+\r
+import java.io.BufferedReader;\r
+import java.io.IOException;\r
+import java.text.MessageFormat;\r
+\r
+import javax.servlet.ServletException;\r
+import javax.servlet.http.HttpServlet;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+\r
+import org.slf4j.Logger;\r
+import org.slf4j.LoggerFactory;\r
+\r
+import com.google.gson.Gson;\r
+import com.google.gson.GsonBuilder;\r
+\r
+/**\r
+ * Servlet class for interpreting json requests.\r
+ * \r
+ * @author James Moger\r
+ * \r
+ */\r
+public abstract class JsonServlet extends HttpServlet {\r
+\r
+       private static final long serialVersionUID = 1L;\r
+\r
+       protected final Logger logger;\r
+\r
+       public JsonServlet() {\r
+               super();\r
+               logger = LoggerFactory.getLogger(getClass());\r
+       }\r
+\r
+       /**\r
+        * Processes an gson request.\r
+        * \r
+        * @param request\r
+        * @param response\r
+        * @throws javax.servlet.ServletException\r
+        * @throws java.io.IOException\r
+        */\r
+       protected abstract void processRequest(HttpServletRequest request, HttpServletResponse response)\r
+                       throws ServletException, IOException;\r
+\r
+       @Override\r
+       protected void doPost(HttpServletRequest request, HttpServletResponse response)\r
+                       throws ServletException, java.io.IOException {\r
+               processRequest(request, response);\r
+       }\r
+\r
+       @Override\r
+       protected void doGet(HttpServletRequest request, HttpServletResponse response)\r
+                       throws ServletException, IOException {\r
+               processRequest(request, response);\r
+       }\r
+\r
+       protected <X> X deserialize(HttpServletRequest request, HttpServletResponse response,\r
+                       Class<X> clazz) throws IOException {\r
+               BufferedReader reader = request.getReader();\r
+               StringBuilder json = new StringBuilder();\r
+               String line = null;\r
+               while ((line = reader.readLine()) != null) {\r
+                       json.append(line);\r
+               }\r
+               reader.close();\r
+\r
+               if (json.length() == 0) {\r
+                       logger.error(MessageFormat.format("Failed to receive json data from {0}",\r
+                                       request.getRemoteAddr()));\r
+                       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
+       }\r
+\r
+       protected void serialize(HttpServletResponse response, Object o) throws IOException {\r
+               if (o != null) {\r
+                       // Send JSON response\r
+                       Gson gson = new GsonBuilder().setPrettyPrinting().create();\r
+                       String json = gson.toJson(o);\r
+                       response.getWriter().append(json);\r
+               }\r
+       }\r
+}\r
diff --git a/src/com/gitblit/RpcServlet.java b/src/com/gitblit/RpcServlet.java
new file mode 100644 (file)
index 0000000..83fd733
--- /dev/null
@@ -0,0 +1,107 @@
+/*\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;\r
+\r
+import java.text.MessageFormat;\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+import javax.servlet.http.HttpServletResponse;\r
+\r
+import com.gitblit.Constants.RpcRequest;\r
+import com.gitblit.models.RepositoryModel;\r
+import com.gitblit.models.UserModel;\r
+import com.gitblit.utils.HttpUtils;\r
+\r
+/**\r
+ * Handles remote procedure calls.\r
+ * \r
+ * @author James Moger\r
+ * \r
+ */\r
+public class RpcServlet extends JsonServlet {\r
+\r
+       private static final long serialVersionUID = 1L;\r
+\r
+       public RpcServlet() {\r
+               super();\r
+       }\r
+\r
+       /**\r
+        * Processes an rpc request.\r
+        * \r
+        * @param request\r
+        * @param response\r
+        * @throws javax.servlet.ServletException\r
+        * @throws java.io.IOException\r
+        */\r
+       @Override\r
+       protected void processRequest(javax.servlet.http.HttpServletRequest request,\r
+                       javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException,\r
+                       java.io.IOException {\r
+               RpcRequest reqType = RpcRequest.fromName(request.getParameter("req"));\r
+               logger.info(MessageFormat.format("Rpc {0} request from {1}", reqType,\r
+                               request.getRemoteAddr()));\r
+\r
+               if (!GitBlit.getBoolean(Keys.web.enableRpcServlet, false)) {\r
+                       logger.warn(Keys.web.enableRpcServlet + " must be set TRUE for rpc requests.");\r
+                       response.sendError(HttpServletResponse.SC_FORBIDDEN);\r
+                       return;\r
+               }\r
+\r
+               // TODO user authentication and authorization\r
+               UserModel user = null;\r
+\r
+               Object result = null;\r
+               if (RpcRequest.LIST_REPOSITORIES.equals(reqType)) {\r
+                       // list repositories\r
+\r
+                       // Determine the Gitblit clone url\r
+                       String gitblitUrl = HttpUtils.getGitblitURL(request);\r
+                       StringBuilder sb = new StringBuilder();\r
+                       sb.append(gitblitUrl);\r
+                       sb.append(Constants.GIT_PATH);\r
+                       sb.append("{0}");\r
+                       String cloneUrl = sb.toString();\r
+\r
+                       List<RepositoryModel> list = GitBlit.self().getRepositoryModels(user);\r
+                       Map<String, RepositoryModel> repositories = new HashMap<String, RepositoryModel>();\r
+                       for (RepositoryModel model : list) {\r
+                               String url = MessageFormat.format(cloneUrl, model.name);\r
+                               repositories.put(url, model);\r
+                       }\r
+                       result = repositories;\r
+               } else if (RpcRequest.LIST_USERS.equals(reqType)) {\r
+                       // list users\r
+                       if (user == null || !user.canAdmin) {\r
+                               response.sendError(HttpServletResponse.SC_FORBIDDEN);\r
+                               return;\r
+                       }\r
+                       // user is authorized to retrieve all accounts\r
+                       List<String> names = GitBlit.self().getAllUsernames();\r
+                       List<UserModel> users = new ArrayList<UserModel>();\r
+                       for (String name : names) {\r
+                               users.add(GitBlit.self().getUserModel(name));\r
+                       }\r
+                       result = users;\r
+               }\r
+\r
+               // send the result of the request\r
+               serialize(response, result);\r
+       }\r
+}\r
index fde95575ae3eb0af7e8780ecc15c9dcfc22d5575..d04a7a3102faf1cb83beaae4bff4256dafdb1310 100644 (file)
  */\r
 package com.gitblit.utils;\r
 \r
-import java.io.BufferedReader;\r
-import java.io.InputStream;\r
-import java.io.InputStreamReader;\r
-import java.io.OutputStream;\r
 import java.lang.reflect.Type;\r
-import java.net.HttpURLConnection;\r
-import java.net.URL;\r
-import java.net.URLConnection;\r
-import java.security.SecureRandom;\r
-import java.security.cert.CertificateException;\r
-import java.security.cert.X509Certificate;\r
 import java.text.MessageFormat;\r
 import java.util.ArrayList;\r
 import java.util.Collection;\r
@@ -34,28 +24,21 @@ import java.util.HashMap;
 import java.util.List;\r
 import java.util.Map;\r
 \r
-import javax.net.ssl.HostnameVerifier;\r
-import javax.net.ssl.HttpsURLConnection;\r
-import javax.net.ssl.SSLContext;\r
-import javax.net.ssl.SSLSession;\r
-import javax.net.ssl.TrustManager;\r
-import javax.net.ssl.X509TrustManager;\r
 import javax.servlet.http.HttpServletResponse;\r
 \r
 import org.slf4j.Logger;\r
 import org.slf4j.LoggerFactory;\r
 \r
+import com.gitblit.Constants;\r
 import com.gitblit.Constants.FederationProposalResult;\r
 import com.gitblit.Constants.FederationRequest;\r
-import com.gitblit.FederationServlet;\r
+import com.gitblit.Constants.FederationToken;\r
 import com.gitblit.IStoredSettings;\r
 import com.gitblit.Keys;\r
 import com.gitblit.models.FederationModel;\r
 import com.gitblit.models.FederationProposal;\r
 import com.gitblit.models.RepositoryModel;\r
 import com.gitblit.models.UserModel;\r
-import com.google.gson.Gson;\r
-import com.google.gson.GsonBuilder;\r
 import com.google.gson.reflect.TypeToken;\r
 \r
 /**\r
@@ -66,8 +49,6 @@ import com.google.gson.reflect.TypeToken;
  */\r
 public class FederationUtils {\r
 \r
-       public static final String CHARSET;\r
-\r
        public static final Type REPOSITORIES_TYPE = new TypeToken<Map<String, RepositoryModel>>() {\r
        }.getType();\r
 \r
@@ -80,23 +61,48 @@ public class FederationUtils {
        public static final Type RESULTS_TYPE = new TypeToken<List<FederationModel>>() {\r
        }.getType();\r
 \r
-       private static final SSLContext SSL_CONTEXT;\r
-\r
-       private static final DummyHostnameVerifier HOSTNAME_VERIFIER;\r
-\r
        private static final Logger LOGGER = LoggerFactory.getLogger(FederationUtils.class);\r
 \r
-       static {\r
-               SSLContext context = null;\r
-               try {\r
-                       context = SSLContext.getInstance("SSL");\r
-                       context.init(null, new TrustManager[] { new DummyTrustManager() }, new SecureRandom());\r
-               } catch (Throwable t) {\r
-                       t.printStackTrace();\r
+       /**\r
+        * Returns an url to this servlet for the specified parameters.\r
+        * \r
+        * @param sourceURL\r
+        *            the url of the source gitblit instance\r
+        * @param token\r
+        *            the federation token of the source gitblit instance\r
+        * @param req\r
+        *            the pull type request\r
+        */\r
+       public static String asLink(String sourceURL, String token, FederationRequest req) {\r
+               return asLink(sourceURL, null, token, req, null);\r
+       }\r
+\r
+       /**\r
+        * \r
+        * @param remoteURL\r
+        *            the url of the remote gitblit instance\r
+        * @param tokenType\r
+        *            the type of federation token of a gitblit instance\r
+        * @param token\r
+        *            the federation token of a gitblit instance\r
+        * @param req\r
+        *            the pull type request\r
+        * @param myURL\r
+        *            the url of this gitblit instance\r
+        * @return\r
+        */\r
+       public static String asLink(String remoteURL, FederationToken tokenType, String token,\r
+                       FederationRequest req, String myURL) {\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 = FederationRequest.PULL_REPOSITORIES;\r
                }\r
-               SSL_CONTEXT = context;\r
-               HOSTNAME_VERIFIER = new DummyHostnameVerifier();\r
-               CHARSET = "UTF-8";\r
+               return remoteURL + Constants.FEDERATION_PATH + "?req=" + req.name().toLowerCase()\r
+                               + (token == null ? "" : ("&token=" + token))\r
+                               + (tokenType == null ? "" : ("&tokenType=" + tokenType.name().toLowerCase()))\r
+                               + (myURL == null ? "" : ("&url=" + StringUtils.encodeURL(myURL)));\r
        }\r
 \r
        /**\r
@@ -195,10 +201,9 @@ public class FederationUtils {
         * @return true if there is a route to the remoteUrl\r
         */\r
        public static boolean poke(String remoteUrl) throws Exception {\r
-               String url = FederationServlet.asFederationLink(remoteUrl, null, FederationRequest.POKE);\r
-               Gson gson = new Gson();\r
-               String json = gson.toJson("POKE");\r
-               int status = writeJson(url, json);\r
+               String url = asLink(remoteUrl, null, FederationRequest.POKE);\r
+               String json = JsonUtils.toJsonString("POKE");\r
+               int status = JsonUtils.sendJsonString(url, json);\r
                return status == HttpServletResponse.SC_OK;\r
        }\r
 \r
@@ -213,11 +218,9 @@ public class FederationUtils {
         */\r
        public static FederationProposalResult propose(String remoteUrl, FederationProposal proposal)\r
                        throws Exception {\r
-               String url = FederationServlet\r
-                               .asFederationLink(remoteUrl, null, FederationRequest.PROPOSAL);\r
-               Gson gson = new GsonBuilder().setPrettyPrinting().create();\r
-               String json = gson.toJson(proposal);\r
-               int status = writeJson(url, json);\r
+               String url = asLink(remoteUrl, null, FederationRequest.PROPOSAL);\r
+               String json = JsonUtils.toJsonString(proposal);\r
+               int status = JsonUtils.sendJsonString(url, json);\r
                switch (status) {\r
                case HttpServletResponse.SC_FORBIDDEN:\r
                        // remote Gitblit Federation disabled\r
@@ -251,9 +254,9 @@ public class FederationUtils {
         */\r
        public static Map<String, RepositoryModel> getRepositories(FederationModel registration,\r
                        boolean checkExclusions) throws Exception {\r
-               String url = FederationServlet.asFederationLink(registration.url, registration.token,\r
+               String url = asLink(registration.url, registration.token,\r
                                FederationRequest.PULL_REPOSITORIES);\r
-               Map<String, RepositoryModel> models = readGson(url, REPOSITORIES_TYPE);\r
+               Map<String, RepositoryModel> models = JsonUtils.retrieveJson(url, REPOSITORIES_TYPE);\r
                if (checkExclusions) {\r
                        Map<String, RepositoryModel> includedModels = new HashMap<String, RepositoryModel>();\r
                        for (Map.Entry<String, RepositoryModel> entry : models.entrySet()) {\r
@@ -274,9 +277,8 @@ public class FederationUtils {
         * @throws Exception\r
         */\r
        public static Collection<UserModel> getUsers(FederationModel registration) throws Exception {\r
-               String url = FederationServlet.asFederationLink(registration.url, registration.token,\r
-                               FederationRequest.PULL_USERS);\r
-               Collection<UserModel> models = readGson(url, USERS_TYPE);\r
+               String url = asLink(registration.url, registration.token, FederationRequest.PULL_USERS);\r
+               Collection<UserModel> models = JsonUtils.retrieveJson(url, USERS_TYPE);\r
                return models;\r
        }\r
 \r
@@ -289,9 +291,8 @@ public class FederationUtils {
         * @throws Exception\r
         */\r
        public static Map<String, String> getSettings(FederationModel registration) throws Exception {\r
-               String url = FederationServlet.asFederationLink(registration.url, registration.token,\r
-                               FederationRequest.PULL_SETTINGS);\r
-               Map<String, String> settings = readGson(url, SETTINGS_TYPE);\r
+               String url = asLink(registration.url, registration.token, FederationRequest.PULL_SETTINGS);\r
+               Map<String, String> settings = JsonUtils.retrieveJson(url, SETTINGS_TYPE);\r
                return settings;\r
        }\r
 \r
@@ -309,122 +310,10 @@ public class FederationUtils {
         */\r
        public static boolean acknowledgeStatus(String identification, FederationModel registration)\r
                        throws Exception {\r
-               String url = FederationServlet.asFederationLink(registration.url, null, registration.token,\r
-                               FederationRequest.STATUS, identification);\r
-               Gson gson = new GsonBuilder().setPrettyPrinting().create();\r
-               String json = gson.toJson(registration);\r
-               int status = writeJson(url, json);\r
+               String url = asLink(registration.url, null, registration.token, FederationRequest.STATUS,\r
+                               identification);\r
+               String json = JsonUtils.toJsonString(registration);\r
+               int status = JsonUtils.sendJsonString(url, json);\r
                return status == HttpServletResponse.SC_OK;\r
        }\r
-\r
-       /**\r
-        * Reads a gson object from the specified url.\r
-        * \r
-        * @param url\r
-        * @param type\r
-        * @return\r
-        * @throws Exception\r
-        */\r
-       public static <X> X readGson(String url, Type type) throws Exception {\r
-               String json = readJson(url);\r
-               if (StringUtils.isEmpty(json)) {\r
-                       return null;\r
-               }\r
-               Gson gson = new Gson();\r
-               return gson.fromJson(json, type);\r
-       }\r
-\r
-       /**\r
-        * Reads a JSON response.\r
-        * \r
-        * @param url\r
-        * @return the JSON response as a string\r
-        * @throws Exception\r
-        */\r
-       public static String readJson(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
-               }\r
-               is.close();\r
-               return json.toString();\r
-       }\r
-\r
-       /**\r
-        * Writes a JSON message to the specified url.\r
-        * \r
-        * @param url\r
-        *            the url to write to\r
-        * @param json\r
-        *            the json message to send\r
-        * @return the http request result code\r
-        * @throws Exception\r
-        */\r
-       public static int writeJson(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
-\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
-       }\r
-\r
-       /**\r
-        * DummyTrustManager trusts all certificates.\r
-        */\r
-       private static class DummyTrustManager implements X509TrustManager {\r
-\r
-               @Override\r
-               public void checkClientTrusted(X509Certificate[] certs, String authType)\r
-                               throws CertificateException {\r
-               }\r
-\r
-               @Override\r
-               public void checkServerTrusted(X509Certificate[] certs, String authType)\r
-                               throws CertificateException {\r
-               }\r
-\r
-               @Override\r
-               public X509Certificate[] getAcceptedIssuers() {\r
-                       return null;\r
-               }\r
-       }\r
-\r
-       /**\r
-        * Trusts all hostnames from a certificate, including self-signed certs.\r
-        */\r
-       private static class DummyHostnameVerifier implements HostnameVerifier {\r
-               @Override\r
-               public boolean verify(String hostname, SSLSession session) {\r
-                       return true;\r
-               }\r
-       }\r
 }\r
diff --git a/src/com/gitblit/utils/JsonUtils.java b/src/com/gitblit/utils/JsonUtils.java
new file mode 100644 (file)
index 0000000..a697b7a
--- /dev/null
@@ -0,0 +1,224 @@
+/*\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.utils;\r
+\r
+import java.io.BufferedReader;\r
+import java.io.InputStream;\r
+import java.io.InputStreamReader;\r
+import java.io.OutputStream;\r
+import java.lang.reflect.Type;\r
+import java.net.HttpURLConnection;\r
+import java.net.URL;\r
+import java.net.URLConnection;\r
+import java.security.SecureRandom;\r
+import java.security.cert.CertificateException;\r
+import java.security.cert.X509Certificate;\r
+import java.util.Collection;\r
+import java.util.Map;\r
+\r
+import javax.net.ssl.HostnameVerifier;\r
+import javax.net.ssl.HttpsURLConnection;\r
+import javax.net.ssl.SSLContext;\r
+import javax.net.ssl.SSLSession;\r
+import javax.net.ssl.TrustManager;\r
+import javax.net.ssl.X509TrustManager;\r
+\r
+import com.gitblit.models.RepositoryModel;\r
+import com.gitblit.models.UserModel;\r
+import com.google.gson.Gson;\r
+import com.google.gson.GsonBuilder;\r
+import com.google.gson.reflect.TypeToken;\r
+\r
+/**\r
+ * Utility methods for gson calls to a Gitblit server.\r
+ * \r
+ * @author James Moger\r
+ * \r
+ */\r
+public class JsonUtils {\r
+\r
+       public static final String CHARSET;\r
+\r
+       public static final Type REPOSITORIES_TYPE = new TypeToken<Map<String, RepositoryModel>>() {\r
+       }.getType();\r
+\r
+       public static final Type USERS_TYPE = new TypeToken<Collection<UserModel>>() {\r
+       }.getType();\r
+\r
+       private static final SSLContext SSL_CONTEXT;\r
+\r
+       private static final DummyHostnameVerifier HOSTNAME_VERIFIER;\r
+\r
+       static {\r
+               SSLContext context = null;\r
+               try {\r
+                       context = SSLContext.getInstance("SSL");\r
+                       context.init(null, new TrustManager[] { new DummyTrustManager() }, new SecureRandom());\r
+               } catch (Throwable t) {\r
+                       t.printStackTrace();\r
+               }\r
+               SSL_CONTEXT = context;\r
+               HOSTNAME_VERIFIER = new DummyHostnameVerifier();\r
+               CHARSET = "UTF-8";\r
+       }\r
+\r
+       /**\r
+        * Creates JSON from the specified object.\r
+        * \r
+        * @param o\r
+        * @return json\r
+        */\r
+       public static String toJsonString(Object o) {\r
+               Gson gson = new GsonBuilder().setPrettyPrinting().create();\r
+               String json = gson.toJson(o);\r
+               return json;\r
+       }\r
+\r
+       /**\r
+        * Convert a json string to an object of the specified type.\r
+        * \r
+        * @param json\r
+        * @param clazz\r
+        * @return an object\r
+        */\r
+       public static <X> X fromJsonString(String json, Class<X> clazz) {\r
+               Gson gson = new Gson();\r
+               return gson.fromJson(json, clazz);\r
+       }\r
+       \r
+       /**\r
+        * Convert a json string to an object of the specified type.\r
+        * \r
+        * @param json\r
+        * @param clazz\r
+        * @return an object\r
+        */\r
+       public static <X> X fromJsonString(String json, Type type) {\r
+               Gson gson = new Gson();\r
+               return gson.fromJson(json, type);\r
+       }\r
+\r
+       /**\r
+        * Reads a gson object from the specified url.\r
+        * \r
+        * @param url\r
+        * @param type\r
+        * @return\r
+        * @throws Exception\r
+        */\r
+       public static <X> X retrieveJson(String url, Type type) throws Exception {\r
+               String json = retrieveJsonString(url);\r
+               if (StringUtils.isEmpty(json)) {\r
+                       return null;\r
+               }\r
+               Gson gson = new Gson();\r
+               return gson.fromJson(json, type);\r
+       }\r
+\r
+       /**\r
+        * Retrieves a JSON message.\r
+        * \r
+        * @param url\r
+        * @return the JSON message as a string\r
+        * @throws Exception\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
+               }\r
+               is.close();\r
+               return json.toString();\r
+       }\r
+\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
+        * @return the http request result code\r
+        * @throws Exception\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
+\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
+       }\r
+\r
+       /**\r
+        * DummyTrustManager trusts all certificates.\r
+        */\r
+       private static class DummyTrustManager implements X509TrustManager {\r
+\r
+               @Override\r
+               public void checkClientTrusted(X509Certificate[] certs, String authType)\r
+                               throws CertificateException {\r
+               }\r
+\r
+               @Override\r
+               public void checkServerTrusted(X509Certificate[] certs, String authType)\r
+                               throws CertificateException {\r
+               }\r
+\r
+               @Override\r
+               public X509Certificate[] getAcceptedIssuers() {\r
+                       return null;\r
+               }\r
+       }\r
+\r
+       /**\r
+        * Trusts all hostnames from a certificate, including self-signed certs.\r
+        */\r
+       private static class DummyHostnameVerifier implements HostnameVerifier {\r
+               @Override\r
+               public boolean verify(String hostname, SSLSession session) {\r
+                       return true;\r
+               }\r
+       }\r
+}\r
diff --git a/src/com/gitblit/utils/RpcUtils.java b/src/com/gitblit/utils/RpcUtils.java
new file mode 100644 (file)
index 0000000..919c7bb
--- /dev/null
@@ -0,0 +1,86 @@
+/*\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.utils;\r
+\r
+import java.lang.reflect.Type;\r
+import java.util.Collection;\r
+import java.util.Map;\r
+\r
+import com.gitblit.Constants;\r
+import com.gitblit.Constants.RpcRequest;\r
+import com.gitblit.models.RepositoryModel;\r
+import com.gitblit.models.UserModel;\r
+import com.google.gson.reflect.TypeToken;\r
+\r
+/**\r
+ * Utility methods for rpc calls.\r
+ * \r
+ * @author James Moger\r
+ * \r
+ */\r
+public class RpcUtils {\r
+\r
+       public static final Type REPOSITORIES_TYPE = new TypeToken<Map<String, RepositoryModel>>() {\r
+       }.getType();\r
+\r
+       public static final Type USERS_TYPE = new TypeToken<Collection<UserModel>>() {\r
+       }.getType();\r
+\r
+       /**\r
+        * \r
+        * @param remoteURL\r
+        *            the url of the remote gitblit instance\r
+        * @param req\r
+        *            the rpc request type\r
+        * @return\r
+        */\r
+       public static String asLink(String remoteURL, RpcRequest req) {\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
+       }\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
+        * @return a map of cloneable repositories\r
+        * @throws Exception\r
+        */\r
+       public static Map<String, RepositoryModel> getRepositories(String serverUrl) throws Exception {\r
+               String url = asLink(serverUrl, RpcRequest.LIST_REPOSITORIES);\r
+               Map<String, RepositoryModel> models = JsonUtils.retrieveJson(url, REPOSITORIES_TYPE);\r
+               return models;\r
+       }\r
+\r
+       /**\r
+        * Tries to pull the gitblit user accounts from the remote gitblit instance.\r
+        * \r
+        * @param serverUrl\r
+        * @return a collection of UserModel objects\r
+        * @throws Exception\r
+        */\r
+       public static Collection<UserModel> getUsers(String serverUrl) throws Exception {\r
+               String url = asLink(serverUrl, RpcRequest.LIST_USERS);\r
+               Collection<UserModel> models = JsonUtils.retrieveJson(url, USERS_TYPE);\r
+               return models;\r
+       }\r
+}\r
index 3a771886d1eb61e678ae9a9cb5e7cdd037827959..3454492f05371b8965f879996a2e36f8e0d037e9 100644 (file)
@@ -28,9 +28,9 @@ import org.apache.wicket.markup.repeater.data.ListDataProvider;
 \r
 import com.gitblit.Constants.FederationRequest;\r
 import com.gitblit.Constants.FederationToken;\r
-import com.gitblit.FederationServlet;\r
 import com.gitblit.GitBlit;\r
 import com.gitblit.Keys;\r
+import com.gitblit.utils.FederationUtils;\r
 import com.gitblit.wicket.WicketUtils;\r
 import com.gitblit.wicket.pages.SendProposalPage;\r
 \r
@@ -42,11 +42,11 @@ public class FederationTokensPanel extends BasePanel {
                super(wicketId);\r
 \r
                final String baseUrl = WicketUtils.getGitblitURL(getRequest());\r
-               add(new ExternalLink("federatedUsers", FederationServlet.asFederationLink(baseUrl, GitBlit.self()\r
+               add(new ExternalLink("federatedUsers", FederationUtils.asLink(baseUrl, GitBlit.self()\r
                                .getFederationToken(FederationToken.USERS_AND_REPOSITORIES),\r
                                FederationRequest.PULL_USERS)));\r
 \r
-               add(new ExternalLink("federatedSettings", FederationServlet.asFederationLink(baseUrl, GitBlit\r
+               add(new ExternalLink("federatedSettings", FederationUtils.asLink(baseUrl, GitBlit\r
                                .self().getFederationToken(FederationToken.ALL), FederationRequest.PULL_SETTINGS)));\r
 \r
                final List<String[]> data = new ArrayList<String[]>();\r
@@ -83,7 +83,7 @@ public class FederationTokensPanel extends BasePanel {
                                }\r
                                item.add(new Label("value", entry[1]));\r
 \r
-                               item.add(new ExternalLink("repositoryDefinitions", FederationServlet.asFederationLink(\r
+                               item.add(new ExternalLink("repositoryDefinitions", FederationUtils.asLink(\r
                                                baseUrl, entry[1], FederationRequest.PULL_REPOSITORIES)));\r
 \r
                                item.add(new BookmarkablePageLink<Void>("send",\r
index c5f7e8d867ef6f655d6173136307c26034309d93..8af3167174473a2cf5308a85b993a0a06aad27aa 100644 (file)
@@ -27,12 +27,11 @@ import com.gitblit.Constants.AccessRestrictionType;
 import com.gitblit.Constants.FederationProposalResult;\r
 import com.gitblit.Constants.FederationRequest;\r
 import com.gitblit.Constants.FederationToken;\r
-import com.gitblit.FederationServlet;\r
 import com.gitblit.GitBlitServer;\r
 import com.gitblit.models.FederationProposal;\r
 import com.gitblit.models.RepositoryModel;\r
 import com.gitblit.utils.FederationUtils;\r
-import com.google.gson.Gson;\r
+import com.gitblit.utils.JsonUtils;\r
 \r
 public class FederationTests extends TestCase {\r
 \r
@@ -66,10 +65,8 @@ public class FederationTests extends TestCase {
        }\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
-               Gson gson = new Gson();\r
-               Map<String, RepositoryModel> models = gson\r
-                               .fromJson(json, FederationUtils.REPOSITORIES_TYPE);\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
@@ -99,9 +96,9 @@ public class FederationTests extends TestCase {
 \r
        public void testPullRepositories() throws Exception {\r
                try {\r
-                       String url = FederationServlet.asFederationLink("http://localhost:" + port,\r
+                       String url = FederationUtils.asLink("http://localhost:" + port,\r
                                        "testtoken", FederationRequest.PULL_REPOSITORIES);\r
-                       String json = FederationUtils.readJson(url);\r
+                       String json = JsonUtils.retrieveJsonString(url);\r
                } catch (IOException e) {\r
                        if (!e.getMessage().contains("403")) {\r
                                throw e;\r
diff --git a/tests/com/gitblit/tests/RpcTests.java b/tests/com/gitblit/tests/RpcTests.java
new file mode 100644 (file)
index 0000000..e140fb4
--- /dev/null
@@ -0,0 +1,40 @@
+/*\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.tests;\r
+\r
+import java.io.IOException;\r
+import java.util.Map;\r
+\r
+import junit.framework.TestCase;\r
+\r
+import com.gitblit.models.RepositoryModel;\r
+import com.gitblit.utils.RpcUtils;\r
+\r
+public class RpcTests extends TestCase {\r
+\r
+       public void testListRepositories() throws Exception {\r
+               Map<String, RepositoryModel> map = null;\r
+               try {\r
+                       map = RpcUtils.getRepositories("https://localhost:8443");\r
+               } catch (IOException e) {\r
+                       if (!e.getMessage().contains("403")) {\r
+                               throw e;\r
+                       }\r
+               }\r
+               assertTrue("Repository list is null!", map != null);\r
+               assertTrue("Repository list is empty!", map.size() > 0);\r
+       }\r
+}\r