auto-format printf if no format is specified

This commit is contained in:
Doug MacEachern 2005-07-24 18:08:04 +00:00
parent 707cb02db1
commit bccdccdee0

View File

@ -2,8 +2,10 @@ package net.hyperic.sigar.cmd;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import net.hyperic.sigar.Sigar;
@ -35,6 +37,7 @@ public abstract class SigarCommandBase
private CollectionCompleter completer;
private Collection completions = new ArrayList();
private PrintfFormat formatter;
private ArrayList printfItems = new ArrayList();
public SigarCommandBase(Shell shell) {
this.shell = shell;
@ -43,7 +46,6 @@ public abstract class SigarCommandBase
this.sigar = shell.getSigar();
this.proxy = shell.getSigarProxy();
//provide simple way for handlers to implement tab completion
this.completer = new CollectionCompleter(shell);
}
@ -70,7 +72,14 @@ public abstract class SigarCommandBase
}
public void printf(Object[] items) {
println(getFormatter().sprintf(items));
PrintfFormat formatter = getFormatter();
if (formatter == null) {
//see flushPrintfItems
this.printfItems.add(items);
}
else {
println(formatter.sprintf(items));
}
}
public void printf(List items) {
@ -86,7 +95,49 @@ public abstract class SigarCommandBase
}
}
private void flushPrintfItems() {
if (this.printfItems.size() == 0) {
return;
}
//no format was specified, just line up the columns
int[] max = null;
for (Iterator it=this.printfItems.iterator();
it.hasNext();)
{
Object[] items = (Object[])it.next();
if (max == null) {
max = new int[items.length];
Arrays.fill(max, 0);
}
for (int i=0; i<items.length; i++) {
int len = items[i].toString().length();
if (len > max[i]) {
max[i] = len;
}
}
}
StringBuffer format = new StringBuffer();
for (int i=0; i<max.length; i++) {
format.append("%-" + max[i] + "s");
if (i < max.length-1) {
format.append(" ");
}
}
for (Iterator it=this.printfItems.iterator();
it.hasNext();)
{
printf(format.toString(), (Object[])it.next());
}
this.printfItems.clear();
}
public void flush() {
flushPrintfItems();
try {
this.shell.performPaging(new StaticPageFetcher(this.output));
} catch(PageFetchException e) {