在java中快速调用第三方软件
2011-11-04 10:21
369 查看
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Adopted by John Xing for Nutch Project from
* http://blog.fivesight.com/prb/space/Call+an+External+Command+from+Java/,
* which explains the code in detail.
* [Original author is moving his site to http://mult.ifario.us/ -peb]
*
* Comments by John Xing on 20040621:
* (1) EDU.oswego.cs.dl.util.concurrent.* is in j2sdk 1.5 now.
* Modifications are needed if we move to j2sdk 1.5.
* (2) The original looks good, not much to change.
*
* This code is in the public domain and comes with no warranty.
*/
package org.apache.nutch.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class CommandRunner {
private boolean _waitForExit = true;
private String _command;
private int _timeout = 10;
private InputStream _stdin;
private OutputStream _stdout;
private OutputStream _stderr;
private static final int BUF = 4096;
private int _xit;
private Throwable _thrownError;
private CyclicBarrier _barrier;
public int getExitValue() {
return _xit;
}
public void setCommand(String s) {
_command = s;
}
public String getCommand() {
return _command;
}
public void setInputStream(InputStream is) {
_stdin = is;
}
public void setStdOutputStream(OutputStream os) {
_stdout = os;
}
public void setStdErrorStream(OutputStream os) {
_stderr = os;
}
public void evaluate() throws IOException {
this.exec();
}
/**
*
* @return process exit value (return code) or -1 if timed out.
* @throws IOException
*/
public int exec() throws IOException {
Process proc = Runtime.getRuntime().exec(_command);
_barrier = new CyclicBarrier(3 + ((_stdin != null) ? 1 : 0));
PullerThread so = new PullerThread("STDOUT", proc.getInputStream(),
_stdout);
so.setDaemon(true);
so.start();
PullerThread se = new PullerThread("STDERR", proc.getErrorStream(),
_stderr);
se.setDaemon(true);
se.start();
PusherThread si = null;
if (_stdin != null) {
si = new PusherThread("STDIN", _stdin, proc.getOutputStream());
si.setDaemon(true);
si.start();
}
boolean _timedout = false;
long end = System.currentTimeMillis() + _timeout * 1000;
//
try {
if (_timeout <= 0) {
_barrier.await();
} else {
_barrier.await(_timeout, TimeUnit.SECONDS);
}
} catch (TimeoutException ex) {
_timedout = true;
} catch (BrokenBarrierException bbe) {
/* IGNORE */
} catch (InterruptedException e) {
/* IGNORE */
}
// tell the io threads we are finished
if (si != null) {
si.interrupt();
}
so.interrupt();
se.interrupt();
_xit = -1;
if (!_timedout) {
if (_waitForExit) {
do {
try {
Thread.sleep(1000);
_xit = proc.exitValue();
} catch (InterruptedException ie) {
if (Thread.interrupted()) {
break; // stop waiting on an interrupt for this
// thread
} else {
continue;
}
} catch (IllegalThreadStateException iltse) {
continue;
}
break;
} while (!(_timedout = (System.currentTimeMillis() > end)));
} else {
try {
_xit = proc.exitValue();
} catch (IllegalThreadStateException iltse) {
_timedout = true;
}
}
}
if (_waitForExit) {
proc.destroy();
}
return _xit;
}
public Throwable getThrownError() {
return _thrownError;
}
private class PumperThread extends Thread {
private OutputStream _os;
private InputStream _is;
private boolean _closeInput;
protected PumperThread(String name, InputStream is, OutputStream os,
boolean closeInput) {
super(name);
_is = is;
_os = os;
_closeInput = closeInput;
}
public void run() {
try {
byte[] buf = new byte[BUF];
int read = 0;
while (!isInterrupted() && (read = _is.read(buf)) != -1) {
if (read == 0)
continue;
_os.write(buf, 0, read);
_os.flush();
}
} catch (InterruptedIOException iioe) {
// ignored
} catch (Throwable t) {
_thrownError = t;
} finally {
try {
if (_closeInput) {
_is.close();
} else {
_os.close();
}
} catch (IOException ioe) {
/* IGNORE */
}
}
try {
_barrier.await();
} catch (InterruptedException ie) {
/* IGNORE */
} catch (BrokenBarrierException bbe) {
/* IGNORE */
}
}
}
private class PusherThread extends PumperThread {
PusherThread(String name, InputStream is, OutputStream os) {
super(name, is, os, false);
}
}
private class PullerThread extends PumperThread {
PullerThread(String name, InputStream is, OutputStream os) {
super(name, is, os, true);
}
}
public int getTimeout() {
return _timeout;
}
public void setTimeout(int timeout) {
_timeout = timeout;
}
public boolean getWaitForExit() {
return _waitForExit;
}
public void setWaitForExit(boolean waitForExit) {
_waitForExit = waitForExit;
}
public static void main(String[] args) throws Exception {
}
}
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Adopted by John Xing for Nutch Project from
* http://blog.fivesight.com/prb/space/Call+an+External+Command+from+Java/,
* which explains the code in detail.
* [Original author is moving his site to http://mult.ifario.us/ -peb]
*
* Comments by John Xing on 20040621:
* (1) EDU.oswego.cs.dl.util.concurrent.* is in j2sdk 1.5 now.
* Modifications are needed if we move to j2sdk 1.5.
* (2) The original looks good, not much to change.
*
* This code is in the public domain and comes with no warranty.
*/
package org.apache.nutch.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class CommandRunner {
private boolean _waitForExit = true;
private String _command;
private int _timeout = 10;
private InputStream _stdin;
private OutputStream _stdout;
private OutputStream _stderr;
private static final int BUF = 4096;
private int _xit;
private Throwable _thrownError;
private CyclicBarrier _barrier;
public int getExitValue() {
return _xit;
}
public void setCommand(String s) {
_command = s;
}
public String getCommand() {
return _command;
}
public void setInputStream(InputStream is) {
_stdin = is;
}
public void setStdOutputStream(OutputStream os) {
_stdout = os;
}
public void setStdErrorStream(OutputStream os) {
_stderr = os;
}
public void evaluate() throws IOException {
this.exec();
}
/**
*
* @return process exit value (return code) or -1 if timed out.
* @throws IOException
*/
public int exec() throws IOException {
Process proc = Runtime.getRuntime().exec(_command);
_barrier = new CyclicBarrier(3 + ((_stdin != null) ? 1 : 0));
PullerThread so = new PullerThread("STDOUT", proc.getInputStream(),
_stdout);
so.setDaemon(true);
so.start();
PullerThread se = new PullerThread("STDERR", proc.getErrorStream(),
_stderr);
se.setDaemon(true);
se.start();
PusherThread si = null;
if (_stdin != null) {
si = new PusherThread("STDIN", _stdin, proc.getOutputStream());
si.setDaemon(true);
si.start();
}
boolean _timedout = false;
long end = System.currentTimeMillis() + _timeout * 1000;
//
try {
if (_timeout <= 0) {
_barrier.await();
} else {
_barrier.await(_timeout, TimeUnit.SECONDS);
}
} catch (TimeoutException ex) {
_timedout = true;
} catch (BrokenBarrierException bbe) {
/* IGNORE */
} catch (InterruptedException e) {
/* IGNORE */
}
// tell the io threads we are finished
if (si != null) {
si.interrupt();
}
so.interrupt();
se.interrupt();
_xit = -1;
if (!_timedout) {
if (_waitForExit) {
do {
try {
Thread.sleep(1000);
_xit = proc.exitValue();
} catch (InterruptedException ie) {
if (Thread.interrupted()) {
break; // stop waiting on an interrupt for this
// thread
} else {
continue;
}
} catch (IllegalThreadStateException iltse) {
continue;
}
break;
} while (!(_timedout = (System.currentTimeMillis() > end)));
} else {
try {
_xit = proc.exitValue();
} catch (IllegalThreadStateException iltse) {
_timedout = true;
}
}
}
if (_waitForExit) {
proc.destroy();
}
return _xit;
}
public Throwable getThrownError() {
return _thrownError;
}
private class PumperThread extends Thread {
private OutputStream _os;
private InputStream _is;
private boolean _closeInput;
protected PumperThread(String name, InputStream is, OutputStream os,
boolean closeInput) {
super(name);
_is = is;
_os = os;
_closeInput = closeInput;
}
public void run() {
try {
byte[] buf = new byte[BUF];
int read = 0;
while (!isInterrupted() && (read = _is.read(buf)) != -1) {
if (read == 0)
continue;
_os.write(buf, 0, read);
_os.flush();
}
} catch (InterruptedIOException iioe) {
// ignored
} catch (Throwable t) {
_thrownError = t;
} finally {
try {
if (_closeInput) {
_is.close();
} else {
_os.close();
}
} catch (IOException ioe) {
/* IGNORE */
}
}
try {
_barrier.await();
} catch (InterruptedException ie) {
/* IGNORE */
} catch (BrokenBarrierException bbe) {
/* IGNORE */
}
}
}
private class PusherThread extends PumperThread {
PusherThread(String name, InputStream is, OutputStream os) {
super(name, is, os, false);
}
}
private class PullerThread extends PumperThread {
PullerThread(String name, InputStream is, OutputStream os) {
super(name, is, os, true);
}
}
public int getTimeout() {
return _timeout;
}
public void setTimeout(int timeout) {
_timeout = timeout;
}
public boolean getWaitForExit() {
return _waitForExit;
}
public void setWaitForExit(boolean waitForExit) {
_waitForExit = waitForExit;
}
public static void main(String[] args) throws Exception {
}
}
相关文章推荐
- java调用com对第三方软件进行操作
- httpfetch 快速使用-一款java语言编写优雅的http接口调用组件
- java暑假软件快速上手集训班开课了
- Java WebService 简单实例、调用第三方提供的webService服务
- java应用中,调用第三方api如何处理异常(系统异常、操作异常等等)
- Java调用C/C++编写的第三方dll动态链接库(非native API)--- JNI
- Java 不使用第三方类库实现REST调用
- Chap5:使用JNI技术实现java程序调用第三方dll(c/c++)文件的功能
- 通过用第三方包jpype在Python中调用Java代码
- 快速掌握PHP调用Java语言方法
- java调用c++的第三方dll动态库详解
- Android逆向之一键将public中的资源ID转换成静态java类以供快速调用资源文件
- Java调用C/C++编写的第三方dll动态链接库(非native API)--- JNI
- Matlab中调用第三方Java代码
- 关于 调用 JNI JAR 的说明和注意事项,调用第三方 JAR SDK 和 翻译 安卓 JAVA 代码 的说明 V2015.6.10
- Java调用C/C++编写的第三方dll动态链接库(非native API)--- JNI
- java校验身份证信息-调用第三方(聚合API)
- java调用第三方包的例子
- 使用Python调用Java第三方库
- Java后台调用第三方支付接口(易宝支付)