org.kisoonlineapp.jsf.CalendarConverterInternal.java Source code

Java tutorial

Introduction

Here is the source code for org.kisoonlineapp.jsf.CalendarConverterInternal.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.kisoonlineapp.jsf;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import org.apache.commons.lang3.StringUtils;
import org.kisoonlineapp.cdi.KisoOnlineApp;

/**
 *
 * @author berni
 */
//@FacesConverter(value = "calendarConverter")
public class CalendarConverterInternal implements Converter {

    protected final KisoOnlineApp kisoOnlineApp;
    private final String pattern;

    public CalendarConverterInternal(String pattern) {
        this.kisoOnlineApp = new KisoOnlineApp();
        this.pattern = pattern;
    }

    //---
    public Calendar retrieveAsObject(String value) {
        Calendar cal = (Calendar) getAsObject(null, null, value);
        return cal;
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        final String trimmedValue = StringUtils.trimToNull(value);
        if (StringUtils.isBlank(trimmedValue)) {
            return null;
        }

        final SimpleDateFormat sdf = createSimpleDateFormat(context, pattern);
        sdf.setLenient(false);
        final ParsePosition pos = new ParsePosition(0);
        final Date date = sdf.parse(trimmedValue, pos);

        if (pos.getErrorIndex() >= 0 || pos.getIndex() != trimmedValue.length()) {
            throw new ConverterException("Cannot parse " + trimmedValue);
        }

        final Calendar cal = kisoOnlineApp.getNow();
        cal.setTime(date);
        return cal;
    }

    //---
    public String retrieveAsString(Calendar value) {
        String result = getAsString(null, null, value);
        return result;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        String valueAsString = "";
        if (value != null && value instanceof Calendar) {
            Calendar calendar = (Calendar) value;
            final SimpleDateFormat sdf = createSimpleDateFormat(context, pattern);
            valueAsString = sdf.format(calendar.getTime());
        }
        return valueAsString;
    }

    protected SimpleDateFormat createSimpleDateFormat(FacesContext context, String pattern) {
        final SimpleDateFormat sdf = kisoOnlineApp.createSimpleDateFormat(pattern);
        return sdf;
    }

}