Package org.jpox.store.mapped.mapping

Source Code of org.jpox.store.mapped.mapping.EnumMapping

/**********************************************************************
Copyright (c) 2005 Erik Bengtson and others. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Contributors:
2006 Andy Jefferson - moved to Core. Removed RDBMS mappings.
2007 Andy Jefferson - support roleForField so it handles collection elements etc
    ...
**********************************************************************/
package org.jpox.store.mapped.mapping;

import java.math.BigInteger;

import org.jpox.ClassLoaderResolver;
import org.jpox.ClassNameConstants;
import org.jpox.ObjectManager;
import org.jpox.metadata.AbstractMemberMetaData;
import org.jpox.metadata.ColumnMetaData;
import org.jpox.store.mapped.DatastoreAdapter;
import org.jpox.store.mapped.DatastoreContainerObject;
import org.jpox.store.mapped.expression.IntegerLiteral;
import org.jpox.store.mapped.expression.Literal;
import org.jpox.store.mapped.expression.LogicSetExpression;
import org.jpox.store.mapped.expression.NumericExpression;
import org.jpox.store.mapped.expression.QueryExpression;
import org.jpox.store.mapped.expression.ScalarExpression;
import org.jpox.store.mapped.expression.StringExpression;
import org.jpox.store.mapped.expression.StringLiteral;
import org.jpox.store.mapped.mapping.SimpleDatastoreRepresentation;
import org.jpox.store.mapped.mapping.SingleFieldMapping;
import org.jpox.util.JPOXLogger;
import org.jpox.util.StringUtils;

/**
* Mapping for JDK1.5 Enum type.
**/
public class EnumMapping extends SingleFieldMapping implements SimpleDatastoreRepresentation
{
    protected String datastoreJavaType = ClassNameConstants.JAVA_LANG_STRING;

    /**
     * Initialize this JavaTypeMapping with the given DatastoreAdapter for the given FieldMetaData.
     * @param dba The Datastore Adapter that this Mapping should use.
     * @param fmd FieldMetaData for the field to be mapped (if any)
     * @param container The datastore container storing this mapping (if any)
     * @param clr the ClassLoaderResolver
     */
    public void initialize(DatastoreAdapter dba, AbstractMemberMetaData fmd, DatastoreContainerObject container, ClassLoaderResolver clr)
    {
        if (fmd != null && fmd.isSerialized())
        {
            datastoreJavaType = ClassNameConstants.JAVA_IO_SERIALIZABLE;
        }
        else if (fmd != null)
        {
            ColumnMetaData[] colmds = null;
            if (roleForField == MAPPING_FIELD)
            {
                if (fmd.getColumnMetaData() != null && fmd.getColumnMetaData().length > 0)
                {
                    colmds = fmd.getColumnMetaData();
                }
            }
            else if (roleForField == MAPPING_COLLECTION_ELEMENT || roleForField == MAPPING_ARRAY_ELEMENT)
            {
                if (fmd.getJoinMetaData() != null)
                {
                    // Mapping for Enum in a join table column
                    if (fmd.getElementMetaData() != null && fmd.getElementMetaData().getColumnMetaData() != null)
                    {
                        colmds = fmd.getElementMetaData().getColumnMetaData();
                    }
                }
            }
            else if (roleForField == MAPPING_MAP_KEY)
            {
                if (fmd.getJoinMetaData() != null)
                {
                    // Mapping for Enum in a join table column
                    if (fmd.getKeyMetaData() != null && fmd.getKeyMetaData().getColumnMetaData() != null)
                    {
                        colmds = fmd.getKeyMetaData().getColumnMetaData();
                    }
                }
            }
            else if (roleForField == MAPPING_MAP_VALUE)
            {
                if (fmd.getJoinMetaData() != null)
                {
                    // Mapping for Enum in a join table column
                    if (fmd.getValueMetaData() != null && fmd.getValueMetaData().getColumnMetaData() != null)
                    {
                        colmds = fmd.getValueMetaData().getColumnMetaData();
                    }
                }
            }

            if (colmds != null)
            {
                // Check if the user requested an INTEGER based datastore type
                if (isNumericJdbcType(colmds[0].getJdbcType()))
                {
                    datastoreJavaType = ClassNameConstants.JAVA_LANG_INTEGER;
                }
            }
        }

        super.initialize(dba, fmd, container, clr);
    }

    // TODO Move this to org.jpox.store.rdbms
    private static boolean isNumericJdbcType(String jdbcType)
    {
        if (jdbcType == null)
        {
            return false;
        }
        if (jdbcType.equalsIgnoreCase("INTEGER") || jdbcType.equalsIgnoreCase("SMALLINT") ||
            jdbcType.equalsIgnoreCase("TINYINT") || jdbcType.equalsIgnoreCase("NUMERIC") ||
            jdbcType.equalsIgnoreCase("BIGINT"))
        {
            return true;
        }
        return false;
    }

    /**
     * Accessor for the valid values for this mapping (if any restriction is imposed).
     * @param index The index of the datastore column
     * @return The valid value(s)
     */
    public ScalarExpression[] getValidValues(int index)
    {
        // this block defines check constraints based on the values of enums
        if (fmd != null)
        {
            if (fmd.getColumnMetaData() != null &&
                fmd.getColumnMetaData().length > 0 &&
                fmd.getColumnMetaData()[0].hasExtension("enum-check-constraint") &&
                fmd.getColumnMetaData()[0].getValueForExtension("enum-check-constraint").equalsIgnoreCase("true"))
            {
                try
                {
                    Enum[] values = (Enum[]) fmd.getType().getMethod("values",(Class[])null).invoke((Object)null, (Object[])null);
                    ScalarExpression[] validValues = new ScalarExpression[values.length];
                    for (int i=0; i<values.length; i++)
                    {
                        validValues[i] = newLiteral(null, values[i]);
                    }
                    return validValues;
                }
                catch (Exception e)
                {
                    JPOXLogger.PERSISTENCE.warn(StringUtils.getStringFromStackTrace(e));
                }
            }
        }
        return super.getValidValues(index);
    }
   
    /**
     * Accessor for the name of the java-type actually used when mapping the particular datastore
     * field. This java-type must have an entry in the datastore mappings.
     * @param index requested datastore field index.
     * @return the name of java-type for the requested datastore field.
     */
    public String getJavaTypeForDatastoreMapping(int index)
    {
        return datastoreJavaType;
    }

    /* (non-Javadoc)
     * @see org.jpox.store.mapping.JavaTypeMapping#getJavaType()
     */
    public Class getJavaType()
    {
        return Enum.class;
    }

    /**
     * Method to set the Enum in the datastore statement.
     * @param om ObjectManager
     * @param preparedStatement Statement for the datastore
     * @param exprIndex Index position(s) to set the Enum at in the statement
     * @param value The Enum value to set
     */
    public void setObject(ObjectManager om, Object preparedStatement, int[] exprIndex, Object value)
    {
        if (value == null)
        {
            getDataStoreMapping(0).setObject(preparedStatement, exprIndex[0], null);
        }
        else if (datastoreJavaType.equals(ClassNameConstants.JAVA_LANG_INTEGER))
        {
            if (value instanceof Enum)
            {
                int intVal = ((Enum)value).ordinal();
                getDataStoreMapping(0).setInt(preparedStatement, exprIndex[0], intVal);
            }
            else if (value instanceof BigInteger)
            {
                // ordinal value passed in directly (e.g ENUM_FIELD == ? in query)
                getDataStoreMapping(0).setInt(preparedStatement, exprIndex[0], ((BigInteger)value).intValue());
            }
        }
        else if (datastoreJavaType.equals(ClassNameConstants.JAVA_LANG_STRING))
        {
            String stringVal;
            if (value instanceof String)
            {
                //it may be String when there is a compare between Enums values and Strings in the JDOQL query (for example)
                stringVal = (String)value;
            }
            else
            {
                stringVal = ((Enum)value).name();
            }
            getDataStoreMapping(0).setString(preparedStatement, exprIndex[0], stringVal);
        }
        else
        {
            super.setObject(om, preparedStatement, exprIndex, value);
        }
    }

    /**
     * Method to extract the Enum object from the passed result set.
     * @param om ObjectManager
     * @param resultSet The result set
     * @param exprIndex The index position(s) in the result set to use.
     * @return The Enum
     */
    @SuppressWarnings("unchecked")
    public Object getObject(ObjectManager om, Object resultSet, int[] exprIndex)
    {
        if (exprIndex == null)
        {
            return null;
        }

        if (getDataStoreMapping(0).getObject(resultSet, exprIndex[0]) == null)
        {
            return null;
        }
        else if (datastoreJavaType.equals(ClassNameConstants.JAVA_LANG_INTEGER))
        {
            long longVal = getDataStoreMapping(0).getLong(resultSet, exprIndex[0]);
            Class enumType = null;
            if (fmd == null)
            {
                enumType = om.getClassLoaderResolver().classForName(type);
            }
            else
            {
                enumType = fmd.getType();
                if (roleForField == MAPPING_COLLECTION_ELEMENT)
                {
                    enumType = om.getClassLoaderResolver().classForName(fmd.getCollection().getElementType());
                }
                else if (roleForField == MAPPING_ARRAY_ELEMENT)
                {
                    enumType = om.getClassLoaderResolver().classForName(fmd.getArray().getElementType());
                }
                else if (roleForField == MAPPING_MAP_KEY)
                {
                    enumType = om.getClassLoaderResolver().classForName(fmd.getMap().getKeyType());
                }
                else if (roleForField == MAPPING_MAP_VALUE)
                {
                    enumType = om.getClassLoaderResolver().classForName(fmd.getMap().getValueType());
                }
            }
            return enumType.getEnumConstants()[(int)longVal];
        }
        else if (datastoreJavaType.equals(ClassNameConstants.JAVA_LANG_STRING))
        {
            String stringVal = getDataStoreMapping(0).getString(resultSet, exprIndex[0]);
            Class enumType = null;
            if (fmd == null)
            {
                enumType = om.getClassLoaderResolver().classForName(type);
            }
            else
            {
                enumType = fmd.getType();
                if (roleForField == MAPPING_COLLECTION_ELEMENT)
                {
                    enumType = om.getClassLoaderResolver().classForName(fmd.getCollection().getElementType());
                }
                else if (roleForField == MAPPING_ARRAY_ELEMENT)
                {
                    enumType = om.getClassLoaderResolver().classForName(fmd.getArray().getElementType());
                }
                else if (roleForField == MAPPING_MAP_KEY)
                {
                    enumType = om.getClassLoaderResolver().classForName(fmd.getMap().getKeyType());
                }
                else if (roleForField == MAPPING_MAP_VALUE)
                {
                    enumType = om.getClassLoaderResolver().classForName(fmd.getMap().getValueType());
                }
            }
            return Enum.valueOf(enumType, stringVal);
        }
        else
        {
            return super.getObject(om, resultSet, exprIndex);
        }
    }

    public Object getSampleValue(ClassLoaderResolver clr)
    {
        throw new UnsupportedOperationException();
    }

    public ScalarExpression newLiteral(QueryExpression qs, Object value)
    {
        if (datastoreJavaType.equals(ClassNameConstants.JAVA_LANG_INTEGER))
        {
            // Return an IntegerLiteral to represent this Enum, but with the original value present just in case
            ScalarExpression expr = new IntegerLiteral(qs, this, BigInteger.valueOf(((Enum)value).ordinal()));
            ((Literal)expr).setRawValue(value);
            return expr;
        }
        else if (datastoreJavaType.equals(ClassNameConstants.JAVA_LANG_STRING))
        {
            // Return an StringLiteral to represent this Enum, but with the original value present just in case
            ScalarExpression expr = new StringLiteral(qs, this, ((Enum)value).name());
            ((Literal)expr).setRawValue(value);
            return expr;
        }
        else
        {
            // No querying of serialised Enums!
            return null;
        }
    }

    public ScalarExpression newScalarExpression(QueryExpression qs, LogicSetExpression te)
    {
        if (datastoreJavaType.equals(ClassNameConstants.JAVA_LANG_INTEGER))
        {
            return new NumericExpression(qs, this, te);
        }
        else if (datastoreJavaType.equals(ClassNameConstants.JAVA_LANG_STRING))
        {
            return new StringExpression(qs, this, te);
        }
        else
        {
            // No querying of serialised Enums!
            return null;
        }
    }
}
TOP

Related Classes of org.jpox.store.mapped.mapping.EnumMapping

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.