Using the Svnkit API, pure Java Operations SVN, to achieve SVN submission, update and other operations (revised version)

Source: Internet
Author: User
Tags getmessage parent directory svn svn client svn update

This is a bug that was modified on the basis of the previous article.


Import Java.io.File;
Import Org.apache.log4j.Logger;
Import Org.tmatesoft.svn.core.SVNCommitInfo;
Import org.tmatesoft.svn.core.SVNDepth;
Import org.tmatesoft.svn.core.SVNException;
Import Org.tmatesoft.svn.core.SVNNodeKind;
Import Org.tmatesoft.svn.core.SVNURL;
Import Org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
Import Org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
Import Org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory;
Import Org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl;
Import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions;
Import Org.tmatesoft.svn.core.io.SVNRepository;
Import Org.tmatesoft.svn.core.io.SVNRepositoryFactory;
Import Org.tmatesoft.svn.core.wc.SVNClientManager;
Import org.tmatesoft.svn.core.wc.SVNRevision;
Import Org.tmatesoft.svn.core.wc.SVNStatus;
Import org.tmatesoft.svn.core.wc.SVNUpdateClient;

Import Org.tmatesoft.svn.core.wc.SVNWCUtil; /** * Svnkit Utility * @author Lena Yang * * */public class SvnutIl {private static Logger Logger = Logger.getlogger (Svnutil.class);
		/** * The version library is initialized with a different protocol/public static void Setuplibrary () {davrepositoryfactory.setup ();
		Svnrepositoryfactoryimpl.setup ();
	Fsrepositoryfactory.setup ();
		/** * Verify login SVN/public static Svnclientmanager authsvn (string svnroot, string Username, string password) {

		Initialize version library setuplibrary ();
		Create a library connection svnrepository repository = null;
		try {repository = svnrepositoryfactory.create (svnurl. parseuriencoded (Svnroot));
			catch (Svnexception e) {logger.error (E.geterrormessage (), E);
		return null; }//Authentication Isvnauthenticationmanager AuthManager = svnwcutil. Createdefaultauthenticationmanager (username, password

		);

		Create the Authentication Manager repository.setauthenticationmanager (AuthManager);
		Defaultsvnoptions options = Svnwcutil.createdefaultoptions (true);
		Svnclientmanager Clientmanager = svnclientmanager.newinstance (options, AuthManager);
	return clientmanager; }
	
	/* * Make directory in SVN repository * @param clientmanager * @param URL * eg:http://svn.ambow.com/wlpt/bsp/ Trunk * @param commitmessage * @return * @throws svnexception/public static Svncommitinfo Makedirectory (SVNCL Ientmanager clientmanager, Svnurl URL, String commitmessage) {try {return clientmanager.getcommitclient (). Domkdi
		R (new svnurl[] {URL}, commitmessage);
		catch (Svnexception e) {logger.error (E.geterrormessage (), E);
	return null; /** * Imports A unversioned directory into a repository location denoted by a * destination URL * @param clie Ntmanager * @param localpath * A unversioned directory or Singal file that would be imported into a * RE
	 Pository;
	 * @param dsturl * A repository location where the local unversioned directory/file'll is * imported into * @param commitmessage * @param isrecursive recursive * @return/public static Svncommitinfo Importdirectory (SvnclienTmanager Clientmanager, File localpath, Svnurl dsturl, String commitmessage, Boolean isrecursive) {try {retur n clientmanager.getcommitclient (). Doimport (LocalPath, Dsturl, commitmessage, NULL, True, True, Svndepth.fromrecu
		RSE (isrecursive));
		catch (Svnexception e) {logger.error (E.geterrormessage (), E);
	return null; }/** * Puts directories and files under version control * @param clientmanager * Svnclientmanager * @param
			Wcpath * Work copy path/public static void AddEntry (Svnclientmanager clientmanager, File wcpath) {try { Clientmanager.getwcclient (). Doadd (New file[] {Wcpath}, True, False, False, Svndepth.infinity, False, False, TR
		UE);
		catch (Svnexception e) {logger.error (E.geterrormessage (), E);
	 }/** * Collects status information on a single Working Copy item * @param clientmanager * @param wcpath * Local item ' s path # @param remote * True to check up the status of the Item in the repository, * that'll tell if the local item was out-of-date (like '-u ' option in the SVN client ' s * ' SVN status ' command, otherwise false * @return * @throws svnexception/public static svnstatus Showstatus (SV
		Nclientmanager Clientmanager, File wcpath, Boolean remote) {svnstatus status = NULL;
		try {status = Clientmanager.getstatusclient (). Dostatus (Wcpath, remote);
		catch (Svnexception e) {logger.error (E.geterrormessage (), E);
	} return status; /** * Commit work copy ' s change to SVN * @param clientmanager * @param wcpath * Working copy paths which C Hanges are to is committed * @param keeplocks * Whether to unlock or not files in the repository * @param commitme Ssage * Commit Log message * @return * @throws svnexception/public static Svncommitinfo commit (Svnclientmana Ger Clientmanager, File Wcpath, Boolean keeplocks, String commitmessage) {try {return clientmanager.getcommitcli ENT (). DOcommit (new file[] {Wcpath}, keeplocks, commitmessage, NULL, NULL, FALSE, False, svndepth.infinity);
		catch (Svnexception e) {logger.error (E.geterrormessage (), E);
	return null;
     }/** * Updates A working copy (brings changes from the repository to the working copy). * @param clientmanager * @param wcpath * Working copy path * @param updatetorevision * Revision To update to * @param depth * Update Depth: directory, subdirectory, file * @return * @throws svnexception/Public Static long update (Svnclientmanager Clientmanager, File Wcpath, svnrevision updatetorevision, svndepth depth) {Svnup

		Dateclient updateclient = Clientmanager.getupdateclient ();

		* * Sets externals not to be ignored during the update/updateclient.setignoreexternals (FALSE); * * Returns the number of the revision Wcpath is updated to/try {return updateclient.doupdate (Wcpath, upd Atetorevision,depth, False, FAlse);
		catch (Svnexception e) {logger.error (E.geterrormessage (), E);
	return 0; /** * Recursively checks out a working copy from URL into Wcdir * @param clientmanager * @param URL * a re Pository location from where a Working Copy is checked out * @param revision * the desired revision King Copy to is checked out * @param destpath * The local path where the Working Copy would be placed * @param dep TH * Checkout depth, directory, subdirectory, file * @return * @throws svnexception/public static long checkout (Svnclientmanager CL Ientmanager, Svnurl URL, svnrevision revision, File destpath, svndepth depth) {svnupdateclient updateclient = Clien
		Tmanager.getupdateclient ();
		* * Sets externals not to be ignored during the checkout/Updateclient.setignoreexternals (FALSE); * * Returns the number of the revision at which the working copy is */try {return updateclient.docheckout (ur L, DestPath, revision, REVISION,DEpth, false);
		catch (Svnexception e) {logger.error (E.geterrormessage (), E);
	return 0; /** * Determines whether the path is a workspace * @param path * @return/public static Boolean isworkingcopy (File path) {if!path.
			Exists ()) {Logger.warn ("'" + Path + "' not exist! ');
		return false;
			try {if (null = Svnwcutil.getworkingcopyroot (path, false)) {return false;
		The catch (Svnexception e) {logger.error (E.geterrormessage (), E);
	return true; /** * Determine if a URL exists on SVN * @param URL * @return/public static Boolean isurlexist (Svnurl url,string username
			, String password) {try {svnrepository svnrepository = svnrepositoryfactory.create (URL);
			Isvnauthenticationmanager AuthManager = Svnwcutil.createdefaultauthenticationmanager (username, password);
			Svnrepository.setauthenticationmanager (AuthManager);
			Svnnodekind Nodekind = Svnrepository.checkpath ("",-1); return Nodekind = = Svnnodekind.none? 
		False:true; catch (Svnexception E) {e.printstacktrace ();
	return false; }

}



/** * Create Project Framework, SVN submit, update * @author Lena Yang */@Service ("Svnprojectservice") public class Svnprojectservice {Priva
	
	Te Logger Logger = Logger.getlogger (Svnprojectservice.class);
	
	The location of the item private String workspace = null;
	
	Private ResourceBundle RB = Resourcebundle.getbundle ("Application");
	SVN user name, password private String username = null;
	
	Private String password = null;
	
	Private String templete = null;
	
	
	@Resource (name= "Xcodeservice") private Xcodeservice Xcodeservice;
		private void Init () {String WebApp = System.getproperty ("Webapp.root");
		if (Null!=webapp&&!webapp.endswith ("/") &&!webapp.endswith ("\")) {WebApp = WebApp + "/";
		After publishing to the Web server, it is possible that the if (new File (WebApp + "WebContent") is webcontent. Exists ()) {WebApp = WebApp + "WebContent";
		} username = rb.getstring ("Svn.username");
		Password = rb.getstring ("Svn.password");
		Workspace = rb.getstring ("Project.svn.path");
	Templete = WebApp + "Templete"; } public SvnprojectserVice () {super ();
	Init (); /** * Create Project Framework * @param projects * Project * @return/public boolean Createprojectframe (Project project,
		List<string> tablenames) {if (project = null) {return false;	File src = new file (templete);	The location of the template project, file WS = new file (workspace);
		Work Copy if (!ws.exists ()) {ws.mkdirs ();
		The file Dest = new file (workspace + "/" + project.getname ());
		if (!dest.exists ()) {dest.mkdirs ();	} checkworkcopy (project);
		Determine workspace/Copy template project to workspace try {fileutils.copydirectory (src, dest);
			catch (IOException e) {logger.error (E.getmessage (), E);
		return false;
		
		//Modify the content in the. project file Editprojectfile (project);	
		
		Generate framework Code Xcodeservice.createbaseframewithdatasource (project,tablenames);	
		
		Submit to SVN COMMITPROJECTTOSVN (project);
	return true; /** * Modify the project file * @param project * @throws documentexception * @throws ioexception/@SuppressWarnings ("Unch ecked ") private void EDitprojectfile (Project project) {String Pro = workspace + "/" + project.getname () + "/";

		String settings = Pro + ". settings/"; 1.
		Modify. settings/org.eclipse.wst.common.component document document = NULL;
		try {document = Xmlreaderutil.getdocument (new File (Settings + "org.eclipse.wst.common.component"));
		catch (Documentexception e) {e.printstacktrace ();

		Element root = Document.getrootelement ();

		Root.element ("Wb-module"). Attribute ("Deploy-name"). SetValue (Project.getname ()); if (Root.element ("Wb-module"). Element ("property"). Attribute ("name"). GetValue (). Equals ("Java-output-path")) {R Oot.element ("Wb-module"). Element ("property"). Attribute ("value"). SetValue ("/" + project.getname () + "/build/classes
		"); } iterator<element> ITR = (iterator<element>) xmlreaderutil.getelements (document, "//wb-module//proper
		
		Ty "). iterator ();
			while (Itr.hasnext ()) {element element = Itr.next (); if ("Context-root").Equals (Element.attribute ("name"). GetValue ())) {Element.attribute ("value"). SetValue ("/" + project.getname ());

		}///write the modified value to Xmlreaderutil.writerxml (document, Settings + "org.eclipse.wst.common.component"); 2.
			Modify. Project try {document = Xmlreaderutil.getdocument (new File (pro +. Project));
			Xmlreaderutil.setelementtext (document, "//projectdescription", "Name", Project.getname ());
		Xmlreaderutil.writerxml (document, Pro + ". Project");
		catch (Documentexception e) {e.printstacktrace (); }/** * from SVN Update project to work copy * @param project * Project * @return/public boolean UPDATEPROJECTFROMSVN (
		Project Project {if (null = = Project | | | null = = rb.getstring ("Svn.url")) {return false;
		
        } project.setsvnurl (Rb.getstring ("Svn.url"));
		Svnclientmanager Clientmanager = SVNUTIL.AUTHSVN (Project.getsvnurl (), username, password); if (null = = Clientmanager) {logger.error ("SVN login error! >>> URL: "+ projecT.getsvnurl () + "Username:" + username + "Password:" + password);
		return false;
        
        //Register an update event handler clientmanager.getcommitclient (). setEventHandler (New Updateeventhandler ());
		Svnurl repositoryurl = null; try {//eg:http://svn.ambow.com/wlpt/bsp Repositoryurl = svnurl.parseuriencoded (Project.getsvnurl ()). AppendPath ("t
		runk/"+project.getname (), false);
			catch (Svnexception e) {logger.error (E.getmessage (), E);
		return false;
        File WS = new file (new file (workspace), project.getname ()); if (! Svnwcutil.isversioneddirectory (WS)) {svnutil.checkout (Clientmanager, Repositoryurl, Svnrevision.head, new File (wo
        Rkspace), svndepth.infinity);
        }else{svnutil.update (Clientmanager, WS, Svnrevision.head, svndepth.infinity);
	return true; /** * Submit Project to SVN * @param project * Project * @return/public boolean COMMITPROJECTTOSVN (Project project ) {SvnclientmanagerClientmanager = SVNUTIL.AUTHSVN (Project.getsvnurl (), username, password);
		
        Clientmanager.getcommitclient (). setEventHandler (New Commiteventhandler ());
        
        File Wc_project = new file (workspace + "/" + project.getname ());
		
		Checkversionddirectory (Clientmanager,wc_project);
		
		Svnutil.commit (Clientmanager, Wc_project, False, "Svnkit");
	return true; /** * Recursively checks for files that are not in version control and add to SVN * @param clientmanager * @param WC/private void Checkversionddirectory (SVNCL Ientmanager Clientmanager,file WC) {if (!
		Svnwcutil.isversioneddirectory (WC)) {svnutil.addentry (Clientmanager, WC); } if (Wc.isdirectory ()) {for (File sub:wc.listFiles ()) {if (Sub.isdirectory () && sub.getname (). Equals (". SVN"
				) {continue;
			} checkversionddirectory (Clientmanager,sub);
		}} private void Checkworkcopy (Project project) {Project.setsvnurl (rb.getstring ("Svn.url")); Svnclientmanager Clientmanager = SVNUTIL.AUTHSVN (project.getsVnurl (), username, password);	Svnurl repositoryurl = null;
					Trunk try {//eg:http://svn.ambow.com/wlpt/bsp Repositoryurl = svnurl.parseuriencoded (Project.getsvnurl ())
		. Appendpath ("trunk", false);
		catch (Svnexception e) {logger.error (E.getmessage (), E);
		The file WC = new file (workspace);
		
		File Wc_project = new file (workspace + "/" + project.getname ());	Svnurl projecturl = null;
		ProjectName try {projecturl = Repositoryurl.appendpath (Project.getname (), false);
		catch (Svnexception e) {logger.error (E.getmessage (), E); } if (! Svnutil.isworkingcopy (WC)) {if (! Svnutil.isurlexist (Projecturl,username,password)) {svnutil.checkout (Clientmanager, RepositoryURL,
			Svnrevision.head, WC, svndepth.empty);
			}else{svnutil.checkout (Clientmanager, Projecturl, Svnrevision.head, Wc_project, svndepth.infinity);
		}}else{svnutil.update (Clientmanager, WC, Svnrevision.head, svndepth.infinity);
 }
	}

}


The article topic is the Svnkit API operation. So it involves other classes that can be ignored. Svnkit has two sets of api,high level and low level. The high level is the operating copy of the work, working copy.

What I'm using here is high.


In the Checkworkcopy method, first check whether the currently specified path is a working copy. If yes, perform an update operation;

If not, there are two types of situations:

1. There is already a project named in this project on SVN, possibly SVN, but working copy has been deleted. Checkout the project down;

2. There is no this project on SVN. At this time checkout an empty thing. Svndepth.empty, just let our path become a working copy, a path appears under the. SVN directory, SVN files will not be checkout down. Because we may have a lot of projects on SVN. If the entire parent directory checkout down will be very slow and waste hard disk space.


To perform a commit operation with Svnkit, the process is as follows:

1. Ensure that the local path is a working copy. i.e. Checkworkcopy method

2. Woking copy may occur to add, update, delete and other changes in operation

3. Check working copy inside the file is under version control. i.e. Checkversionddirectory method

4. Perform a commit operation





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.