8/26/2008

用JAVA操作ClearCase

本文关注怎么用JAVA处理ClearCase(ClearCase是rational公司开发的配置管理工具,了解详情点这里).在了解了怎么用JAVA.LANG.RUNTIME以后,主要的事情还是输入输出流,同步,以及字符串的处理.
下面这段代码演示了如何调用ClearCase的命令行:
[coolcode,lang="java",linenum="off"]
public String exec(String command) throws IOException {
Process process = Runtime.getRuntime().exec(command);

StringWriter outWriter = new StringWriter();
StringWriter errWriter = new StringWriter();
ProcessOutputReader outReader = new ProcessOutputReader(
process.getInputStream(),
outWriter);
ProcessOutputReader errReader = new ProcessOutputReader(
process.getErrorStream(),
errWriter);

Thread outReaderThread = new Thread(outReader);
Thread errReaderThread = new Thread(errReader);
outReaderThread.start();
errReaderThread.start();

synchronized (outReaderThread) {
if (outReaderThread.isAlive()) {
try {
outReaderThread.wait();
} catch (InterruptedException ie) {}
}
}
synchronized (errReaderThread) {
if (errReaderThread.isAlive()) {
try {
errReaderThread.wait();
} catch (InterruptedException ie) {}
}
}

String out = outWriter.toString();
String err = errWriter.toString();

return out
+(out.length() > 0 && err.length() > 0 ? "\n":"")
+err;
}
[/coolcode]
其中ProcessOutputReader类的定义:
[coolcode,lang="java",linenum="off"]
class ProcessOutputReader implements Runnable {
private InputStream _readFrom;
private Writer _writeTo;
ProcessOutputReader( InputStream readFrom, Writer writeTo) {
_readFrom = readFrom;
_writeTo = writeTo;
}
public void run() {
InputStreamReader bir = new InputStreamReader( _readFrom );
char[] ca = new char[100];
int numRead = 0;while ( numRead != -1 ) {

try {
numRead = bir.read(ca);
if ( numRead > 0 ) {
_writeTo.write(ca, 0, numRead);
}
} catch ( IOException e ) {
numRead = -1;
}
}
}
}
[/coolcode]
调用以上的方法:
[coolcode,lang="java",linenum="off"]
public static void main(String[] args) throws Exception {
RuntimeExec re = new RuntimeExec();
String result = re.exec("cleartool ls -s /XX/XX/XX...");
String result1=re.exec("cleartool lsvtr -g /XX/XX/XX...");
System.out.println(result);
System.out.println(result1);
}
[/coolcode]
上面代码的几点说明:
1.Runtime.getRuntime().exec(command) 通过JAVA提供的Runtime直接运行ClearCase的命令.Runtime是JAVA提供的,用于当前应用程序和运行环境交互,getRuntime()方法返回的就是当前Runtime实例.
2./XX/XX/XX... 代表目标文件夹或者文件.
3.cleartool lsvtr -g这个ClearCase命令可以打开图形界面.

如果想要获得Config Spec(不知道什么是Config Spec?点击这里了解),则应该这样调用:
[coolcode,lang="java",linenum="off"]
String catcs = re.exec("cleartool catcs");
[/coolcode]
在取得Config Spec后,剩下的都是字符串操作.

0 评论:

发表评论