package com.zaranux.os.client.commands;
import com.zaranux.client.api.AsyncCallback;
import com.zaranux.client.java.io.BufferedReader;
import com.zaranux.client.java.io.FileInputStream;
import com.zaranux.client.java.io.InputStreamReader;
import com.zaranux.client.java.io.PrintStream;
public class cat extends Command {
public cat()
{
// super.addOption("n", false, "do not output the trailing newline");
}
@Override
public void execute( final AsyncCallback<Boolean> callback) {
/* if(_in == null)
{
super.reportError("echo.java: Input stream is null", callback);
}else */ if(System.out == null)
{
super.reportError("echo.java: Output stream is null", callback);
}else
{
String[] args = super.getArgs();
FileInputStream fis = new FileInputStream(args[0]);
InputStreamReader isr = new InputStreamReader(fis);
br = new BufferedReader( isr);
this.callback = callback;
//PrintedCallback pCallback = new PrintedCallback(this);
//printLines(new PrintedCallback(this));
//printAllLines(br, outPS,callback);
printAllLines(callback);
}
}
AsyncCallback<Boolean> callback;
BufferedReader br;
//PrintStream outPS;
void printLines(final PrintedCallback pcallback)
{
final cat _this = this;
br.readLine(new AsyncCallback<String>()
{
public void onSuccess(String line)
{
if(line != null)
{
System.out.println(line,new PrintedCallback(_this));
//new PrintedCallback(_this).onSuccess(true);
}else
{
callback.onSuccess(true);
}
}
public void onFailure(Throwable t)
{
callback.onFailure(t);
}
});
}
class PrintedCallback implements AsyncCallback<Boolean>
{
cat c;
PrintedCallback(cat c)
{
this.c = c;
}
public void onSuccess(Boolean b)
{
c.printLines(this);
}
public void onFailure(Throwable t)
{
}
}
StringBuffer sb = new StringBuffer();
private void printAllLines(final AsyncCallback<Boolean> callback)
{
br.readLine(new AsyncCallback<String>()
{
public void onSuccess(String line)
{
if(line != null)
{
sb.append(line + "\n");
printAllLines(callback);
}else
{
System.out.print(sb, new AsyncCallback<Boolean>()
{
public void onSuccess(Boolean b)
{
callback.onSuccess(b);
}
public void onFailure(Throwable t)
{
callback.onFailure(t);
}
});
callback.onSuccess(true);
}
}
public void onFailure(Throwable t)
{
callback.onFailure(t);
}
});
}
}