com.webbfontaine.valuewebb.model.validators.MpPriceDateValidator.java Source code

Java tutorial

Introduction

Here is the source code for com.webbfontaine.valuewebb.model.validators.MpPriceDateValidator.java

Source

package com.webbfontaine.valuewebb.model.validators;

import com.webbfontaine.valuewebb.action.pricedb.mp.MarketPriceHome;
import com.webbfontaine.valuewebb.model.MarketPrice;
import com.webbfontaine.valuewebb.model.constants.Messages;
import com.webbfontaine.valuewebb.validation.ErrorHandling;
import org.apache.commons.lang3.time.DateUtils;
import org.jboss.seam.Component;
import org.jboss.seam.annotations.Name;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Copyrights 2002-2012 Webb Fontaine
 * This software is the proprietary information of Webb Fontaine.
 * Its use is subject to License terms.
 * Developer: nigiyan
 * Date: 22/03/2012
 */

@Name("mpPriceDateValidator")
public class MpPriceDateValidator implements Validator {

    @Override
    public void validate(FacesContext facesContext, UIComponent uiComponent, Object o) {

        ErrorHandling errorHandling = (ErrorHandling) Component.getInstance(ErrorHandling.class, true);
        MarketPriceHome marketPriceHome = (MarketPriceHome) Component.getInstance(MarketPriceHome.class, true);

        errorHandling.removeErrorByMessage(Messages.EXC_RATE_INVALID);
        errorHandling.removeErrorByMessage(Messages.INVALID_DATE);

        MarketPrice mp = marketPriceHome.getInstance();

        Date priceDate = (Date) o;
        if (validate(priceDate)) {
            if (!CurrencyRateValidator.isValid(mp.getRetailerPriceCur(), priceDate)) {
                ErrorHandling.addFacesMessageError(uiComponent.getClientId(FacesContext.getCurrentInstance()),
                        Messages.EXC_RATE_INVALID);
            }
            if (mp.getSourceOfPrice() != null) {
                if (!CurrencyRateValidator.isValid("USD", priceDate)) {
                    ErrorHandling.addFacesMessageError(uiComponent.getClientId(FacesContext.getCurrentInstance()),
                            Messages.EXC_RATE_INVALID + " Currency: USD");
                }
            }
        } else {
            ErrorHandling.addFacesMessageError(uiComponent.getClientId(facesContext), Messages.INVALID_DATE);
        }
    }

    public static boolean validate(Date date) {
        Date todayDate = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
        Date dateWithoutTime = DateUtils.truncate(date, Calendar.DAY_OF_MONTH);

        return date == null || Integer.parseInt(new SimpleDateFormat("yyyy").format(date)) >= 2010
                && !todayDate.before(dateWithoutTime);
    }
}