Category: Code

Scala – Scalatra – Salat – MongoDB : test drive

CodeDevEnglishTutorials

Hello there, a little test with Scala (2.9.0-1) for the backend services, Scalatra for the REST part, Salat and MongoBB for the persistance layer. I will use sbt (0.10) for the project management and you should use IntelliJ Idea IDE (what else ? ).

What this test does ?

It exposes a REST API (and its documentation) in order to play with a user (login, email, password). This API is extremely simplified, so you understand easely the concepts.
The objective is to :
– add a user,
– get a user (with its id or login),
– delete a user
– have the API documentation online for each method
Keep reading

Scala – Scalatra – Salat – MongoDB : découverte

CodeDevFrançaisTutorials

Bonjour, un petit test avec Scala (2.9.0-1) pour la partie service, Scalatra concernant le front en REST, Salat et MongoBB pour la persistance des données. J’utiliserai sbt (0.10) pour la gestion du projet et IntelliJ Idea comme IDE (What else ?).

Qu’allons nous voir ici ?

Nous allons exposer une API REST (et sa documentation associée) afin de créer des utilisateurs (identifiant, courriel, mot de passe). Cette API est extrèmement simple afin de bien comprendre ce qui se passe.
L’objectif est donc de pouvoir :
– créer un utilisateur,
– trouver un utilisateur (avec son ID ou son identifiant),
– effacer un utilisateur
– visualiser la documentation de chaque API en ligne pour chacune des méthodes
Keep reading

Code generator with ant FMPP and FreeMarker

CodeDevEnglish

A simple code generator example with FMPP and FreeMarker with the help of ant and antelope for automation.

Content :
– Why should we do code generators ?
– How it works
– Prepare ant tasks
– Let’s try with a simple file
– Now let’s do something bigger

Why should we do code generators
Some people are…pretty anxious when I advocate the use of a code generator. Most of the time they think spending time on a code generator isn’t productive enough for their short term objectives… These kind of person spend their lives running to catch a train that goes to fast for their capacity. Actually, code generators are a perfect answer for short term project, but not the first one (and again this isn’t obvious).

Code generators are part of your company’s (or personal) normalisation, industrialisation, and process simplification.
– Developers can focus more on business than technical implementation,
– Maintenance is easier : all code base is similar
– If your company turnover is important, process are simpler to acquire

So actually you can code faster, with a better quality, the ROI is always (if code generator is correctly done) positive.

How it works
Creating a code generator project is really fast, just :
1- use a real project you want to generate and copy it somewhere,
2- identify the dynamic stuff inside this project, like :
– classnames,
– packages,
– folders,
– …
3- replace dynamic patterns with a property tag
4- generate it once and do the adjustments if needed

In order to have an idea, a code generator creating around fifty files, that creates a Flex module with BlazeDS Java endpoints takes about 4 hours of work and tuning before beiing live.

Prepare ant tasks
Download Fmpp and AntelopeTasks jars and put them inside your ANT_HOME/lib folder.
Then inside your build.xml add those 2 lines after your project definition :

1
2
<taskdef name="antelope" classname="ise.antelope.tasks.StringUtilTask" />
<taskdef name="fmpp" classname="fmpp.tools.AntTask" />

Now to use fmpp just do something like this inside a target :

1
2
3
4
5
6
<fmpp sourceRoot="${basedir}/src/MODULE/entity_and_code"
      outputroot="${module_base_dir}/${entity_and_code}"
      alwaysCreateDirectories="true"
      logfile="${basedir}/logs/${entity_and_code}.log" >
  <data>antProperties()</data>
</fmpp>

Antelope in this project will be used mostly for its lowercase/upperCase/replace commands. Example :

1
2
3
4
5
6
7
<property name="entity_and_code" value="${entity_and_project}_${module_code}" />
<antelope string="${entity_and_code}" property="entity_and_code">
  <lowercase />
</antelope>
<antelope string="${entity_and_code}" property="ENTITY_AND_CODE">
  <uppercase />
</antelope>

Let’s try with a simple file

You can get the files here : QQ_CG01.tar

The src folder contains this hierarchy : fr/quidquid/sample/flex/modules/MODULE_CODE
This folder contains the ModuleConstants.as file.

Inside the ModuleConstants.as file you’ll find freemarker tags :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package ${module_base_package}.flex.${module_code}
{
    public class  ModuleConstants{
 
        // ***********************************************
        // ******** EVENTS FOR ${module_code?upper_case}_${module_name}
 
        public static const EVENT_${module_code?upper_case}_TESTBUTTON_SUBMIT:String = "EVENT_${module_code?upper_case}_TESTBUTTON_SUBMIT";
 
        // ####_DO_NEVER_(RE)MOVE_THIS_LINE_NOR_CHANGE_IT_#### EVENTS
 
        // ***********************************************
        // ******** NOTIF FOR ${module_code?upper_case}_${module_name}
 
        public static const NOTIF_${module_code?upper_case}_I18N_GET_OK:String = "NOTIF_${module_code?upper_case}_I18N_GET_OK";
 
        // ####_DO_NEVER_(RE)MOVE_THIS_LINE_NOR_CHANGE_IT_#### NOTIF
 
    }
}

Our goal is to replace these tags and after generation rename the MODULE_CODE folder with the right name.

First step to see how it works, in the root folder open the PROJECT.properties, it contains our dynamic stuffs (quite simple on this example):

1
2
3
4
5
6
7
8
9
# Output folder of the code generator
output_dir = OUT
 
# Base package, will be suffixed with the module_code upper case
module_base_package = fr.quidquid.sample.flex.modules
# Functionnal name
module_name = Quidquid Test
# Module unique name in the whole application
module_code = QQT01

Then let’s look at the build.xml file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<project name="SimpleCodeGenerator" default="generate" basedir=".">
 
  <!-- Initialize antelope and fmpp -->
  <taskdef name="antelope" classname="ise.antelope.tasks.StringUtilTask" />
  <taskdef name="fmpp" classname="fmpp.tools.AntTask" />
 
  <target name="generate">
 
    <!-- Get properties from property file -->
    <property file="${basedir}/PROJECT.properties" />
 
    <!-- I need module_code to be lower case -->
    <antelope string="${module_code}" property="module_code">
      <lowercase />
    </antelope>
     
    <!-- I need module_base_package to be lower case -->
    <antelope string="${module_base_package}" property="module_base_package">
      <lowercase />
    </antelope>
    <!-- Get the path from the package ( just replaces . with / )-->
    <antelope string="${module_base_package}" property="module_base_path">
      <replace regex="\." replacement="/" />
    </antelope>
 
    <!-- MODULE GENERATION -->
    <fmpp sourceRoot="${basedir}/src/"
          outputroot="${output_dir}/"
          alwaysCreateDirectories="true"
          logfile="${basedir}/${module_code}.log" >
      <data>antProperties()</data>
    </fmpp>
 
    <!-- Rename the module folder -->
    <move todir="${output_dir}/${module_base_path}/${module_code}">
      <fileset dir="${output_dir}/${module_base_path}/MODULE_CODE" />
    </move>
 
  </target>
 
</project>

You can now open a command line ant do:

1
[julien@mars QQ_CG01]# ant

Output should be something like:

Now you should have an OUT folder containing your fr/quidquid/sample/flex/modules/qqt01/ModuleConstants.as with all the freemarker tags replaced… Easy no ?

Some freeMarker expressions you can use:
${module_code?upper_case}
${module_code?lower_case}
${module_code?cap_first}

To change the name of a filename:
<@pp.dropOutputFile />
<@pp.changeOutputFile name=module_name?cap_first + "Mediator.as" />

Well just go through the manual: http://freemarker.sourceforge.net/docs/dgui_template_exp.html

.

CastorHelper

CodeDevFrançais

Dans la série code à garder sous la main : Une classe pour travailler Castor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package com.ledruide.utils.xml;
 
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
 
import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;
import org.xml.sax.InputSource;
 
public class CastorHelper {
 
    private CastorHelper() {}
 
    private static final String ENCODING = "UTF-16";
 
    /**
     * Permet de creer un fichier contenant le XML genere
     *
     * @param monObjet la classe contenant les donnees a 'castoriser'
     * @param mappingFile le fichier XML de mapping pour savoir quoi faire avec l'Objet
     * @throws Exception si une erreur survient.
     */
    public static String saveXMLFile( Object monObjet , String mappingFile ) throws Exception {
        try {
 
            StringWriter content = new StringWriter();
            // First look into the classpath
            InputStream is = CastorHelper.class.getResourceAsStream( mappingFile );
            // If the input stream is not OK I look into the filesystem
            if ( is == null ) {
                is = new FileInputStream( mappingFile );
            }
            // Chargement du mapping
            Mapping mapping = new Mapping();
            mapping.loadMapping( new InputSource( is ) );
            // Marshal l'object -> La transformation de Java en XML !
            final Marshaller marshaller = new Marshaller( content );
            marshaller.setValidation( false );
            marshaller.setMapping( mapping );
            marshaller.setEncoding( ENCODING );
            marshaller.marshal( monObjet );
 
            return content.toString();
        }
        catch ( Exception e ) {
            throw e;
        }
    }
 
    /**
     * Permet de lire un fichier XML contenant les donnees
     *
     * @param aClasse la classe d'implémentation des donnees a 'decastoriser'
     * @throws Exception si une erreur survient.
     */
    public static void loadXMLFile( Object monObjet , String mappingFile , String xml ) throws Exception {
        try {
            // First llok into the classpath
            InputStream is = CastorHelper.class.getResourceAsStream( mappingFile );
            // If the input stream is not OK I look into the filesystem
            if ( is == null ) {
                is = new FileInputStream( mappingFile );
            }
 
            // Chargement du mapping
            Mapping mapping = new Mapping();
            mapping.loadMapping( new InputSource( is ) );
            // UnMarshal l'object -> La transformation XML vers Java !
            Unmarshaller unmarshaller = new Unmarshaller( monObjet );
            unmarshaller.setWhitespacePreserve( true );
            unmarshaller.setMapping( mapping );
            monObjet = unmarshaller.unmarshal( new FileReader( xml ) );
        }
        catch ( Exception e ) {
            throw e;
        }
    }
 
    /**
     * @param result
     * @return
     * @throws IOException
     * @throws MarshalException
     * @throws ValidationException
     */
    public static String dynamicXmlFromObject( Object object ) throws Exception {
        StringWriter content = new StringWriter();
        final Marshaller marshaller = new Marshaller( content );
        marshaller.setValidation( false );
        marshaller.setEncoding( ENCODING );
        marshaller.setSuppressXSIType(true);
        marshaller.marshal( object );
 
        return content.toString();
    }
 
}

Java Connexion LDAP

CodeDevFrançais

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/*********************************************************/
/*            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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
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

1
 

/*********************************************************/
/* 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]

  • 1
  • 2