package periman;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import com.thoughtworks.xstream.InitializationException;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.XStreamException;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class Util {
/** create a directory.
* return true if succeeded or directory already exist
* return false if directory could not be created.*/
static boolean createDirectory(final String path)
{
File formDir = new File(path);
if(formDir.exists()==false)
{
boolean retVal = (formDir.mkdir());
if(retVal == false)
{
return false;
}
}
return true;
}
public static void copyFile(File in, File out) throws Exception {
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out);
try {
byte[] buf = new byte[1024];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
}
catch (Exception e) {
throw e;
}
finally {
if (fis != null) fis.close();
if (fos != null) fos.close();
}
}
/**
* Fetch the entire contents of a text file, and return it in a String.
* This style of implementation does not throw Exceptions to the caller.
*
* function does not check the input file.
* warning function ignore text encoding. it converts using the file bytes to chars using the current encoding but file encoding could be different.
*
* @param aFile is a file which already exists and can be read.
*/
// TODO: this function is not good. text encoding should be considered, look at discussion at http://episteme.arstechnica.com/eve/forums/a/tpc/f/6330927813/m/842009413931
static public String getContents(File aFile) {
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(aFile)); // warning this converts bytes to chars...
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contents.toString();
}
public static String getText(File f, String charsetName) throws IOException {
if (f.length() > Integer.MAX_VALUE) {
throw new IOException("Not enough memory to load " + f.getAbsolutePath());
}
byte[] data = new byte[ (int) f.length()];
new DataInputStream(new FileInputStream(f)).readFully(data);
return new String(data, charsetName);
}
public static void serializeXML(Document dom, String pathDest)
{
OutputFormat format = new OutputFormat(dom);
format.setIndenting(true);
XMLSerializer serializer;
try {
File fileDest = new File(pathDest);
serializer = new XMLSerializer(
new FileOutputStream( fileDest ),
format);
serializer.serialize(dom);
} catch (FileNotFoundException e1) {
JOptionPane.showMessageDialog(null, "Could not create a serielize xml.\n"+e1.getMessage() );
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, "Could not create a serielize xml.\n"+e1.getMessage() );
}
}
public static Document createDom()
{
Document dom = null;
//get an instance of factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
//get an instance of builder
DocumentBuilder db = dbf.newDocumentBuilder();
//create an instance of DOM
dom = db.newDocument();
}catch(ParserConfigurationException pce) {
JOptionPane.showMessageDialog( null, "Error while trying to instantiate DocumentBuilder " + pce);
}
return dom;
}
public static Document loadDom(String path)
{
File file = new File(path);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document dom = null;
try {
DocumentBuilder db;
db = dbf.newDocumentBuilder();
dom = db.parse(file);
} catch (ParserConfigurationException e) {
JOptionPane.showMessageDialog(null, "Could not load Questionnaire XML:\n" + path);
} catch (SAXException e) {
JOptionPane.showMessageDialog(null, "Could not load Questionnaire XML:\n" + path);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Could not load Questionnaire XML:\n" + path);
}
return dom;
}
/**
* XML elements must follow these naming rules:
* *Names can contain letters, numbers, and other characters
* *Names cannot start with a number or punctuation character
* *Names cannot start with the letters xml (or XML, or Xml, etc)
* *Names cannot contain spaces
*/
public static String xmlElementValidfy(final String str)
{
String ret = str;
// replace spaces with underscores.
ret.replace(' ', '_');
// check for some of the common things that an element can start with
if(ret.startsWith(".") ||
ret.startsWith(",") ||
ret.startsWith(":") ||
ret.startsWith(";") ||
ret.startsWith("xml") ||
ret.startsWith("XML") ||
ret.startsWith("Xml") )
ret = "a_" + ret;
return ret;
}
public static void writeObject(final String path, Object obj)
{
XStream xstream = new XStream(new DomDriver());
try {
FileWriter fw = new FileWriter(path);
xstream.toXML( obj, fw );
}
catch (IOException ex) {
JOptionPane.showMessageDialog( null, "Could not write object:\n"+ex.getMessage());
}
catch(XStreamException ex){
JOptionPane.showMessageDialog( null, "Could not write object:\n"+ex.getMessage());
}
}
public static Object loadMyObject(final String path)
{
try{
XStream xstream = new XStream( new DomDriver() );
FileReader fr = new FileReader( path );
return xstream.fromXML(fr);
}
catch(InitializationException e)
{
JOptionPane.showMessageDialog( null, e.getMessage());
return null;
}
catch(XStreamException e)
{
JOptionPane.showMessageDialog( null,"Not a proper configuration file.\n"+ e.getMessage());
return null;
}
catch (FileNotFoundException e) {
JOptionPane.showMessageDialog( null, e.getMessage());
return null;
}
}
public static int getScreenWidth()
{
Toolkit t = Toolkit.getDefaultToolkit();
return t.getScreenSize().width;
}
}