package org.lucci.madhoc.script;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Date;
import java.util.Collections;
import java.util.List;
import java.util.Vector;
import org.lucci.madhoc.Version;
import org.lucci.math.relation.Function;
import org.lucci.math.relation.NumericFunction;
import org.lucci.text.TextUtilities;
public class Batch
{
private int verboseLevel = 0;
public Batch()
{
}
private long lastDate = -1;
public void println(PrintStream stream, String s, int level)
{
if (level >= getVerboseLevel())
{
stream.println(getDate() + " - " + s);
}
}
public void println(String s, int level)
{
println(System.out, s, level);
}
public void println(String s)
{
println(System.out, s, 1);
}
public File getDataFile(String[] parms, File directory)
{
String s = directory.getAbsolutePath();
for (int i = 0; i < parms.length; ++i)
{
s += '/' + normalize(parms[i]);
}
s += ".txt";
return new File(s);
}
public String normalize(String s)
{
return s.replaceAll(" ", "_");
}
public void saveFunctionToFile(NumericFunction f, File dataFile)
{
dataFile.getParentFile().mkdirs();
List keys = new Vector(f.getKeys());
Collections.sort(keys);
String text = f.getGNUPlotText(keys);
if (text.length() == 0)
println("\nWarning!!! \"" + dataFile.getAbsolutePath() + "\" will not contain any data\n");
try
{
FileOutputStream fos = new FileOutputStream(dataFile);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write(text.getBytes());
bos.flush();
bos.close();
fos.flush();
fos.close();
}
catch (IOException ex)
{
println("\nWarning!!! I/O error while attempting to write \"" + dataFile.getAbsolutePath() + "\"\n. Here is the text to write:\n");
println(text);
println("\n");
}
}
private String getDate()
{
long currentDate = System.currentTimeMillis();
Date date = new Date(currentDate);
String s = date.toLocaleString();
int durationLenght = 18;
if (lastDate == -1)
{
s += TextUtilities.repeat(" ", durationLenght);
}
else
{
long duration = currentDate - lastDate;
s += TextUtilities.flushRight("(" + duration + "ms later)", durationLenght, ' ');
}
lastDate = currentDate;
return s;
}
public String getHostName()
{
try
{
return InetAddress.getLocalHost().getHostName();
}
catch (UnknownHostException e)
{
throw new IllegalStateException();
}
}
public int getVerboseLevel()
{
return verboseLevel;
}
public void setVerboseLevel(int verboseLevel)
{
this.verboseLevel = verboseLevel;
}
}