001/*
002 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Nuxeo - initial API and implementation
016 *     Vilogia - Mail address formatting
017 *
018 */
019
020package org.nuxeo.ecm.platform.mail.web.converter;
021
022import java.util.regex.Matcher;
023import java.util.regex.Pattern;
024
025import javax.faces.component.UIComponent;
026import javax.faces.context.FacesContext;
027import javax.faces.convert.Converter;
028
029import static java.util.regex.Pattern.*;
030
031/**
032 * Simple mail address converter: most of the addresses imported from the POP3 or IMAP mailbox simply return the string
033 * "null <mail.address@domain.org>". To avoid a list of nulls this converter removes the "null" aliases and only keep
034 * the mail address. Also return a mailto: link to the sender.
035 *
036 * @author <a href="mailto:christophe.capon@vilogia.fr">Christophe Capon</a>
037 */
038public class MailAddressConverter implements Converter {
039
040    private static final String EMAIL_REGEXP = "(.*)<([A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4})>";
041
042    private static final Pattern pattern = compile(EMAIL_REGEXP, CASE_INSENSITIVE);
043
044    public Object getAsObject(FacesContext ctx, UIComponent uiComp, String inStr) {
045        return inStr;
046    }
047
048    public String getAsString(FacesContext ctx, UIComponent uiComp, Object inObj) {
049        if (null == inObj) {
050            return null;
051        }
052
053        if (inObj instanceof String) {
054            String inStr = (String) inObj;
055            Matcher m = pattern.matcher(inStr);
056
057            if (m.matches()) {
058                String alias = m.group(1);
059                String email = m.group(2);
060
061                if (alias.trim().toLowerCase().equals("null")) {
062                    alias = email;
063                }
064
065                return String.format("<a href=\"mailto:%s\">%s</a>", email, alias);
066
067            } else {
068                return inStr;
069            }
070        } else {
071            return inObj.toString();
072        }
073    }
074
075}