com.sunrun.crportal.util.CRPortalUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.sunrun.crportal.util.CRPortalUtil.java

Source

package com.sunrun.crportal.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.rmi.RemoteException;
import java.security.SecureRandom;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.SimpleTimeZone;
import java.util.TimeZone;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import javax.portlet.RenderRequest;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.rpc.ServiceException;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import com.cdyne.pav3.IPavService;
import com.cdyne.pav3.ZipCodesResponse;
import com.liferay.mail.service.MailServiceUtil;
import com.liferay.portal.NoSuchUserException;
import com.liferay.portal.kernel.cache.MultiVMPoolUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.mail.MailMessage;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.Company;
import com.liferay.portal.model.Group;
import com.liferay.portal.model.User;
import com.liferay.portal.model.UserGroup;
import com.liferay.portal.service.GroupServiceUtil;
import com.liferay.portal.service.UserGroupLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.sunrun.crportal.beans.CustomerAccountBean;
import com.sunrun.crportal.beans.AccountDetailsBean;
import com.sunrun.crportal.constants.CRPortalConstants;
import com.sunrun.crportal.datasource.beans.CustomerPaymentPreferenceBean;
import com.sunrun.crportal.datasource.beans.InvoiceSummaryBean;
import com.sunrun.crportal.exceptions.BestBillNoSuchInvoiceException;
import com.sunrun.crportal.exceptions.CRPortletException;
import com.sunrun.crportal.exceptions.NoCustomerLogonException;
import com.sunrun.crportal.exceptions.NoSunRunHomeException;
import com.sunrun.crportal.gateway.AccountInfoModel;
import com.sunrun.crportal.gateway.AccountModel;
import com.sunrun.crportal.gateway.GatewayException;
import com.sunrun.crportal.gateway.SFDCGateway;
import com.sunrun.crportal.gateway.SunRunAccountGateway;
import com.sunrun.crportal.webservices.account.ResidentialCustomer010000;
import com.sunrun.crportal.webservices.account.SunRunHome010000;
import com.sunrun.crportal.webservices.pavservice.PavServiceLocator;

/*
 * Utility methods for the SR CP.
 */
public class CRPortalUtil {

    /*
     * Encrypt/Decrypt methods for CP2.0.
     */
    static final String CP2_URL_ENCRYPTION_KEY = "CP2.0-Encryption";
    final static Log LOG = LogFactory.getLog(CRPortalUtil.class);
    //final static SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss.sssz");
    final static String df = "EEE, d MMM yyyy HH:mm:ss.sssz";

    /*
     * Methods to randomize and unrandomize a string using a basic algorithm that
     * inserts random characters inside the original string.
     */
    static final int RANDOM_SUBSTRING_SIZE = 4;

    public static User addCustomerUserToLRDatabase(String customerId, Company co, String emailAddress,
            String password) throws PortalException, SystemException, NumberFormatException, GatewayException {
        // TODO-CP2.0 Cleanup this code.
        ResidentialCustomer010000 residentialCustomer = null;
        AccountModel accountModel = new SunRunAccountGateway();
        residentialCustomer = (ResidentialCustomer010000) accountModel.getCustomer(Integer.parseInt(customerId));

        long creatorUserId = 0;
        boolean autoPassword = false; // we have to set the password to something. replace this in the // future with something smarter
        boolean autoScreenName = false;
        Locale locale = Locale.US;
        password = "replaceme";
        String userScreenName = customerId;
        String firstName = residentialCustomer.getFirstName();
        String middleName = null;
        String lastName = residentialCustomer.getLastName();
        long facebookId = 99;
        long[] ids;
        ids = new long[0];
        long[] communityIds = new long[2];
        communityIds[0] = co.getGroup().getGroupId();
        //Add the SUNRUNHOME.COM community
        Group group = GroupServiceUtil.getGroup(co.getCompanyId(), "Guest");
        communityIds[1] = group.getGroupId();
        //communityIds[1] = 10527;
        int prefixId = 0;
        int suffixId = 0;
        boolean male = true;
        int birthdayMonth = Calendar.JANUARY;
        int birthdayDay = 1;
        int birthdayYear = 1970;
        String jobTitle = null;
        boolean sendEmail = false; // setting password to null returns errors (actually null)
        User user = UserLocalServiceUtil.addUser(creatorUserId, co.getCompanyId(), autoPassword, password, password,
                autoScreenName, userScreenName, emailAddress, facebookId, customerId, locale, firstName, middleName,
                lastName, prefixId, suffixId, male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
                communityIds, ids, ids, ids, sendEmail, null);

        LOG.info("Added the customer user with " + emailAddress + " to the Liferay database.");

        return user;
    }

    /**
     * Add preserved parameters (doAsUserId etc, for instance) to the URL
     * @param request
     * @param url
     * @return
     */
    public static String addPreservedParameters(HttpServletRequest request, String url) {
        ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
        return PortalUtil.addPreservedParameters(themeDisplay, url);
    }

    public static void buildAccountDetailsBean(RenderRequest renderRequest, AccountDetailsBean accountDetailsBean)
            throws GatewayException {
        AccountInfoModel SFDCaccountmodel = new SFDCGateway();
        SFDCaccountmodel.getAccountDetails(renderRequest, accountDetailsBean);
    }

    public static void buildAccountDetailsBean(int sunRunHomeId, AccountDetailsBean accountDetailsBean)
            throws GatewayException {
        AccountInfoModel SFDCaccountmodel = new SFDCGateway();
        SFDCaccountmodel.getAccountDetails(sunRunHomeId, accountDetailsBean);
    }

    /*
     * A utility method to convert a string into a Calendar object
     */
    public static Calendar convertFromStringToCalendar(String sDate, String dateFormat, TimeZone tz) {
        Calendar calDate = null;
        SimpleDateFormat formatter;
        Date date;

        if (CRPortalUtil.isValidDate(sDate, dateFormat)) {
            formatter = new SimpleDateFormat(dateFormat);
            //formatter.setTimeZone(tz);
            try {
                date = (Date) formatter.parse(sDate);
                calDate = Calendar.getInstance(tz);
                calDate.setTime(date);
            } catch (java.text.ParseException e) {
                LOG.warn(e.getMessage());
                LOG.warn("Setting date to null");
            }
        }
        return calDate;
    }

    public static String decryptURL(String s) {

        String sDecrypted = "";

        try {
            // Decrypt using Blowfish algorithm.
            Cipher cipher = Cipher.getInstance("Blowfish");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(CP2_URL_ENCRYPTION_KEY.getBytes(), "Blowfish"));
            sDecrypted = new Base64(true).encodeToString(cipher.doFinal(s.getBytes()));

        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return sDecrypted;
    }

    /**
     * Create a cipher using a session random key and an id
     * @param userSessionRandomKey
     * @param id
     * @return String, the created cipher
     * @throws CRPortletException
     */
    public static String cipherCreate(String userSessionRandomKey, int id) throws CRPortletException {
        String cipherString = null;
        String subject = null;

        subject = userSessionRandomKey + id;
        cipherString = CRPortalUtil._cipherCreate(subject);

        return cipherString;
    }

    /**
     * Common method to generate an SHA-512 cipher
     * @param subject
     * @return
     * @throws CRPortletException
     */
    private static String _cipherCreate(String subject) throws CRPortletException {
        String cipherString = null;

        cipherString = DigestUtils.sha512Hex(subject);

        return cipherString;
    }

    /**
     * Compares a cipher submitted as part of a URL with one generated by the application
     * using the arguments used to build the UTL's cipher
     * @param userSessionRandomKey
     * @param id
     * @param submitedCyper
     * @return true if they are the same, false otherwise
     * @throws CRPortletException
     */
    public static boolean cipherCompare(String userSessionRandomKey, int id, String submitedCyper)
            throws CRPortletException {
        boolean isValid = false;

        String subject = null;
        String generatedCipher = null;

        subject = userSessionRandomKey + id;
        generatedCipher = CRPortalUtil._cipherCreate(subject);
        isValid = submitedCyper.equals(generatedCipher);

        return isValid;
    }

    public static String encryptURL(String s) {

        String sEncrypted = null;

        if (s != null) {
            try {
                // Encrypt using Blowfish algorithm.
                Cipher cipher = Cipher.getInstance("Blowfish");
                cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(CP2_URL_ENCRYPTION_KEY.getBytes(), "Blowfish"));
                // line length 100, nothing at EOL, URL safe
                sEncrypted = new Base64(100, new byte[] {}, true).encodeToString(cipher.doFinal(s.getBytes()));

            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
            }
        } else {
            sEncrypted = "InputWasNull";
        }
        return sEncrypted;
    }

    public static void generateInvoicePDF(ResourceRequest request, ResourceResponse response) throws IOException {
        try {
            LOG.info("invoiceId = " + request.getParameter("invoiceId"));
            LOG.info("invoiceCypher = " + request.getParameter("AUTH"));

            //Ensure this is a valid invoice
            String userSessionRandomKey = CRPortalUtil.getSessionAttribute(request, "USER_Session_Random_Key");
            int invoiceId = new Integer(request.getParameter("invoiceId")).intValue();
            String submitedEncryptedInvoiceId = request.getParameter("AUTH");
            boolean isValidInvoice = CRPortalUtil.cipherCompare(userSessionRandomKey, invoiceId,
                    submitedEncryptedInvoiceId);
            if (isValidInvoice) {
                BestBill b = new BestBill("TBD");
                // b.getInvoice(348940);
                b.getInvoice(new Integer(request.getParameter("invoiceId")).intValue());
                response.setContentType("application/pdf");
                response.getPortletOutputStream().write(b.getResponseBody().getBytes("8859_1"));
                response.getPortletOutputStream().flush();
                response.getPortletOutputStream().close();
            } else {
                LOG.info("Unable to show invoice");
                //TODO: Improve this error handling
            }
        } catch (BestBillNoSuchInvoiceException e) {
            SessionErrors.add(request, e.getClass().getName(), e);

            response.setContentType("text/html");

            HttpServletRequest httpRequest = PortalUtil.getHttpServletRequest(request);
            String url = PortalUtil.getCurrentURL(httpRequest);
            String path = url.substring(0, url.indexOf("?"));
            String urlToRedirect = PortalUtil.getPortalURL(httpRequest) + path;
            String htmlCodeRedirect = "<html><head><meta http-equiv=\"Refresh\" content=\"1;url=" + urlToRedirect
                    + "\" /></head><body></body></html>";

            OutputStream out = response.getPortletOutputStream();
            out.write(htmlCodeRedirect.getBytes());
            out.flush();
            out.close();
        } catch (Exception e) {
            SessionErrors.add(request, e.getClass().getName());
        }
    }

    public static String getAgreementTypeFromMostRecentInvoice(InvoiceSummaryBean invoice) {
        if (invoice.getConsolidatedMeterSummaries() != null) {
            if (invoice.getConsolidatedMeterSummaries().length > 0) {
                String leaseType = pricingPlanCodeToAgreementType
                        .get(invoice.getConsolidatedMeterSummaries()[0].getPricingPlanId());
                if (leaseType != null) {
                    return leaseType;
                }
            }
        }
        return UNKNOWN;
    }

    public static String getAgreementTypeFromPaymentPreference(CustomerPaymentPreferenceBean prefs) {
        String leaseType = pricingPlanCodeToAgreementType.get(prefs.getPricingPlanCode());
        return (leaseType != null ? leaseType : UNKNOWN);
    }

    /*
     * getCRPortalProperty = Retrieves the URL for a particular web service.
     * 
     * @param  propertyKey  The property for which to get the web service url
     * 
     * @return the property value representing the web service URL, null if not found
     */
    public static String getCRPortalProperty(String propertyKey) {
        LOG.debug("* ---------------------------------------------------------- *");
        LOG.debug("* getCRPortalProperty - Entering                             *");
        LOG.debug("* ---------------------------------------------------------- *");

        LOG.debug("   getCRPortalProperty - Property Key = " + propertyKey);

        ResourceBundle rb;
        String propertyValue = null;

        try {
            rb = ResourceBundle.getBundle("content/CRPortal");
            propertyValue = rb.getString(propertyKey);
        } catch (NullPointerException npe) {
            LOG.warn("Property not found: " + propertyKey + ". Using default: " + propertyValue);
            propertyValue = null;
        } catch (MissingResourceException mre) {
            LOG.warn("Property not found: " + propertyKey + ". Using default: " + propertyValue);
            propertyValue = null;
        }

        LOG.debug("   getCRPortalProperty - Property Value = " + propertyValue);
        LOG.debug("* ---------------------------------------------------------- *");
        LOG.debug("* getCRPortalProperty - Exiting                              *");
        LOG.debug("* ---------------------------------------------------------- *");
        return propertyValue;
    }

    //Utility function to retrieve the portlet's heading
    public static String getCurrentURL(PortletRequest r) {
        ThemeDisplay themeDisplay = (ThemeDisplay) r.getAttribute(WebKeys.THEME_DISPLAY);
        return themeDisplay.getURLCurrent();
    }

    public static String getCustomerIdBySRHId(Integer SRHomeId, String dwrAjaxErrorMessage) {
        String SRCustomerId = null;
        ResidentialCustomer010000 SRCustomer = null;
        try {
            SRCustomer = getCustomerBySRHId(SRHomeId);
        } catch (CRPortletException e) {
            e.printStackTrace();
        }

        SRCustomerId = SRCustomer != null ? String.valueOf(SRCustomer.getId()) : dwrAjaxErrorMessage;
        return SRCustomerId;
    }

    public static ResidentialCustomer010000 getCustomerBySRHId(Integer SRHomeId) throws CRPortletException {
        SunRunAccountGateway accountGateway = new SunRunAccountGateway();
        ResidentialCustomer010000 SRCustomer = accountGateway.getCustomerBySunRunHomeid(SRHomeId);
        return SRCustomer;
    }

    public static CustomerAccountBean getCustomerAccountBean(PortletRequest request) throws CRPortletException {
        CustomerAccountBean custAccountBean;
        HttpServletRequest httpRequest = PortalUtil.getHttpServletRequest(request);
        HttpSession session = httpRequest.getSession();

        if (session.getAttribute("CustomerAccountDetails") == null) {
            custAccountBean = new CustomerAccountBean();
            custAccountBean.setSRCustomerId(getSRCustomerId(request));
            custAccountBean.setSRHomeId(getSunRunHomeId(request));
            custAccountBean.setSRAllHomeIds(getSunRunAllHomeIds(request));
            custAccountBean.setSFDCAccountId(getSFDCAccountId(request));
            custAccountBean.setUserSessionRandomKey((String) session.getAttribute("USER_Session_Random_Key")); // used for creating cipher text (invoiceId, caseId ..) 

            session.setAttribute("CustomerAccountDetails", custAccountBean);
        } else {
            custAccountBean = (CustomerAccountBean) session.getAttribute("CustomerAccountDetails");
            custAccountBean.setSRHomeId(getSunRunHomeId(request)); // update the current SRHomeId set in session
        }

        return custAccountBean;
    }

    public static String getCustomerName(HttpServletRequest httpServletRequest, String emailAddress) {
        LOG.debug("Inside getCustomerName");
        Long companyId = null;
        String customerName = "";
        AccountModel m = new SunRunAccountGateway();
        ResidentialCustomer010000 crPortalResidentialCustomer;
        ThemeDisplay themeDisplay = (ThemeDisplay) httpServletRequest.getAttribute(WebKeys.THEME_DISPLAY);
        companyId = themeDisplay.getCompanyId();
        try {
            User user = UserLocalServiceUtil.getUserByEmailAddress(companyId, emailAddress);
            int customerId = Integer.valueOf(user.getScreenName());
            crPortalResidentialCustomer = (ResidentialCustomer010000) m.getCustomer(customerId);
            customerName = crPortalResidentialCustomer.getFirstName();
            LOG.debug("CustomerName" + customerName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return customerName;
    }

    public static String getCybersourceHopConfigurationProperty(String transactionType) {
        return getCybersourceHopConfigurationProperty(transactionType, null);
    }

    public static String getCybersourceHopConfigurationProperty(String transactionType, String invoiceType) {

        StringBuilder propertyName = new StringBuilder(CRPortalConstants.CYBERSOURCE_PROPERTY_ROOT);
        propertyName.append(transactionType);

        if (invoiceType != null) {
            if (CRPortalConstants.MONTHLY_INVOICE.equals(invoiceType)) {
                propertyName.append("-lease");
            } else if (CRPortalConstants.UPFRONT_INVOICE.equals(invoiceType)) {
                propertyName.append("-upfront");
            }
        }
        return propertyName.toString();
    }

    public static String getDateString(Calendar calDate, String frmtDate) {
        String strDate = null;
        SimpleDateFormat df = new SimpleDateFormat(frmtDate);

        strDate = df.format(calDate.getTimeInMillis());

        return strDate;
    }

    public static String[] getZipcodesForCityAndState(String city, String state) throws RemoteException {

        final int ZIP_SUCCESS = 0;
        final int ZIP_INVALID_INPUT = 1;
        final int ZIP_INVALID_LICENSE = 2;
        String authkey = getCRPortalProperty("billing-accountlist-cdyne-license-key");
        IPavService service = null;
        try {
            service = new PavServiceLocator().getpavsoap();
        } catch (ServiceException e) {
            LOG.error("AddressVerifier failed to initialize.", e);
        }
        ZipCodesResponse z = service.getZipCodesForCityAndState(city, state, authkey);
        switch (z.getReturnCode().intValue()) {
        case ZIP_SUCCESS:
            return z.getZipCodes();
        case ZIP_INVALID_INPUT:
            throw new RemoteException("Invalid input.");
        case ZIP_INVALID_LICENSE:
            throw new RemoteException("Invalid license.");
        default:
            return new String[] {};
        }
    }

    public static Document getDocumentBuilder(String fileName) {
        Document doc = null;
        DocumentBuilderFactory dbf = null;
        DocumentBuilder db = null;
        File file = null;

        dbf = DocumentBuilderFactory.newInstance();
        try {
            db = dbf.newDocumentBuilder();

            File dir1 = new File(".");
            File dir2 = new File("..");
            String tomcatDir = System.getProperty("catalina.base");
            try {
                System.out.println("Current   dir : " + dir1.getCanonicalPath());
                System.out.println("Parent    dir : " + dir2.getCanonicalPath());
                System.out.println("tomcatDir dir : " + tomcatDir);
            } catch (Exception e) {
                e.printStackTrace();
            }
            file = new File(fileName);

            if (file.exists()) {
                doc = db.parse(file);
            }
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return doc;
    }

    public static Object getJAXBRootObject(String xmlFile, @SuppressWarnings("rawtypes") Class classToBeBound)
            throws CRPortletException {
        Object rootObject;
        try {
            JAXBContext jc = JAXBContext.newInstance(classToBeBound);
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            rootObject = unmarshaller.unmarshal(new FileInputStream(CRPortalUtil.getTestDataFilePath(xmlFile)));
        } catch (Exception e) {
            throw new CRPortletException(e.getLocalizedMessage(), e);
        }
        return rootObject;
    }

    public static User getLiferayUser(PortletRequest req) throws CRPortletException {
        try {
            return UserLocalServiceUtil.getUserById(getUserId(req));
        } catch (Exception e) {
            throw new CRPortletException(e.getLocalizedMessage(), e);
        }
    }

    public static Calendar getPtoDate(int sunRunHomeId) {
        Calendar ptoDate = null;
        SFDCGateway gateaway = null;

        try {
            //Attempt to retrieve it from SFDC.
            gateaway = new SFDCGateway();
            ptoDate = gateaway.getGenAssetPtoDate(sunRunHomeId);

        } catch (CRPortletException e) {
            e.printStackTrace();
        }

        return ptoDate;
    }

    public static ResourceBundle getResourceBundle() {
        return ResourceBundle.getBundle("content/Language");
    }

    public static ResourceBundle getResourceBundle(HttpServletRequest request) {
        //Locale locale = (Locale)request.getSession().getAttribute("org.apache.struts.action.LOCALE");
        //String language = locale.getLanguage();
        //ResourceBundle res = ResourceBundle.getBundle("content/Language", new Locale(language, country));
        return ResourceBundle.getBundle("content/Language");
    }

    public static Throwable getRootException(Throwable exception) {
        if (exception.getCause() != null) {
            return getRootException(exception.getCause());
        }
        return exception;
    }

    public static String getSessionAttribute(PortletRequest request, String sessionAttributeKey)
            throws CRPortletException {
        String sessionAttribute = null;

        HttpServletRequest httpRequest = PortalUtil.getHttpServletRequest(request);
        HttpSession session = httpRequest.getSession();
        sessionAttribute = (String) session.getAttribute(sessionAttributeKey);

        if (sessionAttribute == null) {
            throw new CRPortletException("sessionAttributeKey is null - serious error");
        }
        return sessionAttribute;
    }

    /**
     * get SFDCAccountId of the user from session. This SFDCAccountId is set in session in DefaultLandingPageAction,
     * that is immediately after successful login
     */
    public static String getSFDCAccountId(PortletRequest request) throws CRPortletException {
        HttpServletRequest httpRequest = PortalUtil.getHttpServletRequest(request);
        HttpSession session = httpRequest.getSession();
        String sfdcAccountId = (String) session.getAttribute("USER_SFDCAccountId");

        if (sfdcAccountId == null) {
            throw new CRPortletException("SFDCAccountId is null - serious error");
        }
        return sfdcAccountId;
    }

    /*
     * The SunRun Customer ID is stored in the LR user screen name field.
     * 
     * Some code may set the SunRunCustomerId in the session; if so, give the session variable precedence.
     */
    public static int getSRCustomerId(PortletRequest req) throws CRPortletException {
        if (getSunRunCustomerIdFromSession(req) != null) {
            return getSunRunCustomerIdFromSession(req).intValue();
        }
        try {
            return new Integer(UserLocalServiceUtil.getUser(getUserId(req)).getScreenName()).intValue();
        } catch (Exception e) {
            throw new CRPortletException(e.getLocalizedMessage(), e.getCause());
        }
    }

    public static String getStateFullName(String stateAbbreviation) {
        String stateName = "unknown";

        if (stateMap.containsKey(stateAbbreviation.toUpperCase())) {
            stateName = stateMap.get(stateAbbreviation.toUpperCase()).toLowerCase();
        }

        return stateName;
    }

    /**
     * Get the SunRunCustomerId from the session.
     * @param ActionRequest
     * @return int, the SunRunCustomerId
     * @throws CRPortletException
     */
    public static Integer getSunRunCustomerId(User user) throws CRPortletException {
        int SRCustomerId = 0;
        String strSRCustomerId = null;

        strSRCustomerId = user.getScreenName();
        SRCustomerId = new Integer(strSRCustomerId);

        return SRCustomerId;
    }

    /**
     * Get the SunRunCustomerId from the session.
     * @param PortletRequest
     * @return int, the SunRunCustomerId
     * @throws CRPortletException
     */
    public static Integer getSunRunCustomerIdFromSession(PortletRequest pr) throws CRPortletException {
        HttpServletRequest httpRequest = PortalUtil.getHttpServletRequest(pr);
        return (Integer) httpRequest.getSession().getAttribute("SunRunCustomerId");
    }

    /*
     * Attempts to get the Session's SunRunHomeId; if not found in the Session,
     * get the first one and add it to the session.
     * 
     * TODO: Ensure that when the user selects a new installation the session's
     * SunRunHomeId is updated accordingly.
     */
    public static int getSunRunHomeId(PortletRequest pr) throws CRPortletException {
        int sunRunHomeId = 0;
        SunRunAccountGateway srag = new SunRunAccountGateway();
        HttpServletRequest httpRequest = PortalUtil.getHttpServletRequest(pr);
        HttpSession session = httpRequest.getSession();

        if (session.getAttribute("SunRunHomeId") == null) {
            //Get the first for the customer
            sunRunHomeId = srag.getFirstSRHomeId(pr);

            //Save it in the session
            session.setAttribute("SunRunHomeId", sunRunHomeId);
            //pr.getPortletSession().setAttribute("SunRunHomeId", sunRunHomeId, PortletSession.APPLICATION_SCOPE);

        } else {
            sunRunHomeId = (Integer) session.getAttribute("SunRunHomeId");
        }
        return sunRunHomeId;
    }

    /*
     * getSunRunHomesForCustomer - Given a RenderRequest returns the SunRun homes
     * associated with the current account
     * 
     * @param RenderRequest
     * 
     * @return SunRunHome010000[int], or null if none
     */
    public static SunRunHome010000[] getSunRunHomesForCustomer(PortletRequest request) throws CRPortletException {

        int SRCustomerId = CRPortalUtil.getSRCustomerId(request);
        return getSunRunHomesForCustomer(SRCustomerId);
    }

    public static SunRunHome010000[] getSunRunHomesForCustomer(int SRCustomerId) throws CRPortletException {
        SunRunHome010000[] sunRunHomes = null;
        AccountModel am = new SunRunAccountGateway();
        sunRunHomes = am.getSunRunHomes(SRCustomerId);
        return sunRunHomes;
    }

    public static List<Integer> getSunRunAllHomeIds(PortletRequest request) throws CRPortletException {
        List<Integer> srAllHomeIds = new ArrayList<Integer>();
        SunRunHome010000[] sunRunHomes = getSunRunHomesForCustomer(request);

        for (SunRunHome010000 srHome : sunRunHomes) {
            srAllHomeIds.add(srHome.getSunRunHomeId());
        }
        return srAllHomeIds;
    }

    public static String getTestAccounts() {
        String testAccounts = null;
        ResourceBundle rb = ResourceBundle.getBundle("content/CRPortal");
        testAccounts = rb.getString("test-accounts");

        return testAccounts;
    }

    public static String getTestDataFilePath(String testDataFileName) {
        //Build the test data XML file full file name
        String tomcatDir = System.getProperty("catalina.base");
        String testDataFolder = tomcatDir
                + "/webapps/CRPortal-portlet/WEB-INF/classes/com/sunrun/crportal/beans/jaxb";

        return testDataFolder + "/" + testDataFileName;
    }

    public static User getUser(PortletRequest portletRequest, String emailAddress) throws CRPortletException {
        User user = null;
        Company company = null;

        try {
            company = PortalUtil.getCompany(portletRequest);
            user = UserLocalServiceUtil.getUserByEmailAddress(company.getCompanyId(), emailAddress);
        } catch (NoSuchUserException e) {
            LOG.debug("No such user with email address : " + emailAddress);
        } catch (Exception e) {
            throw new CRPortletException(e.getLocalizedMessage(), e);
        }
        return user;
    }

    /*
     * Get a user's LR userid from the RenderRequest object.
     * The LR userid is stored in the req.getUserPrincipal().getName() method (I think).
     */
    public static int getUserId(PortletRequest req) throws CRPortletException {
        if (req.getUserPrincipal() != null) {
            return new Integer(req.getUserPrincipal().getName()).intValue();
        }
        throw new CRPortletException("PortletRequest doesn't contain a logged in user.");
    }

    public static String getUserSessionRandomKey(HttpServletRequest httpRequest) {
        String userSessionRandomKey = null;
        HttpSession session = httpRequest.getSession();

        if (session.getAttribute("USER_Session_Random_Key") == null) {
            SecureRandom random = new SecureRandom();
            userSessionRandomKey = new BigInteger(130, random).toString(128);

            session.setAttribute("USER_Session_Random_Key", userSessionRandomKey);
        } else {
            userSessionRandomKey = (String) session.getAttribute("USER_Session_Random_Key");
        }
        return userSessionRandomKey;
    }

    public static String getValueFromCookies(HttpServletRequest request, String cookieName) {
        String cookieValue = "";
        Cookie[] cookieArray = request.getCookies();
        if (cookieArray != null) {
            for (int i = 0; i < cookieArray.length; i++) {
                Cookie aCookie = cookieArray[i];
                if (cookieName.equals(aCookie.getName())) {
                    cookieValue = aCookie.getValue();
                }
            }
        }
        return cookieValue;
    }

    /**
     * Checks if the user belongs to usergroups that require Dockbar access to use the menu items, for instance 
     * MarketingAdmin users will use Dockbar > Add application > WebContentDisplay 
     * @param request
     * @return
     * @throws PortletException
     */
    public static Boolean hasDockbarAccess(PortletRequest request) throws PortletException {
        LOG.debug("Leaving hasDockbarAccess()");
        Boolean hasPermission = false;

        HttpServletRequest httpServletRequest = PortalUtil
                .getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));
        ThemeDisplay themeDisplay = (ThemeDisplay) httpServletRequest.getAttribute(WebKeys.THEME_DISPLAY);
        User user = themeDisplay.getUser();
        long userId = themeDisplay.getUserId();

        LOG.debug("User Email: " + user.getEmailAddress());
        LOG.debug("User Id: " + userId);

        List<UserGroup> userGroups = null;
        try {
            userGroups = UserGroupLocalServiceUtil.getUserUserGroups(userId);
        } catch (SystemException e) {
            throw new PortletException(e.getLocalizedMessage(), e);
        }
        for (UserGroup userGroup : userGroups) {
            if (getCRPortalProperty("marketingadmin-usergroup").equals(userGroup.getName().trim())) {
                hasPermission = true;
            }
        }

        LOG.debug("hasPermission : " + hasPermission);
        LOG.debug("Leaving hasDockbarAccess()");
        return hasPermission;
    }

    /**
     * Impersonator's are restricted to edit the details of Impersonatee through EDIT mode unless they belong to certain Usergroups.
     * The EDIT link will be made visible in the portlet's VIEW mode only if this method return true.  
     * 
     * @param request
     * @return
     * @throws PortletException 
     */
    public static Boolean hasEditPermission(PortletRequest request) throws CRPortletException {
        LOG.debug("Entering hasEditPermission()");
        Boolean hasPermission = false;

        HttpServletRequest httpServletRequest = PortalUtil
                .getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));
        ThemeDisplay themeDisplay = (ThemeDisplay) httpServletRequest.getAttribute(WebKeys.THEME_DISPLAY);
        User realUser = themeDisplay.getRealUser();
        long realUserId = themeDisplay.getRealUserId();

        LOG.debug("RealUser Email: " + realUser.getEmailAddress());
        LOG.debug("RealUser Id: " + realUserId);

        if (httpServletRequest.getParameter("doAsUserId") != null) { // check for impersonation
            LOG.debug("Impersonator access..");
            List<UserGroup> userGroups = null;
            try {
                userGroups = UserGroupLocalServiceUtil.getUserUserGroups(realUserId);
            } catch (SystemException e) {
                throw new CRPortletException(e.getLocalizedMessage(), e);
            }
            for (UserGroup userGroup : userGroups) {
                // only the Impersonator users associated to CustomerCareAdmin usergroup is allowed to edit details of Impersonatee
                if (getCRPortalProperty("customercareadmin-usergroup").equals(userGroup.getName().trim())
                        || CRPortalUtil.getCRPortalProperty("admin-usergroup").equals(userGroup.getName().trim())) {
                    hasPermission = true;
                }
            }
        } else {
            // for ordinary users (non-impersonators)
            hasPermission = true;
        }
        LOG.debug("hasPermission : " + hasPermission);
        LOG.debug("Leaving hasEditPermission()");
        return hasPermission;
    }

    /**
     * Check if the user belongs to usergroups having ImpersonateUser role
     * @param request
     * @return
     * @throws PortletException
     */

    public static Boolean hasImpersonateUserRole(PortletRequest request) throws CRPortletException {
        LOG.debug("Entering hasImpersonateUserRole()");
        Boolean hasPermission = false;

        HttpServletRequest httpServletRequest = PortalUtil
                .getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));
        ThemeDisplay themeDisplay = (ThemeDisplay) httpServletRequest.getAttribute(WebKeys.THEME_DISPLAY);
        User user = themeDisplay.getUser();
        long userId = themeDisplay.getUserId();

        LOG.debug("User Email: " + user.getEmailAddress());
        LOG.debug("User Id: " + userId);

        List<UserGroup> userGroups = null;
        try {
            userGroups = UserGroupLocalServiceUtil.getUserUserGroups(userId);
        } catch (SystemException e) {
            throw new CRPortletException(e.getLocalizedMessage(), e);
        }
        for (UserGroup userGroup : userGroups) {
            // only the following usergroups has ImpersonateUser Role
            if (getCRPortalProperty("customercareadmin-usergroup").equals(userGroup.getName().trim())
                    || getCRPortalProperty("customercareuser-usergroup").equals(userGroup.getName().trim())
                    || getCRPortalProperty("operationsuser-usergroup").equals(userGroup.getName().trim())
                    || getCRPortalProperty("accountinguser-usergroup").equals(userGroup.getName().trim())
                    || getCRPortalProperty("admin-usergroup").equals(userGroup.getName().trim())) {
                hasPermission = true;
            }
        }

        LOG.debug("hasPermission : " + hasPermission);
        LOG.debug("Leaving hasImpersonateUserRole()");
        return hasPermission;
    }

    /**
     * Check if the new logon emailAddress already exist for the user 
     * @param SRHomeId
     * @param logonEmailId
     * @return
     */
    public static Boolean isEmailMatchCustomerEmail(int SRHomeId, String logonEmailId) throws CRPortletException {
        boolean emailAlreadyExist = false;

        // check if emailAddress exist in SFDC
        AccountInfoModel sfdc = new SFDCGateway();

        String custEmailAddress = sfdc.getCustomerEmailAddress(SRHomeId);
        if (logonEmailId.equals(custEmailAddress)) {
            emailAlreadyExist = true;
        } else {
            // check if emailAddress exist in Contract db
            AccountModel am = new SunRunAccountGateway();
            ResidentialCustomer010000 customer = am.getCustomerByEmailAddress(logonEmailId);
            emailAlreadyExist = (customer != null) ? true : false;
        }
        return emailAlreadyExist;
    }

    /**
     * Overloaded for Ajax request
     */
    public static Boolean isEmailMatchCustomerEmail(Integer SRHomeId, String logonEmailId,
            String dwrAjaxErrorMessage) {
        Boolean emailAlreadyExist = false;

        try {
            emailAlreadyExist = isEmailMatchCustomerEmail(SRHomeId, logonEmailId);
        } catch (CRPortletException e) {
            e.printStackTrace();
        }
        return emailAlreadyExist;
    }

    public static boolean isMobileRequest(PortletRequest r) {
        ThemeDisplay themeDisplay = (ThemeDisplay) r.getAttribute(WebKeys.THEME_DISPLAY);
        return themeDisplay.getURLCurrent().startsWith("/group/guest/mobile/");
    }

    public static boolean isSunRunEmployeeUser(String emailAddress) {
        return emailAddress != null && emailAddress.endsWith("sunrunhome.com");
    }

    /*
     * isValidDate - Validates that a date, formated as a string, is formated as
     * MM/dd/yyyy, and that it is a valid date
     */
    public static boolean isValidDate(String date) {
        // Set the required date format
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

        // Declare and initialize testDate variable, this is what will hold our 
        // converted string
        Date testDate = null;

        // Attempt to parse the string into date form
        try {
            testDate = sdf.parse(date);
        }
        // If the format of the string provided doesn't match the required format 
        // declared in SimpleDateFormat() we will get an exception
        catch (Exception e) {
            return false;
        }
        // dateformat.parse will accept any date as long as it's in the defined 
        // format, it simply rolls dates over, for example, december 32 becomes 
        // jan 1 and december 0 becomes november 30.
        //
        // This statement will make sure that once the string has been checked for 
        // proper formatting that the date is still the date that was entered, if 
        // it's not, we assume that the date is invalid
        if (!sdf.format(testDate).equals(date)) {
            return false;
        }

        // if we make it to here without getting an error it is assumed that
        // the date was a valid one and that it's in the proper format
        return true;
    } // end isValidDate

    /*
     * US Valid zipcode - CDYNE WEBSERVICES.
     */
    public static boolean isValidZipcode(String city, String state, String zipcode) {
        boolean validzipcode = false;
        String ziparr[];
        try {
            ziparr = getZipcodesForCityAndState(city, state);
            for (int i = 0; i < ziparr.length; i++) {
                if ((zipcode).equals(ziparr[i])) {
                    validzipcode = true;
                }
                if (validzipcode)
                    break;
            }
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return validzipcode;
    }

    /**
     * check if user and realUser are same (non-impersonated users)
     * @param request
     * @return
     */
    public static Boolean isUserTheRealUser(PortletRequest request) {
        HttpServletRequest httpServletRequest = PortalUtil
                .getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));
        ThemeDisplay themeDisplay = (ThemeDisplay) httpServletRequest.getAttribute(WebKeys.THEME_DISPLAY);
        return themeDisplay.getUserId() == themeDisplay.getRealUserId();
    }

    /*
     * isValidDate - Validates that a date, formated as a string, is formated as
     * MM/dd/yyyy, and that it is a valid date
     */
    public static boolean isValidDate(String date, String dateFormat) {
        // Set the required date format
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);

        // Declare and initialize testDate variable, this is what will hold our 
        // converted string
        Date testDate = null;

        // Attempt to parse the string into date form
        try {
            testDate = sdf.parse(date);
        }
        // If the format of the string provided doesn't match the required format 
        // declared in SimpleDateFormat() we will get an exception
        catch (Exception e) {
            return false;
        }
        // dateformat.parse will accept any date as long as it's in the defined 
        // format, it simply rolls dates over, for example, december 32 becomes 
        // jan 1 and december 0 becomes november 30.
        //
        // This statement will make sure that once the string has been checked for 
        // proper formatting that the date is still the date that was entered, if 
        // it's not, we assume that the date is invalid
        if (!sdf.format(testDate).equals(date)) {
            return false;
        }

        // if we make it to here without getting an error it is assumed that
        // the date was a valid one and that it's in the proper format
        return true;
    } // end isValidDate

    /**
     * Masks all the characters of a string leaving the last four
     * @param number
     * @return
     */
    public static String maskSecuredNumber(String number) {
        final int NUM_LAST_CHARS_NO_MASK = 4;
        StringBuilder maskedNumber = new StringBuilder();
        int startIndex = 0;
        if (number != null && number.length() > NUM_LAST_CHARS_NO_MASK) {
            startIndex = number.length() - NUM_LAST_CHARS_NO_MASK;
            for (int i = 0; i < startIndex; i++) {
                maskedNumber.append("x");
            }
            maskedNumber.append(number.substring(startIndex));
        } else {
            return number;
        }
        return maskedNumber.toString();
    }

    public static void processException(Throwable ex, PortletRequest request) {
        Throwable e = getRootException(ex);

        if (e instanceof NoSunRunHomeException) {
            SessionErrors.add(request, NoSunRunHomeException.class.getName());
        } else if (e instanceof NoCustomerLogonException) {
            SessionErrors.add(request, NoCustomerLogonException.class.getName());
        } else {
            SessionErrors.add(request, CRPortletException.class.getName());
        }
    }

    public static String randomize(String s) {
        // TODO: Implement randomizer
        return s;
    }

    public static void removeCacheObject(String cacheName, String cacheKey) {
        MultiVMPoolUtil.remove(cacheName, cacheKey);
        LOG.info("Cleared the cache Name: " + cacheName + " Key: " + cacheKey);
    }

    public static Properties resourceBundleToProperties(ResourceBundle rb) {
        Properties properties = new Properties();

        Enumeration<String> keys = rb.getKeys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            properties.put(key, rb.getString(key));
        }

        return properties;
    }

    /**
     * sendEmail - Sends an email
     * @param msgSubject
     * @param msgBody
     * @param emailAddress
     * @throws PortletException
     */
    public static void sendEmail(String msgSubject, String msgBody, String emailAddress) throws PortletException { //MDSW-2443
        LOG.debug("Entering sendEmail()");

        InternetAddress from;
        InternetAddress to;
        try {
            from = new InternetAddress("no-reply@sunrunhome.com"); //MDSW-2443
            to = new InternetAddress(emailAddress); //MDSW-2443

            MailMessage message = new MailMessage(from, to, msgSubject, msgBody, true); //MDSW-2443
            MailServiceUtil.sendEmail(message); //MDSW-2443
        } catch (AddressException e) { //MDSW-2443
            LOG.error("Invalid email address");
            e.printStackTrace();
        }

        LOG.debug("Leaving sendEmail()");
    }

    /*
     * getLastDayOfTheMonth - Returns the last day of the month
      * See: http://www.java2s.com/Tutorial/Java/0040__Data-Type/Getthelastdayofamonth.htm
      * 
      */
    public static void setCalendarToLastDayOfTheMonth(Calendar thisDate) {
        int lastDate;

        lastDate = thisDate.getActualMaximum(Calendar.DATE);
        thisDate.set(Calendar.DATE, lastDate);
        thisDate.add(Calendar.DAY_OF_MONTH, 0);
    }

    /*
     * setCalendarToDayOfMonth - Sets a Calendar date to have a fixed hour
     */
    public static void setCalendarToDayOfMonth(Calendar cal, int dayOfTheMonth) {
        cal.set(Calendar.DAY_OF_MONTH, dayOfTheMonth);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        cal.add(Calendar.MILLISECOND, 0); //force setting the dates
    }

    /*
     * setNewCalendar - Borrows the day, month, and year from the Calendar argument
     * and generated a new Calendar taking into account the time zone
     */
    public static Calendar setNewCalendar(Calendar oldCalendar, TimeZone tz) {

        LOG.debug("* ---------------------------------------------------------- *");
        LOG.debug("* setNewCalendar - Entering                                  *");
        LOG.debug("* ---------------------------------------------------------- *");

        SimpleDateFormat sdf = new SimpleDateFormat(df);
        //sdf.setTimeZone(tz);
        LOG.debug("   setNewCalendar - oldCalendar = " + sdf.format(oldCalendar.getTimeInMillis()));
        LOG.debug("   setNewCalendar - TimeZone    = " + tz.getID());

        Calendar newCalendar = null;

        DateFormat dfm;
        int intDay;
        int intMonth;
        int intYear;
        Date dtRightNow = null;
        String strRightNow;

        intDay = oldCalendar.get(Calendar.DAY_OF_MONTH);
        intMonth = oldCalendar.get(Calendar.MONTH);
        intYear = oldCalendar.get(Calendar.YEAR);

        strRightNow = "";
        strRightNow += intYear;
        strRightNow += "-";
        strRightNow += intMonth + 1;
        strRightNow += "-";
        strRightNow += intDay;
        LOG.debug("   setCalendar - strRightNow = " + strRightNow);
        try {
            dfm = new SimpleDateFormat("yyyy-MM-dd");
            //dfm.setTimeZone(tz);
            dtRightNow = dfm.parse(strRightNow);
            newCalendar = Calendar.getInstance(tz);
            newCalendar.setTime(dtRightNow);
            LOG.debug("   setNewCalendar - newCalendar    = " + sdf.format(newCalendar.getTimeInMillis()));
            LOG.debug("   setNewCalendar - newCalendar TZ = " + newCalendar.getTimeZone().getID());
        } catch (java.text.ParseException e) {
            LOG.warn(e.getMessage());
            LOG.debug("   setNewCalendar - defaultFromDate = null");
        }

        LOG.debug("* ---------------------------------------------------------- *");
        LOG.debug("* setNewCalendar - Exiting                                   *");
        LOG.debug("* ---------------------------------------------------------- *");
        return newCalendar;
    }

    public static String unRandomize(String s) {
        // TODO: Implement unrandomizer
        return s;
    }

    /*
     * useTestData - There are two ways to request a portlet to use test data instead
     * of production data:
     * 1 - In portlet.xml, to set up the portlet to use test data, regardless of
     * of the account. To do so set up the portlet's init-args UseTestData to yes.
     * 2 - In CRPortal.properties, to set up the portlet to use test data only for
     * a given account. To do so add the account's login email to the test-accounts
     * property.
     */
    public static boolean useTestData(String sUuseTestData, RenderRequest rr) {
        boolean _useTestData = false;

        if (sUuseTestData.equalsIgnoreCase("yes")) {
            _useTestData = true;
        } else {
            _useTestData = CRPortalUtil.isTestAccount(rr);
        }

        return _useTestData;
    }

    /*
     * zeroCalendarHHH_MM_SS_MMM - Sets a Calendar date to have a fixed hour
     */
    public static void zeroCalendarHHH_MM_SS_MMM(Calendar cal) {
        if (cal != null) {
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 1);
            cal.add(Calendar.MILLISECOND, 0); //force setting the dates
        }
    }

    public static TimeZone getPacificTimeZone() {
        TimeZone tz = new SimpleTimeZone(-28800000, "America/Los_Angeles");
        return tz;
    }

    public static void initToDateHH_MM_SS_mmm(Calendar cal) {
        if (cal != null) {
            cal.set(Calendar.HOUR_OF_DAY, 23);
            cal.set(Calendar.MINUTE, 59);
            cal.set(Calendar.SECOND, 59);
            cal.set(Calendar.MILLISECOND, 999);
            cal.add(Calendar.MILLISECOND, 0); //force setting the dates
        }
    }

    @SuppressWarnings("serial")
    private static Map<String, String> stateMap = new HashMap<String, String>() {
        {
            put("AK", "Alaska");
            put("AL", "Alabama");
            put("AR", "Arkansas");
            put("AZ", "Arizona");
            put("CA", "California");
            put("CO", "Colorado");
            put("CT", "Connecticut");
            put("DE", "Delaware");
            put("FL", "Florida");
            put("GA", "Georgia");
            put("HI", "Hawaii");
            put("IA", "Iowa");
            put("ID", "Idaho");
            put("IL", "Illinois");
            put("IN", "Indiana");
            put("KS", "Kansas");
            put("KY", "Kentucky");
            put("LA", "Louisiana");
            put("MA", "Massachusetts");
            put("MD", "Maryland");
            put("ME", "Maine");
            put("MI", "Michigan");
            put("MN", "Minnesota");
            put("MO", "Missouri");
            put("MS", "Mississippi");
            put("MT", "Montana");
            put("NC", "North Carolina");
            put("ND", "North Dakota");
            put("NE", "Nebraska");
            put("NH", "New Hampshire");
            put("NJ", "New Jersey");
            put("NM", "New Mexico");
            put("NV", "Nevada");
            put("NY", "New York");
            put("OH", "Ohio");
            put("OK", "Oklahoma");
            put("OR", "Oregon");
            put("PA", "Pennsylvania");
            put("RI", "Rhode Island");
            put("SC", "South Carolina");
            put("SD", "South Dakota");
            put("TN", "Tennessee");
            put("TX", "Texas");
            put("UT", "Utah");
            put("VA", "Virginia");
            put("VT", "Vermont");
            put("WA", "Washington");
            put("WI", "Wisconsin");
            put("WV", "West Virginia");
            put("WY", "Wyoming");
        }
    };

    /*
     * Map a Pricing Plan Code to a Agreement Type based on a fixed mapping.
     */
    @SuppressWarnings("serial")
    private static Map<Integer, String> pricingPlanCodeToAgreementType = new HashMap<Integer, String>() {
        {
            put(7, "Lease");
            put(1, "Power Purchase Agreement"); // aka: PPA - Generation 
            put(4, "Power Purchase Agreement"); // aka: PPA - Balanced
            put(8, "Power Purchase Agreement"); // aka: PPA - Fixed Annual
        }
    };

    private static final String UNKNOWN = "Unknown";

    private static boolean isTestAccount(RenderRequest rr) {
        boolean _useTestData = false;

        String testAccounts = null;
        User user = null;
        String userEmail = null;

        try {
            user = CRPortalUtil.getLiferayUser(rr);
            userEmail = user.getEmailAddress();

            testAccounts = CRPortalUtil.getTestAccounts();
            if (testAccounts != null) {
                if (testAccounts.indexOf(userEmail) > -1) {
                    _useTestData = true;
                }
            }
        } catch (CRPortletException e) {
            LOG.debug("useTestData - did not find user, assuming using test data");
            e.printStackTrace();
            //TODO handle the exception
        }

        return _useTestData;
    }

}