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

Java tutorial

Introduction

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

Source

/**
 * $Id: AddProductController.java 2020 2011-05-17 07:25:20Z imustafa $
 */
package com.lm.lic.manager.controller;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
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.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;

import com.lm.lic.manager.form.AddProductForm;
import com.lm.lic.manager.form.HashedLicMechConfigForm;
import com.lm.lic.manager.form.LicWithdrawMailConfigForm;
import com.lm.lic.manager.hibernate.Category;
import com.lm.lic.manager.hibernate.HashedLicMechConfig;
import com.lm.lic.manager.hibernate.Isv;
import com.lm.lic.manager.hibernate.IsvLicensePricing;
import com.lm.lic.manager.hibernate.LicMechType;
import com.lm.lic.manager.hibernate.LicWithdrawMailConfig;
import com.lm.lic.manager.hibernate.LicensePaymentStatus;
import com.lm.lic.manager.hibernate.ParticipantStore;
import com.lm.lic.manager.hibernate.Platform;
import com.lm.lic.manager.hibernate.Product;
import com.lm.lic.manager.hibernate.ProductDef;
import com.lm.lic.manager.hibernate.QuickyProductDef;
import com.lm.lic.manager.management.IsvLicensePricingManager;
import com.lm.lic.manager.service.IsvLicensePricingService;
import com.lm.lic.manager.service.IsvService;
import com.lm.lic.manager.service.ProductService;
import com.lm.lic.manager.util.GenUtil;

/**
 * @author Ibrahim Mustafa
 */
public class AddProductController extends BaseLicenseManagerFormController {
    public static final String CLASS_VERSION = "$Id: AddProductController.java 2020 2011-05-17 07:25:20Z imustafa $";

    private IsvService isvService;
    private IsvLicensePricingService isvLicensePricingService;
    private IsvLicensePricingManager isvLicensePricingManager;
    private LicenseAvailabilityAdvisor licenseAvailabilityAdvisor;

    public AddProductController() {
        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 {
        AddProductForm addProdCommand = (AddProductForm) command;
        Map<String, Object> refData = new HashMap<String, Object>();
        String isvId = GenUtil.findLoggedinIsv(request, loginService);
        addProdCommand.setIsvId(isvId);

        List<QuickyProductDef> productDefsList = findProductDefs(isvId);
        refData.put("productDefsList", productDefsList);

        refData.put("licMechTypeList", lmxContext.findLicMechTypeList(request));
        refData.put("licLifeTypeList", lmxContext.findLicLifeTypeList(request));
        refData.put("licKeyLengthList", lmxContext.findLicKeyLengthsList(request));
        refData.put("numTrialDownloadsList", lmxContext.findNumTrialDownloadsList(request));
        refData.put("participantStoresList", lmxContext.findParticipantStoresList(request));
        refData.put("categoriesList", lmxContext.findCategoriesList(request));
        refData.put("platformsList", lmxContext.findPlatformsList(request));

        refData.put("supportedHashAlgorithmsList", lmxContext.findSupportedHashAlgorithmsList(request));
        refData.put("supportedHashCharSetsList", lmxContext.findSupportedHashCharSetsList(request));
        refData.put("supportedHashKeyFormatsList", lmxContext.findSupportedHashKeyFormatsList(request));
        refData.put("supportedHashKeyLengthsList", lmxContext.findSupportedHashKeyLengthsList(request));
        refData.put("supportedHashBasesList", lmxContext.findSupportedHashBasesList(request));
        refData.put("supportedHashSegmentsList", lmxContext.findSupportedHashSegmentsList(request));

        return refData;
    }

    /**
     *
     */

    @SuppressWarnings("deprecation")
    @Override
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
            BindException errors) throws Exception {
        AddProductForm form = (AddProductForm) command;

        Product product = extractProduct(request, form);
        boolean besidesMe = false; // I don't exist yet
        String isvId = GenUtil.findLoggedinIsv(request, loginService);
        Long storeId = form.getListingStoreId();
        boolean isUnique = checkUniqueness(product, isvId, storeId, errors, besidesMe);

        String destView = getFormView();
        ModelAndView modelAndView = null;

        if (isUnique) {
            IsvLicensePricing isvLicensePricing = isvLicensePricingManager.findIsvLicensePricing(form.getIsvId(),
                    product.getLicLifeInDays());
            isvLicensePricing.setProduct(product);
            Isv isv = isvService.findIsvById(form.getIsvId());
            isvLicensePricing.setIsv(isv);
            productService.save(product);
            isvLicensePricingService.save(isvLicensePricing);

            if (product.getLicWithdrawMailConfigs() != null && product.getLicWithdrawMailConfigs().size() > 0)
                licWithdrawMailConfigService
                        .save((LicWithdrawMailConfig) product.getLicWithdrawMailConfigs().toArray()[0]);

            // If the user chose to have "Hashed" License mechanism, then see if he entered a secret key (message).
            // If none was entered, use the product definition key as the secret key. The product definition key can
            // only be visible tot he owner of the product when he logs in to the system and lists his products.
            HashedLicMechConfig hashedLicMechConfig = product.getOwnHashedLicMechConfig();
            if (hashedLicMechConfig != null) {
                useOwnerProductDefKeyForSecretKey(product, hashedLicMechConfig);
                hashedLicMechConfigService.save(hashedLicMechConfig);
            }

            String localeLang = extractLocaleLang(request);
            Integer numOverDraft = 0;
            String deviceId = null;
            int numIntroLics = findNumIntroLics(product);
            licenseAvailabilityAdvisor.generateLicenses(deviceId, localeLang, product, numIntroLics, numOverDraft,
                    LicensePaymentStatus.FREE);
            destView = getSuccessView();
            modelAndView = new ModelAndView(destView);
        } else {
            modelAndView = new ModelAndView(destView);
            modelAndView.addObject("command", form);
            modelAndView.addAllObjects(errors.getModel());
            modelAndView.addObject("licMechTypeList", lmxContext.findLicMechTypeList(request));
            modelAndView.addObject("licLifeTypeList", lmxContext.findLicLifeTypeList(request));
            modelAndView.addObject("licKeyLengthList", lmxContext.findLicKeyLengthsList(request));
            modelAndView.addObject("numTrialDownloadsList", lmxContext.findNumTrialDownloadsList(request));
            modelAndView.addObject("participantStoresList", lmxContext.findParticipantStoresList(request));

            List<QuickyProductDef> productDefsList = findProductDefs(isvId);
            modelAndView.addObject("productDefsList", productDefsList);
            modelAndView.addObject("categoriesList", lmxContext.findCategoriesList(request));
            modelAndView.addObject("platformsList", lmxContext.findPlatformsList(request));

            modelAndView.addObject("supportedHashAlgorithmsList",
                    lmxContext.findSupportedHashAlgorithmsList(request));
            modelAndView.addObject("supportedHashCharSetsList", lmxContext.findSupportedHashCharSetsList(request));
            modelAndView.addObject("supportedHashKeyFormatsList",
                    lmxContext.findSupportedHashKeyFormatsList(request));
            modelAndView.addObject("supportedHashKeyLengthsList",
                    lmxContext.findSupportedHashKeyLengthsList(request));
            modelAndView.addObject("supportedHashBasesList", lmxContext.findSupportedHashBasesList(request));
            modelAndView.addObject("supportedHashSegmentsList", lmxContext.findSupportedHashSegmentsList(request));
        }
        return modelAndView;
    }

    /**
     * @param product
     * @return
     */
    private int findNumIntroLics(Product product) {
        int numIntroLics = lmxContext.getNumIntroLics();
        if (product.isFloatlyLicensed())
            numIntroLics = lmxContext.getNumIntroDomainLics();
        return numIntroLics;
    }

    /**
     * @param product
     * @param hashedLicMechConfig
     */
    private void useOwnerProductDefKeyForSecretKey(Product product, HashedLicMechConfig hashedLicMechConfig) {
        String message = hashedLicMechConfig.getMessage();
        if (StringUtils.isEmpty(message))
            hashedLicMechConfig.setMessage(product.getProductDefKey());
    }

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

    @Override
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws ServletException {
        // to actually be able to convert Multipart instance to byte[]
        // we have to register a custom editor
        binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
        // now Spring knows how to handle multipart object and convert them
    }

    /**
     * @param form
     * @return
     */
    private Product extractProduct(HttpServletRequest request, AddProductForm form) {
        String isvId = form.getIsvId();
        Isv isv = isvService.findIsvById(isvId);

        Long prodDefId = form.getProdDefId();
        ProductDef productDef = null;
        if (prodDefId != null && prodDefId > 0)
            productDef = productDefService.findProdDefById(isvId, prodDefId);

        Long categoryId = form.getCategoryId();
        Category category = null;
        if (categoryId != null && categoryId > 0)
            category = lmxContext.getCategoryService().findCategoryById(categoryId);

        Long platformId = form.getPlatformId();
        Platform platform = null;
        if (platformId != null && platformId > 0)
            platform = lmxContext.getPlatformService().findPlatformById(platformId);

        Long licMechTypeId = form.getLicMechTypeId();
        LicMechType licMechType = null;
        if (licMechTypeId != null && licMechTypeId > 0)
            licMechType = lmxContext.getLicMechTypeService().findLicMechTypeById(licMechTypeId);

        Long listingStoreId = form.getListingStoreId();
        ParticipantStore listingStore = null;
        if (listingStoreId != null && listingStoreId > 0)
            listingStore = lmxContext.getParticipantStoreService().findParticipantStoreById(listingStoreId);

        String uniqueKey = uniqueKeyGenerator.generateProdInstKey();
        String name = form.getName();
        String version = form.getVersion();
        String isvProductId = form.getIsvProductId();
        Integer licLifeInDays = form.getLicLifeInDays();
        Integer licKeyLength = form.getLicKeyLength();

        // Since the dynamic license key length was disabled when Hashed license type is chosen in the view/UI,
        // choose that of the hashed configuration for the product.
        if (licMechType.isHashedLicMechType() || licMechType.isFloatingHashedLicMechType())
            licKeyLength = form.getHlmcForm().getKeyLength();

        Double price = isvLicensePricingManager.findLmxLicensePrice(licLifeInDays);
        Integer numTrialDownloads = form.getNumTrialDownloads();
        String description = form.getDescription();
        String image = "/images/bb.gif";
        Boolean enabled = true;
        Boolean locked = false;
        Boolean deleted = false;
        String localeLang = extractLocaleLang(request);
        byte[] icon = form.getIcon();
        if (icon == null || icon.length < 2)
            icon = null;

        Product product = new Product(isv, productDef, category, platform, licMechType, listingStore, uniqueKey,
                name, version, isvProductId, licLifeInDays, licKeyLength, price, numTrialDownloads, description,
                image, icon, enabled, locked, deleted, localeLang, null, null, null, null, null, null, null, null,
                null, null, null, null, null);
        setCommonDefaults(product);

        if (form.isMailBuyer()) {
            Set<LicWithdrawMailConfig> lwmcs = extractLicWithdrawMailConfigs(product, form.getLwmcForm());
            product.setLicWithdrawMailConfigs(lwmcs);
        }

        if (licMechType.isHashedLicMechType()) {
            Set<HashedLicMechConfig> hlmcs = extractHashedLicMechConfigs(product, form.getHlmcForm());
            product.setHashedLicMechConfigs(hlmcs);
        }

        return product;
    }

    private Set<LicWithdrawMailConfig> extractLicWithdrawMailConfigs(Product product,
            LicWithdrawMailConfigForm form) {
        Boolean mailBuyer = form.getMailBuyer();
        Boolean mailOwner = form.getMailOwner();
        String subject = (String) GenUtil.chooseSecondIfFirstIsNull(form.getSubject(), EMPTY);
        String fromx = (String) GenUtil.chooseSecondIfFirstIsNull(form.getFromx(), EMPTY);
        String cc = form.getCc();
        String bcc = form.getBcc();
        String body = (String) GenUtil.chooseSecondIfFirstIsNull(form.getBody(), EMPTY);
        Boolean sendLicKeys = form.getSendLicKeys();
        Timestamp timeNow = GenUtil.timeNow();
        LicWithdrawMailConfig lwmc = new LicWithdrawMailConfig(product, mailBuyer, mailOwner, subject, fromx, cc,
                bcc, body, sendLicKeys, DEFAULT_USER, timeNow, DEFAULT_USER, timeNow);
        Set<LicWithdrawMailConfig> lwmcs = new HashSet<LicWithdrawMailConfig>(1);
        lwmcs.add(lwmc);
        return lwmcs;
    }

    /**
     * @param product
     * @param hlmcForm
     * @return
     */
    private Set<HashedLicMechConfig> extractHashedLicMechConfigs(Product product,
            HashedLicMechConfigForm hlmcForm) {

        String algorithm = hlmcForm.getAlgorithm();
        String keyFormat = hlmcForm.getKeyFormat();
        String charSet = hlmcForm.getCharSet();
        String base = hlmcForm.getBase();
        String segment = hlmcForm.getSegment();
        Integer keyLength = hlmcForm.getKeyLength();
        String message = hlmcForm.getMessage();
        Timestamp timeNow = GenUtil.timeNow();
        HashedLicMechConfig hlmc = new HashedLicMechConfig(product, algorithm, keyFormat, charSet, base, segment,
                keyLength, message, DEFAULT_USER, timeNow, DEFAULT_USER, timeNow);
        Set<HashedLicMechConfig> hlmcs = new HashSet<HashedLicMechConfig>(1);
        hlmcs.add(hlmc);
        return hlmcs;
    }

    /**
     * @param product
     */
    private void setCommonDefaults(Product product) {
        product.setCreatedBy(DEFAULT_USER);
        product.setModifiedBy(DEFAULT_USER);
        product.setDateCreated(GenUtil.timeNow());
        product.setDateModified(GenUtil.timeNow());
    }

    /**
     * @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 isvLicensePricingService the isvLicensePricingService to set
     */
    public void setIsvLicensePricingService(IsvLicensePricingService isvLicensePricingService) {
        this.isvLicensePricingService = isvLicensePricingService;
    }

    /**
     * @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 licenseAvailabilityAdvisor
     */
    public LicenseAvailabilityAdvisor getLicenseAvailabilityAdvisor() {
        return this.licenseAvailabilityAdvisor;
    }

    /**
     * @param licenseAvailabilityAdvisor the licenseAvailabilityAdvisor to set
     */
    public void setLicenseAvailabilityAdvisor(LicenseAvailabilityAdvisor licenseAvailabilityAdvisor) {
        this.licenseAvailabilityAdvisor = licenseAvailabilityAdvisor;
    }

    /**
     * @return the isvLicensePricingService
     */
    public IsvLicensePricingService getIsvLicensePricingService() {
        return this.isvLicensePricingService;
    }
}