Zi Youltimayte Torque gaïde !

DevFrançaisTutorials

1 Introduction

URL : http://db.apache.org/torque/ et http://db.apache.org/torque-32/
Licence : Apache Software License, Version 1.1

1.1 A quoi ça sert ?

Torque est juste un outils qui permet de générer pour toi des objets java avec tout le mécanisme qui te permettra d’accéder à une base de donnée, même principe qu’Hibernate donc.

1.2 Comment ça marche ?

Il se branche sur le pool de ton serveur d’appli (Tomcat, Weblogic, JBoss…) ou sinon il peut te fournir un pool à lui basé sur commons-dbcp package configurable avec le SharedPoolDataSourceFactory. Keep reading

Java Connexion LDAP

CodeDevFrançais

Dans la série code à garder sous la main : une connexion LDAP en Java :

/*********************************************************/
/*            Connexion à une base LDAP                  */
/*********************************************************/
import javax.naming.*;
import javax.naming.directory.*;
import java.util.Hashtable;

class LDAPConnect {
    public static void main(String[] args) throws java.io.IOException {

        // On met tout OK dans l'environement
        Hashtable env = new Hashtable(11);
        env.put(Context.INITIAL_CONTEXT_FACTORY,  "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldap://myLdapServer:389/");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");

        try {
            // Creer un InitialDirContext
            DirContext ctx = new InitialDirContext(env);

            // Ici on peut faire plein de truc avec ctx !
            String temp = (String)ctx.lookup("DC=referentiel,DC=unit,DC=com");
            System.out.println("temp = " + temp);

            // Fermeture du contexte
            ctx.close();
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }
}

Java – Sending email

CodeDevEnglish

Source to keep somewhere: 2 classes to send emails.

In order to work these classes requires activation.jar et mail.jar
First java class : email data object.

package com.ledruide.utils.mail;

import java.util.ArrayList;
import java.util.List;

/**
 * @author JRA
 * @since 26 fev. 2005
 */
public class Mail {

    public String login         = null;
    public String password      = null;
    public String host          = null;
    public List<String> to      = null;
    public List<String> cc      = null;
    public List<String> bcc     = null;
    public List<String> attach  = null;
    public String from          = null;
    public String fromName      = null;
    public String replyTo       = null;
    public String subject       = null;
    public String mode          = "html";
    public String content       = null;
    public String priority      = null;
    
    
    public String getLogin() {
        return login;
    }
    public void setLogin(String string) {
        login = string;
    }

    public String getPassword() {
        return password;
    }
    public void setPassword(String string) {
        password = string;
    }

    public String getHost() {
        return host;
    }
    public void setHost(String string) {
        host = string;
    }

    public String getFrom() {
        return from;
    }
    public void setFrom(String string) {
        from = string;
    }

    public String getFromName() {
        return fromName;
    }
    public void setFromName(String string) {
        fromName = string;
    }

    public String getReplyTo() {
        return replyTo;
    }
    public void setReplyTo(String string) {
        replyTo = string;
    }

    public String getSubject() {
        return subject;
    }
    public void setSubject(String string) {
        subject = string;
    }

    public String getMode() {
        return mode;
    }
    public void setMode(String string) {
        mode = string;
    }

    public String getContent() {
        return content;
    }
    public void setContent(String string) {
        content = string;
    }

    public List<String> getTo() {
        return to;
    }
    public void setTo(List<String> list) {
        to = list;
    }
    public void addTo(String string) {
        if (to == null) {
            to = new ArrayList<String>();
        }
        to.add(string);
    }

    public List<String> getCc() {
        return cc;
    }
    public void setCc(List<String> list) {
        cc = list;
    }
    public void addCc(String string) {
        if (cc == null) {
            cc = new ArrayList<String>();
        }
        cc.add(string);
    }

    public List<String> getBcc() {
        return bcc;
    }
    public void setBcc(List<String> list) {
        bcc = list;
    }
    public void addBcc(String string) {
        if (bcc == null) {
            bcc = new ArrayList<String>();
        }
        bcc.add(string);
    }

    public List<String> getAttach() {
        return attach;
    }
    public void setAttach(List<String> list) {
        attach = list;
    }
    public void addAttach(String string) {
        if (attach == null) {
            attach = new ArrayList<String>();
        }
        attach.add(string);
    }

    public String getPriority(){
        return priority;
    }
    public void setPriority( String priority ){
        this.priority = priority;
    }
}
</pre>

Second java class, email send job:
<pre class="brush:java>
package com.ledruide.utils.mail;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;


/**
 * EnvoiMail
 * Classe permettant d'envoyer un mail acceptant comme parametres :
 *
 * Emetteur.
 * Adresse de retour.
 * Destinataires (TO, CC, BCC).
 * Fichiers attachés.
 * Nom de serveur SMTP
 * Nom d'utilisateur
 * Mot de passe (au cas ou..)
 * Sujet
 * Contenu
 * @author JRA
 * @since 26 fev. 2005
 */
public final class SendMail {

    private SendMail() {    }
    
    /**
     * Permet d'utiliser le programme en ligne de commande
     * de facon independante.<BR>
     * Usage : EnvoiMail [-l login -p password -H host <br>
     *                  -TO to@to1.com;to@to2.com -CC cc@cc1.com;cc@cc2.com -BCC bcc@bcc1.com;bcc@bcc2.com <BR>
     *                  -F fichierAttaché1;fichierAttaché2 -e emetteur -r adresseReponse <BR>
     *                  Sujet et contenu sont demandés ensuite.
     *
     * @param args
     */
    public static void main (final String[] args) {
        if (args.length < 4) {
            System.out.println(usage());
            System.exit(1);
        } else {
            try {
                System.out.println("constructParam");
                final Mail arguments = constructParam(args);
                System.out.println("createMessage");
                createMessage(arguments);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static String usage() {
        return "\nUsage : SendMail &#91;-l login\n" + 
               "\t-p password\n" + 
               "\t-H host\n" +
               "\t-TO to@to1.com;to@to2.com\n" + 
               "\t-CC cc@cc1.com;cc@cc2.com\n" + 
               "\t-BCC bcc@bcc1.com;bcc@bcc2.com\n" +
               "\t-F fichierAttache1;fichierAttache2\n" + 
               "\t-e emetteur\n" + 
               "\t-r adresseReponse\n" +
               "\t-m mode&#91;text or html(default)&#93;\n" +
               "\nLe sujet et le contenu sont demandes ensuite...";
    }

    /**
     * Construit la HashMap en fonction des arguments passés en ligne de commande
     * <h4>Ne doit être appelé que par le main en ligne de commande !<h4>
     *
     * @param args les arguments de la ligne de commande
     * @return la HashMap construite.
     */
    private static Mail constructParam (final String[] args) throws Exception {

        final Mail courriel = new Mail();
        StringTokenizer tokenizer;
        final String separateur = ";";

        final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        int i;
        for (i = 0; i < args.length; i++) {

            /* LOGIN */
            if ("-l".equalsIgnoreCase(args&#91;i&#93;)) {
                courriel.setLogin(args&#91;++i&#93;);
                System.out.println("login = " + courriel.getLogin());
            }
            /* PASSWORD */
            else if ("-p".equalsIgnoreCase(args&#91;i&#93;)) {
                courriel.setPassword(args&#91;++i&#93;);
                System.out.println("password = " + courriel.getPassword());
            }
            /* HOST */
            else if ("-H".equalsIgnoreCase(args&#91;i&#93;)) {
                courriel.setHost(args&#91;++i&#93;);
                System.out.println("host = " + courriel.getHost());
            }
            /* EMETTEUR */
            else if ("-e".equalsIgnoreCase(args&#91;i&#93;)) {
                courriel.setFrom(args&#91;++i&#93;);
                System.out.println("emetteur = " + courriel.getFrom());
            }
            /* ADRESSE REPONSE */
            else if ("-r".equalsIgnoreCase(args&#91;i&#93;)) {
                courriel.setReplyTo(args&#91;++i&#93;);
                System.out.println("addresseReponse = " + courriel.getReplyTo());
            }
            /* TO */
            else if ("-TO".equalsIgnoreCase(args&#91;i&#93;)) {
                tokenizer = new StringTokenizer(args&#91;++i&#93;, separateur);
                while (tokenizer.hasMoreElements()) {
                    courriel.addTo(tokenizer.nextElement().toString());
                }
            }
            /* CC */
            else if ("-CC".equalsIgnoreCase(args&#91;i&#93;)) {
                tokenizer = new StringTokenizer(args&#91;++i&#93;, separateur);
                while (tokenizer.hasMoreElements()) {
                    courriel.addCc(tokenizer.nextElement().toString());
                }
            }
            /* BCC */
            else if ("-BCC".equalsIgnoreCase(args&#91;i&#93;)) {
                tokenizer = new StringTokenizer(args&#91;++i&#93;, separateur);
                while (tokenizer.hasMoreElements()) {
                    courriel.addBcc(tokenizer.nextElement().toString());
                }
            }
            /* MODE */
            else if ("-m".equalsIgnoreCase(args&#91;i&#93;)) {
                courriel.setMode(args&#91;++i&#93;);
                System.out.println("mode = " + courriel.getMode());
            }
            /* FICHIERS ATTACHES */
            else if ("-F".equalsIgnoreCase(args&#91;i&#93;)) {
                tokenizer = new StringTokenizer(args&#91;++i&#93;, separateur);
                while (tokenizer.hasMoreElements()) {
                    courriel.addAttach(tokenizer.nextElement().toString());
                }
            }/* SINON AFFICHER L'AIDE */
            else {
                System.out.println(usage());
                System.exit(1);
                break;
            }
        }
        System.out.print("Sujet: ");
        System.out.flush();
        final String sujet = in.readLine();
        courriel.setSubject(sujet);
        System.out.print("Contenu: ");
        System.out.flush();
        final StringBuffer contenu = new StringBuffer(in.readLine());
        courriel.setContent(contenu.toString());

        return courriel;
    }

    /**
     * Methode d'envoi du message.<br>
     * Inclus le traitement des parametres envoyés (test des paramètres nécessaires.
     *
     * @param mail Mail contenant les paramètres du message
     * @exception Exception if an error occurs
     */
    public static void createMessage (final Mail mail) throws Exception {
        final StringBuffer probleme = new StringBuffer(2000);
        if (!testParametres(mail, probleme)) {
            throw new Exception(probleme.toString());
        }

        final Properties properties = System.getProperties();
        properties.put("mail.smtp.host", mail.getHost());

        final Session session = Session.getInstance(properties, null);
        /*
        * Inclusion de toutes les variables d'envoi.
        */
        final MimeMessage message = new MimeMessage(session);
        final Multipart multiPart = new MimeMultipart();

        /* SET FROM */
        message.setFrom(new InternetAddress(mail.getFrom().toString()));

        /* REPLY TO */
        final String replyTo = mail.getReplyTo().toString();
        //message.setReplyTo(ia.parse(replyTo));
        message.setReplyTo(InternetAddress.parse(replyTo));

        /* DESTINATAIRE(S) */
        Iterator lEnum = mail.getTo().iterator();
        while (lEnum.hasNext()) {
            final String dest = lEnum.next().toString();
            final InternetAddress destIA = new InternetAddress(dest);
            message.addRecipient(Message.RecipientType.TO, destIA);
        }

        /* CARBON COPY */
        lEnum = mail.getCc().iterator();
        while (lEnum.hasNext()) {
            final String dest = lEnum.next().toString();
            final InternetAddress destIA = new InternetAddress(dest);
            message.addRecipient(Message.RecipientType.CC, destIA);
        }

        /* BLIND CARBON COPY */
        lEnum = mail.getBcc().iterator();
        while (lEnum.hasNext()) {
            final String dest = lEnum.next().toString();
            final InternetAddress destIA = new InternetAddress(dest);
            message.addRecipient(Message.RecipientType.BCC, destIA);
        }

        /* SUJET */
        message.setSubject(mail.getSubject());

        /* DATE D'ENVOI */
        message.setSentDate(new Date());

        /* TYPE MIME DE LA PARTIE CONTENU DU MESSAGE */
        String charset="utf-8";

        final MimeBodyPart mbpMessage = new MimeBodyPart();
        if ("html".equalsIgnoreCase(mail.getMode())) {
            mbpMessage.setContent(mail.getContent(), "text/html");
        }
        else {
            mbpMessage.setText(mail.getContent());
        }

        /* AJOUT DU CONTENU AU MESSAGE EN 1ERE PARTIE */
        multiPart.addBodyPart(mbpMessage);

        /* FICHIERS ATTACHES */
        MimeBodyPart mbpAttach;

        List fichiers = mail.getAttach();
        if (fichiers != null) {
            lEnum = fichiers.iterator();
            while (lEnum.hasNext()) {
                String name = lEnum.next().toString();
                File fichier = new File(name);
                mbpAttach = new MimeBodyPart();
                FileDataSource fds = new FileDataSource(name);
                mbpAttach.setDataHandler(new DataHandler(fds));
                mbpAttach.setFileName(fichier.getName());
                /* AJOUT DU CONTENU AU MESSAGE EN 1ERE PARTIE */

                multiPart.addBodyPart(mbpAttach);
            }
        }
        message.setContent(multiPart);
        /*
        * Transport du message
        */
        try {
            if ("".equals(mail.getLogin()) && "".equals(mail.getPassword())) {
                Transport.send(message, message.getAllRecipients());
            }
            else {
                final Transport transport = session.getTransport("smtp");
                transport.connect(mail.getHost(), mail.getLogin(), mail.getPassword());
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
            }
        }catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * Teste la validités des parametres reçu dans la HashMap
     *
     * @param map la Map des parametres a tester
     * @return true si tous les parametres sont testés avec succès
     */
    private static boolean testParametres (final Mail mail, final StringBuffer probleme) {

        boolean ok = true;
        probleme.append("\n*****************************");
        probleme.append("\n**** PROBLEMS :");
        if (mail == null) {
            probleme.append("\nNothing to send ! ........KO");
            ok = false;
        }
        else {

            /*
            * Verification de la validites de tous les parametres pour
            * eviter plus tard une NullPointerException
            */
            if ( mail.getLogin() == null ) {
                probleme.append("\nNo login..................OK");
                mail.setLogin("");
            }
            if ( mail.getPassword() == null ) {
                mail.setPassword("");
                probleme.append("\nNo password...............OK");
            }
            if ( mail.getFrom() == null ) {
                mail.setFrom("");
                probleme.append("\nNo From...................OK");
            }
            if ( mail.getReplyTo() == null ) {
                mail.setReplyTo(mail.getFrom());
                probleme.append("\nNo Reply to...............OK");
            }
            if ( mail.getHost() == null ) {
                mail.setHost("");
                probleme.append("\nNo SMTP Host...........FATAL");
                ok = false;
            }
            if ( mail.getSubject() == null ) {
                mail.setSubject("");
                probleme.append("\nNo subject................OK");
            }
            if ( mail.getMode() == null ) {
                mail.setMode("html");
                probleme.append("\nNo mode...................OK");
            }
            if ( mail.getContent() == null ) {
                mail.setContent("");
                probleme.append("\nNo content................OK");
            }
            if ( mail.getTo() == null ) {
                mail.setTo(new ArrayList<String>(0));
                probleme.append("\nNo recipient TO........FATAL");
                ok = false;
            }
            if ( mail.getCc() == null ) {
                mail.setCc(new ArrayList<String>(0));
                probleme.append("\nNo Carbon Copy............OK");
            }
            if ( mail.getBcc() == null ) {
                mail.setBcc(new ArrayList<String>(0));
                probleme.append("\nNo Blind Carbon Copy......OK");
            }
            /*
            * Ici je regarde de quel type sont les fichiers que je recoit File ou URL
            */
            if ( mail.getAttach() != null ) {
                List fichiers = mail.getAttach();
                Iterator ite = fichiers.iterator();
                while (ite.hasNext()) {
                    final String name = (String)ite.next();
                    // Try to open URL connection first
                    try {
                        URL url = new URL(name);
                        //InputStream file = null;
                        url.openStream();
                    } 
                    catch (MalformedURLException e) {
                        // Try to open plain file, if `name' is not a URL specification
                        try {
                            //InputStream file = null;
                            new FileInputStream(name);
                        } catch (FileNotFoundException ex) {
                            probleme.append("\nAttached file '" + name + "' not found.....FATAL");
                            ok = false;
                        }
                    } catch (IOException ex) {
                        probleme.append("\nAttached file '" + name + "' not found.....FATAL");
                        ok = false;
                    }
                } //while
            } else {
                probleme.append("\nNo attached file..........OK");
            }
        }
        probleme.append("\n*****************************");
        return ok;
    }
}

Java – Envoi de mail

CodeDevFrançais

Dans la série code à garder sous la main : Deux classes pour envoyer des emails

Ces classes pour compiler et fonctionner ont besoin de activation.jar et mail.jar
Première classe : un objet contenant les caractéristiques d’un email

package com.ledruide.utils.mail;

import java.util.ArrayList;
import java.util.List;

/**
 * @author JRA
 * @since 26 fev. 2005
 */
public class Mail {

    public String login         = null;
    public String password      = null;
    public String host          = null;
    public List<String> to      = null;
    public List<String> cc      = null;
    public List<String> bcc     = null;
    public List<String> attach  = null;
    public String from          = null;
    public String fromName      = null;
    public String replyTo       = null;
    public String subject       = null;
    public String mode          = "html";
    public String content       = null;
    public String priority      = null;
    
    
    public String getLogin() {
        return login;
    }
    public void setLogin(String string) {
        login = string;
    }

    public String getPassword() {
        return password;
    }
    public void setPassword(String string) {
        password = string;
    }

    public String getHost() {
        return host;
    }
    public void setHost(String string) {
        host = string;
    }

    public String getFrom() {
        return from;
    }
    public void setFrom(String string) {
        from = string;
    }

    public String getFromName() {
        return fromName;
    }
    public void setFromName(String string) {
        fromName = string;
    }

    public String getReplyTo() {
        return replyTo;
    }
    public void setReplyTo(String string) {
        replyTo = string;
    }

    public String getSubject() {
        return subject;
    }
    public void setSubject(String string) {
        subject = string;
    }

    public String getMode() {
        return mode;
    }
    public void setMode(String string) {
        mode = string;
    }

    public String getContent() {
        return content;
    }
    public void setContent(String string) {
        content = string;
    }

    public List<String> getTo() {
        return to;
    }
    public void setTo(List<String> list) {
        to = list;
    }
    public void addTo(String string) {
        if (to == null) {
            to = new ArrayList<String>();
        }
        to.add(string);
    }

    public List<String> getCc() {
        return cc;
    }
    public void setCc(List<String> list) {
        cc = list;
    }
    public void addCc(String string) {
        if (cc == null) {
            cc = new ArrayList<String>();
        }
        cc.add(string);
    }

    public List<String> getBcc() {
        return bcc;
    }
    public void setBcc(List<String> list) {
        bcc = list;
    }
    public void addBcc(String string) {
        if (bcc == null) {
            bcc = new ArrayList<String>();
        }
        bcc.add(string);
    }

    public List<String> getAttach() {
        return attach;
    }
    public void setAttach(List<String> list) {
        attach = list;
    }
    public void addAttach(String string) {
        if (attach == null) {
            attach = new ArrayList<String>();
        }
        attach.add(string);
    }

    public String getPriority(){
        return priority;
    }
    public void setPriority( String priority ){
        this.priority = priority;
    }
}
</pre>

Seconde classe, l'envoi d'email
<pre class="brush:java>
package com.ledruide.utils.mail;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;


/**
 * EnvoiMail
 * Classe permettant d'envoyer un mail acceptant comme parametres :
 *
 * Emetteur.
 * Adresse de retour.
 * Destinataires (TO, CC, BCC).
 * Fichiers attachés.
 * Nom de serveur SMTP
 * Nom d'utilisateur
 * Mot de passe (au cas ou..)
 * Sujet
 * Contenu
 * @author JRA
 * @since 26 fev. 2005
 */
public final class SendMail {

    private SendMail() {    }
    
    /**
     * Permet d'utiliser le programme en ligne de commande
     * de facon independante.<BR>
     * Usage : EnvoiMail [-l login -p password -H host <br>
     *                  -TO to@to1.com;to@to2.com -CC cc@cc1.com;cc@cc2.com -BCC bcc@bcc1.com;bcc@bcc2.com <BR>
     *                  -F fichierAttaché1;fichierAttaché2 -e emetteur -r adresseReponse <BR>
     *                  Sujet et contenu sont demandés ensuite.
     *
     * @param args
     */
    public static void main (final String[] args) {
        if (args.length < 4) {
            System.out.println(usage());
            System.exit(1);
        } else {
            try {
                System.out.println("constructParam");
                final Mail arguments = constructParam(args);
                System.out.println("createMessage");
                createMessage(arguments);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static String usage() {
        return "\nUsage : SendMail &#91;-l login\n" + 
               "\t-p password\n" + 
               "\t-H host\n" +
               "\t-TO to@to1.com;to@to2.com\n" + 
               "\t-CC cc@cc1.com;cc@cc2.com\n" + 
               "\t-BCC bcc@bcc1.com;bcc@bcc2.com\n" +
               "\t-F fichierAttache1;fichierAttache2\n" + 
               "\t-e emetteur\n" + 
               "\t-r adresseReponse\n" +
               "\t-m mode&#91;text or html(default)&#93;\n" +
               "\nLe sujet et le contenu sont demandes ensuite...";
    }

    /**
     * Construit la HashMap en fonction des arguments passés en ligne de commande
     * <h4>Ne doit être appelé que par le main en ligne de commande !<h4>
     *
     * @param args les arguments de la ligne de commande
     * @return la HashMap construite.
     */
    private static Mail constructParam (final String[] args) throws Exception {

        final Mail courriel = new Mail();
        StringTokenizer tokenizer;
        final String separateur = ";";

        final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        int i;
        for (i = 0; i < args.length; i++) {

            /* LOGIN */
            if ("-l".equalsIgnoreCase(args&#91;i&#93;)) {
                courriel.setLogin(args&#91;++i&#93;);
                System.out.println("login = " + courriel.getLogin());
            }
            /* PASSWORD */
            else if ("-p".equalsIgnoreCase(args&#91;i&#93;)) {
                courriel.setPassword(args&#91;++i&#93;);
                System.out.println("password = " + courriel.getPassword());
            }
            /* HOST */
            else if ("-H".equalsIgnoreCase(args&#91;i&#93;)) {
                courriel.setHost(args&#91;++i&#93;);
                System.out.println("host = " + courriel.getHost());
            }
            /* EMETTEUR */
            else if ("-e".equalsIgnoreCase(args&#91;i&#93;)) {
                courriel.setFrom(args&#91;++i&#93;);
                System.out.println("emetteur = " + courriel.getFrom());
            }
            /* ADRESSE REPONSE */
            else if ("-r".equalsIgnoreCase(args&#91;i&#93;)) {
                courriel.setReplyTo(args&#91;++i&#93;);
                System.out.println("addresseReponse = " + courriel.getReplyTo());
            }
            /* TO */
            else if ("-TO".equalsIgnoreCase(args&#91;i&#93;)) {
                tokenizer = new StringTokenizer(args&#91;++i&#93;, separateur);
                while (tokenizer.hasMoreElements()) {
                    courriel.addTo(tokenizer.nextElement().toString());
                }
            }
            /* CC */
            else if ("-CC".equalsIgnoreCase(args&#91;i&#93;)) {
                tokenizer = new StringTokenizer(args&#91;++i&#93;, separateur);
                while (tokenizer.hasMoreElements()) {
                    courriel.addCc(tokenizer.nextElement().toString());
                }
            }
            /* BCC */
            else if ("-BCC".equalsIgnoreCase(args&#91;i&#93;)) {
                tokenizer = new StringTokenizer(args&#91;++i&#93;, separateur);
                while (tokenizer.hasMoreElements()) {
                    courriel.addBcc(tokenizer.nextElement().toString());
                }
            }
            /* MODE */
            else if ("-m".equalsIgnoreCase(args&#91;i&#93;)) {
                courriel.setMode(args&#91;++i&#93;);
                System.out.println("mode = " + courriel.getMode());
            }
            /* FICHIERS ATTACHES */
            else if ("-F".equalsIgnoreCase(args&#91;i&#93;)) {
                tokenizer = new StringTokenizer(args&#91;++i&#93;, separateur);
                while (tokenizer.hasMoreElements()) {
                    courriel.addAttach(tokenizer.nextElement().toString());
                }
            }/* SINON AFFICHER L'AIDE */
            else {
                System.out.println(usage());
                System.exit(1);
                break;
            }
        }
        System.out.print("Sujet: ");
        System.out.flush();
        final String sujet = in.readLine();
        courriel.setSubject(sujet);
        System.out.print("Contenu: ");
        System.out.flush();
        final StringBuffer contenu = new StringBuffer(in.readLine());
        courriel.setContent(contenu.toString());

        return courriel;
    }

    /**
     * Methode d'envoi du message.<br>
     * Inclus le traitement des parametres envoyés (test des paramètres nécessaires.
     *
     * @param mail Mail contenant les paramètres du message
     * @exception Exception if an error occurs
     */
    public static void createMessage (final Mail mail) throws Exception {
        final StringBuffer probleme = new StringBuffer(2000);
        if (!testParametres(mail, probleme)) {
            throw new Exception(probleme.toString());
        }

        final Properties properties = System.getProperties();
        properties.put("mail.smtp.host", mail.getHost());

        final Session session = Session.getInstance(properties, null);
        /*
        * Inclusion de toutes les variables d'envoi.
        */
        final MimeMessage message = new MimeMessage(session);
        final Multipart multiPart = new MimeMultipart();

        /* SET FROM */
        message.setFrom(new InternetAddress(mail.getFrom().toString()));

        /* REPLY TO */
        final String replyTo = mail.getReplyTo().toString();
        //message.setReplyTo(ia.parse(replyTo));
        message.setReplyTo(InternetAddress.parse(replyTo));

        /* DESTINATAIRE(S) */
        Iterator lEnum = mail.getTo().iterator();
        while (lEnum.hasNext()) {
            final String dest = lEnum.next().toString();
            final InternetAddress destIA = new InternetAddress(dest);
            message.addRecipient(Message.RecipientType.TO, destIA);
        }

        /* CARBON COPY */
        lEnum = mail.getCc().iterator();
        while (lEnum.hasNext()) {
            final String dest = lEnum.next().toString();
            final InternetAddress destIA = new InternetAddress(dest);
            message.addRecipient(Message.RecipientType.CC, destIA);
        }

        /* BLIND CARBON COPY */
        lEnum = mail.getBcc().iterator();
        while (lEnum.hasNext()) {
            final String dest = lEnum.next().toString();
            final InternetAddress destIA = new InternetAddress(dest);
            message.addRecipient(Message.RecipientType.BCC, destIA);
        }

        /* SUJET */
        message.setSubject(mail.getSubject());

        /* DATE D'ENVOI */
        message.setSentDate(new Date());

        /* TYPE MIME DE LA PARTIE CONTENU DU MESSAGE */
        String charset="utf-8";

        final MimeBodyPart mbpMessage = new MimeBodyPart();
        if ("html".equalsIgnoreCase(mail.getMode())) {
            mbpMessage.setContent(mail.getContent(), "text/html");
        }
        else {
            mbpMessage.setText(mail.getContent());
        }

        /* AJOUT DU CONTENU AU MESSAGE EN 1ERE PARTIE */
        multiPart.addBodyPart(mbpMessage);

        /* FICHIERS ATTACHES */
        MimeBodyPart mbpAttach;

        List fichiers = mail.getAttach();
        if (fichiers != null) {
            lEnum = fichiers.iterator();
            while (lEnum.hasNext()) {
                String name = lEnum.next().toString();
                File fichier = new File(name);
                mbpAttach = new MimeBodyPart();
                FileDataSource fds = new FileDataSource(name);
                mbpAttach.setDataHandler(new DataHandler(fds));
                mbpAttach.setFileName(fichier.getName());
                /* AJOUT DU CONTENU AU MESSAGE EN 1ERE PARTIE */

                multiPart.addBodyPart(mbpAttach);
            }
        }
        message.setContent(multiPart);
        /*
        * Transport du message
        */
        try {
            if ("".equals(mail.getLogin()) && "".equals(mail.getPassword())) {
                Transport.send(message, message.getAllRecipients());
            }
            else {
                final Transport transport = session.getTransport("smtp");
                transport.connect(mail.getHost(), mail.getLogin(), mail.getPassword());
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
            }
        }catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * Teste la validités des parametres reçu dans la HashMap
     *
     * @param map la Map des parametres a tester
     * @return true si tous les parametres sont testés avec succès
     */
    private static boolean testParametres (final Mail mail, final StringBuffer probleme) {

        boolean ok = true;
        probleme.append("\n*****************************");
        probleme.append("\n**** PROBLEMS :");
        if (mail == null) {
            probleme.append("\nNothing to send ! ........KO");
            ok = false;
        }
        else {

            /*
            * Verification de la validites de tous les parametres pour
            * eviter plus tard une NullPointerException
            */
            if ( mail.getLogin() == null ) {
                probleme.append("\nNo login..................OK");
                mail.setLogin("");
            }
            if ( mail.getPassword() == null ) {
                mail.setPassword("");
                probleme.append("\nNo password...............OK");
            }
            if ( mail.getFrom() == null ) {
                mail.setFrom("");
                probleme.append("\nNo From...................OK");
            }
            if ( mail.getReplyTo() == null ) {
                mail.setReplyTo(mail.getFrom());
                probleme.append("\nNo Reply to...............OK");
            }
            if ( mail.getHost() == null ) {
                mail.setHost("");
                probleme.append("\nNo SMTP Host...........FATAL");
                ok = false;
            }
            if ( mail.getSubject() == null ) {
                mail.setSubject("");
                probleme.append("\nNo subject................OK");
            }
            if ( mail.getMode() == null ) {
                mail.setMode("html");
                probleme.append("\nNo mode...................OK");
            }
            if ( mail.getContent() == null ) {
                mail.setContent("");
                probleme.append("\nNo content................OK");
            }
            if ( mail.getTo() == null ) {
                mail.setTo(new ArrayList<String>(0));
                probleme.append("\nNo recipient TO........FATAL");
                ok = false;
            }
            if ( mail.getCc() == null ) {
                mail.setCc(new ArrayList<String>(0));
                probleme.append("\nNo Carbon Copy............OK");
            }
            if ( mail.getBcc() == null ) {
                mail.setBcc(new ArrayList<String>(0));
                probleme.append("\nNo Blind Carbon Copy......OK");
            }
            /*
            * Ici je regarde de quel type sont les fichiers que je recoit File ou URL
            */
            if ( mail.getAttach() != null ) {
                List fichiers = mail.getAttach();
                Iterator ite = fichiers.iterator();
                while (ite.hasNext()) {
                    final String name = (String)ite.next();
                    // Try to open URL connection first
                    try {
                        URL url = new URL(name);
                        //InputStream file = null;
                        url.openStream();
                    } 
                    catch (MalformedURLException e) {
                        // Try to open plain file, if `name' is not a URL specification
                        try {
                            //InputStream file = null;
                            new FileInputStream(name);
                        } catch (FileNotFoundException ex) {
                            probleme.append("\nAttached file '" + name + "' not found.....FATAL");
                            ok = false;
                        }
                    } catch (IOException ex) {
                        probleme.append("\nAttached file '" + name + "' not found.....FATAL");
                        ok = false;
                    }
                } //while
            } else {
                probleme.append("\nNo attached file..........OK");
            }
        }
        probleme.append("\n*****************************");
        return ok;
    }
}

Java – Encode and decode in base 64

CodeDevEnglish

Source to keep somewhere: Encoder and decode in base 64


/*********************************************************/
/* Coder ou décoder en Base64 */
/*********************************************************/
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Base64 {

public static void main(String[] args) {

if (args.length < 1) { System.out.println("Usage : java Base64 [Chaine a coder et decoder]"); System.exit(-1); } new Base64(args[0]); } public Base64(String chaine) { System.out.println("Encodage de " + chaine + " = " + encode(chaine)); System.out.println("Decodage de " + chaine + " = " + decode(chaine)); } private String encode(String toEncode) { String encoded = toEncode; BASE64Encoder encoder = new BASE64Encoder(); try { encoded = new String(encoder.encodeBuffer(encoded.getBytes())); } catch (Exception e) { System.out.println("Probleme lors du codage !" + e); } return encoded; } private String decode(String toDecode) { String decoded = toDecode; BASE64Decoder decoder = new BASE64Decoder(); try { decoded = new String(decoder.decodeBuffer(decoded)); } catch (Exception e) { System.out.println("Probleme lors du decodage !" + e); } return decoded; } } [/java]

Java – Coder ou décoder en base 64

CodeDevFrançais

Dans la série code à garder sous la main : Coder ou décoder en base 64


/*********************************************************/
/* Coder ou décoder en Base64 */
/*********************************************************/
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Base64 {

public static void main(String[] args) {

if (args.length < 1) { System.out.println("Usage : java Base64 [Chaine a coder et decoder]"); System.exit(-1); } new Base64(args[0]); } public Base64(String chaine) { System.out.println("Encodage de " + chaine + " = " + encode(chaine)); System.out.println("Decodage de " + chaine + " = " + decode(chaine)); } private String encode(String toEncode) { String encoded = toEncode; BASE64Encoder encoder = new BASE64Encoder(); try { encoded = new String(encoder.encodeBuffer(encoded.getBytes())); } catch (Exception e) { System.out.println("Probleme lors du codage !" + e); } return encoded; } private String decode(String toDecode) { String decoded = toDecode; BASE64Decoder decoder = new BASE64Decoder(); try { decoded = new String(decoder.decodeBuffer(decoded)); } catch (Exception e) { System.out.println("Probleme lors du decodage !" + e); } return decoded; } } [/java]

Java – DirectoryToolkit en Java

CodeDevFrançais

Dans la série code à garder sous la main : Une classe pour travailler les fichiers et les répertoires

/**
 * Copyright (C) 2001 JRA This program is free software; you can redistribute
 * it and/or modify it under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option) any later version. This
 * program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details. You should have received a copy of the GNU General Public
 * License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass
 * Ave, Cambridge, MA 02139, USA.
 */
package com.ledruide.utils.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * Titre : Directory Toolkit Description : DirectoryToolkit permet de travailler rapidement sur les
 * repertoires.<br>
 * Deplacement, copie, supression.<br>
 * La meme chose est possible sur les fichiers.
 * 
 * @author JRA
 * @version 1.0
 */
public class DirectoryToolkit {

    /**
     * Constructeur, ne doit jamais servir donc private !
     */
    private DirectoryToolkit() {}

    // ************************************************************************
    // ** CREER UN REPERTOIRE **
    // ************************************************************************
    /**
     * Permet de creer un repertoire, si ce repertoire existe deja il ne fait rien.<br>
     * Par contre cette methode cree automatiquement toute l'arborescence du repertoire a creer si
     * celle-ci n'existe pas.
     * 
     * @param aCheminComplet du (ou des) repertoire(s) a creer
     * @throws Exception si une erreur survient
     */
    public static void createDirectory( final String aCheminComplet ) throws Exception {
        final File lDirectory = new File( aCheminComplet );
        if ( !lDirectory.canRead() ) {
            lDirectory.mkdirs();
        }
    }

    // ************************************************************************
    // ** EFFACER UN REPERTOIRE **
    // ************************************************************************
    /**
     * Effacer un repertoire et son contenu. Exemple : <BR>
     * DirectoryToolkit.deleteDirectory("c:/dev/myProject");<BR>
     * 
     * @param aCheminComplet du repertoire a effacer
     * @throws Exception If an error occurs
     */
    public static void deleteDirectory( final String aCheminComplet ) throws Exception {
        deleteDirectory( new File( aCheminComplet ) );
    }

    /**
     * Effacer un repertoire et son contenu. Exemple : <BR>
     * DirectoryToolkit.deleteDirectory(new File("c:/dev/myProject"));<BR>
     * Cette methode s'apelle recursivement pour suprimer son contenu
     * 
     * @param aDirectory L'objet File representant un repertoire
     * @throws Exception If an error occurs
     */
    public static void deleteDirectory( final File aDirectory ) throws Exception {
        final File[] lFiles = aDirectory.listFiles(); // Récupération de tous les fichiers du
        // répertoire
        if ( lFiles != null ) {
            for ( int i = 0 ; i < lFiles.length ; ++i ) {
                if ( lFiles&#91;i&#93;.isDirectory() ) { // Si le fichier traité est un répertoire
                    deleteDirectory( lFiles&#91;i&#93; ); // j'appelle cette méthode de faéon récursive
                }
                else { // Sinon
                    lFiles&#91;i&#93;.delete(); // j'efface le fichier
                }
            }
        }
        aDirectory.delete();
    }

    /**
     * Effacer seulement le contenu d'un répertoire et optionellement de ses sous-répertoires.<br>
     * Exemple (dans ce cas, tous les fichiers sont supprimés: <BR>
     * <code>DirectoryToolkit.deleteDirectoryContent(new File("c:/dev/myProject"), null, true);</code>
     * <BR>
     * <br>
     * Avec un filtre sur "csv" (seul les fichier possédant "csv" dans leur nom seront supprimés)
     * :<BR>
     * <code>DirectoryToolkit.deleteDirectoryContent(new File("c:/dev/myProject"), "csv", true);</code>
     * 
     * @param aDirectory L'objet File représentant un répertoire
     * @param aFiltre Le filtre pour la suppression des fichiers (null pour tout effacer).
     * @param aSousRepertoires true efface tout les sous repertoires.
     * @throws Exception If an error occurs
     */
    public static void deleteDirectoryContent( final File aDirectory , final String aFiltre ,
            final boolean aSousRepertoires ) throws Exception {
        final File[] lFiles = aDirectory.listFiles(); // Récupération de tous les fichiers du
        // répertoire
        if ( lFiles != null ) {
            for ( int i = 0 ; i < lFiles.length ; ++i ) {
                // Si le fichier traité est un répertoire
                // Et que l'on veut supprimer de faéon récursive
                if ( aSousRepertoires && lFiles&#91;i&#93;.isDirectory() ) {
                    // j'appelle cette méthode de faéon récursive
                    deleteDirectoryContent( lFiles&#91;i&#93; , aFiltre , aSousRepertoires );
                }
                else {
                    // Vérification du filtre
                    if ( aFiltre == null ) {
                        // j'efface le fichier
                        lFiles&#91;i&#93;.delete();
                    }
                    else {
                        // Si le filtre existe
                        // et que le fichier correspond au critere, on le supprime
                        if ( lFiles&#91;i&#93;.getName().indexOf( aFiltre ) != -1 ) {
                            lFiles&#91;i&#93;.delete();
                        }
                    }
                }
            }
        }
    }

    /**
     * @see DirectoryToolkit#deleteDirectoryContent(File aDirectory, String aFiltre, boolean
     *      aSousRepertoires)
     * @param aCheminComplet du (ou des) répertoire(s) é effacer
     * @param aFiltre Le filtre pour la suppression des fichiers (null pour tout éffacer).
     * @param aSousRepertoires true efface tout les sous repertoires.
     * @throws Exception si une erreur survient
     */
    public static void deleteDirectoryContent( final String aCheminComplet , final String aFiltre ,
            final boolean aSousRepertoires ) throws Exception {
        deleteDirectoryContent( new File( aCheminComplet ) , aFiltre , aSousRepertoires );
    }

    // ************************************************************************
    // ** DEPLACER UN REPERTOIRE **
    // ************************************************************************
    /**
     * Déplacer un répertoire entier et ses sous-répertoire, exemple :<BR>
     * DirectoryToolkit.moveDirectory("c:/dev/", "c:/LOCAL/amoi/", "testsJava");<BR>
     * 
     * @param aCheminActuel
     * @param aCheminDestination
     * @param aRepertoire
     * @throws Exception If an error occurs
     */
    public static void moveDirectory( final String aCheminActuel , final String aCheminDestination ,
            final String aRepertoire ) throws Exception {
        // Reviens é copier, puis effacer
        copyDirectory( aCheminActuel , aCheminDestination , aRepertoire );
        deleteDirectory( aCheminActuel + aRepertoire );
    }

    // ************************************************************************
    // ** COPIER UN REPERTOIRE **
    // ************************************************************************
    /**
     * Copier un répertoire entier sans effacer le contenu de l'original, exemple :<BR>
     * DirectoryToolkit.copyDirectory("c:/dev/", "c:/LOCAL/amoi/", "testsJava");<BR>
     * 
     * @param aCheminActuel
     * @param aCheminDestination
     * @param aRepertoire
     * @throws Exception If an error occurs
     */
    public static void copyDirectory( final String aCheminActuel , final String aCheminDestination ,
            final String aRepertoire ) throws Exception {
        // OK copie de répertoire
        copyDirectory( new File( aCheminActuel + aRepertoire ) , new File( aCheminDestination + aRepertoire ) );
    }

    /**
     * Copier un répertoire entier sans effacer le contenu de l'original, exemple :<BR>
     * DirectoryToolkit.copyDirectory("c:/dev/", "c:/LOCAL/amoi/", "testsJava");<BR>
     * 
     * @param aRepertoireActuel
     * @param aCheminDestination
     * @throws Exception Si une erreur survient
     */
    public static void copyDirectory( final File aRepertoireActuel , final File aCheminDestination ) throws Exception {
        final File[] lFiles = aRepertoireActuel.listFiles(); // Récupération de tous les fichiers
        // du répertoire
        File lFile;
        File lTemp;
        final String lSEPARATOR = System.getProperty( "lFile.separator" );

        if ( lFiles != null ) {
            for ( int i = 0 ; i < lFiles.length ; ++i ) {
                lFile = lFiles&#91;i&#93;;
                System.out.println( new StringBuffer().append( "lFile.getName   = " ).append( lFile.getName() )
                        .toString() );
                System.out.println( new StringBuffer().append( "lFile.getParent = " ).append( lFile.getParent() )
                        .toString() );
                if ( lFile.isDirectory() ) { // Si le fichier traité est un répertoire
                    // Comme le répertoire de destination n'existe pas, je le crée
                    lTemp = new File( new StringBuffer().append( aCheminDestination ).append( lSEPARATOR ).append(
                            lFile.getName() ).toString() );
                    lTemp.mkdirs();
                    copyDirectory( lFile , lTemp ); // j'appelle cette méthode de faéon récursive
                }
                else { // Sinon je copie le fichier
                    // Si le répertoire de destination n'existe pas, je le crée
                    if ( !aCheminDestination.exists() ) {
                        createDirectory( aCheminDestination.getAbsolutePath() );
                    }
                    // Comme le fichier de destination n'existe pas, je le crée
                    lTemp = new File( new StringBuffer().append( aCheminDestination.getAbsolutePath() ).append(
                            lSEPARATOR ).append( lFile.getName() ).toString() );
                    copyFile( lFile.getAbsolutePath() , lTemp.getAbsolutePath() );
                }
            }
        }
        // copyFile(actualDirectory.getAbsolutePath(), destinationDirectory + lSEPARATOR +
        // actualDirectory.getName());
    }

    private static void copyFile( final String aSourceFile , final String aTargetFile ) throws Exception {
        final File lInputFile = new File( aSourceFile );
        final File lOutputFile = new File( aTargetFile );

        final FileInputStream lIn = new FileInputStream( lInputFile );
        final FileOutputStream lOut = new FileOutputStream( lOutputFile );
        int c;

        while ( ( c = lIn.read() ) != -1 )
            lOut.write( c );

        lIn.close();
        lOut.close();
    }

    // ************************************************************************
    // ** RENOMER UN REPERTOIRE **
    // ************************************************************************
    /**
     * Renomer un répertoire. Exemple :<BR>
     * DirectoryToolkit.renameDirectory("c:/dev/", "projectToto", "TotoProject");<BR>
     * 
     * @param aChemin
     * @param aNomActuel
     * @param aNouveauNom
     * @throws Exception If an error occurs
     */
    public static void renameDirectory( final String aChemin , final String aNomActuel , final String aNouveauNom )
            throws Exception {
        // OK ICI L'IMPLEMENTATION DOIT ETRE
        final File lActual = new File( aChemin + aNomActuel );
        lActual.renameTo( new java.io.File( aChemin + aNouveauNom ) );
    }
}

Java – DirectoryToolkit, play with folders

CodeDevEnglish

Source to keep somewhere: a java class to work with files and directories
Javadoc is in french… sorry, someday I’ll traduce it.

/**
 * Copyright (C) 2001 JRA This program is free software; you can redistribute
 * it and/or modify it under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option) any later version. This
 * program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details. You should have received a copy of the GNU General Public
 * License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass
 * Ave, Cambridge, MA 02139, USA.
 */
package com.ledruide.utils.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * Titre : Directory Toolkit Description : DirectoryToolkit permet de travailler rapidement sur les
 * repertoires.<br>
 * Deplacement, copie, supression.<br>
 * La meme chose est possible sur les fichiers.
 * 
 * @author JRA
 * @version 1.0
 */
public class DirectoryToolkit {

    /**
     * Constructeur, ne doit jamais servir donc private !
     */
    private DirectoryToolkit() {}

    // ************************************************************************
    // ** CREER UN REPERTOIRE **
    // ************************************************************************
    /**
     * Permet de creer un repertoire, si ce repertoire existe deja il ne fait rien.<br>
     * Par contre cette methode cree automatiquement toute l'arborescence du repertoire a creer si
     * celle-ci n'existe pas.
     * 
     * @param aCheminComplet du (ou des) repertoire(s) a creer
     * @throws Exception si une erreur survient
     */
    public static void createDirectory( final String aCheminComplet ) throws Exception {
        final File lDirectory = new File( aCheminComplet );
        if ( !lDirectory.canRead() ) {
            lDirectory.mkdirs();
        }
    }

    // ************************************************************************
    // ** EFFACER UN REPERTOIRE **
    // ************************************************************************
    /**
     * Effacer un repertoire et son contenu. Exemple : <BR>
     * DirectoryToolkit.deleteDirectory("c:/dev/myProject");<BR>
     * 
     * @param aCheminComplet du repertoire a effacer
     * @throws Exception If an error occurs
     */
    public static void deleteDirectory( final String aCheminComplet ) throws Exception {
        deleteDirectory( new File( aCheminComplet ) );
    }

    /**
     * Effacer un repertoire et son contenu. Exemple : <BR>
     * DirectoryToolkit.deleteDirectory(new File("c:/dev/myProject"));<BR>
     * Cette methode s'apelle recursivement pour suprimer son contenu
     * 
     * @param aDirectory L'objet File representant un repertoire
     * @throws Exception If an error occurs
     */
    public static void deleteDirectory( final File aDirectory ) throws Exception {
        final File[] lFiles = aDirectory.listFiles(); // Récupération de tous les fichiers du
        // répertoire
        if ( lFiles != null ) {
            for ( int i = 0 ; i < lFiles.length ; ++i ) {
                if ( lFiles&#91;i&#93;.isDirectory() ) { // Si le fichier traité est un répertoire
                    deleteDirectory( lFiles&#91;i&#93; ); // j'appelle cette méthode de faéon récursive
                }
                else { // Sinon
                    lFiles&#91;i&#93;.delete(); // j'efface le fichier
                }
            }
        }
        aDirectory.delete();
    }

    /**
     * Effacer seulement le contenu d'un répertoire et optionellement de ses sous-répertoires.<br>
     * Exemple (dans ce cas, tous les fichiers sont supprimés: <BR>
     * <code>DirectoryToolkit.deleteDirectoryContent(new File("c:/dev/myProject"), null, true);</code>
     * <BR>
     * <br>
     * Avec un filtre sur "csv" (seul les fichier possédant "csv" dans leur nom seront supprimés)
     * :<BR>
     * <code>DirectoryToolkit.deleteDirectoryContent(new File("c:/dev/myProject"), "csv", true);</code>
     * 
     * @param aDirectory L'objet File représentant un répertoire
     * @param aFiltre Le filtre pour la suppression des fichiers (null pour tout effacer).
     * @param aSousRepertoires true efface tout les sous repertoires.
     * @throws Exception If an error occurs
     */
    public static void deleteDirectoryContent( final File aDirectory , final String aFiltre ,
            final boolean aSousRepertoires ) throws Exception {
        final File[] lFiles = aDirectory.listFiles(); // Récupération de tous les fichiers du
        // répertoire
        if ( lFiles != null ) {
            for ( int i = 0 ; i < lFiles.length ; ++i ) {
                // Si le fichier traité est un répertoire
                // Et que l'on veut supprimer de faéon récursive
                if ( aSousRepertoires && lFiles&#91;i&#93;.isDirectory() ) {
                    // j'appelle cette méthode de faéon récursive
                    deleteDirectoryContent( lFiles&#91;i&#93; , aFiltre , aSousRepertoires );
                }
                else {
                    // Vérification du filtre
                    if ( aFiltre == null ) {
                        // j'efface le fichier
                        lFiles&#91;i&#93;.delete();
                    }
                    else {
                        // Si le filtre existe
                        // et que le fichier correspond au critere, on le supprime
                        if ( lFiles&#91;i&#93;.getName().indexOf( aFiltre ) != -1 ) {
                            lFiles&#91;i&#93;.delete();
                        }
                    }
                }
            }
        }
    }

    /**
     * @see DirectoryToolkit#deleteDirectoryContent(File aDirectory, String aFiltre, boolean
     *      aSousRepertoires)
     * @param aCheminComplet du (ou des) répertoire(s) é effacer
     * @param aFiltre Le filtre pour la suppression des fichiers (null pour tout éffacer).
     * @param aSousRepertoires true efface tout les sous repertoires.
     * @throws Exception si une erreur survient
     */
    public static void deleteDirectoryContent( final String aCheminComplet , final String aFiltre ,
            final boolean aSousRepertoires ) throws Exception {
        deleteDirectoryContent( new File( aCheminComplet ) , aFiltre , aSousRepertoires );
    }

    // ************************************************************************
    // ** DEPLACER UN REPERTOIRE **
    // ************************************************************************
    /**
     * Déplacer un répertoire entier et ses sous-répertoire, exemple :<BR>
     * DirectoryToolkit.moveDirectory("c:/dev/", "c:/LOCAL/amoi/", "testsJava");<BR>
     * 
     * @param aCheminActuel
     * @param aCheminDestination
     * @param aRepertoire
     * @throws Exception If an error occurs
     */
    public static void moveDirectory( final String aCheminActuel , final String aCheminDestination ,
            final String aRepertoire ) throws Exception {
        // Reviens é copier, puis effacer
        copyDirectory( aCheminActuel , aCheminDestination , aRepertoire );
        deleteDirectory( aCheminActuel + aRepertoire );
    }

    // ************************************************************************
    // ** COPIER UN REPERTOIRE **
    // ************************************************************************
    /**
     * Copier un répertoire entier sans effacer le contenu de l'original, exemple :<BR>
     * DirectoryToolkit.copyDirectory("c:/dev/", "c:/LOCAL/amoi/", "testsJava");<BR>
     * 
     * @param aCheminActuel
     * @param aCheminDestination
     * @param aRepertoire
     * @throws Exception If an error occurs
     */
    public static void copyDirectory( final String aCheminActuel , final String aCheminDestination ,
            final String aRepertoire ) throws Exception {
        // OK copie de répertoire
        copyDirectory( new File( aCheminActuel + aRepertoire ) , new File( aCheminDestination + aRepertoire ) );
    }

    /**
     * Copier un répertoire entier sans effacer le contenu de l'original, exemple :<BR>
     * DirectoryToolkit.copyDirectory("c:/dev/", "c:/LOCAL/amoi/", "testsJava");<BR>
     * 
     * @param aRepertoireActuel
     * @param aCheminDestination
     * @throws Exception Si une erreur survient
     */
    public static void copyDirectory( final File aRepertoireActuel , final File aCheminDestination ) throws Exception {
        final File[] lFiles = aRepertoireActuel.listFiles(); // Récupération de tous les fichiers
        // du répertoire
        File lFile;
        File lTemp;
        final String lSEPARATOR = System.getProperty( "lFile.separator" );

        if ( lFiles != null ) {
            for ( int i = 0 ; i < lFiles.length ; ++i ) {
                lFile = lFiles&#91;i&#93;;
                System.out.println( new StringBuffer().append( "lFile.getName   = " ).append( lFile.getName() )
                        .toString() );
                System.out.println( new StringBuffer().append( "lFile.getParent = " ).append( lFile.getParent() )
                        .toString() );
                if ( lFile.isDirectory() ) { // Si le fichier traité est un répertoire
                    // Comme le répertoire de destination n'existe pas, je le crée
                    lTemp = new File( new StringBuffer().append( aCheminDestination ).append( lSEPARATOR ).append(
                            lFile.getName() ).toString() );
                    lTemp.mkdirs();
                    copyDirectory( lFile , lTemp ); // j'appelle cette méthode de faéon récursive
                }
                else { // Sinon je copie le fichier
                    // Si le répertoire de destination n'existe pas, je le crée
                    if ( !aCheminDestination.exists() ) {
                        createDirectory( aCheminDestination.getAbsolutePath() );
                    }
                    // Comme le fichier de destination n'existe pas, je le crée
                    lTemp = new File( new StringBuffer().append( aCheminDestination.getAbsolutePath() ).append(
                            lSEPARATOR ).append( lFile.getName() ).toString() );
                    copyFile( lFile.getAbsolutePath() , lTemp.getAbsolutePath() );
                }
            }
        }
        // copyFile(actualDirectory.getAbsolutePath(), destinationDirectory + lSEPARATOR +
        // actualDirectory.getName());
    }

    private static void copyFile( final String aSourceFile , final String aTargetFile ) throws Exception {
        final File lInputFile = new File( aSourceFile );
        final File lOutputFile = new File( aTargetFile );

        final FileInputStream lIn = new FileInputStream( lInputFile );
        final FileOutputStream lOut = new FileOutputStream( lOutputFile );
        int c;

        while ( ( c = lIn.read() ) != -1 )
            lOut.write( c );

        lIn.close();
        lOut.close();
    }

    // ************************************************************************
    // ** RENOMER UN REPERTOIRE **
    // ************************************************************************
    /**
     * Renomer un répertoire. Exemple :<BR>
     * DirectoryToolkit.renameDirectory("c:/dev/", "projectToto", "TotoProject");<BR>
     * 
     * @param aChemin
     * @param aNomActuel
     * @param aNouveauNom
     * @throws Exception If an error occurs
     */
    public static void renameDirectory( final String aChemin , final String aNomActuel , final String aNouveauNom )
            throws Exception {
        // OK ICI L'IMPLEMENTATION DOIT ETRE
        final File lActual = new File( aChemin + aNomActuel );
        lActual.renameTo( new java.io.File( aChemin + aNouveauNom ) );
    }
}

Java – Read a property file

CodeDevEnglish

Source to keep somewhere: read a property file in Java:

/*********************************************************/
/*            Récuperer un fichier properties            */
/*********************************************************/

import java.io.InputStream;
import java.util.Properties;

public class LoadProperties {

    private static Properties props = null;
    private static final String PROPERTY_FILE = "com/mytests/ejb/client/agent.properties";

    // Singleton
    private static LoadProperties instance = new LoadProperties();

    public static LoadProperties getInstance() {
        return instance;
    }

    private LoadProperties() {
        this.init();
    }

    private void init() {

        // If property isn't loaded
        if (props == null) {
            try {
                InputStream is = LoadProperties.class.getResourceAsStream(PROPERTY_FILE);
                if (is == null) {
                    throw  new Exception();
                }
                props = new Properties();
                props.load(is);
            }
            catch (Exception e) {
                System.out.println("Could not load property file!");
            }
        }
    }

    public String getProperty(String key) {
        return props.getProperty(key);
    }
}

Example of property file:

Access with:

String myValue = LoadProperties.getInstance().getProperty("mykey");

Java – Récupérer un fichier properties

CodeDevFrançais

Dans la série code à garder sous la main : récupérer un fichier properties en Java :

/*********************************************************/
/*            Récuperer un fichier properties            */
/*********************************************************/

import java.io.InputStream;
import java.util.Properties;

public class LoadProperties {

    private static Properties props = null;
    private static final String FICHIER_PROPERTIES = "com/mestests/ejb/client/agent.properties";

    // Singleton
    private static LoadProperties instance = new LoadProperties();

    public static LoadProperties getInstance() {
        return instance;
    }

    private LoadProperties() {
        this.init();
    }

    private void init() {

        // Si le fichier de properties n'est pas chargé : on le charge
        if (props == null) {
            try {
                InputStream is = LoadProperties.class.getResourceAsStream(FICHIER_PROPERTIES);
                if (is == null) {
                    throw  new Exception();
                }
                props = new Properties();
                props.load(is);
            }
            catch (Exception e) {
                System.out.println("Impossible de charger le fichier de configuration demandé !");
            }
        }
    }

    public String getProperty(String maClef) {
        return props.getProperty(maClef);
    }
}

Exemple de fichier properties:

Acces par:

String maValeur = LoadProperties.getInstance().getProperty("maclef");
  • 1
  • 5
  • 6