JAVA CVS Client代码收集org-netbeans-lib-cvsclient

樊桐
2023-12-01

代码来自互联网。

 http://blog.csdn.net/strawbingo/article/details/6301546

1.下载http://javacvs.netbeans.org/files/documents/51/640/org-netbeans-lib-cvsclient.jar

2.把jar包加入到classpath。相信大家对cvs都是比较熟悉的了,架设cvsnt的步骤很简单,网上也有很多文章,我就不多赘述了

3.为了帮助理解,这里对这些类的使用方式做个简单介绍,下面就是具体的程序代码,稍后可以细看。netbean的cvs包里包含这样几个重要的类,Client,MessageEvent,多种Command对象。client对象是来负责连接cvs server,messageEvent是来接收cvs server 传回的信息,当cvs server做出response的时候,就会出发messageEvent事件。多种Command对象,一种对象对应一种cvs command,例如CommitCommand对应的就是cvs的Commit命令,然后命令后附带的参数通过设置此对象的类属性变量来实现。执行命令的时候将Command对象传入Client方法的executeCommand来执行这些命令。

4.这是一个自己封装的cvsclient对象,包含了比较常用的几个cvs命令,代码如下:

public class CVSClient {
 /** Cvs clinet instance used to communicate with cvs server */
 private Client cvsclient;
 /** Cvs connect string */
 private CVSRoot cvsroot;
 /** Connection instance to keep connect with cvs server */
 private Connection connection;
 /** Global options to store the requied parameter for cvs server */
 private GlobalOptions globalOptions;
 /** The local path on ur local machine */
 private String localPath;
 /**
  * Inner class extend CVSAdapter <br>
  * <p>used to get and send message of the CVS server</p>
  * */
 class BasicListener extends CVSAdapter {
  /**
   * Stores a tagged line
   */
  private final StringBuffer taggedLine = new StringBuffer();
  /**
   * Called when the server wants to send a message to be displayed to the
   * user. The message is only for information purposes and clients can
   * choose to ignore these messages if they wish.
   * 
   * @param e
   *            the event
   */
  public void messageSent(MessageEvent e) {
   String line = e.getMessage();
   PrintStream stream = e.isError() ? System.err : System.out;
   if (e.isTagged()) {
    String message = MessageEvent.parseTaggedMessage(taggedLine,
      "Daniel Six");
    // if we get back a non-null line, we have something
    // to output. Otherwise, there is more to come and we
    // should do nothing yet.
    if (message != null) {
     stream.println(message);
    }
   } else {
    stream.println(line);
   }
  }
 }
    /**
     * Default constructor allows to construct CVSRoot from Properties object.
     * The names are exactly the same as the attribute names in this class.
     */
 public CVSClient() {
 }
 
    /**
     * Breaks the string representation of CVSClient into it's components:
     *
     * The valid format (from the cederqvist) is:
     *
     * :method:[[user][:password]@]hostname[:[port]]/path/to/repository
     *
     * e.g. :pserver;username=anonymous;hostname=localhost:/path/to/repository
     */ 
 public CVSClient(String connectionString) {
  cvsroot = CVSRoot.parse(connectionString);
 }
 /**
  * Get the localPath
  * @return localPath the local path to get project from the CVS server
  * */
 public String getLocalPath() {
  return localPath;
 }
 /**
  * Set the localPath
  * 
  * */
 public void setLocalPath(String localPath) {
  this.localPath = localPath;
 }
 
 /**
  * Parse the CVSROOT string into CVSRoot object. 
  * 
     * The valid format (from the cederqvist) is:
     *
     * :method:[[user][:password]@]hostname[:[port]]/path/to/repository
     *
     * e.g. :pserver;username=anonymous;hostname=localhost:/path/to/repository
  */
 public void createConnection(String connectionString) {
  cvsroot = CVSRoot.parse(connectionString);
 }
 /**
  * Open connection to the cvs server <br>
  * 
  * @return connection to cvs server
  * @throws AuthenticationException
  * @throws CommandAbortedException
  */
 public Connection openConnection() throws AuthenticationException,
   CommandAbortedException {
  connection = ConnectionFactory.getConnection(cvsroot);
  connection.open();
  return connection;
 }
 
 /**
  * Close connection to the cvs server <br>
  * */
 public void closeConnection() throws IOException{
  connection.close();
 }
 
 /**
  * <p>Excute cvs command</p>
  * 
  * @param command to be excute by the cliet
  * @throws AuthenticationException
  * @throws CommandAbortedException
  * @throws IOException
  * @throws CommandException
  */
 public void excute(Command command) throws AuthenticationException,
   CommandAbortedException, IOException, CommandException {
  cvsclient = new Client(connection, new StandardAdminHandler());
  cvsclient.setLocalPath(localPath);
  globalOptions = new GlobalOptions();
  globalOptions.setCVSRoot("d:/client/java");
  cvsclient.getEventManager().addCVSListener(new BasicListener());
  //put the command to the console
  System.out.println("***Command***"+command.getCVSCommand());
  cvsclient.executeCommand(command, globalOptions);
 }
 /**
  * <p>Called when need add files</p>
  * @param files that indicate to be added
  * @return command of add files
  */
 public Command add(String[] files) {
  AddCommand command = new AddCommand();
  command.setBuilder(null);
  for (int i = 0; i < files.length; i++) {
   command.setFiles(new File[] { new File(files[i]) });
  }
  return command;
 }
 /**
  * Called when need commit all files under the local path
  * @return command command of commit files
  */
 public Command commit() {
  CommitCommand command = new CommitCommand();
  command.setBuilder(null);
  command.setForceCommit(true);
  command.setRecursive(true);
  return command;
 }
 /**
  * Called when need commit files
  * @param files need to be commit
  * @return command command of commit files
  * */
 public Command commit(String[] files) {
  CommitCommand command = new CommitCommand();
  for (int i = 0; i < files.length; i++) {
   command.setFiles(new File[] { new File(files[i])});
  }
  command.setBuilder(null);
  command.setForceCommit(true);
  command.setRecursive(true);
  return command;
 }
 /**
  * Called when need update the certain files
  * @param files need to be update
  * @return command command of update files and directoris
  * */
 public Command update(String[] files) {
  UpdateCommand command = new UpdateCommand();
  //fetch files from the array
  for (int i = 0; i < files.length; i++) {
   command.setFiles(new File[] { new File(files[i]) });
  }
  command.setBuilder(null);
  command.setRecursive(true);
  command.setBuildDirectories(true);
  command.setPruneDirectories(true);
  return command;
 }
 /**
  * Called to show the history list since given date
  * @param date Date of the history
  *@return command command show history list
  * */
 public Command historysincedate(String date){
  HistoryCommand command=new HistoryCommand();
  //Format is yyyymmdd e.g 20070205
  command.setSinceDate(date);
  return command;
 }
 
 /**
  *Called to show the history list since given version
  *@param reversion reversion of the history
  *@return command command show history list 
  **/
 public Command historysincerRevision(String reversion){
  //Init command
  HistoryCommand command=new HistoryCommand();
  //set parameters
  command.setSinceRevision(reversion);
  return command;
 }
 
 /**
  * Called to show the different between two versions
  * @param files the files to compare with
  * @param revision1 one revision 
  * @param revision2 another revision 
  * @return
  * */
 public Command diffbyreveision(String[] files,String revision1,String revision2){
  //Inite command
  DiffCommand command=new DiffCommand();
  //Set parameters
  for(int i=0;i<files.length;i++){
   command.setFiles(new File[]{new File(files[i])});
  }
  command.setRevision1(revision1);
  command.setRevision2(revision2);
  return command;
 }
 
 /**
  * Show difference between of the file that with different date
  * @param files an array of files path
  * @param date1 one date
  * @param date2 another date 
  * @return command command of show difference between files
  * */
 public Command diffbydate(String[] files,String date1,String date2){
  //Init command
  DiffCommand command=new DiffCommand();
  //Set parameters
  for(int i=0;i<files.length;i++){
   command.setFiles(new File[]{new File(files[i])});
  }
  //Format is yyyymmdd e.g 20070205
  command.setBeforeDate1(date1);
  command.setBeforeDate2(date2);
  return command;
 }
 
 /**
  * Check out the module
  * @param modulename name of the module that to be checked out
  * @return command command of check out the module
  * */
 public Command checkout(String modulename){
  //Init new command
  CheckoutCommand command=new CheckoutCommand();
  //Set paramaters
  command.setModule(modulename);
  command.setRecursive(true);
  return command;
 }
 
 /**
  * Check out the module
  * @param modulename name of the module that to be checked out
  * @return command command of check out the module
  * */
 public Command checkouttoOutput(String modulename){
  //Init new command
  CheckoutCommand command=new CheckoutCommand();
  //Set paramaters
  command.setModule(modulename);
  command.setPipeToOutput(true);
  command.setRecursive(true);
  return command;
 } 
}

如下是一个小的demo来使用这个client类来执行cvs的客户端操作:

public class CVSDemo {
 public static void main(String []args) throws AuthenticationException, IOException, CommandException{
  
  /* <p>set the connection string of the cvs server</p>
   * connect string provide protocol,hostname,user,password,repository
   * e.g:":pserver:ibmuser:icmadmin@localhost:d:/root"
   */
  CVSClient cvsclient=new CVSClient(":pserver:ibmuser:icmadmin@localhost:d:/root");
  //open the connection
  cvsclient.openConnection();
  //set the local directory
  cvsclient.setLocalPath("d:/client/");
  /*Demo of excute command as follow*/
  //add
  //cvsclient.excute(cvsclient.add(new String[]{"D:/client/java/abc/abc.java"}));
  
  //commit
  //cvsclient.excute(cvsclient.commit(new String[]{"D:/client/java/abc/abc.java"}));
  
  //check out
  //cvsclient.excute(cvsclient.checkout("cvsroot"));
  cvsclient.excute(cvsclient.checkouttoOutput("java"));
  
  //update
  //cvsclient.excute(cvsclient.update(new String[]{"D:/client/"}));
  
  //diff
  //cvsclient.excute(cvsclient.diffbyreveision(new String[]{"d:/client/java/abc/abc.java"}, "1.1", "1.2"));
  //cvsclient.excute(cvsclient.diffbydate(new String[]{"D:/client/java/abc/abc.java"}, "20070206", "20070207"));
  
  //history
  //cvsclient.excute(cvsclient.historysincedate("20070201"));
  //cvsclient.excute(cvsclient.historysincerRevision("1.1"));
  cvsclient.closeConnection();
 }
}

Case 2:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

import org.netbeans.lib.cvsclient.CVSRoot;
import org.netbeans.lib.cvsclient.Client;
import org.netbeans.lib.cvsclient.admin.Entry;
import org.netbeans.lib.cvsclient.admin.StandardAdminHandler;
import org.netbeans.lib.cvsclient.command.Builder;
import org.netbeans.lib.cvsclient.command.CommandAbortedException;
import org.netbeans.lib.cvsclient.command.CommandException;
import org.netbeans.lib.cvsclient.command.GlobalOptions;
import org.netbeans.lib.cvsclient.command.checkout.CheckoutCommand;
import org.netbeans.lib.cvsclient.command.commit.CommitCommand;
import org.netbeans.lib.cvsclient.command.diff.DiffCommand;
import org.netbeans.lib.cvsclient.command.diff.DiffInformation;
import org.netbeans.lib.cvsclient.command.diff.SimpleDiffBuilder;
import org.netbeans.lib.cvsclient.command.log.LogCommand;
import org.netbeans.lib.cvsclient.commandLine.BasicListener;
import org.netbeans.lib.cvsclient.connection.AuthenticationException;
import org.netbeans.lib.cvsclient.connection.Connection;
import org.netbeans.lib.cvsclient.connection.ConnectionFactory;
import org.netbeans.lib.cvsclient.event.EventManager;

import junit.framework.TestCase;


public class CVSClientTest extends TestCase{
	/** Cvs clinet instance used to communicate with cvs server */
	 private static Client cvsclient = null;
	 
	 /** Cvs connect string */
	 private static CVSRoot cvsroot = null;
	 
	 /** Connection instance to keep connect with cvs server */
	 private static Connection connection = null;
	 
	 /** Global options to store the requied parameter for cvs server */
	 private static GlobalOptions globalOptions = null;
	 
	 /** The local path on ur local machine */
	 private static String LOCALPATH ="d:/cvs_checkout";

	 final static String  CONNECTION_STRING = ":pserver:test:8888@192.168.1.125:/home/cvsroot";
	  		
	 public Connection openConnection() throws AuthenticationException,
	  IOException, CommandException {
		 cvsroot = CVSRoot.parse(CONNECTION_STRING);
		 connection = ConnectionFactory.getConnection(cvsroot);
		 cvsclient=new Client(connection, new StandardAdminHandler());
		 cvsclient.setLocalPath(LOCALPATH);
		 cvsclient.getEventManager().addCVSListener(new BasicListener());
		 connection.open();
		 
		 globalOptions=new GlobalOptions();
		 globalOptions.setCVSRoot(CVSRoot.parse(CONNECTION_STRING).getRepository());
		
		 return connection;
}
	 
	 public Client getCvsclient() throws AuthenticationException, IOException, CommandException{
		 if(cvsclient==null){
			 openConnection();			 
		 }
			 return cvsclient;
		 
	 }
	 
	 public void closeConnection() throws IOException{
		 if(connection!=null){
			 connection.close();
		 }
	 }
	 //重定向输出流
	 public static void systemSetOut() {
			try {
				File test = new File("D:/test.txt ");
				test.createNewFile();
				PrintStream out = new PrintStream(new FileOutputStream(test));
				//PrintStream out = new PrintStream(new String());
				System.setOut(out);
			} catch (Exception e) {
			}

		}
	
	/** Start test...*/
	 
	public void testLogCommand() throws CommandAbortedException,
		CommandException, AuthenticationException, IOException {
		openConnection();
		LogCommand logCommand = new LogCommand();
		logCommand.setFiles(new File[] { new File(
				"d:/cvs_checkout/IM800KBS/src/web/com/syni/im800/kb/attendant/webapp/action/KbsEntryAction.java") });
		cvsclient.executeCommand(logCommand, globalOptions);
		closeConnection();
	}
	
	public void testCheckoutCommand() throws AuthenticationException, IOException, CommandException{
		openConnection();
		CheckoutCommand checkoutCommand  =new CheckoutCommand();
		checkoutCommand.setModule("IM800KBS");
		//只输出信息不输出文件
		//checkoutCommand.setPipeToOutput(true);
		checkoutCommand.setRecursive(true);
		checkoutCommand.setCheckoutByRevision("v1-3-1-1000");
		cvsclient.executeCommand(checkoutCommand, globalOptions);
		closeConnection();
	}
	
	public void testCommitCommand() throws AuthenticationException, IOException, CommandException{
		openConnection();
		CommitCommand commitCommand = new CommitCommand();
		File files[] = {
				new File("d:/cvs_checkout/IM800KBS/src/web/com/syni/im800/kb/attendant/webapp/action/Abc.java")};
		commitCommand.setFiles(files);
		commitCommand.setBuilder(null);
		commitCommand.setForceCommit(true);
		commitCommand.setRecursive(true);
		cvsclient.executeCommand(commitCommand, globalOptions);
		closeConnection();
	}
	
	public void testDiffCommand() throws AuthenticationException, IOException, CommandException{
		systemSetOut();
		openConnection();
		DiffCommand diffCommand = new DiffCommand();
		/** 
		 * 某个文件两个不同版本的比较
		 * setRevision1:设置某一个版本,如果不设置就是拿本地的文件做比较
		 * setRevision2:设置另一个版本
		 * */
	//	diffCommand.setRevision1("1.64.2.229");
		diffCommand.setRevision2("1.64.2.230");
		diffCommand.setFiles(new File[]{new File(
				  "d:/cvs_checkout/IM800KBS/src/web/com/syni/im800/kb/attendant/webapp/action/KbsEntryAction.java")});	
		cvsclient.executeCommand(diffCommand, globalOptions);				
		closeConnection();
	}
	
	public void testDiffInformation() throws AuthenticationException, IOException, CommandException{
		openConnection();
		EventManager em = new EventManager(cvsclient);
		em.addCVSListener(new BasicListener());
		DiffCommand diffCommand = new DiffCommand();
		diffCommand.setFiles(new File[]{new File(			  
				"d:/cvs_checkout/IM800KBS/src/web/com/syni/im800/kb/attendant/webapp/action/KbsEntryAction.java")});			
	//	diffCommand.setRevision1("1.64.2.229");
		diffCommand.setRevision2("1.64.2.230");
		SimpleDiffBuilder sdb = new SimpleDiffBuilder(em,diffCommand);	
	//	cvsclient.executeCommand(diffCommand, globalOptions);
		DiffInformation diffInfo = sdb.createDiffInformation();
		diffInfo.setRepositoryFileName("d:/cvs_checkout/IM800KBS/src/web/com/syni/im800/kb/attendant/webapp/action/KbsEntryAction.java");
		diffInfo.setLeftRevision("1.64.2.229");
		diffInfo.setRightRevision("1.64.2.230");
		
		System.out.println(diffInfo.getFirstChange());
		
		
		
	/*	File diffFile = new File("d:/diff.txt");
		diffFile.createNewFile();	
		diffInfo.setFile(diffFile);
		diffInfo.setRepositoryFileName("d:/cvs_checkout/IM800KBS/src/web/com/syni/im800/kb/attendant/webapp/action/KbsEntryAction.java");
		diffInfo.setLeftRevision("1.64.2.220");
		diffInfo.setRightRevision("1.64.2.230");*/

		
		closeConnection();
	}
	
	
	public void testEntry()throws AuthenticationException, IOException, CommandException{
		systemSetOut();
		openConnection();
		File file = new File
				("d:/cvs_checkout/IM800KBS/src/web/com/syni/im800/kb/attendant/webapp/form/KbsEntryForm.java");
		Entry entry = cvsclient.getEntry(file);
		System.out.println(entry.getRevision());
		closeConnection();
	}
}

 

转载于:https://my.oschina.net/jerval/blog/1827298

 类似资料: