package com.zll.batch;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author zhaolulu
*
*/
public class Batch$SSH$IO$Manager {
private BatchInputStream inputStream;
private BatchOutputStream outputStream;
private List<BatchCommand> commands = new LinkedList<BatchCommand>();
private int mCmdIdx;
public InputStream getInputStream() {
return inputStream;
}
public OutputStream getOutputStream() {
return outputStream;
}
// Load the command from file.
public void loadCommands(InputStream pIns) {
inputStream = new BatchInputStream();
outputStream = new BatchOutputStream();
inputStream.setManager(this);
outputStream.setManager(this);
mCmdIdx = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(pIns));
String line;
try {
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) {
continue;
}
if (line.startsWith("#")) {
continue;
}
addCommandLine(line);
}
} catch (IOException e) {
e.printStackTrace();
}
mCmdIdx = 0;
}
public void loadCommand(List<String> commands) {
inputStream = new BatchInputStream();
outputStream = new BatchOutputStream();
inputStream.setManager(this);
outputStream.setManager(this);
mCmdIdx = 0;
for (String command : commands) {
if (command.isEmpty()) {
continue;
}
if (command.startsWith("#")) {
continue;
}
addCommandLine(command);
}
mCmdIdx = 0;
}
static Pattern cmdptn = Pattern.compile("\\[([^\\s\\]]*)\\]([^\\s\\[]*)\\[([^\\]]*)\\]");
private void addCommandLine(String pLine) {
Matcher m = cmdptn.matcher(pLine);
if (m.find()) {
System.out.println("load command: " + pLine);
addCommand(m.group(2), m.group(1), m.group(3));
}
}
private void addCommand(String pCmd, String pEnds, String pContent) {
commands.add(new BatchCommand(pCmd, pEnds, pContent, mCmdIdx));
mCmdIdx++;
}
public BatchCommand getNextCommand() {
if (mCmdIdx >= commands.size()) {
return null;
}
synchronized (commands) {
try {
commands.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
return commands.get(mCmdIdx++);
}
}
public BatchCommand getCommand() {
if (mCmdIdx >= commands.size()) {
return null;
}
synchronized (commands) {
return commands.get(mCmdIdx);
}
}
public void enableSend() {
synchronized (commands) {
commands.notify();
}
}
}
评论0