com.lm.lic.manager.controller.UpdateDomainLicActiveUserCountController.java Source code

Java tutorial

Introduction

Here is the source code for com.lm.lic.manager.controller.UpdateDomainLicActiveUserCountController.java

Source

/**
 * $Id: VerifyLicController.java 1478 2010-05-14 01:56:14Z imustafa $
 */
package com.lm.lic.manager.controller;

import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import com.lm.lic.manager.form.UpdateDomainLicActiveUserCountForm;
import com.lm.lic.manager.form.VerifyDomainLicForm;
import com.lm.lic.manager.hibernate.FloatingLicenseConfig;
import com.lm.lic.manager.hibernate.Isv;
import com.lm.lic.manager.hibernate.License;
import com.lm.lic.manager.hibernate.LicenseVerificationStatus;
import com.lm.lic.manager.hibernate.Product;

import edu.emory.mathcs.backport.java.util.Arrays;

/**
 * @author Ibrahim Mustafa
 */
public class UpdateDomainLicActiveUserCountController extends BaseDomainLicController {
    public static final String CLASS_VERSION = "$Id: VerifyLicController.java 1478 2010-05-14 01:56:14Z imustafa $";

    private static Logger logger = Logger.getLogger(UpdateDomainLicActiveUserCountController.class);

    public UpdateDomainLicActiveUserCountController() {
        super();
        setSupportedMethods(new String[] { METHOD_GET, METHOD_POST });
    }

    /**
     *
     */
    @Override
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
            BindException errors) throws Exception {
        logger.info("Start Handling of Domain License Update ActiveUser COunt Request - Manual Submission");

        UpdateDomainLicActiveUserCountForm ulf = (UpdateDomainLicActiveUserCountForm) command;
        return doUpdate(request, response, ulf);
    }

    /**
     * @param request
     * @param command
     * @return
     * @throws IOException
     * @throws ServletException
     */
    @SuppressWarnings("deprecation")
    protected ModelAndView doUpdate(HttpServletRequest request, HttpServletResponse response,
            UpdateDomainLicActiveUserCountForm ulf) throws ServletException, IOException {

        String clientEmail = ulf.getClientEmail();
        String licKey = ulf.getLicKey();
        String isvKey = ulf.getIsvKey();
        String prodDefKey = ulf.getProdDefKey();
        String prodName = ulf.getProdName();
        String prodVersion = ulf.getProdVersion();
        int numActiveUsers = ulf.getNumActiveUsers();
        logger.info("UPDATE_DOM_LIC_USAGE -> " + "numActiveUsers: " + numActiveUsers + ", clientEmail: "
                + clientEmail + ", licKey: " + licKey + ", isvKey: " + isvKey + ", prodDefKey: " + prodDefKey
                + ", prodName: " + prodName + ", prodVersion: " + prodVersion);

        String hellView = getDeniedView();

        Isv isv = isvService.findIsvByKey(isvKey);
        if (isv == null) {
            logger.info("UPDATE_DOM_LIC_USAGE -> " + "Going to Hell - ISV Not Found");
            toHell(request, response, hellView, "+++++++++++");
            return null;
        }

        logger.info("UPDATE_DOM_LIC_USAGE -> " + "ISV: " + isv);
        String sisvId = isv.getId() + EMPTY;
        String storeId = lmxContext.findStoreId(ParticipantStoresAtLicmax.ISV, request).toString();
        Product product = productService.findQuickyProductByNameAndVersion(sisvId, prodDefKey, prodName,
                prodVersion, storeId);

        if (product == null) {
            logger.info("UPDATE_DOM_LIC_USAGE -> " + "Going to Hell - PRODUCT Not Found");
            toHell(request, response, hellView, "+++++++++++");
            return null;
        }

        logger.info("UPDATE_DOM_LIC_USAGE -> " + "PRODUCT: " + product.getName());

        Boolean inUse = null;
        Boolean decomStatus = null;
        License license = licenseService.findLicenseByEmailAndKey(clientEmail, licKey, prodDefKey, decomStatus,
                inUse);
        if (license == null) {
            logger.info("UPDATE_DOM_LIC_USAGE -> " + "Going to Hell - LICENSE Not Found");
            toHell(request, response, hellView, "+++++++++++");
            return null;
        }

        Long isvId = isv.getId();
        String prodKey = product.getProductKey();
        FloatingLicenseConfig floatingLicenseConfig = floatingLicenseConfigService
                .findFloatingLicenseConfigForProductAndLicKeyForEmail(isvId, prodKey, licKey, clientEmail);
        logger.info("UPDATE_DOM_LIC_USAGE -> " + "FLOATING_LICENSE_CONFIG: " + floatingLicenseConfig);

        if (floatingLicenseConfig == null) {
            logger.info("UPDATE_DOM_LIC_USAGE -> " + "Going to Hell - floatingLicenseConfig Not Found");
            toHell(request, response, hellView, "+++++++++++");
            return null;
        }

        int allowedToStartWith = tryUpdateActiveUserCount(ulf, request, floatingLicenseConfig);
        String validity = licenseService.findDomainLicenseValidityStatus(license, allowedToStartWith);

        logger.info("License Usage Update - EMAIL: " + clientEmail + ", KEY: " + licKey + ", ProdDefKey: "
                + prodDefKey + ", RESP: " + validity);

        if (LicenseVerificationStatus.isNotAuthorized(validity)) {
            logger.info("UPDATE_DOM_LIC_USAGE -> " + "Going to Hell - valid license:" + validity);
            toHell(request, response, hellView, "+++++++++++");
            return null;
        }

        ModelAndView modelAndView = new ModelAndView(getSuccessView());
        recordVerifIncident(request, ulf, license, clientEmail, licKey, validity);

        modelAndView.addObject("validity", validity);
        modelAndView.addObject("clientEmail", clientEmail);
        modelAndView.addObject("licKey", licKey);
        modelAndView.addObject("product", product);
        modelAndView.addObject("license", license);
        modelAndView.addObject("floatingLicenseConfig", floatingLicenseConfig);

        return modelAndView;
    }

    /**
     * @param ulf
     * @param floatingLicenseConfig
     */
    private int tryUpdateActiveUserCount(UpdateDomainLicActiveUserCountForm ulf, HttpServletRequest request,
            FloatingLicenseConfig floatingLicenseConfig) {

        int numActiveUsers = ulf.getNumActiveUsers();
        logger.info("UPDATE_DOM_LIC_USAGE -> numActiveUsers: " + numActiveUsers);

        if (numActiveUsers < 0)
            return 0;

        String gatewayIp = findIpAddress(request);
        String incomingDomain = findDomain(request);

        // First time activation
        String currDomain = floatingLicenseConfig.getCurrDomain();
        if (StringUtils.isEmpty(currDomain) || currDomain.equals("STUBBED")) {
            updateLicenseConfigWithNewValue(floatingLicenseConfig, numActiveUsers, gatewayIp, incomingDomain);
            return 0;
        }

        boolean isInCurrentDomain = isIncomingDomainCurrentDomain(incomingDomain, currDomain);
        boolean isInExtraAllowedDomains = isIncomingDomainInExtraAllowedDomains(floatingLicenseConfig,
                incomingDomain);

        String prevDomain = floatingLicenseConfig.getPrevDomain();

        // Detect a difference in the incoming domain from the previously recorded domain
        if (isInCurrentDomain || isInExtraAllowedDomains) {

            // Allow one domain change but when the domain comes back to original domain, hell breaks loose
            if (StringUtils.isEmpty(prevDomain) || prevDomain.equals("STUBBED") || isInExtraAllowedDomains) {
                floatingLicenseConfig.setPrevDomain(currDomain);
                updateLicenseConfigWithNewValue(floatingLicenseConfig, numActiveUsers, gatewayIp, incomingDomain);
                return 0;
            }

            String domainsUsageHistory = floatingLicenseConfig.getDomainsUsage();
            domainsUsageHistory = domainsUsageHistory == null ? EMPTY : domainsUsageHistory;

            // Check to see if the incoming domain exists in the domain usage history.
            boolean isIncomingDomainInDomainHistory = isIncomingDomaInInDomainHistory(incomingDomain,
                    domainsUsageHistory);
            if (isIncomingDomainInDomainHistory && StringUtils.isNotEmpty(domainsUsageHistory)
                    && !incomingDomain.equals(currDomain) && !isInExtraAllowedDomains)
                return -1;

            addIncomingDomainToHistory(incomingDomain, floatingLicenseConfig);
            floatingLicenseConfig.setGatewayIpAddress(gatewayIp);
            floatingLicenseConfig.setNumActiveUsers(numActiveUsers);
            floatingLicenseConfigService.save(floatingLicenseConfig);

            return 0;
        }

        // Detect a domain change. By this time, at least the currentDomain must have been set earlier in the first-time detecion
        boolean incomingAndCurrAreDifferent = isIncomingAndCurrAreDifferent(incomingDomain, currDomain);
        if (incomingAndCurrAreDifferent) {
            boolean incomingAndPrevAreEqual = isIncomingAndPrevAreEqual(incomingDomain, prevDomain);
            if (incomingAndPrevAreEqual)
                return -1; // disallow return to previous domain

            // Allow first differing of incoming from current and prev domain
            updateLicenseConfigWithNewValue(floatingLicenseConfig, numActiveUsers, gatewayIp, incomingDomain);
            return 0;
        }

        return -1;
    }

    /**
     * @param incomingDomain
     * @param prevDomain
     * @return
     */
    private boolean isIncomingAndPrevAreEqual(String incomingDomain, String prevDomain) {
        boolean incomingAndPrevAreDifferent = prevDomain != null && incomingDomain.equals(prevDomain);
        return incomingAndPrevAreDifferent;
    }

    /**
     * @param incomingDomain
     * @param currDomain
     * @return
     */
    private boolean isIncomingAndCurrAreDifferent(String incomingDomain, String currDomain) {
        boolean incomingAndCurrAreDifferent = !incomingDomain.equals(currDomain);
        return incomingAndCurrAreDifferent;
    }

    /**
     * @param floatingLicenseConfig
     * @param numActiveUsers
     * @param gatewayIp
     * @param incomingDomain
     */
    private void updateLicenseConfigWithNewValue(FloatingLicenseConfig floatingLicenseConfig, int numActiveUsers,
            String gatewayIp, String incomingDomain) {
        floatingLicenseConfig.setCurrDomain(incomingDomain);
        addIncomingDomainToHistory(incomingDomain, floatingLicenseConfig);
        floatingLicenseConfig.setGatewayIpAddress(gatewayIp);
        floatingLicenseConfig.setNumActiveUsers(numActiveUsers);
        floatingLicenseConfigService.save(floatingLicenseConfig);
    }

    /**
     * @param incomingDomain
     * @param currDomain
     * @return
     */
    private boolean isIncomingDomainCurrentDomain(String incomingDomain, String currDomain) {

        // Just in case a verification occurs before the current domain is set.
        if (StringUtils.isEmpty(currDomain))
            return false;

        int indexInCurrentDomain = StringUtils.indexOfDifference(incomingDomain, currDomain);
        boolean bothIncomingAndCurrentEqual = indexInCurrentDomain == -1;

        return bothIncomingAndCurrentEqual;
    }

    /**
     * @param incomingDomain
     * @param domainHistory
     * @return
     */
    private boolean isIncomingDomaInInDomainHistory(String incomingDomain, String domainHistory) {

        // Just in case a verification occurs before the current domain is set.
        if (StringUtils.isEmpty(domainHistory))
            return false;

        String[] domainHistoryArray = org.springframework.util.StringUtils
                .commaDelimitedListToStringArray(domainHistory);
        List<String> domainHistoryList = convertArrayStringsToListStrings(domainHistoryArray);
        boolean isInDomainHistory = domainHistoryList.contains(incomingDomain);

        return isInDomainHistory;
    }

    /**
     * Check to see if the incoming domain is part of the
     * 
     * @param incomingDomain
     * @return
     */
    @SuppressWarnings("unchecked")
    private boolean isIncomingDomainInExtraAllowedDomains(FloatingLicenseConfig floatingLicenseConfig,
            String incomingDomain) {

        String extraAllowedDomains = floatingLicenseConfig.getExtraAllowedDomains();
        if (StringUtils.isEmpty(extraAllowedDomains))
            extraAllowedDomains = EMPTY;
        if (StringUtils.isEmpty(incomingDomain))
            incomingDomain = EMPTY;

        String[] extraAllowedDomainsArray = org.springframework.util.StringUtils
                .commaDelimitedListToStringArray(extraAllowedDomains);
        Set<String> extraAllowedDomainsSet = new LinkedHashSet<String>();
        extraAllowedDomainsSet.addAll(Arrays.asList(extraAllowedDomainsArray));
        boolean inList = extraAllowedDomainsSet.contains(incomingDomain);
        return inList;
    }

    /**
     * @param incomingDomain
     * @param floatingLicenseConfig
     * @return
     */
    private String addIncomingDomainToHistory(String incomingDomain, FloatingLicenseConfig floatingLicenseConfig) {
        String[] domainHistoryArray = org.springframework.util.StringUtils
                .commaDelimitedListToStringArray(floatingLicenseConfig.getDomainsUsage());
        domainHistoryArray = org.springframework.util.StringUtils.addStringToArray(domainHistoryArray,
                incomingDomain);

        List<String> domainsHistoryList = convertArrayStringsToListStrings(domainHistoryArray);
        Set<String> domainHistorySet = new LinkedHashSet<String>(domainsHistoryList); // made unique - always should be

        String domainHistoryString = org.springframework.util.StringUtils
                .collectionToCommaDelimitedString(domainHistorySet);
        floatingLicenseConfig.setDomainsUsage(domainHistoryString);

        return domainHistoryString;
    }

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        if (isManualVerification(request) || isCancel(request))
            return super.handleRequestInternal(request, response);

        UpdateDomainLicActiveUserCountForm ulf = extractUpdateDomainLicActiveUserCountForm(request);
        logger.info("Start Handling of Domain License Update Active User Count Request - Auto Submission");
        ModelAndView modelAndView = doUpdate(request, response, ulf);

        return modelAndView;
    }

    /**
     * Extract the command used when it is an auto verification request. auto verifiction requests are handled without having to
     * render the manual verification form. Auto and Manual verifiction requests share the same controller. Manul requests have a
     * parameter "manual" on the request indicating so.
     * 
     * @param request
     * @return
     */
    protected UpdateDomainLicActiveUserCountForm extractUpdateDomainLicActiveUserCountForm(
            HttpServletRequest request) {
        VerifyDomainLicForm vlf = super.extractCommand(request);
        UpdateDomainLicActiveUserCountForm ulf = new UpdateDomainLicActiveUserCountForm(vlf);

        String numActiveUsers = request.getParameter("numActiveUsers");
        int naus = Integer.parseInt(numActiveUsers);
        ulf.setNumActiveUsers(naus);

        return ulf;
    }
}