⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sqldate.java

📁 derby database source code.good for you.
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*   Derby - Class org.apache.derby.iapi.types.SQLDate   Copyright 2001, 2004 The Apache Software Foundation or its licensors, as applicable.   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. */package org.apache.derby.iapi.types;import org.apache.derby.iapi.types.SQLInteger;import org.apache.derby.iapi.reference.SQLState;import org.apache.derby.iapi.services.io.ArrayInputStream;import org.apache.derby.iapi.error.StandardException;import org.apache.derby.iapi.db.DatabaseContext;import org.apache.derby.iapi.types.DataValueDescriptor;import org.apache.derby.iapi.types.TypeId;import org.apache.derby.iapi.types.NumberDataValue;import org.apache.derby.iapi.types.DateTimeDataValue;import org.apache.derby.iapi.services.context.ContextService;import org.apache.derby.iapi.services.io.StoredFormatIds; import org.apache.derby.iapi.services.sanity.SanityManager;import org.apache.derby.iapi.types.DataType;import org.apache.derby.iapi.services.cache.ClassSize;import org.apache.derby.iapi.services.i18n.LocaleFinder;import org.apache.derby.iapi.util.StringUtil;import java.sql.Date;import java.sql.Time;import java.sql.Timestamp;import java.sql.Types;import java.sql.PreparedStatement;import java.util.Calendar;import java.util.GregorianCalendar;import java.io.ObjectOutput;import java.io.ObjectInput;import java.io.IOException;import java.sql.ResultSet;import java.sql.SQLException;import java.text.DateFormat;import java.text.ParseException;/** * This contains an instance of a SQL Date. * <p> * The date is stored as int (year << 16 + month << 8 + day) * Null is represented by an encodedDate value of 0. * Some of the static methods in this class are also used by SQLTime and SQLTimestamp * so check those classes if you change the date encoding * * PERFORMANCE OPTIMIZATION: * The java.sql.Date object is only instantiated when needed * do to the overhead of Date.valueOf(), etc. methods. */public final class SQLDate extends DataType						implements DateTimeDataValue{	private int	encodedDate;	//year << 16 + month << 8 + day	// The cached value.toString()	private String	valueString;    private static final int BASE_MEMORY_USAGE = ClassSize.estimateBaseFromCatalog( SQLDate.class);    public int estimateMemoryUsage()    {        return BASE_MEMORY_USAGE + ClassSize.estimateMemoryUsage( valueString);    } // end of estimateMemoryUsage    int getEncodedDate()    {        return encodedDate;    }    	/*	** DataValueDescriptor interface	** (mostly implemented in DataType)	*/	public String getString()	{		//format is [yyy]y-mm-dd e.g. 1-01-01, 9999-99-99		if (!isNull())		{			if (valueString == null)			{				valueString = encodedDateToString(encodedDate);			}			return valueString;		}		else		{			if (SanityManager.DEBUG)			{				if (valueString != null)				{					SanityManager.THROWASSERT(						"valueString expected to be null, not " +						valueString);				}			}			return null;		}	}	/**		getTimestamp returns a timestamp with the date value 		time is set to 00:00:00.0	*/	public Timestamp getTimestamp( Calendar cal) 	{		if (isNull())		{			return null;		}		else 			// date is converted to a timestamp filling the time in with 00:00:00            return newTimestamp(cal);    }    private long getTimeInMillis( Calendar cal)    {        if( cal == null)            cal = new GregorianCalendar();        cal.clear();        cal.set( getYear( encodedDate), getMonth( encodedDate)-1, getDay( encodedDate));        return cal.getTime().getTime();    }        private Timestamp newTimestamp(java.util.Calendar cal)    {        return new Timestamp(getTimeInMillis( cal));	}	/**		getObject returns the date value	 */	public Object getObject()	{		return getDate( (Calendar) null);	}			public int getLength()	{		return 4;	}	/* this is for DataType's error generator */	public String getTypeName()	{		return "DATE";	}	/*	 * Storable interface, implies Externalizable, TypedFormat	 */	/**		Return my format identifier.		@see org.apache.derby.iapi.services.io.TypedFormat#getTypeFormatId	*/	public int getTypeFormatId() {		return StoredFormatIds.SQL_DATE_ID;	}	/** 		@exception IOException error writing data	*/	public void writeExternal(ObjectOutput out) throws IOException {		if (SanityManager.DEBUG)			SanityManager.ASSERT(!isNull(), "writeExternal() is not supposed to be called for null values.");		out.writeInt(encodedDate);	}	/**	 * @see java.io.Externalizable#readExternal	 *	 * @exception IOException	Thrown on error reading the object	 */	public void readExternal(ObjectInput in) throws IOException	{		encodedDate = in.readInt();		// reset cached string values		valueString = null;	}	public void readExternalFromArray(ArrayInputStream in) throws IOException	{		encodedDate = in.readInt();		// reset cached string values		valueString = null;	}	/*	 * DataValueDescriptor interface	 */	/** @see DataValueDescriptor#getClone */	public DataValueDescriptor getClone()	{		// Call constructor with all of our info		return new SQLDate(encodedDate);	}	/**	 * @see DataValueDescriptor#getNewNull	 */	public DataValueDescriptor getNewNull()	{		return new SQLDate();	}	/**	 * @see org.apache.derby.iapi.services.io.Storable#restoreToNull	 *	 */	public void restoreToNull()	{		// clear encodedDate		encodedDate = 0;		// clear cached valueString		valueString = null;	}	/*	 * DataValueDescriptor interface	 */	/** 	 * @see DataValueDescriptor#setValueFromResultSet 	 *	 * @exception SQLException		Thrown on error	 */	public void setValueFromResultSet(ResultSet resultSet, int colNumber,									  boolean isNullable)		throws SQLException, StandardException	{        setValue(resultSet.getDate(colNumber), (Calendar) null);	}	/**	 * Orderable interface	 *	 *	 * @see org.apache.derby.iapi.types.Orderable	 *	 * @exception StandardException thrown on failure	 */	public int compare(DataValueDescriptor other)		throws StandardException	{		/* Use compare method from dominant type, negating result		 * to reflect flipping of sides.		 */		if (typePrecedence() < other.typePrecedence())		{			return - (other.compare(this));		}		boolean thisNull, otherNull;		thisNull = this.isNull();		otherNull = other.isNull();		/*		 * thisNull otherNull	return		 *	T		T		 	0	(this == other)		 *	F		T		 	-1 	(this < other)		 *	T		F		 	1	(this > other)		 */		if (thisNull || otherNull)		{			if (!thisNull)		// otherNull must be true				return -1;			if (!otherNull)		// thisNull must be true				return 1;			return 0;		}		/*			Neither are null compare them 		 */		int comparison;		/* get the comparison date values */		int otherVal = 0;		/* if the argument is another SQLDate		 * get the encodedDate		 */		if (other instanceof SQLDate)		{			otherVal = ((SQLDate)other).encodedDate; 		}		else 		{			/* O.K. have to do it the hard way and calculate the numeric value			 * from the value			 */			otherVal = SQLDate.computeEncodedDate(other.getDate(new GregorianCalendar()));		}		if (encodedDate > otherVal)			comparison = 1;		else if (encodedDate < otherVal)			comparison = -1;		else 			comparison = 0;		return comparison;	}	/**		@exception StandardException thrown on error	 */	public boolean compare(int op,						   DataValueDescriptor other,						   boolean orderedNulls,						   boolean unknownRV)		throws StandardException	{		if (!orderedNulls)		// nulls are unordered		{			if (this.isNull() || other.isNull())				return unknownRV;		}		/* Do the comparison */		return super.compare(op, other, orderedNulls, unknownRV);	}	/*	** Class interface	*/	/*	** Constructors	*/	/** no-arg constructor required by Formattable */	public SQLDate() {	}	public SQLDate(Date value) throws StandardException	{		parseDate(value);	}        private void parseDate( java.util.Date value) throws StandardException	{		encodedDate = computeEncodedDate(value);	}	private SQLDate(int encodedDate) {		this.encodedDate = encodedDate;	}    /**     * Construct a date from a string. The allowed date formats are:     *<ol>     *<li>ISO: yyyy-mm-dd     *<li>IBM USA standard: mm/dd/yyyy     *<li>IBM European standard: dd.mm.yyyy     *</ol>     * Trailing blanks may be included; leading zeros may be omitted from the month and day portions.     *     * @param dateStr     * @param isJdbcEscape if true then only the JDBC date escape syntax is allowed     * @param localeFinder     *     * @return the internal DataValueDescriptor for the value     *     * @exception Standard exception if the syntax is invalid or the value is out of range.     */    public SQLDate( String dateStr, boolean isJdbcEscape, LocaleFinder localeFinder)        throws StandardException    {        parseDate( dateStr, isJdbcEscape, localeFinder, (Calendar) null);    }    /**     * Construct a date from a string. The allowed date formats are:     *<ol>     *<li>ISO: yyyy-mm-dd     *<li>IBM USA standard: mm/dd/yyyy     *<li>IBM European standard: dd.mm.yyyy     *</ol>     * Trailing blanks may be included; leading zeros may be omitted from the month and day portions.     *     * @param dateStr     * @param isJdbcEscape if true then only the JDBC date escape syntax is allowed     * @param localeFinder     *     * @return the internal DataValueDescriptor for the value     *     * @exception Standard exception if the syntax is invalid or the value is out of range.     */    public SQLDate( String dateStr, boolean isJdbcEscape, LocaleFinder localeFinder, Calendar cal)        throws StandardException    {        parseDate( dateStr, isJdbcEscape, localeFinder, cal);    }    static final char ISO_SEPARATOR = '-';    private static final char[] ISO_SEPARATOR_ONLY = {ISO_SEPARATOR};    private static final char IBM_USA_SEPARATOR = '/';    private static final char[] IBM_USA_SEPARATOR_ONLY = {IBM_USA_SEPARATOR};    private static final char IBM_EUR_SEPARATOR = '.';    private static final char[] IBM_EUR_SEPARATOR_ONLY = {IBM_EUR_SEPARATOR};    private static final char[] END_OF_STRING = {(char) 0};        private void parseDate( String dateStr, boolean isJdbcEscape, LocaleFinder localeFinder, Calendar cal)        throws StandardException    {        boolean validSyntax = true;        DateTimeParser parser = new DateTimeParser( dateStr);        int year = 0;        int month = 0;        int day = 0;        StandardException thrownSE = null;        try        {            switch( parser.nextSeparator())            {            case ISO_SEPARATOR:                encodedDate = SQLTimestamp.parseDateOrTimestamp( parser, false)[0];                valueString = parser.getTrimmedString();                return;            case IBM_USA_SEPARATOR:                if( isJdbcEscape)                {                    validSyntax = false;                    break;                }                month = parser.parseInt( 2, true, IBM_USA_SEPARATOR_ONLY, false);                day = parser.parseInt( 2, true, IBM_USA_SEPARATOR_ONLY, false);                year = parser.parseInt( 4, false, END_OF_STRING, false);                break;            case IBM_EUR_SEPARATOR:                if( isJdbcEscape)                {                    validSyntax = false;                    break;                }                day = parser.parseInt( 2, true, IBM_EUR_SEPARATOR_ONLY, false);                month = parser.parseInt( 2, true, IBM_EUR_SEPARATOR_ONLY, false);                year = parser.parseInt( 4, false, END_OF_STRING, false);                break;            default:                validSyntax = false;            }        }        catch( StandardException se)        {            validSyntax = false;            thrownSE = se;        }        if( validSyntax)        {            valueString = parser.checkEnd();            encodedDate = computeEncodedDate( year, month, day);        }        else        {            // See if it is a localized date or timestamp.            dateStr = StringUtil.trimTrailing( dateStr);            DateFormat dateFormat = null;            if( localeFinder == null)                dateFormat = DateFormat.getDateInstance();            else if( cal == null)                dateFormat = localeFinder.getDateFormat();            else                dateFormat = (DateFormat) localeFinder.getDateFormat().clone();            if( cal != null)                dateFormat.setCalendar( cal);            try            {                encodedDate = computeEncodedDate( dateFormat.parse( dateStr), cal);            }            catch( ParseException pe)            {                // Maybe it is a localized timestamp                try                {                    encodedDate = SQLTimestamp.parseLocalTimestamp( dateStr, localeFinder, cal)[0];                }                catch( ParseException pe2)                {                    if( thrownSE != null)                        throw thrownSE;                    throw StandardException.newException( SQLState.LANG_DATE_SYNTAX_EXCEPTION);                }            }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -