Saturday, December 29, 2007

serialize a bean into xml

import java.beans.PersistenceDelegate;
import java.beans.XMLEncoder;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public final class XMLTools {
private XMLTools() {}
/**
* Serialisation d'un objet dans un fichier
* @param object objet a serialiser
* @param filename chemin du fichier
*/
public static void encodeToFile(Object object, String fileName) throws FileNotFoundException,
IOException {
// ouverture de l'encodeur vers le fichier
XMLEncoder encoder = new XMLEncoder(new FileOutputStream(fileName));
try {
// serialisation de l'objet
encoder.writeObject(object);
encoder.flush ();
} finally {
// fermeture de l'encodeur
encoder.close();
}
}
}

SAX + Xerces serialization to file output stream

import java.io.*;
// Xerces 1 or 2 additional classes.
Import org.apache.xml.serialize.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
[…]
FileOutputStream fos = new FileOutputStream(filename);
// XERCES 1 or 2 additionnal classes.
OutputFormat of = new OutputFormat("XML","ISO-8859-1",true);
of.setIndent(1);
of.setIndenting(true);
of.setDoctype(null,"users.dtd");
XMLSerializer serializer = new XMLSerializer(fos,of);
// SAX2.0 ContentHandler.
ContentHandler hd = serializer.asContentHandler();
hd.startDocument();
// Processing instruction sample.
//hd.processingInstruction("xml-stylesheet","type=\"text/xsl\" href=\" users.xsl\"");
// USER attributes.
AttributesImpl atts = new AttributesImpl();
// USERS tag.
Hd.startElement("","","USERS",atts);
// USER tags.
String[] id = {"PWD122","MX787","A4Q45"};
String[] type = {"customer","manager","employee"};
String[] desc = {"Tim@Home","Jack&Moud","John D'oé"};
for (int i=0;i<id.length;i++)
{
  atts.clear();
  atts.addAttribute("","","ID","CDATA",id[i]);
  atts.addAttribute("","","TYPE","CDATA",type[i]);
  hd.startElement("","","USER",atts);
  hd.characters(desc[i].toCharArray(),0,desc[i].length());
  hd.endElement("","","USER");
}
hd.endElement("","","USERS");
hd.endDocument();
fos.close ();
[…]

DOM + Xerces serialization to file output stream


import java.io.*;
// DOM
import org.w3c.dom.*;
// Xerces classes.
Import org.apache.xerces.dom.DocumentImpl;
import org.apache.xml.serialize.*;
[…]
Element e = null;
Node n = null;
// Document (Xerces implementation only).
Document xmldoc= new DocumentImpl();
// Root element.
Element root = xmldoc.createElement("USERS");
String[] id = {"PWD122","MX787","A4Q45"};
String[] type = {"customer","manager","employee"};
String[] desc = {"Tim@Home","Jack&Moud","John D'oé"};
for (int i=0;i<id.length;i++)
{
  // Child i.
  E = xmldoc.createElementNS(null, "USER");
  e.setAttributeNS(null, "ID", id[i]);
  e.setAttributeNS(null, "TYPE", type[i]);
  n = xmldoc.createTextNode(desc[i]);
  e.appendChild(n);
  root.appendChild€;
}
xmldoc.appendChild(root);
FileOutputStream fos = new FileOutputStream(filename);
// XERCES 1 or 2 additionnal classes.
OutputFormat of = new OutputFormat("XML","ISO-8859-1",true);
of.setIndent(1);
of.setIndenting(true);
of.setDoctype(null,"users.dtd");
XMLSerializer serializer = new XMLSerializer(fos,of);
// As a DOM Serializer
serializer.asDOMSerializer();
serializer.serialize ( xmldoc.getDocumentElement() );
fos.close();
[…]

to verify if an email address is well formed

public boolean testEmail(String email)
    {
        email=email.toLowerCase();
        String charOk="abcdefghijklmnopqrstuvwxyz0123456789_@.";
        boolean test=false;
        if (email.length ()<8){return false;}// Si l'email fait moins de 8 caractéres
        if (email.indexOf('@')<0){return false;}// Si l'email ne contient pas d'@'
        if (email.indexOf('.')<0){return false;}// Si l'email ne contient pas de '.'
        if (((email.indexOf('.', (((email.indexOf('@'))+1)))))==(email.indexOf('@')+1)){return false;}// Si l'email as un '.' apres l'@
        if (((email.indexOf('.', ((( email.indexOf('@'))-1)))))==(email.indexOf('@')-1)){return false;}// Si l'email as un '.' avant l'@
        if ((email.indexOf('.'))==0){return false;}// Si l'email as un '.' au debut
        if ((email.charAt((email.length()-1))=='.')){return false;}// Si l'email a un '.' a la fin
        if ((email.indexOf('@'))==0){return false;}// Si l'email as un '@' au debut
        if ((email.charAt((email.length()-1))=='@')){return false;}// Si l'email a un '@' a la fin
        // Si l'email n'a pas de '.' un peu apres le '@'
        boolean tmp=false;
        for (int i=1;i<(email.length()-(email.indexOf('@')));i++)
        {
            if (email.charAt((email.indexOf('@'))+i)=='.')
            {
                tmp=true;
                i=(email.length());
            }
        }
        if (tmp==false){return false;}
        // Si l'email a plusieurs '@'
        for (int i=0;i<email.length();i++)
        {
            if (email.charAt(i)=='@')
            {
                for (int j=i+1;j<email.length();j++)
                {if (email.charAt(j)=='@'){return false;}}
            }        
        }
        // Si l'email a 2 '.' d'affilé
        for (int i=0;i<(email.length()-1);i++)
        {if ((email.charAt(i)=='.') && (email.charAt(i+1)=='.')){return false;}}
        // Si l'email contient un caractére interdis
        for (int i=0;i<email.length();i++)
        {
            for (int j=0;j<charOk.length();j++)
            {
                if ((email.charAt (i))==(charOk.charAt(j)))
                {
                    test=true;
                    j=(charOk.length());
                }
                else {test=false;}
            }
            if (test==false){return test;}
        }
        return test;                
    }

to create a class singleton

public class MonSingleton {
    private static final MonSingleton INSTANCE = new MonSingleton();
    private MonSingleton() {}
    public static final MonSingleton getInstance() {
        return INSTANCE;
    }
}

create an enumeration equivalent for java < 1.5

public class MyEnum
{
  public static final MyEnum VALUE1 = new MyEnum(0);
  public static final MyEnum VALUE2 = new MyEnum(1);
  public static final MyEnum VALUE3 = new MyEnum(2);
  public static final MyEnum VALUE4 = new MyEnum(3);

  protected int x = 0;

  private MyEnum(int x)
  {
    this.x = x;
  }
}

//Exemple of use

MyEnum value1 = MyEnum.VALUE1;

to save a file

public static void saveInFile(String completePathFile, InputStream in)
            throws IOException {
        BufferedInputStream bis = new BufferedInputStream(in);
        File file = new File(completePathFile);
        if (!file.exists())
            file.createNewFile();

        FileOutputStream stream = new FileOutputStream(completePathFile);
        BufferedOutputStream bos = null;
        try {
            int read_bytes = 0;
            byte[] buffer = new byte[4096];
            bos = new BufferedOutputStream(stream, buffer.length);
            while ((read_bytes = bis.read(buffer, 0, buffer.length)) != -1) {
                bos.write (buffer, 0, read_bytes);
            }
        } catch (IOException ex) {
            throw new IOException("ERROR IN SAVING FILE !! pathFile : "
                    + file.getAbsolutePath());
        } finally {
            bos.flush();
            bos.close();
            stream.close();
        }
    }

to read a file

public static InputStream readFile(String completePathFile)
            throws IOException {
        try {
            File file = new File(completePathFile);
            if (file.exists()) {
                InputStream in = new FileInputStream(file);
                // byte myBytes[] = new byte[in.available()];
                // in.read(myBytes);
                // return new String(myBytes);
                return in;
            } else {
                throw new IOException("FILE TO READ NOT FOUND !! pathFile : "
                        + file.getAbsolutePath());
            }
        } catch (IOException ex) {
            throw new IOException("Error in reading file");
        }
    }

to read a configuration file

import java.util.Properties;

Properties prop = new Properties();
/* Ici le fichier contenant les données de configuration est nommé 'db.myproperties' */
FileInputStream in = new FileInputStream("db.myproperties ");
prop.load(in);
in.close();
// Extraction des propriétés
String url = prop.getProperty("jdbc.url");
String user = prop.getProperty("jdbc.user");
String password = prop.getProperty ("jdbc.password");

to delete a file

public static void deleteFile(String completePathFile) throws IOException {
        try {
            File filetoDelete = new File(completePathFile);
            if (filetoDelete.exists()) {
                if (!filetoDelete.delete())
                    throw new IOException(
                            "ERROR FILE NOT DELETED !! pathFile : "
                                    + filetoDelete.getAbsolutePath());
            }
        } catch (IOException ex) {
            throw new IOException("Error in deleting file");
        }
    }

Simple class that writes a line in a log file

package Log;

import java.io.*;
import java.text.*;
import java.util.*;

public class Log
{
    private String fileName;
    
    public Log(String n) {fileName = n;}

    public void writeLine(String line)
    {
        try
        {
            FileWriter f = new FileWriter(fileName,true);
            BufferedWriter bf = new BufferedWriter(f);
            Calendar c = Calendar.getInstance();
            Date maintenant = c.getTime();
            String datelog = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.MEDIUM,Locale.FRANCE).format(maintenant);
            bf.write("[" + datelog + "]: " + ligne);
            bf.newLine();
            bf.close();
        }
        catch(IOException e)
        {   
            System.out.println(e.getMessage());
        }
    }

    public void writeLine(String header,String info)
    {
        writeLine(header+ " > " + info);
    }
}

getting the list of files of a folder


/**
     * returns the list of files of a given directory
     *
     * @param listOfFiles
     */
    public static void getListOfFilesOfFolder(File directory,
            List<File> listOfFiles) {
        
        File[] fileList = directory.listFiles(FileFilter.getInstance());
        for (int iFile = 0; iFile < fileList.length; iFile++) {
            File oneFile = fileList[iFile];
            if (!oneFile.isDirectory()) {
                listOfFiles.add(fileList[iFile]);
            } else {
                getListOfFilesOfFolder(oneFile, listOfFiles);
            }
        }
    }

//the FileFilter class is a class that implements the interface FileNameFilter

create a file

/**
     * creates a file given its name and content
     *
     * @param fileName
     * @param fileContent
     */
    public static void createFile(String fileName, StringBuffer fileContent) {
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
            out.write(fileContent.toString());
            out.close();
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }