Package DisplayProject

Source Code of DisplayProject.DataFieldFormatter

/*
Copyright (c) 2003-2008 ITerative Consulting Pty Ltd. All Rights Reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:

o Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
 
o Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the distribution.
   
o This jcTOOL Helper Class software, whether in binary or source form may not be used within,
or to derive, any other product without the specific prior written permission of the copyright holder

 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


*/
package DisplayProject;

import java.beans.PropertyChangeListener;
import java.lang.reflect.Constructor;
import java.text.ParseException;

import javax.swing.JFormattedTextField;
import javax.swing.text.DefaultFormatter;
import javax.swing.text.DocumentFilter;

import org.apache.log4j.Logger;

import DisplayProject.binding.BindingManager;
import Framework.DataValue;
import Framework.DateTimeData;
import Framework.DateTimeNullable;
import Framework.ErrorMgr;
import Framework.TextData;

/**
* A formatter for use with Data Fields. Has support for datavalue and data
* nullable types.
*/
@SuppressWarnings("serial")
public class DataFieldFormatter extends DefaultFormatter {
    private static final Logger log = Logger
            .getLogger(DataFieldFormatter.class);

    private JFormattedTextField installedTextField;

    public DataFieldFormatter() {
        setCommitsOnValidEdit(true);
        setOverwriteMode(false);
    }

    /**
     * Overridden to handle datavalue and nullable data values
     *
     * @param value
     * @return
     * @throws ParseException
     */
    public String valueToString(Object value) throws ParseException {
      log.debug("valueToString(" + value + ")");

      if (value instanceof DataValue) {
        DataValue dataValue = (DataValue) value;
        Class<?> vc = this.getValueClass();
       
        //PM:7 oct. 2008:this is a special case for DateTimeNullable
        /*
         * if it is set to the beginning of the Gregorian calendar
         * the mask should contain '*'
         */
        if (DateTimeNullable.class.isAssignableFrom(vc)){
          DateTimeNullable dtn = (DateTimeNullable)value;
          if (dtn.asDate().getTime()==DateTimeData.GREGORIAN_START_AS_LONG){
            return super.valueToString(null);
          }
        }
       
        if (dataValue.isNullable() && dataValue.isNull()) {

          // TF+CraigM:19/08/2008 - Only set N/A if we are based on a TextData
          if (TextData.class.isAssignableFrom(vc)) {
            // TF:19/06/2008:Changed this to return N/A if the data field is null
            return "N/A";
         
          } else {
            //TF:22/07/2009:The Date DateTimeData may have formatter on it and if the value is "N/A", the formatter will need to return the mask instead of "N/A"
            if (DateTimeData.class.isAssignableFrom(vc)){
              return super.valueToString(null);
            }
            else {
              // CraigM:15/01/2009 - Always use the dataValues fillString method in case it has been overridden
              return super.valueToString(dataValue);
            }
          }
        }

        return super.valueToString(dataValueToString(dataValue));
      }
      else if (value == null) {
            // Null type. If we're using a TextData or subclass display N/A by default
            Class<?> vc = this.getValueClass();
            if (TextData.class.isAssignableFrom(vc)) {
                return "N/A";
            }
            else {
              // CraigM:16/01/2009 - If our parent object is null, we return N/A (just like Forte)
              if (this.getFormattedTextField() != null) {
                String boundPath = BindingManager.getDataObjectPath(this.getFormattedTextField()); // Find our bound path
               
                if (boundPath != null) {
                  int index = boundPath.lastIndexOf("."); // Look to see if we have a parent in the bound path
                 
                  if (index != -1) {
                    // Get the binding manager (don't bother trying to find the getBindingManager method, as the text field
                    // probably hasn't been added to the window yet).
                    Object bindingMgr = this.getFormattedTextField().getClientProperty(BindingManager.BINDING_MANAGER_PROPERTY);
                   
                    if (bindingMgr instanceof BindingManager) {
                      String parentBoundPath = boundPath.substring(0,index); // Get our parents bound path
                        Object parentBoundObj = ((BindingManager)bindingMgr).getDataObject(parentBoundPath); // Get our parents bound object

                        // Return N/A if our parents object is null
                        if (parentBoundObj == null) {
                          return "N/A";
                        }
                    }
                  }
                }
              }
              return super.valueToString(value);
            }
        }
        else {
            return super.valueToString(value);
        }
    }

    /**
     * Overridden to handle datavalue and nullable data values
     *
     * @param value
     * @return
     * @throws ParseException
     */
    @SuppressWarnings("unchecked")
  public Object stringToValue(String value) throws ParseException {
        log.debug("stringToValue(" + value + ")");
        Class<?> vc = getValueClass();
        if (vc != null) {
            if (DataValue.class.isAssignableFrom(vc)) {
                DataValue dataValue = null;
                // If its already created we want to reuse the same instance in
                // order to preseve the datavalues current state
                if (installedTextField != null
                        && installedTextField.getValue() != null) {
                    log.debug("using existing data value");
                    DataValue existingValue = (DataValue) installedTextField.getValue();

                    // The setValue mutator fires a value change that we dont want
                    // anyone to receive so we need to remolve any listeners from
                    // the textfield before we set the value
                    PropertyChangeListener[] listeners = removeValueChangeListeners(existingValue);
                    // TF:07/06/2008:Added in safety in case an exception is thrown
                    try {
                      // CraigM:15/01/2009 - Removed length==0 check as it meant it would incorrectly force
                      //             a non null TextNullable with length 0, to be null.
                      // if (existingValue.isNullable() && (value == null || value.length() == 0))
                      if (existingValue.isNullable() && value == null)
                      {
                          existingValue.setIsNull(true);
                          dataValue = existingValue;
                      }
                      else
                      {
                          // Set the internal value from the string
                          dataValue = setDataValueFromString(existingValue, value);
                      }
                    }
                    finally {
                      // Add the value change listeners back
                      addValueChangeListeners(existingValue, listeners);
                    }
                }
                else
                {
                    log.debug("Creating new data value instance");
                    dataValue = createDataValueInstance((Class<DataValue>)vc, value);
                }

                return dataValue;
            }
        }
        // Default behaviour if its not or we cant determine that the value is a
        // data value
        return super.stringToValue(value);
    }

    protected DataValue setDataValueFromString(DataValue dataValue, String value)
            throws ParseException {
        dataValue.setValue(value);
        return dataValue;
    }

    protected DataValue createDataValueInstance(Class<? extends DataValue> dataValueClass, String value)
            throws ParseException {
        try {
            Constructor<? extends DataValue> constructor = dataValueClass.getConstructor(new Class[0]);
            DataValue dataValue = constructor.newInstance(new Object[0]);
            return setDataValueFromString(dataValue,  value);
        } catch (Throwable t) {
            ParseException errorVar = new ParseException("Unable to instantiate valueclass", 0);
            ErrorMgr.addError(errorVar);
            throw errorVar;
        }
    }

    protected String dataValueToString(DataValue value) {
        TextData buffer = new TextData();
        value.fillString(buffer);
        return buffer.toString();
    }

    public void install(JFormattedTextField ftf) {
        log.debug("Install");
        super.install(ftf);
        installedTextField = ftf;
    }

    private void addValueChangeListeners(DataValue dataValue,
            PropertyChangeListener[] listeners) {
        for (int i = 0; i < listeners.length; i++)
            dataValue.addPropertyChangeListener("value", listeners[i]);
    }

    private PropertyChangeListener[] removeValueChangeListeners(
            DataValue dataValue) {
        PropertyChangeListener[] listeners = dataValue.getPropertyListeners()
                .getPropertyChangeListeners("value");
        for (int i = 0; i < listeners.length; i++)
            dataValue.removePropertyChangeListener("value", listeners[i]);

        return listeners;
    }

    /**
     * @return Returns the filter.
     */
    public DocumentFilter getFilter() {
        return this.filter;
    }

    /**
     * @param theFilter
     *            The filter to set.
     */
    public void setFilter(DocumentFilter theFilter) {
        this.filter = theFilter;
    }

    protected DocumentFilter filter;

    protected DocumentFilter getDocumentFilter() {
        DocumentFilter filter = getFilter();
        if (filter != null)
            return filter;

        return super.getDocumentFilter();
    }
}
TOP

Related Classes of DisplayProject.DataFieldFormatter

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.