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

Java tutorial

Introduction

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

Source

/**
 * $Id: BuyLicenseBlockController.java 1116 2010-02-12 20:51:23Z imustafa $
 */
package com.lm.lic.manager.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.validation.Errors;
import org.springframework.web.servlet.ModelAndView;

import com.lm.lic.manager.controller.LmxLicensePricingTable.PricingRow;
import com.lm.lic.manager.form.BuyLicenseBlockForm;
import com.lm.lic.manager.hibernate.DecomLicenseReason;
import com.lm.lic.manager.hibernate.Isv;
import com.lm.lic.manager.hibernate.License;
import com.lm.lic.manager.hibernate.LicenseBlock;
import com.lm.lic.manager.hibernate.LicensePaymentStatus;
import com.lm.lic.manager.hibernate.Product;
import com.lm.lic.manager.management.IsvLicensePricingManager;
import com.lm.lic.manager.management.LicenseManager;
import com.lm.lic.manager.service.IsvService;
import com.lm.lic.manager.service.LicenseBlockService;
import com.lm.lic.manager.service.LicenseService;
import com.lm.lic.manager.service.ProductService;
import com.lm.lic.manager.util.GenConst;

/**
 * @author Ibrahim Mustafa
 */
public class BuyLicenseBlockController extends BaseLicenseManagerFormController {

    public static final String CLASS_VERSION = "$Id: BuyLicenseBlockController.java 1116 2010-02-12 20:51:23Z imustafa $";

    static Logger logger = Logger.getLogger(BuyLicenseBlockController.class);

    private IsvService isvService;
    private ProductService productService;
    private IsvLicensePricingManager isvLicensePricingManager;
    private LicenseBlockService licenseBlockService;
    private LicenseService licenseService;
    private LicenseManager licenseManager;

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

    /**
     * Determine if the given request represents a form submission.
     * <p>
     * The default implementation treats a POST request as form submission. Note: If the form session attribute
     * doesn't exist when using session form mode, the request is always treated as new form by
     * handleRequestInternal. It is possible for the user to issue a GET request with enough parameters to issue
     * a full meaningful LDAP search. This method detects that and tries to treat it as a form submission.
     * 
     * @param request current HTTP request
     * @return if the request represents a form submission
     */
    @Override
    protected boolean isFormSubmission(HttpServletRequest request) {
        boolean formSubmission = false;
        String method = request.getMethod();
        formSubmission = METHOD_POST.equals(method);
        return formSubmission;
    }

    @Override
    protected Map<String, Object> referenceData(HttpServletRequest request, Object command, Errors errors)
            throws Exception {
        BuyLicenseBlockForm buyLicCommand = (BuyLicenseBlockForm) command;
        Map<String, Object> refData = new HashMap<String, Object>();
        String prodId = request.getParameter("prodId");
        String isvId = request.getParameter("isvId");
        String amount = request.getParameter("amount");

        buyLicCommand.setIsvId(isvId);
        buyLicCommand.setProdId(prodId);
        Product product = productService.findProdById(prodId);
        buyLicCommand.setProduct(product);

        refData.put("amount", amount);
        refData.put("product", product);
        refData.put("prodId", prodId);
        refData.put("isvId", isvId);
        LmxLicensePricingTable pricingTable = lmxContext.buildLicensePricingTable();
        List<PricingRow> pricingRows = pricingTable.getPricingRows();
        refData.put("pricingTable", pricingRows);
        addProductUnderManagement(request, prodId);
        return refData;
    }

    /**
     * If a blcok exists for this uer/product add to it, otherwise create and populate
     */
    @SuppressWarnings("deprecation")
    @Override
    protected ModelAndView onSubmit(HttpServletRequest req, HttpServletResponse response, Object command,
            BindException bindException) throws Exception {

        BuyLicenseBlockForm blbf = (BuyLicenseBlockForm) command;
        String isvId = blbf.getIsvId();
        String prodId = blbf.getProdId();
        Product product = productService.findProdById(prodId);

        LicenseBlock lb = makeLicenseBlock(blbf);
        Integer numLicenses = lb.getNumLicenses();
        Integer numLeft = lb.getNumLeft();
        Long totalNumBought = lb.getTotalNumBought();
        LicenseBlock foundLicenseBlock = licenseBlockService.findByIsvIdProdId(isvId, prodId);
        if (foundLicenseBlock == null) {
            licenseBlockService.save(lb);
        } else {
            numLeft += foundLicenseBlock.getNumLeft();
            foundLicenseBlock.setNumLeft(numLeft);

            Integer newNumLicenses = numLicenses + foundLicenseBlock.getNumLicenses();
            foundLicenseBlock.setNumLicenses(newNumLicenses);

            totalNumBought += foundLicenseBlock.getTotalNumBought();
            foundLicenseBlock.setTotalNumBought(totalNumBought);

            foundLicenseBlock.setPricePerLicense(lb.getPricePerLicense());
            Double totalPrice = foundLicenseBlock.getTotalPrice() + lb.getTotalPrice();
            foundLicenseBlock.setTotalPrice(totalPrice);
            licenseBlockService.update(foundLicenseBlock);
            lb = foundLicenseBlock;
        }

        List<String> licKeys = licenseManager.generate(numLicenses, product.getLicKeyLength());
        List<License> licenses = extractRawLicenses(req, licKeys, lb, isvId, prodId);
        licenseService.save(licenses);

        String successView = getSuccessView() + isvId;
        ModelAndView modelAndView = new ModelAndView(successView);

        return modelAndView;
    }

    @SuppressWarnings("deprecation")
    @Override
    protected ModelAndView onCancel(HttpServletRequest request, HttpServletResponse response, Object command) {
        BuyLicenseBlockForm form = (BuyLicenseBlockForm) command;
        String cancelView = getCancelView() + form.getIsvId();
        ModelAndView modelAndView = new ModelAndView(cancelView);
        return modelAndView;
    }

    private List<License> extractRawLicenses(HttpServletRequest req, List<String> licKeys, LicenseBlock lb,
            String isvId, String prodId) {
        List<License> licenses = new ArrayList<License>(licKeys.size());
        Isv isv = isvService.findIsvById(isvId);
        Product product = productService.findProdById(prodId);
        for (String lk : licKeys) {
            boolean inUse = false;
            String endUserName = StringUtils.EMPTY;
            String endUserCell = StringUtils.EMPTY;
            String endUserPin = StringUtils.EMPTY;

            Calendar calendar = Calendar.getInstance();
            Timestamp dateIssued = new Timestamp(calendar.getTimeInMillis());

            calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) - 1);
            Timestamp dateActivated = new Timestamp(calendar.getTimeInMillis());

            calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + 2);
            Timestamp dateExpires = new Timestamp(calendar.getTimeInMillis());

            Boolean decom = false;
            String decomReason = DecomLicenseReason.NOT_YET.name();
            String shadowLicKey = EMPTY;

            Double cost = lb.getPricePerLicense();
            Double price = lb.getPricePerLicense();
            String localeLang = BaseLicenseManagerFormController.extractLocaleLang(req);

            License lic = new License(lb, isv, product, null, inUse, lk, TRIAL_LICENSE_AGE, decom, decomReason,
                    shadowLicKey, LicensePaymentStatus.FREE.name(), endUserName, endUserCell, endUserPin,
                    dateIssued, dateActivated, dateExpires, cost, price, localeLang, GenConst.DEFAULT_USER,
                    GenConst.CURRENT_TIME, GenConst.DEFAULT_USER, GenConst.CURRENT_TIME);
            licenses.add(lic);

        }
        return licenses;
    }

    private LicenseBlock makeLicenseBlock(BuyLicenseBlockForm blbf) {
        String isvId = blbf.getIsvId();
        Isv isv = isvService.findIsvById(isvId);

        String prodId = blbf.getProdId();
        Product product = productService.findProdById(prodId);

        Double pricePerLicense = isvLicensePricingManager.findIsvLicensePrice(isvId, prodId);
        Integer numLicenses = calculateNumLicenses(blbf, pricePerLicense);
        Integer numLeft = numLicenses;
        long totalNumBought = numLicenses;
        Double totalPrice = numLicenses * pricePerLicense;
        Integer numOverdraft = 0;
        LicenseBlock lb = new LicenseBlock(isv, product, numLeft, numOverdraft, numLicenses, totalNumBought,
                pricePerLicense, totalPrice, GenConst.CURRENT_TIME, GenConst.DEFAULT_USER, GenConst.CURRENT_TIME,
                GenConst.DEFAULT_USER, GenConst.CURRENT_TIME, null);
        return lb;
    }

    private Integer calculateNumLicenses(BuyLicenseBlockForm blbf, Double ppl) {
        Double amount = blbf.getAmount();
        Double numLicenses = amount / ppl;
        Integer nl = numLicenses.intValue();
        return nl;
    }

    /**
     * @return the isvService
     */
    @Override
    public IsvService getIsvService() {
        return this.isvService;
    }

    /**
     * @param isvService the isvService to set
     */
    @Override
    public void setIsvService(IsvService isvService) {
        this.isvService = isvService;
    }

    /**
     * @return the productService
     */
    @Override
    public ProductService getProductService() {
        return this.productService;
    }

    /**
     * @param productService the productService to set
     */
    @Override
    public void setProductService(ProductService productService) {
        this.productService = productService;
    }

    /**
     * @return the isvLicensePricingManager
     */
    public IsvLicensePricingManager getIsvLicensePricingManager() {
        return this.isvLicensePricingManager;
    }

    /**
     * @param isvLicensePricingManager the isvLicensePricingManager to set
     */
    public void setIsvLicensePricingManager(IsvLicensePricingManager isvLicensePricingManager) {
        this.isvLicensePricingManager = isvLicensePricingManager;
    }

    /**
     * @return the licenseBlockService
     */
    public LicenseBlockService getLicenseBlockService() {
        return this.licenseBlockService;
    }

    /**
     * @param licenseBlockService the licenseBlockService to set
     */
    public void setLicenseBlockService(LicenseBlockService licenseBlockService) {
        this.licenseBlockService = licenseBlockService;
    }

    /**
     * @return the licenseService
     */
    @Override
    public LicenseService getLicenseService() {
        return this.licenseService;
    }

    /**
     * @param licenseService the licenseService to set
     */
    @Override
    public void setLicenseService(LicenseService licenseService) {
        this.licenseService = licenseService;
    }

    /**
     * @return the licenseManager
     */
    public LicenseManager getLicenseManager() {
        return this.licenseManager;
    }

    /**
     * @param licenseManager the licenseManager to set
     */
    public void setLicenseManager(LicenseManager licenseManager) {
        this.licenseManager = licenseManager;
    }
}