/*
 * This file is part of DebGen Biobank Software developed by ASTRID Research.
 * All rights reserved. Reproduction, modification, use or disclosure
 * to third parties without express authority is forbidden.
 *
 * Copyright ASTRID Research Inc., Hungary, 2009-2011.
 *
 * ASTRID Research
 * Headquaters: Csapo utca 42. Debrecen H-4029 HUNGARY
 * Phone: +36-52-533-173        Fax: +36-52-533-174
 * Web: http://www.astrid.hu    E-mail: info@astrid.hu
 *
 * Project name: DebGen Biobank Software project.
 * URLS:
 * Developers: Istvan Zoltan Nagy (istvan.nagy@astrid.hu)
 */
package hu.astrid.debgen.mail.service;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Class to validate email addresses.
 * @author István Zoltán Nagy
 */
public class EmailValidator {

    /**
     * The regular expression used to validate the address.
     */
    private static String EMAIL_REGEX = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+([\\.-][A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
            //"^(\\w(([-._]{0,1})\\w)*\\w@\\w(([-._]{0,1})\\w)*\\w\\.\\w{2,4})$";
//    private static String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";

    /**
     * Validates the mail string.
     * @param mail the String to validate.
     * @return true if mail is valid, false otherwise.
     */
    public static boolean isValid(String mail) {
        if (mail == null) {
            return false;
        }
        if (mail.matches(EMAIL_REGEX)) {
            return ((EmailValidator.getResponseCode("http://www." + mail.substring(mail.indexOf("@") + 1)) != 404) || (EmailValidator.getResponseCode("http://" + mail.substring(mail.indexOf("@") + 1)) != 404));
        } else {
            return false;
        }
    }

    /**
     * Gets the HTTP response code when the URL is opened, or 404 if an error occures.
     * @param urlString The URL to open.
     * @return code The response code or 404 if error occures.
     */
    private static int getResponseCode(String urlString) {
        try {
            URL u = new URL(urlString);
            HttpURLConnection huc = (HttpURLConnection) u.openConnection();
            huc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
            huc.setRequestMethod("GET");
            huc.connect();
            return huc.getResponseCode();
        } catch (MalformedURLException ex) {
            return 404;
        } catch (IOException ex) {
            return 404;
        }
    }
}
