java操作svn的第三方包

本文介绍如何使用SVNKit库进行Java操作SVN的基本步骤,包括登录验证、获取版本库条目列表,并通过Servlet返回JSON格式的数据。此外,还提供了一个基于jQuery EasyUI的前端展示版本库列表的例子。

SVNKit 是一个完全基于Java的Subversion开源工具库,通过它提供的API,可以用Java操作svn,如代码提交,更新等。下面的例子,是我通过svnkit来获取svn版本库的最新版本。

svnkit是客户端jar包,所以不能用它来创建svn账户,那是服务端的事情,SVNKit is a client library, and Subversion client-server protocol does not provide a way to add or modify user account. Besides, there are numerous ways Subversion users can be defined (in svnserve.conf for svnserve, in LDAP for Apache, etc). 如果想创建用户的话,可以通过服务端的配置文件,或者通过apache的htpasswd工具来创建。

 

 

新建一个类(SVNUtil.class)实现svn功能

 

    private String svnRoot;

 

    private String userName;

 

    private String password;

 

    private SVNRepository repository;

 

   

 

    /***

 

     * 构造方法

 

     * @param svnRoot

 

     *             svn根目录

 

     */

 

    public SVNUtil(String svnRoot) {

 

       this.svnRoot=svnRoot;

 

    }

 

    /***

 

     * 构造方法

 

     * @param svnRoot

 

     *             svn根目录

 

     * @param userName

 

     *             登录用户名

 

     * @param password

 

     *             登录密码

 

     */

 

    public SVNUtil(String svnRoot, String userName, String password) {

 

       this.svnRoot=svnRoot;

 

       this.userName=userName;

 

       this.password=password;

 

    }

 

/***

 

     * 通过不同的协议初始化版本库

 

     */

 

    private static void setupLibrary() {

 

       // 对于使用http://https//

 

       DAVRepositoryFactory.setup();

 

       //对于使用svn/ /svn+xxx/ /

 

       SVNRepositoryFactoryImpl.setup();

 

       //对于使用file://

 

       FSRepositoryFactory.setup();

 

}

 

每次连接库都进行登陆验证

 

    /***

 

     * 登录验证

 

     * @return

 

     */

 

    public boolean login(){

 

       setupLibrary();

 

       try{

 

           //创建库连接

 

          repository=SVNRepositoryFactory.create(SVNURL.parseURIEncoded(this.svnRoot));

 

           //身份验证

 

           ISVNAuthenticationManager authManager = SVNWCUtil

 

           .createDefaultAuthenticationManager(this.userName,

 

                  this.password);

 

           //创建身份验证管理器

 

           repository.setAuthenticationManager(authManager);

 

           return true;

 

       catch(SVNException svne){

 

           svne.printStackTrace();

 

           return false;

 

       }

 

    }

 

下面的方法实现查询给定路径下的条目列表功能

 

/***

 

     *

 

     * @param path

 

     * @return 查询给定路径下的条目列表

 

     * @throws SVNException

 

     */

 

    @SuppressWarnings("rawtypes")

 

    public List<SVN> listEntries(String path)

 

           throws SVNException {

 

       Collection entries = repository.getDir(path, -1, null,

 

              (Collection) null);

 

       Iterator iterator = entries.iterator();

 

       List<SVN> svns = new ArrayList<SVN>();

 

       while (iterator.hasNext()) {

 

           SVNDirEntry entry = (SVNDirEntry) iterator.next();

 

           SVN svn = new SVN();

 

           svn.setCommitMessage(entry.getCommitMessage());

 

           svn.setDate(entry.getDate());

 

           svn.setKind(entry.getKind().toString());

 

           svn.setName(entry.getName());

 

           svn.setRepositoryRoot(entry.getRepositoryRoot().toString());

 

           svn.setRevision(entry.getRevision());

 

           svn.setSize(entry.getSize()/1024);

 

           svn.setUrl(path.equals("") ? "/"+entry.getName() : path +"/"+entry.getName());

 

           svn.setAuthor(entry.getAuthor());

 

           svn.setState(svn.getKind() == "file"?null:"closed");

 

           svns.add(svn);

 

       }

 

新建一个SVNServlet

 

添加一个方法用于把java对象转换为json字符串

 

/**

 

     * java对象转换为json字符串

 

     *

 

     * @param obj

 

     *            :可以为map,list,javaBean

 

     * @return json字符串

 

     * @createTime 2010-11-23 下午07:42:58

 

     */

 

    public static String object2Json(Object obj) {

 

       try {

 

           StringWriter sw = new StringWriter();

 

           JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);

 

           mapper.writeValue(gen, obj);

 

           gen.close();

 

           return sw.toString();

 

       catch (Exception e) {

 

           e.printStackTrace();

 

       }

 

       return null;

 

    }

 

 

 

    protected void doGet(HttpServletRequest request,

 

           HttpServletResponse response) throws ServletException, IOException {

 

       // TODO Auto-generated method stub

 

       this.doPost(request, response);

 

    }

 

 

 

   

 

    protected void doPost(HttpServletRequest request,

 

           HttpServletResponse response) throws ServletException, IOException {

 

       // TODO Auto-generated method stub

 

       Object svns = null;

 

       request.setCharacterEncoding("UTF-8");

 

       response.setCharacterEncoding("UTF-8");

 

       String path = request.getParameter("pid");

 

       String url = "svn://localhost/svndemo1";

 

       String usrName = "usrName";

 

       String password = "password";

 

       if (path == null) {

 

           path = "";

 

       }

 

       path = new String(path.getBytes("ISO-8859-1"),"UTF-8");

 

       String type = request.getParameter("type");

 

       PrintWriter out = response.getWriter();

 

       try {

 

           SVNUtil svnUtil = new SVNUtil(url, usrName, password);

 

           if (svnUtil.login()) {

 

              /*用于查询历史记录

 

if ("history".equals(type)) {

 

                  List<SVN> svnl = svnUtil.getHistory(path);

 

                  HashMap<String, Object> sv = new HashMap<String, Object>();

 

                  sv.put("total", svnl.size());

 

                  sv.put("rows", svnl);

 

                  svns = sv;

 

              else {*/

 

                  svns = svnUtil.listEntries(path);

 

              //}

 

              //java对象转换成json字符串

 

              String json = SVNServlet.object2Json(svns);

 

              out.print(json);

 

           else {

 

              System.out.println("验证失败");

 

           }

 

       catch (SVNException ex) {

 

           ex.printStackTrace();

 

       }

 

       out.flush();

 

       out.close();

 

    }

 

新建一个index.jsp用户显示版本数列表,页面显示我使用了jquery-easyui模板

 

<%@ page language="java" contentType="text/html; charset=utf-8"

 

    pageEncoding="utf-8"%>

 

    <%

 

    String path = request.getContextPath();

 

    String basePath = request.getScheme() + "://"

 

           + request.getServerName() + ":" + request.getServerPort()

 

           + path + "/";

 

    %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">

 

<html>

 

<head>

 

<base href="<%=basePath%>">

 

<title>SVN</title>

 

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

 

<meta http-equiv="pragma" content="no-cache">

 

<meta http-equiv="cache-control" content="no-cache">

 

<meta http-equiv="expires" content="0">

 

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

 

<meta http-equiv="description" content="This is my page">

 

<link rel="stylesheet" type="text/css"

 

    href="plugs/themes/default/easyui.css">

 

<link rel="stylesheet" type="text/css" href="plugs/themes/icon.css">

 

<script type="text/javascript" src="plugs/jquery-1.4.2.min.js"></script>

 

<script type="text/javascript" src="plugs/jquery.easyui.min.js"></script>

 

<script type="text/javascript">

 

    $(function() {

 

       $('#test').treegrid({

 

           title : 'SVN列表',

 

           nowrap : false,

 

           rownumbers : true,

 

           collapsible : false,

 

           url : 'svn?pid=',

 

           idField : 'url',

 

           treeField : 'url',

 

           frozenColumns : [ [ {

 

              title : '路径',

 

              field : 'url',

 

              width : 350,

 

              formatter : function(value) {

 

                  return '<span style="color:red">' + decodeURI(value.substr(value.lastIndexOf("/"))) + '</span>';

 

              }

 

           } ] ],

 

           columns : [ [ {

 

              field : 'name',

 

              title : '名称',

 

              width : 120

 

           }, {

 

              field : 'size',

 

              title : '文件大小(KB)',

 

              width : 80,

 

              rowspan : 2

 

           }, {

 

              field : 'revision',

 

              title : '版本号',

 

              width : 80,

 

              rowspan : 2

 

           }, {

 

              field : 'author',

 

              title : '作者',

 

              width : 100,

 

              rowspan : 2

 

           }, {

 

              field : 'date',

 

              title : '修改日期',

 

              width : 130,

 

              rowspan : 2

 

           }, {

 

              field : 'commitMessage',

 

              title : '注释',

 

              width : 150,

 

              rowspan : 2

 

           }, {

 

              field : 'kind',

 

              title : '操作',

 

              width : 120,

 

              align : 'center',

 

              rowspan : 2,

 

              formatter : function(value) {

 

                  return value=='file' ? '<a onclick="download()" style="cursor: pointer;color:red">下载</a><a onclick="viewHistory()" style="margin-left:5px; cursor: pointer;color:red">历史版本</a>' : '';

 

              }

 

           }] ],

 

           onBeforeExpand : function(row, param) {

 

              $(this).treegrid('options').url = 'svn?pid='+encodeURI(decodeURI(row.url));

 

           }

 

       });

 

    });

 

   

 

    function download(){

 

       setTimeout(function(){

 

           var node = $('#test').treegrid('getSelected');

 

           if(node !=null)

 

              window.open("download?url="+encodeURI(decodeURI(node.url))+"&size="+node.size+"&name="+encodeURI(decodeURI(node.name))+"&revision="+node.revision);

 

       },200);

 

      

 

    }

 

   

 

    function viewHistory(){

 

       setTimeout(function(){

 

           var node = $('#test').treegrid('getSelected');

 

           if(node != null) {

 

              window.open("history.jsp?uri="+encodeURI(decodeURI(node.url)),"_blank","height=400,width=700,status=yes,toolbar=no,menubar=no,location=no");

 

           }

 

       }, 200);

 

    }

 

</script>

 

 

 

</head>

 

<body>

 

 

 

<table id="test"></table>

 

 

 

</body>

 

</html>

 

转载于:https://www.cnblogs.com/dafengshou/p/3652339.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值