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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
package Torello.Java;

import java.io.*;
import java.util.*;
import javax.mail.internet.*;

/**
 * Some simple methods that make use of the Java Mail API.
 * 
 * <BR /><BR /><EMBED CLASS="external-html" DATA-FILE-ID="EML">
 */
public class EMailLists extends TreeMap<String, String[]>
{
    /** <EMBED CLASS="external-html" DATA-FILE-ID="SVUID">  */
    public static final long serialVersionUID = 1;

    /**
     * This stores the name of the data-file that contains the Rolodex information.
     * It is a <B><I>compressed</I></B> (ZIP-format Compression), java
     * <B><I>java.io.serializable</I></B> object file containing just a single
     * data object of type: "{@code java.util.TreeMap<String, String[]>}"
     */
    public final String DATA_FILE_NAME;

    /**
     * This simply takes the file name that has been provided via the {@code String diskFileName}
     * parameter, and loads that file to memory from disk.
     *
     * @param dataFileName The name of a datafile that has been stored somewhere on disk.  It is
     * stored as a {@code java interface java.io.Serializable} object file.  <B><I>The file that is
     * on disk will not be of type {@code EMailLists} but rather of type
     * {@code java.util.TreeMap<String, String[]>}, to ensure forward-compatability</I></B>.  This
     * conversion is done automatically within this class by the {@code public void writeToDisk()}
     * method.
     *
     * @return An instance of {@code class EMailLists} that has been fully instantiated and
     * populated with the Rolodex data that is stored within the data-file identified by the
     * data-file name provided in the parameter list.
     */
    public static EMailLists loadFromDisk(String dataFileName) throws IOException
    {
        @SuppressWarnings("unchecked")
        TreeMap<String, String[]> tm = (TreeMap<String, String[]>) FileRW.readObjectFromFileNOCNFE
            (dataFileName, TreeMap.class, true);

        return new EMailLists(dataFileName, tm, false);
    }

    /**
     * Loads an instance of this class from a {@code TreeMap<String, String[]>} - which may
     * or may or may not have been generated by this class.
     *
     * @param tm A map of e-mail address lists.
     *
     * @return An instance of {@code class EMailLists} that has been fully instantiated and
     * populated with the Rolodex data that is stored within the data-file identified by the
     * data-file name provided in the parameter list.
     */
    public static EMailLists fromTreeMap(TreeMap<String, String[]> tm)
    { return new EMailLists(null, tm, false); }

    /**
     * Loads this Rolodex from a MIME-{@code String}
     *
     * @param b64MimeEncoded The internal e-mail address {@code TreeMap} data, encoded as a 
     * base 64 MIME {@code String}.
     *
     * @return An instance of this class, derived from a {@code MIME-String} encoded data.
     */
    @SuppressWarnings("unchecked")
    public static EMailLists fromString(String b64MimeEncoded) throws IOException
    { return new EMailLists(null, (TreeMap<String, String[]>) StringParse.b64MimeStrToObj(b64MimeEncoded), false); }

    /**
     * This creates a brand new, empty "e-mail address Rolodex."  This class is a sub-class of 
     * {@code java.util.TreeMap<String, String[]>}
     *
     * @return A new instance of this class.
     *
     * <BR /><B>IMPORTANT NOTE:</B> A data-file for this class instance will not be created.
     * After saving some lists to this Rolodex, the user must execute a call to: <B>{@code public
     * void writeToDisk()}</B> in order to check the data in this data-structure out to disk.
     */
    public static EMailLists createNewInstance()
    { return new EMailLists(null, null, true); }


    /**
     * This loads a data-file that must have been generated by the <B>{@code interface
     * java.io.Serializable}</B>.  The contents of this data file <B><I>should be just one java
     * {@code java.lang.Object} of specific-type {@code java.util.TreeMap<String, String[]>}</I></B>
     *
     * @param dataFileName The name of the file where data will or should be stored.
     *
     * @param tm A {@code TreeMap} containing an e-mail address Rolodex.
     *
     * @param newInstance This should be set to <B>TRUE</B> if the user intends to create a
     * <I>brand new instance</I> of the EMailLists class.
     *
     * <BR /><BR /><B>NOTE:</B> If this variable is true, the disk-data file specified by
     * parameter {@code dataFileName} will not be visited.
     *
     * <BR /><BR /><B>CAUTION:</B> If this variable is set to <B>TRUE</B>, but there is already an
     * older data-file present on disk with this file-name, then <I>that file will be
     * over-written</I> with the first call the programmer makes to
     * {@code public void writeToDisk()}}.
     */
    protected EMailLists
        (String dataFileName, TreeMap<String, String[]> tm, boolean newInstance)
    {
        super();

        this.DATA_FILE_NAME = dataFileName;

        if (! newInstance) this.putAll(tm);
    }


    /**
     * This saves the data-contents of this class directly to disk.  It uses the
     * {@code interface java.io.Serializable} to save the data.
     *
     * <BR /><BR /><B>NOTE:</B> The data stored in this
     * <B>{@code class TreeMap<String, String[]>}</B>, which is indeed a parent-class that is
     * "extended" by this (the <B>{@code class EMailLists}</B>), is first converted back into the
     * parent TreeMap class.  This is done for one reason, and that is regarding Java's quirks in
     * {@code Object} serialization.  If future versions of {@code class EMailLists} are written,
     * previously serialized objects of type {@code Torello.Java.EMailLists} would cease to be
     * readable with the serializable interface.  In the method {@code public void writeToDisk()},
     * the contents of the Tree-Map are cloned into the parent TreeMap class, and only then are
     * they written to disk.
     */
    public void writeToDisk() throws IOException
    {
        if (DATA_FILE_NAME == null) throw new IllegalArgumentException(
            "This instance of EMailLists was not loaded from disk, so there is no data file-name " +
            "to write the TreeMap to."
        );

        TreeMap<String, String[]> temp = new TreeMap<>();

        temp.putAll(this);

        FileRW.writeObjectToFileNOCNFE(this, DATA_FILE_NAME, true);
    }

    /**
     * Writes this class' internal e-mail address data to disk.
     * 
     * @param fileName The name of the data-file to be used for writing.
     */
    public void writeToDisk(String fileName) throws IOException
    {
        TreeMap<String, String[]> temp = new TreeMap<>();

        temp.putAll(this);

        FileRW.writeObjectToFileNOCNFE(this, fileName, true);
    }

    /**
     * Writes this class' internal e-mail address data to an output {@code String}.
     *
     * @return This class' internal data as a Base-64 MIME Encoded {@code String}.
     */
    public String writeToString() throws IOException
    {
        TreeMap<String, String[]> temp = new TreeMap<>();

        temp.putAll(this);

        return StringParse.objToB64MimeStr(temp);
    }

    /**
     * This This prints the names of the lists to a {@code StringBuilder}, and how many e-mail
     * addresses are in each list.
     */
    public String summariesToString() throws IOException
    {
        StringBuilder sb = new StringBuilder();

        for (String s : keySet())
            sb.append(StringParse.zeroPad(get(s).length) + " elements in group: " + s);

        return sb.toString();
    }

    /**
     * This simply prints the contents of the underlying {@code TreeMap} data-structure using a
     * {@code StringBuilder}, and returns the {@code String}.
     * @return A String representation of the internal {@code TreeMap}
     */
    public String listsToString()
    {
        StringBuilder sb = new StringBuilder();

        for (String listName : keySet())
        {
            String[] list = get(listName);

            sb.append(
                "************************************************************************************************************\n" +
                "PRINTING LIST:\t" + listName + ", which has " + list.length + " elements.\n"
            );

            int count = 1;
            for (String eMailAddr : list) sb.append("[" + (count++) + ": " + eMailAddr + "], ");

            sb.append("\nThere were a total of " + (count-1) + " addresses in this subset.\n");
        }

        return sb.toString();
    }


    /**
     * This generates a simple, view-able, HTML file as a {@code String}.  The HTML
     * {@code String} that is returned does not contain header information, nor footer info.  It is
     * just a series of {@code <H1> List Name </H1>} followed by tables as
     * {@code <TABLE CLASS="EMailListsTable"> ... </TABLE>}.  The user needs to add opening and
     * closing HTML tags if this is to be a complete page with well-formatted HTML.
     *
     * @return The internal e-mail Rolodex data-structure as a series of HTML tables.
     */
    public String printToHTML() throws IOException
    {
        StringBuilder sb = new StringBuilder();
        sb.append("<STYLE type=\"text/css\">\n.EMailListsTable TD { width: 33%; }\n</STYLE>\n");

        for (String listName : keySet())
        {
            String[] list = get(listName);
            sb.append("<H1>" + listName + "</H1>\n<TABLE CLASS=\"EMailListsTable\" STYLE=\"width: 100%;\">");

            for (int i=0; i < list.length; i += 3)
                sb.append(
                    "<TR>\n" +
                    "<TD>" + list[i] + "</TD>\n" +
                    "<TD>" + (i+1 < list.length ? list[i+1] : " ") + "</TD>\n" +
                    "<TD>" + (i+2 < list.length ? list[i+2] : " ") + "</TD>\n" +
                    "</TR>\n"
                );

            sb.append("</TABLE>\n<BR /><BR />\n\n\n");
        }
        return sb.toString();
    }


    /**
     * This does a simple validity check by attempting to instantiate each e-mail address stored in
     * the {@code String[]} e-mail address {@code String Arrays} within the TreeMap by performing
     * this instantiation: {@code new javax.mail.internet.InternetAddress(eMailAddress); }
     *
     * <BR /><BR />If the above line of code throws an Exception, then this will be identified as
     * an "invalid e-mail address" and returned with the result set.  <B><I>Invalid e-mail
     * addresses are not removed from the data-structure</I></B>, but rather, they are returned
     * with the result set.
     *
     * <BR /><BR />If the parameter {@code boolean verbosePrint} is set to TRUE, messages will be
     * sent to {@code System.out.println(...)}
     *
     * @param listName The name of the list whose {@code String[] Array} contents need to be
     * checked here.
     *
     * @param verbosePrint When <B>TRUE</B>, messages will be sent to {@code System.out}
     *
     * @return A list of potentially improperly formed e-mail addresses.
     */
    public Vector<String> checkValidity(String listName, boolean verbosePrint)
    {
        Vector<String> ret = new Vector<String>();

        for (String emailAddress : get(listName))
            try
                { InternetAddress ia = new InternetAddress(emailAddress); System.out.print("."); }
            catch (Exception e)
            {
                if (verbosePrint) System.out.println(
                    "\nE-Mail Address:\t[" + emailAddress + "] from list:\t[" + listName + "] " +
                    "generated an Exception!"
                );

                ret.addElement(emailAddress);
            }

        return ret;
    }


    /**
     * This performs the validity check on each and every list in this {@code TreeMap}
     * data-structure.  It calls the method {@link #checkValidity(String, boolean)}
     *
     * @param verbosePrint When <B>TRUE</B>, messages will be sent to {@code System.out}
     *
     * @return A list of potentially improperly formed e-mail addresses.
     *
     * @see #checkValidity(String, boolean)
     */
    public Vector<String> checkValidity(boolean verbosePrint) throws IOException
    {
        Vector<String> ret = new Vector<String>();

        for (String listName : keySet())
        {
            if (verbosePrint) System.out.print("Working list: " + listName);

            ret.addAll(checkValidity(listName, verbosePrint));

            if (verbosePrint) System.out.println();
        }

        return ret;
    }


    /**
     * <B>NOTE:</B> The original name of this function was
     * {@code removePossibleDuplicatesAndSort(String)}, but was shortened to just "{@code clean}"
     *
     * <BR /><BR />This will go through the contents of the list identified by {@code 'listName'},
     * and ensure there are no duplicate e-mail addresses.  If there are, they will be removed.
     * The arrays are also sorted.  Each address stored in the {@code String Arrays} is converted
     * to lower-case text, and trimmed.
     *
     * <BR /><BR /><B>NOTE:</B> If this list has been modified, it is up to the user/programmer to
     * write the changes to the disk data-file.  Disk data-file writes are <B><I>not done
     * automatically</I></B>.  You need to concern yourself with this aspect.
     *
     * @param listName The name of the {@code String[] list} in the underlying
     * {@code java.util.TreeMap<String, String[]>} data-structure whose contents need to be pruned.
     *
     * @return The number of e-mail addresses that were removed from this subset of the Rolodex,
     * because there were duplicates present.
     */
    public int clean(String listName)
    {
        String[]        list        = get(listName);
        TreeSet<String> ts          = new TreeSet<String>();
        int             oldLength   = list.length;

        for (int i=0; i < oldLength; i++) ts.add(list[i].toLowerCase().trim());

        put(listName, ts.toArray(new String[0]));

        return oldLength - ts.size();
    }


    /**
     * The original name of this function was {@code removePossibleDuplicatesAndSort(String)},
     * but was shortened to just {@code 'cleanEachList()'}. This will remove all duplicates from
     * each and every list in the {@code TreeMap}.  The arrays will also be sorted.  Each address
     * stored in the {@code String[] array's} is converted to lower-case text, and trimmed.
     *
     * <BR /><B>IMPORTANT NOTE:</B> This will removed duplicates that are <B><I>identified on a on
     * a "list by list" basis.</I></B>  This means that in the case where there are two identical
     * e-mail addresses in a single list, one will be removed.  <B><I>HOWEVER</I></B>, if a single
     * e-mail address is present in multiple, different lists, this method will not catch that
     * scenario as a mistake.  If the programmer considers this scenario a mistake, it should be
     * important to remember that the underlying {@code TreeMap<String, String[]>} data-structure
     * is perfectly visible (as a super-class), and therefore can be modified in whatever way
     * 3rd-party programmers wish to change the contents of this data-structure.
     * 
     * <BR /><BR />The clean methods in this class are just designed to make sure that the arrays
     * themselves do not have multiple copies of the same address, because that is a guaranteed
     * "programmatically incorrect" scenario.  Having a single address distributed in multiple
     * lists, however, might easily a desired situation for some programmers.
     * 
     * <BR /><BR />This is why the method is called "cleanEachList" instead of just "clean" or
     * "cleanAll" - since they are done sequentially.
     *
     * @return The total number of e-mail addresses that were duplicates and were removed from all
     * lists in this Rolodex.
     */
    public int cleanEachList()
    {
        int total = 0;

        for (String listName : keySet()) total += clean(listName);

        return total;
    }


    /**
     * This will add the given e-mail address(es) to the specified list in this data structure.
     * The list that is stored back into the {@code String[] Array} will be sorted, and the
     * {@code String} elements will be made to lower-case text, and trimmed (using
     * {@code java.lang.String.trim()}).
     *
     * @param listName The name of the <I>already-existing list</I> in this {@code TreeMap}.
     *
     * @param eMailAddress One or more e-mail addresses to be added to this list
     *
     * @throws IllegalArgumentException This will throw an exception if:
     *
     * <BR /><BR /><UL CLASS="JDUL">
     * <LI> This {@code String[] Array} specified by parameter {@code 'listName'} in the
     *      {@code TreeMap} already contains a copy of this e-mail address
     * </LI>
     * <LI> The passed parameter {@code String[] eMailAddress} has multiple copies of the same
     *      address
     * </LI>
     * <LI> The instantiation {@code new javax.mail.internet.InternetAddress(eMailAddress)}
     *      generates an exception
     * </LI>
     * </UL>
     */
    public void addAddress(String listName, String... eMailAddress)
    {
        TreeSet<String> ts      = new TreeSet<String>();
        String[]        curList = get(listName);

        for (String address : curList) ts.add(address.trim().toLowerCase());

        for (String address : eMailAddress)
        {
            try
                { new InternetAddress(address = address.trim().toLowerCase()); }
            catch (Exception e)
            {
                throw new IllegalArgumentException(
                    "E-Mail Address: [" + address + "] is not a valid address.  It generated an " +
                    "exception:\n" + e.getMessage()
                );
            }

            if (! ts.add(address)) throw new IllegalArgumentException
                ("E-Mail Address: [" + address + "] is already in the list: [" + listName + "]");
        }

        put(listName, ts.toArray(new String[0]));
    }

    /**
     * Removes the specified e-mail addresses from the list specified by the
     * {@code String listName} parameter.
     *
     * @param listName The name of the <I>already-existing list</I> in this {@code TreeMap}.
     *
     * @param eMailAddress One or more e-mail addresses to be added to this {@code String[] Array}
     * e-mail address list.
     *
     * @throws IllegalArgumentException This will throw an exception if one or more of the
     * requested addresses to be removed <I><B>is/are not actually present in the underlying
     * {@code String[] Array}</I></B> associated with {@code listName}.
     */
    public void removeAddress(String listName, String... eMailAddress)
    {
        TreeSet<String> ts      = new TreeSet<String>();
        String[]        curList = get(listName);

        for (String address : curList) ts.add(address.trim().toLowerCase());

        for (String address : eMailAddress)
            if (! ts.remove(address = address.trim().toLowerCase()))
                throw new IllegalArgumentException
                    ("E-Mail Address: [" + address + "] is not in the list: [" + listName + "]");

        put(listName, ts.toArray(new String[0]));
    }

    /**
     * This will create a new section in the Rolodex with the name of this list.  If the Rolodex
     * already contains a list by this name, the two lists will be merged.
     *
     * @param listName This is the name "Rolodex subsection."  It is an element in the
     * {@code TreeMap}, and contains one list of e-mail addresses.
     *
     * @param newAddressListFileName This is a list of e-mail addresses, stored in a text-file.
     * The name of the text-file to load may be provided here.  The format of the file expects
     * new addresses to be included, one per line.
     *
     * @return Whether updating a list that already exists, or creating a brand new list - the
     * e-mail addresses that are found in the text file ({@code 'newAddressListFileName'}) will
     * be checked for validity.  Checking for validity simply means calling Java's {@code class
     * InternetAddress} constructor, and waiting to see if the address may be instantiated, or if
     * it generates an exception.  If an exception does occur, that address will be skipped, and
     * the exception will be saved in the response {@code TreeMap}.
     *
     * <BR /><BR />The response tree-map simply contains a list of the e-mail addresses that were
     * problems to instantiate with the {@code class javax.mail.internet.InternetAddress}
     * <I><B>in the TreeMap key field</B></I>.  In the lookup/value field of the {@code TreeMap},
     * the exception that was generated will be provided.
     */
    public TreeMap<String, Exception> updateList
        (String listName, String newAddressListFileName) throws IOException
    {
        TreeSet<String>             ts                  = new TreeSet<String>();
        String[]                    curAddrList         = get(listName);
        TreeMap<String, Exception>  errors              = new TreeMap<>();
        Vector<String>              newAddrList         = FileRW.loadFileToVector(newAddressListFileName, false);

        // Make sure that all the elements in the old list (if there is one!) are trimmed and lower-case
        if (curAddrList != null)
            for (String addr : curAddrList) ts.add(addr.trim().toLowerCase());

        // Make sure all the newly loaded e-mail addresses are trim/lower-case
        newAddrList.replaceAll(addr -> addr.trim().toLowerCase());

        // Make sure that each new address does not cause an exception when instantiating.
        for (String addr : newAddrList)
            try                 { new InternetAddress(addr.trim().toLowerCase()); }
            catch (Exception e) { errors.put(addr, e); }

        // Add only the "safe addresses" to this list.
        for (String addr : newAddrList) if (! errors.containsKey(addr)) ts.add(addr);

        // Convert the new list to an array
        String[]                    newAddrListAsArr    = new String[ts.size()];
        int                         i                   = 0;

        for (String addr : ts) newAddrListAsArr[i++] = addr;
        put(listName, newAddrListAsArr);

        if (errors.size() > 0) return errors; else return null;
    }

    /**
     * Facilitates a (very) small console-driven menu for adding and removing addresses to specific
     * lists.  At the BASH/UNIX/MS-DOS console, execute a call to:
     * {@code java Torello.Java.EMailLists } to see this {@code printMenu()} help menu command
     * output.  Follow instructions from there.
     *
     * <BR /><BR /><B>NOTE:</B> Menu Option #1 will ask you to specify the name of your e-mail
     * list data-file.  It will not create one for your, but rather, just save that file-name to
     * a temporary text-file in your current working directory.  This will be used for the duration
     * of your console session.
     */
    public static void printMenu()
    {
        System.out.println(
            "1: set temporary text-file pointer  ... SPECIFICALLY: argv[0]=\"1\", argv[1]=your-email-data-file-name" +
            "2: printLists();" +
            "3: addAddress(argv[1], argv[2]);    ... SPECIFICALLY: argv[0]=\"3\", argv[1]=list-name, argv[2]=e-mail address" +
            "4: removeAddress(argv[1], argv[2]); ... SPECIFICALLY: argv[0]=\"4\", argv[1]=list-name, argv[2]=e-mail address"
        );

        System.exit(0);
    }

    /**
     * This will facilitate a (very) small console-driven command program to add or remove e-mail
     * lists to and from already existent lists.  If incorrect command-line arguments are not
     * provided, the help menu is printed to console.
     */
    public static void main(String argv[]) throws IOException
    {
        if (argv.length < 1) printMenu();
        
        if (argv[0].equals("1"))
            if (argv.length != 2)   printMenu();
            else                    FileRW.writeFile(argv[1] + "\n", "EMAIL_LISTS_TEMP_FILE.txt");

        EMailLists lists = EMailLists.loadFromDisk
            (FileRW.loadFileToString("EMAIL_LISTS_TEMP_FILE.txt").trim());

        if (argv[0].equals("2"))
            if (argv.length != 1)   printMenu();
            else                    System.out.print(lists.listsToString());

        if (argv[0].equals("3"))
            if (argv.length != 3)   printMenu();
            else                    { lists.addAddress(argv[1], argv[2]); lists.writeToDisk(); }

        if (argv[0].equals("4"))
            if (argv.length != 3)   printMenu(); 
            else                    { lists.removeAddress(argv[1], argv[2]); lists.writeToDisk(); }
    }
}